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
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/html.py
python
HtmlStatus.settings_hash
(self)
return self.settings
Get the hash of the coverage.py settings.
Get the hash of the coverage.py settings.
[ "Get", "the", "hash", "of", "the", "coverage", ".", "py", "settings", "." ]
def settings_hash(self): """Get the hash of the coverage.py settings.""" return self.settings
[ "def", "settings_hash", "(", "self", ")", ":", "return", "self", ".", "settings" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/html.py#L393-L395
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/rnn_cell.py
python
RNNCell.state_size
(self)
size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes.
size(s) of state(s) used by this cell.
[ "size", "(", "s", ")", "of", "state", "(", "s", ")", "used", "by", "this", "cell", "." ]
def state_size(self): """size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. """ raise NotImplementedError("Abstract method")
[ "def", "state_size", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"Abstract method\"", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/rnn_cell.py#L131-L137
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/runtime/context.py
python
NRTContext.decref
(self, builder, typ, value)
Recursively decref the given *value* and its members.
Recursively decref the given *value* and its members.
[ "Recursively", "decref", "the", "given", "*", "value", "*", "and", "its", "members", "." ]
def decref(self, builder, typ, value): """ Recursively decref the given *value* and its members. """ self._call_incref_decref(builder, typ, value, "NRT_decref")
[ "def", "decref", "(", "self", ",", "builder", ",", "typ", ",", "value", ")", ":", "self", ".", "_call_incref_decref", "(", "builder", ",", "typ", ",", "value", ",", "\"NRT_decref\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/runtime/context.py#L222-L226
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/bccache.py
python
Bucket.write_bytecode
(self, f: t.BinaryIO)
Dump the bytecode into the file or file like object passed.
Dump the bytecode into the file or file like object passed.
[ "Dump", "the", "bytecode", "into", "the", "file", "or", "file", "like", "object", "passed", "." ]
def write_bytecode(self, f: t.BinaryIO) -> None: """Dump the bytecode into the file or file like object passed.""" if self.code is None: raise TypeError("can't write empty bucket") f.write(bc_magic) pickle.dump(self.checksum, f, 2) marshal.dump(self.code, f)
[ "def", "write_bytecode", "(", "self", ",", "f", ":", "t", ".", "BinaryIO", ")", "->", "None", ":", "if", "self", ".", "code", "is", "None", ":", "raise", "TypeError", "(", "\"can't write empty bucket\"", ")", "f", ".", "write", "(", "bc_magic", ")", "p...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/bccache.py#L82-L88
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/webchecker/tktools.py
python
make_group_frame
(master, name=None, label=None, fill=Y, side=None, expand=None, font=None)
return inner
Create nested frames with a border and optional label. The outer frame is only used to provide the decorative border, to control packing, and to host the label. The inner frame is packed to fill the outer frame and should be used as the parent of all sub-widgets. Only the inner frame is returned.
Create nested frames with a border and optional label.
[ "Create", "nested", "frames", "with", "a", "border", "and", "optional", "label", "." ]
def make_group_frame(master, name=None, label=None, fill=Y, side=None, expand=None, font=None): """Create nested frames with a border and optional label. The outer frame is only used to provide the decorative border, to control packing, and to host the label. The inner frame is packed to fill the outer frame and should be used as the parent of all sub-widgets. Only the inner frame is returned. """ font = font or "-*-helvetica-medium-r-normal-*-*-100-*-*-*-*-*-*" outer = Frame(master, borderwidth=2, relief=GROOVE) outer.pack(expand=expand, fill=fill, side=side) if label: Label(outer, text=label, font=font, anchor=W).pack(fill=X) inner = Frame(master, borderwidth='1m', name=name) inner.pack(expand=1, fill=BOTH, in_=outer) inner.forget = outer.forget return inner
[ "def", "make_group_frame", "(", "master", ",", "name", "=", "None", ",", "label", "=", "None", ",", "fill", "=", "Y", ",", "side", "=", "None", ",", "expand", "=", "None", ",", "font", "=", "None", ")", ":", "font", "=", "font", "or", "\"-*-helveti...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/webchecker/tktools.py#L299-L317
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/normalization.py
python
_shape_infer
(x_shape, num_feature)
return axes, re_shape
global Batch Normalization shape and axes infer
global Batch Normalization shape and axes infer
[ "global", "Batch", "Normalization", "shape", "and", "axes", "infer" ]
def _shape_infer(x_shape, num_feature): """global Batch Normalization shape and axes infer""" if len(x_shape) == 4: axes = (0, 2, 3) re_shape = (1, num_feature, 1, 1) else: axes = (0,) re_shape = (1, num_feature) return axes, re_shape
[ "def", "_shape_infer", "(", "x_shape", ",", "num_feature", ")", ":", "if", "len", "(", "x_shape", ")", "==", "4", ":", "axes", "=", "(", "0", ",", "2", ",", "3", ")", "re_shape", "=", "(", "1", ",", "num_feature", ",", "1", ",", "1", ")", "else...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/normalization.py#L273-L281
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/shell.py
python
_pipespawn
(argv, env)
Pipe spawn
Pipe spawn
[ "Pipe", "spawn" ]
def _pipespawn(argv, env): """ Pipe spawn """ # pylint: disable = R0912 import pickle as _pickle fd, name = mkstemp('.py') try: _os.write(fd, ((r""" import os import pickle import subprocess import sys argv = pickle.loads(%(argv)s) env = pickle.loads(%(env)s) if 'X_JYTHON_WA_PATH' in env: env['PATH'] = env['X_JYTHON_WA_PATH'] p = subprocess.Popen(argv, env=env) result = p.wait() if result < 0: print("\n%%d 1" %% (-result)) sys.exit(2) if result == 0: sys.exit(0) print("\n%%d" %% (result & 7,)) sys.exit(3) """.strip() + "\n") % { 'argv': repr(_pickle.dumps(argv)), 'env': repr(_pickle.dumps(dict(env))), }).encode('utf-8')) fd, _ = None, _os.close(fd) if _sys.platform == 'win32': argv = [] for arg in [_sys.executable, name]: if ' ' in arg or arg.startswith('"'): arg = '"%s"' % arg.replace('"', '\\"') argv.append(arg) argv = ' '.join(argv) shell = True close_fds = False else: argv = [_sys.executable, name] shell = False close_fds = True res = 0 if 'X_JYTHON_WA_PATH' in env: env['PATH'] = env['X_JYTHON_WA_PATH'] proc = _subprocess.Popen(argv, shell=shell, stdin=_subprocess.PIPE, stdout=_subprocess.PIPE, close_fds=close_fds, env=env, ) try: proc.stdin.close() result = proc.stdout.read() finally: res = proc.wait() if res != 0: if res == 2: signal, code = list(map(int, result.splitlines()[-1].split())) raise SignalError(code, signal) elif res == 3: code = int(result.splitlines()[-1].strip()) raise ExitError(code) raise ExitError(res) return result.decode('latin-1') finally: try: if fd is not None: _os.close(fd) finally: _os.unlink(name)
[ "def", "_pipespawn", "(", "argv", ",", "env", ")", ":", "# pylint: disable = R0912", "import", "pickle", "as", "_pickle", "fd", ",", "name", "=", "mkstemp", "(", "'.py'", ")", "try", ":", "_os", ".", "write", "(", "fd", ",", "(", "(", "r\"\"\"\nimport os...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/shell.py#L96-L172
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/lite.py
python
TFLiteConverterBase._get_base_converter_args
(self)
return args
Returns the base converter args. Returns: {key str: val}
Returns the base converter args.
[ "Returns", "the", "base", "converter", "args", "." ]
def _get_base_converter_args(self): """Returns the base converter args. Returns: {key str: val} """ float16_quantize = self._is_float16_quantize() args = { "input_format": constants.TENSORFLOW_GRAPHDEF, "allow_custom_ops": self.allow_custom_ops, "post_training_quantize": (self._is_int8_weight_only_quantize() or float16_quantize), "quantize_to_float16": float16_quantize, "debug_info": self._debug_info, "target_ops": self.target_spec.supported_ops, "enable_mlir_converter": self.experimental_enable_mlir_converter, } return args
[ "def", "_get_base_converter_args", "(", "self", ")", ":", "float16_quantize", "=", "self", ".", "_is_float16_quantize", "(", ")", "args", "=", "{", "\"input_format\"", ":", "constants", ".", "TENSORFLOW_GRAPHDEF", ",", "\"allow_custom_ops\"", ":", "self", ".", "al...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/lite.py#L241-L258
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
parserCtxt.htmlCtxtUseOptions
(self, options)
return ret
Applies the options to the parser context
Applies the options to the parser context
[ "Applies", "the", "options", "to", "the", "parser", "context" ]
def htmlCtxtUseOptions(self, options): """Applies the options to the parser context """ ret = libxml2mod.htmlCtxtUseOptions(self._o, options) return ret
[ "def", "htmlCtxtUseOptions", "(", "self", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "htmlCtxtUseOptions", "(", "self", ".", "_o", ",", "options", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4993-L4996
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/plugin.py
python
PluginData.SetDescription
(self, descript)
@return: Plugins description string
[]
def SetDescription(self, descript): """@return: Plugins description string""" if not isinstance(descript, basestring): try: descript = str(descript) except (ValueError, TypeError): descript = u'' self._description = descript
[ "def", "SetDescription", "(", "self", ",", "descript", ")", ":", "if", "not", "isinstance", "(", "descript", ",", "basestring", ")", ":", "try", ":", "descript", "=", "str", "(", "descript", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/plugin.py#L387-L394
OkCupid/okws
1c337392c676ccb4e9a4c92d11d5d2fada6427d2
contrib/pub2-upgrade.py
python
PubParser.parse
(self, data, lexer=None, *args, **kwargs)
return self.parser.parse(data, lexer=lexer, *args, **kwargs)
Parse the input JSON data string into a python data structure. Args: data: An input data string lexer: An optional ply.lex instance that overrides the default lexer. Returns: A python dict or list representing the input JSON data.
Parse the input JSON data string into a python data structure. Args: data: An input data string lexer: An optional ply.lex instance that overrides the default lexer. Returns: A python dict or list representing the input JSON data.
[ "Parse", "the", "input", "JSON", "data", "string", "into", "a", "python", "data", "structure", ".", "Args", ":", "data", ":", "An", "input", "data", "string", "lexer", ":", "An", "optional", "ply", ".", "lex", "instance", "that", "overrides", "the", "def...
def parse(self, data, lexer=None, *args, **kwargs): '''Parse the input JSON data string into a python data structure. Args: data: An input data string lexer: An optional ply.lex instance that overrides the default lexer. Returns: A python dict or list representing the input JSON data. ''' if lexer is None: lexer = self.lexer return self.parser.parse(data, lexer=lexer, *args, **kwargs)
[ "def", "parse", "(", "self", ",", "data", ",", "lexer", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "lexer", "is", "None", ":", "lexer", "=", "self", ".", "lexer", "return", "self", ".", "parser", ".", "parse", "(", ...
https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/contrib/pub2-upgrade.py#L314-L325
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/xcode6.py
python
xcode.execute
(self)
Entry point
Entry point
[ "Entry", "point" ]
def execute(self): """ Entry point """ self.restore() if not self.all_envs: self.load_envs() self.recurse([self.run_dir]) appname = getattr(Context.g_module, Context.APPNAME, os.path.basename(self.srcnode.abspath())) p = PBXProject(appname, ('Xcode 3.2', 46), self.env) # If we don't create a Products group, then # XCode will create one, which entails that # we'll start to see duplicate files in the UI # for some reason. products_group = PBXGroup('Products') p.mainGroup.children.append(products_group) self.project = p self.products_group = products_group # post all task generators # the process_xcode method above will be called for each target if self.targets and self.targets != '*': (self._min_grp, self._exact_tg) = self.get_targets() self.current_group = 0 while self.current_group < len(self.groups): self.post_group() self.current_group += 1 node = self.bldnode.make_node('%s.xcodeproj' % appname) node.mkdir() node = node.make_node('project.pbxproj') with open(node.abspath(), 'w') as f: p.write(f) Logs.pprint('GREEN', 'Wrote %r' % node.abspath())
[ "def", "execute", "(", "self", ")", ":", "self", ".", "restore", "(", ")", "if", "not", "self", ".", "all_envs", ":", "self", ".", "load_envs", "(", ")", "self", ".", "recurse", "(", "[", "self", ".", "run_dir", "]", ")", "appname", "=", "getattr",...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/xcode6.py#L656-L694
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pexpect/pexpect/fdpexpect.py
python
fdspawn.read_nonblocking
(self, size=1, timeout=-1)
return super(fdspawn, self).read_nonblocking(size)
Read from the file descriptor and return the result as a string. The read_nonblocking method of :class:`SpawnBase` assumes that a call to os.read will not block (timeout parameter is ignored). This is not the case for POSIX file-like objects such as sockets and serial ports. Use :func:`select.select`, timeout is implemented conditionally for POSIX systems. :param int size: Read at most *size* bytes. :param int timeout: Wait timeout seconds for file descriptor to be ready to read. When -1 (default), use self.timeout. When 0, poll. :return: String containing the bytes read
Read from the file descriptor and return the result as a string.
[ "Read", "from", "the", "file", "descriptor", "and", "return", "the", "result", "as", "a", "string", "." ]
def read_nonblocking(self, size=1, timeout=-1): """ Read from the file descriptor and return the result as a string. The read_nonblocking method of :class:`SpawnBase` assumes that a call to os.read will not block (timeout parameter is ignored). This is not the case for POSIX file-like objects such as sockets and serial ports. Use :func:`select.select`, timeout is implemented conditionally for POSIX systems. :param int size: Read at most *size* bytes. :param int timeout: Wait timeout seconds for file descriptor to be ready to read. When -1 (default), use self.timeout. When 0, poll. :return: String containing the bytes read """ if os.name == 'posix': if timeout == -1: timeout = self.timeout rlist = [self.child_fd] wlist = [] xlist = [] if self.use_poll: rlist = poll_ignore_interrupts(rlist, timeout) else: rlist, wlist, xlist = select_ignore_interrupts( rlist, wlist, xlist, timeout ) if self.child_fd not in rlist: raise TIMEOUT('Timeout exceeded.') return super(fdspawn, self).read_nonblocking(size)
[ "def", "read_nonblocking", "(", "self", ",", "size", "=", "1", ",", "timeout", "=", "-", "1", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "rlist", "=", "["...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pexpect/pexpect/fdpexpect.py#L118-L148
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tpu/topology.py
python
_tpu_host_device_name
(job, task)
Returns the device name for the CPU device on `task` of `job`.
Returns the device name for the CPU device on `task` of `job`.
[ "Returns", "the", "device", "name", "for", "the", "CPU", "device", "on", "task", "of", "job", "." ]
def _tpu_host_device_name(job, task): """Returns the device name for the CPU device on `task` of `job`.""" if job is None: return "/task:%d/device:CPU:0" % task else: return "/job:%s/task:%d/device:CPU:0" % (job, task)
[ "def", "_tpu_host_device_name", "(", "job", ",", "task", ")", ":", "if", "job", "is", "None", ":", "return", "\"/task:%d/device:CPU:0\"", "%", "task", "else", ":", "return", "\"/job:%s/task:%d/device:CPU:0\"", "%", "(", "job", ",", "task", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/topology.py#L31-L36
liuheng92/tensorflow_PSENet
e2cd908f301b762150aa36893677c1c51c98ff9e
utils/data_provider/data_provider.py
python
crop_area
(im, polys, tags, crop_background=False, max_tries=50)
return im, polys, tags
make random crop from the input image :param im: :param polys: :param tags: :param crop_background: :param max_tries: :return:
make random crop from the input image :param im: :param polys: :param tags: :param crop_background: :param max_tries: :return:
[ "make", "random", "crop", "from", "the", "input", "image", ":", "param", "im", ":", ":", "param", "polys", ":", ":", "param", "tags", ":", ":", "param", "crop_background", ":", ":", "param", "max_tries", ":", ":", "return", ":" ]
def crop_area(im, polys, tags, crop_background=False, max_tries=50): ''' make random crop from the input image :param im: :param polys: :param tags: :param crop_background: :param max_tries: :return: ''' h, w, _ = im.shape pad_h = h//10 pad_w = w//10 h_array = np.zeros((h + pad_h*2), dtype=np.int32) w_array = np.zeros((w + pad_w*2), dtype=np.int32) for poly in polys: poly = np.round(poly, decimals=0).astype(np.int32) minx = np.min(poly[:, 0]) maxx = np.max(poly[:, 0]) w_array[minx+pad_w:maxx+pad_w] = 1 miny = np.min(poly[:, 1]) maxy = np.max(poly[:, 1]) h_array[miny+pad_h:maxy+pad_h] = 1 # ensure the cropped area not across a text h_axis = np.where(h_array == 0)[0] w_axis = np.where(w_array == 0)[0] if len(h_axis) == 0 or len(w_axis) == 0: return im, polys, tags for i in range(max_tries): xx = np.random.choice(w_axis, size=2) xmin = np.min(xx) - pad_w xmax = np.max(xx) - pad_w xmin = np.clip(xmin, 0, w-1) xmax = np.clip(xmax, 0, w-1) yy = np.random.choice(h_axis, size=2) ymin = np.min(yy) - pad_h ymax = np.max(yy) - pad_h ymin = np.clip(ymin, 0, h-1) ymax = np.clip(ymax, 0, h-1) if xmax - xmin < FLAGS.min_crop_side_ratio*w or ymax - ymin < FLAGS.min_crop_side_ratio*h: # area too small continue if polys.shape[0] != 0: poly_axis_in_area = (polys[:, :, 0] >= xmin) & (polys[:, :, 0] <= xmax) \ & (polys[:, :, 1] >= ymin) & (polys[:, :, 1] <= ymax) selected_polys = np.where(np.sum(poly_axis_in_area, axis=1) == 4)[0] else: selected_polys = [] if len(selected_polys) == 0: # no text in this area if crop_background: return im[ymin:ymax+1, xmin:xmax+1, :], polys[selected_polys], tags[selected_polys] else: continue im = im[ymin:ymax+1, xmin:xmax+1, :] polys = polys[selected_polys] tags = tags[selected_polys] polys[:, :, 0] -= xmin polys[:, :, 1] -= ymin return im, polys, tags return im, polys, tags
[ "def", "crop_area", "(", "im", ",", "polys", ",", "tags", ",", "crop_background", "=", "False", ",", "max_tries", "=", "50", ")", ":", "h", ",", "w", ",", "_", "=", "im", ".", "shape", "pad_h", "=", "h", "//", "10", "pad_w", "=", "w", "//", "10...
https://github.com/liuheng92/tensorflow_PSENet/blob/e2cd908f301b762150aa36893677c1c51c98ff9e/utils/data_provider/data_provider.py#L104-L165
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/network.py
python
Network._name_scope_name
(self, current_variable_scope)
return _network_name_scope_naming( current_variable_scope=current_variable_scope)
Overrides Layer op naming to match variable naming.
Overrides Layer op naming to match variable naming.
[ "Overrides", "Layer", "op", "naming", "to", "match", "variable", "naming", "." ]
def _name_scope_name(self, current_variable_scope): """Overrides Layer op naming to match variable naming.""" return _network_name_scope_naming( current_variable_scope=current_variable_scope)
[ "def", "_name_scope_name", "(", "self", ",", "current_variable_scope", ")", ":", "return", "_network_name_scope_naming", "(", "current_variable_scope", "=", "current_variable_scope", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/network.py#L199-L202
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py
python
Merge
(text, message)
Merges an ASCII representation of a protocol message into a message. Args: text: Message ASCII representation. message: A protocol buffer message to merge into. Raises: ParseError: On ASCII parsing problems.
Merges an ASCII representation of a protocol message into a message.
[ "Merges", "an", "ASCII", "representation", "of", "a", "protocol", "message", "into", "a", "message", "." ]
def Merge(text, message): """Merges an ASCII representation of a protocol message into a message. Args: text: Message ASCII representation. message: A protocol buffer message to merge into. Raises: ParseError: On ASCII parsing problems. """ tokenizer = _Tokenizer(text) while not tokenizer.AtEnd(): _MergeField(tokenizer, message)
[ "def", "Merge", "(", "text", ",", "message", ")", ":", "tokenizer", "=", "_Tokenizer", "(", "text", ")", "while", "not", "tokenizer", ".", "AtEnd", "(", ")", ":", "_MergeField", "(", "tokenizer", ",", "message", ")" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py#L126-L138
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/module/module.py
python
Module.modules
(self, **kwargs)
r"""Returns an iterable for all the modules within this module, including itself.
r"""Returns an iterable for all the modules within this module, including itself.
[ "r", "Returns", "an", "iterable", "for", "all", "the", "modules", "within", "this", "module", "including", "itself", "." ]
def modules(self, **kwargs) -> "Iterable[Module]": r"""Returns an iterable for all the modules within this module, including itself.""" if "with_parent" in kwargs and kwargs["with_parent"]: yield self, None else: yield self yield from self._flatten(with_key=False, predicate=_is_module, **kwargs)
[ "def", "modules", "(", "self", ",", "*", "*", "kwargs", ")", "->", "\"Iterable[Module]\"", ":", "if", "\"with_parent\"", "in", "kwargs", "and", "kwargs", "[", "\"with_parent\"", "]", ":", "yield", "self", ",", "None", "else", ":", "yield", "self", "yield",...
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/module/module.py#L354-L360
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/core.py
python
convolve
(a, v, mode='full', propagate_mask=True)
return _convolve_or_correlate(np.convolve, a, v, mode, propagate_mask)
Returns the discrete, linear convolution of two one-dimensional sequences. Parameters ---------- a, v : array_like Input sequences. mode : {'valid', 'same', 'full'}, optional Refer to the `np.convolve` docstring. propagate_mask : bool If True, then if any masked element is included in the sum for a result element, then the result is masked. If False, then the result element is only masked if no non-masked cells contribute towards it Returns ------- out : MaskedArray Discrete, linear convolution of `a` and `v`. See Also -------- numpy.convolve : Equivalent function in the top-level NumPy module.
Returns the discrete, linear convolution of two one-dimensional sequences.
[ "Returns", "the", "discrete", "linear", "convolution", "of", "two", "one", "-", "dimensional", "sequences", "." ]
def convolve(a, v, mode='full', propagate_mask=True): """ Returns the discrete, linear convolution of two one-dimensional sequences. Parameters ---------- a, v : array_like Input sequences. mode : {'valid', 'same', 'full'}, optional Refer to the `np.convolve` docstring. propagate_mask : bool If True, then if any masked element is included in the sum for a result element, then the result is masked. If False, then the result element is only masked if no non-masked cells contribute towards it Returns ------- out : MaskedArray Discrete, linear convolution of `a` and `v`. See Also -------- numpy.convolve : Equivalent function in the top-level NumPy module. """ return _convolve_or_correlate(np.convolve, a, v, mode, propagate_mask)
[ "def", "convolve", "(", "a", ",", "v", ",", "mode", "=", "'full'", ",", "propagate_mask", "=", "True", ")", ":", "return", "_convolve_or_correlate", "(", "np", ".", "convolve", ",", "a", ",", "v", ",", "mode", ",", "propagate_mask", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L7535-L7560
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/flatnotebook.py
python
FlatNotebook.GetPageImage
(self, nPage)
return self._pages.GetPageImage(nPage)
Returns the image index for the given page. Image is an index into the image list which was set with SetImageList.
Returns the image index for the given page. Image is an index into the image list which was set with SetImageList.
[ "Returns", "the", "image", "index", "for", "the", "given", "page", ".", "Image", "is", "an", "index", "into", "the", "image", "list", "which", "was", "set", "with", "SetImageList", "." ]
def GetPageImage(self, nPage): """ Returns the image index for the given page. Image is an index into the image list which was set with SetImageList. """ return self._pages.GetPageImage(nPage)
[ "def", "GetPageImage", "(", "self", ",", "nPage", ")", ":", "return", "self", ".", "_pages", ".", "GetPageImage", "(", "nPage", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L3685-L3691
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/_pslinux.py
python
pid_exists
(pid)
return _psposix.pid_exists(pid)
Check For the existence of a unix pid.
Check For the existence of a unix pid.
[ "Check", "For", "the", "existence", "of", "a", "unix", "pid", "." ]
def pid_exists(pid): """Check For the existence of a unix pid.""" return _psposix.pid_exists(pid)
[ "def", "pid_exists", "(", "pid", ")", ":", "return", "_psposix", ".", "pid_exists", "(", "pid", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/_pslinux.py#L355-L357
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/lib/arraypad.py
python
_as_pairs
(x, ndim, as_index=False)
return np.broadcast_to(x, (ndim, 2)).tolist()
Broadcast `x` to an array with the shape (`ndim`, 2). A helper function for `pad` that prepares and validates arguments like `pad_width` for iteration in pairs. Parameters ---------- x : {None, scalar, array-like} The object to broadcast to the shape (`ndim`, 2). ndim : int Number of pairs the broadcasted `x` will have. as_index : bool, optional If `x` is not None, try to round each element of `x` to an integer (dtype `np.intp`) and ensure every element is positive. Returns ------- pairs : nested iterables, shape (`ndim`, 2) The broadcasted version of `x`. Raises ------ ValueError If `as_index` is True and `x` contains negative elements. Or if `x` is not broadcastable to the shape (`ndim`, 2).
Broadcast `x` to an array with the shape (`ndim`, 2).
[ "Broadcast", "x", "to", "an", "array", "with", "the", "shape", "(", "ndim", "2", ")", "." ]
def _as_pairs(x, ndim, as_index=False): """ Broadcast `x` to an array with the shape (`ndim`, 2). A helper function for `pad` that prepares and validates arguments like `pad_width` for iteration in pairs. Parameters ---------- x : {None, scalar, array-like} The object to broadcast to the shape (`ndim`, 2). ndim : int Number of pairs the broadcasted `x` will have. as_index : bool, optional If `x` is not None, try to round each element of `x` to an integer (dtype `np.intp`) and ensure every element is positive. Returns ------- pairs : nested iterables, shape (`ndim`, 2) The broadcasted version of `x`. Raises ------ ValueError If `as_index` is True and `x` contains negative elements. Or if `x` is not broadcastable to the shape (`ndim`, 2). """ if x is None: # Pass through None as a special case, otherwise np.round(x) fails # with an AttributeError return ((None, None),) * ndim x = np.array(x) if as_index: x = np.round(x).astype(np.intp, copy=False) if x.ndim < 3: # Optimization: Possibly use faster paths for cases where `x` has # only 1 or 2 elements. `np.broadcast_to` could handle these as well # but is currently slower if x.size == 1: # x was supplied as a single value x = x.ravel() # Ensure x[0] works for x.ndim == 0, 1, 2 if as_index and x < 0: raise ValueError("index can't contain negative values") return ((x[0], x[0]),) * ndim if x.size == 2 and x.shape != (2, 1): # x was supplied with a single value for each side # but except case when each dimension has a single value # which should be broadcasted to a pair, # e.g. [[1], [2]] -> [[1, 1], [2, 2]] not [[1, 2], [1, 2]] x = x.ravel() # Ensure x[0], x[1] works if as_index and (x[0] < 0 or x[1] < 0): raise ValueError("index can't contain negative values") return ((x[0], x[1]),) * ndim if as_index and x.min() < 0: raise ValueError("index can't contain negative values") # Converting the array with `tolist` seems to improve performance # when iterating and indexing the result (see usage in `pad`) return np.broadcast_to(x, (ndim, 2)).tolist()
[ "def", "_as_pairs", "(", "x", ",", "ndim", ",", "as_index", "=", "False", ")", ":", "if", "x", "is", "None", ":", "# Pass through None as a special case, otherwise np.round(x) fails", "# with an AttributeError", "return", "(", "(", "None", ",", "None", ")", ",", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/arraypad.py#L877-L941
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/defchararray.py
python
isdigit
(a)
return _vec_string(a, bool_, 'isdigit')
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. Calls `str.isdigit` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.isdigit
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise.
[ "Returns", "true", "for", "each", "element", "if", "all", "characters", "in", "the", "string", "are", "digits", "and", "there", "is", "at", "least", "one", "character", "false", "otherwise", "." ]
def isdigit(a): """ Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. Calls `str.isdigit` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.isdigit """ return _vec_string(a, bool_, 'isdigit')
[ "def", "isdigit", "(", "a", ")", ":", "return", "_vec_string", "(", "a", ",", "bool_", ",", "'isdigit'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/defchararray.py#L810-L832
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
python
setup_train_data_feeder
(x, y, n_classes, batch_size=None, shuffle=True, epochs=None)
return data_feeder_cls( x, y, n_classes, batch_size, shuffle=shuffle, epochs=epochs)
Create data feeder, to sample inputs from dataset. If `x` and `y` are iterators, use `StreamingDataFeeder`. Args: x: numpy, pandas or Dask matrix or dictionary of aforementioned. Also supports iterables. y: numpy, pandas or Dask array or dictionary of aforementioned. Also supports iterables. n_classes: number of classes. Must be None or same type as y. In case, `y` is `dict` (or iterable which returns dict) such that `n_classes[key] = n_classes for y[key]` batch_size: size to split data into parts. Must be >= 1. shuffle: Whether to shuffle the inputs. epochs: Number of epochs to run. Returns: DataFeeder object that returns training data. Raises: ValueError: if one of `x` and `y` is iterable and the other is not.
Create data feeder, to sample inputs from dataset.
[ "Create", "data", "feeder", "to", "sample", "inputs", "from", "dataset", "." ]
def setup_train_data_feeder(x, y, n_classes, batch_size=None, shuffle=True, epochs=None): """Create data feeder, to sample inputs from dataset. If `x` and `y` are iterators, use `StreamingDataFeeder`. Args: x: numpy, pandas or Dask matrix or dictionary of aforementioned. Also supports iterables. y: numpy, pandas or Dask array or dictionary of aforementioned. Also supports iterables. n_classes: number of classes. Must be None or same type as y. In case, `y` is `dict` (or iterable which returns dict) such that `n_classes[key] = n_classes for y[key]` batch_size: size to split data into parts. Must be >= 1. shuffle: Whether to shuffle the inputs. epochs: Number of epochs to run. Returns: DataFeeder object that returns training data. Raises: ValueError: if one of `x` and `y` is iterable and the other is not. """ x, y = _data_type_filter(x, y) if HAS_DASK: # pylint: disable=g-import-not-at-top import dask.dataframe as dd if (isinstance(x, (dd.Series, dd.DataFrame)) and (y is None or isinstance(y, (dd.Series, dd.DataFrame)))): data_feeder_cls = DaskDataFeeder else: data_feeder_cls = DataFeeder else: data_feeder_cls = DataFeeder if _is_iterable(x): if y is not None and not _is_iterable(y): raise ValueError('Both x and y should be iterators for ' 'streaming learning to work.') return StreamingDataFeeder(x, y, n_classes, batch_size) return data_feeder_cls( x, y, n_classes, batch_size, shuffle=shuffle, epochs=epochs)
[ "def", "setup_train_data_feeder", "(", "x", ",", "y", ",", "n_classes", ",", "batch_size", "=", "None", ",", "shuffle", "=", "True", ",", "epochs", "=", "None", ")", ":", "x", ",", "y", "=", "_data_type_filter", "(", "x", ",", "y", ")", "if", "HAS_DA...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py#L104-L152
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
SpinCtrlDouble.Create
(*args, **kwargs)
return _controls_.SpinCtrlDouble_Create(*args, **kwargs)
Create(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_ARROW_KEYS, double min=0, double max=100, double initial=0, double inc=1, String name="wxSpinCtrlDouble") -> bool
Create(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_ARROW_KEYS, double min=0, double max=100, double initial=0, double inc=1, String name="wxSpinCtrlDouble") -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "ID_ANY", "String", "value", "=", "wxEmptyString", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "SP_ARROW_KEYS", "double", "min", "=", "0", "dou...
def Create(*args, **kwargs): """ Create(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_ARROW_KEYS, double min=0, double max=100, double initial=0, double inc=1, String name="wxSpinCtrlDouble") -> bool """ return _controls_.SpinCtrlDouble_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "SpinCtrlDouble_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L2482-L2490
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/losses/python/losses/loss_ops.py
python
mean_squared_error
(predictions, labels=None, weights=1.0, scope=None)
Adds a Sum-of-Squares loss to the training procedure. `weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size [batch_size], then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector. If the shape of `weights` matches the shape of `predictions`, then the loss of each measurable element of `predictions` is scaled by the corresponding value of `weights`. Args: predictions: The predicted outputs. labels: The ground truth output tensor, same dimensions as 'predictions'. weights: Coefficients for the loss a scalar, a tensor of shape [batch_size] or a tensor whose shape matches `predictions`. scope: The scope for the operations performed in computing the loss. Returns: A scalar `Tensor` representing the loss value. Raises: ValueError: If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid.
Adds a Sum-of-Squares loss to the training procedure.
[ "Adds", "a", "Sum", "-", "of", "-", "Squares", "loss", "to", "the", "training", "procedure", "." ]
def mean_squared_error(predictions, labels=None, weights=1.0, scope=None): """Adds a Sum-of-Squares loss to the training procedure. `weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size [batch_size], then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector. If the shape of `weights` matches the shape of `predictions`, then the loss of each measurable element of `predictions` is scaled by the corresponding value of `weights`. Args: predictions: The predicted outputs. labels: The ground truth output tensor, same dimensions as 'predictions'. weights: Coefficients for the loss a scalar, a tensor of shape [batch_size] or a tensor whose shape matches `predictions`. scope: The scope for the operations performed in computing the loss. Returns: A scalar `Tensor` representing the loss value. Raises: ValueError: If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid. """ with ops.name_scope(scope, "mean_squared_error", [predictions, labels, weights]) as scope: predictions.get_shape().assert_is_compatible_with(labels.get_shape()) predictions = math_ops.cast(predictions, dtypes.float32) labels = math_ops.cast(labels, dtypes.float32) losses = math_ops.squared_difference(predictions, labels) return compute_weighted_loss(losses, weights, scope=scope)
[ "def", "mean_squared_error", "(", "predictions", ",", "labels", "=", "None", ",", "weights", "=", "1.0", ",", "scope", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "scope", ",", "\"mean_squared_error\"", ",", "[", "predictions", ",", "labe...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/losses/python/losses/loss_ops.py#L487-L518
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/optimizer/optimizer.py
python
Updater.get_states
(self, dump_optimizer=False)
return pickle.dumps((self.states, self.optimizer) if dump_optimizer else self.states)
Gets updater states. Parameters ---------- dump_optimizer : bool, default False Whether to also save the optimizer itself. This would also save optimizer information such as learning rate and weight decay schedules.
Gets updater states.
[ "Gets", "updater", "states", "." ]
def get_states(self, dump_optimizer=False): """Gets updater states. Parameters ---------- dump_optimizer : bool, default False Whether to also save the optimizer itself. This would also save optimizer information such as learning rate and weight decay schedules. """ return pickle.dumps((self.states, self.optimizer) if dump_optimizer else self.states)
[ "def", "get_states", "(", "self", ",", "dump_optimizer", "=", "False", ")", ":", "return", "pickle", ".", "dumps", "(", "(", "self", ".", "states", ",", "self", ".", "optimizer", ")", "if", "dump_optimizer", "else", "self", ".", "states", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/optimizer/optimizer.py#L1727-L1736
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/base.py
python
BaseContext.get_return_value
(self, builder, ty, val)
return self.data_model_manager[ty].as_return(builder, val)
Local value representation to return type representation
Local value representation to return type representation
[ "Local", "value", "representation", "to", "return", "type", "representation" ]
def get_return_value(self, builder, ty, val): """ Local value representation to return type representation """ return self.data_model_manager[ty].as_return(builder, val)
[ "def", "get_return_value", "(", "self", ",", "builder", ",", "ty", ",", "val", ")", ":", "return", "self", ".", "data_model_manager", "[", "ty", "]", ".", "as_return", "(", "builder", ",", "val", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/base.py#L661-L665
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Sizer.Detach
(*args, **kwargs)
return _core_.Sizer_Detach(*args, **kwargs)
Detach(self, item) -> bool Detaches an item from the sizer without destroying it. This method does not cause any layout or resizing to take place, call `Layout` to do so. The *item* parameter can be either a window, a sizer, or the zero-based index of the item to be detached. Returns True if the child item was found and detached.
Detach(self, item) -> bool
[ "Detach", "(", "self", "item", ")", "-", ">", "bool" ]
def Detach(*args, **kwargs): """ Detach(self, item) -> bool Detaches an item from the sizer without destroying it. This method does not cause any layout or resizing to take place, call `Layout` to do so. The *item* parameter can be either a window, a sizer, or the zero-based index of the item to be detached. Returns True if the child item was found and detached. """ return _core_.Sizer_Detach(*args, **kwargs)
[ "def", "Detach", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Sizer_Detach", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14519-L14529
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/tools/transformers/machine_info.py
python
MachineInfo.get_machine_info
(self)
return machine_info
Get machine info in metric format
Get machine info in metric format
[ "Get", "machine", "info", "in", "metric", "format" ]
def get_machine_info(self): """Get machine info in metric format""" gpu_info = self.get_gpu_info_by_nvml() cpu_info = cpuinfo.get_cpu_info() machine_info = { "gpu": gpu_info, "cpu": self.get_cpu_info(), "memory": self.get_memory_info(), "os": platform.platform(), "python": self._try_get(cpu_info, ["python_version"]), "packages": self.get_related_packages(), "onnxruntime": self.get_onnxruntime_info(), "pytorch": self.get_pytorch_info(), "tensorflow": self.get_tensorflow_info() } return machine_info
[ "def", "get_machine_info", "(", "self", ")", ":", "gpu_info", "=", "self", ".", "get_gpu_info_by_nvml", "(", ")", "cpu_info", "=", "cpuinfo", ".", "get_cpu_info", "(", ")", "machine_info", "=", "{", "\"gpu\"", ":", "gpu_info", ",", "\"cpu\"", ":", "self", ...
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/transformers/machine_info.py#L39-L55
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/client/timeline.py
python
_TensorTracker.last_unref
(self)
return max(self._unref_times)
Last unreference timestamp of this tensor (long integer).
Last unreference timestamp of this tensor (long integer).
[ "Last", "unreference", "timestamp", "of", "this", "tensor", "(", "long", "integer", ")", "." ]
def last_unref(self): """Last unreference timestamp of this tensor (long integer).""" return max(self._unref_times)
[ "def", "last_unref", "(", "self", ")", ":", "return", "max", "(", "self", ".", "_unref_times", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/timeline.py#L324-L326
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/incubate/fleet/base/role_maker.py
python
MPISymetricRoleMaker._worker_num
(self)
return 0
return the current number of worker
return the current number of worker
[ "return", "the", "current", "number", "of", "worker" ]
def _worker_num(self): """ return the current number of worker """ if self._check_role_generation(): return int(self._get_size() / self._proc_per_node) return 0
[ "def", "_worker_num", "(", "self", ")", ":", "if", "self", ".", "_check_role_generation", "(", ")", ":", "return", "int", "(", "self", ".", "_get_size", "(", ")", "/", "self", ".", "_proc_per_node", ")", "return", "0" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/base/role_maker.py#L381-L387
KhronosGroup/SPIR
f33c27876d9f3d5810162b60fa89cc13d2b55725
bindings/python/clang/cindex.py
python
TranslationUnit.diagnostics
(self)
return DiagIterator(self)
Return an iterable (and indexable) object containing the diagnostics.
Return an iterable (and indexable) object containing the diagnostics.
[ "Return", "an", "iterable", "(", "and", "indexable", ")", "object", "containing", "the", "diagnostics", "." ]
def diagnostics(self): """ Return an iterable (and indexable) object containing the diagnostics. """ class DiagIterator: def __init__(self, tu): self.tu = tu def __len__(self): return int(conf.lib.clang_getNumDiagnostics(self.tu)) def __getitem__(self, key): diag = conf.lib.clang_getDiagnostic(self.tu, key) if not diag: raise IndexError return Diagnostic(diag) return DiagIterator(self)
[ "def", "diagnostics", "(", "self", ")", ":", "class", "DiagIterator", ":", "def", "__init__", "(", "self", ",", "tu", ")", ":", "self", ".", "tu", "=", "tu", "def", "__len__", "(", "self", ")", ":", "return", "int", "(", "conf", ".", "lib", ".", ...
https://github.com/KhronosGroup/SPIR/blob/f33c27876d9f3d5810162b60fa89cc13d2b55725/bindings/python/clang/cindex.py#L2100-L2117
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
tools/coverage/coverage_diff_list.py
python
filter_by
(list_file, max_rate)
Args: list_file (str): File of list. max_rate (float): Max rate. Returns: tuple: File and coverage rate.
Args: list_file (str): File of list. max_rate (float): Max rate.
[ "Args", ":", "list_file", "(", "str", ")", ":", "File", "of", "list", ".", "max_rate", "(", "float", ")", ":", "Max", "rate", "." ]
def filter_by(list_file, max_rate): """ Args: list_file (str): File of list. max_rate (float): Max rate. Returns: tuple: File and coverage rate. """ with open(list_file) as list_file: for line in list_file: line = line.strip() split = line.split('|') # name name = split[0].strip() if name.startswith('/paddle/'): name = name[len('/paddle/'):] # rate try: rate = split[1].split()[0].strip('%') rate = float(rate) if rate >= max_rate: continue except: pass print(name, rate)
[ "def", "filter_by", "(", "list_file", ",", "max_rate", ")", ":", "with", "open", "(", "list_file", ")", "as", "list_file", ":", "for", "line", "in", "list_file", ":", "line", "=", "line", ".", "strip", "(", ")", "split", "=", "line", ".", "split", "(...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/coverage/coverage_diff_list.py#L24-L57
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/tex.py
python
ScanFiles
(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files)
return file_tests
For theFile (a Node) update any file_tests and search for graphics files then find all included files and call ScanFiles recursively for each of them
For theFile (a Node) update any file_tests and search for graphics files then find all included files and call ScanFiles recursively for each of them
[ "For", "theFile", "(", "a", "Node", ")", "update", "any", "file_tests", "and", "search", "for", "graphics", "files", "then", "find", "all", "included", "files", "and", "call", "ScanFiles", "recursively", "for", "each", "of", "them" ]
def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files): """ For theFile (a Node) update any file_tests and search for graphics files then find all included files and call ScanFiles recursively for each of them""" content = theFile.get_text_contents() if Verbose: print(" scanning ",str(theFile)) for i in range(len(file_tests_search)): if file_tests[i][0] is None: if Verbose: print("scan i ",i," files_tests[i] ",file_tests[i], file_tests[i][1]) file_tests[i][0] = file_tests_search[i].search(content) if Verbose and file_tests[i][0]: print(" found match for ",file_tests[i][1][-1]) # for newglossary insert the suffixes in file_tests[i] if file_tests[i][0] and file_tests[i][1][-1] == 'newglossary': findresult = file_tests_search[i].findall(content) for l in range(len(findresult)) : (file_tests[i][1]).insert(0,'.'+findresult[l][3]) (file_tests[i][1]).insert(0,'.'+findresult[l][2]) (file_tests[i][1]).insert(0,'.'+findresult[l][0]) suffix_list = ['.'+findresult[l][0],'.'+findresult[l][2],'.'+findresult[l][3] ] newglossary_suffix.append(suffix_list) if Verbose: print(" new suffixes for newglossary ",newglossary_suffix) incResult = includeOnly_re.search(content) if incResult: aux_files.append(os.path.join(targetdir, incResult.group(1))) if Verbose: print(r"\include file names : ", aux_files) # recursively call this on each of the included files inc_files = [ ] inc_files.extend( include_re.findall(content) ) if Verbose: print("files included by '%s': "%str(theFile),inc_files) # inc_files is list of file names as given. need to find them # using TEXINPUTS paths. for src in inc_files: srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False) if srcNode is not None: file_tests = ScanFiles(srcNode, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files) if Verbose: print(" done scanning ",str(theFile)) return file_tests
[ "def", "ScanFiles", "(", "theFile", ",", "target", ",", "paths", ",", "file_tests", ",", "file_tests_search", ",", "env", ",", "graphics_extensions", ",", "targetdir", ",", "aux_files", ")", ":", "content", "=", "theFile", ".", "get_text_contents", "(", ")", ...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/tex.py#L623-L670
Tokutek/mongo
0653eabe2c5b9d12b4814617cb7fb2d799937a0f
src/third_party/v8/tools/stats-viewer.py
python
SharedDataAccess.IntAt
(self, index)
return result
Return the little-endian 32-byte int at the specified byte index.
Return the little-endian 32-byte int at the specified byte index.
[ "Return", "the", "little", "-", "endian", "32", "-", "byte", "int", "at", "the", "specified", "byte", "index", "." ]
def IntAt(self, index): """Return the little-endian 32-byte int at the specified byte index.""" word_str = self.data[index:index+4] result, = struct.unpack("I", word_str) return result
[ "def", "IntAt", "(", "self", ",", "index", ")", ":", "word_str", "=", "self", ".", "data", "[", "index", ":", "index", "+", "4", "]", "result", ",", "=", "struct", ".", "unpack", "(", "\"I\"", ",", "word_str", ")", "return", "result" ]
https://github.com/Tokutek/mongo/blob/0653eabe2c5b9d12b4814617cb7fb2d799937a0f/src/third_party/v8/tools/stats-viewer.py#L316-L320
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/configparser.py
python
ConfigParser._read_defaults
(self, defaults)
Reads the defaults passed in the initializer, implicitly converting values to strings like the rest of the API. Does not perform interpolation for backwards compatibility.
Reads the defaults passed in the initializer, implicitly converting values to strings like the rest of the API.
[ "Reads", "the", "defaults", "passed", "in", "the", "initializer", "implicitly", "converting", "values", "to", "strings", "like", "the", "rest", "of", "the", "API", "." ]
def _read_defaults(self, defaults): """Reads the defaults passed in the initializer, implicitly converting values to strings like the rest of the API. Does not perform interpolation for backwards compatibility. """ try: hold_interpolation = self._interpolation self._interpolation = Interpolation() self.read_dict({self.default_section: defaults}) finally: self._interpolation = hold_interpolation
[ "def", "_read_defaults", "(", "self", ",", "defaults", ")", ":", "try", ":", "hold_interpolation", "=", "self", ".", "_interpolation", "self", ".", "_interpolation", "=", "Interpolation", "(", ")", "self", ".", "read_dict", "(", "{", "self", ".", "default_se...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/configparser.py#L1213-L1224
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.SetPrintMagnification
(*args, **kwargs)
return _stc.StyledTextCtrl_SetPrintMagnification(*args, **kwargs)
SetPrintMagnification(self, int magnification) Sets the print magnification added to the point size of each style for printing.
SetPrintMagnification(self, int magnification)
[ "SetPrintMagnification", "(", "self", "int", "magnification", ")" ]
def SetPrintMagnification(*args, **kwargs): """ SetPrintMagnification(self, int magnification) Sets the print magnification added to the point size of each style for printing. """ return _stc.StyledTextCtrl_SetPrintMagnification(*args, **kwargs)
[ "def", "SetPrintMagnification", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetPrintMagnification", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L3464-L3470
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py
python
Counter.__and__
(self, other)
return result
Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1})
Intersection is the minimum of corresponding counts.
[ "Intersection", "is", "the", "minimum", "of", "corresponding", "counts", "." ]
def __and__(self, other): ''' Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): other_count = other[elem] newcount = count if count < other_count else other_count if newcount > 0: result[elem] = newcount return result
[ "def", "__and__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Counter", ")", ":", "return", "NotImplemented", "result", "=", "Counter", "(", ")", "for", "elem", ",", "count", "in", "self", ".", "items", "(", ")...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py#L782-L797
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/contact.py
python
worldContactMap
(world,padding,kFriction=1,collider=None)
return cmap
Given a WorldModel, returns a contact map representing all current contacts (distance >= 0 and <= padding). Args: world (WorldModel): the world padding (float or function): if float, a constant padding, otherwise a function f(object) that returns the padding for an object. kFriction (float or function, optional): if float, a constant friction. Otherwise, a function f(object1,object2) that returns the friction for a pair of objects. collider (WorldCollider, optional): if given, only the pairs of objects whose collisions are enabled will be checked. Note: Contact normals may be set to (0,0,0) if they cannot be computed properly, such as when two meshes intersect.
Given a WorldModel, returns a contact map representing all current contacts (distance >= 0 and <= padding).
[ "Given", "a", "WorldModel", "returns", "a", "contact", "map", "representing", "all", "current", "contacts", "(", "distance", ">", "=", "0", "and", "<", "=", "padding", ")", "." ]
def worldContactMap(world,padding,kFriction=1,collider=None): """Given a WorldModel, returns a contact map representing all current contacts (distance >= 0 and <= padding). Args: world (WorldModel): the world padding (float or function): if float, a constant padding, otherwise a function f(object) that returns the padding for an object. kFriction (float or function, optional): if float, a constant friction. Otherwise, a function f(object1,object2) that returns the friction for a pair of objects. collider (WorldCollider, optional): if given, only the pairs of objects whose collisions are enabled will be checked. Note: Contact normals may be set to (0,0,0) if they cannot be computed properly, such as when two meshes intersect. """ fpadding = padding ffriction = kFriction if not callable(padding): fpadding = lambda obj:padding if not callable(kFriction): ffriction = lambda obj1,obj2:kFriction from collide import WorldCollider if collider is None: collider = WorldCollider(world) cmap = dict() for (i,j) in collider.collisionTests(bb_reject=False): obj1,geom1 = i obj2,geom2 = j pad1 = fpadding(obj1) pad2 = fpadding(obj2) clist = geometryContacts(geom1,geom2,pad1,pad2) if len(clist) > 0: kf = ffriction(obj1,obj2) for c in clist: c.kFriction = kf cmap[(obj1,obj2)] = clist return cmap
[ "def", "worldContactMap", "(", "world", ",", "padding", ",", "kFriction", "=", "1", ",", "collider", "=", "None", ")", ":", "fpadding", "=", "padding", "ffriction", "=", "kFriction", "if", "not", "callable", "(", "padding", ")", ":", "fpadding", "=", "la...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/contact.py#L264-L305
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/engine/topology.py
python
Layer.get_input_mask_at
(self, node_index)
Retrieves the input mask tensor(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A mask tensor (or list of tensors if the layer has multiple inputs).
Retrieves the input mask tensor(s) of a layer at a given node.
[ "Retrieves", "the", "input", "mask", "tensor", "(", "s", ")", "of", "a", "layer", "at", "a", "given", "node", "." ]
def get_input_mask_at(self, node_index): """Retrieves the input mask tensor(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A mask tensor (or list of tensors if the layer has multiple inputs). """ inputs = self.get_input_at(node_index) if isinstance(inputs, list): return [getattr(x, '_keras_mask', None) for x in inputs] else: return getattr(inputs, '_keras_mask', None)
[ "def", "get_input_mask_at", "(", "self", ",", "node_index", ")", ":", "inputs", "=", "self", ".", "get_input_at", "(", "node_index", ")", "if", "isinstance", "(", "inputs", ",", "list", ")", ":", "return", "[", "getattr", "(", "x", ",", "'_keras_mask'", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/engine/topology.py#L318-L335
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/patchcheck.py
python
changed_files
(base_branch=None)
return filenames2
Get the list of changed or added files from git.
Get the list of changed or added files from git.
[ "Get", "the", "list", "of", "changed", "or", "added", "files", "from", "git", "." ]
def changed_files(base_branch=None): """Get the list of changed or added files from git.""" if os.path.exists(os.path.join(SRCDIR, '.git')): # We just use an existence check here as: # directory = normal git checkout/clone # file = git worktree directory if base_branch: cmd = 'git diff --name-status ' + base_branch else: cmd = 'git status --porcelain' filenames = [] with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd=SRCDIR) as st: for line in st.stdout: line = line.decode().rstrip() status_text, filename = line.split(maxsplit=1) status = set(status_text) # modified, added or unmerged files if not status.intersection('MAU'): continue if ' -> ' in filename: # file is renamed filename = filename.split(' -> ', 2)[1].strip() filenames.append(filename) else: sys.exit('need a git checkout to get modified files') filenames2 = [] for filename in filenames: # Normalize the path to be able to match using .startswith() filename = os.path.normpath(filename) if any(filename.startswith(path) for path in EXCLUDE_DIRS): # Exclude the file continue filenames2.append(filename) return filenames2
[ "def", "changed_files", "(", "base_branch", "=", "None", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "SRCDIR", ",", "'.git'", ")", ")", ":", "# We just use an existence check here as:", "# directory = normal git...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/patchcheck.py#L94-L131
eric612/Caffe-YOLOv3-Windows
6736ca6e16781789b828cc64218ff77cc3454e5d
scripts/cpp_lint.py
python
_IncludeState.IsInAlphabeticalOrder
(self, clean_lines, linenum, header_path)
return True
Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order.
Check if a header is in alphabetical order with the previous header.
[ "Check", "if", "a", "header", "is", "in", "alphabetical", "order", "with", "the", "previous", "header", "." ]
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and not Match(r'^\s*$', clean_lines.elided[linenum - 1])): return False return True
[ "def", "IsInAlphabeticalOrder", "(", "self", ",", "clean_lines", ",", "linenum", ",", "header_path", ")", ":", "# If previous section is different from current section, _last_header will", "# be reset to empty string, so it's always less than current header.", "#", "# If previous line ...
https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/scripts/cpp_lint.py#L616-L635
NREL/EnergyPlus
fadc5973b85c70e8cc923efb69c144e808a26078
src/EnergyPlus/api/datatransfer.py
python
DataExchange.get_meter_handle
(self, state: c_void_p, meter_name: Union[str, bytes])
return self.api.getMeterHandle(state, meter_name)
Get a handle to a meter in a running simulation. The meter name passed into this function do not need to be a particular case, as the EnergyPlus API automatically converts values to upper-case when finding matches to internal variables in the simulation. Note also that the meter name passed in here can be either strings or bytes, as this wrapper handles conversion as needed. :param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`. :param meter_name: The name of the variable to retrieve, e.g. "Electricity:Facility", or "Fans:Electricity" :return: An integer ID for this meter, or -1 if one could not be found.
Get a handle to a meter in a running simulation.
[ "Get", "a", "handle", "to", "a", "meter", "in", "a", "running", "simulation", "." ]
def get_meter_handle(self, state: c_void_p, meter_name: Union[str, bytes]) -> int: """ Get a handle to a meter in a running simulation. The meter name passed into this function do not need to be a particular case, as the EnergyPlus API automatically converts values to upper-case when finding matches to internal variables in the simulation. Note also that the meter name passed in here can be either strings or bytes, as this wrapper handles conversion as needed. :param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`. :param meter_name: The name of the variable to retrieve, e.g. "Electricity:Facility", or "Fans:Electricity" :return: An integer ID for this meter, or -1 if one could not be found. """ meter_name = meter_name.upper() if isinstance(meter_name, str): meter_name = meter_name.encode('utf-8') elif not isinstance(meter_name, bytes): raise EnergyPlusException( "`get_meter_handle` expects `component_type` as a `str` or UTF-8 encoded `bytes`, not " "'{}'".format(meter_name)) return self.api.getMeterHandle(state, meter_name)
[ "def", "get_meter_handle", "(", "self", ",", "state", ":", "c_void_p", ",", "meter_name", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "int", ":", "meter_name", "=", "meter_name", ".", "upper", "(", ")", "if", "isinstance", "(", "meter_name", ...
https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/src/EnergyPlus/api/datatransfer.py#L386-L407
widelands/widelands
e9f047d46a23d81312237d52eabf7d74e8de52d6
utils/update_authors.py
python
add_lua_array
(values)
return text
Creates an array.
Creates an array.
[ "Creates", "an", "array", "." ]
def add_lua_array(values): """Creates an array.""" text = '{' for value in values: if value.startswith('_("'): # a translation marker has already been added text += value else: text += '"' + value + '",' text += '},' return text
[ "def", "add_lua_array", "(", "values", ")", ":", "text", "=", "'{'", "for", "value", "in", "values", ":", "if", "value", ".", "startswith", "(", "'_(\"'", ")", ":", "# a translation marker has already been added", "text", "+=", "value", "else", ":", "text", ...
https://github.com/widelands/widelands/blob/e9f047d46a23d81312237d52eabf7d74e8de52d6/utils/update_authors.py#L17-L28
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/operator/_hamiltonian.py
python
Ising.J
(self)
return self._J
The magnitude of the hopping
The magnitude of the hopping
[ "The", "magnitude", "of", "the", "hopping" ]
def J(self) -> float: """The magnitude of the hopping""" return self._J
[ "def", "J", "(", "self", ")", "->", "float", ":", "return", "self", ".", "_J" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/operator/_hamiltonian.py#L162-L164
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Taskmaster.py
python
Task.postprocess
(self)
Post-processes a task after it's been executed. This examines all the targets just built (or not, we don't care if the build was successful, or even if there was no build because everything was up-to-date) to see if they have any waiting parent Nodes, or Nodes waiting on a common side effect, that can be put back on the candidates list.
Post-processes a task after it's been executed.
[ "Post", "-", "processes", "a", "task", "after", "it", "s", "been", "executed", "." ]
def postprocess(self): """ Post-processes a task after it's been executed. This examines all the targets just built (or not, we don't care if the build was successful, or even if there was no build because everything was up-to-date) to see if they have any waiting parent Nodes, or Nodes waiting on a common side effect, that can be put back on the candidates list. """ T = self.tm.trace if T: T.write(self.trace_message(u'Task.postprocess()', self.node)) # We may have built multiple targets, some of which may have # common parents waiting for this build. Count up how many # targets each parent was waiting for so we can subtract the # values later, and so we *don't* put waiting side-effect Nodes # back on the candidates list if the Node is also a waiting # parent. targets = set(self.targets) pending_children = self.tm.pending_children parents = {} for t in targets: # A node can only be in the pending_children set if it has # some waiting_parents. if t.waiting_parents: if T: T.write(self.trace_message(u'Task.postprocess()', t, 'removing')) pending_children.discard(t) for p in t.waiting_parents: parents[p] = parents.get(p, 0) + 1 for t in targets: if t.side_effects is not None: for s in t.side_effects: if s.get_state() == NODE_EXECUTING: s.set_state(NODE_NO_STATE) for p in s.waiting_parents: parents[p] = parents.get(p, 0) + 1 for p in s.waiting_s_e: if p.ref_count == 0: self.tm.candidates.append(p) for p, subtract in parents.items(): p.ref_count = p.ref_count - subtract if T: T.write(self.trace_message(u'Task.postprocess()', p, 'adjusted parent ref count')) if p.ref_count == 0: self.tm.candidates.append(p) for t in targets: t.postprocess()
[ "def", "postprocess", "(", "self", ")", ":", "T", "=", "self", ".", "tm", ".", "trace", "if", "T", ":", "T", ".", "write", "(", "self", ".", "trace_message", "(", "u'Task.postprocess()'", ",", "self", ".", "node", ")", ")", "# We may have built multiple ...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Taskmaster.py#L432-L487
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py
python
get_axis_order
()
return axis_order
Get the axis_order set by any containing axis_order_scope. Returns: List of strings giving an order to use for axis names, or None, if no axis order is set.
Get the axis_order set by any containing axis_order_scope.
[ "Get", "the", "axis_order", "set", "by", "any", "containing", "axis_order_scope", "." ]
def get_axis_order(): """Get the axis_order set by any containing axis_order_scope. Returns: List of strings giving an order to use for axis names, or None, if no axis order is set. """ # By storing axis_order in the graph, we can ensure that axis_order_scope is # thread-safe. axis_order_list = ops.get_collection(_AXIS_ORDER_KEY) if axis_order_list: axis_order, = axis_order_list else: axis_order = None return axis_order
[ "def", "get_axis_order", "(", ")", ":", "# By storing axis_order in the graph, we can ensure that axis_order_scope is", "# thread-safe.", "axis_order_list", "=", "ops", ".", "get_collection", "(", "_AXIS_ORDER_KEY", ")", "if", "axis_order_list", ":", "axis_order", ",", "=", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py#L779-L793
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/graph_util_impl.py
python
_get_colocated_node_name
(colocated_node_name)
return colocated_node_decoded
Decodes colocated node name and returns it without loc:@ prepended.
Decodes colocated node name and returns it without loc:
[ "Decodes", "colocated", "node", "name", "and", "returns", "it", "without", "loc", ":" ]
def _get_colocated_node_name(colocated_node_name): """Decodes colocated node name and returns it without loc:@ prepended.""" colocated_node_decoded = colocated_node_name.decode("utf-8") if colocated_node_decoded.startswith("loc:@"): return colocated_node_decoded[5:] return colocated_node_decoded
[ "def", "_get_colocated_node_name", "(", "colocated_node_name", ")", ":", "colocated_node_decoded", "=", "colocated_node_name", ".", "decode", "(", "\"utf-8\"", ")", "if", "colocated_node_decoded", ".", "startswith", "(", "\"loc:@\"", ")", ":", "return", "colocated_node_...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/graph_util_impl.py#L167-L172
telefonicaid/fiware-orion
27c3202b9ddcfb9e3635a0af8d373f76e89b1d24
scripts/pdi-pep8.py
python
whitespace_before_inline_comment
(logical_line, tokens)
Separate inline comments by at least two spaces. An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space. Okay: x = x + 1 # Increment x Okay: x = x + 1 # Increment x E261: x = x + 1 # Increment x E262: x = x + 1 #Increment x E262: x = x + 1 # Increment x
Separate inline comments by at least two spaces.
[ "Separate", "inline", "comments", "by", "at", "least", "two", "spaces", "." ]
def whitespace_before_inline_comment(logical_line, tokens): """ Separate inline comments by at least two spaces. An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space. Okay: x = x + 1 # Increment x Okay: x = x + 1 # Increment x E261: x = x + 1 # Increment x E262: x = x + 1 #Increment x E262: x = x + 1 # Increment x """ prev_end = (0, 0) for token_type, text, start, end, line in tokens: if token_type == tokenize.NL: continue if token_type == tokenize.COMMENT: if not line[:start[1]].strip(): continue if prev_end[0] == start[0] and start[1] < prev_end[1] + 2: return (prev_end, "E261 at least two spaces before inline comment") if (len(text) > 1 and text.startswith('# ') or not text.startswith('# ')): return start, "E262 inline comment should start with '# '" else: prev_end = end
[ "def", "whitespace_before_inline_comment", "(", "logical_line", ",", "tokens", ")", ":", "prev_end", "=", "(", "0", ",", "0", ")", "for", "token_type", ",", "text", ",", "start", ",", "end", ",", "line", "in", "tokens", ":", "if", "token_type", "==", "to...
https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/pdi-pep8.py#L579-L607
opencv/opencv
76aff8478883858f0e46746044348ebb16dc3c67
doc/pattern_tools/svgfig.py
python
Curve.subsample
(self, left, right, depth, trans=None)
Part of the adaptive-sampling algorithm that chooses the best sample points. Called by sample().
Part of the adaptive-sampling algorithm that chooses the best sample points. Called by sample().
[ "Part", "of", "the", "adaptive", "-", "sampling", "algorithm", "that", "chooses", "the", "best", "sample", "points", ".", "Called", "by", "sample", "()", "." ]
def subsample(self, left, right, depth, trans=None): """Part of the adaptive-sampling algorithm that chooses the best sample points. Called by sample().""" if self.random_sampling: mid = self.Sample(left.t + random.uniform(0.3, 0.7) * (right.t - left.t)) else: mid = self.Sample(left.t + 0.5 * (right.t - left.t)) left.right = mid right.left = mid mid.link(left, right) mid.evaluate(self.f, trans) # calculate the distance of closest approach of mid to the line between left and right numer = left.X*(right.Y - mid.Y) + mid.X*(left.Y - right.Y) + right.X*(mid.Y - left.Y) denom = math.sqrt((left.X - right.X)**2 + (left.Y - right.Y)**2) # if we haven't sampled enough or left fails to be close enough to right, or mid fails to be linear enough... if (depth < 3 or (denom == 0 and left.t != right.t) or denom > self.discontinuity_limit or (denom != 0. and abs(numer/denom) > self.linearity_limit)): # and we haven't sampled too many points if depth < self.recursion_limit: self.subsample(left, mid, depth+1, trans) self.subsample(mid, right, depth+1, trans) else: # We've sampled many points and yet it's still not a small linear gap. # Break the line: it's a discontinuity mid.y = mid.Y = None
[ "def", "subsample", "(", "self", ",", "left", ",", "right", ",", "depth", ",", "trans", "=", "None", ")", ":", "if", "self", ".", "random_sampling", ":", "mid", "=", "self", ".", "Sample", "(", "left", ".", "t", "+", "random", ".", "uniform", "(", ...
https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/doc/pattern_tools/svgfig.py#L1777-L1809
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
FlagValues._GetFlagsDefinedByModule
(self, module)
return list(self.FlagsByModuleDict().get(module, []))
Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object.
Returns the list of flags defined by a module.
[ "Returns", "the", "list", "of", "flags", "defined", "by", "a", "module", "." ]
def _GetFlagsDefinedByModule(self, module): """Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ return list(self.FlagsByModuleDict().get(module, []))
[ "def", "_GetFlagsDefinedByModule", "(", "self", ",", "module", ")", ":", "if", "not", "isinstance", "(", "module", ",", "str", ")", ":", "module", "=", "module", ".", "__name__", "return", "list", "(", "self", ".", "FlagsByModuleDict", "(", ")", ".", "ge...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L913-L927
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/akg/ascend/maximum.py
python
_maximum_akg
()
return
Maximum Akg register
Maximum Akg register
[ "Maximum", "Akg", "register" ]
def _maximum_akg(): """Maximum Akg register""" return
[ "def", "_maximum_akg", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/akg/ascend/maximum.py#L34-L36
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/ops.py
python
RegisterGradient.__init__
(self, op_type)
Creates a new decorator with `op_type` as the Operation type. Args: op_type: The string type of an operation. This corresponds to the `OpDef.name` field for the proto that defines the operation.
Creates a new decorator with `op_type` as the Operation type.
[ "Creates", "a", "new", "decorator", "with", "op_type", "as", "the", "Operation", "type", "." ]
def __init__(self, op_type): """Creates a new decorator with `op_type` as the Operation type. Args: op_type: The string type of an operation. This corresponds to the `OpDef.name` field for the proto that defines the operation. """ if not isinstance(op_type, six.string_types): raise TypeError("op_type must be a string") self._op_type = op_type
[ "def", "__init__", "(", "self", ",", "op_type", ")", ":", "if", "not", "isinstance", "(", "op_type", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"op_type must be a string\"", ")", "self", ".", "_op_type", "=", "op_type" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L1593-L1602
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/misc_util.py
python
has_cxx_sources
(sources)
return False
Return True if sources contains C++ files
Return True if sources contains C++ files
[ "Return", "True", "if", "sources", "contains", "C", "++", "files" ]
def has_cxx_sources(sources): """Return True if sources contains C++ files """ for source in sources: if cxx_ext_match(source): return True return False
[ "def", "has_cxx_sources", "(", "sources", ")", ":", "for", "source", "in", "sources", ":", "if", "cxx_ext_match", "(", "source", ")", ":", "return", "True", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/misc_util.py#L503-L508
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/trace.py
python
find_strings
(filename)
return d
Return a dict of possible docstring positions. The dict maps line numbers to strings. There is an entry for line that contains only a string or a part of a triple-quoted string.
Return a dict of possible docstring positions.
[ "Return", "a", "dict", "of", "possible", "docstring", "positions", "." ]
def find_strings(filename): """Return a dict of possible docstring positions. The dict maps line numbers to strings. There is an entry for line that contains only a string or a part of a triple-quoted string. """ d = {} # If the first token is a string, then it's the module docstring. # Add this special case so that the test in the loop passes. prev_ttype = token.INDENT f = open(filename) for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline): if ttype == token.STRING: if prev_ttype == token.INDENT: sline, scol = start eline, ecol = end for i in range(sline, eline + 1): d[i] = 1 prev_ttype = ttype f.close() return d
[ "def", "find_strings", "(", "filename", ")", ":", "d", "=", "{", "}", "# If the first token is a string, then it's the module docstring.", "# Add this special case so that the test in the loop passes.", "prev_ttype", "=", "token", ".", "INDENT", "f", "=", "open", "(", "file...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/trace.py#L415-L436
tensorflow/minigo
6d89c202cdceaf449aefc3149ab2110d44f1a6a4
validate.py
python
validate
(*tf_records)
Validate a model's performance on a set of holdout data.
Validate a model's performance on a set of holdout data.
[ "Validate", "a", "model", "s", "performance", "on", "a", "set", "of", "holdout", "data", "." ]
def validate(*tf_records): """Validate a model's performance on a set of holdout data.""" if FLAGS.use_tpu: def _input_fn(params): return preprocessing.get_tpu_input_tensors( params['train_batch_size'], params['input_layout'], tf_records, filter_amount=1.0) else: def _input_fn(): return preprocessing.get_input_tensors( FLAGS.train_batch_size, FLAGS.input_layout, tf_records, filter_amount=1.0, shuffle_examples=False) steps = FLAGS.examples_to_validate // FLAGS.train_batch_size if FLAGS.use_tpu: steps //= FLAGS.num_tpu_cores estimator = dual_net.get_estimator() with utils.logged_timer("Validating"): estimator.evaluate(_input_fn, steps=steps, name=FLAGS.validate_name)
[ "def", "validate", "(", "*", "tf_records", ")", ":", "if", "FLAGS", ".", "use_tpu", ":", "def", "_input_fn", "(", "params", ")", ":", "return", "preprocessing", ".", "get_tpu_input_tensors", "(", "params", "[", "'train_batch_size'", "]", ",", "params", "[", ...
https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/validate.py#L46-L65
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Plot/Plot.py
python
Line.getp
(self, prop)
return plt.getp(self.line, prop)
Get line property value. Keyword arguments: prop -- Property name.
Get line property value.
[ "Get", "line", "property", "value", "." ]
def getp(self, prop): """Get line property value. Keyword arguments: prop -- Property name. """ return plt.getp(self.line, prop)
[ "def", "getp", "(", "self", ",", "prop", ")", ":", "return", "plt", ".", "getp", "(", "self", ".", "line", ",", "prop", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Plot/Plot.py#L398-L404
interpretml/interpret
29466bffc04505fe4f836a83fcfebfd313ac8454
python/interpret-core/interpret/perf/curve.py
python
ROC.__init__
(self, predict_fn, feature_names=None, feature_types=None, **kwargs)
Initializes class. Args: predict_fn: Function of blackbox that takes input, and returns prediction. feature_names: List of feature names. feature_types: List of feature types. **kwargs: Currently unused. Due for deprecation.
Initializes class.
[ "Initializes", "class", "." ]
def __init__(self, predict_fn, feature_names=None, feature_types=None, **kwargs): """ Initializes class. Args: predict_fn: Function of blackbox that takes input, and returns prediction. feature_names: List of feature names. feature_types: List of feature types. **kwargs: Currently unused. Due for deprecation. """ self.predict_fn = predict_fn self.feature_names = feature_names self.feature_types = feature_types self.kwargs = kwargs
[ "def", "__init__", "(", "self", ",", "predict_fn", ",", "feature_names", "=", "None", ",", "feature_types", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "predict_fn", "=", "predict_fn", "self", ".", "feature_names", "=", "feature_names", "s...
https://github.com/interpretml/interpret/blob/29466bffc04505fe4f836a83fcfebfd313ac8454/python/interpret-core/interpret/perf/curve.py#L84-L96
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/distribution.py
python
Distribution.survival_function
(self, value, *args, **kwargs)
return self._call_survival(value, *args, **kwargs)
Evaluate the survival function at given value. Args: value (Tensor): value to be evaluated. *args (list): the list of positional arguments forwarded to subclasses. **kwargs (dict): the dictionary of keyword arguments forwarded to subclasses. Note: A distribution can be optionally passed to the function by passing its dist_spec_args through `args` or `kwargs`. Output: Tensor, the survival function of the distribution.
Evaluate the survival function at given value.
[ "Evaluate", "the", "survival", "function", "at", "given", "value", "." ]
def survival_function(self, value, *args, **kwargs): """ Evaluate the survival function at given value. Args: value (Tensor): value to be evaluated. *args (list): the list of positional arguments forwarded to subclasses. **kwargs (dict): the dictionary of keyword arguments forwarded to subclasses. Note: A distribution can be optionally passed to the function by passing its dist_spec_args through `args` or `kwargs`. Output: Tensor, the survival function of the distribution. """ return self._call_survival(value, *args, **kwargs)
[ "def", "survival_function", "(", "self", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_call_survival", "(", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/distribution.py#L510-L526
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/checkdeps/graphdeps.py
python
DepsGrapher._DumpDependenciesImpl
(self, deps, out)
Computes nodes' and edges' properties for the dependency graph |deps| and carries out the actual dumping to a file/pipe |out|.
Computes nodes' and edges' properties for the dependency graph |deps| and carries out the actual dumping to a file/pipe |out|.
[ "Computes", "nodes", "and", "edges", "properties", "for", "the", "dependency", "graph", "|deps|", "and", "carries", "out", "the", "actual", "dumping", "to", "a", "file", "/", "pipe", "|out|", "." ]
def _DumpDependenciesImpl(self, deps, out): """Computes nodes' and edges' properties for the dependency graph |deps| and carries out the actual dumping to a file/pipe |out|.""" deps_graph = dict() deps_srcs = set() # Pre-initialize the graph with src->(dst, allow) pairs. for (allow, src, dst) in deps: if allow == Rule.TEMP_ALLOW and self.ignore_temp_rules: continue deps_srcs.add(src) if src not in deps_graph: deps_graph[src] = [] deps_graph[src].append((dst, allow)) # Add all hierarchical parents too, in case some of them don't have their # own DEPS, and therefore are missing from the list of rules. Those will # be recursively populated with their parents' rules in the next block. parent_src = os.path.dirname(src) while parent_src: if parent_src not in deps_graph: deps_graph[parent_src] = [] parent_src = os.path.dirname(parent_src) # For every node, propagate its rules down to all its children. deps_srcs = list(deps_srcs) deps_srcs.sort() for src in deps_srcs: parent_src = os.path.dirname(src) if parent_src: # We presort the list, so parents are guaranteed to precede children. assert parent_src in deps_graph,\ "src: %s, parent_src: %s" % (src, parent_src) for (dst, allow) in deps_graph[parent_src]: # Check that this node does not explicitly override a rule from the # parent that we're about to add. if ((dst, Rule.ALLOW) not in deps_graph[src]) and \ ((dst, Rule.TEMP_ALLOW) not in deps_graph[src]) and \ ((dst, Rule.DISALLOW) not in deps_graph[src]): deps_graph[src].append((dst, allow)) node_props = {} edges = [] # 1) Populate a list of edge specifications in DOT format; # 2) Populate a list of computed raw node attributes to be output as node # specifications in DOT format later on. # Edges and nodes are emphasized with color and line/border weight depending # on how many of incl/excl/hilite_fanins/hilite_fanouts filters they hit, # and in what way. for src in deps_graph.keys(): for (dst, allow) in deps_graph[src]: if allow == Rule.DISALLOW and self.hide_disallowed_deps: continue if allow == Rule.ALLOW and src == dst: continue edge_spec = "%s->%s" % (src, dst) if not re.search(self.incl, edge_spec) or \ re.search(self.excl, edge_spec): continue if src not in node_props: node_props[src] = {'hilite': None, 'degree': 0} if dst not in node_props: node_props[dst] = {'hilite': None, 'degree': 0} edge_weight = 1 if self.hilite_fanouts and re.search(self.hilite_fanouts, src): node_props[src]['hilite'] = 'lightgreen' node_props[dst]['hilite'] = 'lightblue' node_props[dst]['degree'] += 1 edge_weight += 1 if self.hilite_fanins and re.search(self.hilite_fanins, dst): node_props[src]['hilite'] = 'lightblue' node_props[dst]['hilite'] = 'lightgreen' node_props[src]['degree'] += 1 edge_weight += 1 if allow == Rule.ALLOW: edge_color = (edge_weight > 1) and 'blue' or 'green' edge_style = 'solid' elif allow == Rule.TEMP_ALLOW: edge_color = (edge_weight > 1) and 'blue' or 'green' edge_style = 'dashed' else: edge_color = 'red' edge_style = 'dashed' edges.append(' "%s" -> "%s" [style=%s,color=%s,penwidth=%d];' % \ (src, dst, edge_style, edge_color, edge_weight)) # Reformat the computed raw node attributes into a final DOT representation. nodes = [] for (node, attrs) in node_props.iteritems(): attr_strs = [] if attrs['hilite']: attr_strs.append('style=filled,fillcolor=%s' % attrs['hilite']) attr_strs.append('penwidth=%d' % (attrs['degree'] or 1)) nodes.append(' "%s" [%s];' % (node, ','.join(attr_strs))) # Output nodes and edges to |out| (can be a file or a pipe). edges.sort() nodes.sort() out.write('digraph DEPS {\n' ' fontsize=8;\n') out.write('\n'.join(nodes)) out.write('\n\n') out.write('\n'.join(edges)) out.write('\n}\n') out.close()
[ "def", "_DumpDependenciesImpl", "(", "self", ",", "deps", ",", "out", ")", ":", "deps_graph", "=", "dict", "(", ")", "deps_srcs", "=", "set", "(", ")", "# Pre-initialize the graph with src->(dst, allow) pairs.", "for", "(", "allow", ",", "src", ",", "dst", ")"...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/checkdeps/graphdeps.py#L145-L258
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
scripts/cpp_lint.py
python
CheckInvalidIncrement
(filename, clean_lines, linenum, error)
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for invalid increment *count++.
[ "Checks", "for", "invalid", "increment", "*", "count", "++", "." ]
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).')
[ "def", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "_RE_PATTERN_INVALID_INCREMENT", ".", "match", "(", "line", ")", ":", "error", ...
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L1737-L1756
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/console/console.py
python
Console.text
(self, x, y, text, attr=None)
Write text at the given position.
Write text at the given position.
[ "Write", "text", "at", "the", "given", "position", "." ]
def text(self, x, y, text, attr=None): '''Write text at the given position.''' if attr is None: attr = self.attr pos = self.fixcoord(x, y) n = c_int(0) self.WriteConsoleOutputCharacterA(self.hout, text, len(text), pos, byref(n)) self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))
[ "def", "text", "(", "self", ",", "x", ",", "y", ",", "text", ",", "attr", "=", "None", ")", ":", "if", "attr", "is", "None", ":", "attr", "=", "self", ".", "attr", "pos", "=", "self", ".", "fixcoord", "(", "x", ",", "y", ")", "n", "=", "c_i...
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/console/console.py#L418-L426
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
prelu
(x, slope)
return PRelu()(x, slope)[0]
PRelu applies the function `f(x) = slope * x` for x < 0, `f(x) = x` for x >= 0 to the data tensor elementwise. Args: x (Tensor): matrix. Return: the result Tensor
PRelu applies the function `f(x) = slope * x` for x < 0, `f(x) = x` for x >= 0 to the data tensor elementwise. Args: x (Tensor): matrix. Return: the result Tensor
[ "PRelu", "applies", "the", "function", "f", "(", "x", ")", "=", "slope", "*", "x", "for", "x", "<", "0", "f", "(", "x", ")", "=", "x", "for", "x", ">", "=", "0", "to", "the", "data", "tensor", "elementwise", ".", "Args", ":", "x", "(", "Tenso...
def prelu(x, slope): """ PRelu applies the function `f(x) = slope * x` for x < 0, `f(x) = x` for x >= 0 to the data tensor elementwise. Args: x (Tensor): matrix. Return: the result Tensor """ return PRelu()(x, slope)[0]
[ "def", "prelu", "(", "x", ",", "slope", ")", ":", "return", "PRelu", "(", ")", "(", "x", ",", "slope", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L845-L854
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/base.py
python
ExtensionArray.to_numpy
( self, dtype: Dtype | None = None, copy: bool = False, na_value=lib.no_default, )
return result
Convert to a NumPy ndarray. .. versionadded:: 1.0.0 This is similar to :meth:`numpy.asarray`, but may provide additional control over how the conversion is done. Parameters ---------- dtype : str or numpy.dtype, optional The dtype to pass to :meth:`numpy.asarray`. copy : bool, default False Whether to ensure that the returned value is a not a view on another array. Note that ``copy=False`` does not *ensure* that ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that a copy is made, even if not strictly necessary. na_value : Any, optional The value to use for missing values. The default value depends on `dtype` and the type of the array. Returns ------- numpy.ndarray
Convert to a NumPy ndarray.
[ "Convert", "to", "a", "NumPy", "ndarray", "." ]
def to_numpy( self, dtype: Dtype | None = None, copy: bool = False, na_value=lib.no_default, ) -> np.ndarray: """ Convert to a NumPy ndarray. .. versionadded:: 1.0.0 This is similar to :meth:`numpy.asarray`, but may provide additional control over how the conversion is done. Parameters ---------- dtype : str or numpy.dtype, optional The dtype to pass to :meth:`numpy.asarray`. copy : bool, default False Whether to ensure that the returned value is a not a view on another array. Note that ``copy=False`` does not *ensure* that ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that a copy is made, even if not strictly necessary. na_value : Any, optional The value to use for missing values. The default value depends on `dtype` and the type of the array. Returns ------- numpy.ndarray """ # error: Argument "dtype" to "asarray" has incompatible type # "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], Type[int], # Type[complex], Type[bool], Type[object], None]"; expected "Union[dtype[Any], # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" result = np.asarray(self, dtype=dtype) # type: ignore[arg-type] if copy or na_value is not lib.no_default: result = result.copy() if na_value is not lib.no_default: result[self.isna()] = na_value return result
[ "def", "to_numpy", "(", "self", ",", "dtype", ":", "Dtype", "|", "None", "=", "None", ",", "copy", ":", "bool", "=", "False", ",", "na_value", "=", "lib", ".", "no_default", ",", ")", "->", "np", ".", "ndarray", ":", "# error: Argument \"dtype\" to \"asa...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/base.py#L429-L470
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Modules/Scripted/DICOM/DICOM.py
python
DICOMFileDialog.execDialog
(self)
Not used
Not used
[ "Not", "used" ]
def execDialog(self): """Not used""" logging.debug('execDialog called on %s' % self)
[ "def", "execDialog", "(", "self", ")", ":", "logging", ".", "debug", "(", "'execDialog called on %s'", "%", "self", ")" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/DICOM/DICOM.py#L337-L339
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py
python
IRC.execute_at
(self, at, function, arguments=())
Execute a function at a specified time. Arguments: at -- Execute at this time (standard \"time_t\" time). function -- Function to call. arguments -- Arguments to give the function.
Execute a function at a specified time.
[ "Execute", "a", "function", "at", "a", "specified", "time", "." ]
def execute_at(self, at, function, arguments=()): """Execute a function at a specified time. Arguments: at -- Execute at this time (standard \"time_t\" time). function -- Function to call. arguments -- Arguments to give the function. """ self.execute_delayed(at-time.time(), function, arguments)
[ "def", "execute_at", "(", "self", ",", "at", ",", "function", ",", "arguments", "=", "(", ")", ")", ":", "self", ".", "execute_delayed", "(", "at", "-", "time", ".", "time", "(", ")", ",", "function", ",", "arguments", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L279-L290
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/lzma.py
python
LZMAFile.read
(self, size=-1)
return self._buffer.read(size)
Read up to size uncompressed bytes from the file. If size is negative or omitted, read until EOF is reached. Returns b"" if the file is already at EOF.
Read up to size uncompressed bytes from the file.
[ "Read", "up", "to", "size", "uncompressed", "bytes", "from", "the", "file", "." ]
def read(self, size=-1): """Read up to size uncompressed bytes from the file. If size is negative or omitted, read until EOF is reached. Returns b"" if the file is already at EOF. """ self._check_can_read() return self._buffer.read(size)
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "self", ".", "_check_can_read", "(", ")", "return", "self", ".", "_buffer", ".", "read", "(", "size", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lzma.py#L193-L200
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/decomposition/_nmf.py
python
_multiplicative_update_h
(X, W, H, beta_loss, l1_reg_H, l2_reg_H, gamma)
return delta_H
update H in Multiplicative Update NMF
update H in Multiplicative Update NMF
[ "update", "H", "in", "Multiplicative", "Update", "NMF" ]
def _multiplicative_update_h(X, W, H, beta_loss, l1_reg_H, l2_reg_H, gamma): """update H in Multiplicative Update NMF""" if beta_loss == 2: numerator = safe_sparse_dot(W.T, X) denominator = np.dot(np.dot(W.T, W), H) else: # Numerator WH_safe_X = _special_sparse_dot(W, H, X) if sp.issparse(X): WH_safe_X_data = WH_safe_X.data X_data = X.data else: WH_safe_X_data = WH_safe_X X_data = X # copy used in the Denominator WH = WH_safe_X.copy() if beta_loss - 1. < 0: WH[WH == 0] = EPSILON # to avoid division by zero if beta_loss - 2. < 0: WH_safe_X_data[WH_safe_X_data == 0] = EPSILON if beta_loss == 1: np.divide(X_data, WH_safe_X_data, out=WH_safe_X_data) elif beta_loss == 0: # speeds up computation time # refer to /numpy/numpy/issues/9363 WH_safe_X_data **= -1 WH_safe_X_data **= 2 # element-wise multiplication WH_safe_X_data *= X_data else: WH_safe_X_data **= beta_loss - 2 # element-wise multiplication WH_safe_X_data *= X_data # here numerator = dot(W.T, (dot(W, H) ** (beta_loss - 2)) * X) numerator = safe_sparse_dot(W.T, WH_safe_X) # Denominator if beta_loss == 1: W_sum = np.sum(W, axis=0) # shape(n_components, ) W_sum[W_sum == 0] = 1. denominator = W_sum[:, np.newaxis] # beta_loss not in (1, 2) else: # computation of WtWH = dot(W.T, dot(W, H) ** beta_loss - 1) if sp.issparse(X): # memory efficient computation # (compute column by column, avoiding the dense matrix WH) WtWH = np.empty(H.shape) for i in range(X.shape[1]): WHi = np.dot(W, H[:, i]) if beta_loss - 1 < 0: WHi[WHi == 0] = EPSILON WHi **= beta_loss - 1 WtWH[:, i] = np.dot(W.T, WHi) else: WH **= beta_loss - 1 WtWH = np.dot(W.T, WH) denominator = WtWH # Add L1 and L2 regularization if l1_reg_H > 0: denominator += l1_reg_H if l2_reg_H > 0: denominator = denominator + l2_reg_H * H denominator[denominator == 0] = EPSILON numerator /= denominator delta_H = numerator # gamma is in ]0, 1] if gamma != 1: delta_H **= gamma return delta_H
[ "def", "_multiplicative_update_h", "(", "X", ",", "W", ",", "H", ",", "beta_loss", ",", "l1_reg_H", ",", "l2_reg_H", ",", "gamma", ")", ":", "if", "beta_loss", "==", "2", ":", "numerator", "=", "safe_sparse_dot", "(", "W", ".", "T", ",", "X", ")", "d...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/decomposition/_nmf.py#L628-L707
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/patcomp.py
python
PatternCompiler.__init__
(self, grammar_file=_PATTERN_GRAMMAR_FILE)
Initializer. Takes an optional alternative filename for the pattern grammar.
Initializer.
[ "Initializer", "." ]
def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE): """Initializer. Takes an optional alternative filename for the pattern grammar. """ self.grammar = driver.load_grammar(grammar_file) self.syms = pygram.Symbols(self.grammar) self.pygrammar = pygram.python_grammar self.pysyms = pygram.python_symbols self.driver = driver.Driver(self.grammar, convert=pattern_convert)
[ "def", "__init__", "(", "self", ",", "grammar_file", "=", "_PATTERN_GRAMMAR_FILE", ")", ":", "self", ".", "grammar", "=", "driver", ".", "load_grammar", "(", "grammar_file", ")", "self", ".", "syms", "=", "pygram", ".", "Symbols", "(", "self", ".", "gramma...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/patcomp.py#L45-L54
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/utils/metaestimators.py
python
_safe_split
(estimator, X, y, indices, train_indices=None)
return X_subset, y_subset
Create subset of dataset and properly handle kernels.
Create subset of dataset and properly handle kernels.
[ "Create", "subset", "of", "dataset", "and", "properly", "handle", "kernels", "." ]
def _safe_split(estimator, X, y, indices, train_indices=None): """Create subset of dataset and properly handle kernels.""" from ..gaussian_process.kernels import Kernel as GPKernel if (hasattr(estimator, 'kernel') and callable(estimator.kernel) and not isinstance(estimator.kernel, GPKernel)): # cannot compute the kernel values with custom function raise ValueError("Cannot use a custom kernel function. " "Precompute the kernel matrix instead.") if not hasattr(X, "shape"): if getattr(estimator, "_pairwise", False): raise ValueError("Precomputed kernels or affinity matrices have " "to be passed as arrays or sparse matrices.") X_subset = [X[index] for index in indices] else: if getattr(estimator, "_pairwise", False): # X is a precomputed square kernel matrix if X.shape[0] != X.shape[1]: raise ValueError("X should be a square kernel matrix") if train_indices is None: X_subset = X[np.ix_(indices, indices)] else: X_subset = X[np.ix_(indices, train_indices)] else: X_subset = safe_indexing(X, indices) if y is not None: y_subset = safe_indexing(y, indices) else: y_subset = None return X_subset, y_subset
[ "def", "_safe_split", "(", "estimator", ",", "X", ",", "y", ",", "indices", ",", "train_indices", "=", "None", ")", ":", "from", ".", ".", "gaussian_process", ".", "kernels", "import", "Kernel", "as", "GPKernel", "if", "(", "hasattr", "(", "estimator", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/metaestimators.py#L83-L115
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/bindings/python/clang/cindex.py
python
File.time
(self)
return conf.lib.clang_getFileTime(self)
Return the last modification time of the file.
Return the last modification time of the file.
[ "Return", "the", "last", "modification", "time", "of", "the", "file", "." ]
def time(self): """Return the last modification time of the file.""" return conf.lib.clang_getFileTime(self)
[ "def", "time", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getFileTime", "(", "self", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L3107-L3109
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column/string.py
python
StringMethods.swapcase
(self)
return self._return_or_inplace(libstrings.swapcase(self._column))
Change each lowercase character to uppercase and vice versa. This only applies to ASCII characters at this time. Equivalent to `str.swapcase() <https://docs.python.org/3/library/stdtypes.html#str.swapcase>`_. Returns ------- Series or Index of object See also -------- lower Converts all characters to lowercase. upper Converts all characters to uppercase. title Converts first character of each word to uppercase and remaining to lowercase. capitalize Converts first character to uppercase and remaining to lowercase. Examples -------- >>> import cudf >>> data = ['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe'] >>> s = cudf.Series(data) >>> s 0 lower 1 CAPITALS 2 this is a sentence 3 SwApCaSe dtype: object >>> s.str.swapcase() 0 LOWER 1 capitals 2 THIS IS A SENTENCE 3 sWaPcAsE dtype: object
Change each lowercase character to uppercase and vice versa. This only applies to ASCII characters at this time.
[ "Change", "each", "lowercase", "character", "to", "uppercase", "and", "vice", "versa", ".", "This", "only", "applies", "to", "ASCII", "characters", "at", "this", "time", "." ]
def swapcase(self) -> SeriesOrIndex: """ Change each lowercase character to uppercase and vice versa. This only applies to ASCII characters at this time. Equivalent to `str.swapcase() <https://docs.python.org/3/library/stdtypes.html#str.swapcase>`_. Returns ------- Series or Index of object See also -------- lower Converts all characters to lowercase. upper Converts all characters to uppercase. title Converts first character of each word to uppercase and remaining to lowercase. capitalize Converts first character to uppercase and remaining to lowercase. Examples -------- >>> import cudf >>> data = ['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe'] >>> s = cudf.Series(data) >>> s 0 lower 1 CAPITALS 2 this is a sentence 3 SwApCaSe dtype: object >>> s.str.swapcase() 0 LOWER 1 capitals 2 THIS IS A SENTENCE 3 sWaPcAsE dtype: object """ return self._return_or_inplace(libstrings.swapcase(self._column))
[ "def", "swapcase", "(", "self", ")", "->", "SeriesOrIndex", ":", "return", "self", ".", "_return_or_inplace", "(", "libstrings", ".", "swapcase", "(", "self", ".", "_column", ")", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/string.py#L1839-L1884
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0131-Palindrome-Partitioning/0131.py
python
Solution.partition
(self, s)
return results
:type s: str :rtype: List[List[str]]
:type s: str :rtype: List[List[str]]
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "List", "[", "List", "[", "str", "]]" ]
def partition(self, s): """ :type s: str :rtype: List[List[str]] """ results = [[s[0]]] for c in s[1:]: for r in results: r.append(c) extra = [] for r in results: if len(r) > 1: p = r[-2] + r[-1] if p == p[::-1]: extra.append(r[:-2] + [p]) elif len(r) > 2: p = r[-3] + r[-2] + r[-1] if p == p[::-1]: extra.append(r[:-3] + [p]) results.extend(extra) return results
[ "def", "partition", "(", "self", ",", "s", ")", ":", "results", "=", "[", "[", "s", "[", "0", "]", "]", "]", "for", "c", "in", "s", "[", "1", ":", "]", ":", "for", "r", "in", "results", ":", "r", ".", "append", "(", "c", ")", "extra", "="...
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0131-Palindrome-Partitioning/0131.py#L29-L51
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/packages/six.py
python
with_metaclass
(meta, base=object)
return meta("NewBase", (base,), {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, base=object): """Create a base class with a metaclass.""" return meta("NewBase", (base,), {})
[ "def", "with_metaclass", "(", "meta", ",", "base", "=", "object", ")", ":", "return", "meta", "(", "\"NewBase\"", ",", "(", "base", ",", ")", ",", "{", "}", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/packages/six.py#L383-L385
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_txt.py
python
EdFile.GetEncoding
(self)
return self.encoding
Get the encoding used by the file it may not be the same as the encoding requested at construction time @return: string encoding name
Get the encoding used by the file it may not be the same as the encoding requested at construction time @return: string encoding name
[ "Get", "the", "encoding", "used", "by", "the", "file", "it", "may", "not", "be", "the", "same", "as", "the", "encoding", "requested", "at", "construction", "time", "@return", ":", "string", "encoding", "name" ]
def GetEncoding(self): """Get the encoding used by the file it may not be the same as the encoding requested at construction time @return: string encoding name """ if self.encoding is None: # Guard against early entry return Profile_Get('ENCODING', default=DEFAULT_ENCODING) return self.encoding
[ "def", "GetEncoding", "(", "self", ")", ":", "if", "self", ".", "encoding", "is", "None", ":", "# Guard against early entry", "return", "Profile_Get", "(", "'ENCODING'", ",", "default", "=", "DEFAULT_ENCODING", ")", "return", "self", ".", "encoding" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_txt.py#L344-L353
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/_sklearn.py
python
_BaseEstimator.get_params
(self, deep=True)
return out
Get parameters for this estimator. Args: deep: boolean, optional If `True`, will return the parameters for this estimator and contained subobjects that are estimators. Returns: params : mapping of string to any Parameter names mapped to their values.
Get parameters for this estimator.
[ "Get", "parameters", "for", "this", "estimator", "." ]
def get_params(self, deep=True): """Get parameters for this estimator. Args: deep: boolean, optional If `True`, will return the parameters for this estimator and contained subobjects that are estimators. Returns: params : mapping of string to any Parameter names mapped to their values. """ out = dict() param_names = [name for name in self.__dict__ if not name.startswith('_')] for key in param_names: value = getattr(self, key, None) if isinstance(value, collections.Callable): continue # XXX: should we rather test if instance of estimator? if deep and hasattr(value, 'get_params'): deep_items = value.get_params().items() out.update((key + '__' + k, val) for k, val in deep_items) out[key] = value return out
[ "def", "get_params", "(", "self", ",", "deep", "=", "True", ")", ":", "out", "=", "dict", "(", ")", "param_names", "=", "[", "name", "for", "name", "in", "self", ".", "__dict__", "if", "not", "name", ".", "startswith", "(", "'_'", ")", "]", "for", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/_sklearn.py#L40-L66
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/GuestHost/OpenGL/glapi_parser/apiutil.py
python
ParamSet
(funcName)
return d[funcName].paramset
Return list of tuples (name, list of values) of function parameters. For PackerTest only.
Return list of tuples (name, list of values) of function parameters. For PackerTest only.
[ "Return", "list", "of", "tuples", "(", "name", "list", "of", "values", ")", "of", "function", "parameters", ".", "For", "PackerTest", "only", "." ]
def ParamSet(funcName): """Return list of tuples (name, list of values) of function parameters. For PackerTest only.""" d = GetFunctionDict() return d[funcName].paramset
[ "def", "ParamSet", "(", "funcName", ")", ":", "d", "=", "GetFunctionDict", "(", ")", "return", "d", "[", "funcName", "]", ".", "paramset" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/GuestHost/OpenGL/glapi_parser/apiutil.py#L291-L295
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/kubeadm.py
python
setup_pvs
(ctx, config)
Create PVs for all scratch LVs and set up a trivial provisioner
Create PVs for all scratch LVs and set up a trivial provisioner
[ "Create", "PVs", "for", "all", "scratch", "LVs", "and", "set", "up", "a", "trivial", "provisioner" ]
def setup_pvs(ctx, config): """ Create PVs for all scratch LVs and set up a trivial provisioner """ log.info('Scanning for scratch devices') crs = [] for remote in ctx.cluster.remotes.keys(): ls = remote.read_file('/scratch_devs').decode('utf-8').strip().splitlines() log.info(f'Scratch devices on {remote.shortname}: {ls}') for dev in ls: devname = dev.split('/')[-1].replace("_", "-") crs.append({ 'apiVersion': 'v1', 'kind': 'PersistentVolume', 'metadata': {'name': f'{remote.shortname}-{devname}'}, 'spec': { 'volumeMode': 'Block', 'accessModes': ['ReadWriteOnce'], 'capacity': {'storage': '100Gi'}, # doesn't matter? 'persistentVolumeReclaimPolicy': 'Retain', 'storageClassName': 'scratch', 'local': {'path': dev}, 'nodeAffinity': { 'required': { 'nodeSelectorTerms': [ { 'matchExpressions': [ { 'key': 'kubernetes.io/hostname', 'operator': 'In', 'values': [remote.shortname] } ] } ] } } } }) # overwriting first few MB is enough to make k8s happy remote.run(args=[ 'sudo', 'dd', 'if=/dev/zero', f'of={dev}', 'bs=1M', 'count=10' ]) crs.append({ 'kind': 'StorageClass', 'apiVersion': 'storage.k8s.io/v1', 'metadata': {'name': 'scratch'}, 'provisioner': 'kubernetes.io/no-provisioner', 'volumeBindingMode': 'WaitForFirstConsumer', }) y = yaml.dump_all(crs) log.info('Creating PVs + StorageClass') log.debug(y) _kubectl(ctx, config, ['create', '-f', '-'], stdin=y) yield
[ "def", "setup_pvs", "(", "ctx", ",", "config", ")", ":", "log", ".", "info", "(", "'Scanning for scratch devices'", ")", "crs", "=", "[", "]", "for", "remote", "in", "ctx", ".", "cluster", ".", "remotes", ".", "keys", "(", ")", ":", "ls", "=", "remot...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/kubeadm.py#L452-L507
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/group.py
python
AutoScalingGroup.delete
(self, force_delete=False)
return self.connection.delete_auto_scaling_group(self.name, force_delete)
Delete this auto-scaling group if no instances attached or no scaling activities in progress.
Delete this auto-scaling group if no instances attached or no scaling activities in progress.
[ "Delete", "this", "auto", "-", "scaling", "group", "if", "no", "instances", "attached", "or", "no", "scaling", "activities", "in", "progress", "." ]
def delete(self, force_delete=False): """ Delete this auto-scaling group if no instances attached or no scaling activities in progress. """ return self.connection.delete_auto_scaling_group(self.name, force_delete)
[ "def", "delete", "(", "self", ",", "force_delete", "=", "False", ")", ":", "return", "self", ".", "connection", ".", "delete_auto_scaling_group", "(", "self", ".", "name", ",", "force_delete", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/group.py#L294-L300
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/container.py
python
CellList.extend
(self, cells)
return self
Appends cells from a Python iterable to the end of the list. Args: cells(list): The subcells to be extended. Raises: TypeError: If the cells are not a list of subcells.
Appends cells from a Python iterable to the end of the list.
[ "Appends", "cells", "from", "a", "Python", "iterable", "to", "the", "end", "of", "the", "list", "." ]
def extend(self, cells): """ Appends cells from a Python iterable to the end of the list. Args: cells(list): The subcells to be extended. Raises: TypeError: If the cells are not a list of subcells. """ cls_name = self.__class__.__name__ if not isinstance(cells, list): raise TypeError(f"For '{cls_name}', the new cells wanted to append " f"should be instance of list, but got {type(cells).__name__}.") prefix, _ = _get_prefix_and_index(self._cells) for cell in cells: if _valid_cell(cell, cls_name): if self._auto_prefix: cell.update_parameters_name(prefix + str(len(self)) + ".") self._cells[str(len(self))] = cell return self
[ "def", "extend", "(", "self", ",", "cells", ")", ":", "cls_name", "=", "self", ".", "__class__", ".", "__name__", "if", "not", "isinstance", "(", "cells", ",", "list", ")", ":", "raise", "TypeError", "(", "f\"For '{cls_name}', the new cells wanted to append \"",...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/container.py#L371-L391
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/grid.py
python
Grid.IsVisible
(*args, **kwargs)
return _grid.Grid_IsVisible(*args, **kwargs)
IsVisible(self, int row, int col, bool wholeCellVisible=True) -> bool
IsVisible(self, int row, int col, bool wholeCellVisible=True) -> bool
[ "IsVisible", "(", "self", "int", "row", "int", "col", "bool", "wholeCellVisible", "=", "True", ")", "-", ">", "bool" ]
def IsVisible(*args, **kwargs): """IsVisible(self, int row, int col, bool wholeCellVisible=True) -> bool""" return _grid.Grid_IsVisible(*args, **kwargs)
[ "def", "IsVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_IsVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1414-L1416
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Base/Python/slicer/slicerqt.py
python
_Internal.setSlicerModuleNames
( self, moduleNames)
Add module names as attributes of module slicer.moduleNames
Add module names as attributes of module slicer.moduleNames
[ "Add", "module", "names", "as", "attributes", "of", "module", "slicer", ".", "moduleNames" ]
def setSlicerModuleNames( self, moduleNames): """Add module names as attributes of module slicer.moduleNames""" for name in moduleNames: setattr( slicer.moduleNames, name, name ) # HACK For backward compatibility with ITKv3, map "dwiconvert" module name to "dicomtonrrdconverter" if name == 'DWIConvert': setattr( slicer.moduleNames, 'DicomToNrrdConverter', name )
[ "def", "setSlicerModuleNames", "(", "self", ",", "moduleNames", ")", ":", "for", "name", "in", "moduleNames", ":", "setattr", "(", "slicer", ".", "moduleNames", ",", "name", ",", "name", ")", "# HACK For backward compatibility with ITKv3, map \"dwiconvert\" module name ...
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Base/Python/slicer/slicerqt.py#L177-L183
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/generator/make.py
python
MakefileWriter.Pchify
(self, path, lang)
return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path)
Convert a prefix header path to its output directory form.
Convert a prefix header path to its output directory form.
[ "Convert", "a", "prefix", "header", "path", "to", "its", "output", "directory", "form", "." ]
def Pchify(self, path, lang): """Convert a prefix header path to its output directory form.""" path = self.Absolutify(path) if '$(' in path: path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' % (self.toolset, lang)) return path return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path)
[ "def", "Pchify", "(", "self", ",", "path", ",", "lang", ")", ":", "path", "=", "self", ".", "Absolutify", "(", "path", ")", "if", "'$('", "in", "path", ":", "path", "=", "path", ".", "replace", "(", "'$(obj)/'", ",", "'$(obj).%s/$(TARGET)/pch-%s'", "%"...
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/make.py#L1901-L1908
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/graph/_lattice_edge_logic.py
python
create_padded_sites
(basis_vectors, extent, site_offsets, pbc, order)
return positions, equivalent_ids
Generates all lattice sites in an extended shell
Generates all lattice sites in an extended shell
[ "Generates", "all", "lattice", "sites", "in", "an", "extended", "shell" ]
def create_padded_sites(basis_vectors, extent, site_offsets, pbc, order): """Generates all lattice sites in an extended shell""" extra_shells = np.where(pbc, order, 0) basis_coords, positions = create_site_positions( basis_vectors, extent, site_offsets, extra_shells ) equivalent_ids = site_to_idx(basis_coords, extent, site_offsets) return positions, equivalent_ids
[ "def", "create_padded_sites", "(", "basis_vectors", ",", "extent", ",", "site_offsets", ",", "pbc", ",", "order", ")", ":", "extra_shells", "=", "np", ".", "where", "(", "pbc", ",", "order", ",", "0", ")", "basis_coords", ",", "positions", "=", "create_sit...
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/graph/_lattice_edge_logic.py#L77-L85
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tix.py
python
Grid.delete_column
(self, from_, to=None)
Delete columns between from_ and to inclusive. If to is not provided, delete only column at from_
Delete columns between from_ and to inclusive. If to is not provided, delete only column at from_
[ "Delete", "columns", "between", "from_", "and", "to", "inclusive", ".", "If", "to", "is", "not", "provided", "delete", "only", "column", "at", "from_" ]
def delete_column(self, from_, to=None): """Delete columns between from_ and to inclusive. If to is not provided, delete only column at from_""" if to is None: self.tk.call(self, 'delete', 'column', from_) else: self.tk.call(self, 'delete', 'column', from_, to)
[ "def", "delete_column", "(", "self", ",", "from_", ",", "to", "=", "None", ")", ":", "if", "to", "is", "None", ":", "self", ".", "tk", ".", "call", "(", "self", ",", "'delete'", ",", "'column'", ",", "from_", ")", "else", ":", "self", ".", "tk", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tix.py#L1838-L1844
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/checkpoint.py
python
CheckpointManager.report_checkpoint_stats
(self, action_name)
Report checkpoint operation stats for current node. Args: action_name: A string of the name of checkpoint operation.
Report checkpoint operation stats for current node.
[ "Report", "checkpoint", "operation", "stats", "for", "current", "node", "." ]
def report_checkpoint_stats(self, action_name): """ Report checkpoint operation stats for current node. Args: action_name: A string of the name of checkpoint operation. """ all_stats = {} self.collect_checkpoint_stats(all_stats) if self._metadata_handler: self._metadata_handler.report(action_name, all_stats)
[ "def", "report_checkpoint_stats", "(", "self", ",", "action_name", ")", ":", "all_stats", "=", "{", "}", "self", ".", "collect_checkpoint_stats", "(", "all_stats", ")", "if", "self", ".", "_metadata_handler", ":", "self", ".", "_metadata_handler", ".", "report",...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/checkpoint.py#L338-L348
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Misc.quit
(self)
Quit the Tcl interpreter. All widgets will be destroyed.
Quit the Tcl interpreter. All widgets will be destroyed.
[ "Quit", "the", "Tcl", "interpreter", ".", "All", "widgets", "will", "be", "destroyed", "." ]
def quit(self): """Quit the Tcl interpreter. All widgets will be destroyed.""" self.tk.quit()
[ "def", "quit", "(", "self", ")", ":", "self", ".", "tk", ".", "quit", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L1069-L1071
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py
python
GetAllIncludeDirectories
(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path)
return all_includes_list
Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options.
Calculate the set of include directories to be used.
[ "Calculate", "the", "set", "of", "include", "directories", "to", "be", "used", "." ]
def GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options. """ gyp_includes_set = set() compiler_includes_list = [] # Find compiler's default include dirs. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-xc++', '-v', '-']) proc = subprocess.Popen(args=command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate()[1] # Extract the list of include dirs from the output, which has this format: # ... # #include "..." search starts here: # #include <...> search starts here: # /usr/include/c++/4.6 # /usr/local/include # End of search list. # ... in_include_list = False for line in output.splitlines(): if line.startswith('#include'): in_include_list = True continue if line.startswith('End of search list.'): break if in_include_list: include_dir = line.strip() if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if config_name in target['configurations']: config = target['configurations'][config_name] # Look for any include dirs that were explicitly added via cflags. This # may be done in gyp files to force certain includes to come at the end. # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and # remove this. if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) cflags = msvs_settings.GetCflags(config_name) else: cflags = config['cflags'] for cflag in cflags: if cflag.startswith('-I'): include_dir = cflag[2:] if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) # Find standard gyp include dirs. if config.has_key('include_dirs'): include_dirs = config['include_dirs'] for shared_intermediate_dir in shared_intermediate_dirs: for include_dir in include_dirs: include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR', shared_intermediate_dir) if not os.path.isabs(include_dir): base_dir = os.path.dirname(target_name) include_dir = base_dir + '/' + include_dir include_dir = os.path.abspath(include_dir) gyp_includes_set.add(include_dir) # Generate a list that has all the include dirs. all_includes_list = list(gyp_includes_set) all_includes_list.sort() for compiler_include in compiler_includes_list: if not compiler_include in gyp_includes_set: all_includes_list.append(compiler_include) # All done. return all_includes_list
[ "def", "GetAllIncludeDirectories", "(", "target_list", ",", "target_dicts", ",", "shared_intermediate_dirs", ",", "config_name", ",", "params", ",", "compiler_path", ")", ":", "gyp_includes_set", "=", "set", "(", ")", "compiler_includes_list", "=", "[", "]", "# Find...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L80-L166
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/reverse-substrings-between-each-pair-of-parentheses.py
python
Solution.reverseParentheses
(self, s)
return "".join(result)
:type s: str :rtype: str
:type s: str :rtype: str
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "str" ]
def reverseParentheses(self, s): """ :type s: str :rtype: str """ stk, lookup = [], {} for i, c in enumerate(s): if c == '(': stk.append(i) elif c == ')': j = stk.pop() lookup[i], lookup[j] = j, i result = [] i, d = 0, 1 while i < len(s): if i in lookup: i = lookup[i] d *= -1 else: result.append(s[i]) i += d return "".join(result)
[ "def", "reverseParentheses", "(", "self", ",", "s", ")", ":", "stk", ",", "lookup", "=", "[", "]", ",", "{", "}", "for", "i", ",", "c", "in", "enumerate", "(", "s", ")", ":", "if", "c", "==", "'('", ":", "stk", ".", "append", "(", "i", ")", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/reverse-substrings-between-each-pair-of-parentheses.py#L5-L26
commaai/openpilot
4416c21b1e738ab7d04147c5ae52b5135e0cdb40
selfdrive/car/interfaces.py
python
CarStateBase.update_blinker_from_lamp
(self, blinker_time: int, left_blinker_lamp: bool, right_blinker_lamp: bool)
return self.left_blinker_cnt > 0, self.right_blinker_cnt > 0
Update blinkers from lights. Enable output when light was seen within the last `blinker_time` iterations
Update blinkers from lights. Enable output when light was seen within the last `blinker_time` iterations
[ "Update", "blinkers", "from", "lights", ".", "Enable", "output", "when", "light", "was", "seen", "within", "the", "last", "blinker_time", "iterations" ]
def update_blinker_from_lamp(self, blinker_time: int, left_blinker_lamp: bool, right_blinker_lamp: bool): """Update blinkers from lights. Enable output when light was seen within the last `blinker_time` iterations""" # TODO: Handle case when switching direction. Now both blinkers can be on at the same time self.left_blinker_cnt = blinker_time if left_blinker_lamp else max(self.left_blinker_cnt - 1, 0) self.right_blinker_cnt = blinker_time if right_blinker_lamp else max(self.right_blinker_cnt - 1, 0) return self.left_blinker_cnt > 0, self.right_blinker_cnt > 0
[ "def", "update_blinker_from_lamp", "(", "self", ",", "blinker_time", ":", "int", ",", "left_blinker_lamp", ":", "bool", ",", "right_blinker_lamp", ":", "bool", ")", ":", "# TODO: Handle case when switching direction. Now both blinkers can be on at the same time", "self", ".",...
https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/selfdrive/car/interfaces.py#L221-L227
cmu-db/bustub
fe1b9e984bd2967997b52df872c873d80f71cf7d
build_support/cpplint.py
python
_CppLintState.IncrementErrorCount
(self, category)
Bumps the module's error statistic.
Bumps the module's error statistic.
[ "Bumps", "the", "module", "s", "error", "statistic", "." ]
def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1
[ "def", "IncrementErrorCount", "(", "self", ",", "category", ")", ":", "self", ".", "error_count", "+=", "1", "if", "self", ".", "counting", "in", "(", "'toplevel'", ",", "'detailed'", ")", ":", "if", "self", ".", "counting", "!=", "'detailed'", ":", "cat...
https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L1092-L1100
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/ensemble/_hist_gradient_boosting/grower.py
python
TreeNode.__lt__
(self, other_node)
return self.split_info.gain > other_node.split_info.gain
Comparison for priority queue. Nodes with high gain are higher priority than nodes with low gain. heapq.heappush only need the '<' operator. heapq.heappop take the smallest item first (smaller is higher priority). Parameters ---------- other_node : TreeNode The node to compare with.
Comparison for priority queue.
[ "Comparison", "for", "priority", "queue", "." ]
def __lt__(self, other_node): """Comparison for priority queue. Nodes with high gain are higher priority than nodes with low gain. heapq.heappush only need the '<' operator. heapq.heappop take the smallest item first (smaller is higher priority). Parameters ---------- other_node : TreeNode The node to compare with. """ return self.split_info.gain > other_node.split_info.gain
[ "def", "__lt__", "(", "self", ",", "other_node", ")", ":", "return", "self", ".", "split_info", ".", "gain", ">", "other_node", ".", "split_info", ".", "gain" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_hist_gradient_boosting/grower.py#L99-L113
floatlazer/semantic_slam
657814a1ba484de6b7f6f9d07c564566c8121f13
semantic_cloud/src/semantic_cloud.py
python
SemanticCloud.__init__
(self, gen_pcl = True)
Constructor \param gen_pcl (bool) whether generate point cloud, if set to true the node will subscribe to depth image
Constructor \param gen_pcl (bool) whether generate point cloud, if set to true the node will subscribe to depth image
[ "Constructor", "\\", "param", "gen_pcl", "(", "bool", ")", "whether", "generate", "point", "cloud", "if", "set", "to", "true", "the", "node", "will", "subscribe", "to", "depth", "image" ]
def __init__(self, gen_pcl = True): """ Constructor \param gen_pcl (bool) whether generate point cloud, if set to true the node will subscribe to depth image """ # Get point type point_type = rospy.get_param('/semantic_pcl/point_type') if point_type == 0: self.point_type = PointType.COLOR print('Generate color point cloud.') elif point_type == 1: self.point_type = PointType.SEMANTICS_MAX print('Generate semantic point cloud [max fusion].') elif point_type == 2: self.point_type = PointType.SEMANTICS_BAYESIAN print('Generate semantic point cloud [bayesian fusion].') else: print("Invalid point type.") return # Get image size self.img_width, self.img_height = rospy.get_param('/camera/width'), rospy.get_param('/camera/height') # Set up CNN is use semantics if self.point_type is not PointType.COLOR: print('Setting up CNN model...') # Set device self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Get dataset dataset = rospy.get_param('/semantic_pcl/dataset') # Setup model model_name ='pspnet' model_path = rospy.get_param('/semantic_pcl/model_path') if dataset == 'sunrgbd': # If use version fine tuned on sunrgbd dataset self.n_classes = 38 # Semantic class number self.model = get_model(model_name, self.n_classes, version = 'sunrgbd_res50') state = torch.load(model_path) self.model.load_state_dict(state) self.cnn_input_size = (321, 321) self.mean = np.array([104.00699, 116.66877, 122.67892]) # Mean value of dataset elif dataset == 'ade20k': self.n_classes = 150 # Semantic class number self.model = get_model(model_name, self.n_classes, version = 'ade20k') state = torch.load(model_path) self.model.load_state_dict(convert_state_dict(state['model_state'])) # Remove 'module' from dictionary keys self.cnn_input_size = (473, 473) self.mean = np.array([104.00699, 116.66877, 122.67892]) # Mean value of dataset self.model = self.model.to(self.device) self.model.eval() self.cmap = color_map(N = self.n_classes, normalized = False) # Color map for semantic classes # Declare array containers if self.point_type is PointType.SEMANTICS_BAYESIAN: self.semantic_colors = np.zeros((3, self.img_height, self.img_width, 3), dtype = np.uint8) # Numpy array to store 3 decoded semantic images with highest confidences self.confidences = np.zeros((3, self.img_height, self.img_width), dtype = np.float32) # Numpy array to store top 3 class confidences # Set up ROS print('Setting up ROS...') self.bridge = CvBridge() # CvBridge to transform ROS Image message to OpenCV image # Semantic image publisher self.sem_img_pub = rospy.Publisher("/semantic_pcl/semantic_image", Image, queue_size = 1) # Set up ros image subscriber # Set buff_size to average msg size to avoid accumulating delay if gen_pcl: # Point cloud frame id frame_id = rospy.get_param('/semantic_pcl/frame_id') # Camera intrinsic matrix fx = rospy.get_param('/camera/fx') fy = rospy.get_param('/camera/fy') cx = rospy.get_param('/camera/cx') cy = rospy.get_param('/camera/cy') intrinsic = np.matrix([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype = np.float32) self.pcl_pub = rospy.Publisher("/semantic_pcl/semantic_pcl", PointCloud2, queue_size = 1) self.color_sub = message_filters.Subscriber(rospy.get_param('/semantic_pcl/color_image_topic'), Image, queue_size = 1, buff_size = 30*480*640) self.depth_sub = message_filters.Subscriber(rospy.get_param('/semantic_pcl/depth_image_topic'), Image, queue_size = 1, buff_size = 40*480*640 ) # increase buffer size to avoid delay (despite queue_size = 1) self.ts = message_filters.ApproximateTimeSynchronizer([self.color_sub, self.depth_sub], queue_size = 1, slop = 0.3) # Take in one color image and one depth image with a limite time gap between message time stamps self.ts.registerCallback(self.color_depth_callback) self.cloud_generator = ColorPclGenerator(intrinsic, self.img_width,self.img_height, frame_id , self.point_type) else: self.image_sub = rospy.Subscriber(rospy.get_param('/semantic_pcl/color_image_topic'), Image, self.color_callback, queue_size = 1, buff_size = 30*480*640) print('Ready.')
[ "def", "__init__", "(", "self", ",", "gen_pcl", "=", "True", ")", ":", "# Get point type", "point_type", "=", "rospy", ".", "get_param", "(", "'/semantic_pcl/point_type'", ")", "if", "point_type", "==", "0", ":", "self", ".", "point_type", "=", "PointType", ...
https://github.com/floatlazer/semantic_slam/blob/657814a1ba484de6b7f6f9d07c564566c8121f13/semantic_cloud/src/semantic_cloud.py#L82-L158
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/examples/tutorials/mnist/mnist.py
python
evaluation
(logits, labels)
return tf.reduce_sum(input_tensor=tf.cast(correct, tf.int32))
Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of examples (out of batch_size) that were predicted correctly.
Evaluate the quality of the logits at predicting the label.
[ "Evaluate", "the", "quality", "of", "the", "logits", "at", "predicting", "the", "label", "." ]
def evaluation(logits, labels): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of examples (out of batch_size) that were predicted correctly. """ # For a classifier model, we can use the in_top_k Op. # It returns a bool tensor with shape [batch_size] that is true for # the examples where the label is in the top k (here k=1) # of all logits for that example. correct = tf.nn.in_top_k(predictions=logits, targets=labels, k=1) # Return the number of true entries. return tf.reduce_sum(input_tensor=tf.cast(correct, tf.int32))
[ "def", "evaluation", "(", "logits", ",", "labels", ")", ":", "# For a classifier model, we can use the in_top_k Op.", "# It returns a bool tensor with shape [batch_size] that is true for", "# the examples where the label is in the top k (here k=1)", "# of all logits for that example.", "corr...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/examples/tutorials/mnist/mnist.py#L130-L148
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/style/checkers/cpp.py
python
_does_primary_header_exist
(filename)
return os.path.isfile(primary_header)
Return a primary header file name for a file, or empty string if the file is not source file or primary header does not exist.
Return a primary header file name for a file, or empty string if the file is not source file or primary header does not exist.
[ "Return", "a", "primary", "header", "file", "name", "for", "a", "file", "or", "empty", "string", "if", "the", "file", "is", "not", "source", "file", "or", "primary", "header", "does", "not", "exist", "." ]
def _does_primary_header_exist(filename): """Return a primary header file name for a file, or empty string if the file is not source file or primary header does not exist. """ fileinfo = FileInfo(filename) if not fileinfo.is_source(): return False primary_header = fileinfo.no_extension() + ".h" return os.path.isfile(primary_header)
[ "def", "_does_primary_header_exist", "(", "filename", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename", ")", "if", "not", "fileinfo", ".", "is_source", "(", ")", ":", "return", "False", "primary_header", "=", "fileinfo", ".", "no_extension", "(", ")", ...
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/style/checkers/cpp.py#L2925-L2933
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/core.py
python
run_setup
(script_name, script_args=None, stop_after="run")
return _setup_distribution
Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or the contents of the config files or command-line. 'script_name' is a file that will be read and run with 'exec()'; 'sys.argv[0]' will be replaced with 'script' for the duration of the call. 'script_args' is a list of strings; if supplied, 'sys.argv[1:]' will be replaced by 'script_args' for the duration of the call. 'stop_after' tells 'setup()' when to stop processing; possible values: init stop after the Distribution instance has been created and populated with the keyword arguments to 'setup()' config stop after config files have been parsed (and their data stored in the Distribution instance) commandline stop after the command-line ('sys.argv[1:]' or 'script_args') have been parsed (and the data stored in the Distribution) run [default] stop after all commands have been run (the same as if 'setup()' had been called in the usual way Returns the Distribution instance, which provides all information used to drive the Distutils.
Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or the contents of the config files or command-line.
[ "Run", "a", "setup", "script", "in", "a", "somewhat", "controlled", "environment", "and", "return", "the", "Distribution", "instance", "that", "drives", "things", ".", "This", "is", "useful", "if", "you", "need", "to", "find", "out", "the", "distribution", "...
def run_setup (script_name, script_args=None, stop_after="run"): """Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or the contents of the config files or command-line. 'script_name' is a file that will be read and run with 'exec()'; 'sys.argv[0]' will be replaced with 'script' for the duration of the call. 'script_args' is a list of strings; if supplied, 'sys.argv[1:]' will be replaced by 'script_args' for the duration of the call. 'stop_after' tells 'setup()' when to stop processing; possible values: init stop after the Distribution instance has been created and populated with the keyword arguments to 'setup()' config stop after config files have been parsed (and their data stored in the Distribution instance) commandline stop after the command-line ('sys.argv[1:]' or 'script_args') have been parsed (and the data stored in the Distribution) run [default] stop after all commands have been run (the same as if 'setup()' had been called in the usual way Returns the Distribution instance, which provides all information used to drive the Distutils. """ if stop_after not in ('init', 'config', 'commandline', 'run'): raise ValueError("invalid value for 'stop_after': %r" % (stop_after,)) global _setup_stop_after, _setup_distribution _setup_stop_after = stop_after save_argv = sys.argv.copy() g = {'__file__': script_name} try: try: sys.argv[0] = script_name if script_args is not None: sys.argv[1:] = script_args with open(script_name, 'rb') as f: exec(f.read(), g) finally: sys.argv = save_argv _setup_stop_after = None except SystemExit: # Hmm, should we do something if exiting with a non-zero code # (ie. error)? pass if _setup_distribution is None: raise RuntimeError(("'distutils.core.setup()' was never called -- " "perhaps '%s' is not a Distutils setup script?") % \ script_name) # I wonder if the setup script's namespace -- g and l -- would be of # any interest to callers? #print "_setup_distribution:", _setup_distribution return _setup_distribution
[ "def", "run_setup", "(", "script_name", ",", "script_args", "=", "None", ",", "stop_after", "=", "\"run\"", ")", ":", "if", "stop_after", "not", "in", "(", "'init'", ",", "'config'", ",", "'commandline'", ",", "'run'", ")", ":", "raise", "ValueError", "(",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/core.py#L170-L232
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py
python
VarTrace.add
(self, var, callback)
return var
Add (var, callback) tuple to untraced list. Args: var: Tk variable instance. callback: Either function name to be used as a callback or a tuple with IdleConf config-type, section, and option names used in the default callback. Return: Tk variable instance.
Add (var, callback) tuple to untraced list.
[ "Add", "(", "var", "callback", ")", "tuple", "to", "untraced", "list", "." ]
def add(self, var, callback): """Add (var, callback) tuple to untraced list. Args: var: Tk variable instance. callback: Either function name to be used as a callback or a tuple with IdleConf config-type, section, and option names used in the default callback. Return: Tk variable instance. """ if isinstance(callback, tuple): callback = self.make_callback(var, callback) self.untraced.append((var, callback)) return var
[ "def", "add", "(", "self", ",", "var", ",", "callback", ")", ":", "if", "isinstance", "(", "callback", ",", "tuple", ")", ":", "callback", "=", "self", ".", "make_callback", "(", "var", ",", "callback", ")", "self", ".", "untraced", ".", "append", "(...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L2218-L2233
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/xrc.py
python
XmlResource.GetXRCID
(*args, **kwargs)
return _xrc.XmlResource_GetXRCID(*args, **kwargs)
GetXRCID(String str_id, int value_if_not_found=ID_NONE) -> int
GetXRCID(String str_id, int value_if_not_found=ID_NONE) -> int
[ "GetXRCID", "(", "String", "str_id", "int", "value_if_not_found", "=", "ID_NONE", ")", "-", ">", "int" ]
def GetXRCID(*args, **kwargs): """GetXRCID(String str_id, int value_if_not_found=ID_NONE) -> int""" return _xrc.XmlResource_GetXRCID(*args, **kwargs)
[ "def", "GetXRCID", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlResource_GetXRCID", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/xrc.py#L187-L189
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/pychan/tools.py
python
applyOnlySuitable
(func,*args,**kwargs)
return func(*args,**kwargs)
This nifty little function takes another function and applies it to a dictionary of keyword arguments. If the supplied function does not expect one or more of the keyword arguments, these are silently discarded. The result of the application is returned. This is useful to pass information to callbacks without enforcing a particular signature.
This nifty little function takes another function and applies it to a dictionary of keyword arguments. If the supplied function does not expect one or more of the keyword arguments, these are silently discarded. The result of the application is returned. This is useful to pass information to callbacks without enforcing a particular signature.
[ "This", "nifty", "little", "function", "takes", "another", "function", "and", "applies", "it", "to", "a", "dictionary", "of", "keyword", "arguments", ".", "If", "the", "supplied", "function", "does", "not", "expect", "one", "or", "more", "of", "the", "keywor...
def applyOnlySuitable(func,*args,**kwargs): """ This nifty little function takes another function and applies it to a dictionary of keyword arguments. If the supplied function does not expect one or more of the keyword arguments, these are silently discarded. The result of the application is returned. This is useful to pass information to callbacks without enforcing a particular signature. """ if sys.version_info < (3,): func_name = 'im_func' code_name = 'func_code' else: func_name = '__func__' code_name = '__code__' if hasattr(func, func_name): code = func.__func__.__code__ varnames = code.co_varnames[1:code.co_argcount]#ditch bound instance elif hasattr(func, code_name): code = func.__code__ varnames = code.co_varnames[0:code.co_argcount] elif hasattr(func,'__call__'): func = func.__call__ if hasattr(func, func_name): code = func.__func__.__code__ varnames = code.co_varnames[1:code.co_argcount]#ditch bound instance elif hasattr(func, code_name): code = func.__code__ varnames = code.co_varnames[0:code.co_argcount] #http://docs.python.org/lib/inspect-types.html if code.co_flags & 8: return func(*args,**kwargs) for name,value in list(kwargs.items()): if name not in varnames: del kwargs[name] return func(*args,**kwargs)
[ "def", "applyOnlySuitable", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", ")", ":", "func_name", "=", "'im_func'", "code_name", "=", "'func_code'", "else", ":", "func_name", "=",...
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/tools.py#L37-L71