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
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/training/training_ops.py
python
_ApplyProximalGradientDescentShape
(op)
return [delta_shape]
Shape function for the ApplyProximalGradientDescent op.
Shape function for the ApplyProximalGradientDescent op.
[ "Shape", "function", "for", "the", "ApplyProximalGradientDescent", "op", "." ]
def _ApplyProximalGradientDescentShape(op): """Shape function for the ApplyProximalGradientDescent op.""" var_shape = op.inputs[0].get_shape() _AssertInputIsScalar(op, 1) # alpha _AssertInputIsScalar(op, 2) # l1 _AssertInputIsScalar(op, 3) # l2 delta_shape = op.inputs[4].get_shape().merge_with(var_shape) return [delta_shape]
[ "def", "_ApplyProximalGradientDescentShape", "(", "op", ")", ":", "var_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "_AssertInputIsScalar", "(", "op", ",", "1", ")", "# alpha", "_AssertInputIsScalar", "(", "op", ",", "2", ")...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/training_ops.py#L149-L156
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/utils/watchdog_timer.py
python
WatchdogTimer.__init__
(self, timeout)
Initializes the watchdog. Args: timeout: The timeout in seconds. If timeout is None it will never timeout.
Initializes the watchdog.
[ "Initializes", "the", "watchdog", "." ]
def __init__(self, timeout): """Initializes the watchdog. Args: timeout: The timeout in seconds. If timeout is None it will never timeout. """ self._start_time = time.time() self._timeout = timeout
[ "def", "__init__", "(", "self", ",", "timeout", ")", ":", "self", ".", "_start_time", "=", "time", ".", "time", "(", ")", "self", ".", "_timeout", "=", "timeout" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/utils/watchdog_timer.py#L16-L23
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/random.py
python
rotl
(x, k)
return (x << k) | (x >> uint32(64 - k))
Left rotate x by k bits.
Left rotate x by k bits.
[ "Left", "rotate", "x", "by", "k", "bits", "." ]
def rotl(x, k): '''Left rotate x by k bits.''' x = uint64(x) k = uint32(k) return (x << k) | (x >> uint32(64 - k))
[ "def", "rotl", "(", "x", ",", "k", ")", ":", "x", "=", "uint64", "(", "x", ")", "k", "=", "uint32", "(", "k", ")", "return", "(", "x", "<<", "k", ")", "|", "(", "x", ">>", "uint32", "(", "64", "-", "k", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/random.py#L64-L68
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
ipc/ipdl/ipdl/parser.py
python
Parser.resolveIncludePath
(self, filepath)
return None
Return the absolute path from which the possibly partial |filepath| should be read, or |None| if |filepath| cannot be located.
Return the absolute path from which the possibly partial |filepath| should be read, or |None| if |filepath| cannot be located.
[ "Return", "the", "absolute", "path", "from", "which", "the", "possibly", "partial", "|filepath|", "should", "be", "read", "or", "|None|", "if", "|filepath|", "cannot", "be", "located", "." ]
def resolveIncludePath(self, filepath): '''Return the absolute path from which the possibly partial |filepath| should be read, or |None| if |filepath| cannot be located.''' for incdir in self.includedirs +[ '' ]: realpath = os.path.join(incdir, filepath) if os.path.isfile(realpath): return os.path.abspath(realpath) return None
[ "def", "resolveIncludePath", "(", "self", ",", "filepath", ")", ":", "for", "incdir", "in", "self", ".", "includedirs", "+", "[", "''", "]", ":", "realpath", "=", "os", ".", "path", ".", "join", "(", "incdir", ",", "filepath", ")", "if", "os", ".", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/ipc/ipdl/ipdl/parser.py#L88-L95
acbull/Unbiased_LambdaMart
7c39abe5caa18ca07df2d23c2db392916d92956c
Unbias_LightGBM/python-package/lightgbm/basic.py
python
Booster.attr
(self, key)
return self.__attr.get(key, None)
Get attribute string from the Booster. Parameters ---------- key : string The name of the attribute. Returns ------- value : string or None The attribute value. Returns None if attribute do not exist.
Get attribute string from the Booster.
[ "Get", "attribute", "string", "from", "the", "Booster", "." ]
def attr(self, key): """Get attribute string from the Booster. Parameters ---------- key : string The name of the attribute. Returns ------- value : string or None The attribute value. Returns None if attribute do not exist. """ return self.__attr.get(key, None)
[ "def", "attr", "(", "self", ",", "key", ")", ":", "return", "self", ".", "__attr", ".", "get", "(", "key", ",", "None", ")" ]
https://github.com/acbull/Unbiased_LambdaMart/blob/7c39abe5caa18ca07df2d23c2db392916d92956c/Unbias_LightGBM/python-package/lightgbm/basic.py#L1987-L2001
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextBuffer.SetStyleSheetAndNotify
(*args, **kwargs)
return _richtext.RichTextBuffer_SetStyleSheetAndNotify(*args, **kwargs)
SetStyleSheetAndNotify(self, wxRichTextStyleSheet sheet) -> bool
SetStyleSheetAndNotify(self, wxRichTextStyleSheet sheet) -> bool
[ "SetStyleSheetAndNotify", "(", "self", "wxRichTextStyleSheet", "sheet", ")", "-", ">", "bool" ]
def SetStyleSheetAndNotify(*args, **kwargs): """SetStyleSheetAndNotify(self, wxRichTextStyleSheet sheet) -> bool""" return _richtext.RichTextBuffer_SetStyleSheetAndNotify(*args, **kwargs)
[ "def", "SetStyleSheetAndNotify", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_SetStyleSheetAndNotify", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2217-L2219
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/random/rng.py
python
RNG.uniform
( self, low: float = 0, high: float = 1, size: Optional[Iterable[int]] = None )
return _uniform( low=low, high=high, size=size, seed=_seed, device=self._device, handle=self._handle, )
r"""Random variable with uniform distribution $U(0, 1)$. Args: low: lower range. Default: 0 high: upper range. Default: 1 size: the size of output tensor. Default: None Returns: the output tensor. Examples: .. testcode:: import megengine as mge import megengine.random as rand x = rand.uniform(size=(2, 2)) print(x.numpy()) Outputs: .. testoutput:: :options: +SKIP [[0.91600335 0.6680226 ] [0.2046729 0.2769141 ]]
r"""Random variable with uniform distribution $U(0, 1)$.
[ "r", "Random", "variable", "with", "uniform", "distribution", "$U", "(", "0", "1", ")", "$", "." ]
def uniform( self, low: float = 0, high: float = 1, size: Optional[Iterable[int]] = None ): r"""Random variable with uniform distribution $U(0, 1)$. Args: low: lower range. Default: 0 high: upper range. Default: 1 size: the size of output tensor. Default: None Returns: the output tensor. Examples: .. testcode:: import megengine as mge import megengine.random as rand x = rand.uniform(size=(2, 2)) print(x.numpy()) Outputs: .. testoutput:: :options: +SKIP [[0.91600335 0.6680226 ] [0.2046729 0.2769141 ]] """ _seed = self._seed() if callable(self._seed) else self._seed return _uniform( low=low, high=high, size=size, seed=_seed, device=self._device, handle=self._handle, )
[ "def", "uniform", "(", "self", ",", "low", ":", "float", "=", "0", ",", "high", ":", "float", "=", "1", ",", "size", ":", "Optional", "[", "Iterable", "[", "int", "]", "]", "=", "None", ")", ":", "_seed", "=", "self", ".", "_seed", "(", ")", ...
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/random/rng.py#L272-L311
notepad-plus-plus/notepad-plus-plus
d372894e784afd3d224e9d4d03ae679ba6312788
scintilla/scripts/FileGenerator.py
python
UpdateFile
(filename, updated)
If the file contents are different to updated then copy updated into the file else leave alone so Mercurial and make don't treat it as modified.
If the file contents are different to updated then copy updated into the file else leave alone so Mercurial and make don't treat it as modified.
[ "If", "the", "file", "contents", "are", "different", "to", "updated", "then", "copy", "updated", "into", "the", "file", "else", "leave", "alone", "so", "Mercurial", "and", "make", "don", "t", "treat", "it", "as", "modified", "." ]
def UpdateFile(filename, updated): """ If the file contents are different to updated then copy updated into the file else leave alone so Mercurial and make don't treat it as modified. """ newOrChanged = "Changed" try: with codecs.open(filename, "r", "utf-8") as infile: original = infile.read() if updated == original: # Same as before so don't write return os.unlink(filename) except IOError: # File is not there yet newOrChanged = "New" with codecs.open(filename, "w", "utf-8") as outfile: outfile.write(updated) print("%s %s" % (newOrChanged, filename))
[ "def", "UpdateFile", "(", "filename", ",", "updated", ")", ":", "newOrChanged", "=", "\"Changed\"", "try", ":", "with", "codecs", ".", "open", "(", "filename", ",", "\"r\"", ",", "\"utf-8\"", ")", "as", "infile", ":", "original", "=", "infile", ".", "rea...
https://github.com/notepad-plus-plus/notepad-plus-plus/blob/d372894e784afd3d224e9d4d03ae679ba6312788/scintilla/scripts/FileGenerator.py#L20-L35
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/markers.py
python
Evaluator.evaluate
(self, expr, context)
return result
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
[ "Evaluate", "a", "marker", "expression", "returned", "by", "the", ":", "func", ":", "parse_requirement", "function", "in", "the", "specified", "context", "." ]
def evaluate(self, expr, context): """ Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. """ if isinstance(expr, string_types): if expr[0] in '\'"': result = expr[1:-1] else: if expr not in context: raise SyntaxError('unknown variable: %s' % expr) result = context[expr] else: assert isinstance(expr, dict) op = expr['op'] if op not in self.operations: raise NotImplementedError('op not implemented: %s' % op) elhs = expr['lhs'] erhs = expr['rhs'] if _is_literal(expr['lhs']) and _is_literal(expr['rhs']): raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs)) lhs = self.evaluate(elhs, context) rhs = self.evaluate(erhs, context) result = self.operations[op](lhs, rhs) return result
[ "def", "evaluate", "(", "self", ",", "expr", ",", "context", ")", ":", "if", "isinstance", "(", "expr", ",", "string_types", ")", ":", "if", "expr", "[", "0", "]", "in", "'\\'\"'", ":", "result", "=", "expr", "[", "1", ":", "-", "1", "]", "else",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/markers.py#L50-L75
p3/regal
184c62b7d7761481609ef1c1484ada659ae181b9
scripts/xml/khronos/reg.py
python
Registry.setGenerator
(self, gen)
Specify output generator object. None restores the default generator
Specify output generator object. None restores the default generator
[ "Specify", "output", "generator", "object", ".", "None", "restores", "the", "default", "generator" ]
def setGenerator(self, gen): """Specify output generator object. None restores the default generator""" self.gen = gen
[ "def", "setGenerator", "(", "self", ",", "gen", ")", ":", "self", ".", "gen", "=", "gen" ]
https://github.com/p3/regal/blob/184c62b7d7761481609ef1c1484ada659ae181b9/scripts/xml/khronos/reg.py#L699-L701
neo-ai/neo-ai-dlr
bf397aa0367a5207654c00d2985f900d94ad1543
python/dlr/dlr_model.py
python
DLRModelImpl._set_input
(self, name, data)
Set the input using the input name with data Parameters __________ name : str The name of an input. data : list of numbers The data to be set.
Set the input using the input name with data
[ "Set", "the", "input", "using", "the", "input", "name", "with", "data" ]
def _set_input(self, name, data): """Set the input using the input name with data Parameters __________ name : str The name of an input. data : list of numbers The data to be set. """ input_dtype = self._get_input_or_weight_dtype_by_name(name) if input_dtype == "json": # Special case for DataTransformed inputs. DLR will expect input as a serialized json # string. in_data = json.dumps(data.tolist()) in_data_pointer = c_char_p(in_data.encode('utf-8')) shape = np.array([len(in_data)], dtype=np.int64) else: # float32 inputs can accept any data (backward compatibility). if input_dtype == "float32": type_match = True else: type_match = (data.dtype.name == input_dtype) if not type_match: raise ValueError("input data with name {} should have dtype {} but {} is provided". format(name, input_dtype, data.dtype.name)) in_data = np.ascontiguousarray(data, dtype=input_dtype) in_data_pointer = in_data.ctypes._as_parameter_ shape = np.array(in_data.shape, dtype=np.int64) self.input_shapes[name] = shape self._check_call(self._lib.SetDLRInput(byref(self.handle), c_char_p(name.encode('utf-8')), shape.ctypes.data_as(POINTER(c_longlong)), in_data_pointer, c_int(len(shape)))) # This helps to determine output batch size only # Treelite model output shape will be know only after the model run if self.backend == "treelite": self._lazy_init_output_shape()
[ "def", "_set_input", "(", "self", ",", "name", ",", "data", ")", ":", "input_dtype", "=", "self", ".", "_get_input_or_weight_dtype_by_name", "(", "name", ")", "if", "input_dtype", "==", "\"json\"", ":", "# Special case for DataTransformed inputs. DLR will expect input a...
https://github.com/neo-ai/neo-ai-dlr/blob/bf397aa0367a5207654c00d2985f900d94ad1543/python/dlr/dlr_model.py#L293-L331
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/text/datasets/wmt14.py
python
WMT14.get_dict
(self, reverse=False)
return src_dict, trg_dict
Get the source and target dictionary. Args: reverse (bool): wether to reverse key and value in dictionary, i.e. key: value to value: key. Returns: Two dictionaries, the source and target dictionary. Examples: .. code-block:: python from paddle.text.datasets import WMT14 wmt14 = WMT14(mode='train', dict_size=50) src_dict, trg_dict = wmt14.get_dict()
Get the source and target dictionary.
[ "Get", "the", "source", "and", "target", "dictionary", "." ]
def get_dict(self, reverse=False): """ Get the source and target dictionary. Args: reverse (bool): wether to reverse key and value in dictionary, i.e. key: value to value: key. Returns: Two dictionaries, the source and target dictionary. Examples: .. code-block:: python from paddle.text.datasets import WMT14 wmt14 = WMT14(mode='train', dict_size=50) src_dict, trg_dict = wmt14.get_dict() """ src_dict, trg_dict = self.src_dict, self.trg_dict if reverse: src_dict = {v: k for k, v in six.iteritems(src_dict)} trg_dict = {v: k for k, v in six.iteritems(trg_dict)} return src_dict, trg_dict
[ "def", "get_dict", "(", "self", ",", "reverse", "=", "False", ")", ":", "src_dict", ",", "trg_dict", "=", "self", ".", "src_dict", ",", "self", ".", "trg_dict", "if", "reverse", ":", "src_dict", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/text/datasets/wmt14.py#L174-L197
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py
python
spawn.eof
(self)
return self.flag_eof
This returns True if the EOF exception was ever raised.
This returns True if the EOF exception was ever raised.
[ "This", "returns", "True", "if", "the", "EOF", "exception", "was", "ever", "raised", "." ]
def eof(self): '''This returns True if the EOF exception was ever raised. ''' return self.flag_eof
[ "def", "eof", "(", "self", ")", ":", "return", "self", ".", "flag_eof" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py#L604-L607
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/analogclock/analogclock.py
python
AnalogClock.SetHandBorderColour
(self, colour, target=ALL)
Sets border colours of hands.
Sets border colours of hands.
[ "Sets", "border", "colours", "of", "hands", "." ]
def SetHandBorderColour(self, colour, target=ALL): """Sets border colours of hands.""" self.Hands.SetBorderColour(colour, target)
[ "def", "SetHandBorderColour", "(", "self", ",", "colour", ",", "target", "=", "ALL", ")", ":", "self", ".", "Hands", ".", "SetBorderColour", "(", "colour", ",", "target", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/analogclock/analogclock.py#L352-L355
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/functional/elemwise.py
python
not_equal
(x, y)
return x != y
r"""Element-wise `(x != y)`.
r"""Element-wise `(x != y)`.
[ "r", "Element", "-", "wise", "(", "x", "!", "=", "y", ")", "." ]
def not_equal(x, y): r"""Element-wise `(x != y)`.""" return x != y
[ "def", "not_equal", "(", "x", ",", "y", ")", ":", "return", "x", "!=", "y" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/elemwise.py#L493-L495
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/sessions.py
python
merge_setting
(request_setting, session_setting, dict_class=OrderedDict)
return merged_setting
Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class`
Determines appropriate setting for a given request, taking into account
[ "Determines", "appropriate", "setting", "for", "a", "given", "request", "taking", "into", "account" ]
def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. none_keys = [k for (k, v) in merged_setting.items() if v is None] for key in none_keys: del merged_setting[key] return merged_setting
[ "def", "merge_setting", "(", "request_setting", ",", "session_setting", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_setting", "is", "None", ":", "return", "request_setting", "if", "request_setting", "is", "None", ":", "return", "session_setting",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/sessions.py#L99-L155
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/linear_model/stochastic_gradient.py
python
BaseSGDRegressor.decision_function
(self, X)
return self._decision_function(X)
Predict using the linear model Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Returns ------- array, shape (n_samples,) Predicted target values per element in X.
Predict using the linear model
[ "Predict", "using", "the", "linear", "model" ]
def decision_function(self, X): """Predict using the linear model Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Returns ------- array, shape (n_samples,) Predicted target values per element in X. """ return self._decision_function(X)
[ "def", "decision_function", "(", "self", ",", "X", ")", ":", "return", "self", ".", "_decision_function", "(", "X", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/stochastic_gradient.py#L976-L988
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
support/cpplint.py
python
CheckIncludeLine
(filename, clean_lines, linenum, include_state, error)
Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found.
Check rules that are applicable to #include lines.
[ "Check", "rules", "that", "are", "applicable", "to", "#include", "lines", "." ]
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" # Only do this check if the included header follows google naming # conventions. If not, assume that it's a 3rd party API that # requires special include conventions. # # We also make an exception for Lua headers, which follow google # naming convention but not the include convention. match = Match(r'#include\s*"([^/]+\.h)"', line) if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): error(filename, linenum, 'build/include', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') duplicate_line = include_state.FindHeader(include) if duplicate_line >= 0: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, duplicate_line)) elif (include.endswith('.cc') and os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)): error(filename, linenum, 'build/include', 4, 'Do not include .cc files from other packages') elif not _THIRD_PARTY_HEADERS_PATTERN.match(include): include_state.include_list[-1].append((include, linenum)) # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include)
[ "def", "CheckIncludeLine", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "include_state", ",", "error", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename", ")", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "# \"include\" shoul...
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L4526-L4596
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/c_ast.py
python
NodeVisitor.generic_visit
(self, node)
Called if no explicit visitor function exists for a node. Implements preorder visiting of the node.
Called if no explicit visitor function exists for a node. Implements preorder visiting of the node.
[ "Called", "if", "no", "explicit", "visitor", "function", "exists", "for", "a", "node", ".", "Implements", "preorder", "visiting", "of", "the", "node", "." ]
def generic_visit(self, node): """ Called if no explicit visitor function exists for a node. Implements preorder visiting of the node. """ for c in node: self.visit(c)
[ "def", "generic_visit", "(", "self", ",", "node", ")", ":", "for", "c", "in", "node", ":", "self", ".", "visit", "(", "c", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/c_ast.py#L160-L165
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBTypeCategory.GetLanguageAtIndex
(self, idx)
return _lldb.SBTypeCategory_GetLanguageAtIndex(self, idx)
GetLanguageAtIndex(SBTypeCategory self, uint32_t idx) -> lldb::LanguageType
GetLanguageAtIndex(SBTypeCategory self, uint32_t idx) -> lldb::LanguageType
[ "GetLanguageAtIndex", "(", "SBTypeCategory", "self", "uint32_t", "idx", ")", "-", ">", "lldb", "::", "LanguageType" ]
def GetLanguageAtIndex(self, idx): """GetLanguageAtIndex(SBTypeCategory self, uint32_t idx) -> lldb::LanguageType""" return _lldb.SBTypeCategory_GetLanguageAtIndex(self, idx)
[ "def", "GetLanguageAtIndex", "(", "self", ",", "idx", ")", ":", "return", "_lldb", ".", "SBTypeCategory_GetLanguageAtIndex", "(", "self", ",", "idx", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L13067-L13069
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py
python
BasicFittingModel.chi_squared
(self)
return self.fitting_context.chi_squared
Returns all of the chi squared values.
Returns all of the chi squared values.
[ "Returns", "all", "of", "the", "chi", "squared", "values", "." ]
def chi_squared(self) -> list: """Returns all of the chi squared values.""" return self.fitting_context.chi_squared
[ "def", "chi_squared", "(", "self", ")", "->", "list", ":", "return", "self", ".", "fitting_context", ".", "chi_squared" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py#L341-L343
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/base64.py
python
b64encode
(s, altchars=None)
return encoded
Encode the bytes-like object s using Base64 and return a bytes object. Optional altchars should be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings.
Encode the bytes-like object s using Base64 and return a bytes object.
[ "Encode", "the", "bytes", "-", "like", "object", "s", "using", "Base64", "and", "return", "a", "bytes", "object", "." ]
def b64encode(s, altchars=None): """Encode the bytes-like object s using Base64 and return a bytes object. Optional altchars should be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. """ encoded = binascii.b2a_base64(s, newline=False) if altchars is not None: assert len(altchars) == 2, repr(altchars) return encoded.translate(bytes.maketrans(b'+/', altchars)) return encoded
[ "def", "b64encode", "(", "s", ",", "altchars", "=", "None", ")", ":", "encoded", "=", "binascii", ".", "b2a_base64", "(", "s", ",", "newline", "=", "False", ")", "if", "altchars", "is", "not", "None", ":", "assert", "len", "(", "altchars", ")", "==",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/base64.py#L51-L62
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Rect.__init__
(self, *args, **kwargs)
__init__(self, int x=0, int y=0, int width=0, int height=0) -> Rect Create a new Rect object.
__init__(self, int x=0, int y=0, int width=0, int height=0) -> Rect
[ "__init__", "(", "self", "int", "x", "=", "0", "int", "y", "=", "0", "int", "width", "=", "0", "int", "height", "=", "0", ")", "-", ">", "Rect" ]
def __init__(self, *args, **kwargs): """ __init__(self, int x=0, int y=0, int width=0, int height=0) -> Rect Create a new Rect object. """ _core_.Rect_swiginit(self,_core_.new_Rect(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "Rect_swiginit", "(", "self", ",", "_core_", ".", "new_Rect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1260-L1266
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
ActivateEvent.GetActive
(*args, **kwargs)
return _core_.ActivateEvent_GetActive(*args, **kwargs)
GetActive(self) -> bool Returns true if the application or window is being activated, false otherwise.
GetActive(self) -> bool
[ "GetActive", "(", "self", ")", "-", ">", "bool" ]
def GetActive(*args, **kwargs): """ GetActive(self) -> bool Returns true if the application or window is being activated, false otherwise. """ return _core_.ActivateEvent_GetActive(*args, **kwargs)
[ "def", "GetActive", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "ActivateEvent_GetActive", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L6389-L6396
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.GetMouseDwellTime
(*args, **kwargs)
return _stc.StyledTextCtrl_GetMouseDwellTime(*args, **kwargs)
GetMouseDwellTime(self) -> int Retrieve the time the mouse must sit still to generate a mouse dwell event.
GetMouseDwellTime(self) -> int
[ "GetMouseDwellTime", "(", "self", ")", "-", ">", "int" ]
def GetMouseDwellTime(*args, **kwargs): """ GetMouseDwellTime(self) -> int Retrieve the time the mouse must sit still to generate a mouse dwell event. """ return _stc.StyledTextCtrl_GetMouseDwellTime(*args, **kwargs)
[ "def", "GetMouseDwellTime", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetMouseDwellTime", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L4047-L4053
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/importDXF.py
python
getWire
(wire, nospline=False, lw=True, asis=False)
return points
Return a list of DXF ready points and bulges from a wire. It builds a list of points from the edges of a `wire`. If the edges are circular arcs, the "bulge" of that edge is calculated, for other cases, the bulge is considered zero. Parameters ---------- wire : Part::TopoShape ('Wire') A shape representing a wire. nospline : bool, optional It defaults to `False`. If it is `True`, the edges of the wire are not considered as being one of `'BSplineCurve'`, `'BezierCurve'`, or `'Ellipse'`, and a simple point is added to the list. Otherwise, `getSplineSegs(edge)` is used to extract the points and add them to the list. lw : bool, optional It defaults to `True`. If it is `True` it assumes the `wire` is a `'lwpolyline'`. Otherwise, it assumes it is a `'polyline'`. asis : bool, optional It defaults to `False`. If it is `True`, it just returns the points of the vertices of the `wire`, and considers the bulge is zero. Otherwise, it processes the edges of the `wire` and calculates the bulge of the edges if they are of type `'Circle'`. For types of edges that are `'BSplineCurve'`, `'BezierCurve'`, or `'Ellipse'`, the bulge is zero Returns ------- list of tuples It returns a list of tuples ``[(...), (...), ...]`` where each tuple indicates a point with additional information besides the coordinates. Two types of tuples may be returned. [(float, float, float, None, None, float), ...] When `lw` is `True` (`'lwpolyline'`) the first three values represent the coordinates of the point, the next two are `None`, and the last value is the bulge. [((float, float, float), None, [None, None], float), ...] When `lw` is `False` (`'polyline'`) the first element is a tuple of three values that indicate the coordinates of the point, the next element is `None`, the next element is a list of two `None` values, and the last element is the value of the bulge. See also -------- calcBulge
Return a list of DXF ready points and bulges from a wire.
[ "Return", "a", "list", "of", "DXF", "ready", "points", "and", "bulges", "from", "a", "wire", "." ]
def getWire(wire, nospline=False, lw=True, asis=False): """Return a list of DXF ready points and bulges from a wire. It builds a list of points from the edges of a `wire`. If the edges are circular arcs, the "bulge" of that edge is calculated, for other cases, the bulge is considered zero. Parameters ---------- wire : Part::TopoShape ('Wire') A shape representing a wire. nospline : bool, optional It defaults to `False`. If it is `True`, the edges of the wire are not considered as being one of `'BSplineCurve'`, `'BezierCurve'`, or `'Ellipse'`, and a simple point is added to the list. Otherwise, `getSplineSegs(edge)` is used to extract the points and add them to the list. lw : bool, optional It defaults to `True`. If it is `True` it assumes the `wire` is a `'lwpolyline'`. Otherwise, it assumes it is a `'polyline'`. asis : bool, optional It defaults to `False`. If it is `True`, it just returns the points of the vertices of the `wire`, and considers the bulge is zero. Otherwise, it processes the edges of the `wire` and calculates the bulge of the edges if they are of type `'Circle'`. For types of edges that are `'BSplineCurve'`, `'BezierCurve'`, or `'Ellipse'`, the bulge is zero Returns ------- list of tuples It returns a list of tuples ``[(...), (...), ...]`` where each tuple indicates a point with additional information besides the coordinates. Two types of tuples may be returned. [(float, float, float, None, None, float), ...] When `lw` is `True` (`'lwpolyline'`) the first three values represent the coordinates of the point, the next two are `None`, and the last value is the bulge. [((float, float, float), None, [None, None], float), ...] When `lw` is `False` (`'polyline'`) the first element is a tuple of three values that indicate the coordinates of the point, the next element is `None`, the next element is a list of two `None` values, and the last element is the value of the bulge. See also -------- calcBulge """ def fmt(v, b=0.0): if lw: # LWpolyline format return (v.x, v.y, v.z, None, None, b) else: # Polyline format return ((v.x, v.y, v.z), None, [None, None], b) points = [] if asis: points = [fmt(v.Point) for v in wire.OrderedVertexes] else: edges = Part.__sortEdges__(wire.Edges) # print("processing wire ",wire.Edges) for edge in edges: v1 = edge.Vertexes[0].Point if DraftGeomUtils.geomType(edge) == "Circle": # polyline bulge -> negative makes the arc go clockwise angle = edge.LastParameter-edge.FirstParameter bul = math.tan(angle/4) # if cross1[2] < 0: # # polyline bulge -> negative makes the arc go clockwise # bul = -bul if edge.Curve.Axis.dot(Vector(0, 0, 1)) < 0: bul = -bul points.append(fmt(v1, bul)) elif (DraftGeomUtils.geomType(edge) in ["BSplineCurve", "BezierCurve", "Ellipse"]) and (not nospline): spline = getSplineSegs(edge) spline.pop() for p in spline: points.append(fmt(p)) else: points.append(fmt(v1)) if not DraftGeomUtils.isReallyClosed(wire): v = edges[-1].Vertexes[-1].Point points.append(fmt(v)) # print("wire verts: ",points) return points
[ "def", "getWire", "(", "wire", ",", "nospline", "=", "False", ",", "lw", "=", "True", ",", "asis", "=", "False", ")", ":", "def", "fmt", "(", "v", ",", "b", "=", "0.0", ")", ":", "if", "lw", ":", "# LWpolyline format", "return", "(", "v", ".", ...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/importDXF.py#L3034-L3131
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/npytypes.py
python
Record.is_title
(self, key)
return self.fields[key].title == key
Returns True if the field named *key* is a title.
Returns True if the field named *key* is a title.
[ "Returns", "True", "if", "the", "field", "named", "*", "key", "*", "is", "a", "title", "." ]
def is_title(self, key): """Returns True if the field named *key* is a title. """ return self.fields[key].title == key
[ "def", "is_title", "(", "self", ",", "key", ")", ":", "return", "self", ".", "fields", "[", "key", "]", ".", "title", "==", "key" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/npytypes.py#L190-L193
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/mixture/_gaussian_mixture.py
python
_estimate_gaussian_covariances_diag
(resp, X, nk, means, reg_covar)
return avg_X2 - 2 * avg_X_means + avg_means2 + reg_covar
Estimate the diagonal covariance vectors. Parameters ---------- responsibilities : array-like, shape (n_samples, n_components) X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) means : array-like, shape (n_components, n_features) reg_covar : float Returns ------- covariances : array, shape (n_components, n_features) The covariance vector of the current components.
Estimate the diagonal covariance vectors.
[ "Estimate", "the", "diagonal", "covariance", "vectors", "." ]
def _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar): """Estimate the diagonal covariance vectors. Parameters ---------- responsibilities : array-like, shape (n_samples, n_components) X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) means : array-like, shape (n_components, n_features) reg_covar : float Returns ------- covariances : array, shape (n_components, n_features) The covariance vector of the current components. """ avg_X2 = np.dot(resp.T, X * X) / nk[:, np.newaxis] avg_means2 = means ** 2 avg_X_means = means * np.dot(resp.T, X) / nk[:, np.newaxis] return avg_X2 - 2 * avg_X_means + avg_means2 + reg_covar
[ "def", "_estimate_gaussian_covariances_diag", "(", "resp", ",", "X", ",", "nk", ",", "means", ",", "reg_covar", ")", ":", "avg_X2", "=", "np", ".", "dot", "(", "resp", ".", "T", ",", "X", "*", "X", ")", "/", "nk", "[", ":", ",", "np", ".", "newax...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/mixture/_gaussian_mixture.py#L199-L222
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/data/python/ops/sliding.py
python
sliding_window_batch
(window_size, stride=None, window_shift=None, window_stride=1)
return _apply_fn
A sliding window over a dataset. This transformation passes a sliding window over this dataset. The window size is `window_size`, the stride of the input elements is `window_stride`, and the shift between consecutive windows is `window_shift`. If the remaining elements cannot fill up the sliding window, this transformation will drop the final smaller element. For example: ```python # NOTE: The following examples use `{ ... }` to represent the # contents of a dataset. a = { [1], [2], [3], [4], [5], [6] } a.apply(sliding_window_batch(window_size=3)) == { [[1], [2], [3]], [[2], [3], [4]], [[3], [4], [5]], [[4], [5], [6]] } a.apply(sliding_window_batch(window_size=3, window_shift=2)) == { [[1], [2], [3]], [[3], [4], [5]] } a.apply(sliding_window_batch(window_size=3, window_stride=2)) == { [[1], [3], [5]], [[2], [4], [6]] } ``` Args: window_size: A `tf.int64` scalar `tf.Tensor`, representing the number of elements in the sliding window. It must be positive. stride: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the forward shift of the sliding window in each iteration. The default is `1`. It must be positive. Deprecated alias for `window_shift`. window_shift: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the forward shift of the sliding window in each iteration. The default is `1`. It must be positive. window_stride: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the stride of the input elements in the sliding window. The default is `1`. It must be positive. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`. Raises: ValueError: if invalid arguments are provided.
A sliding window over a dataset.
[ "A", "sliding", "window", "over", "a", "dataset", "." ]
def sliding_window_batch(window_size, stride=None, window_shift=None, window_stride=1): """A sliding window over a dataset. This transformation passes a sliding window over this dataset. The window size is `window_size`, the stride of the input elements is `window_stride`, and the shift between consecutive windows is `window_shift`. If the remaining elements cannot fill up the sliding window, this transformation will drop the final smaller element. For example: ```python # NOTE: The following examples use `{ ... }` to represent the # contents of a dataset. a = { [1], [2], [3], [4], [5], [6] } a.apply(sliding_window_batch(window_size=3)) == { [[1], [2], [3]], [[2], [3], [4]], [[3], [4], [5]], [[4], [5], [6]] } a.apply(sliding_window_batch(window_size=3, window_shift=2)) == { [[1], [2], [3]], [[3], [4], [5]] } a.apply(sliding_window_batch(window_size=3, window_stride=2)) == { [[1], [3], [5]], [[2], [4], [6]] } ``` Args: window_size: A `tf.int64` scalar `tf.Tensor`, representing the number of elements in the sliding window. It must be positive. stride: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the forward shift of the sliding window in each iteration. The default is `1`. It must be positive. Deprecated alias for `window_shift`. window_shift: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the forward shift of the sliding window in each iteration. The default is `1`. It must be positive. window_stride: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the stride of the input elements in the sliding window. The default is `1`. It must be positive. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`. Raises: ValueError: if invalid arguments are provided. """ if stride is None and window_shift is None: window_shift = 1 elif stride is not None and window_shift is None: window_shift = stride elif stride is not None and window_shift is not None: raise ValueError("Cannot specify both `stride` and `window_shift`") def _apply_fn(dataset): return _SlideDataset(dataset, window_size, window_shift, window_stride) return _apply_fn
[ "def", "sliding_window_batch", "(", "window_size", ",", "stride", "=", "None", ",", "window_shift", "=", "None", ",", "window_stride", "=", "1", ")", ":", "if", "stride", "is", "None", "and", "window_shift", "is", "None", ":", "window_shift", "=", "1", "el...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/data/python/ops/sliding.py#L72-L129
ukoethe/vigra
093d57d15c8c237adf1704d96daa6393158ce299
vigranumpy/lib/arraytypes.py
python
VigraArray._empty_axistags
(ndim)
return AxisTags(ndim)
Create an axistags object with non-informative entries. That is, all axisinfo objects are '?'.
Create an axistags object with non-informative entries. That is, all axisinfo objects are '?'.
[ "Create", "an", "axistags", "object", "with", "non", "-", "informative", "entries", ".", "That", "is", "all", "axisinfo", "objects", "are", "?", "." ]
def _empty_axistags(ndim): '''Create an axistags object with non-informative entries. That is, all axisinfo objects are '?'. ''' return AxisTags(ndim)
[ "def", "_empty_axistags", "(", "ndim", ")", ":", "return", "AxisTags", "(", "ndim", ")" ]
https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/arraytypes.py#L471-L475
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/ccompiler.py
python
CCompiler_show_customization
(self)
Print the compiler customizations to stdout. Parameters ---------- None Returns ------- None Notes ----- Printing is only done if the distutils log threshold is < 2.
Print the compiler customizations to stdout.
[ "Print", "the", "compiler", "customizations", "to", "stdout", "." ]
def CCompiler_show_customization(self): """ Print the compiler customizations to stdout. Parameters ---------- None Returns ------- None Notes ----- Printing is only done if the distutils log threshold is < 2. """ if 0: for attrname in ['include_dirs', 'define', 'undef', 'libraries', 'library_dirs', 'rpath', 'link_objects']: attr = getattr(self, attrname, None) if not attr: continue log.info("compiler '%s' is set to %s" % (attrname, attr)) try: self.get_version() except: pass if log._global_log.threshold<2: print('*'*80) print(self.__class__) print(_compiler_to_string(self)) print('*'*80)
[ "def", "CCompiler_show_customization", "(", "self", ")", ":", "if", "0", ":", "for", "attrname", "in", "[", "'include_dirs'", ",", "'define'", ",", "'undef'", ",", "'libraries'", ",", "'library_dirs'", ",", "'rpath'", ",", "'link_objects'", "]", ":", "attr", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/ccompiler.py#L275-L308
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/base/__init__.py
python
Attribute.__init__
(self, name=None, attribute_type=None, count=None, value=None, text=None, extension_elements=None, extension_attributes=None)
Constructor for Attribute metadata element Args: name: str (optional) The name of the attribute attribute_type: str (optional) The type for the attribute. Examples: test, float, etc. count: str (optional) The number of times this attribute appears in the query results. value: list (optional) The values which are often used for this attirbute. text: str (optional) The text contents of the XML for this attribute. extension_elements: list (optional) A list of ExtensionElement instances extension_attributes: dict (optional) A dictionary of attribute value string pairs
Constructor for Attribute metadata element
[ "Constructor", "for", "Attribute", "metadata", "element" ]
def __init__(self, name=None, attribute_type=None, count=None, value=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Attribute metadata element Args: name: str (optional) The name of the attribute attribute_type: str (optional) The type for the attribute. Examples: test, float, etc. count: str (optional) The number of times this attribute appears in the query results. value: list (optional) The values which are often used for this attirbute. text: str (optional) The text contents of the XML for this attribute. extension_elements: list (optional) A list of ExtensionElement instances extension_attributes: dict (optional) A dictionary of attribute value string pairs """ self.name = name self.type = attribute_type self.count = count self.value = value or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {}
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "attribute_type", "=", "None", ",", "count", "=", "None", ",", "value", "=", "None", ",", "text", "=", "None", ",", "extension_elements", "=", "None", ",", "extension_attributes", "=", "None"...
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/base/__init__.py#L408-L433
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/catkin_support.py
python
call
(command, pipe=None)
Copy of call() function from catkin-generate-debian to mimic output
Copy of call() function from catkin-generate-debian to mimic output
[ "Copy", "of", "call", "()", "function", "from", "catkin", "-", "generate", "-", "debian", "to", "mimic", "output" ]
def call(command, pipe=None): """ Copy of call() function from catkin-generate-debian to mimic output """ working_dir = '.' #print('+ cd %s && ' % working_dir + ' '.join(command)) process = Popen(command, stdout=pipe, stderr=pipe, cwd=working_dir) output, unused_err = process.communicate() retcode = process.poll() if retcode: raise CalledProcessError(retcode, command) if pipe: return output
[ "def", "call", "(", "command", ",", "pipe", "=", "None", ")", ":", "working_dir", "=", "'.'", "#print('+ cd %s && ' % working_dir + ' '.join(command))", "process", "=", "Popen", "(", "command", ",", "stdout", "=", "pipe", ",", "stderr", "=", "pipe", ",", "cwd"...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/catkin_support.py#L38-L50
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
ReduceSum.forward
(self, x)
return _x.data
forward of ReduceSum Args: x (CTensor): input tensor. Returns: the output CTensor.
forward of ReduceSum Args: x (CTensor): input tensor. Returns: the output CTensor.
[ "forward", "of", "ReduceSum", "Args", ":", "x", "(", "CTensor", ")", ":", "input", "tensor", ".", "Returns", ":", "the", "output", "CTensor", "." ]
def forward(self, x): """ forward of ReduceSum Args: x (CTensor): input tensor. Returns: the output CTensor. """ _x = tensor.from_raw_tensor(x) x_shape = list(_x.shape) # handle the special axes if self.axes is None: self.axes = [i for i in range(len(x_shape))] # axes = None else: self.axes = [i if i >= 0 else len(x_shape) + i for i in self.axes ] # axes has negative self.axes.sort(reverse=True) for axis in self.axes: _x = tensor.sum(_x, axis) x_shape[axis] = 1 if self.keepdims == 1: _x = tensor.reshape(_x, x_shape) self.cache = (x_shape, x) return _x.data
[ "def", "forward", "(", "self", ",", "x", ")", ":", "_x", "=", "tensor", ".", "from_raw_tensor", "(", "x", ")", "x_shape", "=", "list", "(", "_x", ".", "shape", ")", "# handle the special axes", "if", "self", ".", "axes", "is", "None", ":", "self", "....
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L4019-L4042
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/ssd/dataset/iterator.py
python
DetIter._get_batch
(self)
Load data/label from dataset
Load data/label from dataset
[ "Load", "data", "/", "label", "from", "dataset" ]
def _get_batch(self): """ Load data/label from dataset """ batch_data = mx.nd.zeros((self.batch_size, 3, self._data_shape[0], self._data_shape[1])) batch_label = [] for i in range(self.batch_size): if (self._current + i) >= self._size: if not self.is_train: continue # use padding from middle in each epoch idx = (self._current + i + self._size // 2) % self._size index = self._index[idx] else: index = self._index[self._current + i] # index = self.debug_index im_path = self._imdb.image_path_from_index(index) with open(im_path, 'rb') as fp: img_content = fp.read() img = mx.img.imdecode(img_content) gt = self._imdb.label_from_index(index).copy() if self.is_train else None data, label = self._data_augmentation(img, gt) batch_data[i] = data if self.is_train: batch_label.append(label) self._data = {'data': batch_data} if self.is_train: self._label = {'label': mx.nd.array(np.array(batch_label))} else: self._label = {'label': None}
[ "def", "_get_batch", "(", "self", ")", ":", "batch_data", "=", "mx", ".", "nd", ".", "zeros", "(", "(", "self", ".", "batch_size", ",", "3", ",", "self", ".", "_data_shape", "[", "0", "]", ",", "self", ".", "_data_shape", "[", "1", "]", ")", ")",...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/dataset/iterator.py#L228-L257
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/chunk.py
python
Chunk.getname
(self)
return self.chunkname
Return the name (ID) of the current chunk.
Return the name (ID) of the current chunk.
[ "Return", "the", "name", "(", "ID", ")", "of", "the", "current", "chunk", "." ]
def getname(self): """Return the name (ID) of the current chunk.""" return self.chunkname
[ "def", "getname", "(", "self", ")", ":", "return", "self", ".", "chunkname" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/chunk.py#L78-L80
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/all_reduce/python/all_reduce.py
python
build_nccl_then_shuffle
(input_tensors, gather_devices, nccl_red_op, shuffle_red_op, un_op=None)
return _build_nccl_hybrid(input_tensors, nccl_red_op, upper_level_f)
Construct hybrid of NCCL within workers, Shuffle across workers.
Construct hybrid of NCCL within workers, Shuffle across workers.
[ "Construct", "hybrid", "of", "NCCL", "within", "workers", "Shuffle", "across", "workers", "." ]
def build_nccl_then_shuffle(input_tensors, gather_devices, nccl_red_op, shuffle_red_op, un_op=None): """Construct hybrid of NCCL within workers, Shuffle across workers.""" upper_level_f = lambda x: build_shuffle_all_reduce(x, gather_devices, shuffle_red_op, un_op) return _build_nccl_hybrid(input_tensors, nccl_red_op, upper_level_f)
[ "def", "build_nccl_then_shuffle", "(", "input_tensors", ",", "gather_devices", ",", "nccl_red_op", ",", "shuffle_red_op", ",", "un_op", "=", "None", ")", ":", "upper_level_f", "=", "lambda", "x", ":", "build_shuffle_all_reduce", "(", "x", ",", "gather_devices", ",...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/all_reduce/python/all_reduce.py#L789-L794
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
DEFINE_float
(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args)
Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range.
Registers a flag whose value must be a float.
[ "Registers", "a", "flag", "whose", "value", "must", "be", "a", "float", "." ]
def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
[ "def", "DEFINE_float", "(", "name", ",", "default", ",", "help", ",", "lower_bound", "=", "None", ",", "upper_bound", "=", "None", ",", "flag_values", "=", "FLAGS", ",", "*", "*", "args", ")", ":", "parser", "=", "FloatParser", "(", "lower_bound", ",", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L2508-L2518
asLody/whale
6a661b27cc4cf83b7b5a3b02451597ee1ac7f264
whale/cpplint.py
python
_SetOutputFormat
(output_format)
Sets the module's output format.
Sets the module's output format.
[ "Sets", "the", "module", "s", "output", "format", "." ]
def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format)
[ "def", "_SetOutputFormat", "(", "output_format", ")", ":", "_cpplint_state", ".", "SetOutputFormat", "(", "output_format", ")" ]
https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L968-L970
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/driver.py
python
Device.get_primary_context
(self)
return ctx
Returns the primary context for the device. Note: it is not pushed to the CPU thread.
Returns the primary context for the device. Note: it is not pushed to the CPU thread.
[ "Returns", "the", "primary", "context", "for", "the", "device", ".", "Note", ":", "it", "is", "not", "pushed", "to", "the", "CPU", "thread", "." ]
def get_primary_context(self): """ Returns the primary context for the device. Note: it is not pushed to the CPU thread. """ if self.primary_context is not None: return self.primary_context met_requirement_for_device(self) # create primary context hctx = drvapi.cu_context() driver.cuDevicePrimaryCtxRetain(byref(hctx), self.id) ctx = Context(weakref.proxy(self), hctx) self.primary_context = ctx return ctx
[ "def", "get_primary_context", "(", "self", ")", ":", "if", "self", ".", "primary_context", "is", "not", "None", ":", "return", "self", ".", "primary_context", "met_requirement_for_device", "(", "self", ")", "# create primary context", "hctx", "=", "drvapi", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/driver.py#L516-L532
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/rpc/options.py
python
TensorPipeRpcBackendOptions.set_device_map
(self, to: str, device_map: Dict[DeviceType, DeviceType])
r""" Set device mapping between each RPC caller and callee pair. This function can be called multiple times to incrementally add device placement configurations. Args: worker_name (str): Callee name. device_map (Dict of int, str, or torch.device): Device placement mappings from this worker to the callee. This map must be invertible. Example:: >>> # both workers >>> def add(x, y): >>> print(x) # tensor([1., 1.], device='cuda:1') >>> return x + y, (x + y).to(2) >>> >>> # on worker 0 >>> options = TensorPipeRpcBackendOptions( >>> num_worker_threads=8, >>> device_maps={"worker1": {0: 1}} >>> # maps worker0's cuda:0 to worker1's cuda:1 >>> ) >>> options.set_device_map("worker1", {1: 2}) >>> # maps worker0's cuda:1 to worker1's cuda:2 >>> >>> rpc.init_rpc( >>> "worker0", >>> rank=0, >>> world_size=2, >>> backend=rpc.BackendType.TENSORPIPE, >>> rpc_backend_options=options >>> ) >>> >>> x = torch.ones(2) >>> rets = rpc.rpc_sync("worker1", add, args=(x.to(0), 1)) >>> # The first argument will be moved to cuda:1 on worker1. When >>> # sending the return value back, it will follow the invert of >>> # the device map, and hence will be moved back to cuda:0 and >>> # cuda:1 on worker0 >>> print(rets[0]) # tensor([2., 2.], device='cuda:0') >>> print(rets[1]) # tensor([2., 2.], device='cuda:1')
r""" Set device mapping between each RPC caller and callee pair. This function can be called multiple times to incrementally add device placement configurations.
[ "r", "Set", "device", "mapping", "between", "each", "RPC", "caller", "and", "callee", "pair", ".", "This", "function", "can", "be", "called", "multiple", "times", "to", "incrementally", "add", "device", "placement", "configurations", "." ]
def set_device_map(self, to: str, device_map: Dict[DeviceType, DeviceType]): r""" Set device mapping between each RPC caller and callee pair. This function can be called multiple times to incrementally add device placement configurations. Args: worker_name (str): Callee name. device_map (Dict of int, str, or torch.device): Device placement mappings from this worker to the callee. This map must be invertible. Example:: >>> # both workers >>> def add(x, y): >>> print(x) # tensor([1., 1.], device='cuda:1') >>> return x + y, (x + y).to(2) >>> >>> # on worker 0 >>> options = TensorPipeRpcBackendOptions( >>> num_worker_threads=8, >>> device_maps={"worker1": {0: 1}} >>> # maps worker0's cuda:0 to worker1's cuda:1 >>> ) >>> options.set_device_map("worker1", {1: 2}) >>> # maps worker0's cuda:1 to worker1's cuda:2 >>> >>> rpc.init_rpc( >>> "worker0", >>> rank=0, >>> world_size=2, >>> backend=rpc.BackendType.TENSORPIPE, >>> rpc_backend_options=options >>> ) >>> >>> x = torch.ones(2) >>> rets = rpc.rpc_sync("worker1", add, args=(x.to(0), 1)) >>> # The first argument will be moved to cuda:1 on worker1. When >>> # sending the return value back, it will follow the invert of >>> # the device map, and hence will be moved back to cuda:0 and >>> # cuda:1 on worker0 >>> print(rets[0]) # tensor([2., 2.], device='cuda:0') >>> print(rets[1]) # tensor([2., 2.], device='cuda:1') """ full_device_map = _to_device_map(device_map) curr_device_maps = super().device_maps if to in curr_device_maps: for k, v in full_device_map.items(): if k in curr_device_maps[to] and v != curr_device_maps[to][k]: raise ValueError( "`set_device_map` only supports 1-to-1 mapping, trying" f" to map {k} to {v} and {curr_device_maps[to][k]}" ) super()._set_device_map(to, full_device_map)
[ "def", "set_device_map", "(", "self", ",", "to", ":", "str", ",", "device_map", ":", "Dict", "[", "DeviceType", ",", "DeviceType", "]", ")", ":", "full_device_map", "=", "_to_device_map", "(", "device_map", ")", "curr_device_maps", "=", "super", "(", ")", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/rpc/options.py#L104-L159
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextParagraphLayoutBox.GetParagraphCount
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_GetParagraphCount(*args, **kwargs)
GetParagraphCount(self) -> int
GetParagraphCount(self) -> int
[ "GetParagraphCount", "(", "self", ")", "-", ">", "int" ]
def GetParagraphCount(*args, **kwargs): """GetParagraphCount(self) -> int""" return _richtext.RichTextParagraphLayoutBox_GetParagraphCount(*args, **kwargs)
[ "def", "GetParagraphCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_GetParagraphCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1708-L1710
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showbase/Audio3DManager.py
python
Audio3DManager.attachListener
(self, object)
return 1
Sounds will be heard relative to this object. Should probably be the camera.
Sounds will be heard relative to this object. Should probably be the camera.
[ "Sounds", "will", "be", "heard", "relative", "to", "this", "object", ".", "Should", "probably", "be", "the", "camera", "." ]
def attachListener(self, object): """ Sounds will be heard relative to this object. Should probably be the camera. """ self.listener_target = object return 1
[ "def", "attachListener", "(", "self", ",", "object", ")", ":", "self", ".", "listener_target", "=", "object", "return", "1" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Audio3DManager.py#L247-L252
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListItem.GetAlign
(*args, **kwargs)
return _controls_.ListItem_GetAlign(*args, **kwargs)
GetAlign(self) -> int
GetAlign(self) -> int
[ "GetAlign", "(", "self", ")", "-", ">", "int" ]
def GetAlign(*args, **kwargs): """GetAlign(self) -> int""" return _controls_.ListItem_GetAlign(*args, **kwargs)
[ "def", "GetAlign", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItem_GetAlign", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4244-L4246
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/saved_model_cli.py
python
scan_meta_graph_def
(meta_graph_def)
Scans meta_graph_def and reports if there are ops on blacklist. Print ops if they are on black list, or print success if no blacklisted ops found. Args: meta_graph_def: MetaGraphDef protocol buffer.
Scans meta_graph_def and reports if there are ops on blacklist.
[ "Scans", "meta_graph_def", "and", "reports", "if", "there", "are", "ops", "on", "blacklist", "." ]
def scan_meta_graph_def(meta_graph_def): """Scans meta_graph_def and reports if there are ops on blacklist. Print ops if they are on black list, or print success if no blacklisted ops found. Args: meta_graph_def: MetaGraphDef protocol buffer. """ all_ops_set = set( meta_graph_lib.ops_used_by_graph_def(meta_graph_def.graph_def)) blacklisted_ops = _OP_BLACKLIST & all_ops_set if blacklisted_ops: # TODO(yifeif): print more warnings print('MetaGraph with tag set %s contains the following blacklisted ops:' % meta_graph_def.meta_info_def.tags, blacklisted_ops) else: print('MetaGraph with tag set %s does not contain blacklisted ops.' % meta_graph_def.meta_info_def.tags)
[ "def", "scan_meta_graph_def", "(", "meta_graph_def", ")", ":", "all_ops_set", "=", "set", "(", "meta_graph_lib", ".", "ops_used_by_graph_def", "(", "meta_graph_def", ".", "graph_def", ")", ")", "blacklisted_ops", "=", "_OP_BLACKLIST", "&", "all_ops_set", "if", "blac...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/saved_model_cli.py#L327-L345
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_IncludeState.ResetSection
(self, directive)
Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else").
Reset section checking for preprocessor directive.
[ "Reset", "section", "checking", "for", "preprocessor", "directive", "." ]
def ResetSection(self, directive): """Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else"). """ # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' # Update list of includes. Note that we never pop from the # include list. if directive in ('if', 'ifdef', 'ifndef'): self.include_list.append([]) elif directive in ('else', 'elif'): self.include_list[-1] = []
[ "def", "ResetSection", "(", "self", ",", "directive", ")", ":", "# The name of the current section.", "self", ".", "_section", "=", "self", ".", "_INITIAL_SECTION", "# The path of last found header.", "self", ".", "_last_header", "=", "''", "# Update list of includes. No...
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L751-L767
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
get_supported_platform
()
return plat
Return this platform's maximum compatible version. distutils.util.get_platform() normally reports the minimum version of Mac OS X that would be required to *use* extensions produced by distutils. But what we want when checking compatibility is to know the version of Mac OS X that we are *running*. To allow usage of packages that explicitly require a newer version of Mac OS X, we must also know the current version of the OS. If this condition occurs for any other platform with a version in its platform strings, this function should be extended accordingly.
Return this platform's maximum compatible version.
[ "Return", "this", "platform", "s", "maximum", "compatible", "version", "." ]
def get_supported_platform(): """Return this platform's maximum compatible version. distutils.util.get_platform() normally reports the minimum version of Mac OS X that would be required to *use* extensions produced by distutils. But what we want when checking compatibility is to know the version of Mac OS X that we are *running*. To allow usage of packages that explicitly require a newer version of Mac OS X, we must also know the current version of the OS. If this condition occurs for any other platform with a version in its platform strings, this function should be extended accordingly. """ plat = get_build_platform() m = macosVersionString.match(plat) if m is not None and sys.platform == "darwin": try: plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3)) except ValueError: # not Mac OS X pass return plat
[ "def", "get_supported_platform", "(", ")", ":", "plat", "=", "get_build_platform", "(", ")", "m", "=", "macosVersionString", ".", "match", "(", "plat", ")", "if", "m", "is", "not", "None", "and", "sys", ".", "platform", "==", "\"darwin\"", ":", "try", ":...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L177-L198
zju3dv/clean-pvnet
5870c509e3cc205e1bb28910a7b1a9a3c8add9a8
lib/utils/meshrenderer/gl_utils/inout.py
python
load_ply
(path)
return model
Loads a 3D mesh model from a PLY file. :param path: Path to a PLY file. :return: The loaded model given by a dictionary with items: 'pts' (nx3 ndarray), 'normals' (nx3 ndarray), 'colors' (nx3 ndarray), 'faces' (mx3 ndarray) - the latter three are optional.
Loads a 3D mesh model from a PLY file.
[ "Loads", "a", "3D", "mesh", "model", "from", "a", "PLY", "file", "." ]
def load_ply(path): """ Loads a 3D mesh model from a PLY file. :param path: Path to a PLY file. :return: The loaded model given by a dictionary with items: 'pts' (nx3 ndarray), 'normals' (nx3 ndarray), 'colors' (nx3 ndarray), 'faces' (mx3 ndarray) - the latter three are optional. """ f = open(path, 'r') n_pts = 0 n_faces = 0 face_n_corners = 3 # Only triangular faces are supported pt_props = [] face_props = [] is_binary = False header_vertex_section = False header_face_section = False # Read header while True: line = f.readline().rstrip('\n').rstrip('\r') # Strip the newline character(s) if line.startswith('element vertex'): n_pts = int(line.split()[-1]) header_vertex_section = True header_face_section = False elif line.startswith('element face'): n_faces = int(line.split()[-1]) header_vertex_section = False header_face_section = True elif line.startswith('element'): # Some other element header_vertex_section = False header_face_section = False elif line.startswith('property') and header_vertex_section: # (name of the property, data type) pt_props.append((line.split()[-1], line.split()[-2])) elif line.startswith('property list') and header_face_section: elems = line.split() if elems[-1] == 'vertex_indices': # (name of the property, data type) face_props.append(('n_corners', elems[2])) for i in range(face_n_corners): face_props.append(('ind_' + str(i), elems[3])) else: print('Warning: Not supported face property: ' + elems[-1]) elif line.startswith('format'): if 'binary' in line: is_binary = True elif line.startswith('end_header'): break # Prepare data structures model = {} model['pts'] = np.zeros((n_pts, 3), np.float) if n_faces > 0: model['faces'] = np.zeros((n_faces, face_n_corners), np.float) pt_props_names = [p[0] for p in pt_props] is_normal = False if {'nx', 'ny', 'nz'}.issubset(set(pt_props_names)): is_normal = True model['normals'] = np.zeros((n_pts, 3), np.float) is_color = False if {'red', 'green', 'blue'}.issubset(set(pt_props_names)): is_color = True model['colors'] = np.zeros((n_pts, 3), np.float) is_texture = False if {'texture_u', 'texture_v'}.issubset(set(pt_props_names)): is_texture = True model['texture_uv'] = np.zeros((n_pts, 2), np.float) formats = { # For binary format 'float': ('f', 4), 'double': ('d', 8), 'int': ('i', 4), 'uchar': ('B', 1) } # Load vertices for pt_id in range(n_pts): prop_vals = {} load_props = ['x', 'y', 'z', 'nx', 'ny', 'nz', 'red', 'green', 'blue', 'texture_u', 'texture_v'] if is_binary: for prop in pt_props: format = formats[prop[1]] val = struct.unpack(format[0], f.read(format[1]))[0] if prop[0] in load_props: prop_vals[prop[0]] = val else: elems = f.readline().rstrip('\n').rstrip('\r').split() for prop_id, prop in enumerate(pt_props): if prop[0] in load_props: prop_vals[prop[0]] = elems[prop_id] model['pts'][pt_id, 0] = float(prop_vals['x']) model['pts'][pt_id, 1] = float(prop_vals['y']) model['pts'][pt_id, 2] = float(prop_vals['z']) if is_normal: model['normals'][pt_id, 0] = float(prop_vals['nx']) model['normals'][pt_id, 1] = float(prop_vals['ny']) model['normals'][pt_id, 2] = float(prop_vals['nz']) if is_color: model['colors'][pt_id, 0] = float(prop_vals['red']) model['colors'][pt_id, 1] = float(prop_vals['green']) model['colors'][pt_id, 2] = float(prop_vals['blue']) if is_texture: model['texture_uv'][pt_id, 0] = float(prop_vals['texture_u']) model['texture_uv'][pt_id, 1] = float(prop_vals['texture_v']) # Load faces for face_id in range(n_faces): prop_vals = {} if is_binary: for prop in face_props: format = formats[prop[1]] val = struct.unpack(format[0], f.read(format[1]))[0] if prop[0] == 'n_corners': if val != face_n_corners: print('Error: Only triangular faces are supported.') print('Number of face corners: ' + str(val)) exit(-1) else: prop_vals[prop[0]] = val else: elems = f.readline().rstrip('\n').rstrip('\r').split() for prop_id, prop in enumerate(face_props): if prop[0] == 'n_corners': if int(elems[prop_id]) != face_n_corners: print('Error: Only triangular faces are supported.') print('Number of face corners: ' + str(int(elems[prop_id]))) exit(-1) else: prop_vals[prop[0]] = elems[prop_id] model['faces'][face_id, 0] = int(prop_vals['ind_0']) model['faces'][face_id, 1] = int(prop_vals['ind_1']) model['faces'][face_id, 2] = int(prop_vals['ind_2']) f.close() return model
[ "def", "load_ply", "(", "path", ")", ":", "f", "=", "open", "(", "path", ",", "'r'", ")", "n_pts", "=", "0", "n_faces", "=", "0", "face_n_corners", "=", "3", "# Only triangular faces are supported", "pt_props", "=", "[", "]", "face_props", "=", "[", "]",...
https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/meshrenderer/gl_utils/inout.py#L8-L155
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/xcodeproj_file.py
python
PBXGroup.AddOrGetFileByPath
(self, path, hierarchical)
Returns an existing or new file reference corresponding to path. If hierarchical is True, this method will create or use the necessary hierarchical group structure corresponding to path. Otherwise, it will look in and create an item in the current group only. If an existing matching reference is found, it is returned, otherwise, a new one will be created, added to the correct group, and returned. If path identifies a directory by virtue of carrying a trailing slash, this method returns a PBXFileReference of "folder" type. If path identifies a variant, by virtue of it identifying a file inside a directory with an ".lproj" extension, this method returns a PBXVariantGroup containing the variant named by path, and possibly other variants. For all other paths, a "normal" PBXFileReference will be returned.
Returns an existing or new file reference corresponding to path.
[ "Returns", "an", "existing", "or", "new", "file", "reference", "corresponding", "to", "path", "." ]
def AddOrGetFileByPath(self, path, hierarchical): """Returns an existing or new file reference corresponding to path. If hierarchical is True, this method will create or use the necessary hierarchical group structure corresponding to path. Otherwise, it will look in and create an item in the current group only. If an existing matching reference is found, it is returned, otherwise, a new one will be created, added to the correct group, and returned. If path identifies a directory by virtue of carrying a trailing slash, this method returns a PBXFileReference of "folder" type. If path identifies a variant, by virtue of it identifying a file inside a directory with an ".lproj" extension, this method returns a PBXVariantGroup containing the variant named by path, and possibly other variants. For all other paths, a "normal" PBXFileReference will be returned. """ # Adding or getting a directory? Directories end with a trailing slash. is_dir = False if path.endswith('/'): is_dir = True path = posixpath.normpath(path) if is_dir: path = path + '/' # Adding or getting a variant? Variants are files inside directories # with an ".lproj" extension. Xcode uses variants for localization. For # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named # MainMenu.nib inside path/to, and give it a variant named Language. In # this example, grandparent would be set to path/to and parent_root would # be set to Language. variant_name = None parent = posixpath.dirname(path) grandparent = posixpath.dirname(parent) parent_basename = posixpath.basename(parent) (parent_root, parent_ext) = posixpath.splitext(parent_basename) if parent_ext == '.lproj': variant_name = parent_root if grandparent == '': grandparent = None # Putting a directory inside a variant group is not currently supported. assert not is_dir or variant_name is None path_split = path.split(posixpath.sep) if len(path_split) == 1 or \ ((is_dir or variant_name != None) and len(path_split) == 2) or \ not hierarchical: # The PBXFileReference or PBXVariantGroup will be added to or gotten from # this PBXGroup, no recursion necessary. if variant_name is None: # Add or get a PBXFileReference. file_ref = self.GetChildByPath(path) if file_ref != None: assert file_ref.__class__ == PBXFileReference else: file_ref = PBXFileReference({'path': path}) self.AppendChild(file_ref) else: # Add or get a PBXVariantGroup. The variant group name is the same # as the basename (MainMenu.nib in the example above). grandparent # specifies the path to the variant group itself, and path_split[-2:] # is the path of the specific variant relative to its group. variant_group_name = posixpath.basename(path) variant_group_ref = self.AddOrGetVariantGroupByNameAndPath( variant_group_name, grandparent) variant_path = posixpath.sep.join(path_split[-2:]) variant_ref = variant_group_ref.GetChildByPath(variant_path) if variant_ref != None: assert variant_ref.__class__ == PBXFileReference else: variant_ref = PBXFileReference({'name': variant_name, 'path': variant_path}) variant_group_ref.AppendChild(variant_ref) # The caller is interested in the variant group, not the specific # variant file. file_ref = variant_group_ref return file_ref else: # Hierarchical recursion. Add or get a PBXGroup corresponding to the # outermost path component, and then recurse into it, chopping off that # path component. next_dir = path_split[0] group_ref = self.GetChildByPath(next_dir) if group_ref != None: assert group_ref.__class__ == PBXGroup else: group_ref = PBXGroup({'path': next_dir}) self.AppendChild(group_ref) return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]), hierarchical)
[ "def", "AddOrGetFileByPath", "(", "self", ",", "path", ",", "hierarchical", ")", ":", "# Adding or getting a directory? Directories end with a trailing slash.", "is_dir", "=", "False", "if", "path", ".", "endswith", "(", "'/'", ")", ":", "is_dir", "=", "True", "pat...
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/xcodeproj_file.py#L1213-L1304
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Plot/Plot.py
python
axes
()
return plt.axes
Return the active plot axes.
Return the active plot axes.
[ "Return", "the", "active", "plot", "axes", "." ]
def axes(): """Return the active plot axes.""" plt = getPlot() if not plt: return None return plt.axes
[ "def", "axes", "(", ")", ":", "plt", "=", "getPlot", "(", ")", "if", "not", "plt", ":", "return", "None", "return", "plt", ".", "axes" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Plot/Plot.py#L279-L284
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
configs/example/read_config.py
python
ConfigManager.find_object
(self, object_name)
return obj
Find and configure (with just non-SimObject parameters) a single object
Find and configure (with just non-SimObject parameters) a single object
[ "Find", "and", "configure", "(", "with", "just", "non", "-", "SimObject", "parameters", ")", "a", "single", "object" ]
def find_object(self, object_name): """Find and configure (with just non-SimObject parameters) a single object""" if object_name == 'Null': return NULL if object_name in self.objects_by_name: return self.objects_by_name[object_name] object_type = self.config.get_param(object_name, 'type') if object_type not in sim_object_classes_by_name: raise Exception('No SimObject type %s is available to' ' build: %s' % (object_type, object_name)) object_class = sim_object_classes_by_name[object_type] parsed_params = {} for param_name, param in list(object_class._params.items()): if issubclass(param.ptype, m5.params.ParamValue): if isinstance(param, m5.params.VectorParamDesc): param_values = self.config.get_param_vector(object_name, param_name) param_value = [ param.ptype.parse_ini(self.flags, value) for value in param_values ] else: param_value = param.ptype.parse_ini( self.flags, self.config.get_param(object_name, param_name)) parsed_params[param_name] = param_value obj = object_class(**parsed_params) self.objects_by_name[object_name] = obj return obj
[ "def", "find_object", "(", "self", ",", "object_name", ")", ":", "if", "object_name", "==", "'Null'", ":", "return", "NULL", "if", "object_name", "in", "self", ".", "objects_by_name", ":", "return", "self", ".", "objects_by_name", "[", "object_name", "]", "o...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/configs/example/read_config.py#L169-L207
wallix/redemption
fb4ceefb39e11e1ae250bce17e878e1dc7d195d2
tools/sesman/sesmanworker/wallixauth.py
python
Authenticator.is_x509_connected
(self, wab_login, ip_client, proxy_type, target, ip_server)
return False
Ask if we are authentifying using x509 (and ask user by opening confirmation popup if we are, session ticket will be asked later in x509_authenticate)
Ask if we are authentifying using x509 (and ask user by opening confirmation popup if we are, session ticket will be asked later in x509_authenticate)
[ "Ask", "if", "we", "are", "authentifying", "using", "x509", "(", "and", "ask", "user", "by", "opening", "confirmation", "popup", "if", "we", "are", "session", "ticket", "will", "be", "asked", "later", "in", "x509_authenticate", ")" ]
def is_x509_connected(self, wab_login, ip_client, proxy_type, target, ip_server): """ Ask if we are authentifying using x509 (and ask user by opening confirmation popup if we are, session ticket will be asked later in x509_authenticate) """ try: self.auth_x509 = AuthX509(username=wab_login, ip=ip_client, requestor=proxy_type, target=target, server_ip=ip_server) result = self.auth_x509.is_connected() return result except Exception: import traceback Logger().info("Engine is_x509_connected failed: " "(((%s)))" % traceback.format_exc()) return False
[ "def", "is_x509_connected", "(", "self", ",", "wab_login", ",", "ip_client", ",", "proxy_type", ",", "target", ",", "ip_server", ")", ":", "try", ":", "self", ".", "auth_x509", "=", "AuthX509", "(", "username", "=", "wab_login", ",", "ip", "=", "ip_client"...
https://github.com/wallix/redemption/blob/fb4ceefb39e11e1ae250bce17e878e1dc7d195d2/tools/sesman/sesmanworker/wallixauth.py#L368-L387
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/instrument.py
python
Instrument.closing_timestamp
(self)
return self._closing_timestamp
Gets the closing_timestamp of this Instrument. # noqa: E501 :return: The closing_timestamp of this Instrument. # noqa: E501 :rtype: datetime
Gets the closing_timestamp of this Instrument. # noqa: E501
[ "Gets", "the", "closing_timestamp", "of", "this", "Instrument", ".", "#", "noqa", ":", "E501" ]
def closing_timestamp(self): """Gets the closing_timestamp of this Instrument. # noqa: E501 :return: The closing_timestamp of this Instrument. # noqa: E501 :rtype: datetime """ return self._closing_timestamp
[ "def", "closing_timestamp", "(", "self", ")", ":", "return", "self", ".", "_closing_timestamp" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument.py#L1780-L1787
chatopera/clause
dee31153d5ffdef33deedb6bff03e7806c296968
thirdparty/crfsuite/crfsuite-0.12/example/crfutils.py
python
to_crfsuite
(X)
return xseq
Convert an item sequence into an object compatible with crfsuite Python module. @type X: list of mapping objects @param X: The sequence. @rtype crfsuite.ItemSequence @return The same sequence in crfsuite.ItemSequence type.
Convert an item sequence into an object compatible with crfsuite Python module.
[ "Convert", "an", "item", "sequence", "into", "an", "object", "compatible", "with", "crfsuite", "Python", "module", "." ]
def to_crfsuite(X): """ Convert an item sequence into an object compatible with crfsuite Python module. @type X: list of mapping objects @param X: The sequence. @rtype crfsuite.ItemSequence @return The same sequence in crfsuite.ItemSequence type. """ import crfsuite xseq = crfsuite.ItemSequence() for x in X: item = crfsuite.Item() for f in x['F']: if isinstance(f, str): item.append(crfsuite.Attribute(escape(f))) else: item.append(crfsuite.Attribute(escape(f[0]), f[1])) xseq.append(item) return xseq
[ "def", "to_crfsuite", "(", "X", ")", ":", "import", "crfsuite", "xseq", "=", "crfsuite", ".", "ItemSequence", "(", ")", "for", "x", "in", "X", ":", "item", "=", "crfsuite", ".", "Item", "(", ")", "for", "f", "in", "x", "[", "'F'", "]", ":", "if",...
https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/thirdparty/crfsuite/crfsuite-0.12/example/crfutils.py#L105-L125
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3poly.py
python
subresultants
(p, q, x)
return AstVector(Z3_polynomial_subresultants(p.ctx_ref(), p.as_ast(), q.as_ast(), x.as_ast()), p.ctx)
Return the non-constant subresultants of 'p' and 'q' with respect to the "variable" 'x'. 'p', 'q' and 'x' are Z3 expressions where 'p' and 'q' are arithmetic terms. Note that, any subterm that cannot be viewed as a polynomial is assumed to be a variable. Example: f(a) is a considered to be a variable b in the polynomial f(a)*f(a) + 2*f(a) + 1 >>> x, y = Reals('x y') >>> subresultants(2*x + y, 3*x - 2*y + 2, x) [-7*y + 4] >>> r = subresultants(3*y*x**2 + y**3 + 1, 2*x**3 + y + 3, x) >>> r[0] 4*y**9 + 12*y**6 + 27*y**5 + 162*y**4 + 255*y**3 + 4 >>> r[1] -6*y**4 + -6*y
Return the non-constant subresultants of 'p' and 'q' with respect to the "variable" 'x'.
[ "Return", "the", "non", "-", "constant", "subresultants", "of", "p", "and", "q", "with", "respect", "to", "the", "variable", "x", "." ]
def subresultants(p, q, x): """ Return the non-constant subresultants of 'p' and 'q' with respect to the "variable" 'x'. 'p', 'q' and 'x' are Z3 expressions where 'p' and 'q' are arithmetic terms. Note that, any subterm that cannot be viewed as a polynomial is assumed to be a variable. Example: f(a) is a considered to be a variable b in the polynomial f(a)*f(a) + 2*f(a) + 1 >>> x, y = Reals('x y') >>> subresultants(2*x + y, 3*x - 2*y + 2, x) [-7*y + 4] >>> r = subresultants(3*y*x**2 + y**3 + 1, 2*x**3 + y + 3, x) >>> r[0] 4*y**9 + 12*y**6 + 27*y**5 + 162*y**4 + 255*y**3 + 4 >>> r[1] -6*y**4 + -6*y """ return AstVector(Z3_polynomial_subresultants(p.ctx_ref(), p.as_ast(), q.as_ast(), x.as_ast()), p.ctx)
[ "def", "subresultants", "(", "p", ",", "q", ",", "x", ")", ":", "return", "AstVector", "(", "Z3_polynomial_subresultants", "(", "p", ".", "ctx_ref", "(", ")", ",", "p", ".", "as_ast", "(", ")", ",", "q", ".", "as_ast", "(", ")", ",", "x", ".", "a...
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3poly.py#L12-L31
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/variable_scope.py
python
VariableScope.__init__
(self, reuse, name="", initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, name_scope="", dtype=dtypes.float32, use_resource=None, constraint=None)
Creates a new VariableScope with the given properties.
Creates a new VariableScope with the given properties.
[ "Creates", "a", "new", "VariableScope", "with", "the", "given", "properties", "." ]
def __init__(self, reuse, name="", initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, name_scope="", dtype=dtypes.float32, use_resource=None, constraint=None): """Creates a new VariableScope with the given properties.""" self._name = name self._initializer = initializer self._regularizer = regularizer self._reuse = reuse self._caching_device = caching_device self._partitioner = partitioner self._custom_getter = custom_getter self._name_scope = name_scope self._dtype = dtype self._use_resource = use_resource self._constraint = constraint if context.in_eager_mode(): if self._caching_device is not None: raise NotImplementedError("Caching devices is not yet supported " "when eager execution is enabled.") if self._partitioner is not None: raise NotImplementedError("Partitioned variables are not yet supported " "when eager execution is enabled.") self._reuse = AUTO_REUSE self._use_resource = True
[ "def", "__init__", "(", "self", ",", "reuse", ",", "name", "=", "\"\"", ",", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "caching_device", "=", "None", ",", "partitioner", "=", "None", ",", "custom_getter", "=", "None", ",", "name_s...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/variable_scope.py#L894-L926
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py
python
Metrowerks_Shell_Suite_Events.Touch
(self, _object, _attributes={}, **_arguments)
Touch: Force recompilation of the specified file(s) Required argument: List of files to compile Keyword argument _attributes: AppleEvent attribute dictionary Returns: Error code for each file touched
Touch: Force recompilation of the specified file(s) Required argument: List of files to compile Keyword argument _attributes: AppleEvent attribute dictionary Returns: Error code for each file touched
[ "Touch", ":", "Force", "recompilation", "of", "the", "specified", "file", "(", "s", ")", "Required", "argument", ":", "List", "of", "files", "to", "compile", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "E...
def Touch(self, _object, _attributes={}, **_arguments): """Touch: Force recompilation of the specified file(s) Required argument: List of files to compile Keyword argument _attributes: AppleEvent attribute dictionary Returns: Error code for each file touched """ _code = 'MMPR' _subcode = 'Toch' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "Touch", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'MMPR'", "_subcode", "=", "'Toch'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_a...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py#L746-L765
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_output.py
python
Vt100_Output.flush
(self)
Write to output stream and flush.
Write to output stream and flush.
[ "Write", "to", "output", "stream", "and", "flush", "." ]
def flush(self): """ Write to output stream and flush. """ if not self._buffer: return data = ''.join(self._buffer) try: # (We try to encode ourself, because that way we can replace # characters that don't exist in the character set, avoiding # UnicodeEncodeError crashes. E.g. u'\xb7' does not appear in 'ascii'.) # My Arch Linux installation of july 2015 reported 'ANSI_X3.4-1968' # for sys.stdout.encoding in xterm. if self.write_binary: if hasattr(self.stdout, 'buffer'): out = self.stdout.buffer # Py3. else: out = self.stdout out.write(data.encode(self.stdout.encoding or 'utf-8', 'replace')) else: self.stdout.write(data) self.stdout.flush() except IOError as e: if e.args and e.args[0] == errno.EINTR: # Interrupted system call. Can happpen in case of a window # resize signal. (Just ignore. The resize handler will render # again anyway.) pass elif e.args and e.args[0] == 0: # This can happen when there is a lot of output and the user # sends a KeyboardInterrupt by pressing Control-C. E.g. in # a Python REPL when we execute "while True: print('test')". # (The `ptpython` REPL uses this `Output` class instead of # `stdout` directly -- in order to be network transparent.) # So, just ignore. pass else: raise self._buffer = []
[ "def", "flush", "(", "self", ")", ":", "if", "not", "self", ".", "_buffer", ":", "return", "data", "=", "''", ".", "join", "(", "self", ".", "_buffer", ")", "try", ":", "# (We try to encode ourself, because that way we can replace", "# characters that don't exist ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_output.py#L578-L620
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
Fixedpoint.get_rules_along_trace
(self)
return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
retrieve rules along the counterexample trace
retrieve rules along the counterexample trace
[ "retrieve", "rules", "along", "the", "counterexample", "trace" ]
def get_rules_along_trace(self): """retrieve rules along the counterexample trace""" return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
[ "def", "get_rules_along_trace", "(", "self", ")", ":", "return", "AstVector", "(", "Z3_fixedpoint_get_rules_along_trace", "(", "self", ".", "ctx", ".", "ref", "(", ")", ",", "self", ".", "fixedpoint", ")", ",", "self", ".", "ctx", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L7505-L7507
PJunhyuk/people-counting-pose
8cdaab5281847c296b305643842053d496e2e4e8
util/mscoco_util.py
python
interweave_matrices
(x, y, z)
return x + y + z
Combine matrices by concatenating their cols: x.col(1),y.col(1),z.col(1) ... x.col(n),y.col(n),z.col(n)
Combine matrices by concatenating their cols: x.col(1),y.col(1),z.col(1) ... x.col(n),y.col(n),z.col(n)
[ "Combine", "matrices", "by", "concatenating", "their", "cols", ":", "x", ".", "col", "(", "1", ")", "y", ".", "col", "(", "1", ")", "z", ".", "col", "(", "1", ")", "...", "x", ".", "col", "(", "n", ")", "y", ".", "col", "(", "n", ")", "z", ...
def interweave_matrices(x, y, z): """Combine matrices by concatenating their cols: x.col(1),y.col(1),z.col(1) ... x.col(n),y.col(n),z.col(n) """ num_joints = x.shape[1] id_x = (np.arange(0, num_joints, 0.5) + 1).astype('int') id_y = (np.arange(0, num_joints, 0.5) + 0.5).astype('int') id_z = (np.arange(0, num_joints, 0.5) + 0).astype('int') x = np.insert(x, id_x, 0, axis=1) y = np.insert(y, id_y, 0, axis=1) z = np.insert(z, id_z, 0, axis=1) return x + y + z
[ "def", "interweave_matrices", "(", "x", ",", "y", ",", "z", ")", ":", "num_joints", "=", "x", ".", "shape", "[", "1", "]", "id_x", "=", "(", "np", ".", "arange", "(", "0", ",", "num_joints", ",", "0.5", ")", "+", "1", ")", ".", "astype", "(", ...
https://github.com/PJunhyuk/people-counting-pose/blob/8cdaab5281847c296b305643842053d496e2e4e8/util/mscoco_util.py#L12-L21
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/houdini/python2.7libs/blastExport/fbxUtil.py
python
FbxSceneUtil.getSceneNodes
(self)
return nodes
:return: list of fbx.FbxNode
:return: list of fbx.FbxNode
[ ":", "return", ":", "list", "of", "fbx", ".", "FbxNode" ]
def getSceneNodes(self): """ :return: list of fbx.FbxNode """ rootNode = self.scene.GetRootNode() nodes = [] for i in range(rootNode.GetChildCount()): childNode = rootNode.GetChild(i) nodes.append(childNode) nodes.extend(self.__getChildNodes(node=childNode)) return nodes
[ "def", "getSceneNodes", "(", "self", ")", ":", "rootNode", "=", "self", ".", "scene", ".", "GetRootNode", "(", ")", "nodes", "=", "[", "]", "for", "i", "in", "range", "(", "rootNode", ".", "GetChildCount", "(", ")", ")", ":", "childNode", "=", "rootN...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/houdini/python2.7libs/blastExport/fbxUtil.py#L40-L50
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/MSVSSettings.py
python
_MSVSOnly
(tool, name, setting_type)
Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting.
Defines a setting that is only found in MSVS.
[ "Defines", "a", "setting", "that", "is", "only", "found", "in", "MSVS", "." ]
def _MSVSOnly(tool, name, setting_type): """Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ def _Translate(unused_value, unused_msbuild_settings): # Since this is for MSVS only settings, no translation will happen. pass _msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate
[ "def", "_MSVSOnly", "(", "tool", ",", "name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "unused_value", ",", "unused_msbuild_settings", ")", ":", "# Since this is for MSVS only settings, no translation will happen.", "pass", "_msvs_validators", "[", "tool",...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/MSVSSettings.py#L292-L306
envoyproxy/envoy-wasm
ab5d9381fdf92a1efa0b87cff80036b5b3e81198
tools/envoy_headersplit/headersplit.py
python
class_definitions
(cursor: Cursor)
return class_cursors
extracts all class definitions in the file pointed by cursor. (typical mocks.h) Args: cursor: cursor of parsing result of target source code by libclang Returns: a list of cursor, each pointing to a class definition.
extracts all class definitions in the file pointed by cursor. (typical mocks.h)
[ "extracts", "all", "class", "definitions", "in", "the", "file", "pointed", "by", "cursor", ".", "(", "typical", "mocks", ".", "h", ")" ]
def class_definitions(cursor: Cursor) -> List[Cursor]: """ extracts all class definitions in the file pointed by cursor. (typical mocks.h) Args: cursor: cursor of parsing result of target source code by libclang Returns: a list of cursor, each pointing to a class definition. """ cursors = cursors_in_same_file(cursor) class_cursors = [] for descendant in cursors: # check if descendant is pointing to a class declaration block. if descendant.kind != CursorKind.CLASS_DECL: continue if not descendant.is_definition(): continue # check if this class is directly enclosed by a namespace. if descendant.semantic_parent.kind != CursorKind.NAMESPACE: continue class_cursors.append(descendant) return class_cursors
[ "def", "class_definitions", "(", "cursor", ":", "Cursor", ")", "->", "List", "[", "Cursor", "]", ":", "cursors", "=", "cursors_in_same_file", "(", "cursor", ")", "class_cursors", "=", "[", "]", "for", "descendant", "in", "cursors", ":", "# check if descendant ...
https://github.com/envoyproxy/envoy-wasm/blob/ab5d9381fdf92a1efa0b87cff80036b5b3e81198/tools/envoy_headersplit/headersplit.py#L100-L122
may0324/DeepCompression-caffe
0aff6c1287bda4cfc7f378ed8a16524e1afabd8c
scripts/cpp_lint.py
python
CheckCaffeRandom
(filename, clean_lines, linenum, error)
Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for calls to C random functions (rand, rand_r, random, ...).
[ "Checks", "for", "calls", "to", "C", "random", "functions", "(", "rand", "rand_r", "random", "...", ")", "." ]
def CheckCaffeRandom(filename, clean_lines, linenum, error): """Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for function in c_random_function_list: ix = line.find(function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'caffe/random_fn', 2, 'Use caffe_rng_rand() (or other caffe_rng_* function) instead of ' + function + ') to ensure results are deterministic for a fixed Caffe seed.')
[ "def", "CheckCaffeRandom", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "function", "in", "c_random_function_list", ":", "ix", "=", "line", ".", "find", ...
https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/scripts/cpp_lint.py#L1640-L1663
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py
python
MaskedArray.__array_finalize__
(self, obj)
return
Finalizes the masked array.
Finalizes the masked array.
[ "Finalizes", "the", "masked", "array", "." ]
def __array_finalize__(self, obj): """Finalizes the masked array. """ # Get main attributes ......... self._update_from(obj) if isinstance(obj, ndarray): odtype = obj.dtype if odtype.names: _mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype)) else: _mask = getattr(obj, '_mask', nomask) else: _mask = nomask self._mask = _mask # Finalize the mask ........... if self._mask is not nomask: try: self._mask.shape = self.shape except ValueError: self._mask = nomask except (TypeError, AttributeError): # When _mask.shape is not writable (because it's a void) pass # Finalize the fill_value for structured arrays if self.dtype.names: if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) return
[ "def", "__array_finalize__", "(", "self", ",", "obj", ")", ":", "# Get main attributes .........", "self", ".", "_update_from", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "ndarray", ")", ":", "odtype", "=", "obj", ".", "dtype", "if", "odtype", "...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L2774-L2801
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/command/sdist.py
python
sdist.read_template
(self)
Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly.
Read and parse manifest template file named by self.template.
[ "Read", "and", "parse", "manifest", "template", "file", "named", "by", "self", ".", "template", "." ]
def read_template(self): """Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly. """ log.info("reading manifest template '%s'", self.template) template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1) try: while True: line = template.readline() if line is None: # end of file break try: self.filelist.process_template_line(line) # the call above can raise a DistutilsTemplateError for # malformed lines, or a ValueError from the lower-level # convert_path function except (DistutilsTemplateError, ValueError) as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) finally: template.close()
[ "def", "read_template", "(", "self", ")", ":", "log", ".", "info", "(", "\"reading manifest template '%s'\"", ",", "self", ".", "template", ")", "template", "=", "TextFile", "(", "self", ".", "template", ",", "strip_comments", "=", "1", ",", "skip_blanks", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/sdist.py#L324-L351
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
build-support/cpplint.py
python
CheckInvalidIncrement
(filename, clean_lines, linenum, error)
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for invalid increment *count++.
[ "Checks", "for", "invalid", "increment", "*", "count", "++", "." ]
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).')
[ "def", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "_RE_PATTERN_INVALID_INCREMENT", ".", "match", "(", "line", ")", ":", "error", ...
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L2401-L2420
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py
python
ReformattedLines._prevent_default_initializer_splitting
(self, item, indent_amt)
Prevent splitting between a default initializer. When there is a default initializer, it's best to keep it all on the same line. It's nicer and more readable, even if it goes over the maximum allowable line length. This goes back along the current line to determine if we have a default initializer, and, if so, to remove extraneous whitespaces and add a line break/indent before it if needed.
Prevent splitting between a default initializer.
[ "Prevent", "splitting", "between", "a", "default", "initializer", "." ]
def _prevent_default_initializer_splitting(self, item, indent_amt): """Prevent splitting between a default initializer. When there is a default initializer, it's best to keep it all on the same line. It's nicer and more readable, even if it goes over the maximum allowable line length. This goes back along the current line to determine if we have a default initializer, and, if so, to remove extraneous whitespaces and add a line break/indent before it if needed. """ if unicode(item) == '=': # This is the assignment in the initializer. Just remove spaces for # now. self._delete_whitespace() return if (not self._prev_item or not self._prev_prev_item or unicode(self._prev_item) != '='): return self._delete_whitespace() prev_prev_index = self._lines.index(self._prev_prev_item) if ( isinstance(self._lines[prev_prev_index - 1], self._Indent) or self.fits_on_current_line(item.size + 1) ): # The default initializer is already the only item on this line. # Don't insert a newline here. return # Replace the space with a newline/indent combo. if isinstance(self._lines[prev_prev_index - 1], self._Space): del self._lines[prev_prev_index - 1] self.add_line_break_at(self._lines.index(self._prev_prev_item), indent_amt)
[ "def", "_prevent_default_initializer_splitting", "(", "self", ",", "item", ",", "indent_amt", ")", ":", "if", "unicode", "(", "item", ")", "==", "'='", ":", "# This is the assignment in the initializer. Just remove spaces for", "# now.", "self", ".", "_delete_whitespace",...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L1696-L1733
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/ReductionWrapper.py
python
ReductionWrapper.run_reduction
(self)
Reduces runs one by one or sum all them together and reduce after this if wait_for_file time is > 0, it will until missing files appear on the data search path
Reduces runs one by one or sum all them together and reduce after this
[ "Reduces", "runs", "one", "by", "one", "or", "sum", "all", "them", "together", "and", "reduce", "after", "this" ]
def run_reduction(self): """" Reduces runs one by one or sum all them together and reduce after this if wait_for_file time is > 0, it will until missing files appear on the data search path """ try: _, r = funcinspect.lhs_info('both') out_ws_name = r[0] # no-exception-type(s) specified. Who knows what exception this internal procedure rises... # pylint: disable=W0702 except: out_ws_name = None # if this is not None, we want to run validation not reduction if self.validate_run_number: self.reducer.prop_man.log \ ("**************************************************************************************", 'warning') self.reducer.prop_man.log \ ("**************************************************************************************", 'warning') rez, mess = self.build_or_validate_result() if rez: self.reducer.prop_man.log("*** SUCCESS! {0}".format(mess)) self.reducer.prop_man.log \ ("**************************************************************************************", 'warning') else: self.reducer.prop_man.log("*** VALIDATION FAILED! {0}".format(mess)) self.reducer.prop_man.log \ ("**************************************************************************************", 'warning') raise RuntimeError("Validation against old data file failed") self.validate_run_number = None return rez, mess if self.reducer.sum_runs: # --------### sum runs provided ------------------------------------### if out_ws_name is None: self.sum_and_reduce() return None else: red_ws = self.sum_and_reduce() RenameWorkspace(InputWorkspace=red_ws, OutputWorkspace=out_ws_name) return mtd[out_ws_name] else: # --------### reduce list of runs one by one ----------------------------### runfiles = PropertyManager.sample_run.get_run_file_list() if out_ws_name is None: for file_name in runfiles: self.reduce(file_name) return None else: results = [] nruns = len(runfiles) for num, file_name in enumerate(runfiles): red_ws = self.reduce(file_name) if isinstance(red_ws, list): for ws in red_ws: results.append(ws) else: if nruns == 1: if red_ws.name() != out_ws_name: RenameWorkspace(InputWorkspace=red_ws, OutputWorkspace=out_ws_name) results.append(mtd[out_ws_name]) else: OutWSName = '{0}#{1}of{2}'.format(out_ws_name, num + 1, nruns) if red_ws.name() != out_ws_name: RenameWorkspace(InputWorkspace=red_ws, OutputWorkspace=OutWSName) results.append(mtd[OutWSName]) # end if len(results) == 1: return results[0] else: return results
[ "def", "run_reduction", "(", "self", ")", ":", "try", ":", "_", ",", "r", "=", "funcinspect", ".", "lhs_info", "(", "'both'", ")", "out_ws_name", "=", "r", "[", "0", "]", "# no-exception-type(s) specified. Who knows what exception this internal procedure rises...", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/ReductionWrapper.py#L658-L732
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/wms/ogc/common/calcs.py
python
CalcZoomLevel
(log_extent, total_log_extent, pixel_extent)
return zoom
Calculates zoom level. We want a zoom level that has enough detail to match the user's request (ie we do our best not to give stretched-out pixels). A bigger zoom == more pixels + detail. But, it would be wasteful to use a higher zoom level than necessary. Args: log_extent: map-space width, height. total_log_extent: total defined map-space extent (size of projection bounds, in its output coordinates). pixel_extent: desired width, height of the final pixel image. Returns: zoom level with at least as much detail as required.
Calculates zoom level.
[ "Calculates", "zoom", "level", "." ]
def CalcZoomLevel(log_extent, total_log_extent, pixel_extent): """Calculates zoom level. We want a zoom level that has enough detail to match the user's request (ie we do our best not to give stretched-out pixels). A bigger zoom == more pixels + detail. But, it would be wasteful to use a higher zoom level than necessary. Args: log_extent: map-space width, height. total_log_extent: total defined map-space extent (size of projection bounds, in its output coordinates). pixel_extent: desired width, height of the final pixel image. Returns: zoom level with at least as much detail as required. """ utils.Assert(isinstance(log_extent, geom.Pair)) utils.Assert(isinstance(total_log_extent, geom.Pair)) utils.Assert(isinstance(pixel_extent, geom.Pair)) # Simple, component-wise division. fraction_of_total = log_extent / total_log_extent utils.logger.debug('fraction %s' % str(fraction_of_total)) total_pixel_extent_needed = pixel_extent / fraction_of_total utils.logger.debug('pixel extent needed %s' % str(total_pixel_extent_needed)) # We want to round the zoom level up; ie, have /at least/ 1 tile pixel # per requested pixel. # 256 x 2^zoom >= totalpixelextent => zoom = log_2(totalpixelextent / 256) x_zoom = int(math.log(math.ceil(total_pixel_extent_needed.x / 256.0), 2)) y_zoom = int(math.log(math.ceil(total_pixel_extent_needed.y / 256.0), 2)) utils.logger.debug('zoom:x,y %s, %s' % (str(x_zoom), str(y_zoom))) zoom = max(x_zoom, y_zoom) if _MAX_ZOOM < zoom: utils.logger.warning('WHOA; wild zoom (%s - should be max 23), ' 'alert Google. Limiting to 23.' % str(zoom)) zoom = _MAX_ZOOM return zoom
[ "def", "CalcZoomLevel", "(", "log_extent", ",", "total_log_extent", ",", "pixel_extent", ")", ":", "utils", ".", "Assert", "(", "isinstance", "(", "log_extent", ",", "geom", ".", "Pair", ")", ")", "utils", ".", "Assert", "(", "isinstance", "(", "total_log_ex...
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/wms/ogc/common/calcs.py#L33-L72
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
hashtable/separate_chaining.py
python
main
()
operational function
operational function
[ "operational", "function" ]
def main(): """ operational function """ table = HashTable() table["march 6"] = 120 table["march 6"] = 78 table["march 8"] = 67 table["march 9"] = 4 table["march 17"] = 459 print(table["march 6"]) # 78 print(table["march 17"]) # 459 del table["march 17"] print(table["march 17"])
[ "def", "main", "(", ")", ":", "table", "=", "HashTable", "(", ")", "table", "[", "\"march 6\"", "]", "=", "120", "table", "[", "\"march 6\"", "]", "=", "78", "table", "[", "\"march 8\"", "]", "=", "67", "table", "[", "\"march 9\"", "]", "=", "4", "...
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/hashtable/separate_chaining.py#L35-L48
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/stringold.py
python
swapcase
(s)
return s.swapcase()
swapcase(s) -> string Return a copy of the string s with upper case characters converted to lowercase and vice versa.
swapcase(s) -> string
[ "swapcase", "(", "s", ")", "-", ">", "string" ]
def swapcase(s): """swapcase(s) -> string Return a copy of the string s with upper case characters converted to lowercase and vice versa. """ return s.swapcase()
[ "def", "swapcase", "(", "s", ")", ":", "return", "s", ".", "swapcase", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/stringold.py#L64-L71
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py
python
_ReductionDims
(x, axis, reduction_indices=None)
Returns range(0, rank(x)) if reduction_indices is None.
Returns range(0, rank(x)) if reduction_indices is None.
[ "Returns", "range", "(", "0", "rank", "(", "x", "))", "if", "reduction_indices", "is", "None", "." ]
def _ReductionDims(x, axis, reduction_indices=None): # pylint: disable=invalid-name """Returns range(0, rank(x)) if reduction_indices is None.""" # TODO(aselle): Remove this after deprecation if reduction_indices is not None: if axis is not None: raise ValueError("Can't specify both axis' and 'reduction_indices'.") axis = reduction_indices if axis is not None: return axis else: # Fast path: avoid creating Rank and Range ops if ndims is known. rank = common_shapes.rank(x) if rank is not None: return constant_op.constant(np.arange(rank), dtype=dtypes.int32) if (isinstance(x, sparse_tensor.SparseTensor) and x.dense_shape.shape.is_fully_defined()): rank = x.dense_shape.shape.dims[0].value # sparse.dense_shape is 1-D. return constant_op.constant(np.arange(rank), dtype=dtypes.int32) # Otherwise, we rely on Range and Rank to do the right thing at run-time. return range(0, array_ops.rank(x))
[ "def", "_ReductionDims", "(", "x", ",", "axis", ",", "reduction_indices", "=", "None", ")", ":", "# pylint: disable=invalid-name", "# TODO(aselle): Remove this after deprecation", "if", "reduction_indices", "is", "not", "None", ":", "if", "axis", "is", "not", "None", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py#L1431-L1451
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/animate.py
python
AnimationCtrlBase.SetAnimation
(*args, **kwargs)
return _animate.AnimationCtrlBase_SetAnimation(*args, **kwargs)
SetAnimation(self, Animation anim)
SetAnimation(self, Animation anim)
[ "SetAnimation", "(", "self", "Animation", "anim", ")" ]
def SetAnimation(*args, **kwargs): """SetAnimation(self, Animation anim)""" return _animate.AnimationCtrlBase_SetAnimation(*args, **kwargs)
[ "def", "SetAnimation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_animate", ".", "AnimationCtrlBase_SetAnimation", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/animate.py#L156-L158
shader-slang/slang
b8982fcf43b86c1e39dcc3dd19bff2821633eda6
external/vulkan/registry/generator.py
python
enquote
(s)
return None
Return string argument with surrounding quotes, for serialization into Python code.
Return string argument with surrounding quotes, for serialization into Python code.
[ "Return", "string", "argument", "with", "surrounding", "quotes", "for", "serialization", "into", "Python", "code", "." ]
def enquote(s): """Return string argument with surrounding quotes, for serialization into Python code.""" if s: return "'{}'".format(s) return None
[ "def", "enquote", "(", "s", ")", ":", "if", "s", ":", "return", "\"'{}'\"", ".", "format", "(", "s", ")", "return", "None" ]
https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/generator.py#L42-L47
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeCtrl.SortChildren
(*args, **kwargs)
return _controls_.TreeCtrl_SortChildren(*args, **kwargs)
SortChildren(self, TreeItemId item)
SortChildren(self, TreeItemId item)
[ "SortChildren", "(", "self", "TreeItemId", "item", ")" ]
def SortChildren(*args, **kwargs): """SortChildren(self, TreeItemId item)""" return _controls_.TreeCtrl_SortChildren(*args, **kwargs)
[ "def", "SortChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_SortChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5546-L5548
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/pydoc.py
python
HTMLDoc.filelink
(self, url, path)
return '<a href="file:%s">%s</a>' % (url, path)
Make a link to source file.
Make a link to source file.
[ "Make", "a", "link", "to", "source", "file", "." ]
def filelink(self, url, path): """Make a link to source file.""" return '<a href="file:%s">%s</a>' % (url, path)
[ "def", "filelink", "(", "self", ",", "url", ",", "path", ")", ":", "return", "'<a href=\"file:%s\">%s</a>'", "%", "(", "url", ",", "path", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pydoc.py#L583-L585
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py
python
spawn.setwinsize
(self, rows, cols)
return self.ptyproc.setwinsize(rows, cols)
This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal.
This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal.
[ "This", "sets", "the", "terminal", "window", "size", "of", "the", "child", "tty", ".", "This", "will", "cause", "a", "SIGWINCH", "signal", "to", "be", "sent", "to", "the", "child", ".", "This", "does", "not", "change", "the", "physical", "window", "size"...
def setwinsize(self, rows, cols): '''This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal. ''' return self.ptyproc.setwinsize(rows, cols)
[ "def", "setwinsize", "(", "self", ",", "rows", ",", "cols", ")", ":", "return", "self", ".", "ptyproc", ".", "setwinsize", "(", "rows", ",", "cols", ")" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py#L707-L713
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/wrappers/local_cli_wrapper.py
python
LocalCLIDebugWrapperSession.invoke_node_stepper
(self, node_stepper, restore_variable_values_on_exit=True)
return stepper_ui.run_ui( init_command="lt", title="Node Stepper: " + self._run_description, title_color="blue_on_white")
Overrides method in base class to implement interactive node stepper. Args: node_stepper: (`stepper.NodeStepper`) The underlying NodeStepper API object. restore_variable_values_on_exit: (`bool`) Whether any variables whose values have been altered during this node-stepper invocation should be restored to their old values when this invocation ends. Returns: The same return values as the `Session.run()` call on the same fetches as the NodeStepper.
Overrides method in base class to implement interactive node stepper.
[ "Overrides", "method", "in", "base", "class", "to", "implement", "interactive", "node", "stepper", "." ]
def invoke_node_stepper(self, node_stepper, restore_variable_values_on_exit=True): """Overrides method in base class to implement interactive node stepper. Args: node_stepper: (`stepper.NodeStepper`) The underlying NodeStepper API object. restore_variable_values_on_exit: (`bool`) Whether any variables whose values have been altered during this node-stepper invocation should be restored to their old values when this invocation ends. Returns: The same return values as the `Session.run()` call on the same fetches as the NodeStepper. """ stepper = stepper_cli.NodeStepperCLI(node_stepper) # On exiting the node-stepper CLI, the finalize method of the node_stepper # object will be called, ensuring that the state of the graph will be the # same as if the stepping did not happen. # TODO(cais): Perhaps some users will want the effect of the interactive # stepping and value injection to persist. When that happens, make the call # to finalize optional. stepper_ui = ui_factory.get_ui( self._ui_type, on_ui_exit=(node_stepper.restore_variable_values if restore_variable_values_on_exit else None)) stepper_ui.register_command_handler( "list_sorted_nodes", stepper.list_sorted_nodes, stepper.arg_parsers["list_sorted_nodes"].format_help(), prefix_aliases=["lt", "lsn"]) stepper_ui.register_command_handler( "cont", stepper.cont, stepper.arg_parsers["cont"].format_help(), prefix_aliases=["ct", "c"]) stepper_ui.register_command_handler( "step", stepper.step, stepper.arg_parsers["step"].format_help(), prefix_aliases=["st", "s"]) stepper_ui.register_command_handler( "print_tensor", stepper.print_tensor, stepper.arg_parsers["print_tensor"].format_help(), prefix_aliases=["pt"]) stepper_ui.register_command_handler( "inject_value", stepper.inject_value, stepper.arg_parsers["inject_value"].format_help(), prefix_aliases=["inject", "override_value", "override"]) # Register tab completion candidates. stepper_ui.register_tab_comp_context([ "cont", "ct", "c", "pt", "inject_value", "inject", "override_value", "override" ], [str(elem) for elem in node_stepper.sorted_nodes()]) # TODO(cais): Tie up register_tab_comp_context to a single alias to shorten # calls like this. return stepper_ui.run_ui( init_command="lt", title="Node Stepper: " + self._run_description, title_color="blue_on_white")
[ "def", "invoke_node_stepper", "(", "self", ",", "node_stepper", ",", "restore_variable_values_on_exit", "=", "True", ")", ":", "stepper", "=", "stepper_cli", ".", "NodeStepperCLI", "(", "node_stepper", ")", "# On exiting the node-stepper CLI, the finalize method of the node_s...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/wrappers/local_cli_wrapper.py#L625-L692
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.GetSizer
(*args, **kwargs)
return _core_.Window_GetSizer(*args, **kwargs)
GetSizer(self) -> Sizer Return the sizer associated with the window by a previous call to SetSizer or None if there isn't one.
GetSizer(self) -> Sizer
[ "GetSizer", "(", "self", ")", "-", ">", "Sizer" ]
def GetSizer(*args, **kwargs): """ GetSizer(self) -> Sizer Return the sizer associated with the window by a previous call to SetSizer or None if there isn't one. """ return _core_.Window_GetSizer(*args, **kwargs)
[ "def", "GetSizer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetSizer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L11524-L11531
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/parallel/_cost_model_context.py
python
_CostModelContext.set_costmodel_communi_threshold
(self, threshold)
Set costmodel communication threshold. Args: threshold (float): A parameter used in adjusting communication calculation for practice. Raises: ValueError: If context handle is none.
Set costmodel communication threshold.
[ "Set", "costmodel", "communication", "threshold", "." ]
def set_costmodel_communi_threshold(self, threshold): """ Set costmodel communication threshold. Args: threshold (float): A parameter used in adjusting communication calculation for practice. Raises: ValueError: If context handle is none. """ if self._context_handle is None: raise ValueError("Context handle is none in context!!!") self._context_handle.set_costmodel_communi_threshold(threshold)
[ "def", "set_costmodel_communi_threshold", "(", "self", ",", "threshold", ")", ":", "if", "self", ".", "_context_handle", "is", "None", ":", "raise", "ValueError", "(", "\"Context handle is none in context!!!\"", ")", "self", ".", "_context_handle", ".", "set_costmodel...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/parallel/_cost_model_context.py#L142-L154
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py
python
BackgroundCorrectionsView.background_correction_mode
(self, mode: str)
Sets the currently selected background correction mode.
Sets the currently selected background correction mode.
[ "Sets", "the", "currently", "selected", "background", "correction", "mode", "." ]
def background_correction_mode(self, mode: str) -> None: """Sets the currently selected background correction mode.""" index = self.mode_combo_box.findText(mode) if index != -1: self.mode_combo_box.setCurrentIndex(index)
[ "def", "background_correction_mode", "(", "self", ",", "mode", ":", "str", ")", "->", "None", ":", "index", "=", "self", ".", "mode_combo_box", ".", "findText", "(", "mode", ")", "if", "index", "!=", "-", "1", ":", "self", ".", "mode_combo_box", ".", "...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py#L160-L164
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_math_ops.py
python
get_bprop_assign_sub
(self)
return bprop
Grad definition for `AssignSub` operation.
Grad definition for `AssignSub` operation.
[ "Grad", "definition", "for", "AssignSub", "operation", "." ]
def get_bprop_assign_sub(self): """Grad definition for `AssignSub` operation.""" def bprop(x, y, out, dout): return zeros_like(x), zeros_like(y) return bprop
[ "def", "get_bprop_assign_sub", "(", "self", ")", ":", "def", "bprop", "(", "x", ",", "y", ",", "out", ",", "dout", ")", ":", "return", "zeros_like", "(", "x", ")", ",", "zeros_like", "(", "y", ")", "return", "bprop" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_math_ops.py#L1036-L1042
CoolProp/CoolProp
381c8535e5dec3eec27ad430ebbfff8bc9dfc008
dev/incompressible_liquids/CPIncomp/DataObjects.py
python
CoefficientData.convertMelinderMatrix
(self, array)
return tmp
Function to convert the full coefficient array from the very first CoolProp implementation based on the book by Melinder
Function to convert the full coefficient array from the very first CoolProp implementation based on the book by Melinder
[ "Function", "to", "convert", "the", "full", "coefficient", "array", "from", "the", "very", "first", "CoolProp", "implementation", "based", "on", "the", "book", "by", "Melinder" ]
def convertMelinderMatrix(self, array): """Function to convert the full coefficient array from the very first CoolProp implementation based on the book by Melinder""" if len(array) != 18: raise ValueError("The length is not equal to 18!") if len(array[0]) != 5: raise ValueError("The length is not equal to 5!") array = np.array(array) tmp = np.zeros((18, 5)) for j in range(5): tmp[0][j] = array[0][j] tmp[1][j] = array[4][j] tmp[2][j] = array[8][j] tmp[3][j] = array[12][j] tmp[4][j] = array[15][j] tmp[5][j] = array[17][j] tmp[6][j] = array[1][j] tmp[7][j] = array[5][j] tmp[8][j] = array[9][j] tmp[9][j] = array[13][j] tmp[10][j] = array[16][j] tmp[11][j] = array[2][j] tmp[12][j] = array[6][j] tmp[13][j] = array[10][j] tmp[14][j] = array[14][j] tmp[15][j] = array[3][j] tmp[16][j] = array[7][j] tmp[17][j] = array[11][j] return tmp
[ "def", "convertMelinderMatrix", "(", "self", ",", "array", ")", ":", "if", "len", "(", "array", ")", "!=", "18", ":", "raise", "ValueError", "(", "\"The length is not equal to 18!\"", ")", "if", "len", "(", "array", "[", "0", "]", ")", "!=", "5", ":", ...
https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/dev/incompressible_liquids/CPIncomp/DataObjects.py#L494-L525
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
chrome/tools/webforms_aggregator.py
python
Crawler.__del__
(self)
Deletes cookie file when Crawler instances are destroyed.
Deletes cookie file when Crawler instances are destroyed.
[ "Deletes", "cookie", "file", "when", "Crawler", "instances", "are", "destroyed", "." ]
def __del__(self): """Deletes cookie file when Crawler instances are destroyed.""" if hasattr(self, '_cookie_file'): self.logger.info('Deleting cookie file %s ...', self._cookie_file) os.unlink(self._cookie_file)
[ "def", "__del__", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_cookie_file'", ")", ":", "self", ".", "logger", ".", "info", "(", "'Deleting cookie file %s ...'", ",", "self", ".", "_cookie_file", ")", "os", ".", "unlink", "(", "self", "."...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/tools/webforms_aggregator.py#L370-L374
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlTextReaderLocator.LineNumber
(self)
return ret
Obtain the line number for the given locator.
Obtain the line number for the given locator.
[ "Obtain", "the", "line", "number", "for", "the", "given", "locator", "." ]
def LineNumber(self): """Obtain the line number for the given locator. """ ret = libxml2mod.xmlTextReaderLocatorLineNumber(self._o) return ret
[ "def", "LineNumber", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderLocatorLineNumber", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L5725-L5728
redpony/cdec
f7c4899b174d86bc70b40b1cae68dcad364615cb
python/cdec/configobj.py
python
Section.__getitem__
(self, key)
return val
Fetch the item and do string interpolation.
Fetch the item and do string interpolation.
[ "Fetch", "the", "item", "and", "do", "string", "interpolation", "." ]
def __getitem__(self, key): """Fetch the item and do string interpolation.""" val = dict.__getitem__(self, key) if self.main.interpolation: if isinstance(val, basestring): return self._interpolate(key, val) if isinstance(val, list): def _check(entry): if isinstance(entry, basestring): return self._interpolate(key, entry) return entry new = [_check(entry) for entry in val] if new != val: return new return val
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "val", "=", "dict", ".", "__getitem__", "(", "self", ",", "key", ")", "if", "self", ".", "main", ".", "interpolation", ":", "if", "isinstance", "(", "val", ",", "basestring", ")", ":", "return"...
https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L565-L579
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/optim/adafactor.py
python
_approx_sq_grad
(exp_avg_sq_row, exp_avg_sq_col)
return P.Mul()(r_factor, c_factor)
Approximation of exponential moving average of square of gradient
Approximation of exponential moving average of square of gradient
[ "Approximation", "of", "exponential", "moving", "average", "of", "square", "of", "gradient" ]
def _approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col): """Approximation of exponential moving average of square of gradient""" reduce_mean = P.ReduceMean(keep_dims=True)(exp_avg_sq_row, -1) div_val = 1.0 / P.Sqrt()(P.Div()(exp_avg_sq_row, reduce_mean)) r_factor = (P.ExpandDims()(div_val, -1)) exp_avg_sq_col = P.ExpandDims()(exp_avg_sq_col, -2) c_factor = 1.0 / P.Sqrt()(exp_avg_sq_col) return P.Mul()(r_factor, c_factor)
[ "def", "_approx_sq_grad", "(", "exp_avg_sq_row", ",", "exp_avg_sq_col", ")", ":", "reduce_mean", "=", "P", ".", "ReduceMean", "(", "keep_dims", "=", "True", ")", "(", "exp_avg_sq_row", ",", "-", "1", ")", "div_val", "=", "1.0", "/", "P", ".", "Sqrt", "("...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/optim/adafactor.py#L36-L44
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
external/tools/build/v2/util/utility.py
python
replace_grist
(features, new_grist)
Replaces the grist of a string by a new one. Returns the string with the new grist.
Replaces the grist of a string by a new one. Returns the string with the new grist.
[ "Replaces", "the", "grist", "of", "a", "string", "by", "a", "new", "one", ".", "Returns", "the", "string", "with", "the", "new", "grist", "." ]
def replace_grist (features, new_grist): """ Replaces the grist of a string by a new one. Returns the string with the new grist. """ def replace_grist_one (name, new_grist): split = __re_grist_and_value.match (name) if not split: return new_grist + name else: return new_grist + split.group (2) if isinstance (features, str): return replace_grist_one (features, new_grist) else: return [ replace_grist_one (feature, new_grist) for feature in features ]
[ "def", "replace_grist", "(", "features", ",", "new_grist", ")", ":", "def", "replace_grist_one", "(", "name", ",", "new_grist", ")", ":", "split", "=", "__re_grist_and_value", ".", "match", "(", "name", ")", "if", "not", "split", ":", "return", "new_grist", ...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/util/utility.py#L55-L69
HackWebRTC/webrtc
7abfc990c00ab35090fff285fcf635d1d7892433
PRESUBMIT.py
python
CheckNativeApiHeaderChanges
(input_api, output_api)
return []
Checks to remind proper changing of native APIs.
Checks to remind proper changing of native APIs.
[ "Checks", "to", "remind", "proper", "changing", "of", "native", "APIs", "." ]
def CheckNativeApiHeaderChanges(input_api, output_api): """Checks to remind proper changing of native APIs.""" files = [] source_file_filter = lambda x: input_api.FilterSourceFile( x, white_list=[r'.+\.(gn|gni|h)$']) for f in input_api.AffectedSourceFiles(source_file_filter): for path in API_DIRS: dn = os.path.dirname(f.LocalPath()) if path == 'api': # Special case: Subdirectories included. if dn == 'api' or dn.startswith('api/'): files.append(f.LocalPath()) else: # Normal case: Subdirectories not included. if dn == path: files.append(f.LocalPath()) if files: return [output_api.PresubmitNotifyResult(API_CHANGE_MSG, files)] return []
[ "def", "CheckNativeApiHeaderChanges", "(", "input_api", ",", "output_api", ")", ":", "files", "=", "[", "]", "source_file_filter", "=", "lambda", "x", ":", "input_api", ".", "FilterSourceFile", "(", "x", ",", "white_list", "=", "[", "r'.+\\.(gn|gni|h)$'", "]", ...
https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/PRESUBMIT.py#L167-L186
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py
python
NDFrame._construct_axes_dict
(self, axes=None, **kwargs)
return d
Return an axes dictionary for myself.
Return an axes dictionary for myself.
[ "Return", "an", "axes", "dictionary", "for", "myself", "." ]
def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d
[ "def", "_construct_axes_dict", "(", "self", ",", "axes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "d", "=", "{", "a", ":", "self", ".", "_get_axis", "(", "a", ")", "for", "a", "in", "(", "axes", "or", "self", ".", "_AXIS_ORDERS", ")", "}",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L343-L347
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/descriptor_pool.py
python
DescriptorPool.AddSerializedFile
(self, serialized_file_desc_proto)
Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add.
Adds the FileDescriptorProto and its types to this pool.
[ "Adds", "the", "FileDescriptorProto", "and", "its", "types", "to", "this", "pool", "." ]
def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. """ # pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pb2 file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( serialized_file_desc_proto) self.Add(file_desc_proto)
[ "def", "AddSerializedFile", "(", "self", ",", "serialized_file_desc_proto", ")", ":", "# pylint: disable=g-import-not-at-top", "from", "google", ".", "protobuf", "import", "descriptor_pb2", "file_desc_proto", "=", "descriptor_pb2", ".", "FileDescriptorProto", ".", "FromStri...
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/descriptor_pool.py#L148-L160
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py
python
NDFrame._needs_reindex_multi
(self, axes, method, level)
return ( (com.count_not_none(*axes.values()) == self._AXIS_LEN) and method is None and level is None and not self._is_mixed_type )
Check if we do need a multi reindex.
Check if we do need a multi reindex.
[ "Check", "if", "we", "do", "need", "a", "multi", "reindex", "." ]
def _needs_reindex_multi(self, axes, method, level) -> bool_t: """Check if we do need a multi reindex.""" return ( (com.count_not_none(*axes.values()) == self._AXIS_LEN) and method is None and level is None and not self._is_mixed_type )
[ "def", "_needs_reindex_multi", "(", "self", ",", "axes", ",", "method", ",", "level", ")", "->", "bool_t", ":", "return", "(", "(", "com", ".", "count_not_none", "(", "*", "axes", ".", "values", "(", ")", ")", "==", "self", ".", "_AXIS_LEN", ")", "an...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py#L4572-L4579
ARM-software/armnn
5e9965cae1cc6162649910f423ebd86001fc1931
python/pyarmnn/src/pyarmnn/_tensor/workload_tensors.py
python
make_input_tensors
(inputs_binding_info: List[Tuple], input_data: List[np.ndarray])
return input_tensors
Returns `inputTensors` to be used with `IRuntime.EnqueueWorkload`. This is the primary function to call when you want to produce `inputTensors` for `IRuntime.EnqueueWorkload`. The output is a list of tuples containing ConstTensors with a corresponding input tensor id. The output should be used directly with `IRuntime.EnqueueWorkload`. This function works for single or multiple input data and binding information. Examples: Creating inputTensors. >>> import pyarmnn as ann >>> import numpy as np >>> >>> parser = ann.ITfLiteParser() >>> ... >>> example_image = np.array(...) >>> input_binding_info = parser.GetNetworkInputBindingInfo(...) >>> >>> input_tensors = ann.make_input_tensors([input_binding_info], [example_image]) Args: inputs_binding_info (list of tuples): (int, `TensorInfo`) Binding information for input tensors obtained from `GetNetworkInputBindingInfo`. input_data (list ndarrays): Tensor data to be used for inference. Returns: list: `inputTensors` - A list of tuples (`int` , `ConstTensor`). Raises: ValueError: If length of `inputs_binding_info` and `input_data` are not the same.
Returns `inputTensors` to be used with `IRuntime.EnqueueWorkload`.
[ "Returns", "inputTensors", "to", "be", "used", "with", "IRuntime", ".", "EnqueueWorkload", "." ]
def make_input_tensors(inputs_binding_info: List[Tuple], input_data: List[np.ndarray]) -> List[Tuple[int, ConstTensor]]: """Returns `inputTensors` to be used with `IRuntime.EnqueueWorkload`. This is the primary function to call when you want to produce `inputTensors` for `IRuntime.EnqueueWorkload`. The output is a list of tuples containing ConstTensors with a corresponding input tensor id. The output should be used directly with `IRuntime.EnqueueWorkload`. This function works for single or multiple input data and binding information. Examples: Creating inputTensors. >>> import pyarmnn as ann >>> import numpy as np >>> >>> parser = ann.ITfLiteParser() >>> ... >>> example_image = np.array(...) >>> input_binding_info = parser.GetNetworkInputBindingInfo(...) >>> >>> input_tensors = ann.make_input_tensors([input_binding_info], [example_image]) Args: inputs_binding_info (list of tuples): (int, `TensorInfo`) Binding information for input tensors obtained from `GetNetworkInputBindingInfo`. input_data (list ndarrays): Tensor data to be used for inference. Returns: list: `inputTensors` - A list of tuples (`int` , `ConstTensor`). Raises: ValueError: If length of `inputs_binding_info` and `input_data` are not the same. """ if len(inputs_binding_info) != len(input_data): raise ValueError("Length of 'inputs_binding_info' does not match length of 'input_data'") input_tensors = [] for in_bind_info, in_data in zip(inputs_binding_info, input_data): in_tensor_id = in_bind_info[0] in_tensor_info = in_bind_info[1] in_tensor_info.SetConstant() input_tensors.append((in_tensor_id, ConstTensor(in_tensor_info, in_data))) return input_tensors
[ "def", "make_input_tensors", "(", "inputs_binding_info", ":", "List", "[", "Tuple", "]", ",", "input_data", ":", "List", "[", "np", ".", "ndarray", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "ConstTensor", "]", "]", ":", "if", "len", "(", ...
https://github.com/ARM-software/armnn/blob/5e9965cae1cc6162649910f423ebd86001fc1931/python/pyarmnn/src/pyarmnn/_tensor/workload_tensors.py#L16-L60
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
ArrayStringProperty_ArrayStringToString
(*args, **kwargs)
return _propgrid.ArrayStringProperty_ArrayStringToString(*args, **kwargs)
ArrayStringProperty_ArrayStringToString(String dst, wxArrayString src, wxUniChar delimiter, int flags)
ArrayStringProperty_ArrayStringToString(String dst, wxArrayString src, wxUniChar delimiter, int flags)
[ "ArrayStringProperty_ArrayStringToString", "(", "String", "dst", "wxArrayString", "src", "wxUniChar", "delimiter", "int", "flags", ")" ]
def ArrayStringProperty_ArrayStringToString(*args, **kwargs): """ ArrayStringProperty_ArrayStringToString(String dst, wxArrayString src, wxUniChar delimiter, int flags) """ return _propgrid.ArrayStringProperty_ArrayStringToString(*args, **kwargs)
[ "def", "ArrayStringProperty_ArrayStringToString", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "ArrayStringProperty_ArrayStringToString", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3160-L3165
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/core/defchararray.py
python
strip
(a, chars=None)
return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars))
For each element in `a`, return a copy with the leading and trailing characters removed. Calls `str.rstrip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix or suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.strip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.strip(c) array(['aAaAaA', 'aA', 'abBABba'], dtype='|S7') >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads array(['AaAaA', ' aA ', 'bBABb'], dtype='|S7') >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails array(['aAaAa', ' aA ', 'abBABba'], dtype='|S7')
For each element in `a`, return a copy with the leading and trailing characters removed.
[ "For", "each", "element", "in", "a", "return", "a", "copy", "with", "the", "leading", "and", "trailing", "characters", "removed", "." ]
def strip(a, chars=None): """ For each element in `a`, return a copy with the leading and trailing characters removed. Calls `str.rstrip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix or suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.strip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.strip(c) array(['aAaAaA', 'aA', 'abBABba'], dtype='|S7') >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads array(['AaAaA', ' aA ', 'bBABb'], dtype='|S7') >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails array(['aAaAa', ' aA ', 'abBABba'], dtype='|S7') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars))
[ "def", "strip", "(", "a", ",", "chars", "=", "None", ")", ":", "a_arr", "=", "numpy", ".", "asarray", "(", "a", ")", "return", "_vec_string", "(", "a_arr", ",", "a_arr", ".", "dtype", ",", "'strip'", ",", "_clean_args", "(", "chars", ")", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/defchararray.py#L1427-L1472
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/asyncio/base_events.py
python
BaseEventLoop.call_soon_threadsafe
(self, callback, *args, context=None)
return handle
Like call_soon(), but thread-safe.
Like call_soon(), but thread-safe.
[ "Like", "call_soon", "()", "but", "thread", "-", "safe", "." ]
def call_soon_threadsafe(self, callback, *args, context=None): """Like call_soon(), but thread-safe.""" self._check_closed() if self._debug: self._check_callback(callback, 'call_soon_threadsafe') handle = self._call_soon(callback, args, context) if handle._source_traceback: del handle._source_traceback[-1] self._write_to_self() return handle
[ "def", "call_soon_threadsafe", "(", "self", ",", "callback", ",", "*", "args", ",", "context", "=", "None", ")", ":", "self", ".", "_check_closed", "(", ")", "if", "self", ".", "_debug", ":", "self", ".", "_check_callback", "(", "callback", ",", "'call_s...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/base_events.py#L789-L798
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/actor/Actor.py
python
Actor.getDuration
(self, animName=None, partName=None, fromFrame=None, toFrame=None)
return ((toFrame+1)-fromFrame) / animControl.getFrameRate()
Return duration of given anim name and given part. If no anim specified, use the currently playing anim. If no part specified, return anim duration of first part. NOTE: returns info for arbitrary LOD
Return duration of given anim name and given part. If no anim specified, use the currently playing anim. If no part specified, return anim duration of first part. NOTE: returns info for arbitrary LOD
[ "Return", "duration", "of", "given", "anim", "name", "and", "given", "part", ".", "If", "no", "anim", "specified", "use", "the", "currently", "playing", "anim", ".", "If", "no", "part", "specified", "return", "anim", "duration", "of", "first", "part", ".",...
def getDuration(self, animName=None, partName=None, fromFrame=None, toFrame=None): """ Return duration of given anim name and given part. If no anim specified, use the currently playing anim. If no part specified, return anim duration of first part. NOTE: returns info for arbitrary LOD """ lodName = next(iter(self.__animControlDict)) controls = self.getAnimControls(animName, partName) if len(controls) == 0: return None animControl = controls[0] if fromFrame is None: fromFrame = 0 if toFrame is None: toFrame = animControl.getNumFrames()-1 return ((toFrame+1)-fromFrame) / animControl.getFrameRate()
[ "def", "getDuration", "(", "self", ",", "animName", "=", "None", ",", "partName", "=", "None", ",", "fromFrame", "=", "None", ",", "toFrame", "=", "None", ")", ":", "lodName", "=", "next", "(", "iter", "(", "self", ".", "__animControlDict", ")", ")", ...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/actor/Actor.py#L873-L891
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
shell/ext-py/prettytable-0.7.2/prettytable.py
python
PrettyTable._get_header
(self)
return self._header
Controls printing of table header with field names Arguments: header - print a header showing field names (True or False)
Controls printing of table header with field names
[ "Controls", "printing", "of", "table", "header", "with", "field", "names" ]
def _get_header(self): """Controls printing of table header with field names Arguments: header - print a header showing field names (True or False)""" return self._header
[ "def", "_get_header", "(", "self", ")", ":", "return", "self", ".", "_header" ]
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/ext-py/prettytable-0.7.2/prettytable.py#L533-L539
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
native_client_sdk/src/build_tools/manifest_util.py
python
DictToJSON
(pydict)
return '\n'.join([line.rstrip() for line in pretty_lines]) + '\n'
Convert a dict to a JSON-formatted string.
Convert a dict to a JSON-formatted string.
[ "Convert", "a", "dict", "to", "a", "JSON", "-", "formatted", "string", "." ]
def DictToJSON(pydict): """Convert a dict to a JSON-formatted string.""" pretty_string = json.dumps(pydict, sort_keys=True, indent=2) # json.dumps sometimes returns trailing whitespace and does not put # a newline at the end. This code fixes these problems. pretty_lines = pretty_string.split('\n') return '\n'.join([line.rstrip() for line in pretty_lines]) + '\n'
[ "def", "DictToJSON", "(", "pydict", ")", ":", "pretty_string", "=", "json", ".", "dumps", "(", "pydict", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")", "# json.dumps sometimes returns trailing whitespace and does not put", "# a newline at the end. This co...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/build_tools/manifest_util.py#L52-L58