nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
danmar/cppcheck
78228599da0dfce3763a90a130b14fa2d614ab9f
addons/misra.py
python
MisraChecker.setSeverity
(self, severity)
Set the severity for all errors.
Set the severity for all errors.
[ "Set", "the", "severity", "for", "all", "errors", "." ]
def setSeverity(self, severity): """ Set the severity for all errors. """ self.severity = severity
[ "def", "setSeverity", "(", "self", ",", "severity", ")", ":", "self", ".", "severity", "=", "severity" ]
https://github.com/danmar/cppcheck/blob/78228599da0dfce3763a90a130b14fa2d614ab9f/addons/misra.py#L4016-L4020
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListMainWindow.GetLine
(self, n)
return self._lines[n]
Returns the line data for the given index. :param `n`: the line index.
Returns the line data for the given index.
[ "Returns", "the", "line", "data", "for", "the", "given", "index", "." ]
def GetLine(self, n): """ Returns the line data for the given index. :param `n`: the line index. """ if self.IsVirtual(): self.CacheLineData(n) n = 0 return self._lines[n]
[ "def", "GetLine", "(", "self", ",", "n", ")", ":", "if", "self", ".", "IsVirtual", "(", ")", ":", "self", ".", "CacheLineData", "(", "n", ")", "n", "=", "0", "return", "self", ".", "_lines", "[", "n", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L6424-L6436
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html.py
python
HtmlPrintout.SetFonts
(*args, **kwargs)
return _html.HtmlPrintout_SetFonts(*args, **kwargs)
SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)
SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)
[ "SetFonts", "(", "self", "String", "normal_face", "String", "fixed_face", "PyObject", "sizes", "=", "None", ")" ]
def SetFonts(*args, **kwargs): """SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)""" return _html.HtmlPrintout_SetFonts(*args, **kwargs)
[ "def", "SetFonts", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlPrintout_SetFonts", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1292-L1294
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextCtrl.IsEmpty
(*args, **kwargs)
return _richtext.RichTextCtrl_IsEmpty(*args, **kwargs)
IsEmpty(self) -> bool Returns True if the value in the text field is empty.
IsEmpty(self) -> bool
[ "IsEmpty", "(", "self", ")", "-", ">", "bool" ]
def IsEmpty(*args, **kwargs): """ IsEmpty(self) -> bool Returns True if the value in the text field is empty. """ return _richtext.RichTextCtrl_IsEmpty(*args, **kwargs)
[ "def", "IsEmpty", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_IsEmpty", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L4202-L4208
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/cephadm/module.py
python
CephadmOrchestrator.get_facts
(self, hostname: Optional[str] = None)
return [self.cache.get_facts(hostname) for hostname in self.cache.get_hosts()]
Return a list of hosts metadata(gather_facts) managed by the orchestrator. Notes: - skip async: manager reads from cache.
Return a list of hosts metadata(gather_facts) managed by the orchestrator.
[ "Return", "a", "list", "of", "hosts", "metadata", "(", "gather_facts", ")", "managed", "by", "the", "orchestrator", "." ]
def get_facts(self, hostname: Optional[str] = None) -> List[Dict[str, Any]]: """ Return a list of hosts metadata(gather_facts) managed by the orchestrator. Notes: - skip async: manager reads from cache. """ if hostname: return [self.cache.get_facts(hostname)] return [self.cache.get_facts(hostname) for hostname in self.cache.get_hosts()]
[ "def", "get_facts", "(", "self", ",", "hostname", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "if", "hostname", ":", "return", "[", "self", ".", "cache", ".", "get_facts", "(", "hostname", ")", "]", "return", "[", "self", ".", "cache", ".", "get_facts", "(", "hostname", ")", "for", "hostname", "in", "self", ".", "cache", ".", "get_hosts", "(", ")", "]" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/cephadm/module.py#L1503-L1513
msracver/Deep-Image-Analogy
632b9287b42552e32dad64922967c8c9ec7fc4d3
examples/pycaffe/tools.py
python
SimpleTransformer.set_scale
(self, scale)
Set the data scaling.
Set the data scaling.
[ "Set", "the", "data", "scaling", "." ]
def set_scale(self, scale): """ Set the data scaling. """ self.scale = scale
[ "def", "set_scale", "(", "self", ",", "scale", ")", ":", "self", ".", "scale", "=", "scale" ]
https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/examples/pycaffe/tools.py#L21-L25
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
applications/graph/communityGAN/model/discriminator.py
python
Discriminator.forward
(self, motif_size, motif_log_embeddings)
return prob, log_not_prob
Predict whether a motif is real. @todo Numerically accurate computation of both log(D) and log(1-D).
Predict whether a motif is real.
[ "Predict", "whether", "a", "motif", "is", "real", "." ]
def forward(self, motif_size, motif_log_embeddings): """Predict whether a motif is real. @todo Numerically accurate computation of both log(D) and log(1-D). """ # D = 1 - exp(-sum_j(prod_i(d_ij))) # log(1-D) = -sum_j(exp(sum_i(log(d_ij)))) x = lbann.MatMul( lbann.Constant(value=1, num_neurons=str_list([1, motif_size])), motif_log_embeddings, ) x = lbann.Exp(x) x = lbann.Reduction(x, mode='sum') x = lbann.Negative(x) log_not_prob = x # Convert log-probability to linear space # Note: D=-expm1(x) is accurate when D~0. When D~1, prefer # 1-D=exp(x). prob = lbann.Negative(lbann.Expm1(log_not_prob)) return prob, log_not_prob
[ "def", "forward", "(", "self", ",", "motif_size", ",", "motif_log_embeddings", ")", ":", "# D = 1 - exp(-sum_j(prod_i(d_ij)))", "# log(1-D) = -sum_j(exp(sum_i(log(d_ij))))", "x", "=", "lbann", ".", "MatMul", "(", "lbann", ".", "Constant", "(", "value", "=", "1", ",", "num_neurons", "=", "str_list", "(", "[", "1", ",", "motif_size", "]", ")", ")", ",", "motif_log_embeddings", ",", ")", "x", "=", "lbann", ".", "Exp", "(", "x", ")", "x", "=", "lbann", ".", "Reduction", "(", "x", ",", "mode", "=", "'sum'", ")", "x", "=", "lbann", ".", "Negative", "(", "x", ")", "log_not_prob", "=", "x", "# Convert log-probability to linear space", "# Note: D=-expm1(x) is accurate when D~0. When D~1, prefer", "# 1-D=exp(x).", "prob", "=", "lbann", ".", "Negative", "(", "lbann", ".", "Expm1", "(", "log_not_prob", ")", ")", "return", "prob", ",", "log_not_prob" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/applications/graph/communityGAN/model/discriminator.py#L46-L70
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/concept.py
python
_union_lists
(lists)
return [seen.setdefault(x, x) for l in lists for x in l if x not in seen]
Return a list that contains of all the elements of lists without duplicates and maintaining the order.
Return a list that contains of all the elements of lists without duplicates and maintaining the order.
[ "Return", "a", "list", "that", "contains", "of", "all", "the", "elements", "of", "lists", "without", "duplicates", "and", "maintaining", "the", "order", "." ]
def _union_lists(lists): """ Return a list that contains of all the elements of lists without duplicates and maintaining the order. """ seen = {} return [seen.setdefault(x, x) for l in lists for x in l if x not in seen]
[ "def", "_union_lists", "(", "lists", ")", ":", "seen", "=", "{", "}", "return", "[", "seen", ".", "setdefault", "(", "x", ",", "x", ")", "for", "l", "in", "lists", "for", "x", "in", "l", "if", "x", "not", "in", "seen", "]" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/concept.py#L120-L128
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/connectionpool.py
python
HTTPConnectionPool._get_conn
(self, timeout=None)
return conn or self._new_conn()
Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``.
Get a connection. Will return a pooled connection if one is available.
[ "Get", "a", "connection", ".", "Will", "return", "a", "pooled", "connection", "if", "one", "is", "available", "." ]
def _get_conn(self, timeout=None): """ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. """ conn = None try: conn = self.pool.get(block=self.block, timeout=timeout) except AttributeError: # self.pool is None raise ClosedPoolError(self, "Pool is closed.") except Empty: if self.block: raise EmptyPoolError(self, "Pool reached maximum size and no more " "connections are allowed.") pass # Oh well, we'll create a new connection then # If this is a persistent connection, check if it got disconnected if conn and is_connection_dropped(conn): log.info("Resetting dropped connection: %s" % self.host) conn.close() if getattr(conn, 'auto_open', 1) == 0: # This is a proxied connection that has been mutated by # httplib._tunnel() and cannot be reused (since it would # attempt to bypass the proxy) conn = None return conn or self._new_conn()
[ "def", "_get_conn", "(", "self", ",", "timeout", "=", "None", ")", ":", "conn", "=", "None", "try", ":", "conn", "=", "self", ".", "pool", ".", "get", "(", "block", "=", "self", ".", "block", ",", "timeout", "=", "timeout", ")", "except", "AttributeError", ":", "# self.pool is None", "raise", "ClosedPoolError", "(", "self", ",", "\"Pool is closed.\"", ")", "except", "Empty", ":", "if", "self", ".", "block", ":", "raise", "EmptyPoolError", "(", "self", ",", "\"Pool reached maximum size and no more \"", "\"connections are allowed.\"", ")", "pass", "# Oh well, we'll create a new connection then", "# If this is a persistent connection, check if it got disconnected", "if", "conn", "and", "is_connection_dropped", "(", "conn", ")", ":", "log", ".", "info", "(", "\"Resetting dropped connection: %s\"", "%", "self", ".", "host", ")", "conn", ".", "close", "(", ")", "if", "getattr", "(", "conn", ",", "'auto_open'", ",", "1", ")", "==", "0", ":", "# This is a proxied connection that has been mutated by", "# httplib._tunnel() and cannot be reused (since it would", "# attempt to bypass the proxy)", "conn", "=", "None", "return", "conn", "or", "self", ".", "_new_conn", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/connectionpool.py#L210-L246
GeometryCollective/boundary-first-flattening
8250e5a0e85980ec50b5e8aa8f49dd6519f915cd
deps/nanogui/docs/exhale.py
python
ExhaleRoot.generateNamespaceNodeDocuments
(self)
Generates the reStructuredText document for every namespace, including nested namespaces that were removed from ``self.namespaces`` (but added as children to one of the namespaces in ``self.namespaces``). The documents generated do not use the Breathe namespace directive, but instead link to the relevant documents associated with this namespace.
Generates the reStructuredText document for every namespace, including nested namespaces that were removed from ``self.namespaces`` (but added as children to one of the namespaces in ``self.namespaces``).
[ "Generates", "the", "reStructuredText", "document", "for", "every", "namespace", "including", "nested", "namespaces", "that", "were", "removed", "from", "self", ".", "namespaces", "(", "but", "added", "as", "children", "to", "one", "of", "the", "namespaces", "in", "self", ".", "namespaces", ")", "." ]
def generateNamespaceNodeDocuments(self): ''' Generates the reStructuredText document for every namespace, including nested namespaces that were removed from ``self.namespaces`` (but added as children to one of the namespaces in ``self.namespaces``). The documents generated do not use the Breathe namespace directive, but instead link to the relevant documents associated with this namespace. ''' # go through all of the top level namespaces for n in self.namespaces: # find any nested namespaces nested_namespaces = [] for child in n.children: child.findNestedNamespaces(nested_namespaces) # generate the children first for nested in reversed(sorted(nested_namespaces)): self.generateSingleNamespace(nested) # generate this top level namespace self.generateSingleNamespace(n)
[ "def", "generateNamespaceNodeDocuments", "(", "self", ")", ":", "# go through all of the top level namespaces", "for", "n", "in", "self", ".", "namespaces", ":", "# find any nested namespaces", "nested_namespaces", "=", "[", "]", "for", "child", "in", "n", ".", "children", ":", "child", ".", "findNestedNamespaces", "(", "nested_namespaces", ")", "# generate the children first", "for", "nested", "in", "reversed", "(", "sorted", "(", "nested_namespaces", ")", ")", ":", "self", ".", "generateSingleNamespace", "(", "nested", ")", "# generate this top level namespace", "self", ".", "generateSingleNamespace", "(", "n", ")" ]
https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/docs/exhale.py#L2275-L2294
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py
python
pooling_nhwc_max_unsigned
( I=TensorDef(T1, S.N, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.C), K=TensorDef(T2, S.KH, S.KW, index_dims=[D.kh, D.kw]), O=TensorDef(U, S.N, S.OH, S.OW, S.C, output=True), strides=IndexAttrDef(S.SH, S.SW), dilations=IndexAttrDef(S.DH, S.DW))
Performs unsigned max pooling. Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output.
Performs unsigned max pooling.
[ "Performs", "unsigned", "max", "pooling", "." ]
def pooling_nhwc_max_unsigned( I=TensorDef(T1, S.N, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.C), K=TensorDef(T2, S.KH, S.KW, index_dims=[D.kh, D.kw]), O=TensorDef(U, S.N, S.OH, S.OW, S.C, output=True), strides=IndexAttrDef(S.SH, S.SW), dilations=IndexAttrDef(S.DH, S.DW)): """Performs unsigned max pooling. Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output. """ implements(ConvolutionOpInterface) domain(D.n, D.oh, D.ow, D.c, D.kh, D.kw) O[D.n, D.oh, D.ow, D.c] = ReduceFn.max_unsigned[D.kh, D.kw]( TypeFn.cast_unsigned( U, I[D.n, D.oh * S.SH + D.kh * S.DH, D.ow * S.SW + D.kw * S.DW, D.c]))
[ "def", "pooling_nhwc_max_unsigned", "(", "I", "=", "TensorDef", "(", "T1", ",", "S", ".", "N", ",", "S", ".", "OH", "*", "S", ".", "SH", "+", "S", ".", "KH", "*", "S", ".", "DH", ",", "S", ".", "OW", "*", "S", ".", "SW", "+", "S", ".", "KW", "*", "S", ".", "DW", ",", "S", ".", "C", ")", ",", "K", "=", "TensorDef", "(", "T2", ",", "S", ".", "KH", ",", "S", ".", "KW", ",", "index_dims", "=", "[", "D", ".", "kh", ",", "D", ".", "kw", "]", ")", ",", "O", "=", "TensorDef", "(", "U", ",", "S", ".", "N", ",", "S", ".", "OH", ",", "S", ".", "OW", ",", "S", ".", "C", ",", "output", "=", "True", ")", ",", "strides", "=", "IndexAttrDef", "(", "S", ".", "SH", ",", "S", ".", "SW", ")", ",", "dilations", "=", "IndexAttrDef", "(", "S", ".", "DH", ",", "S", ".", "DW", ")", ")", ":", "implements", "(", "ConvolutionOpInterface", ")", "domain", "(", "D", ".", "n", ",", "D", ".", "oh", ",", "D", ".", "ow", ",", "D", ".", "c", ",", "D", ".", "kh", ",", "D", ".", "kw", ")", "O", "[", "D", ".", "n", ",", "D", ".", "oh", ",", "D", ".", "ow", ",", "D", ".", "c", "]", "=", "ReduceFn", ".", "max_unsigned", "[", "D", ".", "kh", ",", "D", ".", "kw", "]", "(", "TypeFn", ".", "cast_unsigned", "(", "U", ",", "I", "[", "D", ".", "n", ",", "D", ".", "oh", "*", "S", ".", "SH", "+", "D", ".", "kh", "*", "S", ".", "DH", ",", "D", ".", "ow", "*", "S", ".", "SW", "+", "D", ".", "kw", "*", "S", ".", "DW", ",", "D", ".", "c", "]", ")", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L488-L504
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Image.__init__
(self, *args, **kwargs)
__init__(self, String name, int type=BITMAP_TYPE_ANY, int index=-1) -> Image Loads an image from a file.
__init__(self, String name, int type=BITMAP_TYPE_ANY, int index=-1) -> Image
[ "__init__", "(", "self", "String", "name", "int", "type", "=", "BITMAP_TYPE_ANY", "int", "index", "=", "-", "1", ")", "-", ">", "Image" ]
def __init__(self, *args, **kwargs): """ __init__(self, String name, int type=BITMAP_TYPE_ANY, int index=-1) -> Image Loads an image from a file. """ _core_.Image_swiginit(self,_core_.new_Image(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "Image_swiginit", "(", "self", ",", "_core_", ".", "new_Image", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2876-L2882
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pgen2/parse.py
python
Parser.__init__
(self, grammar, convert=None)
Constructor. The grammar argument is a grammar.Grammar instance; see the grammar module for more information. The parser is not ready yet for parsing; you must call the setup() method to get it started. The optional convert argument is a function mapping concrete syntax tree nodes to abstract syntax tree nodes. If not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function.
Constructor.
[ "Constructor", "." ]
def __init__(self, grammar, convert=None): """Constructor. The grammar argument is a grammar.Grammar instance; see the grammar module for more information. The parser is not ready yet for parsing; you must call the setup() method to get it started. The optional convert argument is a function mapping concrete syntax tree nodes to abstract syntax tree nodes. If not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function. """ self.grammar = grammar self.convert = convert or (lambda grammar, node: node)
[ "def", "__init__", "(", "self", ",", "grammar", ",", "convert", "=", "None", ")", ":", "self", ".", "grammar", "=", "grammar", "self", ".", "convert", "=", "convert", "or", "(", "lambda", "grammar", ",", "node", ":", "node", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pgen2/parse.py#L57-L87
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/media.py
python
MediaCtrl.GetDownloadProgress
(*args, **kwargs)
return _media.MediaCtrl_GetDownloadProgress(*args, **kwargs)
GetDownloadProgress(self) -> wxFileOffset
GetDownloadProgress(self) -> wxFileOffset
[ "GetDownloadProgress", "(", "self", ")", "-", ">", "wxFileOffset" ]
def GetDownloadProgress(*args, **kwargs): """GetDownloadProgress(self) -> wxFileOffset""" return _media.MediaCtrl_GetDownloadProgress(*args, **kwargs)
[ "def", "GetDownloadProgress", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_media", ".", "MediaCtrl_GetDownloadProgress", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/media.py#L170-L172
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/hermite_e.py
python
hermepow
(c, pow, maxpower=16)
return pu._pow(hermemul, c, pow, maxpower)
Raise a Hermite series to a power. Returns the Hermite series `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.`` Parameters ---------- c : array_like 1-D array of Hermite series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Hermite series of power. See Also -------- hermeadd, hermesub, hermemulx, hermemul, hermediv Examples -------- >>> from numpy.polynomial.hermite_e import hermepow >>> hermepow([1, 2, 3], 2) array([23., 28., 46., 12., 9.])
Raise a Hermite series to a power.
[ "Raise", "a", "Hermite", "series", "to", "a", "power", "." ]
def hermepow(c, pow, maxpower=16): """Raise a Hermite series to a power. Returns the Hermite series `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.`` Parameters ---------- c : array_like 1-D array of Hermite series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Hermite series of power. See Also -------- hermeadd, hermesub, hermemulx, hermemul, hermediv Examples -------- >>> from numpy.polynomial.hermite_e import hermepow >>> hermepow([1, 2, 3], 2) array([23., 28., 46., 12., 9.]) """ return pu._pow(hermemul, c, pow, maxpower)
[ "def", "hermepow", "(", "c", ",", "pow", ",", "maxpower", "=", "16", ")", ":", "return", "pu", ".", "_pow", "(", "hermemul", ",", "c", ",", "pow", ",", "maxpower", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/hermite_e.py#L533-L567
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/recfunctions.py
python
join_by
(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None, usemask=True, asrecarray=False)
return _fix_output(_fix_defaults(output, defaults), **kwargs)
Join arrays `r1` and `r2` on key `key`. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the `key` field cannot be found in the two input arrays. Neither `r1` nor `r2` should have any duplicates along `key`: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters ---------- key : {string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2 : arrays Structured arrays. jointype : {'inner', 'outer', 'leftouter'}, optional If 'inner', returns the elements common to both r1 and r2. If 'outer', returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If 'leftouter', returns the common elements and the elements of r1 not in r2. r1postfix : string, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfix : string, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults : {dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask : {True, False}, optional Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`) or a ndarray. asrecarray : {False, True}, optional Whether to return a recarray (or MaskedRecords if `usemask==True`) or just a flexible-type ndarray. Notes ----- * The output is sorted along the key. * A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates...
Join arrays `r1` and `r2` on key `key`.
[ "Join", "arrays", "r1", "and", "r2", "on", "key", "key", "." ]
def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None, usemask=True, asrecarray=False): """ Join arrays `r1` and `r2` on key `key`. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the `key` field cannot be found in the two input arrays. Neither `r1` nor `r2` should have any duplicates along `key`: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters ---------- key : {string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2 : arrays Structured arrays. jointype : {'inner', 'outer', 'leftouter'}, optional If 'inner', returns the elements common to both r1 and r2. If 'outer', returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If 'leftouter', returns the common elements and the elements of r1 not in r2. r1postfix : string, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfix : string, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults : {dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask : {True, False}, optional Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`) or a ndarray. asrecarray : {False, True}, optional Whether to return a recarray (or MaskedRecords if `usemask==True`) or just a flexible-type ndarray. Notes ----- * The output is sorted along the key. * A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates... """ # Check jointype if jointype not in ('inner', 'outer', 'leftouter'): raise ValueError( "The 'jointype' argument should be in 'inner', " "'outer' or 'leftouter' (got '%s' instead)" % jointype ) # If we have a single key, put it in a tuple if isinstance(key, basestring): key = (key,) # Check the keys if len(set(key)) != len(key): dup = next(x for n,x in enumerate(key) if x in key[n+1:]) raise ValueError("duplicate join key %r" % dup) for name in key: if name not in r1.dtype.names: raise ValueError('r1 does not have key field %r' % name) if name not in r2.dtype.names: raise ValueError('r2 does not have key field %r' % name) # Make sure we work with ravelled arrays r1 = r1.ravel() r2 = r2.ravel() # Fixme: nb2 below is never used. Commenting out for pyflakes. # (nb1, nb2) = (len(r1), len(r2)) nb1 = len(r1) (r1names, r2names) = (r1.dtype.names, r2.dtype.names) # Check the names for collision collisions = (set(r1names) & set(r2names)) - set(key) if collisions and not (r1postfix or r2postfix): msg = "r1 and r2 contain common names, r1postfix and r2postfix " msg += "can't both be empty" raise ValueError(msg) # Make temporary arrays of just the keys # (use order of keys in `r1` for back-compatibility) key1 = [ n for n in r1names if n in key ] r1k = _keep_fields(r1, key1) r2k = _keep_fields(r2, key1) # Concatenate the two arrays for comparison aux = ma.concatenate((r1k, r2k)) idx_sort = aux.argsort(order=key) aux = aux[idx_sort] # # Get the common keys flag_in = ma.concatenate(([False], aux[1:] == aux[:-1])) flag_in[:-1] = flag_in[1:] + flag_in[:-1] idx_in = idx_sort[flag_in] idx_1 = idx_in[(idx_in < nb1)] idx_2 = idx_in[(idx_in >= nb1)] - nb1 (r1cmn, r2cmn) = (len(idx_1), len(idx_2)) if jointype == 'inner': (r1spc, r2spc) = (0, 0) elif jointype == 'outer': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) idx_2 = np.concatenate((idx_2, idx_out[(idx_out >= nb1)] - nb1)) (r1spc, r2spc) = (len(idx_1) - r1cmn, len(idx_2) - r2cmn) elif jointype == 'leftouter': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) (r1spc, r2spc) = (len(idx_1) - r1cmn, 0) # Select the entries from each input (s1, s2) = (r1[idx_1], r2[idx_2]) # # Build the new description of the output array ....... # Start with the key fields ndtype = _get_fieldspec(r1k.dtype) # Add the fields from r1 for fname, fdtype in _get_fieldspec(r1.dtype): if fname not in key: ndtype.append((fname, fdtype)) # Add the fields from r2 for fname, fdtype in _get_fieldspec(r2.dtype): # Have we seen the current name already ? # we need to rebuild this list every time names = list(name for name, dtype in ndtype) try: nameidx = names.index(fname) except ValueError: #... we haven't: just add the description to the current list ndtype.append((fname, fdtype)) else: # collision _, cdtype = ndtype[nameidx] if fname in key: # The current field is part of the key: take the largest dtype ndtype[nameidx] = (fname, max(fdtype, cdtype)) else: # The current field is not part of the key: add the suffixes, # and place the new field adjacent to the old one ndtype[nameidx:nameidx + 1] = [ (fname + r1postfix, cdtype), (fname + r2postfix, fdtype) ] # Rebuild a dtype from the new fields ndtype = np.dtype(ndtype) # Find the largest nb of common fields : # r1cmn and r2cmn should be equal, but... cmn = max(r1cmn, r2cmn) # Construct an empty array output = ma.masked_all((cmn + r1spc + r2spc,), dtype=ndtype) names = output.dtype.names for f in r1names: selected = s1[f] if f not in names or (f in r2names and not r2postfix and f not in key): f += r1postfix current = output[f] current[:r1cmn] = selected[:r1cmn] if jointype in ('outer', 'leftouter'): current[cmn:cmn + r1spc] = selected[r1cmn:] for f in r2names: selected = s2[f] if f not in names or (f in r1names and not r1postfix and f not in key): f += r2postfix current = output[f] current[:r2cmn] = selected[:r2cmn] if (jointype == 'outer') and r2spc: current[-r2spc:] = selected[r2cmn:] # Sort and finalize the output output.sort(order=key) kwargs = dict(usemask=usemask, asrecarray=asrecarray) return _fix_output(_fix_defaults(output, defaults), **kwargs)
[ "def", "join_by", "(", "key", ",", "r1", ",", "r2", ",", "jointype", "=", "'inner'", ",", "r1postfix", "=", "'1'", ",", "r2postfix", "=", "'2'", ",", "defaults", "=", "None", ",", "usemask", "=", "True", ",", "asrecarray", "=", "False", ")", ":", "# Check jointype", "if", "jointype", "not", "in", "(", "'inner'", ",", "'outer'", ",", "'leftouter'", ")", ":", "raise", "ValueError", "(", "\"The 'jointype' argument should be in 'inner', \"", "\"'outer' or 'leftouter' (got '%s' instead)\"", "%", "jointype", ")", "# If we have a single key, put it in a tuple", "if", "isinstance", "(", "key", ",", "basestring", ")", ":", "key", "=", "(", "key", ",", ")", "# Check the keys", "if", "len", "(", "set", "(", "key", ")", ")", "!=", "len", "(", "key", ")", ":", "dup", "=", "next", "(", "x", "for", "n", ",", "x", "in", "enumerate", "(", "key", ")", "if", "x", "in", "key", "[", "n", "+", "1", ":", "]", ")", "raise", "ValueError", "(", "\"duplicate join key %r\"", "%", "dup", ")", "for", "name", "in", "key", ":", "if", "name", "not", "in", "r1", ".", "dtype", ".", "names", ":", "raise", "ValueError", "(", "'r1 does not have key field %r'", "%", "name", ")", "if", "name", "not", "in", "r2", ".", "dtype", ".", "names", ":", "raise", "ValueError", "(", "'r2 does not have key field %r'", "%", "name", ")", "# Make sure we work with ravelled arrays", "r1", "=", "r1", ".", "ravel", "(", ")", "r2", "=", "r2", ".", "ravel", "(", ")", "# Fixme: nb2 below is never used. Commenting out for pyflakes.", "# (nb1, nb2) = (len(r1), len(r2))", "nb1", "=", "len", "(", "r1", ")", "(", "r1names", ",", "r2names", ")", "=", "(", "r1", ".", "dtype", ".", "names", ",", "r2", ".", "dtype", ".", "names", ")", "# Check the names for collision", "collisions", "=", "(", "set", "(", "r1names", ")", "&", "set", "(", "r2names", ")", ")", "-", "set", "(", "key", ")", "if", "collisions", "and", "not", "(", "r1postfix", "or", "r2postfix", ")", ":", "msg", "=", "\"r1 and r2 contain common names, r1postfix and r2postfix \"", "msg", "+=", "\"can't both be empty\"", "raise", "ValueError", "(", "msg", ")", "# Make temporary arrays of just the keys", "# (use order of keys in `r1` for back-compatibility)", "key1", "=", "[", "n", "for", "n", "in", "r1names", "if", "n", "in", "key", "]", "r1k", "=", "_keep_fields", "(", "r1", ",", "key1", ")", "r2k", "=", "_keep_fields", "(", "r2", ",", "key1", ")", "# Concatenate the two arrays for comparison", "aux", "=", "ma", ".", "concatenate", "(", "(", "r1k", ",", "r2k", ")", ")", "idx_sort", "=", "aux", ".", "argsort", "(", "order", "=", "key", ")", "aux", "=", "aux", "[", "idx_sort", "]", "#", "# Get the common keys", "flag_in", "=", "ma", ".", "concatenate", "(", "(", "[", "False", "]", ",", "aux", "[", "1", ":", "]", "==", "aux", "[", ":", "-", "1", "]", ")", ")", "flag_in", "[", ":", "-", "1", "]", "=", "flag_in", "[", "1", ":", "]", "+", "flag_in", "[", ":", "-", "1", "]", "idx_in", "=", "idx_sort", "[", "flag_in", "]", "idx_1", "=", "idx_in", "[", "(", "idx_in", "<", "nb1", ")", "]", "idx_2", "=", "idx_in", "[", "(", "idx_in", ">=", "nb1", ")", "]", "-", "nb1", "(", "r1cmn", ",", "r2cmn", ")", "=", "(", "len", "(", "idx_1", ")", ",", "len", "(", "idx_2", ")", ")", "if", "jointype", "==", "'inner'", ":", "(", "r1spc", ",", "r2spc", ")", "=", "(", "0", ",", "0", ")", "elif", "jointype", "==", "'outer'", ":", "idx_out", "=", "idx_sort", "[", "~", "flag_in", "]", "idx_1", "=", "np", ".", "concatenate", "(", "(", "idx_1", ",", "idx_out", "[", "(", "idx_out", "<", "nb1", ")", "]", ")", ")", "idx_2", "=", "np", ".", "concatenate", "(", "(", "idx_2", ",", "idx_out", "[", "(", "idx_out", ">=", "nb1", ")", "]", "-", "nb1", ")", ")", "(", "r1spc", ",", "r2spc", ")", "=", "(", "len", "(", "idx_1", ")", "-", "r1cmn", ",", "len", "(", "idx_2", ")", "-", "r2cmn", ")", "elif", "jointype", "==", "'leftouter'", ":", "idx_out", "=", "idx_sort", "[", "~", "flag_in", "]", "idx_1", "=", "np", ".", "concatenate", "(", "(", "idx_1", ",", "idx_out", "[", "(", "idx_out", "<", "nb1", ")", "]", ")", ")", "(", "r1spc", ",", "r2spc", ")", "=", "(", "len", "(", "idx_1", ")", "-", "r1cmn", ",", "0", ")", "# Select the entries from each input", "(", "s1", ",", "s2", ")", "=", "(", "r1", "[", "idx_1", "]", ",", "r2", "[", "idx_2", "]", ")", "#", "# Build the new description of the output array .......", "# Start with the key fields", "ndtype", "=", "_get_fieldspec", "(", "r1k", ".", "dtype", ")", "# Add the fields from r1", "for", "fname", ",", "fdtype", "in", "_get_fieldspec", "(", "r1", ".", "dtype", ")", ":", "if", "fname", "not", "in", "key", ":", "ndtype", ".", "append", "(", "(", "fname", ",", "fdtype", ")", ")", "# Add the fields from r2", "for", "fname", ",", "fdtype", "in", "_get_fieldspec", "(", "r2", ".", "dtype", ")", ":", "# Have we seen the current name already ?", "# we need to rebuild this list every time", "names", "=", "list", "(", "name", "for", "name", ",", "dtype", "in", "ndtype", ")", "try", ":", "nameidx", "=", "names", ".", "index", "(", "fname", ")", "except", "ValueError", ":", "#... we haven't: just add the description to the current list", "ndtype", ".", "append", "(", "(", "fname", ",", "fdtype", ")", ")", "else", ":", "# collision", "_", ",", "cdtype", "=", "ndtype", "[", "nameidx", "]", "if", "fname", "in", "key", ":", "# The current field is part of the key: take the largest dtype", "ndtype", "[", "nameidx", "]", "=", "(", "fname", ",", "max", "(", "fdtype", ",", "cdtype", ")", ")", "else", ":", "# The current field is not part of the key: add the suffixes,", "# and place the new field adjacent to the old one", "ndtype", "[", "nameidx", ":", "nameidx", "+", "1", "]", "=", "[", "(", "fname", "+", "r1postfix", ",", "cdtype", ")", ",", "(", "fname", "+", "r2postfix", ",", "fdtype", ")", "]", "# Rebuild a dtype from the new fields", "ndtype", "=", "np", ".", "dtype", "(", "ndtype", ")", "# Find the largest nb of common fields :", "# r1cmn and r2cmn should be equal, but...", "cmn", "=", "max", "(", "r1cmn", ",", "r2cmn", ")", "# Construct an empty array", "output", "=", "ma", ".", "masked_all", "(", "(", "cmn", "+", "r1spc", "+", "r2spc", ",", ")", ",", "dtype", "=", "ndtype", ")", "names", "=", "output", ".", "dtype", ".", "names", "for", "f", "in", "r1names", ":", "selected", "=", "s1", "[", "f", "]", "if", "f", "not", "in", "names", "or", "(", "f", "in", "r2names", "and", "not", "r2postfix", "and", "f", "not", "in", "key", ")", ":", "f", "+=", "r1postfix", "current", "=", "output", "[", "f", "]", "current", "[", ":", "r1cmn", "]", "=", "selected", "[", ":", "r1cmn", "]", "if", "jointype", "in", "(", "'outer'", ",", "'leftouter'", ")", ":", "current", "[", "cmn", ":", "cmn", "+", "r1spc", "]", "=", "selected", "[", "r1cmn", ":", "]", "for", "f", "in", "r2names", ":", "selected", "=", "s2", "[", "f", "]", "if", "f", "not", "in", "names", "or", "(", "f", "in", "r1names", "and", "not", "r1postfix", "and", "f", "not", "in", "key", ")", ":", "f", "+=", "r2postfix", "current", "=", "output", "[", "f", "]", "current", "[", ":", "r2cmn", "]", "=", "selected", "[", ":", "r2cmn", "]", "if", "(", "jointype", "==", "'outer'", ")", "and", "r2spc", ":", "current", "[", "-", "r2spc", ":", "]", "=", "selected", "[", "r2cmn", ":", "]", "# Sort and finalize the output", "output", ".", "sort", "(", "order", "=", "key", ")", "kwargs", "=", "dict", "(", "usemask", "=", "usemask", ",", "asrecarray", "=", "asrecarray", ")", "return", "_fix_output", "(", "_fix_defaults", "(", "output", ",", "defaults", ")", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/recfunctions.py#L1412-L1588
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
build/android/android_commands.py
python
AndroidCommands.Adb
(self)
return self._adb
Returns our AdbInterface to avoid us wrapping all its methods.
Returns our AdbInterface to avoid us wrapping all its methods.
[ "Returns", "our", "AdbInterface", "to", "avoid", "us", "wrapping", "all", "its", "methods", "." ]
def Adb(self): """Returns our AdbInterface to avoid us wrapping all its methods.""" return self._adb
[ "def", "Adb", "(", "self", ")", ":", "return", "self", ".", "_adb" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/android_commands.py#L221-L223
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/bisect_fyi.py
python
BisectFYIHandler.get
(self)
A get request is the same a post request for this endpoint.
A get request is the same a post request for this endpoint.
[ "A", "get", "request", "is", "the", "same", "a", "post", "request", "for", "this", "endpoint", "." ]
def get(self): """A get request is the same a post request for this endpoint.""" self.post()
[ "def", "get", "(", "self", ")", ":", "self", ".", "post", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/bisect_fyi.py#L31-L33
gromacs/gromacs
7dec3a3f99993cf5687a122de3e12de31c21c399
python_packaging/src/gmxapi/simulation/mdrun.py
python
ResourceManager.update_output
(self)
Override gmxapi.operation.ResourceManager.update_output because we handle paralellism as 0.0.7.
Override gmxapi.operation.ResourceManager.update_output because we handle paralellism as 0.0.7.
[ "Override", "gmxapi", ".", "operation", ".", "ResourceManager", ".", "update_output", "because", "we", "handle", "paralellism", "as", "0", ".", "0", ".", "7", "." ]
def update_output(self): """Override gmxapi.operation.ResourceManager.update_output because we handle paralellism as 0.0.7.""" # For the moment, this is copy-pasted from gmxapi.operation.ResourceManager, # but the only part we need to override is the ensemble handling at `for i in range(self.ensemble_width)` # TODO: Reimplement as the resource factory and director for the operation target context. if not self.done(): self.__operation_entrance_counter += 1 if self.__operation_entrance_counter > 1: raise exceptions.ProtocolError( 'Bug detected: resource manager tried to execute operation twice.') if not self.done(): # TODO: rewrite with the pattern that this block is directing and then resolving an operation in the # operation's library/implementation context. ### # Note: this is the resource translation from gmxapi.operation context # to the dispatching runner director. It uses details of the gmxapi.operation.Context # and of the operation. # Create on all ranks. # Unlike gmxapi.operation.ResourceManager, here we create the input resources # once for the entire ensemble, rather than once per ensemble member. # This is because the simulation actually runs as an ensemble operation # (in gmxapi 0.0.7 context) in order to service the input resources of this # version of the mdrun operation, which in actuality merely retrieves the # gmxapi 0.0.7 results for the current interface. # Abstractions that could allow reunification with the parent implementation # could be asyncio or concurrent processing of the ensemble members, or a `map` # generalization that could be implemented in serial or parallel according to the # ResourceManager and task requirements. # TODO: Dispatch/discover this resource factory from a canonical place. input = LegacyImplementationSubscription(self) # End of action of the InputResourceDirector[Context, MdRunSubscription]. ### # We are giving the director a resource that contains the subscription # to the dispatched work. publishing_resources = self.publishing_resources() for member in range(self.ensemble_width): with publishing_resources(ensemble_member=member) as output: error_message = 'Got {} while executing {} for operation {}.' try: resources = self._resource_factory(input=input, output=output) except exceptions.TypeError as e: message = error_message.format(e, self._resource_factory, self.operation_id) raise exceptions.ApiError(message) from e runner = self._runner_director(resources) try: runner() except Exception as e: message = error_message.format(e, runner, self.operation_id) raise exceptions.ApiError(message) from e if not self.done(): message = f'update_output implementation failed to update all outputs for {self.operation_id}.' raise exceptions.ApiError(message)
[ "def", "update_output", "(", "self", ")", ":", "# For the moment, this is copy-pasted from gmxapi.operation.ResourceManager,", "# but the only part we need to override is the ensemble handling at `for i in range(self.ensemble_width)`", "# TODO: Reimplement as the resource factory and director for the operation target context.", "if", "not", "self", ".", "done", "(", ")", ":", "self", ".", "__operation_entrance_counter", "+=", "1", "if", "self", ".", "__operation_entrance_counter", ">", "1", ":", "raise", "exceptions", ".", "ProtocolError", "(", "'Bug detected: resource manager tried to execute operation twice.'", ")", "if", "not", "self", ".", "done", "(", ")", ":", "# TODO: rewrite with the pattern that this block is directing and then resolving an operation in the", "# operation's library/implementation context.", "###", "# Note: this is the resource translation from gmxapi.operation context", "# to the dispatching runner director. It uses details of the gmxapi.operation.Context", "# and of the operation.", "# Create on all ranks.", "# Unlike gmxapi.operation.ResourceManager, here we create the input resources", "# once for the entire ensemble, rather than once per ensemble member.", "# This is because the simulation actually runs as an ensemble operation", "# (in gmxapi 0.0.7 context) in order to service the input resources of this", "# version of the mdrun operation, which in actuality merely retrieves the", "# gmxapi 0.0.7 results for the current interface.", "# Abstractions that could allow reunification with the parent implementation", "# could be asyncio or concurrent processing of the ensemble members, or a `map`", "# generalization that could be implemented in serial or parallel according to the", "# ResourceManager and task requirements.", "# TODO: Dispatch/discover this resource factory from a canonical place.", "input", "=", "LegacyImplementationSubscription", "(", "self", ")", "# End of action of the InputResourceDirector[Context, MdRunSubscription].", "###", "# We are giving the director a resource that contains the subscription", "# to the dispatched work.", "publishing_resources", "=", "self", ".", "publishing_resources", "(", ")", "for", "member", "in", "range", "(", "self", ".", "ensemble_width", ")", ":", "with", "publishing_resources", "(", "ensemble_member", "=", "member", ")", "as", "output", ":", "error_message", "=", "'Got {} while executing {} for operation {}.'", "try", ":", "resources", "=", "self", ".", "_resource_factory", "(", "input", "=", "input", ",", "output", "=", "output", ")", "except", "exceptions", ".", "TypeError", "as", "e", ":", "message", "=", "error_message", ".", "format", "(", "e", ",", "self", ".", "_resource_factory", ",", "self", ".", "operation_id", ")", "raise", "exceptions", ".", "ApiError", "(", "message", ")", "from", "e", "runner", "=", "self", ".", "_runner_director", "(", "resources", ")", "try", ":", "runner", "(", ")", "except", "Exception", "as", "e", ":", "message", "=", "error_message", ".", "format", "(", "e", ",", "runner", ",", "self", ".", "operation_id", ")", "raise", "exceptions", ".", "ApiError", "(", "message", ")", "from", "e", "if", "not", "self", ".", "done", "(", ")", ":", "message", "=", "f'update_output implementation failed to update all outputs for {self.operation_id}.'", "raise", "exceptions", ".", "ApiError", "(", "message", ")" ]
https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/simulation/mdrun.py#L529-L587
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
clang/tools/scan-build-py/lib/libscanbuild/arguments.py
python
parse_args_for_analyze_build
()
return args
Parse and validate command-line arguments for analyze-build.
Parse and validate command-line arguments for analyze-build.
[ "Parse", "and", "validate", "command", "-", "line", "arguments", "for", "analyze", "-", "build", "." ]
def parse_args_for_analyze_build(): """ Parse and validate command-line arguments for analyze-build. """ from_build_command = False parser = create_analyze_parser(from_build_command) args = parser.parse_args() reconfigure_logging(args.verbose) logging.debug('Raw arguments %s', sys.argv) normalize_args_for_analyze(args, from_build_command) validate_args_for_analyze(parser, args, from_build_command) logging.debug('Parsed arguments: %s', args) return args
[ "def", "parse_args_for_analyze_build", "(", ")", ":", "from_build_command", "=", "False", "parser", "=", "create_analyze_parser", "(", "from_build_command", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "reconfigure_logging", "(", "args", ".", "verbose", ")", "logging", ".", "debug", "(", "'Raw arguments %s'", ",", "sys", ".", "argv", ")", "normalize_args_for_analyze", "(", "args", ",", "from_build_command", ")", "validate_args_for_analyze", "(", "parser", ",", "args", ",", "from_build_command", ")", "logging", ".", "debug", "(", "'Parsed arguments: %s'", ",", "args", ")", "return", "args" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/tools/scan-build-py/lib/libscanbuild/arguments.py#L45-L58
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeCtrl.GetPrevVisible
(*args, **kwargs)
return _controls_.TreeCtrl_GetPrevVisible(*args, **kwargs)
GetPrevVisible(self, TreeItemId item) -> TreeItemId
GetPrevVisible(self, TreeItemId item) -> TreeItemId
[ "GetPrevVisible", "(", "self", "TreeItemId", "item", ")", "-", ">", "TreeItemId" ]
def GetPrevVisible(*args, **kwargs): """GetPrevVisible(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetPrevVisible(*args, **kwargs)
[ "def", "GetPrevVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_GetPrevVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5422-L5424
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.GetMarginType
(*args, **kwargs)
return _stc.StyledTextCtrl_GetMarginType(*args, **kwargs)
GetMarginType(self, int margin) -> int Retrieve the type of a margin.
GetMarginType(self, int margin) -> int
[ "GetMarginType", "(", "self", "int", "margin", ")", "-", ">", "int" ]
def GetMarginType(*args, **kwargs): """ GetMarginType(self, int margin) -> int Retrieve the type of a margin. """ return _stc.StyledTextCtrl_GetMarginType(*args, **kwargs)
[ "def", "GetMarginType", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetMarginType", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2442-L2448
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/session_manager.py
python
SessionManager.prepare_session
(self, master, init_op=None, saver=None, checkpoint_dir=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, init_feed_dict=None, init_fn=None)
return sess
Creates a `Session`. Makes sure the model is ready to be used. Creates a `Session` on 'master'. If a `saver` object is passed in, and `checkpoint_dir` points to a directory containing valid checkpoint files, then it will try to recover the model from checkpoint. If no checkpoint files are available, and `wait_for_checkpoint` is `True`, then the process would check every `recovery_wait_secs`, up to `max_wait_secs`, for recovery to succeed. If the model cannot be recovered successfully then it is initialized by either running the provided `init_op`, or calling the provided `init_fn`. The local_init_op is also run after init_op and init_fn, regardless of whether the model was recovered successfully, but only if ready_for_local_init_op passes. It is an error if the model cannot be recovered and no `init_op` or `init_fn` or `local_init_op` are passed. Args: master: `String` representation of the TensorFlow master to use. init_op: Optional `Operation` used to initialize the model. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. init_feed_dict: Optional dictionary that maps `Tensor` objects to feed values. This feed dictionary is passed to the session `run()` call when running the init op. init_fn: Optional callable used to initialize the model. Called after the optional `init_op` is called. The callable must accept one argument, the session being initialized. Returns: A `Session` object that can be used to drive the model. Raises: RuntimeError: If the model cannot be initialized or recovered.
Creates a `Session`. Makes sure the model is ready to be used.
[ "Creates", "a", "Session", ".", "Makes", "sure", "the", "model", "is", "ready", "to", "be", "used", "." ]
def prepare_session(self, master, init_op=None, saver=None, checkpoint_dir=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, init_feed_dict=None, init_fn=None): """Creates a `Session`. Makes sure the model is ready to be used. Creates a `Session` on 'master'. If a `saver` object is passed in, and `checkpoint_dir` points to a directory containing valid checkpoint files, then it will try to recover the model from checkpoint. If no checkpoint files are available, and `wait_for_checkpoint` is `True`, then the process would check every `recovery_wait_secs`, up to `max_wait_secs`, for recovery to succeed. If the model cannot be recovered successfully then it is initialized by either running the provided `init_op`, or calling the provided `init_fn`. The local_init_op is also run after init_op and init_fn, regardless of whether the model was recovered successfully, but only if ready_for_local_init_op passes. It is an error if the model cannot be recovered and no `init_op` or `init_fn` or `local_init_op` are passed. Args: master: `String` representation of the TensorFlow master to use. init_op: Optional `Operation` used to initialize the model. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. init_feed_dict: Optional dictionary that maps `Tensor` objects to feed values. This feed dictionary is passed to the session `run()` call when running the init op. init_fn: Optional callable used to initialize the model. Called after the optional `init_op` is called. The callable must accept one argument, the session being initialized. Returns: A `Session` object that can be used to drive the model. Raises: RuntimeError: If the model cannot be initialized or recovered. """ sess, is_loaded_from_checkpoint = self._restore_checkpoint( master, saver, checkpoint_dir=checkpoint_dir, wait_for_checkpoint=wait_for_checkpoint, max_wait_secs=max_wait_secs, config=config) if not is_loaded_from_checkpoint: if init_op is None and not init_fn and self._local_init_op is None: raise RuntimeError("Model is not initialized and no init_op or " "init_fn or local_init_op was given") if init_op is not None: sess.run(init_op, feed_dict=init_feed_dict) if init_fn: init_fn(sess) local_init_success, msg = self._try_run_local_init_op(sess) if not local_init_success: raise RuntimeError( "Init operations did not make model ready for local_init. " "Init op: %s, init fn: %s, error: %s" % ("None" if init_op is None else init_op.name, init_fn, msg)) is_ready, msg = self._model_ready(sess) if not is_ready: raise RuntimeError( "Init operations did not make model ready. " "Init op: %s, init fn: %s, local_init_op: %s, error: %s" % (None if init_op is None else init_op.name, init_fn, self._local_init_op, msg)) return sess
[ "def", "prepare_session", "(", "self", ",", "master", ",", "init_op", "=", "None", ",", "saver", "=", "None", ",", "checkpoint_dir", "=", "None", ",", "wait_for_checkpoint", "=", "False", ",", "max_wait_secs", "=", "7200", ",", "config", "=", "None", ",", "init_feed_dict", "=", "None", ",", "init_fn", "=", "None", ")", ":", "sess", ",", "is_loaded_from_checkpoint", "=", "self", ".", "_restore_checkpoint", "(", "master", ",", "saver", ",", "checkpoint_dir", "=", "checkpoint_dir", ",", "wait_for_checkpoint", "=", "wait_for_checkpoint", ",", "max_wait_secs", "=", "max_wait_secs", ",", "config", "=", "config", ")", "if", "not", "is_loaded_from_checkpoint", ":", "if", "init_op", "is", "None", "and", "not", "init_fn", "and", "self", ".", "_local_init_op", "is", "None", ":", "raise", "RuntimeError", "(", "\"Model is not initialized and no init_op or \"", "\"init_fn or local_init_op was given\"", ")", "if", "init_op", "is", "not", "None", ":", "sess", ".", "run", "(", "init_op", ",", "feed_dict", "=", "init_feed_dict", ")", "if", "init_fn", ":", "init_fn", "(", "sess", ")", "local_init_success", ",", "msg", "=", "self", ".", "_try_run_local_init_op", "(", "sess", ")", "if", "not", "local_init_success", ":", "raise", "RuntimeError", "(", "\"Init operations did not make model ready for local_init. \"", "\"Init op: %s, init fn: %s, error: %s\"", "%", "(", "\"None\"", "if", "init_op", "is", "None", "else", "init_op", ".", "name", ",", "init_fn", ",", "msg", ")", ")", "is_ready", ",", "msg", "=", "self", ".", "_model_ready", "(", "sess", ")", "if", "not", "is_ready", ":", "raise", "RuntimeError", "(", "\"Init operations did not make model ready. \"", "\"Init op: %s, init fn: %s, local_init_op: %s, error: %s\"", "%", "(", "None", "if", "init_op", "is", "None", "else", "init_op", ".", "name", ",", "init_fn", ",", "self", ".", "_local_init_op", ",", "msg", ")", ")", "return", "sess" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/session_manager.py#L177-L252
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/parsers/XmlPortsParser.py
python
Interface.__init__
(self, namespace, name, comment=None)
Constructor
Constructor
[ "Constructor" ]
def __init__(self, namespace, name, comment=None): """ Constructor """ self.__namespace = namespace self.__name = name self.__comment = comment self.__return_type = None self.__return_modifier = None
[ "def", "__init__", "(", "self", ",", "namespace", ",", "name", ",", "comment", "=", "None", ")", ":", "self", ".", "__namespace", "=", "namespace", "self", ".", "__name", "=", "name", "self", ".", "__comment", "=", "comment", "self", ".", "__return_type", "=", "None", "self", ".", "__return_modifier", "=", "None" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/parsers/XmlPortsParser.py#L260-L268
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/pdbfile.py
python
_format_83
(f)
Format a single float into a string of width 8, with ideally 3 decimal places of precision. If the number is a little too large, we can gracefully degrade the precision by lopping off some of the decimal places. If it's much too large, we throw a ValueError
Format a single float into a string of width 8, with ideally 3 decimal places of precision. If the number is a little too large, we can gracefully degrade the precision by lopping off some of the decimal places. If it's much too large, we throw a ValueError
[ "Format", "a", "single", "float", "into", "a", "string", "of", "width", "8", "with", "ideally", "3", "decimal", "places", "of", "precision", ".", "If", "the", "number", "is", "a", "little", "too", "large", "we", "can", "gracefully", "degrade", "the", "precision", "by", "lopping", "off", "some", "of", "the", "decimal", "places", ".", "If", "it", "s", "much", "too", "large", "we", "throw", "a", "ValueError" ]
def _format_83(f): """Format a single float into a string of width 8, with ideally 3 decimal places of precision. If the number is a little too large, we can gracefully degrade the precision by lopping off some of the decimal places. If it's much too large, we throw a ValueError""" if -999.999 < f < 9999.999: return '%8.3f' % f if -9999999 < f < 99999999: return ('%8.3f' % f)[:8] raise ValueError('coordinate "%s" could not be represented ' 'in a width-8 field' % f)
[ "def", "_format_83", "(", "f", ")", ":", "if", "-", "999.999", "<", "f", "<", "9999.999", ":", "return", "'%8.3f'", "%", "f", "if", "-", "9999999", "<", "f", "<", "99999999", ":", "return", "(", "'%8.3f'", "%", "f", ")", "[", ":", "8", "]", "raise", "ValueError", "(", "'coordinate \"%s\" could not be represented '", "'in a width-8 field'", "%", "f", ")" ]
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/pdbfile.py#L462-L472
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/util/request.py
python
set_file_position
(body, pos)
return pos
If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use.
If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use.
[ "If", "a", "position", "is", "provided", "move", "file", "to", "that", "point", ".", "Otherwise", "we", "ll", "attempt", "to", "record", "a", "position", "for", "future", "use", "." ]
def set_file_position(body, pos): """ If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. """ if pos is not None: rewind_body(body, pos) elif getattr(body, "tell", None) is not None: try: pos = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body. pos = _FAILEDTELL return pos
[ "def", "set_file_position", "(", "body", ",", "pos", ")", ":", "if", "pos", "is", "not", "None", ":", "rewind_body", "(", "body", ",", "pos", ")", "elif", "getattr", "(", "body", ",", "\"tell\"", ",", "None", ")", "is", "not", "None", ":", "try", ":", "pos", "=", "body", ".", "tell", "(", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "# This differentiates from None, allowing us to catch", "# a failed `tell()` later when trying to rewind the body.", "pos", "=", "_FAILEDTELL", "return", "pos" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/util/request.py#L98-L113
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/flatten-nested-list-iterator.py
python
NestedIterator.next
(self)
return nestedList[i].getInteger()
:rtype: int
:rtype: int
[ ":", "rtype", ":", "int" ]
def next(self): """ :rtype: int """ nestedList, i = self.__depth[-1] self.__depth[-1][1] += 1 return nestedList[i].getInteger()
[ "def", "next", "(", "self", ")", ":", "nestedList", ",", "i", "=", "self", ".", "__depth", "[", "-", "1", "]", "self", ".", "__depth", "[", "-", "1", "]", "[", "1", "]", "+=", "1", "return", "nestedList", "[", "i", "]", ".", "getInteger", "(", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/flatten-nested-list-iterator.py#L14-L20
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py
python
_default_compare_fn
(curr_best_eval_result, cand_eval_result)
return curr_best_eval_result[default_key] > cand_eval_result[default_key]
Compares two evaluation results and returns true if the 2nd one is better. Both evaluation results should have the values for MetricKey.LOSS, which are used for comparison. Args: curr_best_eval_result: current best eval metrics. cand_eval_result: candidate eval metrics. Returns: True if cand_eval_result is better. Raises: ValueError: If input eval result is None or no loss is available.
Compares two evaluation results and returns true if the 2nd one is better.
[ "Compares", "two", "evaluation", "results", "and", "returns", "true", "if", "the", "2nd", "one", "is", "better", "." ]
def _default_compare_fn(curr_best_eval_result, cand_eval_result): """Compares two evaluation results and returns true if the 2nd one is better. Both evaluation results should have the values for MetricKey.LOSS, which are used for comparison. Args: curr_best_eval_result: current best eval metrics. cand_eval_result: candidate eval metrics. Returns: True if cand_eval_result is better. Raises: ValueError: If input eval result is None or no loss is available. """ default_key = metric_key.MetricKey.LOSS if not curr_best_eval_result or default_key not in curr_best_eval_result: raise ValueError( 'curr_best_eval_result cannot be empty or no loss is found in it.') if not cand_eval_result or default_key not in cand_eval_result: raise ValueError( 'cand_eval_result cannot be empty or no loss is found in it.') return curr_best_eval_result[default_key] > cand_eval_result[default_key]
[ "def", "_default_compare_fn", "(", "curr_best_eval_result", ",", "cand_eval_result", ")", ":", "default_key", "=", "metric_key", ".", "MetricKey", ".", "LOSS", "if", "not", "curr_best_eval_result", "or", "default_key", "not", "in", "curr_best_eval_result", ":", "raise", "ValueError", "(", "'curr_best_eval_result cannot be empty or no loss is found in it.'", ")", "if", "not", "cand_eval_result", "or", "default_key", "not", "in", "cand_eval_result", ":", "raise", "ValueError", "(", "'cand_eval_result cannot be empty or no loss is found in it.'", ")", "return", "curr_best_eval_result", "[", "default_key", "]", ">", "cand_eval_result", "[", "default_key", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py#L514-L539
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/1-bit-and-2-bit-characters.py
python
Solution.isOneBitCharacter
(self, bits)
return parity == 0
:type bits: List[int] :rtype: bool
:type bits: List[int] :rtype: bool
[ ":", "type", "bits", ":", "List", "[", "int", "]", ":", "rtype", ":", "bool" ]
def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ parity = 0 for i in reversed(xrange(len(bits)-1)): if bits[i] == 0: break parity ^= bits[i] return parity == 0
[ "def", "isOneBitCharacter", "(", "self", ",", "bits", ")", ":", "parity", "=", "0", "for", "i", "in", "reversed", "(", "xrange", "(", "len", "(", "bits", ")", "-", "1", ")", ")", ":", "if", "bits", "[", "i", "]", "==", "0", ":", "break", "parity", "^=", "bits", "[", "i", "]", "return", "parity", "==", "0" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/1-bit-and-2-bit-characters.py#L6-L16
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cgi.py
python
FieldStorage.getlist
(self, key)
Return list of received values.
Return list of received values.
[ "Return", "list", "of", "received", "values", "." ]
def getlist(self, key): """ Return list of received values.""" if key in self: value = self[key] if type(value) is type([]): return map(attrgetter('value'), value) else: return [value.value] else: return []
[ "def", "getlist", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ":", "value", "=", "self", "[", "key", "]", "if", "type", "(", "value", ")", "is", "type", "(", "[", "]", ")", ":", "return", "map", "(", "attrgetter", "(", "'value'", ")", ",", "value", ")", "else", ":", "return", "[", "value", ".", "value", "]", "else", ":", "return", "[", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cgi.py#L568-L577
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py
python
MainWindow.add_scans_ub_table
(self, scan_list)
add scans to UB matrix construction table :param scan_list: :return:
add scans to UB matrix construction table :param scan_list: :return:
[ "add", "scans", "to", "UB", "matrix", "construction", "table", ":", "param", "scan_list", ":", ":", "return", ":" ]
def add_scans_ub_table(self, scan_list): """ add scans to UB matrix construction table :param scan_list: :return: """ # TODO/FIXME/ISSUE/NOW - consider to refactor with do_add_peaks_for_ub() and # get experiment number status, exp_number = gutil.parse_integers_editors(self.ui.lineEdit_exp) if not status: self.pop_one_button_dialog('Unable to get experiment number\n due to %s.' % str(exp_number)) return # switch to tab-3 # self.ui.tabWidget.setCurrentIndex(MainWindow.TabPage['Calculate UB']) # prototype for a new thread self.ui.progressBar_add_ub_peaks.setRange(0, len(scan_list)) self._addUBPeaksThread = thread_pool.AddPeaksThread(self, exp_number, scan_list) self._addUBPeaksThread.start() # set the flag/notification where the indexing (HKL) from self.ui.lineEdit_peaksIndexedBy.setText(IndexFromSpice)
[ "def", "add_scans_ub_table", "(", "self", ",", "scan_list", ")", ":", "# TODO/FIXME/ISSUE/NOW - consider to refactor with do_add_peaks_for_ub() and", "# get experiment number", "status", ",", "exp_number", "=", "gutil", ".", "parse_integers_editors", "(", "self", ".", "ui", ".", "lineEdit_exp", ")", "if", "not", "status", ":", "self", ".", "pop_one_button_dialog", "(", "'Unable to get experiment number\\n due to %s.'", "%", "str", "(", "exp_number", ")", ")", "return", "# switch to tab-3", "# self.ui.tabWidget.setCurrentIndex(MainWindow.TabPage['Calculate UB'])", "# prototype for a new thread", "self", ".", "ui", ".", "progressBar_add_ub_peaks", ".", "setRange", "(", "0", ",", "len", "(", "scan_list", ")", ")", "self", ".", "_addUBPeaksThread", "=", "thread_pool", ".", "AddPeaksThread", "(", "self", ",", "exp_number", ",", "scan_list", ")", "self", ".", "_addUBPeaksThread", ".", "start", "(", ")", "# set the flag/notification where the indexing (HKL) from", "self", ".", "ui", ".", "lineEdit_peaksIndexedBy", ".", "setText", "(", "IndexFromSpice", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py#L681-L702
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/nntplib.py
python
NNTP.body
(self, id, file=None)
return self.artcmd('BODY ' + id, file)
Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used
Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used
[ "Process", "a", "BODY", "command", ".", "Argument", ":", "-", "id", ":", "article", "number", "or", "message", "id", "-", "file", ":", "Filename", "string", "or", "file", "object", "to", "store", "the", "article", "in", "Returns", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "nr", ":", "article", "number", "-", "id", ":", "message", "id", "-", "list", ":", "the", "lines", "of", "the", "article", "s", "body", "or", "an", "empty", "list", "if", "file", "was", "used" ]
def body(self, id, file=None): """Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used""" return self.artcmd('BODY ' + id, file)
[ "def", "body", "(", "self", ",", "id", ",", "file", "=", "None", ")", ":", "return", "self", ".", "artcmd", "(", "'BODY '", "+", "id", ",", "file", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/nntplib.py#L431-L442
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
.github/manylinux.py
python
compile_wheels
(idx)
Compile binary wheels for different python versions.
Compile binary wheels for different python versions.
[ "Compile", "binary", "wheels", "for", "different", "python", "versions", "." ]
def compile_wheels(idx): ''' Compile binary wheels for different python versions. ''' for pybin in glob('/opt/python/*/bin'): # Requires Py3.6 or greater - on the docker image 3.5 is cp35-cp35m if "35" not in pybin: check_call(['rm', '-rf', '_skbuild']) args = [path.join(pybin, 'pip'), 'wheel', '--verbose', '--no-deps', '-w', 'wheelhouse/'] if idx is not None: args.extend(['--extra-index-url', idx]) args.extend(['./']) check_call(args)
[ "def", "compile_wheels", "(", "idx", ")", ":", "for", "pybin", "in", "glob", "(", "'/opt/python/*/bin'", ")", ":", "# Requires Py3.6 or greater - on the docker image 3.5 is cp35-cp35m", "if", "\"35\"", "not", "in", "pybin", ":", "check_call", "(", "[", "'rm'", ",", "'-rf'", ",", "'_skbuild'", "]", ")", "args", "=", "[", "path", ".", "join", "(", "pybin", ",", "'pip'", ")", ",", "'wheel'", ",", "'--verbose'", ",", "'--no-deps'", ",", "'-w'", ",", "'wheelhouse/'", "]", "if", "idx", "is", "not", "None", ":", "args", ".", "extend", "(", "[", "'--extra-index-url'", ",", "idx", "]", ")", "args", ".", "extend", "(", "[", "'./'", "]", ")", "check_call", "(", "args", ")" ]
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/.github/manylinux.py#L50-L62
timi-liuliang/echo
40a5a24d430eee4118314459ab7e03afcb3b8719
thirdparty/protobuf/python/google/protobuf/internal/python_message.py
python
_ExtensionDict.__init__
(self, extended_message)
extended_message: Message instance for which we are the Extensions dict.
extended_message: Message instance for which we are the Extensions dict.
[ "extended_message", ":", "Message", "instance", "for", "which", "we", "are", "the", "Extensions", "dict", "." ]
def __init__(self, extended_message): """extended_message: Message instance for which we are the Extensions dict. """ self._extended_message = extended_message
[ "def", "__init__", "(", "self", ",", "extended_message", ")", ":", "self", ".", "_extended_message", "=", "extended_message" ]
https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/internal/python_message.py#L1158-L1162
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicle.py
python
VehicleDomain.replaceStop
(self, vehID, nextStopIndex, edgeID, pos=1., laneIndex=0, duration=tc.INVALID_DOUBLE_VALUE, flags=tc.STOP_DEFAULT, startPos=tc.INVALID_DOUBLE_VALUE, until=tc.INVALID_DOUBLE_VALUE, teleport=0)
replaceStop(string, int, string, double, integer, double, integer, double, double) -> None Replaces stop at the given index with a new stop. Automatically modifies the route if the replacement stop is at another location. For edgeID a stopping place id may be given if the flag marks this stop as stopping on busStop, parkingArea, containerStop etc. If edgeID is "", the stop at the given index will be removed without replacement and the route will not be modified. If teleport is set to 1, the route to the replacement stop will be disconnected (forcing a teleport). If stopIndex is 0 the gap will be between the current edge and the new stop. Otherwise the gap will be between the stop edge for nextStopIndex - 1 and the new stop.
replaceStop(string, int, string, double, integer, double, integer, double, double) -> None
[ "replaceStop", "(", "string", "int", "string", "double", "integer", "double", "integer", "double", "double", ")", "-", ">", "None" ]
def replaceStop(self, vehID, nextStopIndex, edgeID, pos=1., laneIndex=0, duration=tc.INVALID_DOUBLE_VALUE, flags=tc.STOP_DEFAULT, startPos=tc.INVALID_DOUBLE_VALUE, until=tc.INVALID_DOUBLE_VALUE, teleport=0): """replaceStop(string, int, string, double, integer, double, integer, double, double) -> None Replaces stop at the given index with a new stop. Automatically modifies the route if the replacement stop is at another location. For edgeID a stopping place id may be given if the flag marks this stop as stopping on busStop, parkingArea, containerStop etc. If edgeID is "", the stop at the given index will be removed without replacement and the route will not be modified. If teleport is set to 1, the route to the replacement stop will be disconnected (forcing a teleport). If stopIndex is 0 the gap will be between the current edge and the new stop. Otherwise the gap will be between the stop edge for nextStopIndex - 1 and the new stop. """ self._setCmd(tc.CMD_REPLACE_STOP, vehID, "tsdbdiddib", 9, edgeID, pos, laneIndex, duration, flags, startPos, until, nextStopIndex, teleport)
[ "def", "replaceStop", "(", "self", ",", "vehID", ",", "nextStopIndex", ",", "edgeID", ",", "pos", "=", "1.", ",", "laneIndex", "=", "0", ",", "duration", "=", "tc", ".", "INVALID_DOUBLE_VALUE", ",", "flags", "=", "tc", ".", "STOP_DEFAULT", ",", "startPos", "=", "tc", ".", "INVALID_DOUBLE_VALUE", ",", "until", "=", "tc", ".", "INVALID_DOUBLE_VALUE", ",", "teleport", "=", "0", ")", ":", "self", ".", "_setCmd", "(", "tc", ".", "CMD_REPLACE_STOP", ",", "vehID", ",", "\"tsdbdiddib\"", ",", "9", ",", "edgeID", ",", "pos", ",", "laneIndex", ",", "duration", ",", "flags", ",", "startPos", ",", "until", ",", "nextStopIndex", ",", "teleport", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L1099-L1117
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
SplitterWindow.IsSplit
(*args, **kwargs)
return _windows_.SplitterWindow_IsSplit(*args, **kwargs)
IsSplit(self) -> bool Is the window split?
IsSplit(self) -> bool
[ "IsSplit", "(", "self", ")", "-", ">", "bool" ]
def IsSplit(*args, **kwargs): """ IsSplit(self) -> bool Is the window split? """ return _windows_.SplitterWindow_IsSplit(*args, **kwargs)
[ "def", "IsSplit", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "SplitterWindow_IsSplit", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1517-L1523
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
chrome/common/extensions/docs/build/build.py
python
RenderPages
(names, dump_render_tree)
return changed_files
Calls DumpRenderTree .../generator.html?<names> and writes the results to .../docs/<name>.html
Calls DumpRenderTree .../generator.html?<names> and writes the results to .../docs/<name>.html
[ "Calls", "DumpRenderTree", "...", "/", "generator", ".", "html?<names", ">", "and", "writes", "the", "results", "to", "...", "/", "docs", "/", "<name", ">", ".", "html" ]
def RenderPages(names, dump_render_tree): """ Calls DumpRenderTree .../generator.html?<names> and writes the results to .../docs/<name>.html """ if not names: raise Exception("RenderPage called with empty names param") generator_url = "file:" + urllib.pathname2url(_generator_html) generator_url += "?" + ",".join(names) # Start with a fresh copy of page shell for each file. # Save the current contents so that we can look for changes later. originals = {} for name in names: input_file = _base_dir + "/" + name + ".html" if (os.path.isfile(input_file)): originals[name] = open(input_file, 'rb').read() os.remove(input_file) else: originals[name] = "" shutil.copy(_page_shell_html, input_file) # Run DumpRenderTree and capture result dump_render_tree_timeout = 1000 * 60 * 5 # five minutes p = Popen( [dump_render_tree, "--test-shell", "%s %s" % (generator_url, dump_render_tree_timeout)], stdout=PIPE) # The remaining output will be the content of the generated pages. output = p.stdout.read() # Parse out just the JSON part. begin = output.find(_expected_output_preamble) end = output.rfind(_expected_output_postamble) if (begin < 0 or end < 0): raise Exception("%s returned invalid output:\n\n%s" % (dump_render_tree, output)) begin += len(_expected_output_preamble) try: output_parsed = json.loads(output[begin:end]) except ValueError, msg: raise Exception("Could not parse DumpRenderTree output as JSON. Error: " + msg + "\n\nOutput was:\n" + output) changed_files = [] for name in names: result = output_parsed[name].encode("utf8") + '\n' # Remove CRs that are appearing from captured DumpRenderTree output. result = result.replace('\r', '') # Remove empty style attributes. result = result.replace(' style=""', '') # Remove page_shell input_file = _base_dir + "/" + name + ".html" os.remove(input_file) # Write output open(input_file, 'wb').write(result) if (originals[name] and result != originals[name]): changed_files.append(input_file) return changed_files
[ "def", "RenderPages", "(", "names", ",", "dump_render_tree", ")", ":", "if", "not", "names", ":", "raise", "Exception", "(", "\"RenderPage called with empty names param\"", ")", "generator_url", "=", "\"file:\"", "+", "urllib", ".", "pathname2url", "(", "_generator_html", ")", "generator_url", "+=", "\"?\"", "+", "\",\"", ".", "join", "(", "names", ")", "# Start with a fresh copy of page shell for each file.", "# Save the current contents so that we can look for changes later.", "originals", "=", "{", "}", "for", "name", "in", "names", ":", "input_file", "=", "_base_dir", "+", "\"/\"", "+", "name", "+", "\".html\"", "if", "(", "os", ".", "path", ".", "isfile", "(", "input_file", ")", ")", ":", "originals", "[", "name", "]", "=", "open", "(", "input_file", ",", "'rb'", ")", ".", "read", "(", ")", "os", ".", "remove", "(", "input_file", ")", "else", ":", "originals", "[", "name", "]", "=", "\"\"", "shutil", ".", "copy", "(", "_page_shell_html", ",", "input_file", ")", "# Run DumpRenderTree and capture result", "dump_render_tree_timeout", "=", "1000", "*", "60", "*", "5", "# five minutes", "p", "=", "Popen", "(", "[", "dump_render_tree", ",", "\"--test-shell\"", ",", "\"%s %s\"", "%", "(", "generator_url", ",", "dump_render_tree_timeout", ")", "]", ",", "stdout", "=", "PIPE", ")", "# The remaining output will be the content of the generated pages.", "output", "=", "p", ".", "stdout", ".", "read", "(", ")", "# Parse out just the JSON part.", "begin", "=", "output", ".", "find", "(", "_expected_output_preamble", ")", "end", "=", "output", ".", "rfind", "(", "_expected_output_postamble", ")", "if", "(", "begin", "<", "0", "or", "end", "<", "0", ")", ":", "raise", "Exception", "(", "\"%s returned invalid output:\\n\\n%s\"", "%", "(", "dump_render_tree", ",", "output", ")", ")", "begin", "+=", "len", "(", "_expected_output_preamble", ")", "try", ":", "output_parsed", "=", "json", ".", "loads", "(", "output", "[", "begin", ":", "end", "]", ")", "except", "ValueError", ",", "msg", ":", "raise", "Exception", "(", "\"Could not parse DumpRenderTree output as JSON. Error: \"", "+", "msg", "+", "\"\\n\\nOutput was:\\n\"", "+", "output", ")", "changed_files", "=", "[", "]", "for", "name", "in", "names", ":", "result", "=", "output_parsed", "[", "name", "]", ".", "encode", "(", "\"utf8\"", ")", "+", "'\\n'", "# Remove CRs that are appearing from captured DumpRenderTree output.", "result", "=", "result", ".", "replace", "(", "'\\r'", ",", "''", ")", "# Remove empty style attributes.", "result", "=", "result", ".", "replace", "(", "' style=\"\"'", ",", "''", ")", "# Remove page_shell", "input_file", "=", "_base_dir", "+", "\"/\"", "+", "name", "+", "\".html\"", "os", ".", "remove", "(", "input_file", ")", "# Write output", "open", "(", "input_file", ",", "'wb'", ")", ".", "write", "(", "result", ")", "if", "(", "originals", "[", "name", "]", "and", "result", "!=", "originals", "[", "name", "]", ")", ":", "changed_files", ".", "append", "(", "input_file", ")", "return", "changed_files" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/docs/build/build.py#L51-L121
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
python
StreamingDataFeeder.__init__
(self, x, y, n_classes, batch_size)
Initializes a StreamingDataFeeder instance. Args: x: iterator each element of which returns one feature sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices. y: iterator each element of which returns one label sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices with 1 or many classes regression values. n_classes: indicator of how many classes the corresponding label sample has for the purposes of one-hot conversion of label. In case where `y` is a dictionary, `n_classes` must be dictionary (with same keys as `y`) of how many classes there are in each label in `y`. If key is present in `y` and missing in `n_classes`, the value is assumed `None` and no one-hot conversion will be applied to the label with that key. batch_size: Mini batch size to accumulate samples in one batch. If set `None`, then assumes that iterator to return already batched element. Attributes: x: input features (or dictionary of input features). y: input label (or dictionary of output features). n_classes: number of classes. batch_size: mini batch size to accumulate. input_shape: shape of the input (can be dictionary depending on `x`). output_shape: shape of the output (can be dictionary depending on `y`). input_dtype: dtype of input (can be dictionary depending on `x`). output_dtype: dtype of output (can be dictionary depending on `y`).
Initializes a StreamingDataFeeder instance.
[ "Initializes", "a", "StreamingDataFeeder", "instance", "." ]
def __init__(self, x, y, n_classes, batch_size): """Initializes a StreamingDataFeeder instance. Args: x: iterator each element of which returns one feature sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices. y: iterator each element of which returns one label sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices with 1 or many classes regression values. n_classes: indicator of how many classes the corresponding label sample has for the purposes of one-hot conversion of label. In case where `y` is a dictionary, `n_classes` must be dictionary (with same keys as `y`) of how many classes there are in each label in `y`. If key is present in `y` and missing in `n_classes`, the value is assumed `None` and no one-hot conversion will be applied to the label with that key. batch_size: Mini batch size to accumulate samples in one batch. If set `None`, then assumes that iterator to return already batched element. Attributes: x: input features (or dictionary of input features). y: input label (or dictionary of output features). n_classes: number of classes. batch_size: mini batch size to accumulate. input_shape: shape of the input (can be dictionary depending on `x`). output_shape: shape of the output (can be dictionary depending on `y`). input_dtype: dtype of input (can be dictionary depending on `x`). output_dtype: dtype of output (can be dictionary depending on `y`). """ # pylint: disable=invalid-name,super-init-not-called x_first_el = six.next(x) self._x = itertools.chain([x_first_el], x) if y is not None: y_first_el = six.next(y) self._y = itertools.chain([y_first_el], y) else: y_first_el = None self._y = None self.n_classes = n_classes x_is_dict = isinstance(x_first_el, dict) y_is_dict = y is not None and isinstance(y_first_el, dict) if y_is_dict and n_classes is not None: assert isinstance(n_classes, dict) # extract shapes for first_elements if x_is_dict: x_first_el_shape = dict( [(k, [1] + list(v.shape)) for k, v in list(x_first_el.items())]) else: x_first_el_shape = [1] + list(x_first_el.shape) if y_is_dict: y_first_el_shape = dict( [(k, [1] + list(v.shape)) for k, v in list(y_first_el.items())]) elif y is None: y_first_el_shape = None else: y_first_el_shape = ( [1] + list(y_first_el[0].shape if isinstance(y_first_el, list) else y_first_el.shape)) self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape( x_first_el_shape, y_first_el_shape, n_classes, batch_size) # Input dtype of x_first_el. if x_is_dict: self._input_dtype = dict( [(k, _check_dtype(v.dtype)) for k, v in list(x_first_el.items())]) else: self._input_dtype = _check_dtype(x_first_el.dtype) # Output dtype of y_first_el. def check_y_dtype(el): if isinstance(el, np.ndarray): return el.dtype elif isinstance(el, list): return check_y_dtype(el[0]) else: return _check_dtype(np.dtype(type(el))) # Output types are floats, due to both softmaxes and regression req. if n_classes is not None and (y is None or not y_is_dict) and n_classes > 0: self._output_dtype = np.float32 elif y_is_dict: self._output_dtype = dict( [(k, check_y_dtype(v)) for k, v in list(y_first_el.items())]) elif y is None: self._output_dtype = None else: self._output_dtype = check_y_dtype(y_first_el)
[ "def", "__init__", "(", "self", ",", "x", ",", "y", ",", "n_classes", ",", "batch_size", ")", ":", "# pylint: disable=invalid-name,super-init-not-called", "x_first_el", "=", "six", ".", "next", "(", "x", ")", "self", ".", "_x", "=", "itertools", ".", "chain", "(", "[", "x_first_el", "]", ",", "x", ")", "if", "y", "is", "not", "None", ":", "y_first_el", "=", "six", ".", "next", "(", "y", ")", "self", ".", "_y", "=", "itertools", ".", "chain", "(", "[", "y_first_el", "]", ",", "y", ")", "else", ":", "y_first_el", "=", "None", "self", ".", "_y", "=", "None", "self", ".", "n_classes", "=", "n_classes", "x_is_dict", "=", "isinstance", "(", "x_first_el", ",", "dict", ")", "y_is_dict", "=", "y", "is", "not", "None", "and", "isinstance", "(", "y_first_el", ",", "dict", ")", "if", "y_is_dict", "and", "n_classes", "is", "not", "None", ":", "assert", "isinstance", "(", "n_classes", ",", "dict", ")", "# extract shapes for first_elements", "if", "x_is_dict", ":", "x_first_el_shape", "=", "dict", "(", "[", "(", "k", ",", "[", "1", "]", "+", "list", "(", "v", ".", "shape", ")", ")", "for", "k", ",", "v", "in", "list", "(", "x_first_el", ".", "items", "(", ")", ")", "]", ")", "else", ":", "x_first_el_shape", "=", "[", "1", "]", "+", "list", "(", "x_first_el", ".", "shape", ")", "if", "y_is_dict", ":", "y_first_el_shape", "=", "dict", "(", "[", "(", "k", ",", "[", "1", "]", "+", "list", "(", "v", ".", "shape", ")", ")", "for", "k", ",", "v", "in", "list", "(", "y_first_el", ".", "items", "(", ")", ")", "]", ")", "elif", "y", "is", "None", ":", "y_first_el_shape", "=", "None", "else", ":", "y_first_el_shape", "=", "(", "[", "1", "]", "+", "list", "(", "y_first_el", "[", "0", "]", ".", "shape", "if", "isinstance", "(", "y_first_el", ",", "list", ")", "else", "y_first_el", ".", "shape", ")", ")", "self", ".", "input_shape", ",", "self", ".", "output_shape", ",", "self", ".", "_batch_size", "=", "_get_in_out_shape", "(", "x_first_el_shape", ",", "y_first_el_shape", ",", "n_classes", ",", "batch_size", ")", "# Input dtype of x_first_el.", "if", "x_is_dict", ":", "self", ".", "_input_dtype", "=", "dict", "(", "[", "(", "k", ",", "_check_dtype", "(", "v", ".", "dtype", ")", ")", "for", "k", ",", "v", "in", "list", "(", "x_first_el", ".", "items", "(", ")", ")", "]", ")", "else", ":", "self", ".", "_input_dtype", "=", "_check_dtype", "(", "x_first_el", ".", "dtype", ")", "# Output dtype of y_first_el.", "def", "check_y_dtype", "(", "el", ")", ":", "if", "isinstance", "(", "el", ",", "np", ".", "ndarray", ")", ":", "return", "el", ".", "dtype", "elif", "isinstance", "(", "el", ",", "list", ")", ":", "return", "check_y_dtype", "(", "el", "[", "0", "]", ")", "else", ":", "return", "_check_dtype", "(", "np", ".", "dtype", "(", "type", "(", "el", ")", ")", ")", "# Output types are floats, due to both softmaxes and regression req.", "if", "n_classes", "is", "not", "None", "and", "(", "y", "is", "None", "or", "not", "y_is_dict", ")", "and", "n_classes", ">", "0", ":", "self", ".", "_output_dtype", "=", "np", ".", "float32", "elif", "y_is_dict", ":", "self", ".", "_output_dtype", "=", "dict", "(", "[", "(", "k", ",", "check_y_dtype", "(", "v", ")", ")", "for", "k", ",", "v", "in", "list", "(", "y_first_el", ".", "items", "(", ")", ")", "]", ")", "elif", "y", "is", "None", ":", "self", ".", "_output_dtype", "=", "None", "else", ":", "self", ".", "_output_dtype", "=", "check_y_dtype", "(", "y_first_el", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py#L591-L680
xenia-project/xenia
9b1fdac98665ac091b9660a5d0fbb259ed79e578
third_party/google-styleguide/cpplint/cpplint.py
python
PrintCategories
()
Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter.
Prints a list of all the error-categories used by error messages.
[ "Prints", "a", "list", "of", "all", "the", "error", "-", "categories", "used", "by", "error", "messages", "." ]
def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0)
[ "def", "PrintCategories", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "''", ".", "join", "(", "' %s\\n'", "%", "cat", "for", "cat", "in", "_ERROR_CATEGORIES", ")", ")", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L5522-L5528
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyserial/serial/serialposix.py
python
PosixSerial.flush
(self)
Flush of file like objects. In this case, wait until all data is written.
Flush of file like objects. In this case, wait until all data is written.
[ "Flush", "of", "file", "like", "objects", ".", "In", "this", "case", "wait", "until", "all", "data", "is", "written", "." ]
def flush(self): """Flush of file like objects. In this case, wait until all data is written.""" self.drainOutput()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "drainOutput", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/serialposix.py#L521-L524
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
NativeFontInfo.GetEncoding
(*args, **kwargs)
return _gdi_.NativeFontInfo_GetEncoding(*args, **kwargs)
GetEncoding(self) -> int
GetEncoding(self) -> int
[ "GetEncoding", "(", "self", ")", "-", ">", "int" ]
def GetEncoding(*args, **kwargs): """GetEncoding(self) -> int""" return _gdi_.NativeFontInfo_GetEncoding(*args, **kwargs)
[ "def", "GetEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "NativeFontInfo_GetEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L1905-L1907
etternagame/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/win_helper.py
python
WinTool.Dispatch
(self, args)
return getattr(self, method)(*args[1:])
Dispatches a string command to a method.
Dispatches a string command to a method.
[ "Dispatches", "a", "string", "command", "to", "a", "method", "." ]
def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:])
[ "def", "Dispatch", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "raise", "Exception", "(", "\"Not enough arguments\"", ")", "method", "=", "\"Exec%s\"", "%", "self", ".", "_CommandifyName", "(", "args", "[", "0", "]", ")", "return", "getattr", "(", "self", ",", "method", ")", "(", "*", "args", "[", "1", ":", "]", ")" ]
https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/win_helper.py#L119-L125
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/SConf.py
python
SConfBase.AddTest
(self, test_name, test_instance)
Adds test_class to this SConf instance. It can be called with self.test_name(...)
Adds test_class to this SConf instance. It can be called with self.test_name(...)
[ "Adds", "test_class", "to", "this", "SConf", "instance", ".", "It", "can", "be", "called", "with", "self", ".", "test_name", "(", "...", ")" ]
def AddTest(self, test_name, test_instance): """Adds test_class to this SConf instance. It can be called with self.test_name(...)""" setattr(self, test_name, SConfBase.TestWrapper(test_instance, self))
[ "def", "AddTest", "(", "self", ",", "test_name", ",", "test_instance", ")", ":", "setattr", "(", "self", ",", "test_name", ",", "SConfBase", ".", "TestWrapper", "(", "test_instance", ",", "self", ")", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/SConf.py#L711-L714
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py
python
LoadSubversionAutoProperties
()
Returns the content of [auto-props] section of Subversion's config file as a dictionary. Returns: A dictionary whose key-value pair corresponds the [auto-props] section's key-value pair. In following cases, returns empty dictionary: - config file doesn't exist, or - 'enable-auto-props' is not set to 'true-like-value' in [miscellany].
Returns the content of [auto-props] section of Subversion's config file as a dictionary.
[ "Returns", "the", "content", "of", "[", "auto", "-", "props", "]", "section", "of", "Subversion", "s", "config", "file", "as", "a", "dictionary", "." ]
def LoadSubversionAutoProperties(): """Returns the content of [auto-props] section of Subversion's config file as a dictionary. Returns: A dictionary whose key-value pair corresponds the [auto-props] section's key-value pair. In following cases, returns empty dictionary: - config file doesn't exist, or - 'enable-auto-props' is not set to 'true-like-value' in [miscellany]. """ if os.name == 'nt': subversion_config = os.environ.get("APPDATA") + "\\Subversion\\config" else: subversion_config = os.path.expanduser("~/.subversion/config") if not os.path.exists(subversion_config): return {} config = ConfigParser.ConfigParser() config.read(subversion_config) if (config.has_section("miscellany") and config.has_option("miscellany", "enable-auto-props") and config.getboolean("miscellany", "enable-auto-props") and config.has_section("auto-props")): props = {} for file_pattern in config.options("auto-props"): props[file_pattern] = ParseSubversionPropertyValues( config.get("auto-props", file_pattern)) return props else: return {}
[ "def", "LoadSubversionAutoProperties", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "subversion_config", "=", "os", ".", "environ", ".", "get", "(", "\"APPDATA\"", ")", "+", "\"\\\\Subversion\\\\config\"", "else", ":", "subversion_config", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.subversion/config\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "subversion_config", ")", ":", "return", "{", "}", "config", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "subversion_config", ")", "if", "(", "config", ".", "has_section", "(", "\"miscellany\"", ")", "and", "config", ".", "has_option", "(", "\"miscellany\"", ",", "\"enable-auto-props\"", ")", "and", "config", ".", "getboolean", "(", "\"miscellany\"", ",", "\"enable-auto-props\"", ")", "and", "config", ".", "has_section", "(", "\"auto-props\"", ")", ")", ":", "props", "=", "{", "}", "for", "file_pattern", "in", "config", ".", "options", "(", "\"auto-props\"", ")", ":", "props", "[", "file_pattern", "]", "=", "ParseSubversionPropertyValues", "(", "config", ".", "get", "(", "\"auto-props\"", ",", "file_pattern", ")", ")", "return", "props", "else", ":", "return", "{", "}" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L2087-L2116
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/descriptor/descriptor.py
python
Descriptor.compute_input_stats
(self, data_coord: List[np.ndarray], data_box: List[np.ndarray], data_atype: List[np.ndarray], natoms_vec: List[np.ndarray], mesh: List[np.ndarray], input_dict: Dict[str, List[np.ndarray]] )
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics. Parameters ---------- data_coord : list[np.ndarray] The coordinates. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` data_box : list[np.ndarray] The box. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` data_atype : list[np.ndarray] The atom types. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` natoms_vec : list[np.ndarray] The vector for the number of atoms of the system and different types of atoms. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` mesh : list[np.ndarray] The mesh for neighbor searching. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` input_dict : dict[str, list[np.ndarray]] Dictionary for additional input Notes ----- This method must be implemented, as it's called by other classes.
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
[ "Compute", "the", "statisitcs", "(", "avg", "and", "std", ")", "of", "the", "training", "data", ".", "The", "input", "will", "be", "normalized", "by", "the", "statistics", "." ]
def compute_input_stats(self, data_coord: List[np.ndarray], data_box: List[np.ndarray], data_atype: List[np.ndarray], natoms_vec: List[np.ndarray], mesh: List[np.ndarray], input_dict: Dict[str, List[np.ndarray]] ) -> None: """ Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics. Parameters ---------- data_coord : list[np.ndarray] The coordinates. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` data_box : list[np.ndarray] The box. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` data_atype : list[np.ndarray] The atom types. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` natoms_vec : list[np.ndarray] The vector for the number of atoms of the system and different types of atoms. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` mesh : list[np.ndarray] The mesh for neighbor searching. Can be generated by :meth:`deepmd.model.model_stat.make_stat_input` input_dict : dict[str, list[np.ndarray]] Dictionary for additional input Notes ----- This method must be implemented, as it's called by other classes. """
[ "def", "compute_input_stats", "(", "self", ",", "data_coord", ":", "List", "[", "np", ".", "ndarray", "]", ",", "data_box", ":", "List", "[", "np", ".", "ndarray", "]", ",", "data_atype", ":", "List", "[", "np", ".", "ndarray", "]", ",", "natoms_vec", ":", "List", "[", "np", ".", "ndarray", "]", ",", "mesh", ":", "List", "[", "np", ".", "ndarray", "]", ",", "input_dict", ":", "Dict", "[", "str", ",", "List", "[", "np", ".", "ndarray", "]", "]", ")", "->", "None", ":" ]
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/descriptor/descriptor.py#L144-L178
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/retdec-3.2/scripts/type_extractor/type_extractor/header_text_filters.py
python
filter_whitespaces
(text)
return text
Filters redundant whitespaces. Adds spaces around pointers, behind commas.
Filters redundant whitespaces.
[ "Filters", "redundant", "whitespaces", "." ]
def filter_whitespaces(text): """Filters redundant whitespaces. Adds spaces around pointers, behind commas. """ text = re.sub(r'\s*\*\s*', ' * ', text) text = re.sub(r'\*\s+\*', '**', text) text = re.sub(r'\*\s+\*', '**', text) # need for 3+ pointers text = re.sub(r'\s*,\s*', ', ', text) text = re.sub(r'\s+', ' ', text) text = re.sub(r'\s*\)\s*', ')', text) text = re.sub(r'\s*\(\s*', '(', text) text = re.sub(r'\s*\{\s*', '{ ', text) text = re.sub(r'\s*\}\s*', ' }', text) text = re.sub(r'\s*\[\s*', '[', text) text = re.sub(r'\s*\]\s*', ']', text) return text
[ "def", "filter_whitespaces", "(", "text", ")", ":", "text", "=", "re", ".", "sub", "(", "r'\\s*\\*\\s*'", ",", "' * '", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\*\\s+\\*'", ",", "'**'", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\*\\s+\\*'", ",", "'**'", ",", "text", ")", "# need for 3+ pointers", "text", "=", "re", ".", "sub", "(", "r'\\s*,\\s*'", ",", "', '", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\s+'", ",", "' '", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\s*\\)\\s*'", ",", "')'", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\s*\\(\\s*'", ",", "'('", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\s*\\{\\s*'", ",", "'{ '", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\s*\\}\\s*'", ",", "' }'", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\s*\\[\\s*'", ",", "'['", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'\\s*\\]\\s*'", ",", "']'", ",", "text", ")", "return", "text" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/type_extractor/header_text_filters.py#L515-L531
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/lib/hl_api_types.py
python
NodeCollection.__array__
(self, dtype=None)
return numpy.array(self.tolist(), dtype=dtype)
Convert the NodeCollection to a NumPy array.
Convert the NodeCollection to a NumPy array.
[ "Convert", "the", "NodeCollection", "to", "a", "NumPy", "array", "." ]
def __array__(self, dtype=None): """Convert the NodeCollection to a NumPy array.""" return numpy.array(self.tolist(), dtype=dtype)
[ "def", "__array__", "(", "self", ",", "dtype", "=", "None", ")", ":", "return", "numpy", ".", "array", "(", "self", ".", "tolist", "(", ")", ",", "dtype", "=", "dtype", ")" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/lib/hl_api_types.py#L514-L516
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
build/ymake_conf.py
python
Platform.__init__
(self, name, os, arch)
:type name: str :type os: str :type arch: str
:type name: str :type os: str :type arch: str
[ ":", "type", "name", ":", "str", ":", "type", "os", ":", "str", ":", "type", "arch", ":", "str" ]
def __init__(self, name, os, arch): """ :type name: str :type os: str :type arch: str """ self.name = name self.os = self._parse_os(os) self.arch = arch.lower() self.is_i386 = self.arch in ('i386', 'x86') self.is_i686 = self.arch == 'i686' self.is_x86 = self.is_i386 or self.is_i686 self.is_x86_64 = self.arch in ('x86_64', 'amd64') self.is_intel = self.is_x86 or self.is_x86_64 self.is_armv7 = self.arch in ('armv7', 'armv7a', 'armv7a_neon', 'arm', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53') self.is_armv8 = self.arch in ('armv8', 'armv8a', 'arm64', 'aarch64', 'armv8a_cortex_a35', 'armv8a_cortex_a53') self.is_armv8m = self.arch in ('armv8m_cortex_m33',) self.is_arm64 = self.arch in ('arm64',) self.is_arm = self.is_armv7 or self.is_armv8 or self.is_armv8m self.is_armv7_neon = self.arch in ('armv7a_neon', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53') self.is_armv7hf = self.arch in ('armv7ahf_cortex_a35', 'armv7ahf_cortex_a53') self.armv7_float_abi = None if self.is_armv7: if self.is_armv7hf: self.armv7_float_abi = 'hard' else: self.armv7_float_abi = 'softfp' self.is_cortex_a9 = self.arch in ('armv7a_cortex_a9',) self.is_cortex_a35 = self.arch in ('armv7ahf_cortex_a35', 'armv8a_cortex_a35') self.is_cortex_a53 = self.arch in ('armv7ahf_cortex_a53', 'armv8a_cortex_a53') self.is_cortex_m33 = self.arch in ('armv8m_cortex_m33',) self.is_power8le = self.arch == 'ppc64le' self.is_power9le = self.arch == 'power9le' self.is_powerpc = self.is_power8le or self.is_power9le self.is_32_bit = self.is_x86 or self.is_armv7 or self.is_armv8m self.is_64_bit = self.is_x86_64 or self.is_armv8 or self.is_powerpc assert self.is_32_bit or self.is_64_bit assert not (self.is_32_bit and self.is_64_bit) self.is_linux = self.os == 'linux' or 'yocto' in self.os self.is_linux_x86_64 = self.is_linux and self.is_x86_64 self.is_linux_armv8 = self.is_linux and self.is_armv8 self.is_linux_armv7 = self.is_linux and self.is_armv7 self.is_linux_power8le = self.is_linux and self.is_power8le self.is_linux_power9le = self.is_linux and self.is_power9le self.is_linux_powerpc = self.is_linux_power8le or self.is_linux_power9le self.is_macos = self.os == 'macos' self.is_macos_x86_64 = self.is_macos and self.is_x86_64 self.is_macos_arm64 = self.is_macos and self.is_arm64 self.is_iossim = self.os == 'iossim' or (self.os == 'ios' and self.is_intel) self.is_ios = self.os == 'ios' or self.is_iossim self.is_apple = self.is_macos or self.is_ios self.is_windows = self.os == 'windows' self.is_windows_x86_64 = self.is_windows and self.is_x86_64 self.is_android = self.os == 'android' if self.is_android: # This is default Android API level unless `ANDROID_API` is specified # 18 is the smallest level with OpenGL support # 21 is the smallest level for 64-bit platforms default_android_api = 21 if self.is_64_bit else 18 self.android_api = int(preset('ANDROID_API', default_android_api)) self.is_cygwin = self.os == 'cygwin' self.is_yocto = self.os == 'yocto' self.is_none = self.os == 'none' self.is_posix = self.is_linux or self.is_apple or self.is_android or self.is_cygwin or self.is_yocto
[ "def", "__init__", "(", "self", ",", "name", ",", "os", ",", "arch", ")", ":", "self", ".", "name", "=", "name", "self", ".", "os", "=", "self", ".", "_parse_os", "(", "os", ")", "self", ".", "arch", "=", "arch", ".", "lower", "(", ")", "self", ".", "is_i386", "=", "self", ".", "arch", "in", "(", "'i386'", ",", "'x86'", ")", "self", ".", "is_i686", "=", "self", ".", "arch", "==", "'i686'", "self", ".", "is_x86", "=", "self", ".", "is_i386", "or", "self", ".", "is_i686", "self", ".", "is_x86_64", "=", "self", ".", "arch", "in", "(", "'x86_64'", ",", "'amd64'", ")", "self", ".", "is_intel", "=", "self", ".", "is_x86", "or", "self", ".", "is_x86_64", "self", ".", "is_armv7", "=", "self", ".", "arch", "in", "(", "'armv7'", ",", "'armv7a'", ",", "'armv7a_neon'", ",", "'arm'", ",", "'armv7a_cortex_a9'", ",", "'armv7ahf_cortex_a35'", ",", "'armv7ahf_cortex_a53'", ")", "self", ".", "is_armv8", "=", "self", ".", "arch", "in", "(", "'armv8'", ",", "'armv8a'", ",", "'arm64'", ",", "'aarch64'", ",", "'armv8a_cortex_a35'", ",", "'armv8a_cortex_a53'", ")", "self", ".", "is_armv8m", "=", "self", ".", "arch", "in", "(", "'armv8m_cortex_m33'", ",", ")", "self", ".", "is_arm64", "=", "self", ".", "arch", "in", "(", "'arm64'", ",", ")", "self", ".", "is_arm", "=", "self", ".", "is_armv7", "or", "self", ".", "is_armv8", "or", "self", ".", "is_armv8m", "self", ".", "is_armv7_neon", "=", "self", ".", "arch", "in", "(", "'armv7a_neon'", ",", "'armv7a_cortex_a9'", ",", "'armv7ahf_cortex_a35'", ",", "'armv7ahf_cortex_a53'", ")", "self", ".", "is_armv7hf", "=", "self", ".", "arch", "in", "(", "'armv7ahf_cortex_a35'", ",", "'armv7ahf_cortex_a53'", ")", "self", ".", "armv7_float_abi", "=", "None", "if", "self", ".", "is_armv7", ":", "if", "self", ".", "is_armv7hf", ":", "self", ".", "armv7_float_abi", "=", "'hard'", "else", ":", "self", ".", "armv7_float_abi", "=", "'softfp'", "self", ".", "is_cortex_a9", "=", "self", ".", "arch", "in", "(", "'armv7a_cortex_a9'", ",", ")", "self", ".", "is_cortex_a35", "=", "self", ".", "arch", "in", "(", "'armv7ahf_cortex_a35'", ",", "'armv8a_cortex_a35'", ")", "self", ".", "is_cortex_a53", "=", "self", ".", "arch", "in", "(", "'armv7ahf_cortex_a53'", ",", "'armv8a_cortex_a53'", ")", "self", ".", "is_cortex_m33", "=", "self", ".", "arch", "in", "(", "'armv8m_cortex_m33'", ",", ")", "self", ".", "is_power8le", "=", "self", ".", "arch", "==", "'ppc64le'", "self", ".", "is_power9le", "=", "self", ".", "arch", "==", "'power9le'", "self", ".", "is_powerpc", "=", "self", ".", "is_power8le", "or", "self", ".", "is_power9le", "self", ".", "is_32_bit", "=", "self", ".", "is_x86", "or", "self", ".", "is_armv7", "or", "self", ".", "is_armv8m", "self", ".", "is_64_bit", "=", "self", ".", "is_x86_64", "or", "self", ".", "is_armv8", "or", "self", ".", "is_powerpc", "assert", "self", ".", "is_32_bit", "or", "self", ".", "is_64_bit", "assert", "not", "(", "self", ".", "is_32_bit", "and", "self", ".", "is_64_bit", ")", "self", ".", "is_linux", "=", "self", ".", "os", "==", "'linux'", "or", "'yocto'", "in", "self", ".", "os", "self", ".", "is_linux_x86_64", "=", "self", ".", "is_linux", "and", "self", ".", "is_x86_64", "self", ".", "is_linux_armv8", "=", "self", ".", "is_linux", "and", "self", ".", "is_armv8", "self", ".", "is_linux_armv7", "=", "self", ".", "is_linux", "and", "self", ".", "is_armv7", "self", ".", "is_linux_power8le", "=", "self", ".", "is_linux", "and", "self", ".", "is_power8le", "self", ".", "is_linux_power9le", "=", "self", ".", "is_linux", "and", "self", ".", "is_power9le", "self", ".", "is_linux_powerpc", "=", "self", ".", "is_linux_power8le", "or", "self", ".", "is_linux_power9le", "self", ".", "is_macos", "=", "self", ".", "os", "==", "'macos'", "self", ".", "is_macos_x86_64", "=", "self", ".", "is_macos", "and", "self", ".", "is_x86_64", "self", ".", "is_macos_arm64", "=", "self", ".", "is_macos", "and", "self", ".", "is_arm64", "self", ".", "is_iossim", "=", "self", ".", "os", "==", "'iossim'", "or", "(", "self", ".", "os", "==", "'ios'", "and", "self", ".", "is_intel", ")", "self", ".", "is_ios", "=", "self", ".", "os", "==", "'ios'", "or", "self", ".", "is_iossim", "self", ".", "is_apple", "=", "self", ".", "is_macos", "or", "self", ".", "is_ios", "self", ".", "is_windows", "=", "self", ".", "os", "==", "'windows'", "self", ".", "is_windows_x86_64", "=", "self", ".", "is_windows", "and", "self", ".", "is_x86_64", "self", ".", "is_android", "=", "self", ".", "os", "==", "'android'", "if", "self", ".", "is_android", ":", "# This is default Android API level unless `ANDROID_API` is specified", "# 18 is the smallest level with OpenGL support", "# 21 is the smallest level for 64-bit platforms", "default_android_api", "=", "21", "if", "self", ".", "is_64_bit", "else", "18", "self", ".", "android_api", "=", "int", "(", "preset", "(", "'ANDROID_API'", ",", "default_android_api", ")", ")", "self", ".", "is_cygwin", "=", "self", ".", "os", "==", "'cygwin'", "self", ".", "is_yocto", "=", "self", ".", "os", "==", "'yocto'", "self", ".", "is_none", "=", "self", ".", "os", "==", "'none'", "self", ".", "is_posix", "=", "self", ".", "is_linux", "or", "self", ".", "is_apple", "or", "self", ".", "is_android", "or", "self", ".", "is_cygwin", "or", "self", ".", "is_yocto" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/build/ymake_conf.py#L41-L118
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/generator/android.py
python
WriteAutoRegenerationRule
(params, root_makefile, makefile_name, build_files)
Write the target to regenerate the Makefile.
Write the target to regenerate the Makefile.
[ "Write", "the", "target", "to", "regenerate", "the", "Makefile", "." ]
def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files): """Write the target to regenerate the Makefile.""" options = params['options'] # Sort to avoid non-functional changes to makefile. build_files = sorted([os.path.join('$(LOCAL_PATH)', f) for f in build_files]) build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir) for filename in params['build_files_arg']] build_files_args = [os.path.join('$(PRIVATE_LOCAL_PATH)', f) for f in build_files_args] gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'], options.toplevel_dir) makefile_path = os.path.join('$(LOCAL_PATH)', makefile_name) if not gyp_binary.startswith(os.sep): gyp_binary = os.path.join('.', gyp_binary) root_makefile.write('GYP_FILES := \\\n %s\n\n' % '\\\n '.join(map(Sourceify, build_files))) root_makefile.write('%s: PRIVATE_LOCAL_PATH := $(LOCAL_PATH)\n' % makefile_path) root_makefile.write('%s: $(GYP_FILES)\n' % makefile_path) root_makefile.write('\techo ACTION Regenerating $@\n\t%s\n\n' % gyp.common.EncodePOSIXShellList([gyp_binary, '-fandroid'] + gyp.RegenerateFlags(options) + build_files_args))
[ "def", "WriteAutoRegenerationRule", "(", "params", ",", "root_makefile", ",", "makefile_name", ",", "build_files", ")", ":", "options", "=", "params", "[", "'options'", "]", "# Sort to avoid non-functional changes to makefile.", "build_files", "=", "sorted", "(", "[", "os", ".", "path", ".", "join", "(", "'$(LOCAL_PATH)'", ",", "f", ")", "for", "f", "in", "build_files", "]", ")", "build_files_args", "=", "[", "gyp", ".", "common", ".", "RelativePath", "(", "filename", ",", "options", ".", "toplevel_dir", ")", "for", "filename", "in", "params", "[", "'build_files_arg'", "]", "]", "build_files_args", "=", "[", "os", ".", "path", ".", "join", "(", "'$(PRIVATE_LOCAL_PATH)'", ",", "f", ")", "for", "f", "in", "build_files_args", "]", "gyp_binary", "=", "gyp", ".", "common", ".", "FixIfRelativePath", "(", "params", "[", "'gyp_binary'", "]", ",", "options", ".", "toplevel_dir", ")", "makefile_path", "=", "os", ".", "path", ".", "join", "(", "'$(LOCAL_PATH)'", ",", "makefile_name", ")", "if", "not", "gyp_binary", ".", "startswith", "(", "os", ".", "sep", ")", ":", "gyp_binary", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "gyp_binary", ")", "root_makefile", ".", "write", "(", "'GYP_FILES := \\\\\\n %s\\n\\n'", "%", "'\\\\\\n '", ".", "join", "(", "map", "(", "Sourceify", ",", "build_files", ")", ")", ")", "root_makefile", ".", "write", "(", "'%s: PRIVATE_LOCAL_PATH := $(LOCAL_PATH)\\n'", "%", "makefile_path", ")", "root_makefile", ".", "write", "(", "'%s: $(GYP_FILES)\\n'", "%", "makefile_path", ")", "root_makefile", ".", "write", "(", "'\\techo ACTION Regenerating $@\\n\\t%s\\n\\n'", "%", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "[", "gyp_binary", ",", "'-fandroid'", "]", "+", "gyp", ".", "RegenerateFlags", "(", "options", ")", "+", "build_files_args", ")", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/generator/android.py#L928-L951
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/archive_util.py
python
default_filter
(src, dst)
return dst
The default progress/filter callback; returns True for all files
The default progress/filter callback; returns True for all files
[ "The", "default", "progress", "/", "filter", "callback", ";", "returns", "True", "for", "all", "files" ]
def default_filter(src, dst): """The default progress/filter callback; returns True for all files""" return dst
[ "def", "default_filter", "(", "src", ",", "dst", ")", ":", "return", "dst" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/archive_util.py#L23-L25
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/data/python/ops/dataset_ops.py
python
Iterator.__init__
(self, iterator_resource, initializer, output_types, output_shapes)
Creates a new iterator from the given iterator resource. NOTE(mrry): Most users will not call this initializer directly, and will instead use `Iterator.from_dataset()` or `Dataset.make_one_shot_iterator()`. Args: iterator_resource: A `tf.resource` scalar `tf.Tensor` representing the iterator. initializer: A `tf.Operation` that should be run to initialize this iterator. output_types: A nested structure of `tf.DType` objects corresponding to each component of an element of this iterator. output_shapes: A nested structure of `tf.TensorShape` objects corresponding to each component of an element of this dataset.
Creates a new iterator from the given iterator resource.
[ "Creates", "a", "new", "iterator", "from", "the", "given", "iterator", "resource", "." ]
def __init__(self, iterator_resource, initializer, output_types, output_shapes): """Creates a new iterator from the given iterator resource. NOTE(mrry): Most users will not call this initializer directly, and will instead use `Iterator.from_dataset()` or `Dataset.make_one_shot_iterator()`. Args: iterator_resource: A `tf.resource` scalar `tf.Tensor` representing the iterator. initializer: A `tf.Operation` that should be run to initialize this iterator. output_types: A nested structure of `tf.DType` objects corresponding to each component of an element of this iterator. output_shapes: A nested structure of `tf.TensorShape` objects corresponding to each component of an element of this dataset. """ self._iterator_resource = iterator_resource self._initializer = initializer self._output_types = output_types self._output_shapes = output_shapes
[ "def", "__init__", "(", "self", ",", "iterator_resource", ",", "initializer", ",", "output_types", ",", "output_shapes", ")", ":", "self", ".", "_iterator_resource", "=", "iterator_resource", "self", ".", "_initializer", "=", "initializer", "self", ".", "_output_types", "=", "output_types", "self", ".", "_output_shapes", "=", "output_shapes" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/data/python/ops/dataset_ops.py#L48-L68
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/range.py
python
RangeIndex.stop
(self)
return self._range.stop
The value of the `stop` parameter.
The value of the `stop` parameter.
[ "The", "value", "of", "the", "stop", "parameter", "." ]
def stop(self) -> int: """ The value of the `stop` parameter. """ return self._range.stop
[ "def", "stop", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_range", ".", "stop" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/range.py#L265-L269
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py
python
IS_CHARACTER_JUNK
(ch, ws=" \t")
return ch in ws
r""" Return True 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 True for ignorable character: iff `ch` is a space or tab.
[ "r", "Return", "True", "for", "ignorable", "character", ":", "iff", "ch", "is", "a", "space", "or", "tab", "." ]
def IS_CHARACTER_JUNK(ch, ws=" \t"): r""" Return True 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/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py#L1102-L1118
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatnotebook.py
python
FlatNotebook.HasAGWFlag
(self, flag)
return res
Returns whether a flag is present in the :class:`FlatNotebook` style. :param `flag`: one of the possible :class:`FlatNotebook` window styles. :see: :meth:`~FlatNotebook.SetAGWWindowStyleFlag` for a list of possible window style flags.
Returns whether a flag is present in the :class:`FlatNotebook` style.
[ "Returns", "whether", "a", "flag", "is", "present", "in", "the", ":", "class", ":", "FlatNotebook", "style", "." ]
def HasAGWFlag(self, flag): """ Returns whether a flag is present in the :class:`FlatNotebook` style. :param `flag`: one of the possible :class:`FlatNotebook` window styles. :see: :meth:`~FlatNotebook.SetAGWWindowStyleFlag` for a list of possible window style flags. """ agwStyle = self.GetAGWWindowStyleFlag() res = (agwStyle & flag and [True] or [False])[0] return res
[ "def", "HasAGWFlag", "(", "self", ",", "flag", ")", ":", "agwStyle", "=", "self", ".", "GetAGWWindowStyleFlag", "(", ")", "res", "=", "(", "agwStyle", "&", "flag", "and", "[", "True", "]", "or", "[", "False", "]", ")", "[", "0", "]", "return", "res" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L4777-L4788
RLBot/RLBot
34332b12cf158b3ef8dbf174ae67c53683368a9d
src/main/python/rlbot/utils/structures/game_interface.py
python
GameInterface.update_rigid_body_tick
(self, rigid_body_tick: RigidBodyTick)
return rigid_body_tick
Get the most recent state of the physics engine.
Get the most recent state of the physics engine.
[ "Get", "the", "most", "recent", "state", "of", "the", "physics", "engine", "." ]
def update_rigid_body_tick(self, rigid_body_tick: RigidBodyTick): """Get the most recent state of the physics engine.""" rlbot_status = self.game.UpdateRigidBodyTick(rigid_body_tick) self.game_status(None, rlbot_status) return rigid_body_tick
[ "def", "update_rigid_body_tick", "(", "self", ",", "rigid_body_tick", ":", "RigidBodyTick", ")", ":", "rlbot_status", "=", "self", ".", "game", ".", "UpdateRigidBodyTick", "(", "rigid_body_tick", ")", "self", ".", "game_status", "(", "None", ",", "rlbot_status", ")", "return", "rigid_body_tick" ]
https://github.com/RLBot/RLBot/blob/34332b12cf158b3ef8dbf174ae67c53683368a9d/src/main/python/rlbot/utils/structures/game_interface.py#L352-L356
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/cli/analyzer_cli.py
python
DebugAnalyzer.add_tensor_filter
(self, filter_name, filter_callable)
Add a tensor filter. A tensor filter is a named callable of the signature: filter_callable(dump_datum, tensor), wherein dump_datum is an instance of debug_data.DebugTensorDatum carrying metadata about the dumped tensor, including tensor name, timestamps, etc. tensor is the value of the dumped tensor as an numpy.ndarray object. The return value of the function is a bool. This is the same signature as the input argument to debug_data.DebugDumpDir.find(). Args: filter_name: (str) name of the filter. Cannot be empty. filter_callable: (callable) a filter function of the signature described as above. Raises: ValueError: If filter_name is an empty str. TypeError: If filter_name is not a str. Or if filter_callable is not callable.
Add a tensor filter.
[ "Add", "a", "tensor", "filter", "." ]
def add_tensor_filter(self, filter_name, filter_callable): """Add a tensor filter. A tensor filter is a named callable of the signature: filter_callable(dump_datum, tensor), wherein dump_datum is an instance of debug_data.DebugTensorDatum carrying metadata about the dumped tensor, including tensor name, timestamps, etc. tensor is the value of the dumped tensor as an numpy.ndarray object. The return value of the function is a bool. This is the same signature as the input argument to debug_data.DebugDumpDir.find(). Args: filter_name: (str) name of the filter. Cannot be empty. filter_callable: (callable) a filter function of the signature described as above. Raises: ValueError: If filter_name is an empty str. TypeError: If filter_name is not a str. Or if filter_callable is not callable. """ if not isinstance(filter_name, str): raise TypeError("Input argument filter_name is expected to be str, " "but is not.") # Check that filter_name is not an empty str. if not filter_name: raise ValueError("Input argument filter_name cannot be empty.") # Check that filter_callable is callable. if not callable(filter_callable): raise TypeError( "Input argument filter_callable is expected to be callable, " "but is not.") self._tensor_filters[filter_name] = filter_callable
[ "def", "add_tensor_filter", "(", "self", ",", "filter_name", ",", "filter_callable", ")", ":", "if", "not", "isinstance", "(", "filter_name", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Input argument filter_name is expected to be str, \"", "\"but is not.\"", ")", "# Check that filter_name is not an empty str.", "if", "not", "filter_name", ":", "raise", "ValueError", "(", "\"Input argument filter_name cannot be empty.\"", ")", "# Check that filter_callable is callable.", "if", "not", "callable", "(", "filter_callable", ")", ":", "raise", "TypeError", "(", "\"Input argument filter_callable is expected to be callable, \"", "\"but is not.\"", ")", "self", ".", "_tensor_filters", "[", "filter_name", "]", "=", "filter_callable" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/analyzer_cli.py#L407-L445
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.DisableDragColSize
(*args, **kwargs)
return _grid.Grid_DisableDragColSize(*args, **kwargs)
DisableDragColSize(self)
DisableDragColSize(self)
[ "DisableDragColSize", "(", "self", ")" ]
def DisableDragColSize(*args, **kwargs): """DisableDragColSize(self)""" return _grid.Grid_DisableDragColSize(*args, **kwargs)
[ "def", "DisableDragColSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_DisableDragColSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1610-L1612
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
Grid.GetLabelFont
(*args, **kwargs)
return _grid.Grid_GetLabelFont(*args, **kwargs)
GetLabelFont(self) -> Font
GetLabelFont(self) -> Font
[ "GetLabelFont", "(", "self", ")", "-", ">", "Font" ]
def GetLabelFont(*args, **kwargs): """GetLabelFont(self) -> Font""" return _grid.Grid_GetLabelFont(*args, **kwargs)
[ "def", "GetLabelFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetLabelFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1494-L1496
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
Optimize.help
(self)
Display a string describing all available options.
Display a string describing all available options.
[ "Display", "a", "string", "describing", "all", "available", "options", "." ]
def help(self): """Display a string describing all available options.""" print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
[ "def", "help", "(", "self", ")", ":", "print", "(", "Z3_optimize_get_help", "(", "self", ".", "ctx", ".", "ref", "(", ")", ",", "self", ".", "optimize", ")", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L7805-L7807
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/validators.py
python
check_filter
(method)
return new_method
check the input arguments of filter.
check the input arguments of filter.
[ "check", "the", "input", "arguments", "of", "filter", "." ]
def check_filter(method): """"check the input arguments of filter.""" @wraps(method) def new_method(self, *args, **kwargs): [predicate, input_columns, num_parallel_workers], _ = parse_user_args(method, *args, **kwargs) if not callable(predicate): raise TypeError("Predicate should be a Python function or a callable Python object.") if num_parallel_workers is not None: check_num_parallel_workers(num_parallel_workers) if input_columns is not None: check_columns(input_columns, "input_columns") return method(self, *args, **kwargs) return new_method
[ "def", "check_filter", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "[", "predicate", ",", "input_columns", ",", "num_parallel_workers", "]", ",", "_", "=", "parse_user_args", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "callable", "(", "predicate", ")", ":", "raise", "TypeError", "(", "\"Predicate should be a Python function or a callable Python object.\"", ")", "if", "num_parallel_workers", "is", "not", "None", ":", "check_num_parallel_workers", "(", "num_parallel_workers", ")", "if", "input_columns", "is", "not", "None", ":", "check_columns", "(", "input_columns", ",", "\"input_columns\"", ")", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_method" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L1126-L1143
smartdevicelink/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
src/3rd_party-static/gmock-1.7.0/scripts/generator/cpp/ast.py
python
PrintIndentifiers
(filename, should_print)
Prints all identifiers for a C++ source file. Args: filename: 'file1' should_print: predicate with signature: bool Function(token)
Prints all identifiers for a C++ source file.
[ "Prints", "all", "identifiers", "for", "a", "C", "++", "source", "file", "." ]
def PrintIndentifiers(filename, should_print): """Prints all identifiers for a C++ source file. Args: filename: 'file1' should_print: predicate with signature: bool Function(token) """ source = utils.ReadFile(filename, False) if source is None: sys.stderr.write('Unable to find: %s\n' % filename) return #print('Processing %s' % actual_filename) builder = BuilderFromSource(source, filename) try: for node in builder.Generate(): if should_print(node): print(node.name) except KeyboardInterrupt: return except: pass
[ "def", "PrintIndentifiers", "(", "filename", ",", "should_print", ")", ":", "source", "=", "utils", ".", "ReadFile", "(", "filename", ",", "False", ")", "if", "source", "is", "None", ":", "sys", ".", "stderr", ".", "write", "(", "'Unable to find: %s\\n'", "%", "filename", ")", "return", "#print('Processing %s' % actual_filename)", "builder", "=", "BuilderFromSource", "(", "source", ",", "filename", ")", "try", ":", "for", "node", "in", "builder", ".", "Generate", "(", ")", ":", "if", "should_print", "(", "node", ")", ":", "print", "(", "node", ".", "name", ")", "except", "KeyboardInterrupt", ":", "return", "except", ":", "pass" ]
https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/src/3rd_party-static/gmock-1.7.0/scripts/generator/cpp/ast.py#L1666-L1687
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Layer.RollbackTransaction
(self, *args)
return _ogr.Layer_RollbackTransaction(self, *args)
r""" RollbackTransaction(Layer self) -> OGRErr OGRErr OGR_L_RollbackTransaction(OGRLayerH hLayer) For datasources which support transactions, RollbackTransaction will roll back a datasource to its state before the start of the current transaction. If no transaction is active, or the rollback fails, will return OGRERR_FAILURE. Datasources which do not support transactions will always return OGRERR_NONE. This function is the same as the C++ method OGRLayer::RollbackTransaction(). Parameters: ----------- hLayer: handle to the layer OGRERR_NONE on success.
r""" RollbackTransaction(Layer self) -> OGRErr OGRErr OGR_L_RollbackTransaction(OGRLayerH hLayer)
[ "r", "RollbackTransaction", "(", "Layer", "self", ")", "-", ">", "OGRErr", "OGRErr", "OGR_L_RollbackTransaction", "(", "OGRLayerH", "hLayer", ")" ]
def RollbackTransaction(self, *args): r""" RollbackTransaction(Layer self) -> OGRErr OGRErr OGR_L_RollbackTransaction(OGRLayerH hLayer) For datasources which support transactions, RollbackTransaction will roll back a datasource to its state before the start of the current transaction. If no transaction is active, or the rollback fails, will return OGRERR_FAILURE. Datasources which do not support transactions will always return OGRERR_NONE. This function is the same as the C++ method OGRLayer::RollbackTransaction(). Parameters: ----------- hLayer: handle to the layer OGRERR_NONE on success. """ return _ogr.Layer_RollbackTransaction(self, *args)
[ "def", "RollbackTransaction", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "Layer_RollbackTransaction", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L2072-L2096
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py
python
_FieldSkipper
()
return SkipField
Constructs the SkipField function.
Constructs the SkipField function.
[ "Constructs", "the", "SkipField", "function", "." ]
def _FieldSkipper(): """Constructs the SkipField function.""" WIRETYPE_TO_SKIPPER = [ _SkipVarint, _SkipFixed64, _SkipLengthDelimited, _SkipGroup, _EndGroup, _SkipFixed32, _RaiseInvalidWireType, _RaiseInvalidWireType, ] wiretype_mask = wire_format.TAG_TYPE_MASK local_ord = ord def SkipField(buffer, pos, end, tag_bytes): """Skips a field with the specified tag. |pos| should point to the byte immediately after the tag. Returns: The new position (after the tag value), or -1 if the tag is an end-group tag (in which case the calling loop should break). """ # The wire type is always in the first byte since varints are little-endian. wire_type = local_ord(tag_bytes[0]) & wiretype_mask return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end) return SkipField
[ "def", "_FieldSkipper", "(", ")", ":", "WIRETYPE_TO_SKIPPER", "=", "[", "_SkipVarint", ",", "_SkipFixed64", ",", "_SkipLengthDelimited", ",", "_SkipGroup", ",", "_EndGroup", ",", "_SkipFixed32", ",", "_RaiseInvalidWireType", ",", "_RaiseInvalidWireType", ",", "]", "wiretype_mask", "=", "wire_format", ".", "TAG_TYPE_MASK", "local_ord", "=", "ord", "def", "SkipField", "(", "buffer", ",", "pos", ",", "end", ",", "tag_bytes", ")", ":", "\"\"\"Skips a field with the specified tag.\n\n |pos| should point to the byte immediately after the tag.\n\n Returns:\n The new position (after the tag value), or -1 if the tag is an end-group\n tag (in which case the calling loop should break).\n \"\"\"", "# The wire type is always in the first byte since varints are little-endian.", "wire_type", "=", "local_ord", "(", "tag_bytes", "[", "0", "]", ")", "&", "wiretype_mask", "return", "WIRETYPE_TO_SKIPPER", "[", "wire_type", "]", "(", "buffer", ",", "pos", ",", "end", ")", "return", "SkipField" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py#L608-L639
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/xrc.py
python
XmlProperty.SetName
(*args, **kwargs)
return _xrc.XmlProperty_SetName(*args, **kwargs)
SetName(self, String name)
SetName(self, String name)
[ "SetName", "(", "self", "String", "name", ")" ]
def SetName(*args, **kwargs): """SetName(self, String name)""" return _xrc.XmlProperty_SetName(*args, **kwargs)
[ "def", "SetName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlProperty_SetName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L328-L330
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/devicearray.py
python
is_hsa_ndarray
(obj)
return getattr(obj, '__hsa_ndarray__', False)
Check if an object is a HSA ndarray
Check if an object is a HSA ndarray
[ "Check", "if", "an", "object", "is", "a", "HSA", "ndarray" ]
def is_hsa_ndarray(obj): "Check if an object is a HSA ndarray" return getattr(obj, '__hsa_ndarray__', False)
[ "def", "is_hsa_ndarray", "(", "obj", ")", ":", "return", "getattr", "(", "obj", ",", "'__hsa_ndarray__'", ",", "False", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/devicearray.py#L24-L26
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/parso/py2/parso/python/tree.py
python
ClassOrFunc.get_decorators
(self)
:rtype: list of :class:`Decorator`
:rtype: list of :class:`Decorator`
[ ":", "rtype", ":", "list", "of", ":", "class", ":", "Decorator" ]
def get_decorators(self): """ :rtype: list of :class:`Decorator` """ decorated = self.parent if decorated.type == 'async_funcdef': decorated = decorated.parent if decorated.type == 'decorated': if decorated.children[0].type == 'decorators': return decorated.children[0].children else: return decorated.children[:1] else: return []
[ "def", "get_decorators", "(", "self", ")", ":", "decorated", "=", "self", ".", "parent", "if", "decorated", ".", "type", "==", "'async_funcdef'", ":", "decorated", "=", "decorated", ".", "parent", "if", "decorated", ".", "type", "==", "'decorated'", ":", "if", "decorated", ".", "children", "[", "0", "]", ".", "type", "==", "'decorators'", ":", "return", "decorated", ".", "children", "[", "0", "]", ".", "children", "else", ":", "return", "decorated", ".", "children", "[", ":", "1", "]", "else", ":", "return", "[", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/parso/py2/parso/python/tree.py#L471-L485
HKUST-Aerial-Robotics/Teach-Repeat-Replan
98505a7f74b13c8b501176ff838a38423dbef536
utils/quadrotor_msgs/src/quadrotor_msgs/msg/_PPROutputData.py
python
PPROutputData.serialize
(self, buff)
serialize message into buffer :param buff: buffer, ``StringIO``
serialize message into buffer :param buff: buffer, ``StringIO``
[ "serialize", "message", "into", "buffer", ":", "param", "buff", ":", "buffer", "StringIO" ]
def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) if python3: buff.write(struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_struct_H13d.pack(_x.quad_time, _x.des_thrust, _x.des_roll, _x.des_pitch, _x.des_yaw, _x.est_roll, _x.est_pitch, _x.est_yaw, _x.est_angvel_x, _x.est_angvel_y, _x.est_angvel_z, _x.est_acc_x, _x.est_acc_y, _x.est_acc_z)) buff.write(_struct_4H.pack(*self.pwm)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x)))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
[ "def", "serialize", "(", "self", ",", "buff", ")", ":", "try", ":", "_x", "=", "self", "buff", ".", "write", "(", "_struct_3I", ".", "pack", "(", "_x", ".", "header", ".", "seq", ",", "_x", ".", "header", ".", "stamp", ".", "secs", ",", "_x", ".", "header", ".", "stamp", ".", "nsecs", ")", ")", "_x", "=", "self", ".", "header", ".", "frame_id", "length", "=", "len", "(", "_x", ")", "if", "python3", "or", "type", "(", "_x", ")", "==", "unicode", ":", "_x", "=", "_x", ".", "encode", "(", "'utf-8'", ")", "length", "=", "len", "(", "_x", ")", "if", "python3", ":", "buff", ".", "write", "(", "struct", ".", "pack", "(", "'<I%sB'", "%", "length", ",", "length", ",", "*", "_x", ")", ")", "else", ":", "buff", ".", "write", "(", "struct", ".", "pack", "(", "'<I%ss'", "%", "length", ",", "length", ",", "_x", ")", ")", "_x", "=", "self", "buff", ".", "write", "(", "_struct_H13d", ".", "pack", "(", "_x", ".", "quad_time", ",", "_x", ".", "des_thrust", ",", "_x", ".", "des_roll", ",", "_x", ".", "des_pitch", ",", "_x", ".", "des_yaw", ",", "_x", ".", "est_roll", ",", "_x", ".", "est_pitch", ",", "_x", ".", "est_yaw", ",", "_x", ".", "est_angvel_x", ",", "_x", ".", "est_angvel_y", ",", "_x", ".", "est_angvel_z", ",", "_x", ".", "est_acc_x", ",", "_x", ".", "est_acc_y", ",", "_x", ".", "est_acc_z", ")", ")", "buff", ".", "write", "(", "_struct_4H", ".", "pack", "(", "*", "self", ".", "pwm", ")", ")", "except", "struct", ".", "error", "as", "se", ":", "self", ".", "_check_types", "(", "struct", ".", "error", "(", "\"%s: '%s' when writing '%s'\"", "%", "(", "type", "(", "se", ")", ",", "str", "(", "se", ")", ",", "str", "(", "_x", ")", ")", ")", ")", "except", "TypeError", "as", "te", ":", "self", ".", "_check_types", "(", "ValueError", "(", "\"%s: '%s' when writing '%s'\"", "%", "(", "type", "(", "te", ")", ",", "str", "(", "te", ")", ",", "str", "(", "_x", ")", ")", ")", ")" ]
https://github.com/HKUST-Aerial-Robotics/Teach-Repeat-Replan/blob/98505a7f74b13c8b501176ff838a38423dbef536/utils/quadrotor_msgs/src/quadrotor_msgs/msg/_PPROutputData.py#L125-L146
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/solver/solver.py
python
parseMarkersDictKey
(key, markers)
return [m for m in mas if m in markers]
Parse dictionary key of type str to marker list. Utility function to parse a dictionary key string into a valid list of markers containing in a given markers list. Parameters ---------- key: str | int Supported are - int: single markers - '*': all markers - 'm1': Single marker - 'm1,m2': Comma separated list - ':': Slice wildcard - 'start:stop:step': Slice like syntax markers: [int] List of integers, e.g., cell or boundary markers Returns ------- mas: [int] List of integers described by key
Parse dictionary key of type str to marker list.
[ "Parse", "dictionary", "key", "of", "type", "str", "to", "marker", "list", "." ]
def parseMarkersDictKey(key, markers): """ Parse dictionary key of type str to marker list. Utility function to parse a dictionary key string into a valid list of markers containing in a given markers list. Parameters ---------- key: str | int Supported are - int: single markers - '*': all markers - 'm1': Single marker - 'm1,m2': Comma separated list - ':': Slice wildcard - 'start:stop:step': Slice like syntax markers: [int] List of integers, e.g., cell or boundary markers Returns ------- mas: [int] List of integers described by key """ markers = pg.unique(markers) mas = None if isinstance(key, str): if key == '*': return markers if ',' in key: mas = [int(k) for k in key.split(',')] elif ':' in key: sse = key.split(':') start = markers[0] stop = markers[-1] + 1 step = 1 if len(sse) > 0: try: start = int(sse[0]) except BaseException as _: pass if len(sse) > 1: try: stop = int(sse[1]) except BaseException as _: pass if len(sse) > 2: try: step = int(sse[2]) except BaseException as _: pass mas = list(range(start, stop, step)) else: mas = [int(key)] else: mas = [int(key)] return [m for m in mas if m in markers]
[ "def", "parseMarkersDictKey", "(", "key", ",", "markers", ")", ":", "markers", "=", "pg", ".", "unique", "(", "markers", ")", "mas", "=", "None", "if", "isinstance", "(", "key", ",", "str", ")", ":", "if", "key", "==", "'*'", ":", "return", "markers", "if", "','", "in", "key", ":", "mas", "=", "[", "int", "(", "k", ")", "for", "k", "in", "key", ".", "split", "(", "','", ")", "]", "elif", "':'", "in", "key", ":", "sse", "=", "key", ".", "split", "(", "':'", ")", "start", "=", "markers", "[", "0", "]", "stop", "=", "markers", "[", "-", "1", "]", "+", "1", "step", "=", "1", "if", "len", "(", "sse", ")", ">", "0", ":", "try", ":", "start", "=", "int", "(", "sse", "[", "0", "]", ")", "except", "BaseException", "as", "_", ":", "pass", "if", "len", "(", "sse", ")", ">", "1", ":", "try", ":", "stop", "=", "int", "(", "sse", "[", "1", "]", ")", "except", "BaseException", "as", "_", ":", "pass", "if", "len", "(", "sse", ")", ">", "2", ":", "try", ":", "step", "=", "int", "(", "sse", "[", "2", "]", ")", "except", "BaseException", "as", "_", ":", "pass", "mas", "=", "list", "(", "range", "(", "start", ",", "stop", ",", "step", ")", ")", "else", ":", "mas", "=", "[", "int", "(", "key", ")", "]", "else", ":", "mas", "=", "[", "int", "(", "key", ")", "]", "return", "[", "m", "for", "m", "in", "mas", "if", "m", "in", "markers", "]" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/solver/solver.py#L14-L77
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/bisect-perf-regression.py
python
BisectPerformanceMetrics.TryParseResultValuesFromOutput
(self, metric, text)
return values_list
Attempts to parse a metric in the format RESULT <graph: <trace>. Args: metric: The metric as a list of [<trace>, <value>] strings. text: The text to parse the metric values from. Returns: A list of floating point numbers found.
Attempts to parse a metric in the format RESULT <graph: <trace>.
[ "Attempts", "to", "parse", "a", "metric", "in", "the", "format", "RESULT", "<graph", ":", "<trace", ">", "." ]
def TryParseResultValuesFromOutput(self, metric, text): """Attempts to parse a metric in the format RESULT <graph: <trace>. Args: metric: The metric as a list of [<trace>, <value>] strings. text: The text to parse the metric values from. Returns: A list of floating point numbers found. """ # Format is: RESULT <graph>: <trace>= <value> <units> metric_formatted = re.escape('RESULT %s: %s=' % (metric[0], metric[1])) text_lines = text.split('\n') values_list = [] for current_line in text_lines: # Parse the output from the performance test for the metric we're # interested in. metric_re = metric_formatted +\ "(\s)*(?P<values>[0-9]+(\.[0-9]*)?)" metric_re = re.compile(metric_re) regex_results = metric_re.search(current_line) if not regex_results is None: values_list += [regex_results.group('values')] else: metric_re = metric_formatted +\ "(\s)*\[(\s)*(?P<values>[0-9,.]+)\]" metric_re = re.compile(metric_re) regex_results = metric_re.search(current_line) if not regex_results is None: metric_values = regex_results.group('values') values_list += metric_values.split(',') values_list = [float(v) for v in values_list if IsStringFloat(v)] # If the metric is times/t, we need to sum the timings in order to get # similar regression results as the try-bots. metrics_to_sum = [['times', 't'], ['times', 'page_load_time'], ['cold_times', 'page_load_time'], ['warm_times', 'page_load_time']] if metric in metrics_to_sum: if values_list: values_list = [reduce(lambda x, y: float(x) + float(y), values_list)] return values_list
[ "def", "TryParseResultValuesFromOutput", "(", "self", ",", "metric", ",", "text", ")", ":", "# Format is: RESULT <graph>: <trace>= <value> <units>", "metric_formatted", "=", "re", ".", "escape", "(", "'RESULT %s: %s='", "%", "(", "metric", "[", "0", "]", ",", "metric", "[", "1", "]", ")", ")", "text_lines", "=", "text", ".", "split", "(", "'\\n'", ")", "values_list", "=", "[", "]", "for", "current_line", "in", "text_lines", ":", "# Parse the output from the performance test for the metric we're", "# interested in.", "metric_re", "=", "metric_formatted", "+", "\"(\\s)*(?P<values>[0-9]+(\\.[0-9]*)?)\"", "metric_re", "=", "re", ".", "compile", "(", "metric_re", ")", "regex_results", "=", "metric_re", ".", "search", "(", "current_line", ")", "if", "not", "regex_results", "is", "None", ":", "values_list", "+=", "[", "regex_results", ".", "group", "(", "'values'", ")", "]", "else", ":", "metric_re", "=", "metric_formatted", "+", "\"(\\s)*\\[(\\s)*(?P<values>[0-9,.]+)\\]\"", "metric_re", "=", "re", ".", "compile", "(", "metric_re", ")", "regex_results", "=", "metric_re", ".", "search", "(", "current_line", ")", "if", "not", "regex_results", "is", "None", ":", "metric_values", "=", "regex_results", ".", "group", "(", "'values'", ")", "values_list", "+=", "metric_values", ".", "split", "(", "','", ")", "values_list", "=", "[", "float", "(", "v", ")", "for", "v", "in", "values_list", "if", "IsStringFloat", "(", "v", ")", "]", "# If the metric is times/t, we need to sum the timings in order to get", "# similar regression results as the try-bots.", "metrics_to_sum", "=", "[", "[", "'times'", ",", "'t'", "]", ",", "[", "'times'", ",", "'page_load_time'", "]", ",", "[", "'cold_times'", ",", "'page_load_time'", "]", ",", "[", "'warm_times'", ",", "'page_load_time'", "]", "]", "if", "metric", "in", "metrics_to_sum", ":", "if", "values_list", ":", "values_list", "=", "[", "reduce", "(", "lambda", "x", ",", "y", ":", "float", "(", "x", ")", "+", "float", "(", "y", ")", ",", "values_list", ")", "]", "return", "values_list" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/bisect-perf-regression.py#L1181-L1229
floatlazer/semantic_slam
657814a1ba484de6b7f6f9d07c564566c8121f13
semantic_cloud/src/semantic_cloud.py
python
SemanticCloud.predict
(self, img)
Do semantic segmantation \param img: (numpy array bgr8) The input cv image
Do semantic segmantation \param img: (numpy array bgr8) The input cv image
[ "Do", "semantic", "segmantation", "\\", "param", "img", ":", "(", "numpy", "array", "bgr8", ")", "The", "input", "cv", "image" ]
def predict(self, img): """ Do semantic segmantation \param img: (numpy array bgr8) The input cv image """ img = img.copy() # Make a copy of image because the method will modify the image #orig_size = (img.shape[0], img.shape[1]) # Original image size # Prepare image: first resize to CNN input size then extract the mean value of SUNRGBD dataset. No normalization img = resize(img, self.cnn_input_size, mode = 'reflect', anti_aliasing=True, preserve_range = True) # Give float64 img = img.astype(np.float32) img -= self.mean # Convert HWC -> CHW img = img.transpose(2, 0, 1) # Convert to tensor img = torch.tensor(img, dtype = torch.float32) img = img.unsqueeze(0) # Add batch dimension required by CNN with torch.no_grad(): img = img.to(self.device) # Do inference since = time.time() outputs = self.model(img) #N,C,W,H # Apply softmax to obtain normalized probabilities outputs = torch.nn.functional.softmax(outputs, 1) return outputs
[ "def", "predict", "(", "self", ",", "img", ")", ":", "img", "=", "img", ".", "copy", "(", ")", "# Make a copy of image because the method will modify the image", "#orig_size = (img.shape[0], img.shape[1]) # Original image size", "# Prepare image: first resize to CNN input size then extract the mean value of SUNRGBD dataset. No normalization", "img", "=", "resize", "(", "img", ",", "self", ".", "cnn_input_size", ",", "mode", "=", "'reflect'", ",", "anti_aliasing", "=", "True", ",", "preserve_range", "=", "True", ")", "# Give float64", "img", "=", "img", ".", "astype", "(", "np", ".", "float32", ")", "img", "-=", "self", ".", "mean", "# Convert HWC -> CHW", "img", "=", "img", ".", "transpose", "(", "2", ",", "0", ",", "1", ")", "# Convert to tensor", "img", "=", "torch", ".", "tensor", "(", "img", ",", "dtype", "=", "torch", ".", "float32", ")", "img", "=", "img", ".", "unsqueeze", "(", "0", ")", "# Add batch dimension required by CNN", "with", "torch", ".", "no_grad", "(", ")", ":", "img", "=", "img", ".", "to", "(", "self", ".", "device", ")", "# Do inference", "since", "=", "time", ".", "time", "(", ")", "outputs", "=", "self", ".", "model", "(", "img", ")", "#N,C,W,H", "# Apply softmax to obtain normalized probabilities", "outputs", "=", "torch", ".", "nn", ".", "functional", ".", "softmax", "(", "outputs", ",", "1", ")", "return", "outputs" ]
https://github.com/floatlazer/semantic_slam/blob/657814a1ba484de6b7f6f9d07c564566c8121f13/semantic_cloud/src/semantic_cloud.py#L260-L283
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/em/fdem.py
python
FDEM2dFOPold.__init__
(self, data, nlay=2, verbose=False)
constructor with data and (optionally) number of layers
constructor with data and (optionally) number of layers
[ "constructor", "with", "data", "and", "(", "optionally", ")", "number", "of", "layers" ]
def __init__(self, data, nlay=2, verbose=False): """ constructor with data and (optionally) number of layers """ pg.core.ModellingBase.__init__(self, verbose) self.nlay = nlay self.FOP1d = data.FOP(nlay) self.nx = len(data.x) self.nf = len(data.freq()) self.mesh_ = pg.meshtools.createMesh1D(self.nx, 2 * nlay - 1) self.setMesh(self.mesh_)
[ "def", "__init__", "(", "self", ",", "data", ",", "nlay", "=", "2", ",", "verbose", "=", "False", ")", ":", "pg", ".", "core", ".", "ModellingBase", ".", "__init__", "(", "self", ",", "verbose", ")", "self", ".", "nlay", "=", "nlay", "self", ".", "FOP1d", "=", "data", ".", "FOP", "(", "nlay", ")", "self", ".", "nx", "=", "len", "(", "data", ".", "x", ")", "self", ".", "nf", "=", "len", "(", "data", ".", "freq", "(", ")", ")", "self", ".", "mesh_", "=", "pg", ".", "meshtools", ".", "createMesh1D", "(", "self", ".", "nx", ",", "2", "*", "nlay", "-", "1", ")", "self", ".", "setMesh", "(", "self", ".", "mesh_", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/em/fdem.py#L55-L63
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/aetools.py
python
decodeerror
(arguments)
return (err_a1, err_a2, err_a3)
Create the 'best' argument for a raise MacOS.Error
Create the 'best' argument for a raise MacOS.Error
[ "Create", "the", "best", "argument", "for", "a", "raise", "MacOS", ".", "Error" ]
def decodeerror(arguments): """Create the 'best' argument for a raise MacOS.Error""" errn = arguments['errn'] err_a1 = errn if 'errs' in arguments: err_a2 = arguments['errs'] else: err_a2 = MacOS.GetErrorString(errn) if 'erob' in arguments: err_a3 = arguments['erob'] else: err_a3 = None return (err_a1, err_a2, err_a3)
[ "def", "decodeerror", "(", "arguments", ")", ":", "errn", "=", "arguments", "[", "'errn'", "]", "err_a1", "=", "errn", "if", "'errs'", "in", "arguments", ":", "err_a2", "=", "arguments", "[", "'errs'", "]", "else", ":", "err_a2", "=", "MacOS", ".", "GetErrorString", "(", "errn", ")", "if", "'erob'", "in", "arguments", ":", "err_a3", "=", "arguments", "[", "'erob'", "]", "else", ":", "err_a3", "=", "None", "return", "(", "err_a1", ",", "err_a2", ",", "err_a3", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/aetools.py#L131-L144
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py
python
RequestsCookieJar.get_policy
(self)
return self._policy
Return the CookiePolicy instance used.
Return the CookiePolicy instance used.
[ "Return", "the", "CookiePolicy", "instance", "used", "." ]
def get_policy(self): """Return the CookiePolicy instance used.""" return self._policy
[ "def", "get_policy", "(", "self", ")", ":", "return", "self", ".", "_policy" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py#L421-L423
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/pypack/altgraph/GraphUtil.py
python
generate_scale_free_graph
(steps, growth_num, self_loops=False, multi_edges=False)
return graph
Generates and returns a L{Graph.Graph} instance that will have C{steps*growth_num} nodes and a scale free (powerlaw) connectivity. Starting with a fully connected graph with C{growth_num} nodes at every step C{growth_num} nodes are added to the graph and are connected to existing nodes with a probability proportional to the degree of these existing nodes.
Generates and returns a L{Graph.Graph} instance that will have C{steps*growth_num} nodes and a scale free (powerlaw) connectivity. Starting with a fully connected graph with C{growth_num} nodes at every step C{growth_num} nodes are added to the graph and are connected to existing nodes with a probability proportional to the degree of these existing nodes.
[ "Generates", "and", "returns", "a", "L", "{", "Graph", ".", "Graph", "}", "instance", "that", "will", "have", "C", "{", "steps", "*", "growth_num", "}", "nodes", "and", "a", "scale", "free", "(", "powerlaw", ")", "connectivity", ".", "Starting", "with", "a", "fully", "connected", "graph", "with", "C", "{", "growth_num", "}", "nodes", "at", "every", "step", "C", "{", "growth_num", "}", "nodes", "are", "added", "to", "the", "graph", "and", "are", "connected", "to", "existing", "nodes", "with", "a", "probability", "proportional", "to", "the", "degree", "of", "these", "existing", "nodes", "." ]
def generate_scale_free_graph(steps, growth_num, self_loops=False, multi_edges=False): ''' Generates and returns a L{Graph.Graph} instance that will have C{steps*growth_num} nodes and a scale free (powerlaw) connectivity. Starting with a fully connected graph with C{growth_num} nodes at every step C{growth_num} nodes are added to the graph and are connected to existing nodes with a probability proportional to the degree of these existing nodes. ''' graph = Graph.Graph() # initialize the graph store = [] for i in range(growth_num): store += [ i ] * (growth_num - 1) for j in range(i + 1, growth_num): graph.add_edge(i,j) # generate for node in range(growth_num, (steps-1) * growth_num): graph.add_node(node) while ( graph.out_degree(node) < growth_num ): nbr = random.choice(store) # loop defense if node == nbr and not self_loops: continue # multi edge defense if graph.edge_by_node(node, nbr) and not multi_edges: continue graph.add_edge(node, nbr) for nbr in graph.out_nbrs(node): store.append(node) store.append(nbr) return graph
[ "def", "generate_scale_free_graph", "(", "steps", ",", "growth_num", ",", "self_loops", "=", "False", ",", "multi_edges", "=", "False", ")", ":", "graph", "=", "Graph", ".", "Graph", "(", ")", "# initialize the graph", "store", "=", "[", "]", "for", "i", "in", "range", "(", "growth_num", ")", ":", "store", "+=", "[", "i", "]", "*", "(", "growth_num", "-", "1", ")", "for", "j", "in", "range", "(", "i", "+", "1", ",", "growth_num", ")", ":", "graph", ".", "add_edge", "(", "i", ",", "j", ")", "# generate", "for", "node", "in", "range", "(", "growth_num", ",", "(", "steps", "-", "1", ")", "*", "growth_num", ")", ":", "graph", ".", "add_node", "(", "node", ")", "while", "(", "graph", ".", "out_degree", "(", "node", ")", "<", "growth_num", ")", ":", "nbr", "=", "random", ".", "choice", "(", "store", ")", "# loop defense", "if", "node", "==", "nbr", "and", "not", "self_loops", ":", "continue", "# multi edge defense", "if", "graph", ".", "edge_by_node", "(", "node", ",", "nbr", ")", "and", "not", "multi_edges", ":", "continue", "graph", ".", "add_edge", "(", "node", ",", "nbr", ")", "for", "nbr", "in", "graph", ".", "out_nbrs", "(", "node", ")", ":", "store", ".", "append", "(", "node", ")", "store", ".", "append", "(", "nbr", ")", "return", "graph" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/altgraph/GraphUtil.py#L39-L76
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/reductions/solvers/conic_solvers/scip_conif.py
python
SCIP._solve
( self, model: ScipModel, variables: List, constraints: List, data: Dict[str, Any], dims: Dict[str, Union[int, List]], )
return solution
Solve and return a solution if one exists.
Solve and return a solution if one exists.
[ "Solve", "and", "return", "a", "solution", "if", "one", "exists", "." ]
def _solve( self, model: ScipModel, variables: List, constraints: List, data: Dict[str, Any], dims: Dict[str, Union[int, List]], ) -> Dict[str, Any]: """Solve and return a solution if one exists.""" solution = {} try: model.optimize() solution["value"] = model.getObjVal() sol = model.getBestSol() solution["primal"] = array([sol[v] for v in variables]) if not (data[s.BOOL_IDX] or data[s.INT_IDX]): # Not the following code calculating the dual values does not # always return the correct values, see tests `test_scip_lp_2` # and `test_scip_socp_1`. vals = [] # Get linear duals. for lc in constraints: if lc is not None and lc.isLinear(): dual = model.getDualsolLinear(lc) vals.append(dual) # Get non-linear duals. if len(dims[s.SOC_DIM]) > 1: for row in model.getNlRows(): vals.append(row.getDualsol()) solution["y"] = -array(vals) solution[s.EQ_DUAL] = solution["y"][0:dims[s.EQ_DIM]] solution[s.INEQ_DUAL] = solution["y"][dims[s.EQ_DIM]:] except Exception as e: log.warning("Error encountered when optimising %s: %s", model, e) solution[s.SOLVE_TIME] = model.getSolvingTime() solution['status'] = STATUS_MAP[model.getStatus()] if solution["status"] == s.SOLVER_ERROR and model.getNCountedSols() > 0: solution["status"] = s.OPTIMAL_INACCURATE return solution
[ "def", "_solve", "(", "self", ",", "model", ":", "ScipModel", ",", "variables", ":", "List", ",", "constraints", ":", "List", ",", "data", ":", "Dict", "[", "str", ",", "Any", "]", ",", "dims", ":", "Dict", "[", "str", ",", "Union", "[", "int", ",", "List", "]", "]", ",", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "solution", "=", "{", "}", "try", ":", "model", ".", "optimize", "(", ")", "solution", "[", "\"value\"", "]", "=", "model", ".", "getObjVal", "(", ")", "sol", "=", "model", ".", "getBestSol", "(", ")", "solution", "[", "\"primal\"", "]", "=", "array", "(", "[", "sol", "[", "v", "]", "for", "v", "in", "variables", "]", ")", "if", "not", "(", "data", "[", "s", ".", "BOOL_IDX", "]", "or", "data", "[", "s", ".", "INT_IDX", "]", ")", ":", "# Not the following code calculating the dual values does not", "# always return the correct values, see tests `test_scip_lp_2`", "# and `test_scip_socp_1`.", "vals", "=", "[", "]", "# Get linear duals.", "for", "lc", "in", "constraints", ":", "if", "lc", "is", "not", "None", "and", "lc", ".", "isLinear", "(", ")", ":", "dual", "=", "model", ".", "getDualsolLinear", "(", "lc", ")", "vals", ".", "append", "(", "dual", ")", "# Get non-linear duals.", "if", "len", "(", "dims", "[", "s", ".", "SOC_DIM", "]", ")", ">", "1", ":", "for", "row", "in", "model", ".", "getNlRows", "(", ")", ":", "vals", ".", "append", "(", "row", ".", "getDualsol", "(", ")", ")", "solution", "[", "\"y\"", "]", "=", "-", "array", "(", "vals", ")", "solution", "[", "s", ".", "EQ_DUAL", "]", "=", "solution", "[", "\"y\"", "]", "[", "0", ":", "dims", "[", "s", ".", "EQ_DIM", "]", "]", "solution", "[", "s", ".", "INEQ_DUAL", "]", "=", "solution", "[", "\"y\"", "]", "[", "dims", "[", "s", ".", "EQ_DIM", "]", ":", "]", "except", "Exception", "as", "e", ":", "log", ".", "warning", "(", "\"Error encountered when optimising %s: %s\"", ",", "model", ",", "e", ")", "solution", "[", "s", ".", "SOLVE_TIME", "]", "=", "model", ".", "getSolvingTime", "(", ")", "solution", "[", "'status'", "]", "=", "STATUS_MAP", "[", "model", ".", "getStatus", "(", ")", "]", "if", "solution", "[", "\"status\"", "]", "==", "s", ".", "SOLVER_ERROR", "and", "model", ".", "getNCountedSols", "(", ")", ">", "0", ":", "solution", "[", "\"status\"", "]", "=", "s", ".", "OPTIMAL_INACCURATE", "return", "solution" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/reductions/solvers/conic_solvers/scip_conif.py#L302-L349
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/tools/stats-viewer.py
python
ChromeCounterCollection.CountersInUse
(self)
return self.max_counters
Return the number of counters in active use.
Return the number of counters in active use.
[ "Return", "the", "number", "of", "counters", "in", "active", "use", "." ]
def CountersInUse(self): """Return the number of counters in active use.""" for i in range(self.max_counters): name_offset = self.counter_names_offset + i * self._COUNTER_NAME_SIZE if self.data.ByteAt(name_offset) == 0: return i return self.max_counters
[ "def", "CountersInUse", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "max_counters", ")", ":", "name_offset", "=", "self", ".", "counter_names_offset", "+", "i", "*", "self", ".", "_COUNTER_NAME_SIZE", "if", "self", ".", "data", ".", "ByteAt", "(", "name_offset", ")", "==", "0", ":", "return", "i", "return", "self", ".", "max_counters" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/tools/stats-viewer.py#L439-L445
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/coverity/coverity.py
python
_ReadPassword
(pwfilename)
return password.rstrip()
Reads the coverity password in from a file where it was stashed
Reads the coverity password in from a file where it was stashed
[ "Reads", "the", "coverity", "password", "in", "from", "a", "file", "where", "it", "was", "stashed" ]
def _ReadPassword(pwfilename): """Reads the coverity password in from a file where it was stashed""" pwfile = open(pwfilename, 'r') password = pwfile.readline() pwfile.close() return password.rstrip()
[ "def", "_ReadPassword", "(", "pwfilename", ")", ":", "pwfile", "=", "open", "(", "pwfilename", ",", "'r'", ")", "password", "=", "pwfile", ".", "readline", "(", ")", "pwfile", ".", "close", "(", ")", "return", "password", ".", "rstrip", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/coverity/coverity.py#L81-L86
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
python/caffe/pycaffe.py
python
_Net_set_input_arrays
(self, data, labels)
return self._set_input_arrays(data, labels)
Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.)
Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.)
[ "Set", "input", "arrays", "of", "the", "in", "-", "memory", "MemoryDataLayer", ".", "(", "Note", ":", "this", "is", "only", "for", "networks", "declared", "with", "the", "memory", "data", "layer", ".", ")" ]
def _Net_set_input_arrays(self, data, labels): """ Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.) """ if labels.ndim == 1: labels = np.ascontiguousarray(labels[:, np.newaxis, np.newaxis, np.newaxis]) return self._set_input_arrays(data, labels)
[ "def", "_Net_set_input_arrays", "(", "self", ",", "data", ",", "labels", ")", ":", "if", "labels", ".", "ndim", "==", "1", ":", "labels", "=", "np", ".", "ascontiguousarray", "(", "labels", "[", ":", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", "]", ")", "return", "self", ".", "_set_input_arrays", "(", "data", ",", "labels", ")" ]
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/python/caffe/pycaffe.py#L251-L259
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py
python
is_calldef_pointer
(type_)
return isinstance(nake_type, cpptypes.compound_t) \ and isinstance(nake_type.base, cpptypes.calldef_type_t)
returns True, if type represents pointer to free/member function, False otherwise
returns True, if type represents pointer to free/member function, False otherwise
[ "returns", "True", "if", "type", "represents", "pointer", "to", "free", "/", "member", "function", "False", "otherwise" ]
def is_calldef_pointer(type_): """returns True, if type represents pointer to free/member function, False otherwise""" if not is_pointer(type_): return False nake_type = remove_alias(type_) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.compound_t) \ and isinstance(nake_type.base, cpptypes.calldef_type_t)
[ "def", "is_calldef_pointer", "(", "type_", ")", ":", "if", "not", "is_pointer", "(", "type_", ")", ":", "return", "False", "nake_type", "=", "remove_alias", "(", "type_", ")", "nake_type", "=", "remove_cv", "(", "nake_type", ")", "return", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "compound_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "calldef_type_t", ")" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py#L239-L247
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py
python
resize
(x, new_shape)
return result
Return a new masked array with the specified size and shape. This is the masked equivalent of the `numpy.resize` function. The new array is filled with repeated copies of `x` (in the order that the data are stored in memory). If `x` is masked, the new array will be masked, and the new mask will be a repetition of the old one. See Also -------- numpy.resize : Equivalent function in the top level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.array([[1, 2] ,[3, 4]]) >>> a[0, 1] = ma.masked >>> a masked_array( data=[[1, --], [3, 4]], mask=[[False, True], [False, False]], fill_value=999999) >>> np.resize(a, (3, 3)) masked_array( data=[[1, 2, 3], [4, 1, 2], [3, 4, 1]], mask=False, fill_value=999999) >>> ma.resize(a, (3, 3)) masked_array( data=[[1, --, 3], [4, 1, --], [3, 4, 1]], mask=[[False, True, False], [False, False, True], [False, False, False]], fill_value=999999) A MaskedArray is always returned, regardless of the input type. >>> a = np.array([[1, 2] ,[3, 4]]) >>> ma.resize(a, (3, 3)) masked_array( data=[[1, 2, 3], [4, 1, 2], [3, 4, 1]], mask=False, fill_value=999999)
Return a new masked array with the specified size and shape.
[ "Return", "a", "new", "masked", "array", "with", "the", "specified", "size", "and", "shape", "." ]
def resize(x, new_shape): """ Return a new masked array with the specified size and shape. This is the masked equivalent of the `numpy.resize` function. The new array is filled with repeated copies of `x` (in the order that the data are stored in memory). If `x` is masked, the new array will be masked, and the new mask will be a repetition of the old one. See Also -------- numpy.resize : Equivalent function in the top level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.array([[1, 2] ,[3, 4]]) >>> a[0, 1] = ma.masked >>> a masked_array( data=[[1, --], [3, 4]], mask=[[False, True], [False, False]], fill_value=999999) >>> np.resize(a, (3, 3)) masked_array( data=[[1, 2, 3], [4, 1, 2], [3, 4, 1]], mask=False, fill_value=999999) >>> ma.resize(a, (3, 3)) masked_array( data=[[1, --, 3], [4, 1, --], [3, 4, 1]], mask=[[False, True, False], [False, False, True], [False, False, False]], fill_value=999999) A MaskedArray is always returned, regardless of the input type. >>> a = np.array([[1, 2] ,[3, 4]]) >>> ma.resize(a, (3, 3)) masked_array( data=[[1, 2, 3], [4, 1, 2], [3, 4, 1]], mask=False, fill_value=999999) """ # We can't use _frommethods here, as N.resize is notoriously whiny. m = getmask(x) if m is not nomask: m = np.resize(m, new_shape) result = np.resize(x, new_shape).view(get_masked_subclass(x)) if result.ndim: result._mask = m return result
[ "def", "resize", "(", "x", ",", "new_shape", ")", ":", "# We can't use _frommethods here, as N.resize is notoriously whiny.", "m", "=", "getmask", "(", "x", ")", "if", "m", "is", "not", "nomask", ":", "m", "=", "np", ".", "resize", "(", "m", ",", "new_shape", ")", "result", "=", "np", ".", "resize", "(", "x", ",", "new_shape", ")", ".", "view", "(", "get_masked_subclass", "(", "x", ")", ")", "if", "result", ".", "ndim", ":", "result", ".", "_mask", "=", "m", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L7062-L7123
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_collections_abc.py
python
Set.isdisjoint
(self, other)
return True
Return True if two sets have a null intersection.
Return True if two sets have a null intersection.
[ "Return", "True", "if", "two", "sets", "have", "a", "null", "intersection", "." ]
def isdisjoint(self, other): 'Return True if two sets have a null intersection.' for value in other: if value in self: return False return True
[ "def", "isdisjoint", "(", "self", ",", "other", ")", ":", "for", "value", "in", "other", ":", "if", "value", "in", "self", ":", "return", "False", "return", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_collections_abc.py#L481-L486
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap.py
python
_gcd_import
(name, package=None, level=0)
return _find_and_load(name, _gcd_import)
Import and return the module based on its name, the package the call is being made from, and the level adjustment. This function represents the greatest common denominator of functionality between import_module and __import__. This includes setting __package__ if the loader did not.
Import and return the module based on its name, the package the call is being made from, and the level adjustment.
[ "Import", "and", "return", "the", "module", "based", "on", "its", "name", "the", "package", "the", "call", "is", "being", "made", "from", "and", "the", "level", "adjustment", "." ]
def _gcd_import(name, package=None, level=0): """Import and return the module based on its name, the package the call is being made from, and the level adjustment. This function represents the greatest common denominator of functionality between import_module and __import__. This includes setting __package__ if the loader did not. """ _sanity_check(name, package, level) if level > 0: name = _resolve_name(name, package, level) return _find_and_load(name, _gcd_import)
[ "def", "_gcd_import", "(", "name", ",", "package", "=", "None", ",", "level", "=", "0", ")", ":", "_sanity_check", "(", "name", ",", "package", ",", "level", ")", "if", "level", ">", "0", ":", "name", "=", "_resolve_name", "(", "name", ",", "package", ",", "level", ")", "return", "_find_and_load", "(", "name", ",", "_gcd_import", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap.py#L994-L1006
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/guidance/train.py
python
general_train
(make_loss, hparams, make_hooks=None)
Trains a general model with a loss. Args: make_loss: Function which creates loss (and possibly registers accuracy summaries and other features). hparams: Hyperparameters (see default_hparams() for details). make_hooks: Optional, function which creates additional hooks for training. Returns: Final loss. Raises: ValueError: If flags are missing or invalid.
Trains a general model with a loss.
[ "Trains", "a", "general", "model", "with", "a", "loss", "." ]
def general_train(make_loss, hparams, make_hooks=None): """Trains a general model with a loss. Args: make_loss: Function which creates loss (and possibly registers accuracy summaries and other features). hparams: Hyperparameters (see default_hparams() for details). make_hooks: Optional, function which creates additional hooks for training. Returns: Final loss. Raises: ValueError: If flags are missing or invalid. """ train_dir = mode_dir('train') if not tf.gfile.Exists(train_dir): tf.gfile.MakeDirs(train_dir) if hparams.seed: tf.set_random_seed(hparams.seed) # Configure keras keras.backend.set_learning_phase(1) keras.backend.manual_variable_initialization(True) with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks, merge_devices=True)): # Set the caching device to prevent hangs during distributed training vs = tf.get_variable_scope() if vs.caching_device is None: vs.set_caching_device(lambda op: op.device) # Grab loss and global step total_loss = make_loss() global_step = slim.get_or_create_global_step() # Set up Polyak averaging if desired if hparams.use_averages: moving_average_variables = tf.trainable_variables() moving_average_variables.extend(slim.losses.get_losses()) moving_average_variables.append(total_loss) variable_averages = tf.train.ExponentialMovingAverage( hparams.moving_average_decay, global_step) # For sync_replicas, averaging happens in the chief queue runner if not hparams.sync_replicas: tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, variable_averages.apply(moving_average_variables)) else: variable_averages = None moving_average_variables = None # Decay learning rate exponentially learning_rate = tf.train.exponential_decay( hparams.learning_rate, global_step, hparams.decay_steps, hparams.learning_rate_decay_factor, staircase=True) tf.contrib.deprecated.scalar_summary('learning rate', learning_rate) # Create optimizer if hparams.optimizer == 'adam': optimizer = tf.train.AdamOptimizer(learning_rate, epsilon=1e-3) elif hparams.optimizer == 'rmsprop': optimizer = tf.train.RMSPropOptimizer( learning_rate=learning_rate, decay=0.9, momentum=0.9, epsilon=1e-5) else: raise ValueError('Unknown optimizer %s' % hparams.optimizer) is_chief = FLAGS.task == 0 chief_only_hooks = [] hooks = [tf.train.LoggingTensorHook({ 'global_step': global_step, 'total_loss': total_loss }, every_n_iter=FLAGS.log_every_n_iter), tf.train.NanTensorHook(total_loss), tf.train.StopAtStepHook(hparams.max_steps), ] if make_hooks is not None: hooks.extend(make_hooks()) # If desired, optimize synchronously if hparams.sync_replicas: optimizer = tf.SyncReplicasOptimizer( optimizer=optimizer, replicas_to_aggregate=FLAGS.worker_replicas - hparams.backup_replicas, variable_averages=variable_averages, variables_to_average=moving_average_variables, replica_id=FLAGS.task, total_num_replicas=FLAGS.worker_replicas) sync_replicas_hook = optimizer.make_session_run_hook(is_chief) hooks.append(sync_replicas_hook) # Train train_tensor = slim.learning.create_train_op( total_loss, optimizer, clip_gradient_norm=hparams.gradient_clipping_norm) saver = tf.train.Saver(keep_checkpoint_every_n_hours=2) scaffold = tf.train.Scaffold(saver=saver) if FLAGS.save_summaries_secs > 0: save_summaries_secs = FLAGS.save_summaries_secs save_summaries_steps = None else: save_summaries_steps = FLAGS.save_summaries_steps save_summaries_secs = None with tf.train.MonitoredTrainingSession( master=FLAGS.super_master, is_chief=is_chief, hooks=hooks, chief_only_hooks=chief_only_hooks, checkpoint_dir=train_dir, scaffold=scaffold, save_checkpoint_secs=FLAGS.save_checkpoint_secs, save_summaries_secs=save_summaries_secs, save_summaries_steps=save_summaries_steps) as mon_sess: while not mon_sess.should_stop(): mon_sess.run(train_tensor)
[ "def", "general_train", "(", "make_loss", ",", "hparams", ",", "make_hooks", "=", "None", ")", ":", "train_dir", "=", "mode_dir", "(", "'train'", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "train_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "train_dir", ")", "if", "hparams", ".", "seed", ":", "tf", ".", "set_random_seed", "(", "hparams", ".", "seed", ")", "# Configure keras", "keras", ".", "backend", ".", "set_learning_phase", "(", "1", ")", "keras", ".", "backend", ".", "manual_variable_initialization", "(", "True", ")", "with", "tf", ".", "device", "(", "tf", ".", "train", ".", "replica_device_setter", "(", "FLAGS", ".", "ps_tasks", ",", "merge_devices", "=", "True", ")", ")", ":", "# Set the caching device to prevent hangs during distributed training", "vs", "=", "tf", ".", "get_variable_scope", "(", ")", "if", "vs", ".", "caching_device", "is", "None", ":", "vs", ".", "set_caching_device", "(", "lambda", "op", ":", "op", ".", "device", ")", "# Grab loss and global step", "total_loss", "=", "make_loss", "(", ")", "global_step", "=", "slim", ".", "get_or_create_global_step", "(", ")", "# Set up Polyak averaging if desired", "if", "hparams", ".", "use_averages", ":", "moving_average_variables", "=", "tf", ".", "trainable_variables", "(", ")", "moving_average_variables", ".", "extend", "(", "slim", ".", "losses", ".", "get_losses", "(", ")", ")", "moving_average_variables", ".", "append", "(", "total_loss", ")", "variable_averages", "=", "tf", ".", "train", ".", "ExponentialMovingAverage", "(", "hparams", ".", "moving_average_decay", ",", "global_step", ")", "# For sync_replicas, averaging happens in the chief queue runner", "if", "not", "hparams", ".", "sync_replicas", ":", "tf", ".", "add_to_collection", "(", "tf", ".", "GraphKeys", ".", "UPDATE_OPS", ",", "variable_averages", ".", "apply", "(", "moving_average_variables", ")", ")", "else", ":", "variable_averages", "=", "None", "moving_average_variables", "=", "None", "# Decay learning rate exponentially", "learning_rate", "=", "tf", ".", "train", ".", "exponential_decay", "(", "hparams", ".", "learning_rate", ",", "global_step", ",", "hparams", ".", "decay_steps", ",", "hparams", ".", "learning_rate_decay_factor", ",", "staircase", "=", "True", ")", "tf", ".", "contrib", ".", "deprecated", ".", "scalar_summary", "(", "'learning rate'", ",", "learning_rate", ")", "# Create optimizer", "if", "hparams", ".", "optimizer", "==", "'adam'", ":", "optimizer", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "learning_rate", ",", "epsilon", "=", "1e-3", ")", "elif", "hparams", ".", "optimizer", "==", "'rmsprop'", ":", "optimizer", "=", "tf", ".", "train", ".", "RMSPropOptimizer", "(", "learning_rate", "=", "learning_rate", ",", "decay", "=", "0.9", ",", "momentum", "=", "0.9", ",", "epsilon", "=", "1e-5", ")", "else", ":", "raise", "ValueError", "(", "'Unknown optimizer %s'", "%", "hparams", ".", "optimizer", ")", "is_chief", "=", "FLAGS", ".", "task", "==", "0", "chief_only_hooks", "=", "[", "]", "hooks", "=", "[", "tf", ".", "train", ".", "LoggingTensorHook", "(", "{", "'global_step'", ":", "global_step", ",", "'total_loss'", ":", "total_loss", "}", ",", "every_n_iter", "=", "FLAGS", ".", "log_every_n_iter", ")", ",", "tf", ".", "train", ".", "NanTensorHook", "(", "total_loss", ")", ",", "tf", ".", "train", ".", "StopAtStepHook", "(", "hparams", ".", "max_steps", ")", ",", "]", "if", "make_hooks", "is", "not", "None", ":", "hooks", ".", "extend", "(", "make_hooks", "(", ")", ")", "# If desired, optimize synchronously", "if", "hparams", ".", "sync_replicas", ":", "optimizer", "=", "tf", ".", "SyncReplicasOptimizer", "(", "optimizer", "=", "optimizer", ",", "replicas_to_aggregate", "=", "FLAGS", ".", "worker_replicas", "-", "hparams", ".", "backup_replicas", ",", "variable_averages", "=", "variable_averages", ",", "variables_to_average", "=", "moving_average_variables", ",", "replica_id", "=", "FLAGS", ".", "task", ",", "total_num_replicas", "=", "FLAGS", ".", "worker_replicas", ")", "sync_replicas_hook", "=", "optimizer", ".", "make_session_run_hook", "(", "is_chief", ")", "hooks", ".", "append", "(", "sync_replicas_hook", ")", "# Train", "train_tensor", "=", "slim", ".", "learning", ".", "create_train_op", "(", "total_loss", ",", "optimizer", ",", "clip_gradient_norm", "=", "hparams", ".", "gradient_clipping_norm", ")", "saver", "=", "tf", ".", "train", ".", "Saver", "(", "keep_checkpoint_every_n_hours", "=", "2", ")", "scaffold", "=", "tf", ".", "train", ".", "Scaffold", "(", "saver", "=", "saver", ")", "if", "FLAGS", ".", "save_summaries_secs", ">", "0", ":", "save_summaries_secs", "=", "FLAGS", ".", "save_summaries_secs", "save_summaries_steps", "=", "None", "else", ":", "save_summaries_steps", "=", "FLAGS", ".", "save_summaries_steps", "save_summaries_secs", "=", "None", "with", "tf", ".", "train", ".", "MonitoredTrainingSession", "(", "master", "=", "FLAGS", ".", "super_master", ",", "is_chief", "=", "is_chief", ",", "hooks", "=", "hooks", ",", "chief_only_hooks", "=", "chief_only_hooks", ",", "checkpoint_dir", "=", "train_dir", ",", "scaffold", "=", "scaffold", ",", "save_checkpoint_secs", "=", "FLAGS", ".", "save_checkpoint_secs", ",", "save_summaries_secs", "=", "save_summaries_secs", ",", "save_summaries_steps", "=", "save_summaries_steps", ")", "as", "mon_sess", ":", "while", "not", "mon_sess", ".", "should_stop", "(", ")", ":", "mon_sess", ".", "run", "(", "train_tensor", ")" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/guidance/train.py#L96-L217
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/config/manager.py
python
recursive_update
(target, new)
Recursively update one dictionary using another. None values will delete their keys.
Recursively update one dictionary using another.
[ "Recursively", "update", "one", "dictionary", "using", "another", "." ]
def recursive_update(target, new): """Recursively update one dictionary using another. None values will delete their keys. """ for k, v in new.items(): if isinstance(v, dict): if k not in target: target[k] = {} recursive_update(target[k], v) if not target[k]: # Prune empty subdicts del target[k] elif v is None: target.pop(k, None) else: target[k] = v
[ "def", "recursive_update", "(", "target", ",", "new", ")", ":", "for", "k", ",", "v", "in", "new", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "if", "k", "not", "in", "target", ":", "target", "[", "k", "]", "=", "{", "}", "recursive_update", "(", "target", "[", "k", "]", ",", "v", ")", "if", "not", "target", "[", "k", "]", ":", "# Prune empty subdicts", "del", "target", "[", "k", "]", "elif", "v", "is", "None", ":", "target", ".", "pop", "(", "k", ",", "None", ")", "else", ":", "target", "[", "k", "]", "=", "v" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/config/manager.py#L14-L32
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/utils.py
python
percent_encode_sequence
(mapping, safe=SAFE_CHARS)
return '&'.join(encoded_pairs)
Urlencode a dict or list into a string. This is similar to urllib.urlencode except that: * It uses quote, and not quote_plus * It has a default list of safe chars that don't need to be encoded, which matches what AWS services expect. If any value in the input ``mapping`` is a list type, then each list element wil be serialized. This is the equivalent to ``urlencode``'s ``doseq=True`` argument. This function should be preferred over the stdlib ``urlencode()`` function. :param mapping: Either a dict to urlencode or a list of ``(key, value)`` pairs.
Urlencode a dict or list into a string.
[ "Urlencode", "a", "dict", "or", "list", "into", "a", "string", "." ]
def percent_encode_sequence(mapping, safe=SAFE_CHARS): """Urlencode a dict or list into a string. This is similar to urllib.urlencode except that: * It uses quote, and not quote_plus * It has a default list of safe chars that don't need to be encoded, which matches what AWS services expect. If any value in the input ``mapping`` is a list type, then each list element wil be serialized. This is the equivalent to ``urlencode``'s ``doseq=True`` argument. This function should be preferred over the stdlib ``urlencode()`` function. :param mapping: Either a dict to urlencode or a list of ``(key, value)`` pairs. """ encoded_pairs = [] if hasattr(mapping, 'items'): pairs = mapping.items() else: pairs = mapping for key, value in pairs: if isinstance(value, list): for element in value: encoded_pairs.append('%s=%s' % (percent_encode(key), percent_encode(element))) else: encoded_pairs.append('%s=%s' % (percent_encode(key), percent_encode(value))) return '&'.join(encoded_pairs)
[ "def", "percent_encode_sequence", "(", "mapping", ",", "safe", "=", "SAFE_CHARS", ")", ":", "encoded_pairs", "=", "[", "]", "if", "hasattr", "(", "mapping", ",", "'items'", ")", ":", "pairs", "=", "mapping", ".", "items", "(", ")", "else", ":", "pairs", "=", "mapping", "for", "key", ",", "value", "in", "pairs", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "element", "in", "value", ":", "encoded_pairs", ".", "append", "(", "'%s=%s'", "%", "(", "percent_encode", "(", "key", ")", ",", "percent_encode", "(", "element", ")", ")", ")", "else", ":", "encoded_pairs", ".", "append", "(", "'%s=%s'", "%", "(", "percent_encode", "(", "key", ")", ",", "percent_encode", "(", "value", ")", ")", ")", "return", "'&'", ".", "join", "(", "encoded_pairs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/utils.py#L536-L569
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/functions.py
python
Dispatcher.get_impl_key
(self, sig)
return self.get_overload(sig)
Get the implementation key for the given signature.
Get the implementation key for the given signature.
[ "Get", "the", "implementation", "key", "for", "the", "given", "signature", "." ]
def get_impl_key(self, sig): """ Get the implementation key for the given signature. """ return self.get_overload(sig)
[ "def", "get_impl_key", "(", "self", ",", "sig", ")", ":", "return", "self", ".", "get_overload", "(", "sig", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/functions.py#L297-L301
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/context.py
python
Context.scope
(self, framebuffer=None, enable_only=None, *, textures=(), uniform_buffers=(), storage_buffers=(), samplers=(), enable=None)
return res
Create a :py:class:`Scope` object. Args: framebuffer (Framebuffer): The framebuffer to use when entering. enable_only (int): The enable_only flags to set when entering. Keyword Args: textures (list): List of (texture, binding) tuples. uniform_buffers (list): List of (buffer, binding) tuples. storage_buffers (list): List of (buffer, binding) tuples. samplers (list): List of sampler bindings enable (int): Flags to enable for this vao such as depth testing and blending
Create a :py:class:`Scope` object.
[ "Create", "a", ":", "py", ":", "class", ":", "Scope", "object", "." ]
def scope(self, framebuffer=None, enable_only=None, *, textures=(), uniform_buffers=(), storage_buffers=(), samplers=(), enable=None) -> 'Scope': ''' Create a :py:class:`Scope` object. Args: framebuffer (Framebuffer): The framebuffer to use when entering. enable_only (int): The enable_only flags to set when entering. Keyword Args: textures (list): List of (texture, binding) tuples. uniform_buffers (list): List of (buffer, binding) tuples. storage_buffers (list): List of (buffer, binding) tuples. samplers (list): List of sampler bindings enable (int): Flags to enable for this vao such as depth testing and blending ''' if enable is not None: enable_only = enable if framebuffer is None: framebuffer = self.screen mgl_textures = tuple((tex.mglo, idx) for tex, idx in textures) mgl_uniform_buffers = tuple((buf.mglo, idx) for buf, idx in uniform_buffers) mgl_storage_buffers = tuple((buf.mglo, idx) for buf, idx in storage_buffers) res = Scope.__new__(Scope) res.mglo = self.mglo.scope(framebuffer.mglo, enable_only, mgl_textures, mgl_uniform_buffers, mgl_storage_buffers, samplers) res.ctx = self res._framebuffer = framebuffer res._textures = textures res._uniform_buffers = uniform_buffers res._storage_buffers = storage_buffers res._samplers = samplers res.extra = None return res
[ "def", "scope", "(", "self", ",", "framebuffer", "=", "None", ",", "enable_only", "=", "None", ",", "*", ",", "textures", "=", "(", ")", ",", "uniform_buffers", "=", "(", ")", ",", "storage_buffers", "=", "(", ")", ",", "samplers", "=", "(", ")", ",", "enable", "=", "None", ")", "->", "'Scope'", ":", "if", "enable", "is", "not", "None", ":", "enable_only", "=", "enable", "if", "framebuffer", "is", "None", ":", "framebuffer", "=", "self", ".", "screen", "mgl_textures", "=", "tuple", "(", "(", "tex", ".", "mglo", ",", "idx", ")", "for", "tex", ",", "idx", "in", "textures", ")", "mgl_uniform_buffers", "=", "tuple", "(", "(", "buf", ".", "mglo", ",", "idx", ")", "for", "buf", ",", "idx", "in", "uniform_buffers", ")", "mgl_storage_buffers", "=", "tuple", "(", "(", "buf", ".", "mglo", ",", "idx", ")", "for", "buf", ",", "idx", "in", "storage_buffers", ")", "res", "=", "Scope", ".", "__new__", "(", "Scope", ")", "res", ".", "mglo", "=", "self", ".", "mglo", ".", "scope", "(", "framebuffer", ".", "mglo", ",", "enable_only", ",", "mgl_textures", ",", "mgl_uniform_buffers", ",", "mgl_storage_buffers", ",", "samplers", ")", "res", ".", "ctx", "=", "self", "res", ".", "_framebuffer", "=", "framebuffer", "res", ".", "_textures", "=", "textures", "res", ".", "_uniform_buffers", "=", "uniform_buffers", "res", ".", "_storage_buffers", "=", "storage_buffers", "res", ".", "_samplers", "=", "samplers", "res", ".", "extra", "=", "None", "return", "res" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/context.py#L1464-L1501
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBMemoryRegionInfo.IsReadable
(self)
return _lldb.SBMemoryRegionInfo_IsReadable(self)
IsReadable(self) -> bool
IsReadable(self) -> bool
[ "IsReadable", "(", "self", ")", "-", ">", "bool" ]
def IsReadable(self): """IsReadable(self) -> bool""" return _lldb.SBMemoryRegionInfo_IsReadable(self)
[ "def", "IsReadable", "(", "self", ")", ":", "return", "_lldb", ".", "SBMemoryRegionInfo_IsReadable", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5838-L5840
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgitb.py
python
scanvars
(reader, frame, locals)
return vars
Scan one logical line of Python and look up values of variables used.
Scan one logical line of Python and look up values of variables used.
[ "Scan", "one", "logical", "line", "of", "Python", "and", "look", "up", "values", "of", "variables", "used", "." ]
def scanvars(reader, frame, locals): """Scan one logical line of Python and look up values of variables used.""" vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__ for ttype, token, start, end, line in tokenize.generate_tokens(reader): if ttype == tokenize.NEWLINE: break if ttype == tokenize.NAME and token not in keyword.kwlist: if lasttoken == '.': if parent is not __UNDEF__: value = getattr(parent, token, __UNDEF__) vars.append((prefix + token, prefix, value)) else: where, value = lookup(token, frame, locals) vars.append((token, where, value)) elif token == '.': prefix += lasttoken + '.' parent = value else: parent, prefix = None, '' lasttoken = token return vars
[ "def", "scanvars", "(", "reader", ",", "frame", ",", "locals", ")", ":", "vars", ",", "lasttoken", ",", "parent", ",", "prefix", ",", "value", "=", "[", "]", ",", "None", ",", "None", ",", "''", ",", "__UNDEF__", "for", "ttype", ",", "token", ",", "start", ",", "end", ",", "line", "in", "tokenize", ".", "generate_tokens", "(", "reader", ")", ":", "if", "ttype", "==", "tokenize", ".", "NEWLINE", ":", "break", "if", "ttype", "==", "tokenize", ".", "NAME", "and", "token", "not", "in", "keyword", ".", "kwlist", ":", "if", "lasttoken", "==", "'.'", ":", "if", "parent", "is", "not", "__UNDEF__", ":", "value", "=", "getattr", "(", "parent", ",", "token", ",", "__UNDEF__", ")", "vars", ".", "append", "(", "(", "prefix", "+", "token", ",", "prefix", ",", "value", ")", ")", "else", ":", "where", ",", "value", "=", "lookup", "(", "token", ",", "frame", ",", "locals", ")", "vars", ".", "append", "(", "(", "token", ",", "where", ",", "value", ")", ")", "elif", "token", "==", "'.'", ":", "prefix", "+=", "lasttoken", "+", "'.'", "parent", "=", "value", "else", ":", "parent", ",", "prefix", "=", "None", ",", "''", "lasttoken", "=", "token", "return", "vars" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgitb.py#L80-L99
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/utils/io.py
python
Tee.close
(self)
Close the file and restore the channel.
Close the file and restore the channel.
[ "Close", "the", "file", "and", "restore", "the", "channel", "." ]
def close(self): """Close the file and restore the channel.""" self.flush() setattr(sys, self.channel, self.ostream) self.file.close() self._closed = True
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "setattr", "(", "sys", ",", "self", ".", "channel", ",", "self", ".", "ostream", ")", "self", ".", "file", ".", "close", "(", ")", "self", ".", "_closed", "=", "True" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/io.py#L137-L142
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/evaluator.py
python
Evaluator.track_metric
(self, metric)
return metric
Add a Metric to be tracked. Metrics can only be tracked by one `Evaluator`. Metrics must be tracked or they will not appear in `all_metric_results()`. Args: metric: A `Metric` object. Returns: The `metric` passed into this function. Raises: RuntimeError: If called before __init__. TypeError: If `metric` is not of the correct type. ValueError: If there is a name collision between Metrics or `metric` has already been added to another `Evaluator`.
Add a Metric to be tracked.
[ "Add", "a", "Metric", "to", "be", "tracked", "." ]
def track_metric(self, metric): """Add a Metric to be tracked. Metrics can only be tracked by one `Evaluator`. Metrics must be tracked or they will not appear in `all_metric_results()`. Args: metric: A `Metric` object. Returns: The `metric` passed into this function. Raises: RuntimeError: If called before __init__. TypeError: If `metric` is not of the correct type. ValueError: If there is a name collision between Metrics or `metric` has already been added to another `Evaluator`. """ if not hasattr(self, "_metrics"): raise RuntimeError( "Need to call Evaluator.__init__ before adding metrics") if not isinstance(metric, metrics.Metric): raise TypeError( "Evaluator.track_metric() passed type %s, not a tfe.metrics.Metric" % (type(metric),)) if metric.name in self._metrics: if metric is self._metrics[metric.name]: return metric raise ValueError( "Attempt to add two Metrics with the name '%s' to the same Evaluator " "'%s'" % (metric.name, self.name)) # pylint: disable=protected-access if hasattr(metric, "_added_to_an_evaluator"): raise ValueError("Metric %s already added to Evaluator %s" % (metric.name, metric._added_to_an_evaluator)) metric._added_to_an_evaluator = self.__class__.__name__ # pylint: enable=protected-access self._metrics[metric.name] = metric return metric
[ "def", "track_metric", "(", "self", ",", "metric", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_metrics\"", ")", ":", "raise", "RuntimeError", "(", "\"Need to call Evaluator.__init__ before adding metrics\"", ")", "if", "not", "isinstance", "(", "metric", ",", "metrics", ".", "Metric", ")", ":", "raise", "TypeError", "(", "\"Evaluator.track_metric() passed type %s, not a tfe.metrics.Metric\"", "%", "(", "type", "(", "metric", ")", ",", ")", ")", "if", "metric", ".", "name", "in", "self", ".", "_metrics", ":", "if", "metric", "is", "self", ".", "_metrics", "[", "metric", ".", "name", "]", ":", "return", "metric", "raise", "ValueError", "(", "\"Attempt to add two Metrics with the name '%s' to the same Evaluator \"", "\"'%s'\"", "%", "(", "metric", ".", "name", ",", "self", ".", "name", ")", ")", "# pylint: disable=protected-access", "if", "hasattr", "(", "metric", ",", "\"_added_to_an_evaluator\"", ")", ":", "raise", "ValueError", "(", "\"Metric %s already added to Evaluator %s\"", "%", "(", "metric", ".", "name", ",", "metric", ".", "_added_to_an_evaluator", ")", ")", "metric", ".", "_added_to_an_evaluator", "=", "self", ".", "__class__", ".", "__name__", "# pylint: enable=protected-access", "self", ".", "_metrics", "[", "metric", ".", "name", "]", "=", "metric", "return", "metric" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/evaluator.py#L241-L279
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/run_config.py
python
_get_master
(cluster_spec, task_type, task_id)
return ''
Returns the appropriate string for the TensorFlow master.
Returns the appropriate string for the TensorFlow master.
[ "Returns", "the", "appropriate", "string", "for", "the", "TensorFlow", "master", "." ]
def _get_master(cluster_spec, task_type, task_id): """Returns the appropriate string for the TensorFlow master.""" if not cluster_spec: return '' # If there is only one node in the cluster, do things locally. jobs = cluster_spec.jobs if len(jobs) == 1 and len(cluster_spec.job_tasks(jobs[0])) == 1: return '' # Lookup the master in cluster_spec using task_type and task_id, # if possible. if task_type: if task_type not in jobs: raise ValueError( '%s is not a valid task_type in the cluster_spec:\n' '%s\n\n' 'Note that these values may be coming from the TF_CONFIG environment ' 'variable.' % (task_type, cluster_spec)) addresses = cluster_spec.job_tasks(task_type) if task_id >= len(addresses) or task_id < 0: raise ValueError( '%d is not a valid task_id for task_type %s in the ' 'cluster_spec:\n' '%s\n\n' 'Note that these value may be coming from the TF_CONFIG environment ' 'variable.' % (task_id, task_type, cluster_spec)) return 'grpc://' + addresses[task_id] # For backwards compatibility, we return empty string if task_type was # not set (task_type did not previously exist). return ''
[ "def", "_get_master", "(", "cluster_spec", ",", "task_type", ",", "task_id", ")", ":", "if", "not", "cluster_spec", ":", "return", "''", "# If there is only one node in the cluster, do things locally.", "jobs", "=", "cluster_spec", ".", "jobs", "if", "len", "(", "jobs", ")", "==", "1", "and", "len", "(", "cluster_spec", ".", "job_tasks", "(", "jobs", "[", "0", "]", ")", ")", "==", "1", ":", "return", "''", "# Lookup the master in cluster_spec using task_type and task_id,", "# if possible.", "if", "task_type", ":", "if", "task_type", "not", "in", "jobs", ":", "raise", "ValueError", "(", "'%s is not a valid task_type in the cluster_spec:\\n'", "'%s\\n\\n'", "'Note that these values may be coming from the TF_CONFIG environment '", "'variable.'", "%", "(", "task_type", ",", "cluster_spec", ")", ")", "addresses", "=", "cluster_spec", ".", "job_tasks", "(", "task_type", ")", "if", "task_id", ">=", "len", "(", "addresses", ")", "or", "task_id", "<", "0", ":", "raise", "ValueError", "(", "'%d is not a valid task_id for task_type %s in the '", "'cluster_spec:\\n'", "'%s\\n\\n'", "'Note that these value may be coming from the TF_CONFIG environment '", "'variable.'", "%", "(", "task_id", ",", "task_type", ",", "cluster_spec", ")", ")", "return", "'grpc://'", "+", "addresses", "[", "task_id", "]", "# For backwards compatibility, we return empty string if task_type was", "# not set (task_type did not previously exist).", "return", "''" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/run_config.py#L446-L477
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/history.py
python
HistoryAccessor.__init__
(self, profile='default', hist_file=u'', **traits)
Create a new history accessor. Parameters ---------- profile : str The name of the profile from which to open history. hist_file : str Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile. config : :class:`~traitlets.config.loader.Config` Config object. hist_file can also be set through this.
Create a new history accessor. Parameters ---------- profile : str The name of the profile from which to open history. hist_file : str Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile. config : :class:`~traitlets.config.loader.Config` Config object. hist_file can also be set through this.
[ "Create", "a", "new", "history", "accessor", ".", "Parameters", "----------", "profile", ":", "str", "The", "name", "of", "the", "profile", "from", "which", "to", "open", "history", ".", "hist_file", ":", "str", "Path", "to", "an", "SQLite", "history", "database", "stored", "by", "IPython", ".", "If", "specified", "hist_file", "overrides", "profile", ".", "config", ":", ":", "class", ":", "~traitlets", ".", "config", ".", "loader", ".", "Config", "Config", "object", ".", "hist_file", "can", "also", "be", "set", "through", "this", "." ]
def __init__(self, profile='default', hist_file=u'', **traits): """Create a new history accessor. Parameters ---------- profile : str The name of the profile from which to open history. hist_file : str Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile. config : :class:`~traitlets.config.loader.Config` Config object. hist_file can also be set through this. """ # We need a pointer back to the shell for various tasks. super(HistoryAccessor, self).__init__(**traits) # defer setting hist_file from kwarg until after init, # otherwise the default kwarg value would clobber any value # set by config if hist_file: self.hist_file = hist_file if self.hist_file == u'': # No one has set the hist_file, yet. self.hist_file = self._get_hist_file_name(profile) if sqlite3 is None and self.enabled: warn("IPython History requires SQLite, your history will not be saved") self.enabled = False self.init_db()
[ "def", "__init__", "(", "self", ",", "profile", "=", "'default'", ",", "hist_file", "=", "u''", ",", "*", "*", "traits", ")", ":", "# We need a pointer back to the shell for various tasks.", "super", "(", "HistoryAccessor", ",", "self", ")", ".", "__init__", "(", "*", "*", "traits", ")", "# defer setting hist_file from kwarg until after init,", "# otherwise the default kwarg value would clobber any value", "# set by config", "if", "hist_file", ":", "self", ".", "hist_file", "=", "hist_file", "if", "self", ".", "hist_file", "==", "u''", ":", "# No one has set the hist_file, yet.", "self", ".", "hist_file", "=", "self", ".", "_get_hist_file_name", "(", "profile", ")", "if", "sqlite3", "is", "None", "and", "self", ".", "enabled", ":", "warn", "(", "\"IPython History requires SQLite, your history will not be saved\"", ")", "self", ".", "enabled", "=", "False", "self", ".", "init_db", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/history.py#L200-L229
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/aoc/upgrade_resource_subprocessor.py
python
AoCUpgradeResourceSubprocessor.starting_stone_upgrade
(converter_group, value, operator, team=False)
return patches
Creates a patch for the starting stone modify effect (ID: 93). :param converter_group: Tech/Civ that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param value: Value used for patching the member. :type value: MemberOperator :param operator: Operator used for patching the member. :type operator: MemberOperator :returns: The forward references for the generated patches. :rtype: list
Creates a patch for the starting stone modify effect (ID: 93).
[ "Creates", "a", "patch", "for", "the", "starting", "stone", "modify", "effect", "(", "ID", ":", "93", ")", "." ]
def starting_stone_upgrade(converter_group, value, operator, team=False): """ Creates a patch for the starting stone modify effect (ID: 93). :param converter_group: Tech/Civ that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param value: Value used for patching the member. :type value: MemberOperator :param operator: Operator used for patching the member. :type operator: MemberOperator :returns: The forward references for the generated patches. :rtype: list """ patches = [] # TODO: Implement return patches
[ "def", "starting_stone_upgrade", "(", "converter_group", ",", "value", ",", "operator", ",", "team", "=", "False", ")", ":", "patches", "=", "[", "]", "# TODO: Implement", "return", "patches" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/upgrade_resource_subprocessor.py#L1104-L1121
stan-dev/math
5fd79f89933269a4ca4d8dd1fde2a36d53d4768c
lib/boost_1.75.0/tools/build/src/build/virtual_target.py
python
NotFileTarget.path
(self)
return None
Returns nothing, to indicate that target path is not known.
Returns nothing, to indicate that target path is not known.
[ "Returns", "nothing", "to", "indicate", "that", "target", "path", "is", "not", "known", "." ]
def path(self): """Returns nothing, to indicate that target path is not known.""" return None
[ "def", "path", "(", "self", ")", ":", "return", "None" ]
https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/virtual_target.py#L753-L755
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/ansic/cparse.py
python
p_type_name
(t)
type_name : specifier_qualifier_list abstract_declarator_opt
type_name : specifier_qualifier_list abstract_declarator_opt
[ "type_name", ":", "specifier_qualifier_list", "abstract_declarator_opt" ]
def p_type_name(t): 'type_name : specifier_qualifier_list abstract_declarator_opt' pass
[ "def", "p_type_name", "(", "t", ")", ":", "pass" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L385-L387
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/displaypub.py
python
DisplayPublisher.clear_output
(self, wait=False)
Clear the output of the cell receiving output.
Clear the output of the cell receiving output.
[ "Clear", "the", "output", "of", "the", "cell", "receiving", "output", "." ]
def clear_output(self, wait=False): """Clear the output of the cell receiving output.""" print('\033[2K\r', end='') sys.stdout.flush() print('\033[2K\r', end='') sys.stderr.flush()
[ "def", "clear_output", "(", "self", ",", "wait", "=", "False", ")", ":", "print", "(", "'\\033[2K\\r'", ",", "end", "=", "''", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "print", "(", "'\\033[2K\\r'", ",", "end", "=", "''", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/displaypub.py#L118-L123
ampl/mp
cad8d370089a76507cb9c5518c21a1097f4a504b
support/build-docs.py
python
copy_content
(src_dir, dst_dir)
Copy content of the src_dir to dst_dir recursively.
Copy content of the src_dir to dst_dir recursively.
[ "Copy", "content", "of", "the", "src_dir", "to", "dst_dir", "recursively", "." ]
def copy_content(src_dir, dst_dir): "Copy content of the src_dir to dst_dir recursively." for entry in os.listdir(src_dir): src = os.path.join(src_dir, entry) dst = os.path.join(dst_dir, entry) if os.path.isdir(src): fileutil.rmtree_if_exists(dst) shutil.copytree(src, dst) else: shutil.copyfile(src, dst)
[ "def", "copy_content", "(", "src_dir", ",", "dst_dir", ")", ":", "for", "entry", "in", "os", ".", "listdir", "(", "src_dir", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "src_dir", ",", "entry", ")", "dst", "=", "os", ".", "path", ".", "join", "(", "dst_dir", ",", "entry", ")", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "fileutil", ".", "rmtree_if_exists", "(", "dst", ")", "shutil", ".", "copytree", "(", "src", ",", "dst", ")", "else", ":", "shutil", ".", "copyfile", "(", "src", ",", "dst", ")" ]
https://github.com/ampl/mp/blob/cad8d370089a76507cb9c5518c21a1097f4a504b/support/build-docs.py#L68-L77
mkeeter/antimony
ee525bbdad34ae94879fd055821f92bcef74e83f
py/fab/shapes.py
python
revolve_xy_y
(a, x)
return move(revolve_y(move(a, -x, 0)), x, 0)
Revolves the given shape about the y-axis (offset by the given x value)
Revolves the given shape about the y-axis (offset by the given x value)
[ "Revolves", "the", "given", "shape", "about", "the", "y", "-", "axis", "(", "offset", "by", "the", "given", "x", "value", ")" ]
def revolve_xy_y(a, x): """ Revolves the given shape about the y-axis (offset by the given x value) """ return move(revolve_y(move(a, -x, 0)), x, 0)
[ "def", "revolve_xy_y", "(", "a", ",", "x", ")", ":", "return", "move", "(", "revolve_y", "(", "move", "(", "a", ",", "-", "x", ",", "0", ")", ")", ",", "x", ",", "0", ")" ]
https://github.com/mkeeter/antimony/blob/ee525bbdad34ae94879fd055821f92bcef74e83f/py/fab/shapes.py#L760-L764
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/regression/scripts/utils/RiemannSolver/riemann.py
python
StateVector.ram
(self)
return self.p + self.rho * self.u ** 2
Computes ram pressure.
Computes ram pressure.
[ "Computes", "ram", "pressure", "." ]
def ram(self): """Computes ram pressure.""" return self.p + self.rho * self.u ** 2
[ "def", "ram", "(", "self", ")", ":", "return", "self", ".", "p", "+", "self", ".", "rho", "*", "self", ".", "u", "**", "2" ]
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/regression/scripts/utils/RiemannSolver/riemann.py#L42-L44