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
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_implementations.py
python
bprop_switch
(cond, tb, fb, out, dout)
return C.zeros_like(cond), F.switch(cond, dout, C.zeros_like(tb)), \ F.switch(cond, C.zeros_like(fb), dout)
Backpropagator for primitive `switch`.
Backpropagator for primitive `switch`.
[ "Backpropagator", "for", "primitive", "switch", "." ]
def bprop_switch(cond, tb, fb, out, dout): """Backpropagator for primitive `switch`.""" return C.zeros_like(cond), F.switch(cond, dout, C.zeros_like(tb)), \ F.switch(cond, C.zeros_like(fb), dout)
[ "def", "bprop_switch", "(", "cond", ",", "tb", ",", "fb", ",", "out", ",", "dout", ")", ":", "return", "C", ".", "zeros_like", "(", "cond", ")", ",", "F", ".", "switch", "(", "cond", ",", "dout", ",", "C", ".", "zeros_like", "(", "tb", ")", ")"...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_implementations.py#L251-L254
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/third_party/Python/module/pexpect-4.6/pexpect/popen_spawn.py
python
PopenSpawn.write
(self, s)
This is similar to send() except that there is no return value.
This is similar to send() except that there is no return value.
[ "This", "is", "similar", "to", "send", "()", "except", "that", "there", "is", "no", "return", "value", "." ]
def write(self, s): '''This is similar to send() except that there is no return value. ''' self.send(s)
[ "def", "write", "(", "self", ",", "s", ")", ":", "self", ".", "send", "(", "s", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/popen_spawn.py#L117-L120
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/Queue.py
python
Queue.task_done
(self)
Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue.
Indicate that a formerly enqueued task is complete.
[ "Indicate", "that", "a", "formerly", "enqueued", "task", "is", "complete", "." ]
def task_done(self): """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. """ self.all_tasks_done.acquire() try: unfinished = self.unfinished_tasks - 1 if unfinished <= 0: if unfinished < 0: raise ValueError('task_done() called too many times') self.all_tasks_done.notify_all() self.unfinished_tasks = unfinished finally: self.all_tasks_done.release()
[ "def", "task_done", "(", "self", ")", ":", "self", ".", "all_tasks_done", ".", "acquire", "(", ")", "try", ":", "unfinished", "=", "self", ".", "unfinished_tasks", "-", "1", "if", "unfinished", "<=", "0", ":", "if", "unfinished", "<", "0", ":", "raise"...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/Queue.py#L45-L68
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
ConfigBase.Exists
(*args, **kwargs)
return _misc_.ConfigBase_Exists(*args, **kwargs)
Exists(self, String name) -> bool Returns True if either a group or an entry with a given name exists
Exists(self, String name) -> bool
[ "Exists", "(", "self", "String", "name", ")", "-", ">", "bool" ]
def Exists(*args, **kwargs): """ Exists(self, String name) -> bool Returns True if either a group or an entry with a given name exists """ return _misc_.ConfigBase_Exists(*args, **kwargs)
[ "def", "Exists", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_Exists", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L3239-L3245
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py
python
ControlFlowState.EnterGradWhileContext
(self, op, before)
Enter the WhileContext for gradient computation.
Enter the WhileContext for gradient computation.
[ "Enter", "the", "WhileContext", "for", "gradient", "computation", "." ]
def EnterGradWhileContext(self, op, before): """Enter the WhileContext for gradient computation.""" grad_state = self._GetGradState(op, before) if grad_state: grad_state.grad_context.Enter()
[ "def", "EnterGradWhileContext", "(", "self", ",", "op", ",", "before", ")", ":", "grad_state", "=", "self", ".", "_GetGradState", "(", "op", ",", "before", ")", "if", "grad_state", ":", "grad_state", ".", "grad_context", ".", "Enter", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L830-L834
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
PrintDialogData.GetEnablePageNumbers
(*args, **kwargs)
return _windows_.PrintDialogData_GetEnablePageNumbers(*args, **kwargs)
GetEnablePageNumbers(self) -> bool
GetEnablePageNumbers(self) -> bool
[ "GetEnablePageNumbers", "(", "self", ")", "-", ">", "bool" ]
def GetEnablePageNumbers(*args, **kwargs): """GetEnablePageNumbers(self) -> bool""" return _windows_.PrintDialogData_GetEnablePageNumbers(*args, **kwargs)
[ "def", "GetEnablePageNumbers", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintDialogData_GetEnablePageNumbers", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L5138-L5140
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/google/protobuf/internal/type_checkers.py
python
GetTypeChecker
(field)
return _VALUE_CHECKERS[field.cpp_type]
Returns a type checker for a message field of the specified types. Args: field: FieldDescriptor object for this field. Returns: An instance of TypeChecker which can be used to verify the types of values assigned to a field of the specified type.
Returns a type checker for a message field of the specified types.
[ "Returns", "a", "type", "checker", "for", "a", "message", "field", "of", "the", "specified", "types", "." ]
def GetTypeChecker(field): """Returns a type checker for a message field of the specified types. Args: field: FieldDescriptor object for this field. Returns: An instance of TypeChecker which can be used to verify the types of values assigned to a field of the specified type. """ if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and field.type == _FieldDescriptor.TYPE_STRING): return UnicodeValueChecker() if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: if SupportsOpenEnums(field): # When open enums are supported, any int32 can be assigned. return _VALUE_CHECKERS[_FieldDescriptor.CPPTYPE_INT32] else: return EnumValueChecker(field.enum_type) return _VALUE_CHECKERS[field.cpp_type]
[ "def", "GetTypeChecker", "(", "field", ")", ":", "if", "(", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_STRING", "and", "field", ".", "type", "==", "_FieldDescriptor", ".", "TYPE_STRING", ")", ":", "return", "UnicodeValueChecker", "(", ")...
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/type_checkers.py#L64-L83
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/data_table_view.py
python
DataTableModel._getCellText
(self, row, col)
return self._dataToText(row, col, rowData[col]).strip() if len(rowData) > col else None
get the text of a cell :param row: row of the cell :param col: column of the cell :return: text of the cell
get the text of a cell :param row: row of the cell :param col: column of the cell :return: text of the cell
[ "get", "the", "text", "of", "a", "cell", ":", "param", "row", ":", "row", "of", "the", "cell", ":", "param", "col", ":", "column", "of", "the", "cell", ":", "return", ":", "text", "of", "the", "cell" ]
def _getCellText(self, row, col): """ get the text of a cell :param row: row of the cell :param col: column of the cell :return: text of the cell """ rowData = self._getRow(row) return self._dataToText(row, col, rowData[col]).strip() if len(rowData) > col else None
[ "def", "_getCellText", "(", "self", ",", "row", ",", "col", ")", ":", "rowData", "=", "self", ".", "_getRow", "(", "row", ")", "return", "self", ".", "_dataToText", "(", "row", ",", "col", ",", "rowData", "[", "col", "]", ")", ".", "strip", "(", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/data_table_view.py#L108-L116
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/modes/notemacs.py
python
NotEmacsMode.backward_kill_line
(self, e)
Kill backward to the beginning of the line.
Kill backward to the beginning of the line.
[ "Kill", "backward", "to", "the", "beginning", "of", "the", "line", "." ]
def backward_kill_line(self, e): # (C-x Rubout) '''Kill backward to the beginning of the line. ''' self.l_buffer.backward_kill_line()
[ "def", "backward_kill_line", "(", "self", ",", "e", ")", ":", "# (C-x Rubout)", "self", ".", "l_buffer", ".", "backward_kill_line", "(", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/notemacs.py#L326-L328
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetExecutableName
(self)
Returns the executable name of the bundle represented by this target. E.g. Chromium.
Returns the executable name of the bundle represented by this target. E.g. Chromium.
[ "Returns", "the", "executable", "name", "of", "the", "bundle", "represented", "by", "this", "target", ".", "E", ".", "g", ".", "Chromium", "." ]
def GetExecutableName(self): """Returns the executable name of the bundle represented by this target. E.g. Chromium.""" if self._IsBundle(): return self.spec.get('product_name', self.spec['target_name']) else: return self._GetStandaloneBinaryPath()
[ "def", "GetExecutableName", "(", "self", ")", ":", "if", "self", ".", "_IsBundle", "(", ")", ":", "return", "self", ".", "spec", ".", "get", "(", "'product_name'", ",", "self", ".", "spec", "[", "'target_name'", "]", ")", "else", ":", "return", "self",...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L401-L407
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
FormulaFactory.instance
(self, type)
return self.instances[type]
Get an instance of the given type.
Get an instance of the given type.
[ "Get", "an", "instance", "of", "the", "given", "type", "." ]
def instance(self, type): "Get an instance of the given type." if not type in self.instances or not self.instances[type]: self.instances[type] = self.create(type) return self.instances[type]
[ "def", "instance", "(", "self", ",", "type", ")", ":", "if", "not", "type", "in", "self", ".", "instances", "or", "not", "self", ".", "instances", "[", "type", "]", ":", "self", ".", "instances", "[", "type", "]", "=", "self", ".", "create", "(", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L3042-L3046
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/web-crawler-multithreaded.py
python
HtmlParser.getUrls
(self, url)
:type url: str :rtype List[str]
:type url: str :rtype List[str]
[ ":", "type", "url", ":", "str", ":", "rtype", "List", "[", "str", "]" ]
def getUrls(self, url): """ :type url: str :rtype List[str] """ pass
[ "def", "getUrls", "(", "self", ",", "url", ")", ":", "pass" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/web-crawler-multithreaded.py#L13-L18
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Accuracy.py
python
Accuracy.reset
(self, reset)
Specifies if the statistics should be reset after each run.
Specifies if the statistics should be reset after each run.
[ "Specifies", "if", "the", "statistics", "should", "be", "reset", "after", "each", "run", "." ]
def reset(self, reset): """Specifies if the statistics should be reset after each run. """ self._internal.set_reset(bool(reset))
[ "def", "reset", "(", "self", ",", "reset", ")", ":", "self", ".", "_internal", ".", "set_reset", "(", "bool", "(", "reset", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Accuracy.py#L74-L77
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/functions/EISFDiffSphere.py
python
EISFDiffSphere.function1D
(self, xvals)
return self.getParameterValue('A') * np.square(3 * self.vecbessel(zs))
r"""Calculate the intensities Parameters ---------- xvals : sequence of floats The domain where to evaluate the function jacobian: 2D array partial derivative of the function with respect to the fitting parameters evaluated at the domain. Returns ------- numpy.ndarray Function values
r"""Calculate the intensities
[ "r", "Calculate", "the", "intensities" ]
def function1D(self, xvals): r"""Calculate the intensities Parameters ---------- xvals : sequence of floats The domain where to evaluate the function jacobian: 2D array partial derivative of the function with respect to the fitting parameters evaluated at the domain. Returns ------- numpy.ndarray Function values """ zs = self.getParameterValue('R') * np.asarray(xvals) return self.getParameterValue('A') * np.square(3 * self.vecbessel(zs))
[ "def", "function1D", "(", "self", ",", "xvals", ")", ":", "zs", "=", "self", ".", "getParameterValue", "(", "'R'", ")", "*", "np", ".", "asarray", "(", "xvals", ")", "return", "self", ".", "getParameterValue", "(", "'A'", ")", "*", "np", ".", "square...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/functions/EISFDiffSphere.py#L45-L62
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py
python
_handle_ns
(packageName, path_item)
return subpath
Ensure that named package includes a subpath of path_item (if needed)
Ensure that named package includes a subpath of path_item (if needed)
[ "Ensure", "that", "named", "package", "includes", "a", "subpath", "of", "path_item", "(", "if", "needed", ")" ]
def _handle_ns(packageName, path_item): """Ensure that named package includes a subpath of path_item (if needed)""" importer = get_importer(path_item) if importer is None: return None # use find_spec (PEP 451) and fall-back to find_module (PEP 302) try: loader = importer.find_spec(packageName).loader except AttributeError: # capture warnings due to #1111 with warnings.catch_warnings(): warnings.simplefilter("ignore") loader = importer.find_module(packageName) if loader is None: return None module = sys.modules.get(packageName) if module is None: module = sys.modules[packageName] = types.ModuleType(packageName) module.__path__ = [] _set_parent_ns(packageName) elif not hasattr(module, '__path__'): raise TypeError("Not a package:", packageName) handler = _find_adapter(_namespace_handlers, importer) subpath = handler(importer, path_item, packageName, module) if subpath is not None: path = module.__path__ path.append(subpath) loader.load_module(packageName) _rebuild_mod_path(path, packageName, module) return subpath
[ "def", "_handle_ns", "(", "packageName", ",", "path_item", ")", ":", "importer", "=", "get_importer", "(", "path_item", ")", "if", "importer", "is", "None", ":", "return", "None", "# use find_spec (PEP 451) and fall-back to find_module (PEP 302)", "try", ":", "loader"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L2193-L2225
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/check_ops.py
python
assert_less
(x, y, data=None, summarize=None, message=None, name=None)
Assert the condition `x < y` holds element-wise. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.assert_less(x, y)]): output = tf.reduce_sum(x) ``` Example of adding dependency to the tensor being checked: ```python x = tf.with_dependencies([tf.assert_less(x, y)], x) ``` This condition holds if for every pair of (possibly broadcast) elements `x[i]`, `y[i]`, we have `x[i] < y[i]`. If both `x` and `y` are empty, this is trivially satisfied. Args: x: Numeric `Tensor`. y: Numeric `Tensor`, same dtype as and broadcastable to `x`. data: The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`, `y`. summarize: Print this many entries of each tensor. message: A string to prefix to the default message. name: A name for this operation (optional). Defaults to "assert_less". Returns: Op that raises `InvalidArgumentError` if `x < y` is False.
Assert the condition `x < y` holds element-wise.
[ "Assert", "the", "condition", "x", "<", "y", "holds", "element", "-", "wise", "." ]
def assert_less(x, y, data=None, summarize=None, message=None, name=None): """Assert the condition `x < y` holds element-wise. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.assert_less(x, y)]): output = tf.reduce_sum(x) ``` Example of adding dependency to the tensor being checked: ```python x = tf.with_dependencies([tf.assert_less(x, y)], x) ``` This condition holds if for every pair of (possibly broadcast) elements `x[i]`, `y[i]`, we have `x[i] < y[i]`. If both `x` and `y` are empty, this is trivially satisfied. Args: x: Numeric `Tensor`. y: Numeric `Tensor`, same dtype as and broadcastable to `x`. data: The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`, `y`. summarize: Print this many entries of each tensor. message: A string to prefix to the default message. name: A name for this operation (optional). Defaults to "assert_less". Returns: Op that raises `InvalidArgumentError` if `x < y` is False. """ message = message or '' with ops.op_scope([x, y, data], name, 'assert_less'): x = ops.convert_to_tensor(x, name='x') y = ops.convert_to_tensor(y, name='y') if data is None: data = [ message, 'Condition x < y did not hold element-wise: x = ', x.name, x, 'y = ', y.name, y ] condition = math_ops.reduce_all(math_ops.less(x, y)) return logging_ops.Assert(condition, data, summarize=summarize)
[ "def", "assert_less", "(", "x", ",", "y", ",", "data", "=", "None", ",", "summarize", "=", "None", ",", "message", "=", "None", ",", "name", "=", "None", ")", ":", "message", "=", "message", "or", "''", "with", "ops", ".", "op_scope", "(", "[", "...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/check_ops.py#L311-L354
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/affine/index.py
python
index.numeric
(self, values)
return values[0][self._orig_key]
Returns the index/slice into the given value.
Returns the index/slice into the given value.
[ "Returns", "the", "index", "/", "slice", "into", "the", "given", "value", "." ]
def numeric(self, values): """ Returns the index/slice into the given value. """ return values[0][self._orig_key]
[ "def", "numeric", "(", "self", ",", "values", ")", ":", "return", "values", "[", "0", "]", "[", "self", ".", "_orig_key", "]" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/index.py#L72-L75
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/input.py
python
TurnIntIntoStrInDict
(the_dict)
Given dict the_dict, recursively converts all integers into strings.
Given dict the_dict, recursively converts all integers into strings.
[ "Given", "dict", "the_dict", "recursively", "converts", "all", "integers", "into", "strings", "." ]
def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if type(v) is int: v = str(v) the_dict[k] = v elif type(v) is dict: TurnIntIntoStrInDict(v) elif type(v) is list: TurnIntIntoStrInList(v) if type(k) is int: del the_dict[k] the_dict[str(k)] = v
[ "def", "TurnIntIntoStrInDict", "(", "the_dict", ")", ":", "# Use items instead of iteritems because there's no need to try to look at", "# reinserted keys and their associated values.", "for", "k", ",", "v", "in", "the_dict", ".", "items", "(", ")", ":", "if", "type", "(", ...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/input.py#L2289-L2305
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/constraint_solver/samples/cvrptw_break.py
python
create_data_model
()
return data
Stores the data for the problem.
Stores the data for the problem.
[ "Stores", "the", "data", "for", "the", "problem", "." ]
def create_data_model(): """Stores the data for the problem.""" data = {} # Locations in block unit locations_ = \ [(4, 4), # depot (2, 0), (8, 0), # locations to visit (0, 1), (1, 1), (5, 2), (7, 2), (3, 3), (6, 3), (5, 5), (8, 5), (1, 6), (2, 6), (3, 7), (6, 7), (0, 8), (7, 8)] # Compute locations in meters using the block dimension defined as follow # Manhattan average block: 750ft x 264ft -> 228m x 80m # here we use: 114m x 80m city block # src: https://nyti.ms/2GDoRIe "NY Times: Know Your distance" data['locations'] = [(l[0] * 114, l[1] * 80) for l in locations_] data['numlocations_'] = len(data['locations']) data['time_windows'] = \ [(0, 0), (75, 85), (75, 85), # 1, 2 (60, 70), (45, 55), # 3, 4 (0, 8), (50, 60), # 5, 6 (0, 10), (10, 20), # 7, 8 (0, 10), (75, 85), # 9, 10 (85, 95), (5, 15), # 11, 12 (15, 25), (10, 20), # 13, 14 (45, 55), (30, 40)] # 15, 16 data['demands'] = \ [0, # depot 1, 1, # 1, 2 2, 4, # 3, 4 2, 4, # 5, 6 8, 8, # 7, 8 1, 2, # 9,10 1, 2, # 11,12 4, 4, # 13, 14 8, 8] # 15, 16 data['time_per_demand_unit'] = 5 # 5 minutes/unit data['num_vehicles'] = 4 data['breaks'] = [(2, False), (2, False), (2, False), (2, False)] data['vehicle_capacity'] = 15 data['vehicle_speed'] = 83 # Travel speed: 5km/h converted in m/min data['depot'] = 0 return data
[ "def", "create_data_model", "(", ")", ":", "data", "=", "{", "}", "# Locations in block unit", "locations_", "=", "[", "(", "4", ",", "4", ")", ",", "# depot", "(", "2", ",", "0", ")", ",", "(", "8", ",", "0", ")", ",", "# locations to visit", "(", ...
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/constraint_solver/samples/cvrptw_break.py#L33-L79
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/cgi.py
python
FieldStorage.__contains__
(self, key)
return any(item.name == key for item in self.list)
Dictionary style __contains__ method.
Dictionary style __contains__ method.
[ "Dictionary", "style", "__contains__", "method", "." ]
def __contains__(self, key): """Dictionary style __contains__ method.""" if self.list is None: raise TypeError("not indexable") return any(item.name == key for item in self.list)
[ "def", "__contains__", "(", "self", ",", "key", ")", ":", "if", "self", ".", "list", "is", "None", ":", "raise", "TypeError", "(", "\"not indexable\"", ")", "return", "any", "(", "item", ".", "name", "==", "key", "for", "item", "in", "self", ".", "li...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/cgi.py#L587-L591
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/wheel.py
python
Wheel.filename
(self)
return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver, abi, arch)
Build and return a filename from the various components.
Build and return a filename from the various components.
[ "Build", "and", "return", "a", "filename", "from", "the", "various", "components", "." ]
def filename(self): """ Build and return a filename from the various components. """ if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arch) # replace - with _ as a local version separator version = self.version.replace('-', '_') return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver, abi, arch)
[ "def", "filename", "(", "self", ")", ":", "if", "self", ".", "buildver", ":", "buildver", "=", "'-'", "+", "self", ".", "buildver", "else", ":", "buildver", "=", "''", "pyver", "=", "'.'", ".", "join", "(", "self", ".", "pyver", ")", "abi", "=", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/wheel.py#L186-L200
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
MajorObject.GetMetadataItem
(self, *args)
return _ogr.MajorObject_GetMetadataItem(self, *args)
r"""GetMetadataItem(MajorObject self, char const * pszName, char const * pszDomain="") -> char const *
r"""GetMetadataItem(MajorObject self, char const * pszName, char const * pszDomain="") -> char const *
[ "r", "GetMetadataItem", "(", "MajorObject", "self", "char", "const", "*", "pszName", "char", "const", "*", "pszDomain", "=", ")", "-", ">", "char", "const", "*" ]
def GetMetadataItem(self, *args): r"""GetMetadataItem(MajorObject self, char const * pszName, char const * pszDomain="") -> char const *""" return _ogr.MajorObject_GetMetadataItem(self, *args)
[ "def", "GetMetadataItem", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "MajorObject_GetMetadataItem", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L443-L445
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/stubs.py
python
ds_permute
(src_lane, dest_lane)
AMDGCN Data Share intrinsic forwards permute (push semantics)
AMDGCN Data Share intrinsic forwards permute (push semantics)
[ "AMDGCN", "Data", "Share", "intrinsic", "forwards", "permute", "(", "push", "semantics", ")" ]
def ds_permute(src_lane, dest_lane): """ AMDGCN Data Share intrinsic forwards permute (push semantics) """ raise _stub_error
[ "def", "ds_permute", "(", "src_lane", ",", "dest_lane", ")", ":", "raise", "_stub_error" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/stubs.py#L102-L106
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ShallowWaterApplication/python_scripts/benchmarks/base_benchmark_process.py
python
BaseBenchmarkProcess.Check
(self)
Check if the input values have physical sense.
Check if the input values have physical sense.
[ "Check", "if", "the", "input", "values", "have", "physical", "sense", "." ]
def Check(self): """Check if the input values have physical sense.""" if len(self.variables) != len(self.exact_variables): raise Exception("The input variables list does not match the input exact variables list") if len(self.variables) != len(self.error_variables): raise Exception("The input variables list does not match the input error variables list") for (var, exact, error) in zip(self.variables, self.exact_variables, self.error_variables): if KM.KratosGlobals.GetVariableType(var.Name()) != KM.KratosGlobals.GetVariableType(exact.Name()): msg = var.Name() + " variable type does not match the " + exact.Name() + " variable type" raise Exception(msg) if KM.KratosGlobals.GetVariableType(var.Name()) != KM.KratosGlobals.GetVariableType(error.Name()): msg = var.Name() + " variable type does not match the " + error.Name() + " variable type" raise Exception(msg)
[ "def", "Check", "(", "self", ")", ":", "if", "len", "(", "self", ".", "variables", ")", "!=", "len", "(", "self", ".", "exact_variables", ")", ":", "raise", "Exception", "(", "\"The input variables list does not match the input exact variables list\"", ")", "if", ...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ShallowWaterApplication/python_scripts/benchmarks/base_benchmark_process.py#L81-L97
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py
python
getwriter
(encoding)
return lookup(encoding).streamwriter
Lookup up the codec for the given encoding and return its StreamWriter class or factory function. Raises a LookupError in case the encoding cannot be found.
Lookup up the codec for the given encoding and return its StreamWriter class or factory function.
[ "Lookup", "up", "the", "codec", "for", "the", "given", "encoding", "and", "return", "its", "StreamWriter", "class", "or", "factory", "function", "." ]
def getwriter(encoding): """ Lookup up the codec for the given encoding and return its StreamWriter class or factory function. Raises a LookupError in case the encoding cannot be found. """ return lookup(encoding).streamwriter
[ "def", "getwriter", "(", "encoding", ")", ":", "return", "lookup", "(", "encoding", ")", ".", "streamwriter" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py#L1014-L1022
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_factory.py
python
decl_factory_t.create_constructor
(self, *arguments, **keywords)
return constructor_t(*arguments, **keywords)
creates instance of class that describes constructor declaration
creates instance of class that describes constructor declaration
[ "creates", "instance", "of", "class", "that", "describes", "constructor", "declaration" ]
def create_constructor(self, *arguments, **keywords): """creates instance of class that describes constructor declaration""" return constructor_t(*arguments, **keywords)
[ "def", "create_constructor", "(", "self", ",", "*", "arguments", ",", "*", "*", "keywords", ")", ":", "return", "constructor_t", "(", "*", "arguments", ",", "*", "*", "keywords", ")" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_factory.py#L40-L42
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/aoc/processor.py
python
AoCProcessor.link_researchables
(full_data_set)
Link techs to their buildings. This is done to provide quick access during conversion. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :type full_data_set: class: ...dataformat.aoc.genie_object_container.GenieObjectContainer
Link techs to their buildings. This is done to provide quick access during conversion.
[ "Link", "techs", "to", "their", "buildings", ".", "This", "is", "done", "to", "provide", "quick", "access", "during", "conversion", "." ]
def link_researchables(full_data_set): """ Link techs to their buildings. This is done to provide quick access during conversion. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :type full_data_set: class: ...dataformat.aoc.genie_object_container.GenieObjectContainer """ tech_groups = full_data_set.tech_groups for tech in tech_groups.values(): if tech.is_researchable(): research_location_id = tech.get_research_location_id() full_data_set.building_lines[research_location_id].add_researchable(tech)
[ "def", "link_researchables", "(", "full_data_set", ")", ":", "tech_groups", "=", "full_data_set", ".", "tech_groups", "for", "tech", "in", "tech_groups", ".", "values", "(", ")", ":", "if", "tech", ".", "is_researchable", "(", ")", ":", "research_location_id", ...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/processor.py#L1087-L1102
electron-archive/brightray
3d9ebb549990d50ab67b705b8ff16433a3dbc546
tools/mac/change_mach_o_flags.py
python
HandleFatFile
(file, options, fat_offset=0)
Seeks the file-like |file| object to |offset| and loops over its |fat_header| entries, calling HandleMachOFile for each.
Seeks the file-like |file| object to |offset| and loops over its |fat_header| entries, calling HandleMachOFile for each.
[ "Seeks", "the", "file", "-", "like", "|file|", "object", "to", "|offset|", "and", "loops", "over", "its", "|fat_header|", "entries", "calling", "HandleMachOFile", "for", "each", "." ]
def HandleFatFile(file, options, fat_offset=0): """Seeks the file-like |file| object to |offset| and loops over its |fat_header| entries, calling HandleMachOFile for each.""" CheckedSeek(file, fat_offset) magic = ReadUInt32(file, '>') assert magic == FAT_MAGIC nfat_arch = ReadUInt32(file, '>') for index in xrange(0, nfat_arch): cputype, cpusubtype, offset, size, align = ReadFatArch(file) assert size >= 28 # HandleMachOFile will seek around. Come back here after calling it, in # case it sought. fat_arch_offset = file.tell() HandleMachOFile(file, options, offset) CheckedSeek(file, fat_arch_offset)
[ "def", "HandleFatFile", "(", "file", ",", "options", ",", "fat_offset", "=", "0", ")", ":", "CheckedSeek", "(", "file", ",", "fat_offset", ")", "magic", "=", "ReadUInt32", "(", "file", ",", "'>'", ")", "assert", "magic", "==", "FAT_MAGIC", "nfat_arch", "...
https://github.com/electron-archive/brightray/blob/3d9ebb549990d50ab67b705b8ff16433a3dbc546/tools/mac/change_mach_o_flags.py#L221-L239
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/algorithm_detail/slice_sans_event.py
python
_get_scaled_workspace
(workspace, factor)
return multiply_alg.getProperty("OutputWorkspace").value
Scales a workspace by a specified factor. :param workspace: the workspace to scale. :param factor: the scale factor. :return: the scaled workspace.
Scales a workspace by a specified factor.
[ "Scales", "a", "workspace", "by", "a", "specified", "factor", "." ]
def _get_scaled_workspace(workspace, factor): """ Scales a workspace by a specified factor. :param workspace: the workspace to scale. :param factor: the scale factor. :return: the scaled workspace. """ single_valued_name = "CreateSingleValuedWorkspace" single_valued_options = {"OutputWorkspace": EMPTY_NAME, "DataValue": factor} single_valued_alg = create_unmanaged_algorithm(single_valued_name, **single_valued_options) single_valued_alg.execute() single_valued_workspace = single_valued_alg.getProperty("OutputWorkspace").value multiply_name = "Multiply" multiply_options = {"LHSWorkspace": workspace, "RHSWorkspace": single_valued_workspace, "OutputWorkspace": EMPTY_NAME} multiply_alg = create_unmanaged_algorithm(multiply_name, **multiply_options) multiply_alg.execute() return multiply_alg.getProperty("OutputWorkspace").value
[ "def", "_get_scaled_workspace", "(", "workspace", ",", "factor", ")", ":", "single_valued_name", "=", "\"CreateSingleValuedWorkspace\"", "single_valued_options", "=", "{", "\"OutputWorkspace\"", ":", "EMPTY_NAME", ",", "\"DataValue\"", ":", "factor", "}", "single_valued_a...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/slice_sans_event.py#L116-L137
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiToolBar.GetToolIndex
(*args, **kwargs)
return _aui.AuiToolBar_GetToolIndex(*args, **kwargs)
GetToolIndex(self, int toolId) -> int
GetToolIndex(self, int toolId) -> int
[ "GetToolIndex", "(", "self", "int", "toolId", ")", "-", ">", "int" ]
def GetToolIndex(*args, **kwargs): """GetToolIndex(self, int toolId) -> int""" return _aui.AuiToolBar_GetToolIndex(*args, **kwargs)
[ "def", "GetToolIndex", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBar_GetToolIndex", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L2094-L2096
Yijunmaverick/GenerativeFaceCompletion
f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2
scripts/cpp_lint.py
python
_CppLintState.PrintErrorCounts
(self)
Print a summary of errors by category, and the total.
Print a summary of errors by category, and the total.
[ "Print", "a", "summary", "of", "errors", "by", "category", "and", "the", "total", "." ]
def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count)
[ "def", "PrintErrorCounts", "(", "self", ")", ":", "for", "category", ",", "count", "in", "self", ".", "errors_by_category", ".", "iteritems", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Category \\'%s\\' errors found: %d\\n'", "%", "(", "category...
https://github.com/Yijunmaverick/GenerativeFaceCompletion/blob/f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2/scripts/cpp_lint.py#L757-L762
lawy623/SVS
b7c7ae367c82a4797ff4a896a2ff304f02e7f724
caffe/scripts/cpp_lint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on compound # literals. closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or Search(r'\s+=\s*$', line_prefix)): match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", ...
https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/scripts/cpp_lint.py#L3069-L3240
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/reinforcement-learning/a3c/launcher.py
python
submit
(args)
Submit function of local jobs.
Submit function of local jobs.
[ "Submit", "function", "of", "local", "jobs", "." ]
def submit(args): gpus = args.gpus.strip().split(',') """Submit function of local jobs.""" def mthread_submit(nworker, nserver, envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters ---------- nworker: number of slave process to start up nserver: number of server nodes to start up envs: enviroment variables to be added to the starting programs """ procs = {} for i, gpu in enumerate(gpus): for j in range(args.num_threads): procs[i] = Thread(target=exec_cmd, args=(args.command + ['--gpus=%s'%gpu], 'worker', i*args.num_threads+j, envs)) procs[i].setDaemon(True) procs[i].start() for i in range(len(gpus)*args.num_threads, len(gpus)*args.num_threads + nserver): procs[i] = Thread(target=exec_cmd, args=(args.command, 'server', i, envs)) procs[i].setDaemon(True) procs[i].start() # call submit, with nslave, the commands to run each job and submit function tracker.submit(args.num_threads*len(gpus), args.num_servers, fun_submit=mthread_submit, pscmd=(' '.join(args.command)))
[ "def", "submit", "(", "args", ")", ":", "gpus", "=", "args", ".", "gpus", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "def", "mthread_submit", "(", "nworker", ",", "nserver", ",", "envs", ")", ":", "\"\"\"\n customized submit script, that...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/reinforcement-learning/a3c/launcher.py#L79-L106
tomahawk-player/tomahawk-resolvers
7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d
archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedCompositeFieldContainer.MergeFrom
(self, other)
Appends the contents of another repeated field of the same type to this one, copying each individual message.
Appends the contents of another repeated field of the same type to this one, copying each individual message.
[ "Appends", "the", "contents", "of", "another", "repeated", "field", "of", "the", "same", "type", "to", "this", "one", "copying", "each", "individual", "message", "." ]
def MergeFrom(self, other): """Appends the contents of another repeated field of the same type to this one, copying each individual message. """ self.extend(other._values)
[ "def", "MergeFrom", "(", "self", ",", "other", ")", ":", "self", ".", "extend", "(", "other", ".", "_values", ")" ]
https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/containers.py#L232-L236
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/generator/msvs.py
python
_GetMSBuildExternalBuilderTargets
(spec)
return targets
Return a list of MSBuild targets for external builders. The "Build" and "Clean" targets are always generated. If the spec contains 'msvs_external_builder_clcompile_cmd', then the "ClCompile" target will also be generated, to support building selected C/C++ files. Arguments: spec: The gyp target spec. Returns: List of MSBuild 'Target' specs.
Return a list of MSBuild targets for external builders.
[ "Return", "a", "list", "of", "MSBuild", "targets", "for", "external", "builders", "." ]
def _GetMSBuildExternalBuilderTargets(spec): """Return a list of MSBuild targets for external builders. The "Build" and "Clean" targets are always generated. If the spec contains 'msvs_external_builder_clcompile_cmd', then the "ClCompile" target will also be generated, to support building selected C/C++ files. Arguments: spec: The gyp target spec. Returns: List of MSBuild 'Target' specs. """ build_cmd = _BuildCommandLineForRuleRaw( spec, spec['msvs_external_builder_build_cmd'], False, False, False, False) build_target = ['Target', {'Name': 'Build'}] build_target.append(['Exec', {'Command': build_cmd}]) clean_cmd = _BuildCommandLineForRuleRaw( spec, spec['msvs_external_builder_clean_cmd'], False, False, False, False) clean_target = ['Target', {'Name': 'Clean'}] clean_target.append(['Exec', {'Command': clean_cmd}]) targets = [build_target, clean_target] if spec.get('msvs_external_builder_clcompile_cmd'): clcompile_cmd = _BuildCommandLineForRuleRaw( spec, spec['msvs_external_builder_clcompile_cmd'], False, False, False, False) clcompile_target = ['Target', {'Name': 'ClCompile'}] clcompile_target.append(['Exec', {'Command': clcompile_cmd}]) targets.append(clcompile_target) return targets
[ "def", "_GetMSBuildExternalBuilderTargets", "(", "spec", ")", ":", "build_cmd", "=", "_BuildCommandLineForRuleRaw", "(", "spec", ",", "spec", "[", "'msvs_external_builder_build_cmd'", "]", ",", "False", ",", "False", ",", "False", ",", "False", ")", "build_target", ...
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/msvs.py#L3346-L3380
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/shutil.py
python
_make_zipfile
(base_name, base_dir, verbose=0, dry_run=0, logger=None)
return zip_filename
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file.
Create a zip file from all the files under 'base_dir'.
[ "Create", "a", "zip", "file", "from", "all", "the", "files", "under", "base_dir", "." ]
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. """ zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # If zipfile module is not available, try spawning an external 'zip' # command. try: import zipfile except ImportError: zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) if logger is not None: logger.info("adding '%s'", path) zip.close() return zip_filename
[ "def", "_make_zipfile", "(", "base_name", ",", "base_dir", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "logger", "=", "None", ")", ":", "zip_filename", "=", "base_name", "+", "\".zip\"", "archive_dir", "=", "os", ".", "path", ".", "dirname",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/shutil.py#L455-L500
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tkinter.py
python
_flatten
(tuple)
return res
Internal function.
Internal function.
[ "Internal", "function", "." ]
def _flatten(tuple): """Internal function.""" res = () for item in tuple: if type(item) in (TupleType, ListType): res = res + _flatten(item) elif item is not None: res = res + (item,) return res
[ "def", "_flatten", "(", "tuple", ")", ":", "res", "=", "(", ")", "for", "item", "in", "tuple", ":", "if", "type", "(", "item", ")", "in", "(", "TupleType", ",", "ListType", ")", ":", "res", "=", "res", "+", "_flatten", "(", "item", ")", "elif", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L96-L104
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py
python
TarIter.__iter__
(self)
return self
Return iterator object.
Return iterator object.
[ "Return", "iterator", "object", "." ]
def __iter__(self): """Return iterator object. """ return self
[ "def", "__iter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L2565-L2568
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
swigibpy.py
python
EClient.cancelOrder
(self, id)
return _swigibpy.EClient_cancelOrder(self, id)
cancelOrder(EClient self, OrderId id)
cancelOrder(EClient self, OrderId id)
[ "cancelOrder", "(", "EClient", "self", "OrderId", "id", ")" ]
def cancelOrder(self, id): """cancelOrder(EClient self, OrderId id)""" return _swigibpy.EClient_cancelOrder(self, id)
[ "def", "cancelOrder", "(", "self", ",", "id", ")", ":", "return", "_swigibpy", ".", "EClient_cancelOrder", "(", "self", ",", "id", ")" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1130-L1132
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/addfunctiondialog/view.py
python
AddFunctionDialogView.is_text_in_function_list
(self, function: str)
return self.ui.functionBox.findText(function, Qt.MatchExactly) != -1
Return True if the given str is in the function list
Return True if the given str is in the function list
[ "Return", "True", "if", "the", "given", "str", "is", "in", "the", "function", "list" ]
def is_text_in_function_list(self, function: str) -> bool: """Return True if the given str is in the function list""" return self.ui.functionBox.findText(function, Qt.MatchExactly) != -1
[ "def", "is_text_in_function_list", "(", "self", ",", "function", ":", "str", ")", "->", "bool", ":", "return", "self", ".", "ui", ".", "functionBox", ".", "findText", "(", "function", ",", "Qt", ".", "MatchExactly", ")", "!=", "-", "1" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/addfunctiondialog/view.py#L68-L70
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py
python
Decimal.is_canonical
(self)
return True
Return True if self is canonical; otherwise return False. Currently, the encoding of a Decimal instance is always canonical, so this method returns True for any Decimal.
Return True if self is canonical; otherwise return False.
[ "Return", "True", "if", "self", "is", "canonical", ";", "otherwise", "return", "False", "." ]
def is_canonical(self): """Return True if self is canonical; otherwise return False. Currently, the encoding of a Decimal instance is always canonical, so this method returns True for any Decimal. """ return True
[ "def", "is_canonical", "(", "self", ")", ":", "return", "True" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L3007-L3013
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBQueue.__init__
(self, *args)
__init__(lldb::SBQueue self) -> SBQueue __init__(lldb::SBQueue self, lldb::QueueSP const & queue_sp) -> SBQueue
__init__(lldb::SBQueue self) -> SBQueue __init__(lldb::SBQueue self, lldb::QueueSP const & queue_sp) -> SBQueue
[ "__init__", "(", "lldb", "::", "SBQueue", "self", ")", "-", ">", "SBQueue", "__init__", "(", "lldb", "::", "SBQueue", "self", "lldb", "::", "QueueSP", "const", "&", "queue_sp", ")", "-", ">", "SBQueue" ]
def __init__(self, *args): """ __init__(lldb::SBQueue self) -> SBQueue __init__(lldb::SBQueue self, lldb::QueueSP const & queue_sp) -> SBQueue """ this = _lldb.new_SBQueue(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "this", "=", "_lldb", ".", "new_SBQueue", "(", "*", "args", ")", "try", ":", "self", ".", "this", ".", "append", "(", "this", ")", "except", "__builtin__", ".", "Exception", ":", "self", "...
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L9041-L9050
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintspointgrp.py
python
PointGroup.__init__
(self, *args)
Constructor
Constructor
[ "Constructor" ]
def __init__(self, *args): """Constructor""" # Schoenflies symbol self.symb = 'c1' # point of origin self.PYorigin = [0.0, 0.0, 0.0] # bit representation of point group self.PYbits = 0 # Divert to constructor functions # if len(args) == 0: # self.constructor_zero_ao_basis() if len(args) == 1 and \ isinstance(args[0], str): self.constructor_schoenflies(*args) elif len(args) == 1 and \ isinstance(args[0], int): self.constructor_bits(*args) elif len(args) == 2 and \ isinstance(args[0], str) and \ len(args[1]) == 3: self.constructor_schoenflies_origin(*args) elif len(args) == 2 and \ isinstance(args[0], int) and \ len(args[1]) == 3: self.constructor_bits_origin(*args) else: raise ValidationError('BasisSet::constructor: Inappropriate configuration of constructor arguments')
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "# Schoenflies symbol", "self", ".", "symb", "=", "'c1'", "# point of origin", "self", ".", "PYorigin", "=", "[", "0.0", ",", "0.0", ",", "0.0", "]", "# bit representation of point group", "self", "...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintspointgrp.py#L1512-L1540
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Driver.DeleteDataSource
(self, *args)
return _ogr.Driver_DeleteDataSource(self, *args)
r"""DeleteDataSource(Driver self, char const * utf8_path) -> int
r"""DeleteDataSource(Driver self, char const * utf8_path) -> int
[ "r", "DeleteDataSource", "(", "Driver", "self", "char", "const", "*", "utf8_path", ")", "-", ">", "int" ]
def DeleteDataSource(self, *args): r"""DeleteDataSource(Driver self, char const * utf8_path) -> int""" return _ogr.Driver_DeleteDataSource(self, *args)
[ "def", "DeleteDataSource", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "Driver_DeleteDataSource", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L536-L538
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/training/device_setter.py
python
_ReplicaDeviceChooser.__init__
(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops, ps_strategy)
Create a new `_ReplicaDeviceChooser`. Args: ps_tasks: Number of tasks in the `ps` job. ps_device: String. Name of the `ps` job. worker_device: String. Name of the `worker` job. merge_devices: Boolean. Set to True to allow merging of device specs. ps_ops: List of strings representing `Operation` types that need to be placed on `ps` devices. ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by `ps_ops`), that takes the `Operation` and returns the ps task index to use.
Create a new `_ReplicaDeviceChooser`.
[ "Create", "a", "new", "_ReplicaDeviceChooser", "." ]
def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops, ps_strategy): """Create a new `_ReplicaDeviceChooser`. Args: ps_tasks: Number of tasks in the `ps` job. ps_device: String. Name of the `ps` job. worker_device: String. Name of the `worker` job. merge_devices: Boolean. Set to True to allow merging of device specs. ps_ops: List of strings representing `Operation` types that need to be placed on `ps` devices. ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by `ps_ops`), that takes the `Operation` and returns the ps task index to use. """ self._ps_tasks = ps_tasks self._ps_device = ps_device self._worker_device = worker_device self._merge_devices = merge_devices self._ps_ops = ps_ops self._ps_strategy = ps_strategy
[ "def", "__init__", "(", "self", ",", "ps_tasks", ",", "ps_device", ",", "worker_device", ",", "merge_devices", ",", "ps_ops", ",", "ps_strategy", ")", ":", "self", ".", "_ps_tasks", "=", "ps_tasks", "self", ".", "_ps_device", "=", "ps_device", "self", ".", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/device_setter.py#L66-L86
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py
python
ungroup
(expr)
return TokenConverter(expr).setParseAction(lambda t:t[0])
Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty.
Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty.
[ "Helper", "to", "undo", "pyparsing", "s", "default", "grouping", "of", "And", "expressions", "even", "if", "all", "but", "one", "are", "non", "-", "empty", "." ]
def ungroup(expr): """ Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. """ return TokenConverter(expr).setParseAction(lambda t:t[0])
[ "def", "ungroup", "(", "expr", ")", ":", "return", "TokenConverter", "(", "expr", ")", ".", "setParseAction", "(", "lambda", "t", ":", "t", "[", "0", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py#L4718-L4723
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/pychan/__init__.py
python
setUnicodePolicy
(*policy)
Set the unicode error handling policy. Possible options are: - 'strict' meaning that encoding errors raise a UnicodeEncodeError. - 'ignore' all encoding errors will be silently ignored. - 'replace' all errors are replaced by the next argument. For further information look at the python documentation, especially C{codecs.register_error}. Example:: pychan.setUnicodePolicy('replace','?')
Set the unicode error handling policy. Possible options are: - 'strict' meaning that encoding errors raise a UnicodeEncodeError. - 'ignore' all encoding errors will be silently ignored. - 'replace' all errors are replaced by the next argument.
[ "Set", "the", "unicode", "error", "handling", "policy", ".", "Possible", "options", "are", ":", "-", "strict", "meaning", "that", "encoding", "errors", "raise", "a", "UnicodeEncodeError", ".", "-", "ignore", "all", "encoding", "errors", "will", "be", "silently...
def setUnicodePolicy(*policy): """ Set the unicode error handling policy. Possible options are: - 'strict' meaning that encoding errors raise a UnicodeEncodeError. - 'ignore' all encoding errors will be silently ignored. - 'replace' all errors are replaced by the next argument. For further information look at the python documentation, especially C{codecs.register_error}. Example:: pychan.setUnicodePolicy('replace','?') """ if not manager: raise InitializationError("PyChan is not initialized yet.") manager.unicodePolicy = policy
[ "def", "setUnicodePolicy", "(", "*", "policy", ")", ":", "if", "not", "manager", ":", "raise", "InitializationError", "(", "\"PyChan is not initialized yet.\"", ")", "manager", ".", "unicodePolicy", "=", "policy" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/__init__.py#L427-L444
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/tpu/python/tpu/tpu.py
python
outside_all_rewrites
()
Experimental API to 'break out' of a tpu.rewrite() (or shard(), etc.).
Experimental API to 'break out' of a tpu.rewrite() (or shard(), etc.).
[ "Experimental", "API", "to", "break", "out", "of", "a", "tpu", ".", "rewrite", "()", "(", "or", "shard", "()", "etc", ".", ")", "." ]
def outside_all_rewrites(): """Experimental API to 'break out' of a tpu.rewrite() (or shard(), etc.).""" with ops.control_dependencies(None): yield
[ "def", "outside_all_rewrites", "(", ")", ":", "with", "ops", ".", "control_dependencies", "(", "None", ")", ":", "yield" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tpu/python/tpu/tpu.py#L98-L101
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
dmlc-core/scripts/lint3.py
python
LintHelper.print_summary
(self, strm)
return nerr
Print summary of lint.
Print summary of lint.
[ "Print", "summary", "of", "lint", "." ]
def print_summary(self, strm): """Print summary of lint.""" nerr = 0 nerr += LintHelper._print_summary_map(strm, self.cpp_header_map, 'cpp-header') nerr += LintHelper._print_summary_map(strm, self.cpp_src_map, 'cpp-soruce') nerr += LintHelper._print_summary_map(strm, self.python_map, 'python') if nerr == 0: strm.write('All passed!\n') else: strm.write('%d files failed lint\n' % nerr) return nerr
[ "def", "print_summary", "(", "self", ",", "strm", ")", ":", "nerr", "=", "0", "nerr", "+=", "LintHelper", ".", "_print_summary_map", "(", "strm", ",", "self", ".", "cpp_header_map", ",", "'cpp-header'", ")", "nerr", "+=", "LintHelper", ".", "_print_summary_m...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/dmlc-core/scripts/lint3.py#L88-L98
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/internal/containers.py
python
RepeatedCompositeFieldContainer.__eq__
(self, other)
return self._values == other._values
Compares the current instance with another one.
Compares the current instance with another one.
[ "Compares", "the", "current", "instance", "with", "another", "one", "." ]
def __eq__(self, other): """Compares the current instance with another one.""" if self is other: return True if not isinstance(other, self.__class__): raise TypeError('Can only compare repeated composite fields against ' 'other repeated composite fields.') return self._values == other._values
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "self", "is", "other", ":", "return", "True", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "raise", "TypeError", "(", "'Can only compare repeated composite field...
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/containers.py#L309-L316
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/core.py
python
strip_protocol
(urlpath)
return cls._strip_protocol(urlpath)
Return only path part of full URL, according to appropriate backend
Return only path part of full URL, according to appropriate backend
[ "Return", "only", "path", "part", "of", "full", "URL", "according", "to", "appropriate", "backend" ]
def strip_protocol(urlpath): """Return only path part of full URL, according to appropriate backend""" protocol, _ = split_protocol(urlpath) cls = get_filesystem_class(protocol) return cls._strip_protocol(urlpath)
[ "def", "strip_protocol", "(", "urlpath", ")", ":", "protocol", ",", "_", "=", "split_protocol", "(", "urlpath", ")", "cls", "=", "get_filesystem_class", "(", "protocol", ")", "return", "cls", ".", "_strip_protocol", "(", "urlpath", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/core.py#L374-L378
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
python/caffe/pycaffe.py
python
_Net_backward
(self, diffs=None, start=None, end=None, **kwargs)
return {out: self.blobs[out].diff for out in outputs}
Backward pass: prepare diffs and run the net backward. Parameters ---------- diffs : list of diffs to return in addition to bottom diffs. kwargs : Keys are output blob names and values are diff ndarrays. If None, top diffs are taken from forward loss. start : optional name of layer at which to begin the backward pass end : optional name of layer at which to finish the backward pass (inclusive) Returns ------- outs: {blob name: diff ndarray} dict.
Backward pass: prepare diffs and run the net backward.
[ "Backward", "pass", ":", "prepare", "diffs", "and", "run", "the", "net", "backward", "." ]
def _Net_backward(self, diffs=None, start=None, end=None, **kwargs): """ Backward pass: prepare diffs and run the net backward. Parameters ---------- diffs : list of diffs to return in addition to bottom diffs. kwargs : Keys are output blob names and values are diff ndarrays. If None, top diffs are taken from forward loss. start : optional name of layer at which to begin the backward pass end : optional name of layer at which to finish the backward pass (inclusive) Returns ------- outs: {blob name: diff ndarray} dict. """ if diffs is None: diffs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = len(self.layers) - 1 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set(self.bottom_names[end] + diffs) else: end_ind = 0 outputs = set(self.inputs + diffs) if kwargs: if set(kwargs.keys()) != set(self.outputs): raise Exception('Top diff arguments do not match net outputs.') # Set top diffs according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for top, diff in six.iteritems(kwargs): if diff.shape[0] != self.blobs[top].shape[0]: raise Exception('Diff is not batch sized') self.blobs[top].diff[...] = diff self._backward(start_ind, end_ind) # Unpack diffs to extract return {out: self.blobs[out].diff for out in outputs}
[ "def", "_Net_backward", "(", "self", ",", "diffs", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "diffs", "is", "None", ":", "diffs", "=", "[", "]", "if", "start", "is", "not", "None", ...
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/pycaffe.py#L137-L182
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
external/tools/build/v2/tools/common.py
python
handle_options
(tool, condition, command, options)
Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags> in options - OPTIONS for compile.c++ to the value of <cxxflags> in options - OPTIONS for compile.fortran to the value of <fflags> in options - OPTIONs for link to the value of <linkflags> in options
Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags> in options - OPTIONS for compile.c++ to the value of <cxxflags> in options - OPTIONS for compile.fortran to the value of <fflags> in options - OPTIONs for link to the value of <linkflags> in options
[ "Handle", "common", "options", "for", "toolset", "specifically", "sets", "the", "following", "flag", "variables", ":", "-", "CONFIG_COMMAND", "to", "command", "-", "OPTIOns", "for", "compile", "to", "the", "value", "of", "<compileflags", ">", "in", "options", ...
def handle_options(tool, condition, command, options): """ Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags> in options - OPTIONS for compile.c++ to the value of <cxxflags> in options - OPTIONS for compile.fortran to the value of <fflags> in options - OPTIONs for link to the value of <linkflags> in options """ from b2.build import toolset assert(isinstance(tool, str)) assert(isinstance(condition, list)) assert(isinstance(command, str)) assert(isinstance(options, list)) assert(command) toolset.flags(tool, 'CONFIG_COMMAND', condition, [command]) toolset.flags(tool + '.compile', 'OPTIONS', condition, feature.get_values('<compileflags>', options)) toolset.flags(tool + '.compile.c', 'OPTIONS', condition, feature.get_values('<cflags>', options)) toolset.flags(tool + '.compile.c++', 'OPTIONS', condition, feature.get_values('<cxxflags>', options)) toolset.flags(tool + '.compile.fortran', 'OPTIONS', condition, feature.get_values('<fflags>', options)) toolset.flags(tool + '.link', 'OPTIONS', condition, feature.get_values('<linkflags>', options))
[ "def", "handle_options", "(", "tool", ",", "condition", ",", "command", ",", "options", ")", ":", "from", "b2", ".", "build", "import", "toolset", "assert", "(", "isinstance", "(", "tool", ",", "str", ")", ")", "assert", "(", "isinstance", "(", "conditio...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/tools/common.py#L423-L445
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/adapters.py
python
HTTPAdapter.request_url
(self, request, proxies)
return url
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str
Obtain the url to use when making the final request.
[ "Obtain", "the", "url", "to", "use", "when", "making", "the", "final", "request", "." ]
def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and scheme != 'https') using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url
[ "def", "request_url", "(", "self", ",", "request", ",", "proxies", ")", ":", "proxy", "=", "select_proxy", "(", "request", ".", "url", ",", "proxies", ")", "scheme", "=", "urlparse", "(", "request", ".", "url", ")", ".", "scheme", "is_proxied_http_request"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/adapters.py#L329-L356
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/tensor/logic.py
python
isclose
(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None)
return out
${comment} Args: x(Tensor): ${input_comment}. y(Tensor): ${other_comment}. rtol(rtoltype, optional): The relative tolerance. Default: :math:`1e-5` . atol(atoltype, optional): The absolute tolerance. Default: :math:`1e-8` . equal_nan(equalnantype, optional): ${equal_nan_comment}. name (str, optional): Name for the operation. For more information, please refer to :ref:`api_guide_Name`. Default: None. Returns: Tensor: ${out_comment}. Raises: TypeError: The data type of ``x`` must be one of float32, float64. TypeError: The data type of ``y`` must be one of float32, float64. TypeError: The type of ``rtol`` must be float. TypeError: The type of ``atol`` must be float. TypeError: The type of ``equal_nan`` must be bool. Examples: .. code-block:: python import paddle x = paddle.to_tensor([10000., 1e-07]) y = paddle.to_tensor([10000.1, 1e-08]) result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name="ignore_nan") np_result1 = result1.numpy() # [True, False] result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=True, name="equal_nan") np_result2 = result2.numpy() # [True, False] x = paddle.to_tensor([1.0, float('nan')]) y = paddle.to_tensor([1.0, float('nan')]) result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name="ignore_nan") np_result1 = result1.numpy() # [True, False] result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=True, name="equal_nan") np_result2 = result2.numpy() # [True, True]
${comment}
[ "$", "{", "comment", "}" ]
def isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None): """ ${comment} Args: x(Tensor): ${input_comment}. y(Tensor): ${other_comment}. rtol(rtoltype, optional): The relative tolerance. Default: :math:`1e-5` . atol(atoltype, optional): The absolute tolerance. Default: :math:`1e-8` . equal_nan(equalnantype, optional): ${equal_nan_comment}. name (str, optional): Name for the operation. For more information, please refer to :ref:`api_guide_Name`. Default: None. Returns: Tensor: ${out_comment}. Raises: TypeError: The data type of ``x`` must be one of float32, float64. TypeError: The data type of ``y`` must be one of float32, float64. TypeError: The type of ``rtol`` must be float. TypeError: The type of ``atol`` must be float. TypeError: The type of ``equal_nan`` must be bool. Examples: .. code-block:: python import paddle x = paddle.to_tensor([10000., 1e-07]) y = paddle.to_tensor([10000.1, 1e-08]) result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name="ignore_nan") np_result1 = result1.numpy() # [True, False] result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=True, name="equal_nan") np_result2 = result2.numpy() # [True, False] x = paddle.to_tensor([1.0, float('nan')]) y = paddle.to_tensor([1.0, float('nan')]) result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name="ignore_nan") np_result1 = result1.numpy() # [True, False] result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=True, name="equal_nan") np_result2 = result2.numpy() # [True, True] """ if in_dygraph_mode(): return _C_ops.isclose(x, y, 'rtol', str(rtol), 'atol', str(atol), 'equal_nan', equal_nan) check_variable_and_dtype(x, "input", ['float32', 'float64'], 'isclose') check_variable_and_dtype(y, "input", ['float32', 'float64'], 'isclose') check_type(rtol, 'rtol', float, 'isclose') check_type(atol, 'atol', float, 'isclose') check_type(equal_nan, 'equal_nan', bool, 'isclose') helper = LayerHelper("isclose", **locals()) out = helper.create_variable_for_type_inference(dtype='bool') inputs = {'Input': x, 'Other': y} outputs = {'Out': out} attrs = {'rtol': str(rtol), 'atol': str(atol), 'equal_nan': equal_nan} helper.append_op( type='isclose', inputs=inputs, outputs=outputs, attrs=attrs) return out
[ "def", "isclose", "(", "x", ",", "y", ",", "rtol", "=", "1e-05", ",", "atol", "=", "1e-08", ",", "equal_nan", "=", "False", ",", "name", "=", "None", ")", ":", "if", "in_dygraph_mode", "(", ")", ":", "return", "_C_ops", ".", "isclose", "(", "x", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/logic.py#L589-L659
jubatus/jubatus
1251ce551bac980488a6313728e72b3fe0b79a9f
tools/codestyle/cpplint/cpplint.py
python
_CppLintState.SetFilters
(self, filters)
Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
Sets the error-message filters.
[ "Sets", "the", "error", "-", "message", "filters", "." ]
def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt)
[ "def", "SetFilters", "(", "self", ",", "filters", ")", ":", "# Default filters always have less priority than the flag ones.", "self", ".", "filters", "=", "_DEFAULT_FILTERS", "[", ":", "]", "for", "filt", "in", "filters", ".", "split", "(", "','", ")", ":", "cl...
https://github.com/jubatus/jubatus/blob/1251ce551bac980488a6313728e72b3fe0b79a9f/tools/codestyle/cpplint/cpplint.py#L536-L559
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/memory_inspector/memory_inspector/frontends/www_server.py
python
_GetProfileTreeDataForSnapshot
(args, req_vars)
return _HTTP_OK, [], resp
Gets the data for the tree chart for a given time and metric. The response is formatted according to the Google Charts DataTable format.
Gets the data for the tree chart for a given time and metric.
[ "Gets", "the", "data", "for", "the", "tree", "chart", "for", "a", "given", "time", "and", "metric", "." ]
def _GetProfileTreeDataForSnapshot(args, req_vars): # pylint: disable=W0613 """Gets the data for the tree chart for a given time and metric. The response is formatted according to the Google Charts DataTable format. """ snapshot_id = args[0] metric_index = int(args[1]) time = int(args[2]) snapshots = _GetCacheObject(snapshot_id) if not snapshots: return _HTTP_GONE, [], 'Cannot find the selected profile.' if time not in snapshots: return _HTTP_GONE, [], 'Cannot find snapshot at T=%d.' % time snapshot = snapshots[time] if metric_index >= len(snapshot.keys): return _HTTP_GONE, [], 'Invalid metric id %d' % metric_index resp = {'cols': [{'label': 'bucket', 'type': 'string'}, {'label': 'parent', 'type': 'string'}], 'rows': []} def VisitBucketAndAddRows(bucket, parent_id=''): """Recursively creates the (node, parent) visiting |ResultTree| in DFS.""" node_id = parent_id + bucket.name + '/' node_label = '<dl><dt>%s</dt><dd>%s</dd></dl>' % ( bucket.name, _StrMem(bucket.values[metric_index])) resp['rows'] += [{'c': [ {'v': node_id, 'f': node_label}, {'v': parent_id, 'f': None}, ]}] for child in bucket.children: VisitBucketAndAddRows(child, node_id) VisitBucketAndAddRows(snapshot.total) return _HTTP_OK, [], resp
[ "def", "_GetProfileTreeDataForSnapshot", "(", "args", ",", "req_vars", ")", ":", "# pylint: disable=W0613", "snapshot_id", "=", "args", "[", "0", "]", "metric_index", "=", "int", "(", "args", "[", "1", "]", ")", "time", "=", "int", "(", "args", "[", "2", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/memory_inspector/memory_inspector/frontends/www_server.py#L262-L296
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.AdjustLibraries
(self, libraries)
return libraries
Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc.
Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc.
[ "Transforms", "entries", "like", "Cocoa", ".", "framework", "in", "libraries", "into", "entries", "like", "-", "framework", "Cocoa", "libcrypto", ".", "dylib", "into", "-", "lcrypto", "etc", "." ]
def AdjustLibraries(self, libraries): """Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. """ libraries = [ self._AdjustLibrary(library) for library in libraries] return libraries
[ "def", "AdjustLibraries", "(", "self", ",", "libraries", ")", ":", "libraries", "=", "[", "self", ".", "_AdjustLibrary", "(", "library", ")", "for", "library", "in", "libraries", "]", "return", "libraries" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcode_emulation.py#L671-L676
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/nn_ops.py
python
gelu
(features, approximate=False, name=None)
Compute the Gaussian Error Linear Unit (GELU) activation function. Gaussian error linear unit (GELU) computes `x * P(X <= x)`, where `P(X) ~ N(0, 1)`. The (GELU) nonlinearity weights inputs by their value, rather than gates inputs by their sign as in ReLU. For example: >>> x = tf.constant([-3.0, -1.0, 0.0, 1.0, 3.0], dtype=tf.float32) >>> y = tf.nn.gelu(x) >>> y.numpy() array([-0.00404951, -0.15865529, 0. , 0.8413447 , 2.9959507 ], dtype=float32) >>> y = tf.nn.gelu(x, approximate=True) >>> y.numpy() array([-0.00363752, -0.15880796, 0. , 0.841192 , 2.9963627 ], dtype=float32) Args: features: A `Tensor` representing preactivation values. approximate: An optional `bool`. Defaults to `False`. Whether to enable approximation. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `features`. References: [Gaussian Error Linear Units (GELUs)](https://arxiv.org/abs/1606.08415).
Compute the Gaussian Error Linear Unit (GELU) activation function.
[ "Compute", "the", "Gaussian", "Error", "Linear", "Unit", "(", "GELU", ")", "activation", "function", "." ]
def gelu(features, approximate=False, name=None): """Compute the Gaussian Error Linear Unit (GELU) activation function. Gaussian error linear unit (GELU) computes `x * P(X <= x)`, where `P(X) ~ N(0, 1)`. The (GELU) nonlinearity weights inputs by their value, rather than gates inputs by their sign as in ReLU. For example: >>> x = tf.constant([-3.0, -1.0, 0.0, 1.0, 3.0], dtype=tf.float32) >>> y = tf.nn.gelu(x) >>> y.numpy() array([-0.00404951, -0.15865529, 0. , 0.8413447 , 2.9959507 ], dtype=float32) >>> y = tf.nn.gelu(x, approximate=True) >>> y.numpy() array([-0.00363752, -0.15880796, 0. , 0.841192 , 2.9963627 ], dtype=float32) Args: features: A `Tensor` representing preactivation values. approximate: An optional `bool`. Defaults to `False`. Whether to enable approximation. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `features`. References: [Gaussian Error Linear Units (GELUs)](https://arxiv.org/abs/1606.08415). """ with ops.name_scope(name, "Gelu", [features]): features = ops.convert_to_tensor(features, name="features") if approximate: coeff = math_ops.cast(0.044715, features.dtype) return 0.5 * features * ( 1.0 + math_ops.tanh(0.7978845608028654 * (features + coeff * math_ops.pow(features, 3)))) else: return 0.5 * features * (1.0 + math_ops.erf( features / math_ops.cast(1.4142135623730951, features.dtype)))
[ "def", "gelu", "(", "features", ",", "approximate", "=", "False", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"Gelu\"", ",", "[", "features", "]", ")", ":", "features", "=", "ops", ".", "convert_to_tensor",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/nn_ops.py#L3668-L3709
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/scripts/cpp_lint.py
python
GetHeaderGuardCPPVariable
(filename)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file.
Returns the CPP variable that should be used as a header guard.
[ "Returns", "the", "CPP", "variable", "that", "should", "be", "used", "as", "a", "header", "guard", "." ]
def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
[ "def", "GetHeaderGuardCPPVariable", "(", "filename", ")", ":", "# Restores original filename in case that cpplint is invoked from Emacs's", "# flymake.", "filename", "=", "re", ".", "sub", "(", "r'_flymake\\.h$'", ",", "'.h'", ",", "filename", ")", "filename", "=", "re", ...
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/scripts/cpp_lint.py#L1388-L1409
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/mooseutils/csvdiff.py
python
CSVTools.convertToTable
(self, files)
return table_pair
Convert text to a map of column names to column values
Convert text to a map of column names to column values
[ "Convert", "text", "to", "a", "map", "of", "column", "names", "to", "column", "values" ]
def convertToTable(self, files): """Convert text to a map of column names to column values""" table_pair = [] for f in files: f.seek(0) text = f.read() text = re.sub( r'\n\s*\n', '\n', text).strip() # Exceptions occur if you try to parse a .e file try: lines = text.split('\n') headers = [x.strip() for x in lines.pop(0).split(',')] table = {} for header in headers: table[header] = [] for row in lines: vals = row.split(',') if len(headers) != len(vals): self.addError(f, "Number of columns ("+str(len(vals))+") not the same as number of column names ("+str(len(headers))+") in row "+repr(row)) break for header, val in zip(headers,vals): try: table[header].append(float(val)) except: # ignore strings table[header].append(0) except Exception as e: self.addError(f, "Exception parsing file: "+str(e.args)) return {} table_pair.append(table) return table_pair
[ "def", "convertToTable", "(", "self", ",", "files", ")", ":", "table_pair", "=", "[", "]", "for", "f", "in", "files", ":", "f", ".", "seek", "(", "0", ")", "text", "=", "f", ".", "read", "(", ")", "text", "=", "re", ".", "sub", "(", "r'\\n\\s*\...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/csvdiff.py#L37-L71
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_message.py
python
Message.clear
(self)
Clears the contents of the :class:`Message`. All fields will be reset to their default values.
Clears the contents of the :class:`Message`. All fields will be reset to their default values.
[ "Clears", "the", "contents", "of", "the", ":", "class", ":", "Message", ".", "All", "fields", "will", "be", "reset", "to", "their", "default", "values", "." ]
def clear(self) -> None: """ Clears the contents of the :class:`Message`. All fields will be reset to their default values. """ pn_message_clear(self._msg) self.instructions = None self.annotations = None self.properties = None self.body = None
[ "def", "clear", "(", "self", ")", "->", "None", ":", "pn_message_clear", "(", "self", ".", "_msg", ")", "self", ".", "instructions", "=", "None", "self", ".", "annotations", "=", "None", "self", ".", "properties", "=", "None", "self", ".", "body", "=",...
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_message.py#L164-L173
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/TaskGen.py
python
process_subst
(self)
Define a transformation that substitutes the contents of *source* files to *target* files:: def build(bld): bld( features='subst', source='foo.c.in', target='foo.c', install_path='${LIBDIR}/pkgconfig', VAR = 'val' ) The input files are supposed to contain macros of the form *@VAR@*, where *VAR* is an argument of the task generator object. This method overrides the processing by :py:meth:`waflib.TaskGen.process_source`.
Define a transformation that substitutes the contents of *source* files to *target* files::
[ "Define", "a", "transformation", "that", "substitutes", "the", "contents", "of", "*", "source", "*", "files", "to", "*", "target", "*", "files", "::" ]
def process_subst(self): """ Define a transformation that substitutes the contents of *source* files to *target* files:: def build(bld): bld( features='subst', source='foo.c.in', target='foo.c', install_path='${LIBDIR}/pkgconfig', VAR = 'val' ) The input files are supposed to contain macros of the form *@VAR@*, where *VAR* is an argument of the task generator object. This method overrides the processing by :py:meth:`waflib.TaskGen.process_source`. """ src = Utils.to_list(getattr(self, 'source', [])) if isinstance(src, Node.Node): src = [src] tgt = Utils.to_list(getattr(self, 'target', [])) if isinstance(tgt, Node.Node): tgt = [tgt] if len(src) != len(tgt): raise Errors.WafError('invalid number of source/target for %r' % self) for x, y in zip(src, tgt): if not x or not y: raise Errors.WafError('null source or target for %r' % self) a, b = None, None if isinstance(x, str) and isinstance(y, str) and x == y: a = self.path.find_node(x) b = self.path.get_bld().make_node(y) if not os.path.isfile(b.abspath()): b.sig = None b.parent.mkdir() else: if isinstance(x, str): a = self.path.find_resource(x) elif isinstance(x, Node.Node): a = x if isinstance(y, str): b = self.path.find_or_declare(y) elif isinstance(y, Node.Node): b = y if not a: raise Errors.WafError('cound not find %r for %r' % (x, self)) has_constraints = False tsk = self.create_task('subst', a, b) for k in ('after', 'before', 'ext_in', 'ext_out'): val = getattr(self, k, None) if val: has_constraints = True setattr(tsk, k, val) # paranoid safety measure for the general case foo.in->foo.h with ambiguous dependencies if not has_constraints and b.name.endswith('.h'): tsk.before = [k for k in ('c', 'cxx') if k in Task.classes] inst_to = getattr(self, 'install_path', None) if inst_to: self.bld.install_files(inst_to, b, chmod=getattr(self, 'chmod', Utils.O644)) self.source = []
[ "def", "process_subst", "(", "self", ")", ":", "src", "=", "Utils", ".", "to_list", "(", "getattr", "(", "self", ",", "'source'", ",", "[", "]", ")", ")", "if", "isinstance", "(", "src", ",", "Node", ".", "Node", ")", ":", "src", "=", "[", "src",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/TaskGen.py#L752-L820
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/fast_rcnn/train_multi_gpu.py
python
train_net_multi_gpu
(solver_prototxt, roidb, output_dir, pretrained_model, max_iter, gpus)
Train a Fast R-CNN network.
Train a Fast R-CNN network.
[ "Train", "a", "Fast", "R", "-", "CNN", "network", "." ]
def train_net_multi_gpu(solver_prototxt, roidb, output_dir, pretrained_model, max_iter, gpus): """Train a Fast R-CNN network.""" uid = caffe.NCCL.new_uid() caffe.init_log() caffe.log('Using devices %s' % str(gpus)) procs = [] for rank in range(len(gpus)): p = Process(target=solve, args=(solver_prototxt, roidb, pretrained_model, gpus, uid, rank, output_dir, max_iter)) p.daemon = False p.start() procs.append(p) for p in procs: p.join()
[ "def", "train_net_multi_gpu", "(", "solver_prototxt", ",", "roidb", ",", "output_dir", ",", "pretrained_model", ",", "max_iter", ",", "gpus", ")", ":", "uid", "=", "caffe", ".", "NCCL", ".", "new_uid", "(", ")", "caffe", ".", "init_log", "(", ")", "caffe",...
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/fast_rcnn/train_multi_gpu.py#L203-L217
cvmfs/cvmfs
4637bdb5153178eadf885c1acf37bdc5c685bf8a
cpplint.py
python
IsOutOfLineMethodDefinition
(clean_lines, linenum)
return False
Check if current line contains an out-of-line method definition. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line contains an out-of-line method definition.
Check if current line contains an out-of-line method definition.
[ "Check", "if", "current", "line", "contains", "an", "out", "-", "of", "-", "line", "method", "definition", "." ]
def IsOutOfLineMethodDefinition(clean_lines, linenum): """Check if current line contains an out-of-line method definition. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line contains an out-of-line method definition. """ # Scan back a few lines for start of current function for i in xrange(linenum, max(-1, linenum - 10), -1): if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]): return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None return False
[ "def", "IsOutOfLineMethodDefinition", "(", "clean_lines", ",", "linenum", ")", ":", "# Scan back a few lines for start of current function", "for", "i", "in", "xrange", "(", "linenum", ",", "max", "(", "-", "1", ",", "linenum", "-", "10", ")", ",", "-", "1", "...
https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L5025-L5038
facebook/fbthrift
fb9c8562aba04c4fd9b17716eb5d970cc88a75bb
build/fbcode_builder/getdeps/fetcher.py
python
ArchiveFetcher._download_dir
(self)
return download_dir
returns the download dir, creating it if it doesn't already exist
returns the download dir, creating it if it doesn't already exist
[ "returns", "the", "download", "dir", "creating", "it", "if", "it", "doesn", "t", "already", "exist" ]
def _download_dir(self): """returns the download dir, creating it if it doesn't already exist""" download_dir = os.path.dirname(self.file_name) if not os.path.exists(download_dir): os.makedirs(download_dir) return download_dir
[ "def", "_download_dir", "(", "self", ")", ":", "download_dir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "file_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "download_dir", ")", ":", "os", ".", "makedirs", "(", "down...
https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/getdeps/fetcher.py#L729-L734
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
bingo/bingo-elastic/python/bingo_elastic/elastic.py
python
ElasticRepository.__init__
( self, index_name: IndexName, *, host: Union[str, List[str]] = "localhost", port: int = 9200, scheme: str = "", http_auth: Optional[Tuple[str]] = None, ssl_context: Any = None, request_timeout: int = 60, retry_on_timeout: bool = True, )
:param index_name: use function get_index_name for setting this argument :param host: host or list of hosts :param port: :param scheme: http or https :param http_auth: :param ssl_context: :param timeout: :param retry_on_timeout:
:param index_name: use function get_index_name for setting this argument :param host: host or list of hosts :param port: :param scheme: http or https :param http_auth: :param ssl_context: :param timeout: :param retry_on_timeout:
[ ":", "param", "index_name", ":", "use", "function", "get_index_name", "for", "setting", "this", "argument", ":", "param", "host", ":", "host", "or", "list", "of", "hosts", ":", "param", "port", ":", ":", "param", "scheme", ":", "http", "or", "https", ":"...
def __init__( self, index_name: IndexName, *, host: Union[str, List[str]] = "localhost", port: int = 9200, scheme: str = "", http_auth: Optional[Tuple[str]] = None, ssl_context: Any = None, request_timeout: int = 60, retry_on_timeout: bool = True, ) -> None: """ :param index_name: use function get_index_name for setting this argument :param host: host or list of hosts :param port: :param scheme: http or https :param http_auth: :param ssl_context: :param timeout: :param retry_on_timeout: """ arguments = { "port": port, "scheme": "https" if scheme == "https" else "http", "request_timeout": request_timeout, "retry_on_timeout": retry_on_timeout, } if isinstance(host, str): arguments["host"] = host else: arguments["hosts"] = host if http_auth: arguments["http_auth"] = http_auth if ssl_context: arguments["ssl_context"] = ssl_context self.index_name = index_name.value self.el_client = Elasticsearch(**arguments)
[ "def", "__init__", "(", "self", ",", "index_name", ":", "IndexName", ",", "*", ",", "host", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "=", "\"localhost\"", ",", "port", ":", "int", "=", "9200", ",", "scheme", ":", "str", "=", "...
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/bingo/bingo-elastic/python/bingo_elastic/elastic.py#L50-L91
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/framework/device.py
python
DeviceSpec.__init__
(self, job=None, replica=None, task=None, device_type=None, device_index=None)
Create a new `DeviceSpec` object. Args: job: string. Optional job name. replica: int. Optional replica index. task: int. Optional task index. device_type: Optional device type string (e.g. "CPU" or "GPU") device_index: int. Optional device index. If left unspecified, device represents 'any' device_index.
Create a new `DeviceSpec` object.
[ "Create", "a", "new", "DeviceSpec", "object", "." ]
def __init__(self, job=None, replica=None, task=None, device_type=None, device_index=None): """Create a new `DeviceSpec` object. Args: job: string. Optional job name. replica: int. Optional replica index. task: int. Optional task index. device_type: Optional device type string (e.g. "CPU" or "GPU") device_index: int. Optional device index. If left unspecified, device represents 'any' device_index. """ self.job = job self.replica = replica self.task = task if device_type == "cpu" or device_type == "gpu": # For backwards compatibility only, we support lowercase variants of # cpu and gpu but turn them into uppercase here. self.device_type = device_type.upper() else: self.device_type = device_type self.device_index = device_index
[ "def", "__init__", "(", "self", ",", "job", "=", "None", ",", "replica", "=", "None", ",", "task", "=", "None", ",", "device_type", "=", "None", ",", "device_index", "=", "None", ")", ":", "self", ".", "job", "=", "job", "self", ".", "replica", "="...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/device.py#L65-L86
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ast.py
python
iter_fields
(node)
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*.
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*.
[ "Yield", "a", "tuple", "of", "(", "fieldname", "value", ")", "for", "each", "field", "in", "node", ".", "_fields", "that", "is", "present", "on", "*", "node", "*", "." ]
def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass
[ "def", "iter_fields", "(", "node", ")", ":", "for", "field", "in", "node", ".", "_fields", ":", "try", ":", "yield", "field", ",", "getattr", "(", "node", ",", "field", ")", "except", "AttributeError", ":", "pass" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ast.py#L161-L170
apache/incubator-weex
5c25f0b59f7ac90703c363e7261f60bd06356dbe
weex_core/tools/cpplint.py
python
CheckCasts
(filename, clean_lines, linenum, error)
Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Various cast related checks.
[ "Various", "cast", "related", "checks", "." ]
def CheckCasts(filename, clean_lines, linenum, error): """Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b' r'(int|float|double|bool|char|int32|uint32|int64|uint64)' r'(\([^)].*)', line) expecting_function = ExpectingFunctionArgs(clean_lines, linenum) if match and not expecting_function: matched_type = match.group(2) # matched_new_or_template is used to silence two false positives: # - New operators # - Template arguments with function types # # For template arguments, we match on types immediately following # an opening bracket without any spaces. This is a fast way to # silence the common case where the function type is the first # template argument. False negative with less-than comparison is # avoided because those operators are usually followed by a space. # # function<double(double)> // bracket + no space = false positive # value < double(42) // bracket + space = true positive matched_new_or_template = match.group(1) # Avoid arrays by looking for brackets that come after the closing # parenthesis. if Match(r'\([^()]+\)\s*\[', match.group(3)): return # Other things to ignore: # - Function pointers # - Casts to pointer types # - Placement new # - Alias declarations matched_funcptr = match.group(3) if (matched_new_or_template is None and not (matched_funcptr and (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', matched_funcptr) or matched_funcptr.startswith('(*)'))) and not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and not Search(r'new\(\S+\)\s*' + matched_type, line)): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % matched_type) if not expecting_function: CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. # # Some non-identifier character is required before the '&' for the # expression to be recognized as a cast. These are casts: # expression = &static_cast<int*>(temporary()); # function(&(int*)(temporary())); # # This is not a cast: # reference_type&(int* function_param); match = Search( r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) if match: # Try a better error message when the & is bound to something # dereferenced by the casted pointer, as opposed to the casted # pointer itself. parenthesis_error = False match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) if match: _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) if x1 >= 0 and clean_lines.elided[y1][x1] == '(': _, y2, x2 = CloseExpression(clean_lines, y1, x1) if x2 >= 0: extended_line = clean_lines.elided[y2][x2:] if y2 < clean_lines.NumLines() - 1: extended_line += clean_lines.elided[y2 + 1] if Match(r'\s*(?:->|\[)', extended_line): parenthesis_error = True if parenthesis_error: error(filename, linenum, 'readability/casting', 4, ('Are you taking an address of something dereferenced ' 'from a cast? Wrapping the dereferenced expression in ' 'parentheses will make the binding more obvious')) else: error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after'))
[ "def", "CheckCasts", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Check to see if they're using an conversion function cast.", "# I just try to capture the most common basic t...
https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/tools/cpplint.py#L5152-L5268
tangzhenyu/Scene-Text-Understanding
0f7ffc7aea5971a50cdc03d33d0a41075285948b
SynthText_Chinese/colorize3_poisson.py
python
FontColor.triangle_color
(self, col1, col2)
return np.squeeze(cv.cvtColor(col1[None,None,:],cv.cv.CV_HSV2RGB))
Returns a color which is "opposite" to both col1 and col2.
Returns a color which is "opposite" to both col1 and col2.
[ "Returns", "a", "color", "which", "is", "opposite", "to", "both", "col1", "and", "col2", "." ]
def triangle_color(self, col1, col2): """ Returns a color which is "opposite" to both col1 and col2. """ col1, col2 = np.array(col1), np.array(col2) col1 = np.squeeze(cv.cvtColor(col1[None,None,:], cv.cv.CV_RGB2HSV)) col2 = np.squeeze(cv.cvtColor(col2[None,None,:], cv.cv.CV_RGB2HSV)) h1, h2 = col1[0], col2[0] if h2 < h1 : h1,h2 = h2,h1 #swap dh = h2-h1 if dh < 127: dh = 255-dh col1[0] = h1 + dh/2 return np.squeeze(cv.cvtColor(col1[None,None,:],cv.cv.CV_HSV2RGB))
[ "def", "triangle_color", "(", "self", ",", "col1", ",", "col2", ")", ":", "col1", ",", "col2", "=", "np", ".", "array", "(", "col1", ")", ",", "np", ".", "array", "(", "col2", ")", "col1", "=", "np", ".", "squeeze", "(", "cv", ".", "cvtColor", ...
https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/colorize3_poisson.py#L113-L125
gemrb/gemrb
730206eed8d1dd358ca5e69a62f9e099aa22ffc6
gemrb/GUIScripts/LevelUp.py
python
GetLevelUpNews
()
return News
Returns a string containing improvements gain on level up. These include: HP, spells per level, and lore, among others.
Returns a string containing improvements gain on level up.
[ "Returns", "a", "string", "containing", "improvements", "gain", "on", "level", "up", "." ]
def GetLevelUpNews(): """Returns a string containing improvements gain on level up. These include: HP, spells per level, and lore, among others.""" News = GemRB.GetString (5259) + '\n\n' # display if our class has been reactivated if IsDual: if (Level[0] - LevelDiff[0]) <= Level[1] and Level[0] > Level[1]: News = GemRB.GetString (5261) + '\n\n' # 5271 - Additional weapon proficiencies if NewProfPoints > 0: News += GemRB.GetString (5271) + ": " + str(NewProfPoints) + '\n\n' # temps to compare all our new saves against (we get the best of our saving throws) LOHGain = 0 BackstabMult = 0 for i in range(NumClasses): # get the class name TmpClassName = GUICommon.GetClassRowName (Classes[i], "class") # backstab # NOTE: Stalkers and assassins should get the correct mods at the correct levels based # on AP_SPCL332 in their respective CLAB files. # APND: Stalkers appear to get the correct mod at the correct levels; however, because they start # at backstab multi x1, they are x1 too many at their respective levels. if Classes[i] == 4 and GemRB.GetPlayerStat (pc, IE_BACKSTABDAMAGEMULTIPLIER, 1) > 1: # we have a thief who can backstab (2 at level 1) # save the backstab multiplier if we have a thief BackstabTable = GemRB.LoadTable ("BACKSTAB") BackstabMult = BackstabTable.GetValue (0, Level[i]) # lay on hands LOHTable = CommonTables.ClassSkills.GetValue (TmpClassName, "LAYHANDS") if LOHTable != "*": # inquisitors and undead hunters don't get lay on hands out the chute, whereas cavaliers # and unkitted paladins do; therefore, we check for the existence of lay on hands to ensure # the character should get the new value; LoH is defined in GA_SPCL211 if anyone wants to # make a pally kit with LoH if (Spellbook.HasSpell (pc, IE_SPELL_TYPE_INNATE, 0, "SPCL211") >= 0): LOHTable = GemRB.LoadTable (LOHTable) LOHGain = LOHTable.GetValue (0, Level[i]) - LOHTable.GetValue (0, Level[i]-LevelDiff[i]) # saving throws # 5277 death # 5278 wand # 5279 polymorph # 5282 breath # 5292 spell # include in news if the save is updated Changed = 0 for i in range (5): CurrentSave = GemRB.GetPlayerStat (pc, IE_SAVEVSDEATH+i, 1) SaveString = 5277+i if i == 3: SaveString = 5282 elif i == 4: SaveString = 5292 if CurrentSave < OldSaves[i]: News += GemRB.GetString (SaveString) + ": " + str(OldSaves[i]-CurrentSave) + '\n' Changed = 1 if Changed: News += '\n' # 5305 - THAC0 Reduced by # only output if there is a change in thaco NewThaco = GemRB.GetPlayerStat (pc, IE_TOHIT, 1) if (NewThaco < OldThaco): News += GemRB.GetString (5305) + ": " + str(OldThaco-NewThaco) + '\n\n' # new spell slots # 5373 - Additional Priest Spells # 5374 - Additional Mage Spells # 61269 - Level <LEVEL> Spells if DeltaDSpells > 0: # new divine spells News += GemRB.GetString (5373) + '\n' for i in range (len (NewDSpells)): # only display classes with new spells if (NewDSpells[i]-OldDSpells[i]) == 0: continue GemRB.SetToken("level", str(i+1)) News += GemRB.GetString(61269)+": " + str(NewDSpells[i]-OldDSpells[i]) + '\n' News += '\n' if DeltaWSpells > 0: # new wizard spells News += GemRB.GetString (5374) + '\n' for i in range (len (NewWSpells)): # only display classes with new spells if (NewWSpells[i]-OldWSpells[i]) == 0: continue GemRB.SetToken("level", str(i+1)) News += GemRB.GetString(61269)+": " + str(NewWSpells[i]-OldWSpells[i]) + '\n' News += '\n' # 5375 - Backstab Multiplier Increased by # this auto-updates... we just need to inform of the update BSGain = BackstabMult - GemRB.GetPlayerStat (pc, IE_BACKSTABDAMAGEMULTIPLIER, 1) if (BSGain > 0): News += GemRB.GetString (5375) + ": " + str(BSGain) + '\n\n' # 5376 - Lay on Hands increased if LOHGain > 0: News += GemRB.GetString (5376) + ": " + str(LOHGain) + '\n\n' # 5293 - HP increased by if (OldHPMax != GemRB.GetPlayerStat (pc, IE_MAXHITPOINTS, 1)): News += GemRB.GetString (5293) + ": " + str(GemRB.GetPlayerStat (pc, IE_MAXHITPOINTS, 1) - OldHPMax) + '\n' # 5377 - Lore Increased by # add the lore gain if we haven't done so already NewLore = GemRB.GetPlayerStat (pc, IE_LORE, 1) if NewLore > OldLore: News += GemRB.GetString (5377) + ": " + str(NewLore-OldLore) + '\n\n' # 5378 - Additional Skill Points # ranger and bard skill(point) gain is not mentioned here in the original if NewSkillPoints > 0: News += GemRB.GetString (5378) + ": " + str(NewSkillPoints) + '\n' return News
[ "def", "GetLevelUpNews", "(", ")", ":", "News", "=", "GemRB", ".", "GetString", "(", "5259", ")", "+", "'\\n\\n'", "# display if our class has been reactivated", "if", "IsDual", ":", "if", "(", "Level", "[", "0", "]", "-", "LevelDiff", "[", "0", "]", ")", ...
https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/LevelUp.py#L346-L467
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
python/artm/score_tracker.py
python
ClassPrecisionScoreTracker.__init__
(self, score)
:Properties: * Note: every field is a list of info about score on all synchronizations. * value - values of ratio of correct predictions. * error - numbers of error predictiona. * total - numbers of all predictions. * Note: every field has a version with prefix 'last_', means retrieving only\ info about the last synchronization.
:Properties: * Note: every field is a list of info about score on all synchronizations. * value - values of ratio of correct predictions. * error - numbers of error predictiona. * total - numbers of all predictions. * Note: every field has a version with prefix 'last_', means retrieving only\ info about the last synchronization.
[ ":", "Properties", ":", "*", "Note", ":", "every", "field", "is", "a", "list", "of", "info", "about", "score", "on", "all", "synchronizations", ".", "*", "value", "-", "values", "of", "ratio", "of", "correct", "predictions", ".", "*", "error", "-", "nu...
def __init__(self, score): """ :Properties: * Note: every field is a list of info about score on all synchronizations. * value - values of ratio of correct predictions. * error - numbers of error predictiona. * total - numbers of all predictions. * Note: every field has a version with prefix 'last_', means retrieving only\ info about the last synchronization. """ BaseScoreTracker.__init__(self, score)
[ "def", "__init__", "(", "self", ",", "score", ")", ":", "BaseScoreTracker", ".", "__init__", "(", "self", ",", "score", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/python/artm/score_tracker.py#L277-L287
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/netapi.py
python
get_roslaunch_uris
()
@return: list of roslaunch XML-RPC URIs for roscore that's in the current environment, or None if roscore cannot be contacted. @rtype: [str]
[]
def get_roslaunch_uris(): """ @return: list of roslaunch XML-RPC URIs for roscore that's in the current environment, or None if roscore cannot be contacted. @rtype: [str] """ try: m = rosgraph.Master(_ID) vals = m.getParam('/roslaunch/uris') return vals.values() except rosgraph.MasterException: return None
[ "def", "get_roslaunch_uris", "(", ")", ":", "try", ":", "m", "=", "rosgraph", ".", "Master", "(", "_ID", ")", "vals", "=", "m", ".", "getParam", "(", "'/roslaunch/uris'", ")", "return", "vals", ".", "values", "(", ")", "except", "rosgraph", ".", "Maste...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/netapi.py#L48-L59
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/atom/token_store.py
python
TokenStore.remove_token
(self, token)
return token_found
Removes the token from the token_store. This method is used when a token is determined to be invalid. If the token was found by find_token, but resulted in a 401 or 403 error stating that the token was invlid, then the token should be removed to prevent future use. Returns: True if a token was found and then removed from the token store. False if the token was not in the TokenStore.
Removes the token from the token_store.
[ "Removes", "the", "token", "from", "the", "token_store", "." ]
def remove_token(self, token): """Removes the token from the token_store. This method is used when a token is determined to be invalid. If the token was found by find_token, but resulted in a 401 or 403 error stating that the token was invlid, then the token should be removed to prevent future use. Returns: True if a token was found and then removed from the token store. False if the token was not in the TokenStore. """ token_found = False scopes_to_delete = [] for scope, stored_token in self._tokens.iteritems(): if stored_token == token: scopes_to_delete.append(scope) token_found = True for scope in scopes_to_delete: del self._tokens[scope] return token_found
[ "def", "remove_token", "(", "self", ",", "token", ")", ":", "token_found", "=", "False", "scopes_to_delete", "=", "[", "]", "for", "scope", ",", "stored_token", "in", "self", ".", "_tokens", ".", "iteritems", "(", ")", ":", "if", "stored_token", "==", "t...
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/atom/token_store.py#L94-L114
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
ScrollHelper.CalcUnscrolledPosition
(*args)
return _windows_.ScrollHelper_CalcUnscrolledPosition(*args)
CalcUnscrolledPosition(self, Point pt) -> Point CalcUnscrolledPosition(int x, int y) -> (ux, uy) Translate between scrolled and unscrolled coordinates.
CalcUnscrolledPosition(self, Point pt) -> Point CalcUnscrolledPosition(int x, int y) -> (ux, uy)
[ "CalcUnscrolledPosition", "(", "self", "Point", "pt", ")", "-", ">", "Point", "CalcUnscrolledPosition", "(", "int", "x", "int", "y", ")", "-", ">", "(", "ux", "uy", ")" ]
def CalcUnscrolledPosition(*args): """ CalcUnscrolledPosition(self, Point pt) -> Point CalcUnscrolledPosition(int x, int y) -> (ux, uy) Translate between scrolled and unscrolled coordinates. """ return _windows_.ScrollHelper_CalcUnscrolledPosition(*args)
[ "def", "CalcUnscrolledPosition", "(", "*", "args", ")", ":", "return", "_windows_", ".", "ScrollHelper_CalcUnscrolledPosition", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L224-L231
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/dygraph/dygraph_to_static/tensor_shape_transformer.py
python
TensorShapeTransformer._is_var_shape
(self, node)
return False
Return True if node is like `x.shape` or `x.shape[0]`, return False otherwise.
Return True if node is like `x.shape` or `x.shape[0]`, return False otherwise.
[ "Return", "True", "if", "node", "is", "like", "x", ".", "shape", "or", "x", ".", "shape", "[", "0", "]", "return", "False", "otherwise", "." ]
def _is_var_shape(self, node): """ Return True if node is like `x.shape` or `x.shape[0]`, return False otherwise. """ if not isinstance(node, (gast.Attribute, gast.Subscript)): return False if isinstance(node, gast.Attribute): # If node is `paddle.shape`, return False if (node.attr == 'shape' and isinstance(node.value, gast.Name) and node.value.id == 'paddle'): return False if node.attr != 'shape': return False return True if isinstance(node, gast.Subscript): value_node = node.value return self._is_var_shape(value_node) return False
[ "def", "_is_var_shape", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "(", "gast", ".", "Attribute", ",", "gast", ".", "Subscript", ")", ")", ":", "return", "False", "if", "isinstance", "(", "node", ",", "gast", "."...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/dygraph_to_static/tensor_shape_transformer.py#L277-L297
stan-dev/math
5fd79f89933269a4ca4d8dd1fde2a36d53d4768c
lib/cpplint_1.4.5/cpplint.py
python
NestingState.UpdatePreprocessor
(self, line)
Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check.
Update preprocessor stack.
[ "Update", "preprocessor", "stack", "." ]
def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass
[ "def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "# Beginning of #if block, save the nesting stack here. The saved", "# stack will allow us to restore the parsing state in the #else cas...
https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/cpplint_1.4.5/cpplint.py#L2757-L2811
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/win_tool.py
python
WinTool._CommandifyName
(self, name_string)
return name_string.title().replace('-', '')
Transforms a tool name like recursive-mirror to RecursiveMirror.
Transforms a tool name like recursive-mirror to RecursiveMirror.
[ "Transforms", "a", "tool", "name", "like", "recursive", "-", "mirror", "to", "RecursiveMirror", "." ]
def _CommandifyName(self, name_string): """Transforms a tool name like recursive-mirror to RecursiveMirror.""" return name_string.title().replace('-', '')
[ "def", "_CommandifyName", "(", "self", ",", "name_string", ")", ":", "return", "name_string", ".", "title", "(", ")", ".", "replace", "(", "'-'", ",", "''", ")" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/win_tool.py#L72-L74
memkind/memkind
cbbf843ba63d852914f665064b6bf74cdc07ac54
utils/qemu/main.py
python
QEMU._hda_option
(self)
return f'-hda {self.cfg.image}'
Hard drive as a file
Hard drive as a file
[ "Hard", "drive", "as", "a", "file" ]
def _hda_option(self) -> str: """ Hard drive as a file """ return f'-hda {self.cfg.image}'
[ "def", "_hda_option", "(", "self", ")", "->", "str", ":", "return", "f'-hda {self.cfg.image}'" ]
https://github.com/memkind/memkind/blob/cbbf843ba63d852914f665064b6bf74cdc07ac54/utils/qemu/main.py#L248-L252
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/shapedbutton.py
python
SButton.SetLabelColour
(self, colour=None)
Sets the button label colour. :param `colour`: an instance of :class:`Colour`.
Sets the button label colour.
[ "Sets", "the", "button", "label", "colour", "." ]
def SetLabelColour(self, colour=None): """ Sets the button label colour. :param `colour`: an instance of :class:`Colour`. """ if colour is None: colour = wx.BLACK self._labelcolour = colour
[ "def", "SetLabelColour", "(", "self", ",", "colour", "=", "None", ")", ":", "if", "colour", "is", "None", ":", "colour", "=", "wx", ".", "BLACK", "self", ".", "_labelcolour", "=", "colour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shapedbutton.py#L357-L367
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py
python
TensorHandle._get_reader_key
(handle)
return handle_parts[0] + ";" + handle_parts[-1]
The graph key for reader.
The graph key for reader.
[ "The", "graph", "key", "for", "reader", "." ]
def _get_reader_key(handle): """The graph key for reader.""" handle_parts = str(handle).split(";") return handle_parts[0] + ";" + handle_parts[-1]
[ "def", "_get_reader_key", "(", "handle", ")", ":", "handle_parts", "=", "str", "(", "handle", ")", ".", "split", "(", "\";\"", ")", "return", "handle_parts", "[", "0", "]", "+", "\";\"", "+", "handle_parts", "[", "-", "1", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py#L128-L131
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/parser/source_reader.py
python
source_reader_t.create_xml_file_from_string
(self, content, destination=None)
return xml_file
Creates XML file from text. :param content: C++ source code :type content: str :param destination: file name for xml file :type destination: str :rtype: returns file name of xml file
Creates XML file from text.
[ "Creates", "XML", "file", "from", "text", "." ]
def create_xml_file_from_string(self, content, destination=None): """ Creates XML file from text. :param content: C++ source code :type content: str :param destination: file name for xml file :type destination: str :rtype: returns file name of xml file """ header_file = utils.create_temp_file_name(suffix='.h') try: with open(header_file, "w+") as header: header.write(content) xml_file = self.create_xml_file(header_file, destination) finally: utils.remove_file_no_raise(header_file, self.__config) return xml_file
[ "def", "create_xml_file_from_string", "(", "self", ",", "content", ",", "destination", "=", "None", ")", ":", "header_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.h'", ")", "try", ":", "with", "open", "(", "header_file", ",", "\"...
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/parser/source_reader.py#L276-L296
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/cubecolourdialog.py
python
Slope
(pt1, pt2)
Calculates the slope of the line connecting 2 points. :param `pt1`: an instance of :class:`Point`; :param `pt2`: another instance of :class:`Point`.
Calculates the slope of the line connecting 2 points.
[ "Calculates", "the", "slope", "of", "the", "line", "connecting", "2", "points", "." ]
def Slope(pt1, pt2): """ Calculates the slope of the line connecting 2 points. :param `pt1`: an instance of :class:`Point`; :param `pt2`: another instance of :class:`Point`. """ y = float(pt2.y - pt1.y) x = float(pt2.x - pt1.x) if x: return y/x else: return None
[ "def", "Slope", "(", "pt1", ",", "pt2", ")", ":", "y", "=", "float", "(", "pt2", ".", "y", "-", "pt1", ".", "y", ")", "x", "=", "float", "(", "pt2", ".", "x", "-", "pt1", ".", "x", ")", "if", "x", ":", "return", "y", "/", "x", "else", "...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/cubecolourdialog.py#L1256-L1270
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
GraphicsBitmap.__init__
(self, *args, **kwargs)
__init__(self) -> GraphicsBitmap
__init__(self) -> GraphicsBitmap
[ "__init__", "(", "self", ")", "-", ">", "GraphicsBitmap" ]
def __init__(self, *args, **kwargs): """__init__(self) -> GraphicsBitmap""" _gdi_.GraphicsBitmap_swiginit(self,_gdi_.new_GraphicsBitmap(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "GraphicsBitmap_swiginit", "(", "self", ",", "_gdi_", ".", "new_GraphicsBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5587-L5589
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/frequencies.py
python
_get_offset
(name: str)
return _offset_map[name]
Return DateOffset object associated with rule name. Examples -------- _get_offset('EOM') --> BMonthEnd(1)
Return DateOffset object associated with rule name.
[ "Return", "DateOffset", "object", "associated", "with", "rule", "name", "." ]
def _get_offset(name: str) -> DateOffset: """ Return DateOffset object associated with rule name. Examples -------- _get_offset('EOM') --> BMonthEnd(1) """ if name not in libfreqs._dont_uppercase: name = name.upper() name = libfreqs._lite_rule_alias.get(name, name) name = libfreqs._lite_rule_alias.get(name.lower(), name) else: name = libfreqs._lite_rule_alias.get(name, name) if name not in _offset_map: try: split = name.split("-") klass = prefix_mapping[split[0]] # handles case where there's no suffix (and will TypeError if too # many '-') offset = klass._from_name(*split[1:]) except (ValueError, TypeError, KeyError): # bad prefix or suffix raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(name)) # cache _offset_map[name] = offset return _offset_map[name]
[ "def", "_get_offset", "(", "name", ":", "str", ")", "->", "DateOffset", ":", "if", "name", "not", "in", "libfreqs", ".", "_dont_uppercase", ":", "name", "=", "name", ".", "upper", "(", ")", "name", "=", "libfreqs", ".", "_lite_rule_alias", ".", "get", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/frequencies.py#L204-L232
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/multiprocessing/__init__.py
python
allow_connection_pickling
()
Install support for sending connections and sockets between processes
Install support for sending connections and sockets between processes
[ "Install", "support", "for", "sending", "connections", "and", "sockets", "between", "processes" ]
def allow_connection_pickling(): ''' Install support for sending connections and sockets between processes ''' from multiprocessing import reduction
[ "def", "allow_connection_pickling", "(", ")", ":", "from", "multiprocessing", "import", "reduction" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/multiprocessing/__init__.py#L161-L165
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py
python
poly2lag
(pol)
return res
poly2lag(pol) Convert a polynomial to a Laguerre series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Laguerre series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-D array containing the polynomial coefficients Returns ------- c : ndarray 1-D array containing the coefficients of the equivalent Laguerre series. See Also -------- lag2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.laguerre import poly2lag >>> poly2lag(np.arange(4)) array([ 23., -63., 58., -18.])
poly2lag(pol)
[ "poly2lag", "(", "pol", ")" ]
def poly2lag(pol) : """ poly2lag(pol) Convert a polynomial to a Laguerre series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Laguerre series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-D array containing the polynomial coefficients Returns ------- c : ndarray 1-D array containing the coefficients of the equivalent Laguerre series. See Also -------- lag2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.laguerre import poly2lag >>> poly2lag(np.arange(4)) array([ 23., -63., 58., -18.]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1) : res = lagadd(lagmulx(res), pol[i]) return res
[ "def", "poly2lag", "(", "pol", ")", ":", "[", "pol", "]", "=", "pu", ".", "as_series", "(", "[", "pol", "]", ")", "deg", "=", "len", "(", "pol", ")", "-", "1", "res", "=", "0", "for", "i", "in", "range", "(", "deg", ",", "-", "1", ",", "-...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py#L78-L121
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/plistlib.py
python
_BinaryPlistParser._read_object
(self, ref)
return result
read the object by reference. May recursively read sub-objects (content of an array/dict/set)
read the object by reference.
[ "read", "the", "object", "by", "reference", "." ]
def _read_object(self, ref): """ read the object by reference. May recursively read sub-objects (content of an array/dict/set) """ result = self._objects[ref] if result is not _undefined: return result offset = self._object_offsets[ref] self._fp.seek(offset) token = self._fp.read(1)[0] tokenH, tokenL = token & 0xF0, token & 0x0F if token == 0x00: result = None elif token == 0x08: result = False elif token == 0x09: result = True # The referenced source code also mentions URL (0x0c, 0x0d) and # UUID (0x0e), but neither can be generated using the Cocoa libraries. elif token == 0x0f: result = b'' elif tokenH == 0x10: # int result = int.from_bytes(self._fp.read(1 << tokenL), 'big', signed=tokenL >= 3) elif token == 0x22: # real result = struct.unpack('>f', self._fp.read(4))[0] elif token == 0x23: # real result = struct.unpack('>d', self._fp.read(8))[0] elif token == 0x33: # date f = struct.unpack('>d', self._fp.read(8))[0] # timestamp 0 of binary plists corresponds to 1/1/2001 # (year of Mac OS X 10.0), instead of 1/1/1970. result = (datetime.datetime(2001, 1, 1) + datetime.timedelta(seconds=f)) elif tokenH == 0x40: # data s = self._get_size(tokenL) result = self._fp.read(s) if len(result) != s: raise InvalidFileException() elif tokenH == 0x50: # ascii string s = self._get_size(tokenL) data = self._fp.read(s) if len(data) != s: raise InvalidFileException() result = data.decode('ascii') elif tokenH == 0x60: # unicode string s = self._get_size(tokenL) * 2 data = self._fp.read(s) if len(data) != s: raise InvalidFileException() result = data.decode('utf-16be') elif tokenH == 0x80: # UID # used by Key-Archiver plist files result = UID(int.from_bytes(self._fp.read(1 + tokenL), 'big')) elif tokenH == 0xA0: # array s = self._get_size(tokenL) obj_refs = self._read_refs(s) result = [] self._objects[ref] = result result.extend(self._read_object(x) for x in obj_refs) # tokenH == 0xB0 is documented as 'ordset', but is not actually # implemented in the Apple reference code. # tokenH == 0xC0 is documented as 'set', but sets cannot be used in # plists. elif tokenH == 0xD0: # dict s = self._get_size(tokenL) key_refs = self._read_refs(s) obj_refs = self._read_refs(s) result = self._dict_type() self._objects[ref] = result try: for k, o in zip(key_refs, obj_refs): result[self._read_object(k)] = self._read_object(o) except TypeError: raise InvalidFileException() else: raise InvalidFileException() self._objects[ref] = result return result
[ "def", "_read_object", "(", "self", ",", "ref", ")", ":", "result", "=", "self", ".", "_objects", "[", "ref", "]", "if", "result", "is", "not", "_undefined", ":", "return", "result", "offset", "=", "self", ".", "_object_offsets", "[", "ref", "]", "self...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/plistlib.py#L506-L605
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py
python
TensorHandle.eval
(self)
return self._session.run(reader, feed_dict={holder: self._handle})
Return the value of the tensor represented by this handle.
Return the value of the tensor represented by this handle.
[ "Return", "the", "value", "of", "the", "tensor", "represented", "by", "this", "handle", "." ]
def eval(self): """Return the value of the tensor represented by this handle.""" if not self._auto_gc_enabled: raise TypeError("Persistent tensor %s may have already been deleted." % self.handle) holder, reader = _get_handle_reader(self._session.graph, self._handle, self._dtype) return self._session.run(reader, feed_dict={holder: self._handle})
[ "def", "eval", "(", "self", ")", ":", "if", "not", "self", ".", "_auto_gc_enabled", ":", "raise", "TypeError", "(", "\"Persistent tensor %s may have already been deleted.\"", "%", "self", ".", "handle", ")", "holder", ",", "reader", "=", "_get_handle_reader", "(",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py#L93-L100
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/html5lib-python/html5lib/inputstream.py
python
HTMLUnicodeInputStream.openStream
(self, source)
return stream
Produces a file object from source. source can be either a file object, local filename or a string.
Produces a file object from source.
[ "Produces", "a", "file", "object", "from", "source", "." ]
def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = StringIO(source) return stream
[ "def", "openStream", "(", "self", ",", "source", ")", ":", "# Already a file object", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "stream", "=", "source", "else", ":", "stream", "=", "StringIO", "(", "source", ")", "return", "stream" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/html5lib-python/html5lib/inputstream.py#L213-L225
jeog/TDAmeritradeAPI
91c738afd7d57b54f6231170bd64c2550fafd34d
python/tdma_api/get.py
python
_OptionChainGetterBase.get_symbol
(self)
return clib.get_str('OptionChainGetter_GetSymbol_ABI', self._obj)
Returns symbol being used.
Returns symbol being used.
[ "Returns", "symbol", "being", "used", "." ]
def get_symbol(self): """Returns symbol being used.""" return clib.get_str('OptionChainGetter_GetSymbol_ABI', self._obj)
[ "def", "get_symbol", "(", "self", ")", ":", "return", "clib", ".", "get_str", "(", "'OptionChainGetter_GetSymbol_ABI'", ",", "self", ".", "_obj", ")" ]
https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/get.py#L796-L798
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/fractions.py
python
Fraction.__repr__
(self)
return '%s(%s, %s)' % (self.__class__.__name__, self._numerator, self._denominator)
repr(self)
repr(self)
[ "repr", "(", "self", ")" ]
def __repr__(self): """repr(self)""" return '%s(%s, %s)' % (self.__class__.__name__, self._numerator, self._denominator)
[ "def", "__repr__", "(", "self", ")", ":", "return", "'%s(%s, %s)'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "_numerator", ",", "self", ".", "_denominator", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/fractions.py#L282-L285
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/typing.py
python
NewType
(name, tp)
return new_type
NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage:: UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int
NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage::
[ "NewType", "creates", "simple", "unique", "types", "with", "almost", "zero", "runtime", "overhead", ".", "NewType", "(", "name", "tp", ")", "is", "considered", "a", "subtype", "of", "tp", "by", "static", "type", "checkers", ".", "At", "runtime", "NewType", ...
def NewType(name, tp): """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage:: UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int """ def new_type(x): return x new_type.__name__ = name new_type.__supertype__ = tp return new_type
[ "def", "NewType", "(", "name", ",", "tp", ")", ":", "def", "new_type", "(", "x", ")", ":", "return", "x", "new_type", ".", "__name__", "=", "name", "new_type", ".", "__supertype__", "=", "tp", "return", "new_type" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/typing.py#L1455-L1479
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py
python
format_translation_includes
(header, body)
return result
Return the necessary list of includes based on the contents of the body.
Return the necessary list of includes based on the contents of the body.
[ "Return", "the", "necessary", "list", "of", "includes", "based", "on", "the", "contents", "of", "the", "body", "." ]
def format_translation_includes(header, body): """ Return the necessary list of includes based on the contents of the body. """ result = '' # <algorithm> required for VS2013. if body.find('std::min') > 0 or body.find('std::max') > 0: result += '#include <algorithm>\n' if body.find('cef_api_hash(') > 0: result += '#include "include/cef_version.h"\n' # identify what CppToC classes are being used p = re.compile('([A-Za-z0-9_]{1,})CppToC') list = sorted(set(p.findall(body))) for item in list: directory = '' if not is_base_class(item): cls = header.get_class(item) dir = cls.get_file_directory() if not dir is None: directory = dir+'/' result += '#include "libcef_dll/cpptoc/'+directory+ \ get_capi_name(item[3:], False)+'_cpptoc.h"\n' # identify what CToCpp classes are being used p = re.compile('([A-Za-z0-9_]{1,})CToCpp') list = sorted(set(p.findall(body))) for item in list: directory = '' if not is_base_class(item): cls = header.get_class(item) dir = cls.get_file_directory() if not dir is None: directory = dir+'/' result += '#include "libcef_dll/ctocpp/'+directory+ \ get_capi_name(item[3:], False)+'_ctocpp.h"\n' if body.find('transfer_') > 0: result += '#include "libcef_dll/transfer_util.h"\n' return result
[ "def", "format_translation_includes", "(", "header", ",", "body", ")", ":", "result", "=", "''", "# <algorithm> required for VS2013.", "if", "body", ".", "find", "(", "'std::min'", ")", ">", "0", "or", "body", ".", "find", "(", "'std::max'", ")", ">", "0", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L293-L335
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/linalg_ops.py
python
_RegularizedGramianCholesky
(matrix, l2_regularizer, first_kind)
return gen_linalg_ops.cholesky(gramian)
r"""Computes Cholesky factorization of regularized gramian matrix. Below we will use the following notation for each pair of matrix and right-hand sides in the batch: `matrix`=\\(A \in \Re^{m \times n}\\), `output`=\\(C \in \Re^{\min(m, n) \times \min(m,n)}\\), `l2_regularizer`=\\(\lambda\\). If `first_kind` is True, returns the Cholesky factorization \\(L\\) such that \\(L L^H = A^H A + \lambda I\\). If `first_kind` is False, returns the Cholesky factorization \\(L\\) such that \\(L L^H = A A^H + \lambda I\\). Args: matrix: `Tensor` of shape `[..., M, N]`. l2_regularizer: 0-D `double` `Tensor`. Ignored if `fast=False`. first_kind: bool. Controls what gramian matrix to factor. Returns: output: `Tensor` of shape `[..., min(M,N), min(M,N)]` whose inner-most 2 dimensions contain the Cholesky factors \\(L\\) described above.
r"""Computes Cholesky factorization of regularized gramian matrix.
[ "r", "Computes", "Cholesky", "factorization", "of", "regularized", "gramian", "matrix", "." ]
def _RegularizedGramianCholesky(matrix, l2_regularizer, first_kind): r"""Computes Cholesky factorization of regularized gramian matrix. Below we will use the following notation for each pair of matrix and right-hand sides in the batch: `matrix`=\\(A \in \Re^{m \times n}\\), `output`=\\(C \in \Re^{\min(m, n) \times \min(m,n)}\\), `l2_regularizer`=\\(\lambda\\). If `first_kind` is True, returns the Cholesky factorization \\(L\\) such that \\(L L^H = A^H A + \lambda I\\). If `first_kind` is False, returns the Cholesky factorization \\(L\\) such that \\(L L^H = A A^H + \lambda I\\). Args: matrix: `Tensor` of shape `[..., M, N]`. l2_regularizer: 0-D `double` `Tensor`. Ignored if `fast=False`. first_kind: bool. Controls what gramian matrix to factor. Returns: output: `Tensor` of shape `[..., min(M,N), min(M,N)]` whose inner-most 2 dimensions contain the Cholesky factors \\(L\\) described above. """ gramian = math_ops.matmul( matrix, matrix, adjoint_a=first_kind, adjoint_b=not first_kind) if isinstance(l2_regularizer, ops.Tensor) or l2_regularizer != 0: matrix_shape = array_ops.shape(matrix) batch_shape = matrix_shape[:-2] if first_kind: small_dim = matrix_shape[-1] else: small_dim = matrix_shape[-2] identity = eye(small_dim, batch_shape=batch_shape, dtype=matrix.dtype) small_dim_static = matrix.shape[-1 if first_kind else -2] identity.set_shape( matrix.shape[:-2].concatenate([small_dim_static, small_dim_static])) gramian += l2_regularizer * identity return gen_linalg_ops.cholesky(gramian)
[ "def", "_RegularizedGramianCholesky", "(", "matrix", ",", "l2_regularizer", ",", "first_kind", ")", ":", "gramian", "=", "math_ops", ".", "matmul", "(", "matrix", ",", "matrix", ",", "adjoint_a", "=", "first_kind", ",", "adjoint_b", "=", "not", "first_kind", "...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/linalg_ops.py#L38-L76
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBModule.get_compile_units_array
(self)
return self.compile_units_array
An accessor function that returns an array object that contains all compile_units in this module object.
An accessor function that returns an array object that contains all compile_units in this module object.
[ "An", "accessor", "function", "that", "returns", "an", "array", "object", "that", "contains", "all", "compile_units", "in", "this", "module", "object", "." ]
def get_compile_units_array(self): '''An accessor function that returns an array object that contains all compile_units in this module object.''' if not hasattr(self, 'compile_units_array'): self.compile_units_array = [] for idx in range(self.GetNumCompileUnits()): self.compile_units_array.append(self.GetCompileUnitAtIndex(idx)) return self.compile_units_array
[ "def", "get_compile_units_array", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'compile_units_array'", ")", ":", "self", ".", "compile_units_array", "=", "[", "]", "for", "idx", "in", "range", "(", "self", ".", "GetNumCompileUnits", "(",...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L6425-L6431
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/tseries/holiday.py
python
previous_workday
(dt)
return dt
returns previous weekday used for observances
returns previous weekday used for observances
[ "returns", "previous", "weekday", "used", "for", "observances" ]
def previous_workday(dt): """ returns previous weekday used for observances """ dt -= timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt -= timedelta(days=1) return dt
[ "def", "previous_workday", "(", "dt", ")", ":", "dt", "-=", "timedelta", "(", "days", "=", "1", ")", "while", "dt", ".", "weekday", "(", ")", ">", "4", ":", "# Mon-Fri are 0-4", "dt", "-=", "timedelta", "(", "days", "=", "1", ")", "return", "dt" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/tseries/holiday.py#L98-L106
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/prediction/data_pipelines/common/online_to_offline.py
python
LabelGenerator.__init__
(self)
feature_dict contains the organized Feature in the following way: obstacle_ID --> [Feature1, Feature2, Feature3, ...] (sequentially sorted)
feature_dict contains the organized Feature in the following way: obstacle_ID --> [Feature1, Feature2, Feature3, ...] (sequentially sorted)
[ "feature_dict", "contains", "the", "organized", "Feature", "in", "the", "following", "way", ":", "obstacle_ID", "--", ">", "[", "Feature1", "Feature2", "Feature3", "...", "]", "(", "sequentially", "sorted", ")" ]
def __init__(self): self.filepath = None ''' feature_dict contains the organized Feature in the following way: obstacle_ID --> [Feature1, Feature2, Feature3, ...] (sequentially sorted) ''' self.feature_dict = dict() ''' observation_dict contains the important observations of the subsequent Features for each obstacle at every timestamp: obstacle_ID@timestamp --> dictionary of observations where dictionary of observations contains: 'obs_traj': the trajectory points (x, y, vel_heading) up to max_observation_time this trajectory poitns must be consecutive (0.1sec sampling period) 'obs_traj_len': length of trajectory points 'obs_actual_lane_ids': the actual sequence of lane_segment ids the obstacle steps on 'has_started_lane_change': whether the obstacle has started lane changing within max_observation_time 'has_finished_lane_change': whether it has finished lane changing 'lane_change_start_time': 'lane_change_finish_time': 'is_jittering': 'new_lane_id': 'total_observed_time_span': This observation_dict, once constructed, can be reused by various labeling functions. ''' self.observation_dict = dict() self.future_status_dict = dict() self.cruise_label_dict = dict() self.junction_label_dict = dict()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "filepath", "=", "None", "self", ".", "feature_dict", "=", "dict", "(", ")", "'''\n observation_dict contains the important observations of the subsequent\n Features for each obstacle at every timestamp:\n ...
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/prediction/data_pipelines/common/online_to_offline.py#L37-L70
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/numbers.py
python
Complex.__rsub__
(self, other)
return -self + other
other - self
other - self
[ "other", "-", "self" ]
def __rsub__(self, other): """other - self""" return -self + other
[ "def", "__rsub__", "(", "self", ",", "other", ")", ":", "return", "-", "self", "+", "other" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/numbers.py#L96-L98