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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/stats/stats.py
python
_iqr_nanpercentile
(x, q, axis=None, interpolation='linear', keepdims=False, contains_nan=False)
return result
Private wrapper that works around the following: 1. A bug in `np.nanpercentile` that was around until numpy version 1.11.0. 2. A bug in `np.percentile` NaN handling that was fixed in numpy version 1.10.0. 3. The non-existence of `np.nanpercentile` before numpy version 1.9.0. While this function is pretty much necessary for the moment, it should be removed as soon as the minimum supported numpy version allows.
Private wrapper that works around the following:
[ "Private", "wrapper", "that", "works", "around", "the", "following", ":" ]
def _iqr_nanpercentile(x, q, axis=None, interpolation='linear', keepdims=False, contains_nan=False): """ Private wrapper that works around the following: 1. A bug in `np.nanpercentile` that was around until numpy version 1.11.0. 2. A bug in `np.percentile` NaN handling that was fixed in numpy version 1.10.0. 3. The non-existence of `np.nanpercentile` before numpy version 1.9.0. While this function is pretty much necessary for the moment, it should be removed as soon as the minimum supported numpy version allows. """ if hasattr(np, 'nanpercentile'): # At time or writing, this means np.__version__ < 1.9.0 result = np.nanpercentile(x, q, axis=axis, interpolation=interpolation, keepdims=keepdims) # If non-scalar result and nanpercentile does not do proper axis roll. # I see no way of avoiding the version test since dimensions may just # happen to match in the data. if result.ndim > 1 and NumpyVersion(np.__version__) < '1.11.0a': axis = np.asarray(axis) if axis.size == 1: # If only one axis specified, reduction happens along that dimension if axis.ndim == 0: axis = axis[None] result = np.rollaxis(result, axis[0]) else: # If multiple axes, reduced dimeision is last result = np.rollaxis(result, -1) else: msg = "Keyword nan_policy='omit' not correctly supported for numpy " \ "versions < 1.9.x. The default behavior of numpy.percentile " \ "will be used." warnings.warn(msg, RuntimeWarning) result = _iqr_percentile(x, q, axis=axis) return result
[ "def", "_iqr_nanpercentile", "(", "x", ",", "q", ",", "axis", "=", "None", ",", "interpolation", "=", "'linear'", ",", "keepdims", "=", "False", ",", "contains_nan", "=", "False", ")", ":", "if", "hasattr", "(", "np", ",", "'nanpercentile'", ")", ":", "# At time or writing, this means np.__version__ < 1.9.0", "result", "=", "np", ".", "nanpercentile", "(", "x", ",", "q", ",", "axis", "=", "axis", ",", "interpolation", "=", "interpolation", ",", "keepdims", "=", "keepdims", ")", "# If non-scalar result and nanpercentile does not do proper axis roll.", "# I see no way of avoiding the version test since dimensions may just", "# happen to match in the data.", "if", "result", ".", "ndim", ">", "1", "and", "NumpyVersion", "(", "np", ".", "__version__", ")", "<", "'1.11.0a'", ":", "axis", "=", "np", ".", "asarray", "(", "axis", ")", "if", "axis", ".", "size", "==", "1", ":", "# If only one axis specified, reduction happens along that dimension", "if", "axis", ".", "ndim", "==", "0", ":", "axis", "=", "axis", "[", "None", "]", "result", "=", "np", ".", "rollaxis", "(", "result", ",", "axis", "[", "0", "]", ")", "else", ":", "# If multiple axes, reduced dimeision is last", "result", "=", "np", ".", "rollaxis", "(", "result", ",", "-", "1", ")", "else", ":", "msg", "=", "\"Keyword nan_policy='omit' not correctly supported for numpy \"", "\"versions < 1.9.x. The default behavior of numpy.percentile \"", "\"will be used.\"", "warnings", ".", "warn", "(", "msg", ",", "RuntimeWarning", ")", "result", "=", "_iqr_percentile", "(", "x", ",", "q", ",", "axis", "=", "axis", ")", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/stats.py#L2557-L2598
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/dispatcher.py
python
_DispatcherBase._compile_for_args
(self, *args, **kws)
For internal use. Compile a specialized version of the function for the given *args* and *kws*, and return the resulting callable.
For internal use. Compile a specialized version of the function for the given *args* and *kws*, and return the resulting callable.
[ "For", "internal", "use", ".", "Compile", "a", "specialized", "version", "of", "the", "function", "for", "the", "given", "*", "args", "*", "and", "*", "kws", "*", "and", "return", "the", "resulting", "callable", "." ]
def _compile_for_args(self, *args, **kws): """ For internal use. Compile a specialized version of the function for the given *args* and *kws*, and return the resulting callable. """ assert not kws def error_rewrite(e, issue_type): """ Rewrite and raise Exception `e` with help supplied based on the specified issue_type. """ if config.SHOW_HELP: help_msg = errors.error_extras[issue_type] e.patch_message('\n'.join((str(e).rstrip(), help_msg))) if config.FULL_TRACEBACKS: raise e else: reraise(type(e), e, None) argtypes = [] for a in args: if isinstance(a, OmittedArg): argtypes.append(types.Omitted(a.value)) else: argtypes.append(self.typeof_pyval(a)) try: return self.compile(tuple(argtypes)) except errors.ForceLiteralArg as e: # Received request for compiler re-entry with the list of arguments # indicated by e.requested_args. # First, check if any of these args are already Literal-ized already_lit_pos = [i for i in e.requested_args if isinstance(args[i], types.Literal)] if already_lit_pos: # Abort compilation if any argument is already a Literal. # Letting this continue will cause infinite compilation loop. m = ("Repeated literal typing request.\n" "{}.\n" "This is likely caused by an error in typing. " "Please see nested and suppressed exceptions.") info = ', '.join('Arg #{} is {}'.format(i, args[i]) for i in sorted(already_lit_pos)) raise errors.CompilerError(m.format(info)) # Convert requested arguments into a Literal. args = [(types.literal if i in e.requested_args else lambda x: x)(args[i]) for i, v in enumerate(args)] # Re-enter compilation with the Literal-ized arguments return self._compile_for_args(*args) except errors.TypingError as e: # Intercept typing error that may be due to an argument # that failed inferencing as a Numba type failed_args = [] for i, arg in enumerate(args): val = arg.value if isinstance(arg, OmittedArg) else arg try: tp = typeof(val, Purpose.argument) except ValueError as typeof_exc: failed_args.append((i, str(typeof_exc))) else: if tp is None: failed_args.append( (i, "cannot determine Numba type of value %r" % (val,))) if failed_args: # Patch error message to ease debugging msg = str(e).rstrip() + ( "\n\nThis error may have been caused by the following argument(s):\n%s\n" % "\n".join("- argument %d: %s" % (i, err) for i, err in failed_args)) e.patch_message(msg) error_rewrite(e, 'typing') except errors.UnsupportedError as e: # Something unsupported is present in the user code, add help info error_rewrite(e, 'unsupported_error') except (errors.NotDefinedError, errors.RedefinedError, errors.VerificationError) as e: # These errors are probably from an issue with either the code supplied # being syntactically or otherwise invalid error_rewrite(e, 'interpreter') except errors.ConstantInferenceError as e: # this is from trying to infer something as constant when it isn't # or isn't supported as a constant error_rewrite(e, 'constant_inference') except Exception as e: if config.SHOW_HELP: if hasattr(e, 'patch_message'): help_msg = errors.error_extras['reportable'] e.patch_message('\n'.join((str(e).rstrip(), help_msg))) # ignore the FULL_TRACEBACKS config, this needs reporting! raise e
[ "def", "_compile_for_args", "(", "self", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "assert", "not", "kws", "def", "error_rewrite", "(", "e", ",", "issue_type", ")", ":", "\"\"\"\n Rewrite and raise Exception `e` with help supplied based on the\n specified issue_type.\n \"\"\"", "if", "config", ".", "SHOW_HELP", ":", "help_msg", "=", "errors", ".", "error_extras", "[", "issue_type", "]", "e", ".", "patch_message", "(", "'\\n'", ".", "join", "(", "(", "str", "(", "e", ")", ".", "rstrip", "(", ")", ",", "help_msg", ")", ")", ")", "if", "config", ".", "FULL_TRACEBACKS", ":", "raise", "e", "else", ":", "reraise", "(", "type", "(", "e", ")", ",", "e", ",", "None", ")", "argtypes", "=", "[", "]", "for", "a", "in", "args", ":", "if", "isinstance", "(", "a", ",", "OmittedArg", ")", ":", "argtypes", ".", "append", "(", "types", ".", "Omitted", "(", "a", ".", "value", ")", ")", "else", ":", "argtypes", ".", "append", "(", "self", ".", "typeof_pyval", "(", "a", ")", ")", "try", ":", "return", "self", ".", "compile", "(", "tuple", "(", "argtypes", ")", ")", "except", "errors", ".", "ForceLiteralArg", "as", "e", ":", "# Received request for compiler re-entry with the list of arguments", "# indicated by e.requested_args.", "# First, check if any of these args are already Literal-ized", "already_lit_pos", "=", "[", "i", "for", "i", "in", "e", ".", "requested_args", "if", "isinstance", "(", "args", "[", "i", "]", ",", "types", ".", "Literal", ")", "]", "if", "already_lit_pos", ":", "# Abort compilation if any argument is already a Literal.", "# Letting this continue will cause infinite compilation loop.", "m", "=", "(", "\"Repeated literal typing request.\\n\"", "\"{}.\\n\"", "\"This is likely caused by an error in typing. \"", "\"Please see nested and suppressed exceptions.\"", ")", "info", "=", "', '", ".", "join", "(", "'Arg #{} is {}'", ".", "format", "(", "i", ",", "args", "[", "i", "]", ")", "for", "i", "in", "sorted", "(", "already_lit_pos", ")", ")", "raise", "errors", ".", "CompilerError", "(", "m", ".", "format", "(", "info", ")", ")", "# Convert requested arguments into a Literal.", "args", "=", "[", "(", "types", ".", "literal", "if", "i", "in", "e", ".", "requested_args", "else", "lambda", "x", ":", "x", ")", "(", "args", "[", "i", "]", ")", "for", "i", ",", "v", "in", "enumerate", "(", "args", ")", "]", "# Re-enter compilation with the Literal-ized arguments", "return", "self", ".", "_compile_for_args", "(", "*", "args", ")", "except", "errors", ".", "TypingError", "as", "e", ":", "# Intercept typing error that may be due to an argument", "# that failed inferencing as a Numba type", "failed_args", "=", "[", "]", "for", "i", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "val", "=", "arg", ".", "value", "if", "isinstance", "(", "arg", ",", "OmittedArg", ")", "else", "arg", "try", ":", "tp", "=", "typeof", "(", "val", ",", "Purpose", ".", "argument", ")", "except", "ValueError", "as", "typeof_exc", ":", "failed_args", ".", "append", "(", "(", "i", ",", "str", "(", "typeof_exc", ")", ")", ")", "else", ":", "if", "tp", "is", "None", ":", "failed_args", ".", "append", "(", "(", "i", ",", "\"cannot determine Numba type of value %r\"", "%", "(", "val", ",", ")", ")", ")", "if", "failed_args", ":", "# Patch error message to ease debugging", "msg", "=", "str", "(", "e", ")", ".", "rstrip", "(", ")", "+", "(", "\"\\n\\nThis error may have been caused by the following argument(s):\\n%s\\n\"", "%", "\"\\n\"", ".", "join", "(", "\"- argument %d: %s\"", "%", "(", "i", ",", "err", ")", "for", "i", ",", "err", "in", "failed_args", ")", ")", "e", ".", "patch_message", "(", "msg", ")", "error_rewrite", "(", "e", ",", "'typing'", ")", "except", "errors", ".", "UnsupportedError", "as", "e", ":", "# Something unsupported is present in the user code, add help info", "error_rewrite", "(", "e", ",", "'unsupported_error'", ")", "except", "(", "errors", ".", "NotDefinedError", ",", "errors", ".", "RedefinedError", ",", "errors", ".", "VerificationError", ")", "as", "e", ":", "# These errors are probably from an issue with either the code supplied", "# being syntactically or otherwise invalid", "error_rewrite", "(", "e", ",", "'interpreter'", ")", "except", "errors", ".", "ConstantInferenceError", "as", "e", ":", "# this is from trying to infer something as constant when it isn't", "# or isn't supported as a constant", "error_rewrite", "(", "e", ",", "'constant_inference'", ")", "except", "Exception", "as", "e", ":", "if", "config", ".", "SHOW_HELP", ":", "if", "hasattr", "(", "e", ",", "'patch_message'", ")", ":", "help_msg", "=", "errors", ".", "error_extras", "[", "'reportable'", "]", "e", ".", "patch_message", "(", "'\\n'", ".", "join", "(", "(", "str", "(", "e", ")", ".", "rstrip", "(", ")", ",", "help_msg", ")", ")", ")", "# ignore the FULL_TRACEBACKS config, this needs reporting!", "raise", "e" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/dispatcher.py#L326-L420
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/rocksdb/6.29/tools/block_cache_analyzer/block_cache_pysim.py
python
PQTable.pqinsert
(self, entry)
return removed_entry
Add a new key or update the priority of an existing key
Add a new key or update the priority of an existing key
[ "Add", "a", "new", "key", "or", "update", "the", "priority", "of", "an", "existing", "key" ]
def pqinsert(self, entry): "Add a new key or update the priority of an existing key" # Remove the entry from the table first. removed_entry = self.table.pop(entry.key, None) if removed_entry: # Mark as removed since there is no 'remove' API in heappq. # Instead, an entry in pq is removed lazily when calling pop. removed_entry.is_removed = True self.table[entry.key] = entry heapq.heappush(self.pq, entry) return removed_entry
[ "def", "pqinsert", "(", "self", ",", "entry", ")", ":", "# Remove the entry from the table first.", "removed_entry", "=", "self", ".", "table", ".", "pop", "(", "entry", ".", "key", ",", "None", ")", "if", "removed_entry", ":", "# Mark as removed since there is no 'remove' API in heappq.", "# Instead, an entry in pq is removed lazily when calling pop.", "removed_entry", ".", "is_removed", "=", "True", "self", ".", "table", "[", "entry", ".", "key", "]", "=", "entry", "heapq", ".", "heappush", "(", "self", ".", "pq", ",", "entry", ")", "return", "removed_entry" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/rocksdb/6.29/tools/block_cache_analyzer/block_cache_pysim.py#L1142-L1152
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/affine/unary_operators.py
python
NegExpression.graph_implementation
( self, arg_objs, shape: Tuple[int, ...], data=None )
return (lu.neg_expr(arg_objs[0]), [])
Negate the affine objective. Parameters ---------- arg_objs : list LinExpr for each argument. shape : tuple The shape of the resulting expression. data : Additional data required by the atom. Returns ------- tuple (LinOp for objective, list of constraints)
Negate the affine objective.
[ "Negate", "the", "affine", "objective", "." ]
def graph_implementation( self, arg_objs, shape: Tuple[int, ...], data=None ) -> Tuple[lo.LinOp, List[Constraint]]: """Negate the affine objective. Parameters ---------- arg_objs : list LinExpr for each argument. shape : tuple The shape of the resulting expression. data : Additional data required by the atom. Returns ------- tuple (LinOp for objective, list of constraints) """ return (lu.neg_expr(arg_objs[0]), [])
[ "def", "graph_implementation", "(", "self", ",", "arg_objs", ",", "shape", ":", "Tuple", "[", "int", ",", "...", "]", ",", "data", "=", "None", ")", "->", "Tuple", "[", "lo", ".", "LinOp", ",", "List", "[", "Constraint", "]", "]", ":", "return", "(", "lu", ".", "neg_expr", "(", "arg_objs", "[", "0", "]", ")", ",", "[", "]", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/unary_operators.py#L77-L96
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathUtils.py
python
findToolController
(obj, proxy, name=None)
return tc
returns a tool controller with a given name. If no name is specified, returns the first controller. if no controller is found, returns None
returns a tool controller with a given name. If no name is specified, returns the first controller. if no controller is found, returns None
[ "returns", "a", "tool", "controller", "with", "a", "given", "name", ".", "If", "no", "name", "is", "specified", "returns", "the", "first", "controller", ".", "if", "no", "controller", "is", "found", "returns", "None" ]
def findToolController(obj, proxy, name=None): """returns a tool controller with a given name. If no name is specified, returns the first controller. if no controller is found, returns None""" PathLog.track("name: {}".format(name)) c = None if UserInput: c = UserInput.selectedToolController() if c is not None: return c controllers = getToolControllers(obj, proxy) if len(controllers) == 0: return None # If there's only one in the job, use it. if len(controllers) == 1: if name is None or name == controllers[0].Label: tc = controllers[0] else: tc = None elif name is not None: # More than one, make the user choose. tc = [i for i in controllers if i.Label == name][0] elif UserInput: tc = UserInput.chooseToolController(controllers) return tc
[ "def", "findToolController", "(", "obj", ",", "proxy", ",", "name", "=", "None", ")", ":", "PathLog", ".", "track", "(", "\"name: {}\"", ".", "format", "(", "name", ")", ")", "c", "=", "None", "if", "UserInput", ":", "c", "=", "UserInput", ".", "selectedToolController", "(", ")", "if", "c", "is", "not", "None", ":", "return", "c", "controllers", "=", "getToolControllers", "(", "obj", ",", "proxy", ")", "if", "len", "(", "controllers", ")", "==", "0", ":", "return", "None", "# If there's only one in the job, use it.", "if", "len", "(", "controllers", ")", "==", "1", ":", "if", "name", "is", "None", "or", "name", "==", "controllers", "[", "0", "]", ".", "Label", ":", "tc", "=", "controllers", "[", "0", "]", "else", ":", "tc", "=", "None", "elif", "name", "is", "not", "None", ":", "# More than one, make the user choose.", "tc", "=", "[", "i", "for", "i", "in", "controllers", "if", "i", ".", "Label", "==", "name", "]", "[", "0", "]", "elif", "UserInput", ":", "tc", "=", "UserInput", ".", "chooseToolController", "(", "controllers", ")", "return", "tc" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathUtils.py#L363-L390
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/lib/nanfunctions.py
python
_nanquantile_1d
(arr1d, q, overwrite_input=False, interpolation='linear')
return function_base._quantile_unchecked( arr1d, q, overwrite_input=overwrite_input, interpolation=interpolation)
Private function for rank 1 arrays. Compute quantile ignoring NaNs. See nanpercentile for parameter usage
Private function for rank 1 arrays. Compute quantile ignoring NaNs. See nanpercentile for parameter usage
[ "Private", "function", "for", "rank", "1", "arrays", ".", "Compute", "quantile", "ignoring", "NaNs", ".", "See", "nanpercentile", "for", "parameter", "usage" ]
def _nanquantile_1d(arr1d, q, overwrite_input=False, interpolation='linear'): """ Private function for rank 1 arrays. Compute quantile ignoring NaNs. See nanpercentile for parameter usage """ arr1d, overwrite_input = _remove_nan_1d(arr1d, overwrite_input=overwrite_input) if arr1d.size == 0: return np.full(q.shape, np.nan)[()] # convert to scalar return function_base._quantile_unchecked( arr1d, q, overwrite_input=overwrite_input, interpolation=interpolation)
[ "def", "_nanquantile_1d", "(", "arr1d", ",", "q", ",", "overwrite_input", "=", "False", ",", "interpolation", "=", "'linear'", ")", ":", "arr1d", ",", "overwrite_input", "=", "_remove_nan_1d", "(", "arr1d", ",", "overwrite_input", "=", "overwrite_input", ")", "if", "arr1d", ".", "size", "==", "0", ":", "return", "np", ".", "full", "(", "q", ".", "shape", ",", "np", ".", "nan", ")", "[", "(", ")", "]", "# convert to scalar", "return", "function_base", ".", "_quantile_unchecked", "(", "arr1d", ",", "q", ",", "overwrite_input", "=", "overwrite_input", ",", "interpolation", "=", "interpolation", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/nanfunctions.py#L1366-L1377
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/utils/cache.py
python
CacheManager.cache
(self, funct, *args, **kwargs)
return cached
Create a unique cache
Create a unique cache
[ "Create", "a", "unique", "cache" ]
def cache(self, funct, *args, **kwargs): """ Create a unique cache """ hashVal = self.hash(funct, *args, **kwargs) cached = Cache(hashVal) cached.info['codeinfo'] = self.functInfo(funct) cached.info['version'] = pg.versionStr() cached.info['args'] = str(args) cached.info['kwargs'] = str(kwargs) return cached
[ "def", "cache", "(", "self", ",", "funct", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "hashVal", "=", "self", ".", "hash", "(", "funct", ",", "*", "args", ",", "*", "*", "kwargs", ")", "cached", "=", "Cache", "(", "hashVal", ")", "cached", ".", "info", "[", "'codeinfo'", "]", "=", "self", ".", "functInfo", "(", "funct", ")", "cached", ".", "info", "[", "'version'", "]", "=", "pg", ".", "versionStr", "(", ")", "cached", ".", "info", "[", "'args'", "]", "=", "str", "(", "args", ")", "cached", ".", "info", "[", "'kwargs'", "]", "=", "str", "(", "kwargs", ")", "return", "cached" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/utils/cache.py#L215-L225
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/nn_grad.py
python
_BiasAddGradV1
(unused_bias_op, received_grad)
return (received_grad, math_ops.reduce_sum(received_grad, reduction_dim_tensor))
Return the gradients for the 2 inputs of bias_op. The first input of unused_bias_op is the tensor t, and its gradient is just the gradient the unused_bias_op received. The second input of unused_bias_op is the bias vector which has one fewer dimension than "received_grad" (the batch dimension.) Its gradient is the received gradient Summed on the batch dimension, which is the first dimension. Args: unused_bias_op: The BiasOp for which we need to generate gradients. received_grad: Tensor. The gradients passed to the BiasOp. Returns: Two tensors, the first one for the "tensor" input of the BiasOp, the second one for the "bias" input of the BiasOp.
Return the gradients for the 2 inputs of bias_op.
[ "Return", "the", "gradients", "for", "the", "2", "inputs", "of", "bias_op", "." ]
def _BiasAddGradV1(unused_bias_op, received_grad): """Return the gradients for the 2 inputs of bias_op. The first input of unused_bias_op is the tensor t, and its gradient is just the gradient the unused_bias_op received. The second input of unused_bias_op is the bias vector which has one fewer dimension than "received_grad" (the batch dimension.) Its gradient is the received gradient Summed on the batch dimension, which is the first dimension. Args: unused_bias_op: The BiasOp for which we need to generate gradients. received_grad: Tensor. The gradients passed to the BiasOp. Returns: Two tensors, the first one for the "tensor" input of the BiasOp, the second one for the "bias" input of the BiasOp. """ reduction_dim_tensor = math_ops.range(array_ops.rank(received_grad) - 1) return (received_grad, math_ops.reduce_sum(received_grad, reduction_dim_tensor))
[ "def", "_BiasAddGradV1", "(", "unused_bias_op", ",", "received_grad", ")", ":", "reduction_dim_tensor", "=", "math_ops", ".", "range", "(", "array_ops", ".", "rank", "(", "received_grad", ")", "-", "1", ")", "return", "(", "received_grad", ",", "math_ops", ".", "reduce_sum", "(", "received_grad", ",", "reduction_dim_tensor", ")", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/nn_grad.py#L208-L228
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/ndarray/ndarray.py
python
greater
(lhs, rhs)
return _ufunc_helper( lhs, rhs, op.broadcast_greater, lambda x, y: 1 if x > y else 0, _internal._greater_scalar, _internal._lesser_scalar)
Returns the result of element-wise **greater than** (>) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are greater than rhs, otherwise return 0(false). Equivalent to ``lhs > rhs`` and ``mx.nd.broadcast_greater(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Parameters ---------- lhs : scalar or mxnet.ndarray.array First array to be compared. rhs : scalar or mxnet.ndarray.array Second array to be compared. If ``lhs.shape != rhs.shape``, they must be broadcastable to a common shape. Returns ------- NDArray Output array of boolean values. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.arange(2).reshape((2,1)) >>> z = mx.nd.arange(2).reshape((1,2)) >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.asnumpy() array([[ 0.], [ 1.]], dtype=float32) >>> z.asnumpy() array([[ 0., 1.]], dtype=float32) >>> (x > 1).asnumpy() array([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) >>> (x > y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) >>> mx.nd.greater(x, y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) >>> (z > y).asnumpy() array([[ 0., 1.], [ 0., 0.]], dtype=float32)
Returns the result of element-wise **greater than** (>) comparison operation with broadcasting.
[ "Returns", "the", "result", "of", "element", "-", "wise", "**", "greater", "than", "**", "(", ">", ")", "comparison", "operation", "with", "broadcasting", "." ]
def greater(lhs, rhs): """Returns the result of element-wise **greater than** (>) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are greater than rhs, otherwise return 0(false). Equivalent to ``lhs > rhs`` and ``mx.nd.broadcast_greater(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Parameters ---------- lhs : scalar or mxnet.ndarray.array First array to be compared. rhs : scalar or mxnet.ndarray.array Second array to be compared. If ``lhs.shape != rhs.shape``, they must be broadcastable to a common shape. Returns ------- NDArray Output array of boolean values. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.arange(2).reshape((2,1)) >>> z = mx.nd.arange(2).reshape((1,2)) >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.asnumpy() array([[ 0.], [ 1.]], dtype=float32) >>> z.asnumpy() array([[ 0., 1.]], dtype=float32) >>> (x > 1).asnumpy() array([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) >>> (x > y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) >>> mx.nd.greater(x, y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) >>> (z > y).asnumpy() array([[ 0., 1.], [ 0., 0.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_greater, lambda x, y: 1 if x > y else 0, _internal._greater_scalar, _internal._lesser_scalar)
[ "def", "greater", "(", "lhs", ",", "rhs", ")", ":", "# pylint: disable= no-member, protected-access", "return", "_ufunc_helper", "(", "lhs", ",", "rhs", ",", "op", ".", "broadcast_greater", ",", "lambda", "x", ",", "y", ":", "1", "if", "x", ">", "y", "else", "0", ",", "_internal", ".", "_greater_scalar", ",", "_internal", ".", "_lesser_scalar", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L3340-L3400
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/sliceshell.py
python
SlicesShell.OnCallTipAutoCompleteManually
(self, shiftDown)
AutoComplete and Calltips manually.
AutoComplete and Calltips manually.
[ "AutoComplete", "and", "Calltips", "manually", "." ]
def OnCallTipAutoCompleteManually (self, shiftDown): """AutoComplete and Calltips manually.""" if self.AutoCompActive(): self.AutoCompCancel() currpos = self.GetCurrentPos() stoppos = self.PositionFromLine(self.GetIOSlice()[0]) cpos = currpos #go back until '.' is found pointavailpos = -1 while cpos >= stoppos: if self.GetCharAt(cpos) == ord ('.'): pointavailpos = cpos break cpos -= 1 #word from non whitespace until '.' if pointavailpos != -1: #look backward for first whitespace char textbehind = self.GetTextRange (pointavailpos + 1, currpos) pointavailpos += 1 if not shiftDown: #call AutoComplete stoppos = self.PositionFromLine(self.GetIOSlice()[0]) textbefore = self.GetTextRange(stoppos, pointavailpos) self.autoCompleteShow(textbefore, len (textbehind)) else: #call CallTips cpos = pointavailpos begpos = -1 while cpos > stoppos: if chr(self.GetCharAt(cpos)).isspace(): begpos = cpos break cpos -= 1 if begpos == -1: begpos = cpos ctips = self.GetTextRange (begpos, currpos) ctindex = ctips.find ('(') if ctindex != -1 and not self.CallTipActive(): #insert calltip, if current pos is '(', otherwise show it only self.autoCallTipShow( ctips[:ctindex + 1], self.GetCharAt(currpos - 1) == ord('(') and self.GetCurrentPos() == self.GetTextLength(), True )
[ "def", "OnCallTipAutoCompleteManually", "(", "self", ",", "shiftDown", ")", ":", "if", "self", ".", "AutoCompActive", "(", ")", ":", "self", ".", "AutoCompCancel", "(", ")", "currpos", "=", "self", ".", "GetCurrentPos", "(", ")", "stoppos", "=", "self", ".", "PositionFromLine", "(", "self", ".", "GetIOSlice", "(", ")", "[", "0", "]", ")", "cpos", "=", "currpos", "#go back until '.' is found", "pointavailpos", "=", "-", "1", "while", "cpos", ">=", "stoppos", ":", "if", "self", ".", "GetCharAt", "(", "cpos", ")", "==", "ord", "(", "'.'", ")", ":", "pointavailpos", "=", "cpos", "break", "cpos", "-=", "1", "#word from non whitespace until '.'", "if", "pointavailpos", "!=", "-", "1", ":", "#look backward for first whitespace char", "textbehind", "=", "self", ".", "GetTextRange", "(", "pointavailpos", "+", "1", ",", "currpos", ")", "pointavailpos", "+=", "1", "if", "not", "shiftDown", ":", "#call AutoComplete", "stoppos", "=", "self", ".", "PositionFromLine", "(", "self", ".", "GetIOSlice", "(", ")", "[", "0", "]", ")", "textbefore", "=", "self", ".", "GetTextRange", "(", "stoppos", ",", "pointavailpos", ")", "self", ".", "autoCompleteShow", "(", "textbefore", ",", "len", "(", "textbehind", ")", ")", "else", ":", "#call CallTips", "cpos", "=", "pointavailpos", "begpos", "=", "-", "1", "while", "cpos", ">", "stoppos", ":", "if", "chr", "(", "self", ".", "GetCharAt", "(", "cpos", ")", ")", ".", "isspace", "(", ")", ":", "begpos", "=", "cpos", "break", "cpos", "-=", "1", "if", "begpos", "==", "-", "1", ":", "begpos", "=", "cpos", "ctips", "=", "self", ".", "GetTextRange", "(", "begpos", ",", "currpos", ")", "ctindex", "=", "ctips", ".", "find", "(", "'('", ")", "if", "ctindex", "!=", "-", "1", "and", "not", "self", ".", "CallTipActive", "(", ")", ":", "#insert calltip, if current pos is '(', otherwise show it only", "self", ".", "autoCallTipShow", "(", "ctips", "[", ":", "ctindex", "+", "1", "]", ",", "self", ".", "GetCharAt", "(", "currpos", "-", "1", ")", "==", "ord", "(", "'('", ")", "and", "self", ".", "GetCurrentPos", "(", ")", "==", "self", ".", "GetTextLength", "(", ")", ",", "True", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/sliceshell.py#L3095-L3140
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PGProperty.GetColumnEditor
(*args, **kwargs)
return _propgrid.PGProperty_GetColumnEditor(*args, **kwargs)
GetColumnEditor(self, int column) -> PGEditor
GetColumnEditor(self, int column) -> PGEditor
[ "GetColumnEditor", "(", "self", "int", "column", ")", "-", ">", "PGEditor" ]
def GetColumnEditor(*args, **kwargs): """GetColumnEditor(self, int column) -> PGEditor""" return _propgrid.PGProperty_GetColumnEditor(*args, **kwargs)
[ "def", "GetColumnEditor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_GetColumnEditor", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L564-L566
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/ChannelHeader.py
python
ChannelHeader.__call__
(self, args)
Main execution point. Calls the accept method on each visitor to generate the code.
Main execution point. Calls the accept method on each visitor to generate the code.
[ "Main", "execution", "point", ".", "Calls", "the", "accept", "method", "on", "each", "visitor", "to", "generate", "the", "code", "." ]
def __call__(self, args): """ Main execution point. Calls the accept method on each visitor to generate the code. """ # Note that name handling for params goes # here so that the visitor in accept can # process all. self.__obj = args for v in self.__visitor_list: self.accept(v)
[ "def", "__call__", "(", "self", ",", "args", ")", ":", "# Note that name handling for params goes", "# here so that the visitor in accept can", "# process all.", "self", ".", "__obj", "=", "args", "for", "v", "in", "self", ".", "__visitor_list", ":", "self", ".", "accept", "(", "v", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/ChannelHeader.py#L57-L67
kismetwireless/kismet
a7c0dc270c960fb1f58bd9cec4601c201885fd4e
capture_sdr_rtl433/KismetCaptureRtl433/kismetexternal/__init__.py
python
Datasource.send_datasource_data_report
(self, message=None, warning=None, full_gps=None, full_signal=None, full_packet=None, full_spectrum=None, full_json=None, full_buffer=None, **kwargs)
When operating as a Kismet datasource, send a data frame :param message: Optional message :param warning: Optional warning to be included in the datasource details :param full_gps: Optional full datasource_pb2.SubGps record :param full_signal: Optional full datasource_pb2.SubSignal record :param full_spectrum: Optional full datasource_pb2 SubSpectrum record :param full_packet: Optional full datasource_pb2.SubPacket record :param full_json: Optional JSON record :param full_buffer: Optional protobuf packed buffer :return: None
When operating as a Kismet datasource, send a data frame
[ "When", "operating", "as", "a", "Kismet", "datasource", "send", "a", "data", "frame" ]
def send_datasource_data_report(self, message=None, warning=None, full_gps=None, full_signal=None, full_packet=None, full_spectrum=None, full_json=None, full_buffer=None, **kwargs): """ When operating as a Kismet datasource, send a data frame :param message: Optional message :param warning: Optional warning to be included in the datasource details :param full_gps: Optional full datasource_pb2.SubGps record :param full_signal: Optional full datasource_pb2.SubSignal record :param full_spectrum: Optional full datasource_pb2 SubSpectrum record :param full_packet: Optional full datasource_pb2.SubPacket record :param full_json: Optional JSON record :param full_buffer: Optional protobuf packed buffer :return: None """ report = datasource_pb2.DataReport() if message is not None: report.message.msgtext = message report.message.msgtype = self.MSG_INFO if full_gps: report.gps.CopyFrom(full_gps) if full_signal: report.signal.CopyFrom(full_signal) if full_spectrum: report.signal.CopyFrom(full_spectrum) if full_packet: report.packet.CopyFrom(full_packet) if full_json: report.json.CopyFrom(full_json) if full_buffer: report.buffer.CopyFrom(full_buffer) if warning: report.warning = warning self.write_ext_packet("KDSDATAREPORT", report)
[ "def", "send_datasource_data_report", "(", "self", ",", "message", "=", "None", ",", "warning", "=", "None", ",", "full_gps", "=", "None", ",", "full_signal", "=", "None", ",", "full_packet", "=", "None", ",", "full_spectrum", "=", "None", ",", "full_json", "=", "None", ",", "full_buffer", "=", "None", ",", "*", "*", "kwargs", ")", ":", "report", "=", "datasource_pb2", ".", "DataReport", "(", ")", "if", "message", "is", "not", "None", ":", "report", ".", "message", ".", "msgtext", "=", "message", "report", ".", "message", ".", "msgtype", "=", "self", ".", "MSG_INFO", "if", "full_gps", ":", "report", ".", "gps", ".", "CopyFrom", "(", "full_gps", ")", "if", "full_signal", ":", "report", ".", "signal", ".", "CopyFrom", "(", "full_signal", ")", "if", "full_spectrum", ":", "report", ".", "signal", ".", "CopyFrom", "(", "full_spectrum", ")", "if", "full_packet", ":", "report", ".", "packet", ".", "CopyFrom", "(", "full_packet", ")", "if", "full_json", ":", "report", ".", "json", ".", "CopyFrom", "(", "full_json", ")", "if", "full_buffer", ":", "report", ".", "buffer", ".", "CopyFrom", "(", "full_buffer", ")", "if", "warning", ":", "report", ".", "warning", "=", "warning", "self", ".", "write_ext_packet", "(", "\"KDSDATAREPORT\"", ",", "report", ")" ]
https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtl433/KismetCaptureRtl433/kismetexternal/__init__.py#L1233-L1277
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/utils/path.py
python
DPH5Path._load_h5py
(cls, path: str)
return h5py.File(path, 'r')
Load hdf5 file. Parameters ---------- path : str path to hdf5 file
Load hdf5 file. Parameters ---------- path : str path to hdf5 file
[ "Load", "hdf5", "file", ".", "Parameters", "----------", "path", ":", "str", "path", "to", "hdf5", "file" ]
def _load_h5py(cls, path: str) -> h5py.File: """Load hdf5 file. Parameters ---------- path : str path to hdf5 file """ # this method has cache to avoid duplicated # loading from different DPH5Path # However the file will be never closed? return h5py.File(path, 'r')
[ "def", "_load_h5py", "(", "cls", ",", "path", ":", "str", ")", "->", "h5py", ".", "File", ":", "# this method has cache to avoid duplicated", "# loading from different DPH5Path", "# However the file will be never closed?", "return", "h5py", ".", "File", "(", "path", ",", "'r'", ")" ]
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/utils/path.py#L226-L237
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/py_compile.py
python
wr_long
(f, x)
Internal; write a 32-bit int to a file in little-endian order.
Internal; write a 32-bit int to a file in little-endian order.
[ "Internal", ";", "write", "a", "32", "-", "bit", "int", "to", "a", "file", "in", "little", "-", "endian", "order", "." ]
def wr_long(f, x): """Internal; write a 32-bit int to a file in little-endian order.""" f.write(chr( x & 0xff)) f.write(chr((x >> 8) & 0xff)) f.write(chr((x >> 16) & 0xff)) f.write(chr((x >> 24) & 0xff))
[ "def", "wr_long", "(", "f", ",", "x", ")", ":", "f", ".", "write", "(", "chr", "(", "x", "&", "0xff", ")", ")", "f", ".", "write", "(", "chr", "(", "(", "x", ">>", "8", ")", "&", "0xff", ")", ")", "f", ".", "write", "(", "chr", "(", "(", "x", ">>", "16", ")", "&", "0xff", ")", ")", "f", ".", "write", "(", "chr", "(", "(", "x", ">>", "24", ")", "&", "0xff", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/py_compile.py#L64-L69
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/tools/saved_model_cli.py
python
get_signature_def_map
(saved_model_dir, tag_set)
return meta_graph.signature_def
Gets SignatureDef map from a MetaGraphDef in a SavedModel. Returns the SignatureDef map for the given tag-set in the SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect or execute. tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. Returns: A SignatureDef map that maps from string keys to SignatureDefs.
Gets SignatureDef map from a MetaGraphDef in a SavedModel.
[ "Gets", "SignatureDef", "map", "from", "a", "MetaGraphDef", "in", "a", "SavedModel", "." ]
def get_signature_def_map(saved_model_dir, tag_set): """Gets SignatureDef map from a MetaGraphDef in a SavedModel. Returns the SignatureDef map for the given tag-set in the SavedModel directory. Args: saved_model_dir: Directory containing the SavedModel to inspect or execute. tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in string format, separated by ','. For tag-set contains multiple tags, all tags must be passed in. Returns: A SignatureDef map that maps from string keys to SignatureDefs. """ meta_graph = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) return meta_graph.signature_def
[ "def", "get_signature_def_map", "(", "saved_model_dir", ",", "tag_set", ")", ":", "meta_graph", "=", "saved_model_utils", ".", "get_meta_graph_def", "(", "saved_model_dir", ",", "tag_set", ")", "return", "meta_graph", ".", "signature_def" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/tools/saved_model_cli.py#L210-L226
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
bin/collect_minidumps.py
python
FileArchiver.make_tarball
(self)
Make a tarball with the maximum number of files such that the size of the tarball is less than or equal to max_output_size. Returns a pair (status (int), message (str)). status represents the result of the operation and follows the unix convention where 0 equals success. message provides additional information. A status of 1 is returned if source_dir is not empty and no files were able to fit into the tarball.
Make a tarball with the maximum number of files such that the size of the tarball is less than or equal to max_output_size. Returns a pair (status (int), message (str)). status represents the result of the operation and follows the unix convention where 0 equals success. message provides additional information. A status of 1 is returned if source_dir is not empty and no files were able to fit into the tarball.
[ "Make", "a", "tarball", "with", "the", "maximum", "number", "of", "files", "such", "that", "the", "size", "of", "the", "tarball", "is", "less", "than", "or", "equal", "to", "max_output_size", ".", "Returns", "a", "pair", "(", "status", "(", "int", ")", "message", "(", "str", "))", ".", "status", "represents", "the", "result", "of", "the", "operation", "and", "follows", "the", "unix", "convention", "where", "0", "equals", "success", ".", "message", "provides", "additional", "information", ".", "A", "status", "of", "1", "is", "returned", "if", "source_dir", "is", "not", "empty", "and", "no", "files", "were", "able", "to", "fit", "into", "the", "tarball", "." ]
def make_tarball(self): '''Make a tarball with the maximum number of files such that the size of the tarball is less than or equal to max_output_size. Returns a pair (status (int), message (str)). status represents the result of the operation and follows the unix convention where 0 equals success. message provides additional information. A status of 1 is returned if source_dir is not empty and no files were able to fit into the tarball. ''' self._compute_file_list() if len(self.file_list) == 0: status = 0 msg = 'No files found in "{0}".' return status, msg.format(self.source_dir) output_size = self._tar_files() if output_size <= self.max_output_size: status = 0 msg = 'Success, archived all {0} files in "{1}".' return status, msg.format(len(self.file_list), self.source_dir) else: max_num_files = self._binary_search() if max_num_files == 0: self._remove_output_file() status = 1 msg = ('Unable to archive any files in "{0}". ' 'Increase max_output_size to at least {1} bytes.') # If max_num_files is 0, we are guaranteed that the binary search tried making a # tarball with 1 file. return status, msg.format(self.source_dir, self.resulting_sizes[1]) else: self._tar_files(max_num_files) status = 0 msg = 'Success. Archived {0} out of {1} files in "{2}".' return status, msg.format(max_num_files, len(self.file_list), self.source_dir)
[ "def", "make_tarball", "(", "self", ")", ":", "self", ".", "_compute_file_list", "(", ")", "if", "len", "(", "self", ".", "file_list", ")", "==", "0", ":", "status", "=", "0", "msg", "=", "'No files found in \"{0}\".'", "return", "status", ",", "msg", ".", "format", "(", "self", ".", "source_dir", ")", "output_size", "=", "self", ".", "_tar_files", "(", ")", "if", "output_size", "<=", "self", ".", "max_output_size", ":", "status", "=", "0", "msg", "=", "'Success, archived all {0} files in \"{1}\".'", "return", "status", ",", "msg", ".", "format", "(", "len", "(", "self", ".", "file_list", ")", ",", "self", ".", "source_dir", ")", "else", ":", "max_num_files", "=", "self", ".", "_binary_search", "(", ")", "if", "max_num_files", "==", "0", ":", "self", ".", "_remove_output_file", "(", ")", "status", "=", "1", "msg", "=", "(", "'Unable to archive any files in \"{0}\". '", "'Increase max_output_size to at least {1} bytes.'", ")", "# If max_num_files is 0, we are guaranteed that the binary search tried making a", "# tarball with 1 file.", "return", "status", ",", "msg", ".", "format", "(", "self", ".", "source_dir", ",", "self", ".", "resulting_sizes", "[", "1", "]", ")", "else", ":", "self", ".", "_tar_files", "(", "max_num_files", ")", "status", "=", "0", "msg", "=", "'Success. Archived {0} out of {1} files in \"{2}\".'", "return", "status", ",", "msg", ".", "format", "(", "max_num_files", ",", "len", "(", "self", ".", "file_list", ")", ",", "self", ".", "source_dir", ")" ]
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/collect_minidumps.py#L115-L146
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/config/configobj.py
python
ConfigObj._parse
(self, infile)
Actually parse the config file.
Actually parse the config file.
[ "Actually", "parse", "the", "config", "file", "." ]
def _parse(self, infile): """Actually parse the config file.""" temp_list_values = self.list_values if self.unrepr: self.list_values = False comment_list = [] done_start = False this_section = self maxline = len(infile) - 1 cur_index = -1 reset_comment = False while cur_index < maxline: if reset_comment: comment_list = [] cur_index += 1 line = infile[cur_index] sline = line.strip() # do we have anything on the line ? if not sline or sline.startswith('#') or sline.startswith(';'): reset_comment = False comment_list.append(line) continue if not done_start: # preserve initial comment self.initial_comment = comment_list comment_list = [] done_start = True reset_comment = True # first we check if it's a section marker mat = self._sectionmarker.match(line) if mat is not None: # is a section line (indent, sect_open, sect_name, sect_close, comment) = ( mat.groups()) if indent and (self.indent_type is None): self.indent_type = indent cur_depth = sect_open.count('[') if cur_depth != sect_close.count(']'): self._handle_error( "Cannot compute the section depth at line %s.", NestingError, infile, cur_index) continue # if cur_depth < this_section.depth: # the new section is dropping back to a previous level try: parent = self._match_depth( this_section, cur_depth).parent except SyntaxError: self._handle_error( "Cannot compute nesting level at line %s.", NestingError, infile, cur_index) continue elif cur_depth == this_section.depth: # the new section is a sibling of the current section parent = this_section.parent elif cur_depth == this_section.depth + 1: # the new section is a child the current section parent = this_section else: self._handle_error( "Section too nested at line %s.", NestingError, infile, cur_index) # sect_name = self._unquote(sect_name) if parent.has_key(sect_name): self._handle_error( 'Duplicate section name at line %s.', DuplicateError, infile, cur_index) continue # create the new section this_section = Section( parent, cur_depth, self, name=sect_name) parent[sect_name] = this_section parent.inline_comments[sect_name] = comment parent.comments[sect_name] = comment_list continue # # it's not a section marker, # so it should be a valid ``key = value`` line mat = self._keyword.match(line) if mat is None: # it neither matched as a keyword # or a section marker self._handle_error( 'Invalid line at line "%s".', ParseError, infile, cur_index) else: # is a keyword value # value will include any inline comment (indent, key, value) = mat.groups() if indent and (self.indent_type is None): self.indent_type = indent # check for a multiline value if value[:3] in ['"""', "'''"]: try: (value, comment, cur_index) = self._multiline( value, infile, cur_index, maxline) except SyntaxError: self._handle_error( 'Parse error in value at line %s.', ParseError, infile, cur_index) continue else: if self.unrepr: comment = '' try: value = unrepr(value) except Exception, e: if type(e) == UnknownType: msg = 'Unknown name or type in value at line %s.' else: msg = 'Parse error in value at line %s.' self._handle_error(msg, UnreprError, infile, cur_index) continue else: if self.unrepr: comment = '' try: value = unrepr(value) except Exception, e: if isinstance(e, UnknownType): msg = 'Unknown name or type in value at line %s.' else: msg = 'Parse error in value at line %s.' self._handle_error(msg, UnreprError, infile, cur_index) continue else: # extract comment and lists try: (value, comment) = self._handle_value(value) except SyntaxError: self._handle_error( 'Parse error in value at line %s.', ParseError, infile, cur_index) continue # key = self._unquote(key) if this_section.has_key(key): self._handle_error( 'Duplicate keyword name at line %s.', DuplicateError, infile, cur_index) continue # add the key. # we set unrepr because if we have got this far we will never # be creating a new section this_section.__setitem__(key, value, unrepr=True) this_section.inline_comments[key] = comment this_section.comments[key] = comment_list continue # if self.indent_type is None: # no indentation used, set the type accordingly self.indent_type = '' # if self._terminated: comment_list.append('') # preserve the final comment if not self and not self.initial_comment: self.initial_comment = comment_list elif not reset_comment: self.final_comment = comment_list self.list_values = temp_list_values
[ "def", "_parse", "(", "self", ",", "infile", ")", ":", "temp_list_values", "=", "self", ".", "list_values", "if", "self", ".", "unrepr", ":", "self", ".", "list_values", "=", "False", "comment_list", "=", "[", "]", "done_start", "=", "False", "this_section", "=", "self", "maxline", "=", "len", "(", "infile", ")", "-", "1", "cur_index", "=", "-", "1", "reset_comment", "=", "False", "while", "cur_index", "<", "maxline", ":", "if", "reset_comment", ":", "comment_list", "=", "[", "]", "cur_index", "+=", "1", "line", "=", "infile", "[", "cur_index", "]", "sline", "=", "line", ".", "strip", "(", ")", "# do we have anything on the line ?", "if", "not", "sline", "or", "sline", ".", "startswith", "(", "'#'", ")", "or", "sline", ".", "startswith", "(", "';'", ")", ":", "reset_comment", "=", "False", "comment_list", ".", "append", "(", "line", ")", "continue", "if", "not", "done_start", ":", "# preserve initial comment", "self", ".", "initial_comment", "=", "comment_list", "comment_list", "=", "[", "]", "done_start", "=", "True", "reset_comment", "=", "True", "# first we check if it's a section marker", "mat", "=", "self", ".", "_sectionmarker", ".", "match", "(", "line", ")", "if", "mat", "is", "not", "None", ":", "# is a section line", "(", "indent", ",", "sect_open", ",", "sect_name", ",", "sect_close", ",", "comment", ")", "=", "(", "mat", ".", "groups", "(", ")", ")", "if", "indent", "and", "(", "self", ".", "indent_type", "is", "None", ")", ":", "self", ".", "indent_type", "=", "indent", "cur_depth", "=", "sect_open", ".", "count", "(", "'['", ")", "if", "cur_depth", "!=", "sect_close", ".", "count", "(", "']'", ")", ":", "self", ".", "_handle_error", "(", "\"Cannot compute the section depth at line %s.\"", ",", "NestingError", ",", "infile", ",", "cur_index", ")", "continue", "#", "if", "cur_depth", "<", "this_section", ".", "depth", ":", "# the new section is dropping back to a previous level", "try", ":", "parent", "=", "self", ".", "_match_depth", "(", "this_section", ",", "cur_depth", ")", ".", "parent", "except", "SyntaxError", ":", "self", ".", "_handle_error", "(", "\"Cannot compute nesting level at line %s.\"", ",", "NestingError", ",", "infile", ",", "cur_index", ")", "continue", "elif", "cur_depth", "==", "this_section", ".", "depth", ":", "# the new section is a sibling of the current section", "parent", "=", "this_section", ".", "parent", "elif", "cur_depth", "==", "this_section", ".", "depth", "+", "1", ":", "# the new section is a child the current section", "parent", "=", "this_section", "else", ":", "self", ".", "_handle_error", "(", "\"Section too nested at line %s.\"", ",", "NestingError", ",", "infile", ",", "cur_index", ")", "#", "sect_name", "=", "self", ".", "_unquote", "(", "sect_name", ")", "if", "parent", ".", "has_key", "(", "sect_name", ")", ":", "self", ".", "_handle_error", "(", "'Duplicate section name at line %s.'", ",", "DuplicateError", ",", "infile", ",", "cur_index", ")", "continue", "# create the new section", "this_section", "=", "Section", "(", "parent", ",", "cur_depth", ",", "self", ",", "name", "=", "sect_name", ")", "parent", "[", "sect_name", "]", "=", "this_section", "parent", ".", "inline_comments", "[", "sect_name", "]", "=", "comment", "parent", ".", "comments", "[", "sect_name", "]", "=", "comment_list", "continue", "#", "# it's not a section marker,", "# so it should be a valid ``key = value`` line", "mat", "=", "self", ".", "_keyword", ".", "match", "(", "line", ")", "if", "mat", "is", "None", ":", "# it neither matched as a keyword", "# or a section marker", "self", ".", "_handle_error", "(", "'Invalid line at line \"%s\".'", ",", "ParseError", ",", "infile", ",", "cur_index", ")", "else", ":", "# is a keyword value", "# value will include any inline comment", "(", "indent", ",", "key", ",", "value", ")", "=", "mat", ".", "groups", "(", ")", "if", "indent", "and", "(", "self", ".", "indent_type", "is", "None", ")", ":", "self", ".", "indent_type", "=", "indent", "# check for a multiline value", "if", "value", "[", ":", "3", "]", "in", "[", "'\"\"\"'", ",", "\"'''\"", "]", ":", "try", ":", "(", "value", ",", "comment", ",", "cur_index", ")", "=", "self", ".", "_multiline", "(", "value", ",", "infile", ",", "cur_index", ",", "maxline", ")", "except", "SyntaxError", ":", "self", ".", "_handle_error", "(", "'Parse error in value at line %s.'", ",", "ParseError", ",", "infile", ",", "cur_index", ")", "continue", "else", ":", "if", "self", ".", "unrepr", ":", "comment", "=", "''", "try", ":", "value", "=", "unrepr", "(", "value", ")", "except", "Exception", ",", "e", ":", "if", "type", "(", "e", ")", "==", "UnknownType", ":", "msg", "=", "'Unknown name or type in value at line %s.'", "else", ":", "msg", "=", "'Parse error in value at line %s.'", "self", ".", "_handle_error", "(", "msg", ",", "UnreprError", ",", "infile", ",", "cur_index", ")", "continue", "else", ":", "if", "self", ".", "unrepr", ":", "comment", "=", "''", "try", ":", "value", "=", "unrepr", "(", "value", ")", "except", "Exception", ",", "e", ":", "if", "isinstance", "(", "e", ",", "UnknownType", ")", ":", "msg", "=", "'Unknown name or type in value at line %s.'", "else", ":", "msg", "=", "'Parse error in value at line %s.'", "self", ".", "_handle_error", "(", "msg", ",", "UnreprError", ",", "infile", ",", "cur_index", ")", "continue", "else", ":", "# extract comment and lists", "try", ":", "(", "value", ",", "comment", ")", "=", "self", ".", "_handle_value", "(", "value", ")", "except", "SyntaxError", ":", "self", ".", "_handle_error", "(", "'Parse error in value at line %s.'", ",", "ParseError", ",", "infile", ",", "cur_index", ")", "continue", "#", "key", "=", "self", ".", "_unquote", "(", "key", ")", "if", "this_section", ".", "has_key", "(", "key", ")", ":", "self", ".", "_handle_error", "(", "'Duplicate keyword name at line %s.'", ",", "DuplicateError", ",", "infile", ",", "cur_index", ")", "continue", "# add the key.", "# we set unrepr because if we have got this far we will never", "# be creating a new section", "this_section", ".", "__setitem__", "(", "key", ",", "value", ",", "unrepr", "=", "True", ")", "this_section", ".", "inline_comments", "[", "key", "]", "=", "comment", "this_section", ".", "comments", "[", "key", "]", "=", "comment_list", "continue", "#", "if", "self", ".", "indent_type", "is", "None", ":", "# no indentation used, set the type accordingly", "self", ".", "indent_type", "=", "''", "#", "if", "self", ".", "_terminated", ":", "comment_list", ".", "append", "(", "''", ")", "# preserve the final comment", "if", "not", "self", "and", "not", "self", ".", "initial_comment", ":", "self", ".", "initial_comment", "=", "comment_list", "elif", "not", "reset_comment", ":", "self", ".", "final_comment", "=", "comment_list", "self", ".", "list_values", "=", "temp_list_values" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/config/configobj.py#L1410-L1578
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/modes/notemacs.py
python
NotEmacsMode.copy_forward_word
(self, e)
Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound.
Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound.
[ "Copy", "the", "word", "following", "point", "to", "the", "kill", "buffer", ".", "The", "word", "boundaries", "are", "the", "same", "as", "forward", "-", "word", ".", "By", "default", "this", "command", "is", "unbound", "." ]
def copy_forward_word(self, e): # () '''Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound.''' pass
[ "def", "copy_forward_word", "(", "self", ",", "e", ")", ":", "# ()", "pass" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/notemacs.py#L387-L391
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/TaskGen.py
python
task_gen.clone
(self, env)
return newobj
Makes a copy of a task generator. Once the copy is made, it is necessary to ensure that the it does not create the same output files as the original, or the same files may be compiled several times. :param env: A configuration set :type env: :py:class:`waflib.ConfigSet.ConfigSet` :return: A copy :rtype: :py:class:`waflib.TaskGen.task_gen`
Makes a copy of a task generator. Once the copy is made, it is necessary to ensure that the it does not create the same output files as the original, or the same files may be compiled several times.
[ "Makes", "a", "copy", "of", "a", "task", "generator", ".", "Once", "the", "copy", "is", "made", "it", "is", "necessary", "to", "ensure", "that", "the", "it", "does", "not", "create", "the", "same", "output", "files", "as", "the", "original", "or", "the", "same", "files", "may", "be", "compiled", "several", "times", "." ]
def clone(self, env): """ Makes a copy of a task generator. Once the copy is made, it is necessary to ensure that the it does not create the same output files as the original, or the same files may be compiled several times. :param env: A configuration set :type env: :py:class:`waflib.ConfigSet.ConfigSet` :return: A copy :rtype: :py:class:`waflib.TaskGen.task_gen` """ newobj = self.bld() for x in self.__dict__: if x in ('env', 'bld'): continue elif x in ('path', 'features'): setattr(newobj, x, getattr(self, x)) else: setattr(newobj, x, copy.copy(getattr(self, x))) newobj.posted = False if isinstance(env, str): newobj.env = self.bld.all_envs[env].derive() else: newobj.env = env.derive() return newobj
[ "def", "clone", "(", "self", ",", "env", ")", ":", "newobj", "=", "self", ".", "bld", "(", ")", "for", "x", "in", "self", ".", "__dict__", ":", "if", "x", "in", "(", "'env'", ",", "'bld'", ")", ":", "continue", "elif", "x", "in", "(", "'path'", ",", "'features'", ")", ":", "setattr", "(", "newobj", ",", "x", ",", "getattr", "(", "self", ",", "x", ")", ")", "else", ":", "setattr", "(", "newobj", ",", "x", ",", "copy", ".", "copy", "(", "getattr", "(", "self", ",", "x", ")", ")", ")", "newobj", ".", "posted", "=", "False", "if", "isinstance", "(", "env", ",", "str", ")", ":", "newobj", ".", "env", "=", "self", ".", "bld", ".", "all_envs", "[", "env", "]", ".", "derive", "(", ")", "else", ":", "newobj", ".", "env", "=", "env", ".", "derive", "(", ")", "return", "newobj" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/TaskGen.py#L287-L313
chuckcho/video-caffe
fc232b3e3a90ea22dd041b9fc5c542f170581f20
tools/extra/summarize.py
python
print_table
(table, max_width)
Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.
Print a simple nicely-aligned table.
[ "Print", "a", "simple", "nicely", "-", "aligned", "table", "." ]
def print_table(table, max_width): """Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.""" max_widths = [max_width] * len(table[0]) column_widths = [max(printed_len(row[j]) + 1 for row in table) for j in range(len(table[0]))] column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)] for row in table: row_str = '' right_col = 0 for cell, width in zip(row, column_widths): right_col += width row_str += cell + ' ' row_str += ' ' * max(right_col - printed_len(row_str), 0) print row_str
[ "def", "print_table", "(", "table", ",", "max_width", ")", ":", "max_widths", "=", "[", "max_width", "]", "*", "len", "(", "table", "[", "0", "]", ")", "column_widths", "=", "[", "max", "(", "printed_len", "(", "row", "[", "j", "]", ")", "+", "1", "for", "row", "in", "table", ")", "for", "j", "in", "range", "(", "len", "(", "table", "[", "0", "]", ")", ")", "]", "column_widths", "=", "[", "min", "(", "w", ",", "max_w", ")", "for", "w", ",", "max_w", "in", "zip", "(", "column_widths", ",", "max_widths", ")", "]", "for", "row", "in", "table", ":", "row_str", "=", "''", "right_col", "=", "0", "for", "cell", ",", "width", "in", "zip", "(", "row", ",", "column_widths", ")", ":", "right_col", "+=", "width", "row_str", "+=", "cell", "+", "' '", "row_str", "+=", "' '", "*", "max", "(", "right_col", "-", "printed_len", "(", "row_str", ")", ",", "0", ")", "print", "row_str" ]
https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/tools/extra/summarize.py#L41-L61
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/appController.py
python
AppController._currentPathChanged
(self)
Called when the currentPathWidget text is changed
Called when the currentPathWidget text is changed
[ "Called", "when", "the", "currentPathWidget", "text", "is", "changed" ]
def _currentPathChanged(self): """Called when the currentPathWidget text is changed""" newPaths = self._ui.currentPathWidget.text() pathList = re.split(", ?", newPaths) pathList = [path for path in pathList if len(path) != 0] try: prims = self._getPrimsFromPaths(pathList) except PrimNotFoundException as ex: # _getPrimsFromPaths couldn't find one of the prims sys.stderr.write("ERROR: %s\n" % str(ex)) self._updatePrimPathText() return explicitProps = any(Sdf.Path(str(path)).IsPropertyPath() for path in pathList) if len(prims) == 1 and not explicitProps: self._dataModel.selection.switchToPrimPath(prims[0].GetPath()) else: with self._dataModel.selection.batchPrimChanges: self._dataModel.selection.clearPrims() for prim in prims: self._dataModel.selection.addPrim(prim) with self._dataModel.selection.batchPropChanges: self._dataModel.selection.clearProps() for path, prim in zip(pathList, prims): sdfPath = Sdf.Path(str(path)) if sdfPath.IsPropertyPath(): self._dataModel.selection.addPropPath(path) self._dataModel.selection.clearComputedProps()
[ "def", "_currentPathChanged", "(", "self", ")", ":", "newPaths", "=", "self", ".", "_ui", ".", "currentPathWidget", ".", "text", "(", ")", "pathList", "=", "re", ".", "split", "(", "\", ?\"", ",", "newPaths", ")", "pathList", "=", "[", "path", "for", "path", "in", "pathList", "if", "len", "(", "path", ")", "!=", "0", "]", "try", ":", "prims", "=", "self", ".", "_getPrimsFromPaths", "(", "pathList", ")", "except", "PrimNotFoundException", "as", "ex", ":", "# _getPrimsFromPaths couldn't find one of the prims", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: %s\\n\"", "%", "str", "(", "ex", ")", ")", "self", ".", "_updatePrimPathText", "(", ")", "return", "explicitProps", "=", "any", "(", "Sdf", ".", "Path", "(", "str", "(", "path", ")", ")", ".", "IsPropertyPath", "(", ")", "for", "path", "in", "pathList", ")", "if", "len", "(", "prims", ")", "==", "1", "and", "not", "explicitProps", ":", "self", ".", "_dataModel", ".", "selection", ".", "switchToPrimPath", "(", "prims", "[", "0", "]", ".", "GetPath", "(", ")", ")", "else", ":", "with", "self", ".", "_dataModel", ".", "selection", ".", "batchPrimChanges", ":", "self", ".", "_dataModel", ".", "selection", ".", "clearPrims", "(", ")", "for", "prim", "in", "prims", ":", "self", ".", "_dataModel", ".", "selection", ".", "addPrim", "(", "prim", ")", "with", "self", ".", "_dataModel", ".", "selection", ".", "batchPropChanges", ":", "self", ".", "_dataModel", ".", "selection", ".", "clearProps", "(", ")", "for", "path", ",", "prim", "in", "zip", "(", "pathList", ",", "prims", ")", ":", "sdfPath", "=", "Sdf", ".", "Path", "(", "str", "(", "path", ")", ")", "if", "sdfPath", ".", "IsPropertyPath", "(", ")", ":", "self", ".", "_dataModel", ".", "selection", ".", "addPropPath", "(", "path", ")", "self", ".", "_dataModel", ".", "selection", ".", "clearComputedProps", "(", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L3280-L3312
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/experimental/driver/tdvp.py
python
qgt_norm
(driver: TDVP, x: PyTree)
return jnp.sqrt(jnp.real(xc_dot_y))
Computes the norm induced by the QGT :math:`S`, i.e, :math:`x^\\dagger S x`.
Computes the norm induced by the QGT :math:`S`, i.e, :math:`x^\\dagger S x`.
[ "Computes", "the", "norm", "induced", "by", "the", "QGT", ":", "math", ":", "S", "i", ".", "e", ":", "math", ":", "x^", "\\\\", "dagger", "S", "x", "." ]
def qgt_norm(driver: TDVP, x: PyTree): """ Computes the norm induced by the QGT :math:`S`, i.e, :math:`x^\\dagger S x`. """ y = driver._last_qgt @ x # pylint: disable=protected-access xc_dot_y = nk.jax.tree_dot(nk.jax.tree_conj(x), y) return jnp.sqrt(jnp.real(xc_dot_y))
[ "def", "qgt_norm", "(", "driver", ":", "TDVP", ",", "x", ":", "PyTree", ")", ":", "y", "=", "driver", ".", "_last_qgt", "@", "x", "# pylint: disable=protected-access", "xc_dot_y", "=", "nk", ".", "jax", ".", "tree_dot", "(", "nk", ".", "jax", ".", "tree_conj", "(", "x", ")", ",", "y", ")", "return", "jnp", ".", "sqrt", "(", "jnp", ".", "real", "(", "xc_dot_y", ")", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/experimental/driver/tdvp.py#L447-L453
gklz1982/caffe-yolov2
ebb27029db4ddc0d40e520634633b0fa9cdcc10d
scripts/cpp_lint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ) or } or ] or >, finds the position that opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "endchar", "=", "line", "[", "pos", "]", "if", "endchar", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", "-", "1", ")", "if", "endchar", "==", "')'", ":", "startchar", "=", "'('", "if", "endchar", "==", "']'", ":", "startchar", "=", "'['", "if", "endchar", "==", "'}'", ":", "startchar", "=", "'{'", "if", "endchar", "==", "'>'", ":", "startchar", "=", "'<'", "# Check last line", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Continue scanning backward", "while", "linenum", ">", "0", ":", "linenum", "-=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "len", "(", "line", ")", "-", "1", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Did not find startchar before beginning of file, give up", "return", "(", "line", ",", "0", ",", "-", "1", ")" ]
https://github.com/gklz1982/caffe-yolov2/blob/ebb27029db4ddc0d40e520634633b0fa9cdcc10d/scripts/cpp_lint.py#L1327-L1369
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/ansic/cparse.py
python
p_translation_unit_2
(t)
translation_unit : translation_unit external_declaration
translation_unit : translation_unit external_declaration
[ "translation_unit", ":", "translation_unit", "external_declaration" ]
def p_translation_unit_2(t): 'translation_unit : translation_unit external_declaration' pass
[ "def", "p_translation_unit_2", "(", "t", ")", ":", "pass" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L20-L22
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py
python
Locator._get_project
(self, name)
For a given project, get a dictionary mapping available versions to Distribution instances. This should be implemented in subclasses. If called from a locate() request, self.matcher will be set to a matcher for the requirement to satisfy, otherwise it will be None.
[]
def _get_project(self, name): """ For a given project, get a dictionary mapping available versions to Distribution instances. This should be implemented in subclasses. If called from a locate() request, self.matcher will be set to a matcher for the requirement to satisfy, otherwise it will be None. """ raise NotImplementedError('Please implement in the subclass')
[ "def", "_get_project", "(", "self", ",", "name", ")", ":", "raise", "NotImplementedError", "(", "'Please implement in the subclass'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py#L305-L325
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
GenericTreeItem.GetCheckedImage
(self, which=TreeItemIcon_Checked)
return self._checkedimages[which]
Returns the item check image. :param integer `which`: can be one of the following bits: ================================= ======================== Item State Description ================================= ======================== ``TreeItemIcon_Checked`` To get the checkbox checked item image ``TreeItemIcon_NotChecked`` To get the checkbox unchecked item image ``TreeItemIcon_Undetermined`` To get the checkbox undetermined state item image ``TreeItemIcon_Flagged`` To get the radiobutton checked image ``TreeItemIcon_NotFlagged`` To get the radiobutton unchecked image ================================= ======================== :return: An integer index that can be used to retrieve the item check image inside a :class:`ImageList`. :note: This method is meaningful only for radio & check items.
Returns the item check image.
[ "Returns", "the", "item", "check", "image", "." ]
def GetCheckedImage(self, which=TreeItemIcon_Checked): """ Returns the item check image. :param integer `which`: can be one of the following bits: ================================= ======================== Item State Description ================================= ======================== ``TreeItemIcon_Checked`` To get the checkbox checked item image ``TreeItemIcon_NotChecked`` To get the checkbox unchecked item image ``TreeItemIcon_Undetermined`` To get the checkbox undetermined state item image ``TreeItemIcon_Flagged`` To get the radiobutton checked image ``TreeItemIcon_NotFlagged`` To get the radiobutton unchecked image ================================= ======================== :return: An integer index that can be used to retrieve the item check image inside a :class:`ImageList`. :note: This method is meaningful only for radio & check items. """ return self._checkedimages[which]
[ "def", "GetCheckedImage", "(", "self", ",", "which", "=", "TreeItemIcon_Checked", ")", ":", "return", "self", ".", "_checkedimages", "[", "which", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L1732-L1754
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py
python
Filterer.__init__
(self)
Initialize the list of filters to be an empty list.
Initialize the list of filters to be an empty list.
[ "Initialize", "the", "list", "of", "filters", "to", "be", "an", "empty", "list", "." ]
def __init__(self): """ Initialize the list of filters to be an empty list. """ self.filters = []
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "filters", "=", "[", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py#L578-L582
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBDebugger.SetScriptLanguage
(self, script_lang)
return _lldb.SBDebugger_SetScriptLanguage(self, script_lang)
SetScriptLanguage(SBDebugger self, lldb::ScriptLanguage script_lang)
SetScriptLanguage(SBDebugger self, lldb::ScriptLanguage script_lang)
[ "SetScriptLanguage", "(", "SBDebugger", "self", "lldb", "::", "ScriptLanguage", "script_lang", ")" ]
def SetScriptLanguage(self, script_lang): """SetScriptLanguage(SBDebugger self, lldb::ScriptLanguage script_lang)""" return _lldb.SBDebugger_SetScriptLanguage(self, script_lang)
[ "def", "SetScriptLanguage", "(", "self", ",", "script_lang", ")", ":", "return", "_lldb", ".", "SBDebugger_SetScriptLanguage", "(", "self", ",", "script_lang", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L4219-L4221
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/auto_bisect/bisect_perf_regression.py
python
RemoveDirectoryTree
(path_to_dir)
Removes a directory tree. Returns True if successful or False otherwise.
Removes a directory tree. Returns True if successful or False otherwise.
[ "Removes", "a", "directory", "tree", ".", "Returns", "True", "if", "successful", "or", "False", "otherwise", "." ]
def RemoveDirectoryTree(path_to_dir): """Removes a directory tree. Returns True if successful or False otherwise.""" if os.path.isfile(path_to_dir): logging.info('REMOVING FILE %s' % path_to_dir) os.remove(path_to_dir) try: if os.path.exists(path_to_dir): shutil.rmtree(path_to_dir) except OSError, e: if e.errno != errno.ENOENT: raise
[ "def", "RemoveDirectoryTree", "(", "path_to_dir", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path_to_dir", ")", ":", "logging", ".", "info", "(", "'REMOVING FILE %s'", "%", "path_to_dir", ")", "os", ".", "remove", "(", "path_to_dir", ")", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "path_to_dir", ")", ":", "shutil", ".", "rmtree", "(", "path_to_dir", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/bisect_perf_regression.py#L2552-L2562
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBValue.GetPreferSyntheticValue
(self)
return _lldb.SBValue_GetPreferSyntheticValue(self)
GetPreferSyntheticValue(self) -> bool
GetPreferSyntheticValue(self) -> bool
[ "GetPreferSyntheticValue", "(", "self", ")", "-", ">", "bool" ]
def GetPreferSyntheticValue(self): """GetPreferSyntheticValue(self) -> bool""" return _lldb.SBValue_GetPreferSyntheticValue(self)
[ "def", "GetPreferSyntheticValue", "(", "self", ")", ":", "return", "_lldb", ".", "SBValue_GetPreferSyntheticValue", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11900-L11902
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/shutil.py
python
chown
(path, user=None, group=None)
Change owner user and group of the given path. user and group can be the uid/gid or the user/group names, and in that case, they are converted to their respective uid/gid.
Change owner user and group of the given path.
[ "Change", "owner", "user", "and", "group", "of", "the", "given", "path", "." ]
def chown(path, user=None, group=None): """Change owner user and group of the given path. user and group can be the uid/gid or the user/group names, and in that case, they are converted to their respective uid/gid. """ if user is None and group is None: raise ValueError("user and/or group must be set") _user = user _group = group # -1 means don't change it if user is None: _user = -1 # user can either be an int (the uid) or a string (the system username) elif isinstance(user, str): _user = _get_uid(user) if _user is None: raise LookupError("no such user: {!r}".format(user)) if group is None: _group = -1 elif not isinstance(group, int): _group = _get_gid(group) if _group is None: raise LookupError("no such group: {!r}".format(group)) os.chown(path, _user, _group)
[ "def", "chown", "(", "path", ",", "user", "=", "None", ",", "group", "=", "None", ")", ":", "if", "user", "is", "None", "and", "group", "is", "None", ":", "raise", "ValueError", "(", "\"user and/or group must be set\"", ")", "_user", "=", "user", "_group", "=", "group", "# -1 means don't change it", "if", "user", "is", "None", ":", "_user", "=", "-", "1", "# user can either be an int (the uid) or a string (the system username)", "elif", "isinstance", "(", "user", ",", "str", ")", ":", "_user", "=", "_get_uid", "(", "user", ")", "if", "_user", "is", "None", ":", "raise", "LookupError", "(", "\"no such user: {!r}\"", ".", "format", "(", "user", ")", ")", "if", "group", "is", "None", ":", "_group", "=", "-", "1", "elif", "not", "isinstance", "(", "group", ",", "int", ")", ":", "_group", "=", "_get_gid", "(", "group", ")", "if", "_group", "is", "None", ":", "raise", "LookupError", "(", "\"no such group: {!r}\"", ".", "format", "(", "group", ")", ")", "os", ".", "chown", "(", "path", ",", "_user", ",", "_group", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/shutil.py#L1042-L1071
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
GraphicsPath.AddArcToPoint
(*args, **kwargs)
return _gdi_.GraphicsPath_AddArcToPoint(*args, **kwargs)
AddArcToPoint(self, Double x1, Double y1, Double x2, Double y2, Double r) Appends an arc to two tangents connecting (current) to (x1,y1) and (x1,y1) to (x2,y2), also a straight line from (current) to (x1,y1)
AddArcToPoint(self, Double x1, Double y1, Double x2, Double y2, Double r)
[ "AddArcToPoint", "(", "self", "Double", "x1", "Double", "y1", "Double", "x2", "Double", "y2", "Double", "r", ")" ]
def AddArcToPoint(*args, **kwargs): """ AddArcToPoint(self, Double x1, Double y1, Double x2, Double y2, Double r) Appends an arc to two tangents connecting (current) to (x1,y1) and (x1,y1) to (x2,y2), also a straight line from (current) to (x1,y1) """ return _gdi_.GraphicsPath_AddArcToPoint(*args, **kwargs)
[ "def", "AddArcToPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "GraphicsPath_AddArcToPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L5965-L5972
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/seqan/dox/inc_mgr.py
python
IncludeManager._loadSnippets
(self, path)
Load snippet @raises IncludeException When there is an error loading the file or snippet.
Load snippet
[ "Load", "snippet" ]
def _loadSnippets(self, path): """Load snippet @raises IncludeException When there is an error loading the file or snippet. """ if not self.file_cache.get(path): self._loadFile(path) current_key = None current_lines = [] fcontents = self.file_cache[path] for line in fcontents.splitlines(): line = line.rstrip() # Strip line ending and trailing whitespace. if line.strip().startswith('//![') and line.strip().endswith(']'): key = line.strip()[4:-1].strip() if key == current_key: self.snippet_cache[(path, key)] = '\n'.join(current_lines) current_lines = [] current_key = None else: current_key = key elif current_key: current_lines.append(line) if current_lines and current_key: self.snippet_cache[(path, current_key)] = '\n'.join(current_lines)
[ "def", "_loadSnippets", "(", "self", ",", "path", ")", ":", "if", "not", "self", ".", "file_cache", ".", "get", "(", "path", ")", ":", "self", ".", "_loadFile", "(", "path", ")", "current_key", "=", "None", "current_lines", "=", "[", "]", "fcontents", "=", "self", ".", "file_cache", "[", "path", "]", "for", "line", "in", "fcontents", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "rstrip", "(", ")", "# Strip line ending and trailing whitespace.", "if", "line", ".", "strip", "(", ")", ".", "startswith", "(", "'//!['", ")", "and", "line", ".", "strip", "(", ")", ".", "endswith", "(", "']'", ")", ":", "key", "=", "line", ".", "strip", "(", ")", "[", "4", ":", "-", "1", "]", ".", "strip", "(", ")", "if", "key", "==", "current_key", ":", "self", ".", "snippet_cache", "[", "(", "path", ",", "key", ")", "]", "=", "'\\n'", ".", "join", "(", "current_lines", ")", "current_lines", "=", "[", "]", "current_key", "=", "None", "else", ":", "current_key", "=", "key", "elif", "current_key", ":", "current_lines", ".", "append", "(", "line", ")", "if", "current_lines", "and", "current_key", ":", "self", ".", "snippet_cache", "[", "(", "path", ",", "current_key", ")", "]", "=", "'\\n'", ".", "join", "(", "current_lines", ")" ]
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/inc_mgr.py#L69-L92
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/python/caffe/io.py
python
Transformer.set_channel_swap
(self, in_, order)
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example.
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose.
[ "Set", "the", "input", "channel", "order", "for", "e", ".", "g", ".", "RGB", "to", "BGR", "conversion", "as", "needed", "for", "the", "reference", "ImageNet", "model", ".", "N", ".", "B", ".", "this", "assumes", "the", "channels", "are", "the", "first", "dimension", "AFTER", "transpose", "." ]
def set_channel_swap(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example. """ self.__check_input(in_) if len(order) != self.inputs[in_][1]: raise Exception('Channel swap needs to have the same number of ' 'dimensions as the input channels.') self.channel_swap[in_] = order
[ "def", "set_channel_swap", "(", "self", ",", "in_", ",", "order", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "if", "len", "(", "order", ")", "!=", "self", ".", "inputs", "[", "in_", "]", "[", "1", "]", ":", "raise", "Exception", "(", "'Channel swap needs to have the same number of '", "'dimensions as the input channels.'", ")", "self", ".", "channel_swap", "[", "in_", "]", "=", "order" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/python/caffe/io.py#L202-L218
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/models/embedding/word2vec.py
python
Word2Vec.forward
(self, examples, labels)
return true_logits, sampled_logits
Build the graph for the forward pass.
Build the graph for the forward pass.
[ "Build", "the", "graph", "for", "the", "forward", "pass", "." ]
def forward(self, examples, labels): """Build the graph for the forward pass.""" opts = self._options # Declare all variables we need. # Embedding: [vocab_size, emb_dim] init_width = 0.5 / opts.emb_dim emb = tf.Variable( tf.random_uniform( [opts.vocab_size, opts.emb_dim], -init_width, init_width), name="emb") self._emb = emb # Softmax weight: [vocab_size, emb_dim]. Transposed. sm_w_t = tf.Variable( tf.zeros([opts.vocab_size, opts.emb_dim]), name="sm_w_t") # Softmax bias: [emb_dim]. sm_b = tf.Variable(tf.zeros([opts.vocab_size]), name="sm_b") # Global step: scalar, i.e., shape []. self.global_step = tf.Variable(0, name="global_step") # Nodes to compute the nce loss w/ candidate sampling. labels_matrix = tf.reshape( tf.cast(labels, dtype=tf.int64), [opts.batch_size, 1]) # Negative sampling. sampled_ids, _, _ = (tf.nn.fixed_unigram_candidate_sampler( true_classes=labels_matrix, num_true=1, num_sampled=opts.num_samples, unique=True, range_max=opts.vocab_size, distortion=0.75, unigrams=opts.vocab_counts.tolist())) # Embeddings for examples: [batch_size, emb_dim] example_emb = tf.nn.embedding_lookup(emb, examples) # Weights for labels: [batch_size, emb_dim] true_w = tf.nn.embedding_lookup(sm_w_t, labels) # Biases for labels: [batch_size, 1] true_b = tf.nn.embedding_lookup(sm_b, labels) # Weights for sampled ids: [num_sampled, emb_dim] sampled_w = tf.nn.embedding_lookup(sm_w_t, sampled_ids) # Biases for sampled ids: [num_sampled, 1] sampled_b = tf.nn.embedding_lookup(sm_b, sampled_ids) # True logits: [batch_size, 1] true_logits = tf.reduce_sum(tf.mul(example_emb, true_w), 1) + true_b # Sampled logits: [batch_size, num_sampled] # We replicate sampled noise labels for all examples in the batch # using the matmul. sampled_b_vec = tf.reshape(sampled_b, [opts.num_samples]) sampled_logits = tf.matmul(example_emb, sampled_w, transpose_b=True) + sampled_b_vec return true_logits, sampled_logits
[ "def", "forward", "(", "self", ",", "examples", ",", "labels", ")", ":", "opts", "=", "self", ".", "_options", "# Declare all variables we need.", "# Embedding: [vocab_size, emb_dim]", "init_width", "=", "0.5", "/", "opts", ".", "emb_dim", "emb", "=", "tf", ".", "Variable", "(", "tf", ".", "random_uniform", "(", "[", "opts", ".", "vocab_size", ",", "opts", ".", "emb_dim", "]", ",", "-", "init_width", ",", "init_width", ")", ",", "name", "=", "\"emb\"", ")", "self", ".", "_emb", "=", "emb", "# Softmax weight: [vocab_size, emb_dim]. Transposed.", "sm_w_t", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "opts", ".", "vocab_size", ",", "opts", ".", "emb_dim", "]", ")", ",", "name", "=", "\"sm_w_t\"", ")", "# Softmax bias: [emb_dim].", "sm_b", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "opts", ".", "vocab_size", "]", ")", ",", "name", "=", "\"sm_b\"", ")", "# Global step: scalar, i.e., shape [].", "self", ".", "global_step", "=", "tf", ".", "Variable", "(", "0", ",", "name", "=", "\"global_step\"", ")", "# Nodes to compute the nce loss w/ candidate sampling.", "labels_matrix", "=", "tf", ".", "reshape", "(", "tf", ".", "cast", "(", "labels", ",", "dtype", "=", "tf", ".", "int64", ")", ",", "[", "opts", ".", "batch_size", ",", "1", "]", ")", "# Negative sampling.", "sampled_ids", ",", "_", ",", "_", "=", "(", "tf", ".", "nn", ".", "fixed_unigram_candidate_sampler", "(", "true_classes", "=", "labels_matrix", ",", "num_true", "=", "1", ",", "num_sampled", "=", "opts", ".", "num_samples", ",", "unique", "=", "True", ",", "range_max", "=", "opts", ".", "vocab_size", ",", "distortion", "=", "0.75", ",", "unigrams", "=", "opts", ".", "vocab_counts", ".", "tolist", "(", ")", ")", ")", "# Embeddings for examples: [batch_size, emb_dim]", "example_emb", "=", "tf", ".", "nn", ".", "embedding_lookup", "(", "emb", ",", "examples", ")", "# Weights for labels: [batch_size, emb_dim]", "true_w", "=", "tf", ".", "nn", ".", "embedding_lookup", "(", "sm_w_t", ",", "labels", ")", "# Biases for labels: [batch_size, 1]", "true_b", "=", "tf", ".", "nn", ".", "embedding_lookup", "(", "sm_b", ",", "labels", ")", "# Weights for sampled ids: [num_sampled, emb_dim]", "sampled_w", "=", "tf", ".", "nn", ".", "embedding_lookup", "(", "sm_w_t", ",", "sampled_ids", ")", "# Biases for sampled ids: [num_sampled, 1]", "sampled_b", "=", "tf", ".", "nn", ".", "embedding_lookup", "(", "sm_b", ",", "sampled_ids", ")", "# True logits: [batch_size, 1]", "true_logits", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "mul", "(", "example_emb", ",", "true_w", ")", ",", "1", ")", "+", "true_b", "# Sampled logits: [batch_size, num_sampled]", "# We replicate sampled noise labels for all examples in the batch", "# using the matmul.", "sampled_b_vec", "=", "tf", ".", "reshape", "(", "sampled_b", ",", "[", "opts", ".", "num_samples", "]", ")", "sampled_logits", "=", "tf", ".", "matmul", "(", "example_emb", ",", "sampled_w", ",", "transpose_b", "=", "True", ")", "+", "sampled_b_vec", "return", "true_logits", ",", "sampled_logits" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/models/embedding/word2vec.py#L194-L257
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/mac/symbolicate_crash.py
python
CrashReport.Symbolicate
(self, symbol_path)
Symbolicates a crash report stack trace.
Symbolicates a crash report stack trace.
[ "Symbolicates", "a", "crash", "report", "stack", "trace", "." ]
def Symbolicate(self, symbol_path): """Symbolicates a crash report stack trace.""" # In order to be efficient, collect all the offsets that will be passed to # atos by the image name. offsets_by_image = self._CollectAddressesForImages(SYMBOL_IMAGE_MAP.keys()) # For each image, run atos with the list of addresses. for image_name, addresses in offsets_by_image.items(): # If this image was not loaded or is in no stacks, skip. if image_name not in self._binary_images or not len(addresses): continue # Combine the |image_name| and |symbol_path| into the path of the dSYM. dsym_file = self._GetDSymPath(symbol_path, image_name) # From the list of 2-Tuples of (frame, address), create a list of just # addresses. address_list = map(lambda x: x[1], addresses) # Look up the load address of the image. binary_base = self._binary_images[image_name][0] # This returns a list of just symbols. The indices will match up with the # list of |addresses|. symbol_names = self._RunAtos(binary_base, dsym_file, address_list) if not symbol_names: print 'Error loading symbols for ' + image_name continue # Attaches a list of symbol names to stack frames. This assumes that the # order of |addresses| has stayed the same as |symbol_names|. self._AddSymbolsToFrames(symbol_names, addresses)
[ "def", "Symbolicate", "(", "self", ",", "symbol_path", ")", ":", "# In order to be efficient, collect all the offsets that will be passed to", "# atos by the image name.", "offsets_by_image", "=", "self", ".", "_CollectAddressesForImages", "(", "SYMBOL_IMAGE_MAP", ".", "keys", "(", ")", ")", "# For each image, run atos with the list of addresses.", "for", "image_name", ",", "addresses", "in", "offsets_by_image", ".", "items", "(", ")", ":", "# If this image was not loaded or is in no stacks, skip.", "if", "image_name", "not", "in", "self", ".", "_binary_images", "or", "not", "len", "(", "addresses", ")", ":", "continue", "# Combine the |image_name| and |symbol_path| into the path of the dSYM.", "dsym_file", "=", "self", ".", "_GetDSymPath", "(", "symbol_path", ",", "image_name", ")", "# From the list of 2-Tuples of (frame, address), create a list of just", "# addresses.", "address_list", "=", "map", "(", "lambda", "x", ":", "x", "[", "1", "]", ",", "addresses", ")", "# Look up the load address of the image.", "binary_base", "=", "self", ".", "_binary_images", "[", "image_name", "]", "[", "0", "]", "# This returns a list of just symbols. The indices will match up with the", "# list of |addresses|.", "symbol_names", "=", "self", ".", "_RunAtos", "(", "binary_base", ",", "dsym_file", ",", "address_list", ")", "if", "not", "symbol_names", ":", "print", "'Error loading symbols for '", "+", "image_name", "continue", "# Attaches a list of symbol names to stack frames. This assumes that the", "# order of |addresses| has stayed the same as |symbol_names|.", "self", ".", "_AddSymbolsToFrames", "(", "symbol_names", ",", "addresses", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/mac/symbolicate_crash.py#L65-L96
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/control_flow_ops.py
python
ControlFlowContext.GetControlPivot
(self)
return None
Returns the pivot node for this context, or None.
Returns the pivot node for this context, or None.
[ "Returns", "the", "pivot", "node", "for", "this", "context", "or", "None", "." ]
def GetControlPivot(self): """Returns the pivot node for this context, or None.""" return None
[ "def", "GetControlPivot", "(", "self", ")", ":", "return", "None" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L1479-L1481
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/core/defchararray.py
python
startswith
(a, prefix, start=0, end=None)
return _vec_string( a, bool_, 'startswith', [prefix, start] + _clean_args(end))
Returns a boolean array which is `True` where the string element in `a` starts with `prefix`, otherwise `False`. Calls `str.startswith` element-wise. Parameters ---------- a : array_like of str or unicode suffix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Array of booleans See also -------- str.startswith
Returns a boolean array which is `True` where the string element in `a` starts with `prefix`, otherwise `False`.
[ "Returns", "a", "boolean", "array", "which", "is", "True", "where", "the", "string", "element", "in", "a", "starts", "with", "prefix", "otherwise", "False", "." ]
def startswith(a, prefix, start=0, end=None): """ Returns a boolean array which is `True` where the string element in `a` starts with `prefix`, otherwise `False`. Calls `str.startswith` element-wise. Parameters ---------- a : array_like of str or unicode suffix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Array of booleans See also -------- str.startswith """ return _vec_string( a, bool_, 'startswith', [prefix, start] + _clean_args(end))
[ "def", "startswith", "(", "a", ",", "prefix", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "return", "_vec_string", "(", "a", ",", "bool_", ",", "'startswith'", ",", "[", "prefix", ",", "start", "]", "+", "_clean_args", "(", "end", ")", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/defchararray.py#L1397-L1425
AcademySoftwareFoundation/OpenColorIO
73508eb5230374df8d96147a0627c015d359a641
src/apps/pyociodisplay/pyociodisplay.py
python
ImagePlane.paintGL
(self)
Called whenever a repaint is needed. Calling ``update()`` will schedule a repaint.
Called whenever a repaint is needed. Calling ``update()`` will schedule a repaint.
[ "Called", "whenever", "a", "repaint", "is", "needed", ".", "Calling", "update", "()", "will", "schedule", "a", "repaint", "." ]
def paintGL(self): """ Called whenever a repaint is needed. Calling ``update()`` will schedule a repaint. """ GL.glClearColor(0.0, 0.0, 0.0, 1.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT) if self._shader_program is not None: GL.glUseProgram(self._shader_program) self._use_ocio_tex() self._use_ocio_uniforms() # Set uniforms mvp_mat = self._proj_mat * self._model_view_mat mvp_mat_loc = GL.glGetUniformLocation( self._shader_program, "mvpMat" ) GL.glUniformMatrix4fv( mvp_mat_loc, 1, GL.GL_FALSE, self._m44f_to_ndarray(mvp_mat) ) image_tex_loc = GL.glGetUniformLocation( self._shader_program, "imageTex" ) GL.glUniform1i(image_tex_loc, 0) # Bind texture, VAO, and draw GL.glActiveTexture(GL.GL_TEXTURE0 + 0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._image_tex) GL.glBindVertexArray(self._plane_vao) GL.glDrawElements( GL.GL_TRIANGLES, 6, GL.GL_UNSIGNED_INT, ctypes.c_void_p(0) ) GL.glBindVertexArray(0)
[ "def", "paintGL", "(", "self", ")", ":", "GL", ".", "glClearColor", "(", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ")", "GL", ".", "glClear", "(", "GL", ".", "GL_COLOR_BUFFER_BIT", ")", "if", "self", ".", "_shader_program", "is", "not", "None", ":", "GL", ".", "glUseProgram", "(", "self", ".", "_shader_program", ")", "self", ".", "_use_ocio_tex", "(", ")", "self", ".", "_use_ocio_uniforms", "(", ")", "# Set uniforms", "mvp_mat", "=", "self", ".", "_proj_mat", "*", "self", ".", "_model_view_mat", "mvp_mat_loc", "=", "GL", ".", "glGetUniformLocation", "(", "self", ".", "_shader_program", ",", "\"mvpMat\"", ")", "GL", ".", "glUniformMatrix4fv", "(", "mvp_mat_loc", ",", "1", ",", "GL", ".", "GL_FALSE", ",", "self", ".", "_m44f_to_ndarray", "(", "mvp_mat", ")", ")", "image_tex_loc", "=", "GL", ".", "glGetUniformLocation", "(", "self", ".", "_shader_program", ",", "\"imageTex\"", ")", "GL", ".", "glUniform1i", "(", "image_tex_loc", ",", "0", ")", "# Bind texture, VAO, and draw", "GL", ".", "glActiveTexture", "(", "GL", ".", "GL_TEXTURE0", "+", "0", ")", "GL", ".", "glBindTexture", "(", "GL", ".", "GL_TEXTURE_2D", ",", "self", ".", "_image_tex", ")", "GL", ".", "glBindVertexArray", "(", "self", ".", "_plane_vao", ")", "GL", ".", "glDrawElements", "(", "GL", ".", "GL_TRIANGLES", ",", "6", ",", "GL", ".", "GL_UNSIGNED_INT", ",", "ctypes", ".", "c_void_p", "(", "0", ")", ")", "GL", ".", "glBindVertexArray", "(", "0", ")" ]
https://github.com/AcademySoftwareFoundation/OpenColorIO/blob/73508eb5230374df8d96147a0627c015d359a641/src/apps/pyociodisplay/pyociodisplay.py#L282-L328
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
Examples/Image/Detection/utils/od_utils.py
python
filter_results
(regressed_rois, cls_probs, cfg)
return filtered_bboxes, filtered_labels, filtered_scores
Filters the provided results by performing NMS (non maximum suppression) :param regressed_rois: the predicted bounding boxes :param cls_probs: class probabilities per bounding box :param cfg: the configuration :return: bboxes - the filtered list of bounding boxes labels - the single class label per bounding box scores - the probability for the assigned class label per bounding box
Filters the provided results by performing NMS (non maximum suppression) :param regressed_rois: the predicted bounding boxes :param cls_probs: class probabilities per bounding box :param cfg: the configuration :return: bboxes - the filtered list of bounding boxes labels - the single class label per bounding box scores - the probability for the assigned class label per bounding box
[ "Filters", "the", "provided", "results", "by", "performing", "NMS", "(", "non", "maximum", "suppression", ")", ":", "param", "regressed_rois", ":", "the", "predicted", "bounding", "boxes", ":", "param", "cls_probs", ":", "class", "probabilities", "per", "bounding", "box", ":", "param", "cfg", ":", "the", "configuration", ":", "return", ":", "bboxes", "-", "the", "filtered", "list", "of", "bounding", "boxes", "labels", "-", "the", "single", "class", "label", "per", "bounding", "box", "scores", "-", "the", "probability", "for", "the", "assigned", "class", "label", "per", "bounding", "box" ]
def filter_results(regressed_rois, cls_probs, cfg): """ Filters the provided results by performing NMS (non maximum suppression) :param regressed_rois: the predicted bounding boxes :param cls_probs: class probabilities per bounding box :param cfg: the configuration :return: bboxes - the filtered list of bounding boxes labels - the single class label per bounding box scores - the probability for the assigned class label per bounding box """ labels = cls_probs.argmax(axis=1) scores = cls_probs.max(axis=1) nmsKeepIndices = apply_nms_to_single_image_results( regressed_rois, labels, scores, use_gpu_nms=cfg.USE_GPU_NMS, device_id=cfg.GPU_ID, nms_threshold=cfg.RESULTS_NMS_THRESHOLD, conf_threshold=cfg.RESULTS_NMS_CONF_THRESHOLD) filtered_bboxes = regressed_rois[nmsKeepIndices] filtered_labels = labels[nmsKeepIndices] filtered_scores = scores[nmsKeepIndices] return filtered_bboxes, filtered_labels, filtered_scores
[ "def", "filter_results", "(", "regressed_rois", ",", "cls_probs", ",", "cfg", ")", ":", "labels", "=", "cls_probs", ".", "argmax", "(", "axis", "=", "1", ")", "scores", "=", "cls_probs", ".", "max", "(", "axis", "=", "1", ")", "nmsKeepIndices", "=", "apply_nms_to_single_image_results", "(", "regressed_rois", ",", "labels", ",", "scores", ",", "use_gpu_nms", "=", "cfg", ".", "USE_GPU_NMS", ",", "device_id", "=", "cfg", ".", "GPU_ID", ",", "nms_threshold", "=", "cfg", ".", "RESULTS_NMS_THRESHOLD", ",", "conf_threshold", "=", "cfg", ".", "RESULTS_NMS_CONF_THRESHOLD", ")", "filtered_bboxes", "=", "regressed_rois", "[", "nmsKeepIndices", "]", "filtered_labels", "=", "labels", "[", "nmsKeepIndices", "]", "filtered_scores", "=", "scores", "[", "nmsKeepIndices", "]", "return", "filtered_bboxes", ",", "filtered_labels", ",", "filtered_scores" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/Image/Detection/utils/od_utils.py#L77-L102
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/named_commands.py
python
emacs_editing_mode
(event: E)
Switch to Emacs editing mode.
Switch to Emacs editing mode.
[ "Switch", "to", "Emacs", "editing", "mode", "." ]
def emacs_editing_mode(event: E) -> None: """ Switch to Emacs editing mode. """ event.app.editing_mode = EditingMode.EMACS
[ "def", "emacs_editing_mode", "(", "event", ":", "E", ")", "->", "None", ":", "event", ".", "app", ".", "editing_mode", "=", "EditingMode", ".", "EMACS" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/named_commands.py#L639-L643
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
openr/py/openr/cli/utils/utils.py
python
adj_dbs_to_dict
(resp, nodes, bidir, iter_func)
return adjs_map
get parsed adjacency db :param resp kv_store_types.Publication, or decision_types.adjDbs :param nodes set: the set of the nodes to print prefixes for :param bidir bool: only dump bidirectional adjacencies :return map(node, map(adjacency_keys, (adjacency_values)): the parsed adjacency DB in a map with keys and values in strings
get parsed adjacency db
[ "get", "parsed", "adjacency", "db" ]
def adj_dbs_to_dict(resp, nodes, bidir, iter_func): """get parsed adjacency db :param resp kv_store_types.Publication, or decision_types.adjDbs :param nodes set: the set of the nodes to print prefixes for :param bidir bool: only dump bidirectional adjacencies :return map(node, map(adjacency_keys, (adjacency_values)): the parsed adjacency DB in a map with keys and values in strings """ adj_dbs = resp if isinstance(adj_dbs, kv_store_types.Publication): adj_dbs = build_global_adj_db(resp) def _parse_adj(adjs_map, adj_db): version = None if isinstance(adj_db, kv_store_types.Value): version = adj_db.version adj_db = deserialize_thrift_object( adj_db.value, openr_types.AdjacencyDatabase ) adj_db_to_dict(adjs_map, adj_dbs, adj_db, bidir, version) adjs_map = {} iter_func(adjs_map, resp, nodes, _parse_adj) return adjs_map
[ "def", "adj_dbs_to_dict", "(", "resp", ",", "nodes", ",", "bidir", ",", "iter_func", ")", ":", "adj_dbs", "=", "resp", "if", "isinstance", "(", "adj_dbs", ",", "kv_store_types", ".", "Publication", ")", ":", "adj_dbs", "=", "build_global_adj_db", "(", "resp", ")", "def", "_parse_adj", "(", "adjs_map", ",", "adj_db", ")", ":", "version", "=", "None", "if", "isinstance", "(", "adj_db", ",", "kv_store_types", ".", "Value", ")", ":", "version", "=", "adj_db", ".", "version", "adj_db", "=", "deserialize_thrift_object", "(", "adj_db", ".", "value", ",", "openr_types", ".", "AdjacencyDatabase", ")", "adj_db_to_dict", "(", "adjs_map", ",", "adj_dbs", ",", "adj_db", ",", "bidir", ",", "version", ")", "adjs_map", "=", "{", "}", "iter_func", "(", "adjs_map", ",", "resp", ",", "nodes", ",", "_parse_adj", ")", "return", "adjs_map" ]
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/utils/utils.py#L530-L555
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Node/FS.py
python
RootDir._lookup_abs
(self, p, klass, create=1)
return result
Fast (?) lookup of a *normalized* absolute path. This method is intended for use by internal lookups with already-normalized path data. For general-purpose lookups, use the FS.Entry(), FS.Dir() or FS.File() methods. The caller is responsible for making sure we're passed a normalized absolute path; we merely let Python's dictionary look up and return the One True Node.FS object for the path. If a Node for the specified "p" doesn't already exist, and "create" is specified, the Node may be created after recursive invocation to find or create the parent directory or directories.
Fast (?) lookup of a *normalized* absolute path.
[ "Fast", "(", "?", ")", "lookup", "of", "a", "*", "normalized", "*", "absolute", "path", "." ]
def _lookup_abs(self, p, klass, create=1): """ Fast (?) lookup of a *normalized* absolute path. This method is intended for use by internal lookups with already-normalized path data. For general-purpose lookups, use the FS.Entry(), FS.Dir() or FS.File() methods. The caller is responsible for making sure we're passed a normalized absolute path; we merely let Python's dictionary look up and return the One True Node.FS object for the path. If a Node for the specified "p" doesn't already exist, and "create" is specified, the Node may be created after recursive invocation to find or create the parent directory or directories. """ k = _my_normcase(p) try: result = self._lookupDict[k] except KeyError: if not create: msg = "No such file or directory: '%s' in '%s' (and create is False)" % (p, str(self)) raise SCons.Errors.UserError(msg) # There is no Node for this path name, and we're allowed # to create it. dir_name, file_name = p.rsplit('/',1) dir_node = self._lookup_abs(dir_name, Dir) result = klass(file_name, dir_node, self.fs) # Double-check on disk (as configured) that the Node we # created matches whatever is out there in the real world. result.diskcheck_match() self._lookupDict[k] = result dir_node.entries[_my_normcase(file_name)] = result dir_node.implicit = None else: # There is already a Node for this path name. Allow it to # complain if we were looking for an inappropriate type. result.must_be_same(klass) return result
[ "def", "_lookup_abs", "(", "self", ",", "p", ",", "klass", ",", "create", "=", "1", ")", ":", "k", "=", "_my_normcase", "(", "p", ")", "try", ":", "result", "=", "self", ".", "_lookupDict", "[", "k", "]", "except", "KeyError", ":", "if", "not", "create", ":", "msg", "=", "\"No such file or directory: '%s' in '%s' (and create is False)\"", "%", "(", "p", ",", "str", "(", "self", ")", ")", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "msg", ")", "# There is no Node for this path name, and we're allowed", "# to create it.", "dir_name", ",", "file_name", "=", "p", ".", "rsplit", "(", "'/'", ",", "1", ")", "dir_node", "=", "self", ".", "_lookup_abs", "(", "dir_name", ",", "Dir", ")", "result", "=", "klass", "(", "file_name", ",", "dir_node", ",", "self", ".", "fs", ")", "# Double-check on disk (as configured) that the Node we", "# created matches whatever is out there in the real world.", "result", ".", "diskcheck_match", "(", ")", "self", ".", "_lookupDict", "[", "k", "]", "=", "result", "dir_node", ".", "entries", "[", "_my_normcase", "(", "file_name", ")", "]", "=", "result", "dir_node", ".", "implicit", "=", "None", "else", ":", "# There is already a Node for this path name. Allow it to", "# complain if we were looking for an inappropriate type.", "result", ".", "must_be_same", "(", "klass", ")", "return", "result" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/FS.py#L2372-L2412
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/group.py
python
AutoScalingGroup.put_notification_configuration
(self, topic, notification_types)
return self.connection.put_notification_configuration(self, topic, notification_types)
Configures an Auto Scaling group to send notifications when specified events take place. Valid notification types are: 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR', 'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR', 'autoscaling:TEST_NOTIFICATION'
Configures an Auto Scaling group to send notifications when specified events take place. Valid notification types are: 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR', 'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR', 'autoscaling:TEST_NOTIFICATION'
[ "Configures", "an", "Auto", "Scaling", "group", "to", "send", "notifications", "when", "specified", "events", "take", "place", ".", "Valid", "notification", "types", "are", ":", "autoscaling", ":", "EC2_INSTANCE_LAUNCH", "autoscaling", ":", "EC2_INSTANCE_LAUNCH_ERROR", "autoscaling", ":", "EC2_INSTANCE_TERMINATE", "autoscaling", ":", "EC2_INSTANCE_TERMINATE_ERROR", "autoscaling", ":", "TEST_NOTIFICATION" ]
def put_notification_configuration(self, topic, notification_types): """ Configures an Auto Scaling group to send notifications when specified events take place. Valid notification types are: 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR', 'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR', 'autoscaling:TEST_NOTIFICATION' """ return self.connection.put_notification_configuration(self, topic, notification_types)
[ "def", "put_notification_configuration", "(", "self", ",", "topic", ",", "notification_types", ")", ":", "return", "self", ".", "connection", ".", "put_notification_configuration", "(", "self", ",", "topic", ",", "notification_types", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/group.py#L309-L321
llvm-mirror/libcxx
78d6a7767ed57b50122a161b91f59f19c9bd0d19
utils/gdb/libcxx/printers.py
python
_typename_with_n_generic_arguments
(gdb_type, n)
return result
Return a string for the type with the first n (1, ...) generic args.
Return a string for the type with the first n (1, ...) generic args.
[ "Return", "a", "string", "for", "the", "type", "with", "the", "first", "n", "(", "1", "...", ")", "generic", "args", "." ]
def _typename_with_n_generic_arguments(gdb_type, n): """Return a string for the type with the first n (1, ...) generic args.""" base_type = _remove_generics(_prettify_typename(gdb_type)) arg_list = [base_type] template = "%s<" for i in range(n): arg_list.append(_typename_for_nth_generic_argument(gdb_type, i)) template += "%s, " result = (template[:-2] + ">") % tuple(arg_list) return result
[ "def", "_typename_with_n_generic_arguments", "(", "gdb_type", ",", "n", ")", ":", "base_type", "=", "_remove_generics", "(", "_prettify_typename", "(", "gdb_type", ")", ")", "arg_list", "=", "[", "base_type", "]", "template", "=", "\"%s<\"", "for", "i", "in", "range", "(", "n", ")", ":", "arg_list", ".", "append", "(", "_typename_for_nth_generic_argument", "(", "gdb_type", ",", "i", ")", ")", "template", "+=", "\"%s, \"", "result", "=", "(", "template", "[", ":", "-", "2", "]", "+", "\">\"", ")", "%", "tuple", "(", "arg_list", ")", "return", "result" ]
https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/utils/gdb/libcxx/printers.py#L109-L119
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/indexed_frame.py
python
IndexedFrame.sort_index
( self, axis=0, level=None, ascending=True, inplace=False, kind=None, na_position="last", sort_remaining=True, ignore_index=False, key=None, )
return self._mimic_inplace(out, inplace=inplace)
Sort object by labels (along an axis). Parameters ---------- axis : {0 or ‘index’, 1 or ‘columns’}, default 0 The axis along which to sort. The value 0 identifies the rows, and 1 identifies the columns. level : int or level name or list of ints or list of level names If not None, sort on values in specified index level(s). This is only useful in the case of MultiIndex. ascending : bool, default True Sort ascending vs. descending. inplace : bool, default False If True, perform operation in-place. kind : sorting method such as `quick sort` and others. Not yet supported. na_position : {‘first’, ‘last’}, default ‘last’ Puts NaNs at the beginning if first; last puts NaNs at the end. sort_remaining : bool, default True Not yet supported ignore_index : bool, default False if True, index will be replaced with RangeIndex. key : callable, optional If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape. For MultiIndex inputs, the key is applied per level. Returns ------- Frame or None Notes ----- Difference from pandas: * Not supporting: kind, sort_remaining=False Examples -------- **Series** >>> import cudf >>> series = cudf.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4]) >>> series 3 a 2 b 1 c 4 d dtype: object >>> series.sort_index() 1 c 2 b 3 a 4 d dtype: object Sort Descending >>> series.sort_index(ascending=False) 4 d 3 a 2 b 1 c dtype: object **DataFrame** >>> df = cudf.DataFrame( ... {"b":[3, 2, 1], "a":[2, 1, 3]}, index=[1, 3, 2]) >>> df.sort_index(axis=0) b a 1 3 2 2 1 3 3 2 1 >>> df.sort_index(axis=1) a b 1 2 3 3 1 2 2 3 1
Sort object by labels (along an axis).
[ "Sort", "object", "by", "labels", "(", "along", "an", "axis", ")", "." ]
def sort_index( self, axis=0, level=None, ascending=True, inplace=False, kind=None, na_position="last", sort_remaining=True, ignore_index=False, key=None, ): """Sort object by labels (along an axis). Parameters ---------- axis : {0 or ‘index’, 1 or ‘columns’}, default 0 The axis along which to sort. The value 0 identifies the rows, and 1 identifies the columns. level : int or level name or list of ints or list of level names If not None, sort on values in specified index level(s). This is only useful in the case of MultiIndex. ascending : bool, default True Sort ascending vs. descending. inplace : bool, default False If True, perform operation in-place. kind : sorting method such as `quick sort` and others. Not yet supported. na_position : {‘first’, ‘last’}, default ‘last’ Puts NaNs at the beginning if first; last puts NaNs at the end. sort_remaining : bool, default True Not yet supported ignore_index : bool, default False if True, index will be replaced with RangeIndex. key : callable, optional If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape. For MultiIndex inputs, the key is applied per level. Returns ------- Frame or None Notes ----- Difference from pandas: * Not supporting: kind, sort_remaining=False Examples -------- **Series** >>> import cudf >>> series = cudf.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4]) >>> series 3 a 2 b 1 c 4 d dtype: object >>> series.sort_index() 1 c 2 b 3 a 4 d dtype: object Sort Descending >>> series.sort_index(ascending=False) 4 d 3 a 2 b 1 c dtype: object **DataFrame** >>> df = cudf.DataFrame( ... {"b":[3, 2, 1], "a":[2, 1, 3]}, index=[1, 3, 2]) >>> df.sort_index(axis=0) b a 1 3 2 2 1 3 3 2 1 >>> df.sort_index(axis=1) a b 1 2 3 3 1 2 2 3 1 """ if kind is not None: raise NotImplementedError("kind is not yet supported") if not sort_remaining: raise NotImplementedError( "sort_remaining == False is not yet supported" ) if key is not None: raise NotImplementedError("key is not yet supported.") if na_position not in {"first", "last"}: raise ValueError(f"invalid na_position: {na_position}") if axis in (0, "index"): idx = self.index if isinstance(idx, MultiIndex): if level is not None: # Pandas doesn't handle na_position in case of MultiIndex. na_position = "first" if ascending is True else "last" labels = [ idx._get_level_label(lvl) for lvl in (level if is_list_like(level) else (level,)) ] # Explicitly construct a Frame rather than using type(self) # to avoid constructing a SingleColumnFrame (e.g. Series). idx = Frame._from_data(idx._data.select_by_label(labels)) inds = idx._get_sorted_inds( ascending=ascending, na_position=na_position ) out = self._gather(inds) # TODO: frame factory function should handle multilevel column # names if isinstance( self, cudf.core.dataframe.DataFrame ) and isinstance( self.columns, pd.core.indexes.multi.MultiIndex ): out.columns = self.columns elif (ascending and idx.is_monotonic_increasing) or ( not ascending and idx.is_monotonic_decreasing ): out = self.copy() else: inds = idx.argsort( ascending=ascending, na_position=na_position ) out = self._gather(inds) if isinstance( self, cudf.core.dataframe.DataFrame ) and isinstance( self.columns, pd.core.indexes.multi.MultiIndex ): out.columns = self.columns else: labels = sorted(self._data.names, reverse=not ascending) out = self[labels] if ignore_index is True: out = out.reset_index(drop=True) return self._mimic_inplace(out, inplace=inplace)
[ "def", "sort_index", "(", "self", ",", "axis", "=", "0", ",", "level", "=", "None", ",", "ascending", "=", "True", ",", "inplace", "=", "False", ",", "kind", "=", "None", ",", "na_position", "=", "\"last\"", ",", "sort_remaining", "=", "True", ",", "ignore_index", "=", "False", ",", "key", "=", "None", ",", ")", ":", "if", "kind", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "\"kind is not yet supported\"", ")", "if", "not", "sort_remaining", ":", "raise", "NotImplementedError", "(", "\"sort_remaining == False is not yet supported\"", ")", "if", "key", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "\"key is not yet supported.\"", ")", "if", "na_position", "not", "in", "{", "\"first\"", ",", "\"last\"", "}", ":", "raise", "ValueError", "(", "f\"invalid na_position: {na_position}\"", ")", "if", "axis", "in", "(", "0", ",", "\"index\"", ")", ":", "idx", "=", "self", ".", "index", "if", "isinstance", "(", "idx", ",", "MultiIndex", ")", ":", "if", "level", "is", "not", "None", ":", "# Pandas doesn't handle na_position in case of MultiIndex.", "na_position", "=", "\"first\"", "if", "ascending", "is", "True", "else", "\"last\"", "labels", "=", "[", "idx", ".", "_get_level_label", "(", "lvl", ")", "for", "lvl", "in", "(", "level", "if", "is_list_like", "(", "level", ")", "else", "(", "level", ",", ")", ")", "]", "# Explicitly construct a Frame rather than using type(self)", "# to avoid constructing a SingleColumnFrame (e.g. Series).", "idx", "=", "Frame", ".", "_from_data", "(", "idx", ".", "_data", ".", "select_by_label", "(", "labels", ")", ")", "inds", "=", "idx", ".", "_get_sorted_inds", "(", "ascending", "=", "ascending", ",", "na_position", "=", "na_position", ")", "out", "=", "self", ".", "_gather", "(", "inds", ")", "# TODO: frame factory function should handle multilevel column", "# names", "if", "isinstance", "(", "self", ",", "cudf", ".", "core", ".", "dataframe", ".", "DataFrame", ")", "and", "isinstance", "(", "self", ".", "columns", ",", "pd", ".", "core", ".", "indexes", ".", "multi", ".", "MultiIndex", ")", ":", "out", ".", "columns", "=", "self", ".", "columns", "elif", "(", "ascending", "and", "idx", ".", "is_monotonic_increasing", ")", "or", "(", "not", "ascending", "and", "idx", ".", "is_monotonic_decreasing", ")", ":", "out", "=", "self", ".", "copy", "(", ")", "else", ":", "inds", "=", "idx", ".", "argsort", "(", "ascending", "=", "ascending", ",", "na_position", "=", "na_position", ")", "out", "=", "self", ".", "_gather", "(", "inds", ")", "if", "isinstance", "(", "self", ",", "cudf", ".", "core", ".", "dataframe", ".", "DataFrame", ")", "and", "isinstance", "(", "self", ".", "columns", ",", "pd", ".", "core", ".", "indexes", ".", "multi", ".", "MultiIndex", ")", ":", "out", ".", "columns", "=", "self", ".", "columns", "else", ":", "labels", "=", "sorted", "(", "self", ".", "_data", ".", "names", ",", "reverse", "=", "not", "ascending", ")", "out", "=", "self", "[", "labels", "]", "if", "ignore_index", "is", "True", ":", "out", "=", "out", ".", "reset_index", "(", "drop", "=", "True", ")", "return", "self", ".", "_mimic_inplace", "(", "out", ",", "inplace", "=", "inplace", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/indexed_frame.py#L321-L474
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
AuiManager.GetAllPanes
(self)
return self._panes
Returns a reference to all the pane info structures.
Returns a reference to all the pane info structures.
[ "Returns", "a", "reference", "to", "all", "the", "pane", "info", "structures", "." ]
def GetAllPanes(self): """ Returns a reference to all the pane info structures. """ return self._panes
[ "def", "GetAllPanes", "(", "self", ")", ":", "return", "self", ".", "_panes" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L4306-L4309
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py
python
DataFrame._set_value
(self, index, col, value, takeable: bool = False)
Put single value at passed column and index. Parameters ---------- index : row label col : column label value : scalar takeable : interpret the index/col as indexers, default False Returns ------- DataFrame If label pair is contained, will be reference to calling DataFrame, otherwise a new object.
Put single value at passed column and index.
[ "Put", "single", "value", "at", "passed", "column", "and", "index", "." ]
def _set_value(self, index, col, value, takeable: bool = False): """ Put single value at passed column and index. Parameters ---------- index : row label col : column label value : scalar takeable : interpret the index/col as indexers, default False Returns ------- DataFrame If label pair is contained, will be reference to calling DataFrame, otherwise a new object. """ try: if takeable is True: series = self._iget_item_cache(col) return series._set_value(index, value, takeable=True) series = self._get_item_cache(col) engine = self.index._engine engine.set_value(series._values, index, value) return self except (KeyError, TypeError): # set using a non-recursive method & reset the cache if takeable: self.iloc[index, col] = value else: self.loc[index, col] = value self._item_cache.pop(col, None) return self
[ "def", "_set_value", "(", "self", ",", "index", ",", "col", ",", "value", ",", "takeable", ":", "bool", "=", "False", ")", ":", "try", ":", "if", "takeable", "is", "True", ":", "series", "=", "self", ".", "_iget_item_cache", "(", "col", ")", "return", "series", ".", "_set_value", "(", "index", ",", "value", ",", "takeable", "=", "True", ")", "series", "=", "self", ".", "_get_item_cache", "(", "col", ")", "engine", "=", "self", ".", "index", ".", "_engine", "engine", ".", "set_value", "(", "series", ".", "_values", ",", "index", ",", "value", ")", "return", "self", "except", "(", "KeyError", ",", "TypeError", ")", ":", "# set using a non-recursive method & reset the cache", "if", "takeable", ":", "self", ".", "iloc", "[", "index", ",", "col", "]", "=", "value", "else", ":", "self", ".", "loc", "[", "index", ",", "col", "]", "=", "value", "self", ".", "_item_cache", ".", "pop", "(", "col", ",", "None", ")", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py#L3009-L3044
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/sparsity/keras/pruning_impl.py
python
Pruning._maybe_update_block_mask
(self, weights)
return new_threshold, tf.reshape(sliced_mask, tf.shape(weights))
Performs block-granular masking of the weights. Block pruning occurs only if the block_height or block_width is > 1 and if the weight tensor, when squeezed, has ndims = 2. Otherwise, elementwise pruning occurs. Args: weights: The weight tensor that needs to be masked. Returns: new_threshold: The new value of the threshold based on weights, and sparsity at the current global_step new_mask: A numpy array of the same size and shape as weights containing 0 or 1 to indicate which of the values in weights falls below the threshold Raises: ValueError: if block pooling function is not AVG or MAX
Performs block-granular masking of the weights.
[ "Performs", "block", "-", "granular", "masking", "of", "the", "weights", "." ]
def _maybe_update_block_mask(self, weights): """Performs block-granular masking of the weights. Block pruning occurs only if the block_height or block_width is > 1 and if the weight tensor, when squeezed, has ndims = 2. Otherwise, elementwise pruning occurs. Args: weights: The weight tensor that needs to be masked. Returns: new_threshold: The new value of the threshold based on weights, and sparsity at the current global_step new_mask: A numpy array of the same size and shape as weights containing 0 or 1 to indicate which of the values in weights falls below the threshold Raises: ValueError: if block pooling function is not AVG or MAX """ if self._block_size == [1, 1]: return self._update_mask(weights) # TODO(pulkitb): Check if squeeze operations should now be removed since # we are only accepting 2-D weights. squeezed_weights = tf.squeeze(weights) abs_weights = tf.math.abs(squeezed_weights) pooled_weights = pruning_utils.factorized_pool( abs_weights, window_shape=self._block_size, pooling_type=self._block_pooling_type, strides=self._block_size, padding='SAME') if pooled_weights.get_shape().ndims != 2: pooled_weights = tf.squeeze(pooled_weights) new_threshold, new_mask = self._update_mask(pooled_weights) updated_mask = pruning_utils.expand_tensor(new_mask, self._block_size) sliced_mask = tf.slice( updated_mask, [0, 0], [squeezed_weights.get_shape()[0], squeezed_weights.get_shape()[1]]) return new_threshold, tf.reshape(sliced_mask, tf.shape(weights))
[ "def", "_maybe_update_block_mask", "(", "self", ",", "weights", ")", ":", "if", "self", ".", "_block_size", "==", "[", "1", ",", "1", "]", ":", "return", "self", ".", "_update_mask", "(", "weights", ")", "# TODO(pulkitb): Check if squeeze operations should now be removed since", "# we are only accepting 2-D weights.", "squeezed_weights", "=", "tf", ".", "squeeze", "(", "weights", ")", "abs_weights", "=", "tf", ".", "math", ".", "abs", "(", "squeezed_weights", ")", "pooled_weights", "=", "pruning_utils", ".", "factorized_pool", "(", "abs_weights", ",", "window_shape", "=", "self", ".", "_block_size", ",", "pooling_type", "=", "self", ".", "_block_pooling_type", ",", "strides", "=", "self", ".", "_block_size", ",", "padding", "=", "'SAME'", ")", "if", "pooled_weights", ".", "get_shape", "(", ")", ".", "ndims", "!=", "2", ":", "pooled_weights", "=", "tf", ".", "squeeze", "(", "pooled_weights", ")", "new_threshold", ",", "new_mask", "=", "self", ".", "_update_mask", "(", "pooled_weights", ")", "updated_mask", "=", "pruning_utils", ".", "expand_tensor", "(", "new_mask", ",", "self", ".", "_block_size", ")", "sliced_mask", "=", "tf", ".", "slice", "(", "updated_mask", ",", "[", "0", ",", "0", "]", ",", "[", "squeezed_weights", ".", "get_shape", "(", ")", "[", "0", "]", ",", "squeezed_weights", ".", "get_shape", "(", ")", "[", "1", "]", "]", ")", "return", "new_threshold", ",", "tf", ".", "reshape", "(", "sliced_mask", ",", "tf", ".", "shape", "(", "weights", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/sparsity/keras/pruning_impl.py#L101-L145
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
LeetCode/python/1020.py
python
Solution.canThreePartsEqualSum
(self, A)
return False
:type A: List[int] :rtype: bool
:type A: List[int] :rtype: bool
[ ":", "type", "A", ":", "List", "[", "int", "]", ":", "rtype", ":", "bool" ]
def canThreePartsEqualSum(self, A): """ :type A: List[int] :rtype: bool """ s = sum(A) if s % 3 != 0: return False s //= 3 cum = 0 total = 0 for a in A: cum += a if cum == s: total += 1 cum = 0 if total == 3 and cum == 0: return True return False
[ "def", "canThreePartsEqualSum", "(", "self", ",", "A", ")", ":", "s", "=", "sum", "(", "A", ")", "if", "s", "%", "3", "!=", "0", ":", "return", "False", "s", "//=", "3", "cum", "=", "0", "total", "=", "0", "for", "a", "in", "A", ":", "cum", "+=", "a", "if", "cum", "==", "s", ":", "total", "+=", "1", "cum", "=", "0", "if", "total", "==", "3", "and", "cum", "==", "0", ":", "return", "True", "return", "False" ]
https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python/1020.py#L2-L20
blitzpp/blitz
39f885951a9b8b11f931f917935a16066a945056
blitz/generate/makeloops.py
python
genf77
(loop)
Generate the fortran code from loop data.
Generate the fortran code from loop data.
[ "Generate", "the", "fortran", "code", "from", "loop", "data", "." ]
def genf77(loop): """Generate the fortran code from loop data.""" f77expr = indexexpr(loop,"i") # see if we must continue line maxlen=60 if len(f77expr)>maxlen: f77expr=f77expr[:maxlen]+"\n !"+f77expr[maxlen:] subs=[ ("loopname",loopname(loop)), ("f77args", cc([", %s"%n for n in looparrays(loop)])+ cc([", %s"%n for n in loopscalars(loop)])), ("f77decls", "%s(N)"%looparrays(loop)[0] + cc([", %s(N)"%n for n in looparrays(loop)[1:]])+ cc([", %s"%n for n in loopscalars(loop)])), ("numtypesize",`loopnumtype(loop)[1]`), ("f77loopexpr", f77expr) ] f77 = sub_skeleton(f77_skeleton, subs) f=open("%sf.f"%loopname(loop),"w") f.write(f77)
[ "def", "genf77", "(", "loop", ")", ":", "f77expr", "=", "indexexpr", "(", "loop", ",", "\"i\"", ")", "# see if we must continue line", "maxlen", "=", "60", "if", "len", "(", "f77expr", ")", ">", "maxlen", ":", "f77expr", "=", "f77expr", "[", ":", "maxlen", "]", "+", "\"\\n !\"", "+", "f77expr", "[", "maxlen", ":", "]", "subs", "=", "[", "(", "\"loopname\"", ",", "loopname", "(", "loop", ")", ")", ",", "(", "\"f77args\"", ",", "cc", "(", "[", "\", %s\"", "%", "n", "for", "n", "in", "looparrays", "(", "loop", ")", "]", ")", "+", "cc", "(", "[", "\", %s\"", "%", "n", "for", "n", "in", "loopscalars", "(", "loop", ")", "]", ")", ")", ",", "(", "\"f77decls\"", ",", "\"%s(N)\"", "%", "looparrays", "(", "loop", ")", "[", "0", "]", "+", "cc", "(", "[", "\", %s(N)\"", "%", "n", "for", "n", "in", "looparrays", "(", "loop", ")", "[", "1", ":", "]", "]", ")", "+", "cc", "(", "[", "\", %s\"", "%", "n", "for", "n", "in", "loopscalars", "(", "loop", ")", "]", ")", ")", ",", "(", "\"numtypesize\"", ",", "`loopnumtype(loop)[1]`", ")", ",", "(", "\"f77loopexpr\"", ",", "f77expr", ")", "]", "f77", "=", "sub_skeleton", "(", "f77_skeleton", ",", "subs", ")", "f", "=", "open", "(", "\"%sf.f\"", "%", "loopname", "(", "loop", ")", ",", "\"w\"", ")", "f", ".", "write", "(", "f77", ")" ]
https://github.com/blitzpp/blitz/blob/39f885951a9b8b11f931f917935a16066a945056/blitz/generate/makeloops.py#L216-L238
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Scripting.py
python
Dist.get_arch_name
(self)
return self.arch_name
Returns the archive file name. Set the attribute *arch_name* to change the default value:: def dist(ctx): ctx.arch_name = 'ctx.tar.bz2' :rtype: string
Returns the archive file name. Set the attribute *arch_name* to change the default value::
[ "Returns", "the", "archive", "file", "name", ".", "Set", "the", "attribute", "*", "arch_name", "*", "to", "change", "the", "default", "value", "::" ]
def get_arch_name(self): """ Returns the archive file name. Set the attribute *arch_name* to change the default value:: def dist(ctx): ctx.arch_name = 'ctx.tar.bz2' :rtype: string """ try: self.arch_name except AttributeError: self.arch_name = self.get_base_name() + '.' + self.ext_algo.get(self.algo, self.algo) return self.arch_name
[ "def", "get_arch_name", "(", "self", ")", ":", "try", ":", "self", ".", "arch_name", "except", "AttributeError", ":", "self", ".", "arch_name", "=", "self", ".", "get_base_name", "(", ")", "+", "'.'", "+", "self", ".", "ext_algo", ".", "get", "(", "self", ".", "algo", ",", "self", ".", "algo", ")", "return", "self", ".", "arch_name" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Scripting.py#L446-L460
happynear/caffe-windows
967eedf25009e334b7f6f933bb5e17aaaff5bef6
examples/pycaffe/tools.py
python
SimpleTransformer.deprocess
(self, im)
return np.uint8(im)
inverse of preprocess()
inverse of preprocess()
[ "inverse", "of", "preprocess", "()" ]
def deprocess(self, im): """ inverse of preprocess() """ im = im.transpose(1, 2, 0) im /= self.scale im += self.mean im = im[:, :, ::-1] # change to RGB return np.uint8(im)
[ "def", "deprocess", "(", "self", ",", "im", ")", ":", "im", "=", "im", ".", "transpose", "(", "1", ",", "2", ",", "0", ")", "im", "/=", "self", ".", "scale", "im", "+=", "self", ".", "mean", "im", "=", "im", "[", ":", ",", ":", ",", ":", ":", "-", "1", "]", "# change to RGB", "return", "np", ".", "uint8", "(", "im", ")" ]
https://github.com/happynear/caffe-windows/blob/967eedf25009e334b7f6f933bb5e17aaaff5bef6/examples/pycaffe/tools.py#L41-L50
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Image.Resize
(*args, **kwargs)
return _core_.Image_Resize(*args, **kwargs)
Resize(self, Size size, Point pos, int r=-1, int g=-1, int b=-1) -> Image Changes the size of the image in-place without scaling it, by adding either a border with the given colour or cropping as necessary. The image is pasted into a new image with the given size and background colour at the position pos relative to the upper left of the new image. If red = green = blue = -1 then use either the current mask colour if set or find, use, and set a suitable mask colour for any newly exposed areas. Returns the (modified) image itself.
Resize(self, Size size, Point pos, int r=-1, int g=-1, int b=-1) -> Image
[ "Resize", "(", "self", "Size", "size", "Point", "pos", "int", "r", "=", "-", "1", "int", "g", "=", "-", "1", "int", "b", "=", "-", "1", ")", "-", ">", "Image" ]
def Resize(*args, **kwargs): """ Resize(self, Size size, Point pos, int r=-1, int g=-1, int b=-1) -> Image Changes the size of the image in-place without scaling it, by adding either a border with the given colour or cropping as necessary. The image is pasted into a new image with the given size and background colour at the position pos relative to the upper left of the new image. If red = green = blue = -1 then use either the current mask colour if set or find, use, and set a suitable mask colour for any newly exposed areas. Returns the (modified) image itself. """ return _core_.Image_Resize(*args, **kwargs)
[ "def", "Resize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_Resize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L2982-L2996
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/mindrecord/mindpage.py
python
MindPage.read_at_page_by_name
(self, category_name, page, num_row)
return self._segment.read_at_page_by_name(category_name, page, num_row)
Query by category name in pagination. Args: category_name (str): String of category field's value, referred to the return of `read_category_info`. page (int): Index of page. num_row (int): Number of row in a page. Returns: list[dict], data queried by category name.
Query by category name in pagination.
[ "Query", "by", "category", "name", "in", "pagination", "." ]
def read_at_page_by_name(self, category_name, page, num_row): """ Query by category name in pagination. Args: category_name (str): String of category field's value, referred to the return of `read_category_info`. page (int): Index of page. num_row (int): Number of row in a page. Returns: list[dict], data queried by category name. """ if not isinstance(category_name, str): raise ParamValueError("Category name should be str.") if not isinstance(page, int) or page < 0: raise ParamValueError("Page should be int and greater than or equal to 0.") if not isinstance(num_row, int) or num_row <= 0: raise ParamValueError("num_row should be int and greater than 0.") return self._segment.read_at_page_by_name(category_name, page, num_row)
[ "def", "read_at_page_by_name", "(", "self", ",", "category_name", ",", "page", ",", "num_row", ")", ":", "if", "not", "isinstance", "(", "category_name", ",", "str", ")", ":", "raise", "ParamValueError", "(", "\"Category name should be str.\"", ")", "if", "not", "isinstance", "(", "page", ",", "int", ")", "or", "page", "<", "0", ":", "raise", "ParamValueError", "(", "\"Page should be int and greater than or equal to 0.\"", ")", "if", "not", "isinstance", "(", "num_row", ",", "int", ")", "or", "num_row", "<=", "0", ":", "raise", "ParamValueError", "(", "\"num_row should be int and greater than 0.\"", ")", "return", "self", ".", "_segment", ".", "read_at_page_by_name", "(", "category_name", ",", "page", ",", "num_row", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/mindpage.py#L151-L170
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0392-Is-Subsequence/0392.py
python
Solution.isSubsequence
(self, s, t)
return True
:type s: str :type t: str :rtype: bool
:type s: str :type t: str :rtype: bool
[ ":", "type", "s", ":", "str", ":", "type", "t", ":", "str", ":", "rtype", ":", "bool" ]
def isSubsequence(self, s, t): """ :type s: str :type t: str :rtype: bool """ for per_s in s: s_index_t = t.find(per_s) if s_index_t == -1: return False if s_index_t == len(t) - 1: t = str() else: t = t[s_index_t+1:] return True
[ "def", "isSubsequence", "(", "self", ",", "s", ",", "t", ")", ":", "for", "per_s", "in", "s", ":", "s_index_t", "=", "t", ".", "find", "(", "per_s", ")", "if", "s_index_t", "==", "-", "1", ":", "return", "False", "if", "s_index_t", "==", "len", "(", "t", ")", "-", "1", ":", "t", "=", "str", "(", ")", "else", ":", "t", "=", "t", "[", "s_index_t", "+", "1", ":", "]", "return", "True" ]
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0392-Is-Subsequence/0392.py#L2-L18
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/boost/tools/build/src/build/property.py
python
take
(attributes, properties)
return result
Returns a property set which include all properties in 'properties' that have any of 'attributes'.
Returns a property set which include all properties in 'properties' that have any of 'attributes'.
[ "Returns", "a", "property", "set", "which", "include", "all", "properties", "in", "properties", "that", "have", "any", "of", "attributes", "." ]
def take(attributes, properties): """Returns a property set which include all properties in 'properties' that have any of 'attributes'.""" assert is_iterable_typed(attributes, basestring) assert is_iterable_typed(properties, basestring) result = [] for e in properties: if b2.util.set.intersection(attributes, feature.attributes(get_grist(e))): result.append(e) return result
[ "def", "take", "(", "attributes", ",", "properties", ")", ":", "assert", "is_iterable_typed", "(", "attributes", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "properties", ",", "basestring", ")", "result", "=", "[", "]", "for", "e", "in", "properties", ":", "if", "b2", ".", "util", ".", "set", ".", "intersection", "(", "attributes", ",", "feature", ".", "attributes", "(", "get_grist", "(", "e", ")", ")", ")", ":", "result", ".", "append", "(", "e", ")", "return", "result" ]
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/property.py#L542-L551
taichi-dev/taichi
973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6
python/taichi/lang/_ndarray.py
python
Ndarray.fill
(self, val)
Fills ndarray with a specific scalar value. Args: val (Union[int, float]): Value to fill.
Fills ndarray with a specific scalar value.
[ "Fills", "ndarray", "with", "a", "specific", "scalar", "value", "." ]
def fill(self, val): """Fills ndarray with a specific scalar value. Args: val (Union[int, float]): Value to fill. """ if self.ndarray_use_torch: self.arr.fill_(val) elif impl.current_cfg( ).arch != _ti_core.Arch.cuda and impl.current_cfg( ).arch != _ti_core.Arch.x64: self.fill_by_kernel(val) elif self.dtype == primitive_types.f32: self.arr.fill_float(val) elif self.dtype == primitive_types.i32: self.arr.fill_int(val) elif self.dtype == primitive_types.u32: self.arr.fill_uint(val) else: self.fill_by_kernel(val)
[ "def", "fill", "(", "self", ",", "val", ")", ":", "if", "self", ".", "ndarray_use_torch", ":", "self", ".", "arr", ".", "fill_", "(", "val", ")", "elif", "impl", ".", "current_cfg", "(", ")", ".", "arch", "!=", "_ti_core", ".", "Arch", ".", "cuda", "and", "impl", ".", "current_cfg", "(", ")", ".", "arch", "!=", "_ti_core", ".", "Arch", ".", "x64", ":", "self", ".", "fill_by_kernel", "(", "val", ")", "elif", "self", ".", "dtype", "==", "primitive_types", ".", "f32", ":", "self", ".", "arr", ".", "fill_float", "(", "val", ")", "elif", "self", ".", "dtype", "==", "primitive_types", ".", "i32", ":", "self", ".", "arr", ".", "fill_int", "(", "val", ")", "elif", "self", ".", "dtype", "==", "primitive_types", ".", "u32", ":", "self", ".", "arr", ".", "fill_uint", "(", "val", ")", "else", ":", "self", ".", "fill_by_kernel", "(", "val", ")" ]
https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/_ndarray.py#L78-L97
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/textwrap.py
python
fill
(text, width=70, **kwargs)
return w.fill(text)
Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour.
Fill a single paragraph of text, returning a new string.
[ "Fill", "a", "single", "paragraph", "of", "text", "returning", "a", "new", "string", "." ]
def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text)
[ "def", "fill", "(", "text", ",", "width", "=", "70", ",", "*", "*", "kwargs", ")", ":", "w", "=", "TextWrapper", "(", "width", "=", "width", ",", "*", "*", "kwargs", ")", "return", "w", ".", "fill", "(", "text", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/textwrap.py#L356-L366
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/ror/nyan_subprocessor.py
python
RoRNyanSubprocessor.unit_line_to_game_entity
(unit_line)
Creates raw API objects for a unit line. :param unit_line: Unit line that gets converted to a game entity. :type unit_line: ..dataformat.converter_object.ConverterObjectGroup
Creates raw API objects for a unit line.
[ "Creates", "raw", "API", "objects", "for", "a", "unit", "line", "." ]
def unit_line_to_game_entity(unit_line): """ Creates raw API objects for a unit line. :param unit_line: Unit line that gets converted to a game entity. :type unit_line: ..dataformat.converter_object.ConverterObjectGroup """ current_unit = unit_line.get_head_unit() current_unit_id = unit_line.get_head_unit_id() dataset = unit_line.data name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) class_lookup_dict = internal_name_lookups.get_class_lookups(dataset.game_version) # Start with the generic GameEntity game_entity_name = name_lookup_dict[current_unit_id][0] obj_location = f"data/game_entity/generic/{name_lookup_dict[current_unit_id][1]}/" raw_api_object = RawAPIObject(game_entity_name, game_entity_name, dataset.nyan_api_objects) raw_api_object.add_raw_parent("engine.util.game_entity.GameEntity") raw_api_object.set_location(obj_location) raw_api_object.set_filename(name_lookup_dict[current_unit_id][1]) unit_line.add_raw_api_object(raw_api_object) # ======================================================================= # Game Entity Types # ======================================================================= # we give a unit two types # - util.game_entity_type.types.Unit (if unit_type >= 70) # - util.game_entity_type.types.<Class> (depending on the class) # ======================================================================= # Create or use existing auxiliary types types_set = [] unit_type = current_unit["unit_type"].get_value() if unit_type >= 70: type_obj = dataset.pregen_nyan_objects["util.game_entity_type.types.Unit"].get_nyan_object() types_set.append(type_obj) unit_class = current_unit["unit_class"].get_value() class_name = class_lookup_dict[unit_class] class_obj_name = f"util.game_entity_type.types.{class_name}" type_obj = dataset.pregen_nyan_objects[class_obj_name].get_nyan_object() types_set.append(type_obj) raw_api_object.add_raw_member("types", types_set, "engine.util.game_entity.GameEntity") # ======================================================================= # Abilities # ======================================================================= abilities_set = [] abilities_set.append(AoCAbilitySubprocessor.death_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.delete_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.despawn_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.idle_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.hitbox_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.live_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.los_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.move_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.named_ability(unit_line)) abilities_set.append(RoRAbilitySubprocessor.resistance_ability(unit_line)) abilities_set.extend(AoCAbilitySubprocessor.selectable_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.stop_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.terrain_requirement_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.turn_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.visibility_ability(unit_line)) # Creation if len(unit_line.creates) > 0: abilities_set.append(AoCAbilitySubprocessor.create_ability(unit_line)) # Config ability = AoCAbilitySubprocessor.use_contingent_ability(unit_line) if ability: abilities_set.append(ability) if unit_line.has_command(104): # Recharging attribute points (priests) abilities_set.extend(AoCAbilitySubprocessor.regenerate_attribute_ability(unit_line)) # Applying effects and shooting projectiles if unit_line.is_projectile_shooter(): abilities_set.append(RoRAbilitySubprocessor.shoot_projectile_ability(unit_line, 7)) RoRNyanSubprocessor.projectiles_from_line(unit_line) elif unit_line.is_melee() or unit_line.is_ranged(): if unit_line.has_command(7): # Attack abilities_set.append(AoCAbilitySubprocessor.apply_discrete_effect_ability(unit_line, 7, unit_line.is_ranged())) if unit_line.has_command(101): # Build abilities_set.append(AoCAbilitySubprocessor.apply_continuous_effect_ability(unit_line, 101, unit_line.is_ranged())) if unit_line.has_command(104): # TODO: Success chance is not a resource in RoR # Convert abilities_set.append(RoRAbilitySubprocessor.apply_discrete_effect_ability(unit_line, 104, unit_line.is_ranged())) if unit_line.has_command(105): # Heal abilities_set.append(AoCAbilitySubprocessor.apply_continuous_effect_ability(unit_line, 105, unit_line.is_ranged())) if unit_line.has_command(106): # Repair abilities_set.append(AoCAbilitySubprocessor.apply_continuous_effect_ability(unit_line, 106, unit_line.is_ranged())) # Formation/Stance if not isinstance(unit_line, GenieVillagerGroup): abilities_set.append(RoRAbilitySubprocessor.game_entity_stance_ability(unit_line)) # Storage abilities if unit_line.is_garrison(): abilities_set.append(AoCAbilitySubprocessor.storage_ability(unit_line)) abilities_set.append(AoCAbilitySubprocessor.remove_storage_ability(unit_line)) if len(unit_line.garrison_locations) > 0: ability = AoCAbilitySubprocessor.enter_container_ability(unit_line) if ability: abilities_set.append(ability) ability = AoCAbilitySubprocessor.exit_container_ability(unit_line) if ability: abilities_set.append(ability) # Resource abilities if unit_line.is_gatherer(): abilities_set.append(AoCAbilitySubprocessor.drop_resources_ability(unit_line)) abilities_set.extend(AoCAbilitySubprocessor.gather_ability(unit_line)) # Resource storage if unit_line.is_gatherer() or unit_line.has_command(111): abilities_set.append(AoCAbilitySubprocessor.resource_storage_ability(unit_line)) if unit_line.is_harvestable(): abilities_set.append(AoCAbilitySubprocessor.harvestable_ability(unit_line)) # Trade abilities if unit_line.has_command(111): abilities_set.append(AoCAbilitySubprocessor.trade_ability(unit_line)) raw_api_object.add_raw_member("abilities", abilities_set, "engine.util.game_entity.GameEntity") # ======================================================================= # Modifiers # ======================================================================= modifiers_set = [] if unit_line.is_gatherer(): modifiers_set.extend(AoCModifierSubprocessor.gather_rate_modifier(unit_line)) # TODO: Other modifiers? raw_api_object.add_raw_member("modifiers", modifiers_set, "engine.util.game_entity.GameEntity") # ======================================================================= # TODO: Variants # ======================================================================= variants_set = [] raw_api_object.add_raw_member("variants", variants_set, "engine.util.game_entity.GameEntity") # ======================================================================= # Misc (Objects that are not used by the unit line itself, but use its values) # ======================================================================= if unit_line.is_creatable(): RoRAuxiliarySubprocessor.get_creatable_game_entity(unit_line)
[ "def", "unit_line_to_game_entity", "(", "unit_line", ")", ":", "current_unit", "=", "unit_line", ".", "get_head_unit", "(", ")", "current_unit_id", "=", "unit_line", ".", "get_head_unit_id", "(", ")", "dataset", "=", "unit_line", ".", "data", "name_lookup_dict", "=", "internal_name_lookups", ".", "get_entity_lookups", "(", "dataset", ".", "game_version", ")", "class_lookup_dict", "=", "internal_name_lookups", ".", "get_class_lookups", "(", "dataset", ".", "game_version", ")", "# Start with the generic GameEntity", "game_entity_name", "=", "name_lookup_dict", "[", "current_unit_id", "]", "[", "0", "]", "obj_location", "=", "f\"data/game_entity/generic/{name_lookup_dict[current_unit_id][1]}/\"", "raw_api_object", "=", "RawAPIObject", "(", "game_entity_name", ",", "game_entity_name", ",", "dataset", ".", "nyan_api_objects", ")", "raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.game_entity.GameEntity\"", ")", "raw_api_object", ".", "set_location", "(", "obj_location", ")", "raw_api_object", ".", "set_filename", "(", "name_lookup_dict", "[", "current_unit_id", "]", "[", "1", "]", ")", "unit_line", ".", "add_raw_api_object", "(", "raw_api_object", ")", "# =======================================================================", "# Game Entity Types", "# =======================================================================", "# we give a unit two types", "# - util.game_entity_type.types.Unit (if unit_type >= 70)", "# - util.game_entity_type.types.<Class> (depending on the class)", "# =======================================================================", "# Create or use existing auxiliary types", "types_set", "=", "[", "]", "unit_type", "=", "current_unit", "[", "\"unit_type\"", "]", ".", "get_value", "(", ")", "if", "unit_type", ">=", "70", ":", "type_obj", "=", "dataset", ".", "pregen_nyan_objects", "[", "\"util.game_entity_type.types.Unit\"", "]", ".", "get_nyan_object", "(", ")", "types_set", ".", "append", "(", "type_obj", ")", "unit_class", "=", "current_unit", "[", "\"unit_class\"", "]", ".", "get_value", "(", ")", "class_name", "=", "class_lookup_dict", "[", "unit_class", "]", "class_obj_name", "=", "f\"util.game_entity_type.types.{class_name}\"", "type_obj", "=", "dataset", ".", "pregen_nyan_objects", "[", "class_obj_name", "]", ".", "get_nyan_object", "(", ")", "types_set", ".", "append", "(", "type_obj", ")", "raw_api_object", ".", "add_raw_member", "(", "\"types\"", ",", "types_set", ",", "\"engine.util.game_entity.GameEntity\"", ")", "# =======================================================================", "# Abilities", "# =======================================================================", "abilities_set", "=", "[", "]", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "death_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "delete_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "despawn_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "idle_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "hitbox_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "live_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "los_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "move_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "named_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "RoRAbilitySubprocessor", ".", "resistance_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "extend", "(", "AoCAbilitySubprocessor", ".", "selectable_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "stop_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "terrain_requirement_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "turn_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "visibility_ability", "(", "unit_line", ")", ")", "# Creation", "if", "len", "(", "unit_line", ".", "creates", ")", ">", "0", ":", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "create_ability", "(", "unit_line", ")", ")", "# Config", "ability", "=", "AoCAbilitySubprocessor", ".", "use_contingent_ability", "(", "unit_line", ")", "if", "ability", ":", "abilities_set", ".", "append", "(", "ability", ")", "if", "unit_line", ".", "has_command", "(", "104", ")", ":", "# Recharging attribute points (priests)", "abilities_set", ".", "extend", "(", "AoCAbilitySubprocessor", ".", "regenerate_attribute_ability", "(", "unit_line", ")", ")", "# Applying effects and shooting projectiles", "if", "unit_line", ".", "is_projectile_shooter", "(", ")", ":", "abilities_set", ".", "append", "(", "RoRAbilitySubprocessor", ".", "shoot_projectile_ability", "(", "unit_line", ",", "7", ")", ")", "RoRNyanSubprocessor", ".", "projectiles_from_line", "(", "unit_line", ")", "elif", "unit_line", ".", "is_melee", "(", ")", "or", "unit_line", ".", "is_ranged", "(", ")", ":", "if", "unit_line", ".", "has_command", "(", "7", ")", ":", "# Attack", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "apply_discrete_effect_ability", "(", "unit_line", ",", "7", ",", "unit_line", ".", "is_ranged", "(", ")", ")", ")", "if", "unit_line", ".", "has_command", "(", "101", ")", ":", "# Build", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "apply_continuous_effect_ability", "(", "unit_line", ",", "101", ",", "unit_line", ".", "is_ranged", "(", ")", ")", ")", "if", "unit_line", ".", "has_command", "(", "104", ")", ":", "# TODO: Success chance is not a resource in RoR", "# Convert", "abilities_set", ".", "append", "(", "RoRAbilitySubprocessor", ".", "apply_discrete_effect_ability", "(", "unit_line", ",", "104", ",", "unit_line", ".", "is_ranged", "(", ")", ")", ")", "if", "unit_line", ".", "has_command", "(", "105", ")", ":", "# Heal", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "apply_continuous_effect_ability", "(", "unit_line", ",", "105", ",", "unit_line", ".", "is_ranged", "(", ")", ")", ")", "if", "unit_line", ".", "has_command", "(", "106", ")", ":", "# Repair", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "apply_continuous_effect_ability", "(", "unit_line", ",", "106", ",", "unit_line", ".", "is_ranged", "(", ")", ")", ")", "# Formation/Stance", "if", "not", "isinstance", "(", "unit_line", ",", "GenieVillagerGroup", ")", ":", "abilities_set", ".", "append", "(", "RoRAbilitySubprocessor", ".", "game_entity_stance_ability", "(", "unit_line", ")", ")", "# Storage abilities", "if", "unit_line", ".", "is_garrison", "(", ")", ":", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "storage_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "remove_storage_ability", "(", "unit_line", ")", ")", "if", "len", "(", "unit_line", ".", "garrison_locations", ")", ">", "0", ":", "ability", "=", "AoCAbilitySubprocessor", ".", "enter_container_ability", "(", "unit_line", ")", "if", "ability", ":", "abilities_set", ".", "append", "(", "ability", ")", "ability", "=", "AoCAbilitySubprocessor", ".", "exit_container_ability", "(", "unit_line", ")", "if", "ability", ":", "abilities_set", ".", "append", "(", "ability", ")", "# Resource abilities", "if", "unit_line", ".", "is_gatherer", "(", ")", ":", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "drop_resources_ability", "(", "unit_line", ")", ")", "abilities_set", ".", "extend", "(", "AoCAbilitySubprocessor", ".", "gather_ability", "(", "unit_line", ")", ")", "# Resource storage", "if", "unit_line", ".", "is_gatherer", "(", ")", "or", "unit_line", ".", "has_command", "(", "111", ")", ":", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "resource_storage_ability", "(", "unit_line", ")", ")", "if", "unit_line", ".", "is_harvestable", "(", ")", ":", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "harvestable_ability", "(", "unit_line", ")", ")", "# Trade abilities", "if", "unit_line", ".", "has_command", "(", "111", ")", ":", "abilities_set", ".", "append", "(", "AoCAbilitySubprocessor", ".", "trade_ability", "(", "unit_line", ")", ")", "raw_api_object", ".", "add_raw_member", "(", "\"abilities\"", ",", "abilities_set", ",", "\"engine.util.game_entity.GameEntity\"", ")", "# =======================================================================", "# Modifiers", "# =======================================================================", "modifiers_set", "=", "[", "]", "if", "unit_line", ".", "is_gatherer", "(", ")", ":", "modifiers_set", ".", "extend", "(", "AoCModifierSubprocessor", ".", "gather_rate_modifier", "(", "unit_line", ")", ")", "# TODO: Other modifiers?", "raw_api_object", ".", "add_raw_member", "(", "\"modifiers\"", ",", "modifiers_set", ",", "\"engine.util.game_entity.GameEntity\"", ")", "# =======================================================================", "# TODO: Variants", "# =======================================================================", "variants_set", "=", "[", "]", "raw_api_object", ".", "add_raw_member", "(", "\"variants\"", ",", "variants_set", ",", "\"engine.util.game_entity.GameEntity\"", ")", "# =======================================================================", "# Misc (Objects that are not used by the unit line itself, but use its values)", "# =======================================================================", "if", "unit_line", ".", "is_creatable", "(", ")", ":", "RoRAuxiliarySubprocessor", ".", "get_creatable_game_entity", "(", "unit_line", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/ror/nyan_subprocessor.py#L158-L339
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/configobj/configobj.py
python
Section.dict
(self)
return newdict
Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() >>> n == a 1 >>> n is a 0
Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() >>> n == a 1 >>> n is a 0
[ "Return", "a", "deepcopy", "of", "self", "as", "a", "dictionary", ".", "All", "members", "that", "are", "Section", "instances", "are", "recursively", "turned", "to", "ordinary", "dictionaries", "-", "by", "calling", "their", "dict", "method", ".", ">>>", "n", "=", "a", ".", "dict", "()", ">>>", "n", "==", "a", "1", ">>>", "n", "is", "a", "0" ]
def dict(self): """ Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() >>> n == a 1 >>> n is a 0 """ newdict = {} for entry in self: this_entry = self[entry] if isinstance(this_entry, Section): this_entry = this_entry.dict() elif isinstance(this_entry, list): # create a copy rather than a reference this_entry = list(this_entry) elif isinstance(this_entry, tuple): # create a copy rather than a reference this_entry = tuple(this_entry) newdict[entry] = this_entry return newdict
[ "def", "dict", "(", "self", ")", ":", "newdict", "=", "{", "}", "for", "entry", "in", "self", ":", "this_entry", "=", "self", "[", "entry", "]", "if", "isinstance", "(", "this_entry", ",", "Section", ")", ":", "this_entry", "=", "this_entry", ".", "dict", "(", ")", "elif", "isinstance", "(", "this_entry", ",", "list", ")", ":", "# create a copy rather than a reference", "this_entry", "=", "list", "(", "this_entry", ")", "elif", "isinstance", "(", "this_entry", ",", "tuple", ")", ":", "# create a copy rather than a reference", "this_entry", "=", "tuple", "(", "this_entry", ")", "newdict", "[", "entry", "]", "=", "this_entry", "return", "newdict" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/configobj/configobj.py#L770-L795
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
AnyButton.SetBitmapMargins
(*args)
return _controls_.AnyButton_SetBitmapMargins(*args)
SetBitmapMargins(self, int x, int y) SetBitmapMargins(self, Size sz)
SetBitmapMargins(self, int x, int y) SetBitmapMargins(self, Size sz)
[ "SetBitmapMargins", "(", "self", "int", "x", "int", "y", ")", "SetBitmapMargins", "(", "self", "Size", "sz", ")" ]
def SetBitmapMargins(*args): """ SetBitmapMargins(self, int x, int y) SetBitmapMargins(self, Size sz) """ return _controls_.AnyButton_SetBitmapMargins(*args)
[ "def", "SetBitmapMargins", "(", "*", "args", ")", ":", "return", "_controls_", ".", "AnyButton_SetBitmapMargins", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L143-L148
facebook/ThreatExchange
31914a51820c73c8a0daffe62ccca29a6e3d359e
python-threatexchange/threatexchange/signal_type/pdq_index.py
python
PDQIndex.query
(self, hash: str)
return matches
Look up entries against the index, up to the max supported distance.
Look up entries against the index, up to the max supported distance.
[ "Look", "up", "entries", "against", "the", "index", "up", "to", "the", "max", "supported", "distance", "." ]
def query(self, hash: str) -> t.List[IndexMatch[IndexT]]: """ Look up entries against the index, up to the max supported distance. """ # query takes a signal hash but index supports batch queries hence [hash] results = self.index.search_with_distance_in_result( [hash], self.get_match_threshold() ) matches = [] for id, _, distance in results[hash]: matches.append(IndexMatch(distance, self.local_id_to_entry[id][1])) return matches
[ "def", "query", "(", "self", ",", "hash", ":", "str", ")", "->", "t", ".", "List", "[", "IndexMatch", "[", "IndexT", "]", "]", ":", "# query takes a signal hash but index supports batch queries hence [hash]", "results", "=", "self", ".", "index", ".", "search_with_distance_in_result", "(", "[", "hash", "]", ",", "self", ".", "get_match_threshold", "(", ")", ")", "matches", "=", "[", "]", "for", "id", ",", "_", ",", "distance", "in", "results", "[", "hash", "]", ":", "matches", ".", "append", "(", "IndexMatch", "(", "distance", ",", "self", ".", "local_id_to_entry", "[", "id", "]", "[", "1", "]", ")", ")", "return", "matches" ]
https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/signal_type/pdq_index.py#L43-L56
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py
python
FieldMask.ToJsonString
(self)
return ','.join(camelcase_paths)
Converts FieldMask to string according to proto3 JSON spec.
Converts FieldMask to string according to proto3 JSON spec.
[ "Converts", "FieldMask", "to", "string", "according", "to", "proto3", "JSON", "spec", "." ]
def ToJsonString(self): """Converts FieldMask to string according to proto3 JSON spec.""" camelcase_paths = [] for path in self.paths: camelcase_paths.append(_SnakeCaseToCamelCase(path)) return ','.join(camelcase_paths)
[ "def", "ToJsonString", "(", "self", ")", ":", "camelcase_paths", "=", "[", "]", "for", "path", "in", "self", ".", "paths", ":", "camelcase_paths", ".", "append", "(", "_SnakeCaseToCamelCase", "(", "path", ")", ")", "return", "','", ".", "join", "(", "camelcase_paths", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L396-L401
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
scripts/cpp_lint.py
python
GetLineWidth
(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "." ]
def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line)
[ "def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_width", "(", "uc", ")", "in", "(", "'W'", ",", "'F'", ")", ":", "width", "+=", "2", "elif", "not", "unicodedata", ".", "combining", "(", "uc", ")", ":", "width", "+=", "1", "return", "width", "else", ":", "return", "len", "(", "line", ")" ]
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L3437-L3456
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/feature_column.py
python
_is_running_on_cpu
()
return tpu_function.get_tpu_context().number_of_shards is None
Returns True if the current context is CPU model.
Returns True if the current context is CPU model.
[ "Returns", "True", "if", "the", "current", "context", "is", "CPU", "model", "." ]
def _is_running_on_cpu(): """Returns True if the current context is CPU model.""" return tpu_function.get_tpu_context().number_of_shards is None
[ "def", "_is_running_on_cpu", "(", ")", ":", "return", "tpu_function", ".", "get_tpu_context", "(", ")", ".", "number_of_shards", "is", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/feature_column.py#L618-L620
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/externals/joblib/memory.py
python
Memory.eval
(self, func, *args, **kwargs)
return self.cache(func)(*args, **kwargs)
Eval function func with arguments `*args` and `**kwargs`, in the context of the memory. This method works similarly to the builtin `apply`, except that the function is called only if the cache is not up to date.
Eval function func with arguments `*args` and `**kwargs`, in the context of the memory.
[ "Eval", "function", "func", "with", "arguments", "*", "args", "and", "**", "kwargs", "in", "the", "context", "of", "the", "memory", "." ]
def eval(self, func, *args, **kwargs): """ Eval function func with arguments `*args` and `**kwargs`, in the context of the memory. This method works similarly to the builtin `apply`, except that the function is called only if the cache is not up to date. """ if self.cachedir is None: return func(*args, **kwargs) return self.cache(func)(*args, **kwargs)
[ "def", "eval", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "cachedir", "is", "None", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "cache", "(", "func", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/joblib/memory.py#L887-L898
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_shgo.py
python
SHGO.surface_topo_ref
(self)
Find the BD and FD finite differences along each component vector.
Find the BD and FD finite differences along each component vector.
[ "Find", "the", "BD", "and", "FD", "finite", "differences", "along", "each", "component", "vector", "." ]
def surface_topo_ref(self): # Validated """ Find the BD and FD finite differences along each component vector. """ # Replace numpy inf, -inf and nan objects with floating point numbers # nan --> float self.F[np.isnan(self.F)] = np.inf # inf, -inf --> floats self.F = np.nan_to_num(self.F) self.Ft = self.F[self.Ind_sorted] self.Ftp = np.diff(self.Ft, axis=0) # FD self.Ftm = np.diff(self.Ft[::-1], axis=0)[::-1]
[ "def", "surface_topo_ref", "(", "self", ")", ":", "# Validated", "# Replace numpy inf, -inf and nan objects with floating point numbers", "# nan --> float", "self", ".", "F", "[", "np", ".", "isnan", "(", "self", ".", "F", ")", "]", "=", "np", ".", "inf", "# inf, -inf --> floats", "self", ".", "F", "=", "np", ".", "nan_to_num", "(", "self", ".", "F", ")", "self", ".", "Ft", "=", "self", ".", "F", "[", "self", ".", "Ind_sorted", "]", "self", ".", "Ftp", "=", "np", ".", "diff", "(", "self", ".", "Ft", ",", "axis", "=", "0", ")", "# FD", "self", ".", "Ftm", "=", "np", ".", "diff", "(", "self", ".", "Ft", "[", ":", ":", "-", "1", "]", ",", "axis", "=", "0", ")", "[", ":", ":", "-", "1", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_shgo.py#L1444-L1456
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_endpoints.py
python
Terminus.capabilities
(self)
return Data(pn_terminus_capabilities(self._impl))
Capabilities of the source or target. :type: :class:`Data` containing an array of :class:`symbol`.
Capabilities of the source or target.
[ "Capabilities", "of", "the", "source", "or", "target", "." ]
def capabilities(self): """ Capabilities of the source or target. :type: :class:`Data` containing an array of :class:`symbol`. """ return Data(pn_terminus_capabilities(self._impl))
[ "def", "capabilities", "(", "self", ")", ":", "return", "Data", "(", "pn_terminus_capabilities", "(", "self", ".", "_impl", ")", ")" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_endpoints.py#L1405-L1411
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftviewproviders/view_dimension.py
python
ViewProviderLinearDimension.is_linked_to_circle
(self)
return False
Return true if the dimension measures a circular edge.
Return true if the dimension measures a circular edge.
[ "Return", "true", "if", "the", "dimension", "measures", "a", "circular", "edge", "." ]
def is_linked_to_circle(self): """Return true if the dimension measures a circular edge.""" obj = self.Object if obj.LinkedGeometry and len(obj.LinkedGeometry) == 1: linked_obj = obj.LinkedGeometry[0][0] subelements = obj.LinkedGeometry[0][1] if len(subelements) == 1 and "Edge" in subelements[0]: sub = subelements[0] index = int(sub[4:]) - 1 edge = linked_obj.Shape.Edges[index] if DraftGeomUtils.geomType(edge) == "Circle": return True return False
[ "def", "is_linked_to_circle", "(", "self", ")", ":", "obj", "=", "self", ".", "Object", "if", "obj", ".", "LinkedGeometry", "and", "len", "(", "obj", ".", "LinkedGeometry", ")", "==", "1", ":", "linked_obj", "=", "obj", ".", "LinkedGeometry", "[", "0", "]", "[", "0", "]", "subelements", "=", "obj", ".", "LinkedGeometry", "[", "0", "]", "[", "1", "]", "if", "len", "(", "subelements", ")", "==", "1", "and", "\"Edge\"", "in", "subelements", "[", "0", "]", ":", "sub", "=", "subelements", "[", "0", "]", "index", "=", "int", "(", "sub", "[", "4", ":", "]", ")", "-", "1", "edge", "=", "linked_obj", ".", "Shape", ".", "Edges", "[", "index", "]", "if", "DraftGeomUtils", ".", "geomType", "(", "edge", ")", "==", "\"Circle\"", ":", "return", "True", "return", "False" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftviewproviders/view_dimension.py#L884-L896
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py
python
PlatformDetail.__init__
(self, platform, enabled, has_server, has_tests, is_monolithic_value, output_folder, aliases, attributes, needs_java, platform_env_dict)
Initialize :param platform: The base name of this platform. (The concrete platform name may be extended with a server suffix if the right options are set) :param enabled: Flag: Is this platform enabled or not :param has_server: Flag: Are server platforms/configurations supported at all :param has_tests: Flag: Does this platform support test configurations? :param is_monolithic_value: Flag: Is this a monolithic platform? (or a list of configurations to force monolithic builds on that configuration.) :param output_folder: The output folder base name that is used as the base for each of the platform configurations output folder :param aliases: Optional aliases to add this platform to :param attributes: Optional platform/specific attributes needed for custom platform processing :param needs_java: Flag to indicate if we need java to be loaded (the javaw module) :param platform_env_dict: Optional env map to apply to the env for this platform during configure
Initialize
[ "Initialize" ]
def __init__(self, platform, enabled, has_server, has_tests, is_monolithic_value, output_folder, aliases, attributes, needs_java, platform_env_dict): """ Initialize :param platform: The base name of this platform. (The concrete platform name may be extended with a server suffix if the right options are set) :param enabled: Flag: Is this platform enabled or not :param has_server: Flag: Are server platforms/configurations supported at all :param has_tests: Flag: Does this platform support test configurations? :param is_monolithic_value: Flag: Is this a monolithic platform? (or a list of configurations to force monolithic builds on that configuration.) :param output_folder: The output folder base name that is used as the base for each of the platform configurations output folder :param aliases: Optional aliases to add this platform to :param attributes: Optional platform/specific attributes needed for custom platform processing :param needs_java: Flag to indicate if we need java to be loaded (the javaw module) :param platform_env_dict: Optional env map to apply to the env for this platform during configure """ self.platform = platform self.enabled = enabled self.has_server = has_server self.has_tests = has_tests # Handle the fact that 'is_monolithic' can be represented in multiple ways if not isinstance(is_monolithic_value, bool) and not isinstance(is_monolithic_value, list) and not isinstance(is_monolithic_value, str): raise Errors.WafError("Invalid settings value type for 'is_platform' for platform '{}'. Expected a boolean, string, or list of strings") if isinstance(is_monolithic_value, str): self.is_monolithic = [is_monolithic_value] else: self.is_monolithic = is_monolithic_value self.output_folder = output_folder self.aliases = aliases self.attributes = attributes self.needs_java = needs_java self.platform_env_dict = platform_env_dict # Initialize all the platform configurations based on the parameters and settings self.platform_configs = {} for config_settings in settings_manager.LUMBERYARD_SETTINGS.get_build_configuration_settings(): # Determine if the configuration is monolithic or not if isinstance(self.is_monolithic, bool): # The 'is_monolithic' flag was set to a boolean value in the platform's configuration file if self.is_monolithic: # The 'is_monolithic' flag was set to True, then set (override) all configurations to be monolithic is_config_monolithic = True else: # The 'is_monolithic' flag was set to False, then use the default configuration specific setting to # control whether its monolithic or not. We will never override 'performance' or 'release' monolithic # settings is_config_monolithic = config_settings.is_monolithic elif isinstance(self.is_monolithic, list): # Special case: If the 'is_monolithic' is a list, then evaluate based on the contents of the list if len(self.is_monolithic) > 0: # If there is at least one configuration specified in the list, then match the current config to any of the # configurations to determine if its monolithic or not. This mechanism can only enable configurations # that by default are non-monolithic. If the default value is monolithic, it cannot be turned off is_config_monolithic = config_settings.name in self.is_monolithic or config_settings.is_monolithic else: # If the list is empty, then that implies we do not override any of the default configuration's # monolithic flag (same behavior as setting 'is_monolithic' to False is_config_monolithic = config_settings.is_monolithic else: raise Errors.WafError("Invalid type for 'is_monolithic' in platform settings for {}".format(platform)) # Add the base configuration base_config = PlatformConfiguration(platform=self, settings=config_settings, platform_output_folder=output_folder, is_test=False, is_server=False, is_monolithic=is_config_monolithic) self.platform_configs[base_config.config_name()] = base_config if has_server and ENABLE_SERVER: # Add the optional server configuration if available(has_server) and enabled(enable_server) non_test_server_config = PlatformConfiguration(platform=self, settings=config_settings, platform_output_folder=output_folder, is_test=False, is_server=True, is_monolithic=is_config_monolithic) self.platform_configs[non_test_server_config.config_name()] = non_test_server_config if self.has_tests and config_settings.has_test and ENABLE_TEST_CONFIGURATIONS: # Add the optional test configuration(s) if available (config_detail.has_test) and enabled (enable_test_configurations) test_non_server_config = PlatformConfiguration(platform=self, settings=config_settings, platform_output_folder=output_folder, is_test=True, is_server=False, is_monolithic=is_config_monolithic) self.platform_configs[test_non_server_config.config_name()] = test_non_server_config if has_server and ENABLE_SERVER: # Add the optional server configuration if available(has_server) and enabled(enable_server) test_server_config = PlatformConfiguration(platform=self, settings=config_settings, platform_output_folder=output_folder, is_test=True, is_server=True, is_monolithic=is_config_monolithic) self.platform_configs[test_server_config.config_name()] = test_server_config # Check if there is a 3rd party platform alias override, otherwise use the platform name config_third_party_platform_alias = self.attributes.get('third_party_alias_platform', None) if config_third_party_platform_alias: try: settings_manager.LUMBERYARD_SETTINGS.get_platform_settings(config_third_party_platform_alias) except Errors.WafError: raise Errors.WafError("Invalid 'third_party_alias_platform' attribute ({}) for platform {}".format(config_third_party_platform_alias, platform)) self.third_party_platform_key = config_third_party_platform_alias else: self.third_party_platform_key = platform
[ "def", "__init__", "(", "self", ",", "platform", ",", "enabled", ",", "has_server", ",", "has_tests", ",", "is_monolithic_value", ",", "output_folder", ",", "aliases", ",", "attributes", ",", "needs_java", ",", "platform_env_dict", ")", ":", "self", ".", "platform", "=", "platform", "self", ".", "enabled", "=", "enabled", "self", ".", "has_server", "=", "has_server", "self", ".", "has_tests", "=", "has_tests", "# Handle the fact that 'is_monolithic' can be represented in multiple ways", "if", "not", "isinstance", "(", "is_monolithic_value", ",", "bool", ")", "and", "not", "isinstance", "(", "is_monolithic_value", ",", "list", ")", "and", "not", "isinstance", "(", "is_monolithic_value", ",", "str", ")", ":", "raise", "Errors", ".", "WafError", "(", "\"Invalid settings value type for 'is_platform' for platform '{}'. Expected a boolean, string, or list of strings\"", ")", "if", "isinstance", "(", "is_monolithic_value", ",", "str", ")", ":", "self", ".", "is_monolithic", "=", "[", "is_monolithic_value", "]", "else", ":", "self", ".", "is_monolithic", "=", "is_monolithic_value", "self", ".", "output_folder", "=", "output_folder", "self", ".", "aliases", "=", "aliases", "self", ".", "attributes", "=", "attributes", "self", ".", "needs_java", "=", "needs_java", "self", ".", "platform_env_dict", "=", "platform_env_dict", "# Initialize all the platform configurations based on the parameters and settings", "self", ".", "platform_configs", "=", "{", "}", "for", "config_settings", "in", "settings_manager", ".", "LUMBERYARD_SETTINGS", ".", "get_build_configuration_settings", "(", ")", ":", "# Determine if the configuration is monolithic or not", "if", "isinstance", "(", "self", ".", "is_monolithic", ",", "bool", ")", ":", "# The 'is_monolithic' flag was set to a boolean value in the platform's configuration file", "if", "self", ".", "is_monolithic", ":", "# The 'is_monolithic' flag was set to True, then set (override) all configurations to be monolithic", "is_config_monolithic", "=", "True", "else", ":", "# The 'is_monolithic' flag was set to False, then use the default configuration specific setting to", "# control whether its monolithic or not. We will never override 'performance' or 'release' monolithic", "# settings", "is_config_monolithic", "=", "config_settings", ".", "is_monolithic", "elif", "isinstance", "(", "self", ".", "is_monolithic", ",", "list", ")", ":", "# Special case: If the 'is_monolithic' is a list, then evaluate based on the contents of the list", "if", "len", "(", "self", ".", "is_monolithic", ")", ">", "0", ":", "# If there is at least one configuration specified in the list, then match the current config to any of the", "# configurations to determine if its monolithic or not. This mechanism can only enable configurations", "# that by default are non-monolithic. If the default value is monolithic, it cannot be turned off", "is_config_monolithic", "=", "config_settings", ".", "name", "in", "self", ".", "is_monolithic", "or", "config_settings", ".", "is_monolithic", "else", ":", "# If the list is empty, then that implies we do not override any of the default configuration's", "# monolithic flag (same behavior as setting 'is_monolithic' to False", "is_config_monolithic", "=", "config_settings", ".", "is_monolithic", "else", ":", "raise", "Errors", ".", "WafError", "(", "\"Invalid type for 'is_monolithic' in platform settings for {}\"", ".", "format", "(", "platform", ")", ")", "# Add the base configuration", "base_config", "=", "PlatformConfiguration", "(", "platform", "=", "self", ",", "settings", "=", "config_settings", ",", "platform_output_folder", "=", "output_folder", ",", "is_test", "=", "False", ",", "is_server", "=", "False", ",", "is_monolithic", "=", "is_config_monolithic", ")", "self", ".", "platform_configs", "[", "base_config", ".", "config_name", "(", ")", "]", "=", "base_config", "if", "has_server", "and", "ENABLE_SERVER", ":", "# Add the optional server configuration if available(has_server) and enabled(enable_server)", "non_test_server_config", "=", "PlatformConfiguration", "(", "platform", "=", "self", ",", "settings", "=", "config_settings", ",", "platform_output_folder", "=", "output_folder", ",", "is_test", "=", "False", ",", "is_server", "=", "True", ",", "is_monolithic", "=", "is_config_monolithic", ")", "self", ".", "platform_configs", "[", "non_test_server_config", ".", "config_name", "(", ")", "]", "=", "non_test_server_config", "if", "self", ".", "has_tests", "and", "config_settings", ".", "has_test", "and", "ENABLE_TEST_CONFIGURATIONS", ":", "# Add the optional test configuration(s) if available (config_detail.has_test) and enabled (enable_test_configurations)", "test_non_server_config", "=", "PlatformConfiguration", "(", "platform", "=", "self", ",", "settings", "=", "config_settings", ",", "platform_output_folder", "=", "output_folder", ",", "is_test", "=", "True", ",", "is_server", "=", "False", ",", "is_monolithic", "=", "is_config_monolithic", ")", "self", ".", "platform_configs", "[", "test_non_server_config", ".", "config_name", "(", ")", "]", "=", "test_non_server_config", "if", "has_server", "and", "ENABLE_SERVER", ":", "# Add the optional server configuration if available(has_server) and enabled(enable_server)", "test_server_config", "=", "PlatformConfiguration", "(", "platform", "=", "self", ",", "settings", "=", "config_settings", ",", "platform_output_folder", "=", "output_folder", ",", "is_test", "=", "True", ",", "is_server", "=", "True", ",", "is_monolithic", "=", "is_config_monolithic", ")", "self", ".", "platform_configs", "[", "test_server_config", ".", "config_name", "(", ")", "]", "=", "test_server_config", "# Check if there is a 3rd party platform alias override, otherwise use the platform name", "config_third_party_platform_alias", "=", "self", ".", "attributes", ".", "get", "(", "'third_party_alias_platform'", ",", "None", ")", "if", "config_third_party_platform_alias", ":", "try", ":", "settings_manager", ".", "LUMBERYARD_SETTINGS", ".", "get_platform_settings", "(", "config_third_party_platform_alias", ")", "except", "Errors", ".", "WafError", ":", "raise", "Errors", ".", "WafError", "(", "\"Invalid 'third_party_alias_platform' attribute ({}) for platform {}\"", ".", "format", "(", "config_third_party_platform_alias", ",", "platform", ")", ")", "self", ".", "third_party_platform_key", "=", "config_third_party_platform_alias", "else", ":", "self", ".", "third_party_platform_key", "=", "platform" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py#L131-L243
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Canvas.create_text
(self, *args, **kw)
return self._create('text', args, kw)
Create text with coordinates x1,y1.
Create text with coordinates x1,y1.
[ "Create", "text", "with", "coordinates", "x1", "y1", "." ]
def create_text(self, *args, **kw): """Create text with coordinates x1,y1.""" return self._create('text', args, kw)
[ "def", "create_text", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "_create", "(", "'text'", ",", "args", ",", "kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L2502-L2504
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/python/cp_model.py
python
CpModel.AddNoOverlap
(self, interval_vars)
return ct
Adds NoOverlap(interval_vars). A NoOverlap constraint ensures that all present intervals do not overlap in time. Args: interval_vars: The list of interval variables to constrain. Returns: An instance of the `Constraint` class.
Adds NoOverlap(interval_vars).
[ "Adds", "NoOverlap", "(", "interval_vars", ")", "." ]
def AddNoOverlap(self, interval_vars): """Adds NoOverlap(interval_vars). A NoOverlap constraint ensures that all present intervals do not overlap in time. Args: interval_vars: The list of interval variables to constrain. Returns: An instance of the `Constraint` class. """ ct = Constraint(self.__model.constraints) model_ct = self.__model.constraints[ct.Index()] model_ct.no_overlap.intervals.extend( [self.GetIntervalIndex(x) for x in interval_vars]) return ct
[ "def", "AddNoOverlap", "(", "self", ",", "interval_vars", ")", ":", "ct", "=", "Constraint", "(", "self", ".", "__model", ".", "constraints", ")", "model_ct", "=", "self", ".", "__model", ".", "constraints", "[", "ct", ".", "Index", "(", ")", "]", "model_ct", ".", "no_overlap", ".", "intervals", ".", "extend", "(", "[", "self", ".", "GetIntervalIndex", "(", "x", ")", "for", "x", "in", "interval_vars", "]", ")", "return", "ct" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1686-L1702
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/reduction_workflow/command_interface.py
python
ClearDataFiles
()
Empty the list of data files to be processed while keeping all other reduction options.
Empty the list of data files to be processed while keeping all other reduction options.
[ "Empty", "the", "list", "of", "data", "files", "to", "be", "processed", "while", "keeping", "all", "other", "reduction", "options", "." ]
def ClearDataFiles(): """ Empty the list of data files to be processed while keeping all other reduction options. """ ReductionSingleton().clear_data_files()
[ "def", "ClearDataFiles", "(", ")", ":", "ReductionSingleton", "(", ")", ".", "clear_data_files", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_workflow/command_interface.py#L113-L118
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/xml/etree/ElementTree.py
python
ElementTree._setroot
(self, element)
Replace root element of this tree. This will discard the current contents of the tree and replace it with the given element. Use with care!
Replace root element of this tree.
[ "Replace", "root", "element", "of", "this", "tree", "." ]
def _setroot(self, element): """Replace root element of this tree. This will discard the current contents of the tree and replace it with the given element. Use with care! """ # assert iselement(element) self._root = element
[ "def", "_setroot", "(", "self", ",", "element", ")", ":", "# assert iselement(element)", "self", ".", "_root", "=", "element" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/etree/ElementTree.py#L546-L554
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/filter_design.py
python
buttap
(N)
return z, p, k
Return (z,p,k) for analog prototype of Nth-order Butterworth filter. The filter will have an angular (e.g. rad/s) cutoff frequency of 1. See Also -------- butter : Filter design function using this prototype
Return (z,p,k) for analog prototype of Nth-order Butterworth filter.
[ "Return", "(", "z", "p", "k", ")", "for", "analog", "prototype", "of", "Nth", "-", "order", "Butterworth", "filter", "." ]
def buttap(N): """Return (z,p,k) for analog prototype of Nth-order Butterworth filter. The filter will have an angular (e.g. rad/s) cutoff frequency of 1. See Also -------- butter : Filter design function using this prototype """ if abs(int(N)) != N: raise ValueError("Filter order must be a nonnegative integer") z = numpy.array([]) m = numpy.arange(-N+1, N, 2) # Middle value is 0 to ensure an exactly real pole p = -numpy.exp(1j * pi * m / (2 * N)) k = 1 return z, p, k
[ "def", "buttap", "(", "N", ")", ":", "if", "abs", "(", "int", "(", "N", ")", ")", "!=", "N", ":", "raise", "ValueError", "(", "\"Filter order must be a nonnegative integer\"", ")", "z", "=", "numpy", ".", "array", "(", "[", "]", ")", "m", "=", "numpy", ".", "arange", "(", "-", "N", "+", "1", ",", "N", ",", "2", ")", "# Middle value is 0 to ensure an exactly real pole", "p", "=", "-", "numpy", ".", "exp", "(", "1j", "*", "pi", "*", "m", "/", "(", "2", "*", "N", ")", ")", "k", "=", "1", "return", "z", ",", "p", ",", "k" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/filter_design.py#L3778-L3795
regomne/chinesize
2ae555445046cd28d60a514e30ac1d6eca1c442a
N2System/nsbparser/nsbParser.py
python
NsbParser.pa5
(self)
加法
加法
[ "加法" ]
def pa5(self): '加法' var1=self.stack.pop() self.stack.append('('+self.stack.pop()+' + '+var1+')')
[ "def", "pa5", "(", "self", ")", ":", "var1", "=", "self", ".", "stack", ".", "pop", "(", ")", "self", ".", "stack", ".", "append", "(", "'('", "+", "self", ".", "stack", ".", "pop", "(", ")", "+", "' + '", "+", "var1", "+", "')'", ")" ]
https://github.com/regomne/chinesize/blob/2ae555445046cd28d60a514e30ac1d6eca1c442a/N2System/nsbparser/nsbParser.py#L118-L121
apache/incubator-weex
5c25f0b59f7ac90703c363e7261f60bd06356dbe
weex_core/tools/cpplint.py
python
_AddFilters
(filters)
Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Adds more filter overrides.
[ "Adds", "more", "filter", "overrides", "." ]
def _AddFilters(filters): """Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.AddFilters(filters)
[ "def", "_AddFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "AddFilters", "(", "filters", ")" ]
https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/tools/cpplint.py#L1013-L1023
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/distutils/config.py
python
PyPIRCCommand._store_pypirc
(self, username, password)
Creates a default .pypirc file.
Creates a default .pypirc file.
[ "Creates", "a", "default", ".", "pypirc", "file", "." ]
def _store_pypirc(self, username, password): """Creates a default .pypirc file.""" rc = self._get_rc_file() with os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f: f.write(DEFAULT_PYPIRC % (username, password))
[ "def", "_store_pypirc", "(", "self", ",", "username", ",", "password", ")", ":", "rc", "=", "self", ".", "_get_rc_file", "(", ")", "with", "os", ".", "fdopen", "(", "os", ".", "open", "(", "rc", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_WRONLY", ",", "0o600", ")", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "DEFAULT_PYPIRC", "%", "(", "username", ",", "password", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/config.py#L42-L46
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/toolchain/win/setup_toolchain.py
python
_DetectVisualStudioPath
()
return vs_toolchain.DetectVisualStudioPath()
Return path to the installed Visual Studio.
Return path to the installed Visual Studio.
[ "Return", "path", "to", "the", "installed", "Visual", "Studio", "." ]
def _DetectVisualStudioPath(): """Return path to the installed Visual Studio. """ # Use the code in build/vs_toolchain.py to avoid duplicating code. chromium_dir = os.path.abspath(os.path.join(SCRIPT_DIR, '..', '..', '..')) sys.path.append(os.path.join(chromium_dir, 'build')) import vs_toolchain return vs_toolchain.DetectVisualStudioPath()
[ "def", "_DetectVisualStudioPath", "(", ")", ":", "# Use the code in build/vs_toolchain.py to avoid duplicating code.", "chromium_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "SCRIPT_DIR", ",", "'..'", ",", "'..'", ",", "'..'", ")", ")", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "chromium_dir", ",", "'build'", ")", ")", "import", "vs_toolchain", "return", "vs_toolchain", ".", "DetectVisualStudioPath", "(", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/toolchain/win/setup_toolchain.py#L71-L79
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/contrib/onnx/mx2onnx/_op_translations.py
python
convert_expand_dims
(node, **kwargs)
return [node]
Map MXNet's expand_dims operator attributes to onnx's Unsqueeze operator and return the created node.
Map MXNet's expand_dims operator attributes to onnx's Unsqueeze operator and return the created node.
[ "Map", "MXNet", "s", "expand_dims", "operator", "attributes", "to", "onnx", "s", "Unsqueeze", "operator", "and", "return", "the", "created", "node", "." ]
def convert_expand_dims(node, **kwargs): """Map MXNet's expand_dims operator attributes to onnx's Unsqueeze operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) axis = int(attrs.get("axis")) node = onnx.helper.make_node( "Unsqueeze", input_nodes, [name], axes=[axis], name=name, ) return [node]
[ "def", "convert_expand_dims", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "axis", "=", "int", "(", "attrs", ".", "get", "(", "\"axis\"", ")", ")", "node", "=", "onnx", ".", "helper", ".", "make_node", "(", "\"Unsqueeze\"", ",", "input_nodes", ",", "[", "name", "]", ",", "axes", "=", "[", "axis", "]", ",", "name", "=", "name", ",", ")", "return", "[", "node", "]" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L1557-L1572
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/distutils/fcompiler/__init__.py
python
FCompiler.update_executables
(elf)
Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary. Note that self.find_executables() is run afterwards, so the self.executables dictionary values can contain <F77> or <F90> as the command, which will be replaced by the found F77 or F90 compiler.
Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary.
[ "Called", "at", "the", "beginning", "of", "customisation", ".", "Subclasses", "should", "override", "this", "if", "they", "need", "to", "set", "up", "the", "executables", "dictionary", "." ]
def update_executables(elf): """Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary. Note that self.find_executables() is run afterwards, so the self.executables dictionary values can contain <F77> or <F90> as the command, which will be replaced by the found F77 or F90 compiler. """ pass
[ "def", "update_executables", "(", "elf", ")", ":", "pass" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/fcompiler/__init__.py#L362-L371
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
cnn_sphere_register/ext/neuron/neuron/plot.py
python
slices
(slices_in, # the 2D slices titles=None, # list of titles cmaps=None, # list of colormaps norms=None, # list of normalizations do_colorbars=False, # option to show colorbars on each slice grid=False, # option to plot the images in a grid or a single row width=15, # width in in show=True, # option to actually show the plot (plt.show()) imshow_args=None)
return (fig, axs)
plot a grid of slices (2d images)
plot a grid of slices (2d images)
[ "plot", "a", "grid", "of", "slices", "(", "2d", "images", ")" ]
def slices(slices_in, # the 2D slices titles=None, # list of titles cmaps=None, # list of colormaps norms=None, # list of normalizations do_colorbars=False, # option to show colorbars on each slice grid=False, # option to plot the images in a grid or a single row width=15, # width in in show=True, # option to actually show the plot (plt.show()) imshow_args=None): ''' plot a grid of slices (2d images) ''' # input processing nb_plots = len(slices_in) def input_check(inputs, nb_plots, name): ''' change input from None/single-link ''' assert (inputs is None) or (len(inputs) == nb_plots) or (len(inputs) == 1), \ 'number of %s is incorrect' % name if inputs is None: inputs = [None] if len(inputs) == 1: inputs = [inputs[0] for i in range(nb_plots)] return inputs titles = input_check(titles, nb_plots, 'titles') cmaps = input_check(cmaps, nb_plots, 'cmaps') norms = input_check(norms, nb_plots, 'norms') imshow_args = input_check(imshow_args, nb_plots, 'imshow_args') for idx, ia in enumerate(imshow_args): imshow_args[idx] = {} if ia is None else ia # figure out the number of rows and columns if grid: if isinstance(grid, bool): rows = np.floor(np.sqrt(nb_plots)).astype(int) cols = np.ceil(nb_plots/rows).astype(int) else: assert isinstance(grid, (list, tuple)), \ "grid should either be bool or [rows,cols]" rows, cols = grid else: rows = 1 cols = nb_plots # prepare the subplot fig, axs = plt.subplots(rows, cols) if rows == 1 and cols == 1: axs = [axs] for i in range(nb_plots): col = np.remainder(i, cols) row = np.floor(i/cols).astype(int) # get row and column axes row_axs = axs if rows == 1 else axs[row] ax = row_axs[col] # turn off axis ax.axis('off') # some cleanup if titles is not None: ax.title.set_text(titles[i]) # show figure im_ax = ax.imshow(slices_in[i], cmap=cmaps[i], interpolation="nearest", norm=norms[i], **imshow_args[i]) # colorbars # http://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph if do_colorbars and cmaps[i] is not None: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) fig.colorbar(im_ax, cax=cax) # show the plots fig.set_size_inches(width, rows/cols*width) plt.tight_layout() if show: plt.show() return (fig, axs)
[ "def", "slices", "(", "slices_in", ",", "# the 2D slices", "titles", "=", "None", ",", "# list of titles", "cmaps", "=", "None", ",", "# list of colormaps", "norms", "=", "None", ",", "# list of normalizations", "do_colorbars", "=", "False", ",", "# option to show colorbars on each slice", "grid", "=", "False", ",", "# option to plot the images in a grid or a single row", "width", "=", "15", ",", "# width in in", "show", "=", "True", ",", "# option to actually show the plot (plt.show())", "imshow_args", "=", "None", ")", ":", "# input processing", "nb_plots", "=", "len", "(", "slices_in", ")", "def", "input_check", "(", "inputs", ",", "nb_plots", ",", "name", ")", ":", "''' change input from None/single-link '''", "assert", "(", "inputs", "is", "None", ")", "or", "(", "len", "(", "inputs", ")", "==", "nb_plots", ")", "or", "(", "len", "(", "inputs", ")", "==", "1", ")", ",", "'number of %s is incorrect'", "%", "name", "if", "inputs", "is", "None", ":", "inputs", "=", "[", "None", "]", "if", "len", "(", "inputs", ")", "==", "1", ":", "inputs", "=", "[", "inputs", "[", "0", "]", "for", "i", "in", "range", "(", "nb_plots", ")", "]", "return", "inputs", "titles", "=", "input_check", "(", "titles", ",", "nb_plots", ",", "'titles'", ")", "cmaps", "=", "input_check", "(", "cmaps", ",", "nb_plots", ",", "'cmaps'", ")", "norms", "=", "input_check", "(", "norms", ",", "nb_plots", ",", "'norms'", ")", "imshow_args", "=", "input_check", "(", "imshow_args", ",", "nb_plots", ",", "'imshow_args'", ")", "for", "idx", ",", "ia", "in", "enumerate", "(", "imshow_args", ")", ":", "imshow_args", "[", "idx", "]", "=", "{", "}", "if", "ia", "is", "None", "else", "ia", "# figure out the number of rows and columns", "if", "grid", ":", "if", "isinstance", "(", "grid", ",", "bool", ")", ":", "rows", "=", "np", ".", "floor", "(", "np", ".", "sqrt", "(", "nb_plots", ")", ")", ".", "astype", "(", "int", ")", "cols", "=", "np", ".", "ceil", "(", "nb_plots", "/", "rows", ")", ".", "astype", "(", "int", ")", "else", ":", "assert", "isinstance", "(", "grid", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"grid should either be bool or [rows,cols]\"", "rows", ",", "cols", "=", "grid", "else", ":", "rows", "=", "1", "cols", "=", "nb_plots", "# prepare the subplot", "fig", ",", "axs", "=", "plt", ".", "subplots", "(", "rows", ",", "cols", ")", "if", "rows", "==", "1", "and", "cols", "==", "1", ":", "axs", "=", "[", "axs", "]", "for", "i", "in", "range", "(", "nb_plots", ")", ":", "col", "=", "np", ".", "remainder", "(", "i", ",", "cols", ")", "row", "=", "np", ".", "floor", "(", "i", "/", "cols", ")", ".", "astype", "(", "int", ")", "# get row and column axes", "row_axs", "=", "axs", "if", "rows", "==", "1", "else", "axs", "[", "row", "]", "ax", "=", "row_axs", "[", "col", "]", "# turn off axis", "ax", ".", "axis", "(", "'off'", ")", "# some cleanup", "if", "titles", "is", "not", "None", ":", "ax", ".", "title", ".", "set_text", "(", "titles", "[", "i", "]", ")", "# show figure", "im_ax", "=", "ax", ".", "imshow", "(", "slices_in", "[", "i", "]", ",", "cmap", "=", "cmaps", "[", "i", "]", ",", "interpolation", "=", "\"nearest\"", ",", "norm", "=", "norms", "[", "i", "]", ",", "*", "*", "imshow_args", "[", "i", "]", ")", "# colorbars", "# http://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph", "if", "do_colorbars", "and", "cmaps", "[", "i", "]", "is", "not", "None", ":", "divider", "=", "make_axes_locatable", "(", "ax", ")", "cax", "=", "divider", ".", "append_axes", "(", "\"right\"", ",", "size", "=", "\"5%\"", ",", "pad", "=", "0.05", ")", "fig", ".", "colorbar", "(", "im_ax", ",", "cax", "=", "cax", ")", "# show the plots", "fig", ".", "set_size_inches", "(", "width", ",", "rows", "/", "cols", "*", "width", ")", "plt", ".", "tight_layout", "(", ")", "if", "show", ":", "plt", ".", "show", "(", ")", "return", "(", "fig", ",", "axs", ")" ]
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/cnn_sphere_register/ext/neuron/neuron/plot.py#L7-L88
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/charset.py
python
add_alias
(alias, canonical)
Add a character set alias. alias is the alias name, e.g. latin-1 canonical is the character set's canonical name, e.g. iso-8859-1
Add a character set alias.
[ "Add", "a", "character", "set", "alias", "." ]
def add_alias(alias, canonical): """Add a character set alias. alias is the alias name, e.g. latin-1 canonical is the character set's canonical name, e.g. iso-8859-1 """ ALIASES[alias] = canonical
[ "def", "add_alias", "(", "alias", ",", "canonical", ")", ":", "ALIASES", "[", "alias", "]", "=", "canonical" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/charset.py#L136-L142
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/cephfs/filesystem.py
python
Filesystem.list_dirfrag
(self, dir_ino)
return key_list_str.strip().split("\n") if key_list_str else []
Read the named object and return the list of omap keys :return a list of 0 or more strings
Read the named object and return the list of omap keys
[ "Read", "the", "named", "object", "and", "return", "the", "list", "of", "omap", "keys" ]
def list_dirfrag(self, dir_ino): """ Read the named object and return the list of omap keys :return a list of 0 or more strings """ dirfrag_obj_name = "{0:x}.00000000".format(dir_ino) try: key_list_str = self.radosmo(["listomapkeys", dirfrag_obj_name], stdout=StringIO()) except CommandFailedError as e: log.error(e.__str__()) raise ObjectNotFound(dirfrag_obj_name) return key_list_str.strip().split("\n") if key_list_str else []
[ "def", "list_dirfrag", "(", "self", ",", "dir_ino", ")", ":", "dirfrag_obj_name", "=", "\"{0:x}.00000000\"", ".", "format", "(", "dir_ino", ")", "try", ":", "key_list_str", "=", "self", ".", "radosmo", "(", "[", "\"listomapkeys\"", ",", "dirfrag_obj_name", "]", ",", "stdout", "=", "StringIO", "(", ")", ")", "except", "CommandFailedError", "as", "e", ":", "log", ".", "error", "(", "e", ".", "__str__", "(", ")", ")", "raise", "ObjectNotFound", "(", "dirfrag_obj_name", ")", "return", "key_list_str", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "if", "key_list_str", "else", "[", "]" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/cephfs/filesystem.py#L1394-L1409
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
python/caffe/net_spec.py
python
assign_proto
(proto, name, val)
Assign a Python object to a protobuf message, based on the Python type (in recursive fashion). Lists become repeated fields/messages, dicts become messages, and other types are assigned directly.
Assign a Python object to a protobuf message, based on the Python type (in recursive fashion). Lists become repeated fields/messages, dicts become messages, and other types are assigned directly.
[ "Assign", "a", "Python", "object", "to", "a", "protobuf", "message", "based", "on", "the", "Python", "type", "(", "in", "recursive", "fashion", ")", ".", "Lists", "become", "repeated", "fields", "/", "messages", "dicts", "become", "messages", "and", "other", "types", "are", "assigned", "directly", "." ]
def assign_proto(proto, name, val): """Assign a Python object to a protobuf message, based on the Python type (in recursive fashion). Lists become repeated fields/messages, dicts become messages, and other types are assigned directly.""" if isinstance(val, list): if isinstance(val[0], dict): for item in val: proto_item = getattr(proto, name).add() for k, v in six.iteritems(item): assign_proto(proto_item, k, v) else: getattr(proto, name).extend(val) elif isinstance(val, dict): for k, v in six.iteritems(val): assign_proto(getattr(proto, name), k, v) else: setattr(proto, name, val)
[ "def", "assign_proto", "(", "proto", ",", "name", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "list", ")", ":", "if", "isinstance", "(", "val", "[", "0", "]", ",", "dict", ")", ":", "for", "item", "in", "val", ":", "proto_item", "=", "getattr", "(", "proto", ",", "name", ")", ".", "add", "(", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "item", ")", ":", "assign_proto", "(", "proto_item", ",", "k", ",", "v", ")", "else", ":", "getattr", "(", "proto", ",", "name", ")", ".", "extend", "(", "val", ")", "elif", "isinstance", "(", "val", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "val", ")", ":", "assign_proto", "(", "getattr", "(", "proto", ",", "name", ")", ",", "k", ",", "v", ")", "else", ":", "setattr", "(", "proto", ",", "name", ",", "val", ")" ]
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/python/caffe/net_spec.py#L56-L73
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/xcodeproj_file.py
python
XCObject._EncodeString
(self, value)
return '"' + _escaped.sub(self._EncodeTransform, value) + '"'
Encodes a string to be placed in the project file output, mimicing Xcode behavior.
Encodes a string to be placed in the project file output, mimicing Xcode behavior.
[ "Encodes", "a", "string", "to", "be", "placed", "in", "the", "project", "file", "output", "mimicing", "Xcode", "behavior", "." ]
def _EncodeString(self, value): """Encodes a string to be placed in the project file output, mimicing Xcode behavior. """ # Use quotation marks when any character outside of the range A-Z, a-z, 0-9, # $ (dollar sign), . (period), and _ (underscore) is present. Also use # quotation marks to represent empty strings. # # Escape " (double-quote) and \ (backslash) by preceding them with a # backslash. # # Some characters below the printable ASCII range are encoded specially: # 7 ^G BEL is encoded as "\a" # 8 ^H BS is encoded as "\b" # 11 ^K VT is encoded as "\v" # 12 ^L NP is encoded as "\f" # 127 ^? DEL is passed through as-is without escaping # - In PBXFileReference and PBXBuildFile objects: # 9 ^I HT is passed through as-is without escaping # 10 ^J NL is passed through as-is without escaping # 13 ^M CR is passed through as-is without escaping # - In other objects: # 9 ^I HT is encoded as "\t" # 10 ^J NL is encoded as "\n" # 13 ^M CR is encoded as "\n" rendering it indistinguishable from # 10 ^J NL # All other characters within the ASCII control character range (0 through # 31 inclusive) are encoded as "\U001f" referring to the Unicode code point # in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e". # Characters above the ASCII range are passed through to the output encoded # as UTF-8 without any escaping. These mappings are contained in the # class' _encode_transforms list. if _unquoted.search(value) and not _quoted.search(value): return value return '"' + _escaped.sub(self._EncodeTransform, value) + '"'
[ "def", "_EncodeString", "(", "self", ",", "value", ")", ":", "# Use quotation marks when any character outside of the range A-Z, a-z, 0-9,", "# $ (dollar sign), . (period), and _ (underscore) is present. Also use", "# quotation marks to represent empty strings.", "#", "# Escape \" (double-quote) and \\ (backslash) by preceding them with a", "# backslash.", "#", "# Some characters below the printable ASCII range are encoded specially:", "# 7 ^G BEL is encoded as \"\\a\"", "# 8 ^H BS is encoded as \"\\b\"", "# 11 ^K VT is encoded as \"\\v\"", "# 12 ^L NP is encoded as \"\\f\"", "# 127 ^? DEL is passed through as-is without escaping", "# - In PBXFileReference and PBXBuildFile objects:", "# 9 ^I HT is passed through as-is without escaping", "# 10 ^J NL is passed through as-is without escaping", "# 13 ^M CR is passed through as-is without escaping", "# - In other objects:", "# 9 ^I HT is encoded as \"\\t\"", "# 10 ^J NL is encoded as \"\\n\"", "# 13 ^M CR is encoded as \"\\n\" rendering it indistinguishable from", "# 10 ^J NL", "# All other characters within the ASCII control character range (0 through", "# 31 inclusive) are encoded as \"\\U001f\" referring to the Unicode code point", "# in hexadecimal. For example, character 14 (^N SO) is encoded as \"\\U000e\".", "# Characters above the ASCII range are passed through to the output encoded", "# as UTF-8 without any escaping. These mappings are contained in the", "# class' _encode_transforms list.", "if", "_unquoted", ".", "search", "(", "value", ")", "and", "not", "_quoted", ".", "search", "(", "value", ")", ":", "return", "value", "return", "'\"'", "+", "_escaped", ".", "sub", "(", "self", ".", "_EncodeTransform", ",", "value", ")", "+", "'\"'" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/xcodeproj_file.py#L532-L569
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/curses/textpad.py
python
rectangle
(win, uly, ulx, lry, lrx)
Draw a rectangle with corners at the provided upper-left and lower-right coordinates.
Draw a rectangle with corners at the provided upper-left and lower-right coordinates.
[ "Draw", "a", "rectangle", "with", "corners", "at", "the", "provided", "upper", "-", "left", "and", "lower", "-", "right", "coordinates", "." ]
def rectangle(win, uly, ulx, lry, lrx): """Draw a rectangle with corners at the provided upper-left and lower-right coordinates. """ win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER)
[ "def", "rectangle", "(", "win", ",", "uly", ",", "ulx", ",", "lry", ",", "lrx", ")", ":", "win", ".", "vline", "(", "uly", "+", "1", ",", "ulx", ",", "curses", ".", "ACS_VLINE", ",", "lry", "-", "uly", "-", "1", ")", "win", ".", "hline", "(", "uly", ",", "ulx", "+", "1", ",", "curses", ".", "ACS_HLINE", ",", "lrx", "-", "ulx", "-", "1", ")", "win", ".", "hline", "(", "lry", ",", "ulx", "+", "1", ",", "curses", ".", "ACS_HLINE", ",", "lrx", "-", "ulx", "-", "1", ")", "win", ".", "vline", "(", "uly", "+", "1", ",", "lrx", ",", "curses", ".", "ACS_VLINE", ",", "lry", "-", "uly", "-", "1", ")", "win", ".", "addch", "(", "uly", ",", "ulx", ",", "curses", ".", "ACS_ULCORNER", ")", "win", ".", "addch", "(", "uly", ",", "lrx", ",", "curses", ".", "ACS_URCORNER", ")", "win", ".", "addch", "(", "lry", ",", "lrx", ",", "curses", ".", "ACS_LRCORNER", ")", "win", ".", "addch", "(", "lry", ",", "ulx", ",", "curses", ".", "ACS_LLCORNER", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/curses/textpad.py#L6-L17
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
DC.SetUserScale
(*args, **kwargs)
return _gdi_.DC_SetUserScale(*args, **kwargs)
SetUserScale(self, double x, double y) Sets the user scaling factor, useful for applications which require 'zooming'.
SetUserScale(self, double x, double y)
[ "SetUserScale", "(", "self", "double", "x", "double", "y", ")" ]
def SetUserScale(*args, **kwargs): """ SetUserScale(self, double x, double y) Sets the user scaling factor, useful for applications which require 'zooming'. """ return _gdi_.DC_SetUserScale(*args, **kwargs)
[ "def", "SetUserScale", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_SetUserScale", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L4429-L4436
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/utils/lui/lldbutil.py
python
value_type_to_str
(enum)
Returns the valueType string given an enum.
Returns the valueType string given an enum.
[ "Returns", "the", "valueType", "string", "given", "an", "enum", "." ]
def value_type_to_str(enum): """Returns the valueType string given an enum.""" if enum == lldb.eValueTypeInvalid: return "invalid" elif enum == lldb.eValueTypeVariableGlobal: return "global_variable" elif enum == lldb.eValueTypeVariableStatic: return "static_variable" elif enum == lldb.eValueTypeVariableArgument: return "argument_variable" elif enum == lldb.eValueTypeVariableLocal: return "local_variable" elif enum == lldb.eValueTypeRegister: return "register" elif enum == lldb.eValueTypeRegisterSet: return "register_set" elif enum == lldb.eValueTypeConstResult: return "constant_result" else: raise Exception("Unknown ValueType enum")
[ "def", "value_type_to_str", "(", "enum", ")", ":", "if", "enum", "==", "lldb", ".", "eValueTypeInvalid", ":", "return", "\"invalid\"", "elif", "enum", "==", "lldb", ".", "eValueTypeVariableGlobal", ":", "return", "\"global_variable\"", "elif", "enum", "==", "lldb", ".", "eValueTypeVariableStatic", ":", "return", "\"static_variable\"", "elif", "enum", "==", "lldb", ".", "eValueTypeVariableArgument", ":", "return", "\"argument_variable\"", "elif", "enum", "==", "lldb", ".", "eValueTypeVariableLocal", ":", "return", "\"local_variable\"", "elif", "enum", "==", "lldb", ".", "eValueTypeRegister", ":", "return", "\"register\"", "elif", "enum", "==", "lldb", ".", "eValueTypeRegisterSet", ":", "return", "\"register_set\"", "elif", "enum", "==", "lldb", ".", "eValueTypeConstResult", ":", "return", "\"constant_result\"", "else", ":", "raise", "Exception", "(", "\"Unknown ValueType enum\"", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/utils/lui/lldbutil.py#L259-L278
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/pytorch/rcfr.py
python
ReservoirBuffer.insert
(self, candidate)
Consider this `candidate` for inclusion in this sampling buffer.
Consider this `candidate` for inclusion in this sampling buffer.
[ "Consider", "this", "candidate", "for", "inclusion", "in", "this", "sampling", "buffer", "." ]
def insert(self, candidate): """Consider this `candidate` for inclusion in this sampling buffer.""" self._num_candidates += 1 if self.num_elements < self.size: self._buffer[self.num_elements] = candidate self.num_elements += 1 return idx = np.random.choice(self._num_candidates) if idx < self.size: self._buffer[idx] = candidate
[ "def", "insert", "(", "self", ",", "candidate", ")", ":", "self", ".", "_num_candidates", "+=", "1", "if", "self", ".", "num_elements", "<", "self", ".", "size", ":", "self", ".", "_buffer", "[", "self", ".", "num_elements", "]", "=", "candidate", "self", ".", "num_elements", "+=", "1", "return", "idx", "=", "np", ".", "random", ".", "choice", "(", "self", ".", "_num_candidates", ")", "if", "idx", "<", "self", ".", "size", ":", "self", ".", "_buffer", "[", "idx", "]", "=", "candidate" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/pytorch/rcfr.py#L799-L808
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
libVeles/cpplint.py
python
CheckForFunctionLengths
(filename, clean_lines, linenum, function_state, error)
Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found.
Reports for long function bodies.
[ "Reports", "for", "long", "function", "bodies", "." ]
def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] raw = clean_lines.raw_lines raw_line = raw[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count()
[ "def", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "function_state", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "lines", "line", "=", "lines", "[", "linenum", "]", "raw", "=", "clean_lines", ".", "raw_lines", "raw_line", "=", "raw", "[", "linenum", "]", "joined_line", "=", "''", "starting_func", "=", "False", "regexp", "=", "r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('", "# decls * & space::name( ...", "match_result", "=", "Match", "(", "regexp", ",", "line", ")", "if", "match_result", ":", "# If the name is all caps and underscores, figure it's a macro and", "# ignore it, unless it's TEST or TEST_F.", "function_name", "=", "match_result", ".", "group", "(", "1", ")", ".", "split", "(", ")", "[", "-", "1", "]", "if", "function_name", "==", "'TEST'", "or", "function_name", "==", "'TEST_F'", "or", "(", "not", "Match", "(", "r'[A-Z_]+$'", ",", "function_name", ")", ")", ":", "starting_func", "=", "True", "if", "starting_func", ":", "body_found", "=", "False", "for", "start_linenum", "in", "xrange", "(", "linenum", ",", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "start_line", "=", "lines", "[", "start_linenum", "]", "joined_line", "+=", "' '", "+", "start_line", ".", "lstrip", "(", ")", "if", "Search", "(", "r'(;|})'", ",", "start_line", ")", ":", "# Declarations and trivial functions", "body_found", "=", "True", "break", "# ... ignore", "elif", "Search", "(", "r'{'", ",", "start_line", ")", ":", "body_found", "=", "True", "function", "=", "Search", "(", "r'((\\w|:)*)\\('", ",", "line", ")", ".", "group", "(", "1", ")", "if", "Match", "(", "r'TEST'", ",", "function", ")", ":", "# Handle TEST... macros", "parameter_regexp", "=", "Search", "(", "r'(\\(.*\\))'", ",", "joined_line", ")", "if", "parameter_regexp", ":", "# Ignore bad syntax", "function", "+=", "parameter_regexp", ".", "group", "(", "1", ")", "else", ":", "function", "+=", "'()'", "function_state", ".", "Begin", "(", "function", ")", "break", "if", "not", "body_found", ":", "# No body for the function (or evidence of a non-function) was found.", "error", "(", "filename", ",", "linenum", ",", "'readability/fn_size'", ",", "5", ",", "'Lint failed to find start of function body.'", ")", "elif", "Match", "(", "r'^\\}\\s*$'", ",", "line", ")", ":", "# function end", "function_state", ".", "Check", "(", "error", ",", "filename", ",", "linenum", ")", "function_state", ".", "End", "(", ")", "elif", "not", "Match", "(", "r'^\\s*$'", ",", "line", ")", ":", "function_state", ".", "Count", "(", ")" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/libVeles/cpplint.py#L1941-L2008
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/bayesflow/python/ops/stochastic_graph.py
python
DistributionTensor._create_value
(self)
Create the value Tensor based on the value type, store as self._value.
Create the value Tensor based on the value type, store as self._value.
[ "Create", "the", "value", "Tensor", "based", "on", "the", "value", "type", "store", "as", "self", ".", "_value", "." ]
def _create_value(self): """Create the value Tensor based on the value type, store as self._value.""" if isinstance(self._value_type, MeanValue): value_tensor = self._dist.mean() elif isinstance(self._value_type, SampleValue): value_tensor = self._dist.sample_n(self._value_type.n) elif isinstance(self._value_type, SampleAndReshapeValue): if self._value_type.n == 1: value_tensor = self._dist.sample() else: samples = self._dist.sample_n(self._value_type.n) samples_shape = array_ops.shape(samples) samples_static_shape = samples.get_shape() new_batch_size = samples_shape[0] * samples_shape[1] value_tensor = array_ops.reshape( samples, array_ops.concat(0, ([new_batch_size], samples_shape[2:]))) if samples_static_shape.ndims is not None: # Update the static shape for shape inference purposes shape_list = samples_static_shape.as_list() new_shape = tensor_shape.vector( shape_list[0] * shape_list[1] if shape_list[0] is not None and shape_list[1] is not None else None) new_shape = new_shape.concatenate(samples_static_shape[2:]) value_tensor.set_shape(new_shape) else: raise TypeError( "Unrecognized Distribution Value Type: %s", self._value_type) if self._value_type.stop_gradient: # stop_gradient is being enforced by the value type return array_ops.stop_gradient(value_tensor) if isinstance(self._value_type, MeanValue): return value_tensor # Using pathwise-derivative for this one. if self._dist.is_continuous and self._dist.is_reparameterized: return value_tensor # Using pathwise-derivative for this one. else: # Will have to perform some variant of score function # estimation. Call stop_gradient on the sampler just in case we # may accidentally leak some gradient from it. return array_ops.stop_gradient(value_tensor)
[ "def", "_create_value", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_value_type", ",", "MeanValue", ")", ":", "value_tensor", "=", "self", ".", "_dist", ".", "mean", "(", ")", "elif", "isinstance", "(", "self", ".", "_value_type", ",", "SampleValue", ")", ":", "value_tensor", "=", "self", ".", "_dist", ".", "sample_n", "(", "self", ".", "_value_type", ".", "n", ")", "elif", "isinstance", "(", "self", ".", "_value_type", ",", "SampleAndReshapeValue", ")", ":", "if", "self", ".", "_value_type", ".", "n", "==", "1", ":", "value_tensor", "=", "self", ".", "_dist", ".", "sample", "(", ")", "else", ":", "samples", "=", "self", ".", "_dist", ".", "sample_n", "(", "self", ".", "_value_type", ".", "n", ")", "samples_shape", "=", "array_ops", ".", "shape", "(", "samples", ")", "samples_static_shape", "=", "samples", ".", "get_shape", "(", ")", "new_batch_size", "=", "samples_shape", "[", "0", "]", "*", "samples_shape", "[", "1", "]", "value_tensor", "=", "array_ops", ".", "reshape", "(", "samples", ",", "array_ops", ".", "concat", "(", "0", ",", "(", "[", "new_batch_size", "]", ",", "samples_shape", "[", "2", ":", "]", ")", ")", ")", "if", "samples_static_shape", ".", "ndims", "is", "not", "None", ":", "# Update the static shape for shape inference purposes", "shape_list", "=", "samples_static_shape", ".", "as_list", "(", ")", "new_shape", "=", "tensor_shape", ".", "vector", "(", "shape_list", "[", "0", "]", "*", "shape_list", "[", "1", "]", "if", "shape_list", "[", "0", "]", "is", "not", "None", "and", "shape_list", "[", "1", "]", "is", "not", "None", "else", "None", ")", "new_shape", "=", "new_shape", ".", "concatenate", "(", "samples_static_shape", "[", "2", ":", "]", ")", "value_tensor", ".", "set_shape", "(", "new_shape", ")", "else", ":", "raise", "TypeError", "(", "\"Unrecognized Distribution Value Type: %s\"", ",", "self", ".", "_value_type", ")", "if", "self", ".", "_value_type", ".", "stop_gradient", ":", "# stop_gradient is being enforced by the value type", "return", "array_ops", ".", "stop_gradient", "(", "value_tensor", ")", "if", "isinstance", "(", "self", ".", "_value_type", ",", "MeanValue", ")", ":", "return", "value_tensor", "# Using pathwise-derivative for this one.", "if", "self", ".", "_dist", ".", "is_continuous", "and", "self", ".", "_dist", ".", "is_reparameterized", ":", "return", "value_tensor", "# Using pathwise-derivative for this one.", "else", ":", "# Will have to perform some variant of score function", "# estimation. Call stop_gradient on the sampler just in case we", "# may accidentally leak some gradient from it.", "return", "array_ops", ".", "stop_gradient", "(", "value_tensor", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/bayesflow/python/ops/stochastic_graph.py#L406-L448
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftutils/utils.py
python
epsilon
()
return 1.0/(10.0**tolerance())
Return a small number based on the tolerance for use in comparisons. The epsilon value is used in floating point comparisons. Use with caution. :: denom = 10**tolerance num = 1 epsilon = num/denom Returns ------- float 1/(10**tolerance)
Return a small number based on the tolerance for use in comparisons.
[ "Return", "a", "small", "number", "based", "on", "the", "tolerance", "for", "use", "in", "comparisons", "." ]
def epsilon(): """Return a small number based on the tolerance for use in comparisons. The epsilon value is used in floating point comparisons. Use with caution. :: denom = 10**tolerance num = 1 epsilon = num/denom Returns ------- float 1/(10**tolerance) """ return 1.0/(10.0**tolerance())
[ "def", "epsilon", "(", ")", ":", "return", "1.0", "/", "(", "10.0", "**", "tolerance", "(", ")", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftutils/utils.py#L362-L376
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
FileCtrl.Create
(*args, **kwargs)
return _controls_.FileCtrl_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, String defaultDirectory=wxEmptyString, String defaultFilename=wxEmptyString, String wildCard=wxFileSelectorDefaultWildcardStr, long style=FC_DEFAULT_STYLE, Point pos=DefaultPosition, Size size=DefaultSize, String name=FileCtrlNameStr) -> bool
Create(self, Window parent, int id=-1, String defaultDirectory=wxEmptyString, String defaultFilename=wxEmptyString, String wildCard=wxFileSelectorDefaultWildcardStr, long style=FC_DEFAULT_STYLE, Point pos=DefaultPosition, Size size=DefaultSize, String name=FileCtrlNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "String", "defaultDirectory", "=", "wxEmptyString", "String", "defaultFilename", "=", "wxEmptyString", "String", "wildCard", "=", "wxFileSelectorDefaultWildcardStr", "long", "style", "=", "FC_DEFAULT_STYLE", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "String", "name", "=", "FileCtrlNameStr", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String defaultDirectory=wxEmptyString, String defaultFilename=wxEmptyString, String wildCard=wxFileSelectorDefaultWildcardStr, long style=FC_DEFAULT_STYLE, Point pos=DefaultPosition, Size size=DefaultSize, String name=FileCtrlNameStr) -> bool """ return _controls_.FileCtrl_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "FileCtrl_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L7597-L7606
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSILLReduction.py
python
SANSILLReduction._split_kinetic_frames
(self, ws)
return frames
Explodes the frames of a kinetic workspace into separate workspaces
Explodes the frames of a kinetic workspace into separate workspaces
[ "Explodes", "the", "frames", "of", "a", "kinetic", "workspace", "into", "separate", "workspaces" ]
def _split_kinetic_frames(self, ws): '''Explodes the frames of a kinetic workspace into separate workspaces''' n_frames = mtd[ws].blocksize() n_hist = mtd[ws].getNumberHistograms() wavelength = round(mtd[ws].getRun().getLogData('wavelength').value * 100) / 100 wave_bins = [wavelength * 0.9, wavelength * 1.1] frames = [] for frame_index in range(n_frames): frame_name = ws + '_t' + str(frame_index) frames.append(frame_name) CropWorkspace(InputWorkspace=ws, OutputWorkspace=frame_name, XMin=frame_index, XMax=frame_index) ConvertToHistogram(InputWorkspace=frame_name, OutputWorkspace=frame_name) mtd[frame_name].getAxis(0).setUnit('Wavelength') for s in range(n_hist): mtd[frame_name].setX(s, wave_bins) RenameWorkspace(InputWorkspace=ws, OutputWorkspace=ws[2:]) return frames
[ "def", "_split_kinetic_frames", "(", "self", ",", "ws", ")", ":", "n_frames", "=", "mtd", "[", "ws", "]", ".", "blocksize", "(", ")", "n_hist", "=", "mtd", "[", "ws", "]", ".", "getNumberHistograms", "(", ")", "wavelength", "=", "round", "(", "mtd", "[", "ws", "]", ".", "getRun", "(", ")", ".", "getLogData", "(", "'wavelength'", ")", ".", "value", "*", "100", ")", "/", "100", "wave_bins", "=", "[", "wavelength", "*", "0.9", ",", "wavelength", "*", "1.1", "]", "frames", "=", "[", "]", "for", "frame_index", "in", "range", "(", "n_frames", ")", ":", "frame_name", "=", "ws", "+", "'_t'", "+", "str", "(", "frame_index", ")", "frames", ".", "append", "(", "frame_name", ")", "CropWorkspace", "(", "InputWorkspace", "=", "ws", ",", "OutputWorkspace", "=", "frame_name", ",", "XMin", "=", "frame_index", ",", "XMax", "=", "frame_index", ")", "ConvertToHistogram", "(", "InputWorkspace", "=", "frame_name", ",", "OutputWorkspace", "=", "frame_name", ")", "mtd", "[", "frame_name", "]", ".", "getAxis", "(", "0", ")", ".", "setUnit", "(", "'Wavelength'", ")", "for", "s", "in", "range", "(", "n_hist", ")", ":", "mtd", "[", "frame_name", "]", ".", "setX", "(", "s", ",", "wave_bins", ")", "RenameWorkspace", "(", "InputWorkspace", "=", "ws", ",", "OutputWorkspace", "=", "ws", "[", "2", ":", "]", ")", "return", "frames" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSILLReduction.py#L852-L868
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/bindings/python/clang/cindex.py
python
Cursor.access_specifier
(self)
return AccessSpecifier.from_id(self._access_specifier)
Retrieves the access specifier (if any) of the entity pointed at by the cursor.
Retrieves the access specifier (if any) of the entity pointed at by the cursor.
[ "Retrieves", "the", "access", "specifier", "(", "if", "any", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def access_specifier(self): """ Retrieves the access specifier (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_access_specifier'): self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) return AccessSpecifier.from_id(self._access_specifier)
[ "def", "access_specifier", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_access_specifier'", ")", ":", "self", ".", "_access_specifier", "=", "conf", ".", "lib", ".", "clang_getCXXAccessSpecifier", "(", "self", ")", "return", "AccessSpecifier", ".", "from_id", "(", "self", ".", "_access_specifier", ")" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L1630-L1638
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/combo.py
python
ComboCtrl.Popup
(*args, **kwargs)
return _combo.ComboCtrl_Popup(*args, **kwargs)
Popup(self)
Popup(self)
[ "Popup", "(", "self", ")" ]
def Popup(*args, **kwargs): """Popup(self)""" return _combo.ComboCtrl_Popup(*args, **kwargs)
[ "def", "Popup", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboCtrl_Popup", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L124-L126
stulp/dmpbbo
ca900e3b851d25faaf59ea296650370c70ed7d0f
python/bbo/updaters.py
python
UpdaterCovarDecay.__init__
(self,eliteness = 10, weighting_method = 'PI-BB', covar_decay_factor = 0.8)
Initialize an UpdaterCovarDecay object. \param[in] eliteness The eliteness parameter (see costsToWeights(...)) \param[in] weighting_method The weighting method ('PI-BB','CMA-ES','CEM', see costsToWeights(...)) \param[in] covar_decay_factor Factor with which to decay the covariance matrix (i.e. covar_decay_factor*covar_decay_factor*C at each update)
Initialize an UpdaterCovarDecay object. \param[in] eliteness The eliteness parameter (see costsToWeights(...)) \param[in] weighting_method The weighting method ('PI-BB','CMA-ES','CEM', see costsToWeights(...)) \param[in] covar_decay_factor Factor with which to decay the covariance matrix (i.e. covar_decay_factor*covar_decay_factor*C at each update)
[ "Initialize", "an", "UpdaterCovarDecay", "object", ".", "\\", "param", "[", "in", "]", "eliteness", "The", "eliteness", "parameter", "(", "see", "costsToWeights", "(", "...", "))", "\\", "param", "[", "in", "]", "weighting_method", "The", "weighting", "method", "(", "PI", "-", "BB", "CMA", "-", "ES", "CEM", "see", "costsToWeights", "(", "...", "))", "\\", "param", "[", "in", "]", "covar_decay_factor", "Factor", "with", "which", "to", "decay", "the", "covariance", "matrix", "(", "i", ".", "e", ".", "covar_decay_factor", "*", "covar_decay_factor", "*", "C", "at", "each", "update", ")" ]
def __init__(self,eliteness = 10, weighting_method = 'PI-BB', covar_decay_factor = 0.8): """ Initialize an UpdaterCovarDecay object. \param[in] eliteness The eliteness parameter (see costsToWeights(...)) \param[in] weighting_method The weighting method ('PI-BB','CMA-ES','CEM', see costsToWeights(...)) \param[in] covar_decay_factor Factor with which to decay the covariance matrix (i.e. covar_decay_factor*covar_decay_factor*C at each update) """ self.eliteness = eliteness self.weighting_method = weighting_method self.covar_decay_factor = covar_decay_factor
[ "def", "__init__", "(", "self", ",", "eliteness", "=", "10", ",", "weighting_method", "=", "'PI-BB'", ",", "covar_decay_factor", "=", "0.8", ")", ":", "self", ".", "eliteness", "=", "eliteness", "self", ".", "weighting_method", "=", "weighting_method", "self", ".", "covar_decay_factor", "=", "covar_decay_factor" ]
https://github.com/stulp/dmpbbo/blob/ca900e3b851d25faaf59ea296650370c70ed7d0f/python/bbo/updaters.py#L77-L85