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
koth/kcws
88efbd36a7022de4e6e90f5a1fb880cf87cfae9f
third_party/setuptools/pkg_resources.py
python
ZipProvider._is_current
(self, file_path, zip_path)
return zip_contents == file_contents
Return True if the file_path is current for this zip_path
Return True if the file_path is current for this zip_path
[ "Return", "True", "if", "the", "file_path", "is", "current", "for", "this", "zip_path" ]
def _is_current(self, file_path, zip_path): """ Return True if the file_path is current for this zip_path """ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not os.path.isfile(file_path): return False stat = os.stat(file_path) if stat.st_size!=size or stat.st_mtime!=timestamp: return False # check that the contents match zip_contents = self.loader.get_data(zip_path) with open(file_path, 'rb') as f: file_contents = f.read() return zip_contents == file_contents
[ "def", "_is_current", "(", "self", ",", "file_path", ",", "zip_path", ")", ":", "timestamp", ",", "size", "=", "self", ".", "_get_date_and_size", "(", "self", ".", "zipinfo", "[", "zip_path", "]", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "False", "stat", "=", "os", ".", "stat", "(", "file_path", ")", "if", "stat", ".", "st_size", "!=", "size", "or", "stat", ".", "st_mtime", "!=", "timestamp", ":", "return", "False", "# check that the contents match", "zip_contents", "=", "self", ".", "loader", ".", "get_data", "(", "zip_path", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "file_contents", "=", "f", ".", "read", "(", ")", "return", "zip_contents", "==", "file_contents" ]
https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/setuptools/pkg_resources.py#L1684-L1698
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/openvino/tools/pot/configs/config.py
python
Config._configure_ac_params
(self)
Converts engine config into accuracy checker config
Converts engine config into accuracy checker config
[ "Converts", "engine", "config", "into", "accuracy", "checker", "config" ]
def _configure_ac_params(self): """ Converts engine config into accuracy checker config """ filtering_params = {'target_devices': ['CPU'], 'target_framework': 'openvino', 'use_new_api': True} if 'config' in self.engine: ac_conf, mode = ConfigReader.merge(Dict({**self.engine, **filtering_params})) ac_conf = Dict(ac_conf) else: mode = 'evaluations' if self.engine.module else 'models' ac_conf = Dict({mode: [self.engine]}) ac_conf[mode][0].name = self.model.model_name datasets_config = ac_conf[mode][0].datasets if mode == 'models' \ else ac_conf[mode][0].module_config.datasets if isinstance(datasets_config, dict) and 'preprocessing' in datasets_config: logger.debug('Global dataset preprocessing configuration found') preprocessing_config = datasets_config.pop('preprocessing') for dataset_name, dataset in datasets_config.items(): if not dataset.preprocessing: dataset['preprocessing'] = preprocessing_config else: logger.debug('Local preprocessing configuration is used for {} dataset'.format(dataset_name)) ConfigReader.check_local_config(ac_conf) ac_conf = ConfigReader.convert_paths(ac_conf) ConfigReader._filter_launchers( ac_conf, filtering_params, mode=mode ) for req_num in ['stat_requests_number', 'eval_requests_number']: ac_conf[req_num] = self.engine[req_num] if req_num in self.engine else None self['engine'] = ac_conf
[ "def", "_configure_ac_params", "(", "self", ")", ":", "filtering_params", "=", "{", "'target_devices'", ":", "[", "'CPU'", "]", ",", "'target_framework'", ":", "'openvino'", ",", "'use_new_api'", ":", "True", "}", "if", "'config'", "in", "self", ".", "engine", ":", "ac_conf", ",", "mode", "=", "ConfigReader", ".", "merge", "(", "Dict", "(", "{", "*", "*", "self", ".", "engine", ",", "*", "*", "filtering_params", "}", ")", ")", "ac_conf", "=", "Dict", "(", "ac_conf", ")", "else", ":", "mode", "=", "'evaluations'", "if", "self", ".", "engine", ".", "module", "else", "'models'", "ac_conf", "=", "Dict", "(", "{", "mode", ":", "[", "self", ".", "engine", "]", "}", ")", "ac_conf", "[", "mode", "]", "[", "0", "]", ".", "name", "=", "self", ".", "model", ".", "model_name", "datasets_config", "=", "ac_conf", "[", "mode", "]", "[", "0", "]", ".", "datasets", "if", "mode", "==", "'models'", "else", "ac_conf", "[", "mode", "]", "[", "0", "]", ".", "module_config", ".", "datasets", "if", "isinstance", "(", "datasets_config", ",", "dict", ")", "and", "'preprocessing'", "in", "datasets_config", ":", "logger", ".", "debug", "(", "'Global dataset preprocessing configuration found'", ")", "preprocessing_config", "=", "datasets_config", ".", "pop", "(", "'preprocessing'", ")", "for", "dataset_name", ",", "dataset", "in", "datasets_config", ".", "items", "(", ")", ":", "if", "not", "dataset", ".", "preprocessing", ":", "dataset", "[", "'preprocessing'", "]", "=", "preprocessing_config", "else", ":", "logger", ".", "debug", "(", "'Local preprocessing configuration is used for {} dataset'", ".", "format", "(", "dataset_name", ")", ")", "ConfigReader", ".", "check_local_config", "(", "ac_conf", ")", "ac_conf", "=", "ConfigReader", ".", "convert_paths", "(", "ac_conf", ")", "ConfigReader", ".", "_filter_launchers", "(", "ac_conf", ",", "filtering_params", ",", "mode", "=", "mode", ")", "for", "req_num", "in", "[", "'stat_requests_number'", ",", "'eval_requests_number'", "]", ":", "ac_conf", "[", "req_num", "]", "=", "self", ".", "engine", "[", "req_num", "]", "if", "req_num", "in", "self", ".", "engine", "else", "None", "self", "[", "'engine'", "]", "=", "ac_conf" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/configs/config.py#L320-L349
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
TranslationUnit.__init__
(self, ptr, index)
Create a TranslationUnit instance. TranslationUnits should be created using one of the from_* @classmethod functions above. __init__ is only called internally.
Create a TranslationUnit instance.
[ "Create", "a", "TranslationUnit", "instance", "." ]
def __init__(self, ptr, index): """Create a TranslationUnit instance. TranslationUnits should be created using one of the from_* @classmethod functions above. __init__ is only called internally. """ assert isinstance(index, Index) ClangObject.__init__(self, ptr)
[ "def", "__init__", "(", "self", ",", "ptr", ",", "index", ")", ":", "assert", "isinstance", "(", "index", ",", "Index", ")", "ClangObject", ".", "__init__", "(", "self", ",", "ptr", ")" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2251-L2259
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/urllib/request.py
python
URLopener.open_unknown
(self, fullurl, data=None)
Overridable interface to open unknown URL type.
Overridable interface to open unknown URL type.
[ "Overridable", "interface", "to", "open", "unknown", "URL", "type", "." ]
def open_unknown(self, fullurl, data=None): """Overridable interface to open unknown URL type.""" type, url = _splittype(fullurl) raise OSError('url error', 'unknown url type', type)
[ "def", "open_unknown", "(", "self", ",", "fullurl", ",", "data", "=", "None", ")", ":", "type", ",", "url", "=", "_splittype", "(", "fullurl", ")", "raise", "OSError", "(", "'url error'", ",", "'unknown url type'", ",", "type", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/urllib/request.py#L1794-L1797
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/hermite_e.py
python
hermediv
(c1, c2)
return pu._div(hermemul, c1, c2)
Divide one Hermite series by another. Returns the quotient-with-remainder of two Hermite series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of Hermite series coefficients representing the quotient and remainder. See Also -------- hermeadd, hermesub, hermemulx, hermemul, hermepow Notes ----- In general, the (polynomial) division of one Hermite series by another results in quotient and remainder terms that are not in the Hermite polynomial basis set. Thus, to express these results as a Hermite series, it is necessary to "reproject" the results onto the Hermite basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite_e import hermediv >>> hermediv([ 14., 15., 28., 7., 6.], [0, 1, 2]) (array([1., 2., 3.]), array([0.])) >>> hermediv([ 15., 17., 28., 7., 6.], [0, 1, 2]) (array([1., 2., 3.]), array([1., 2.]))
Divide one Hermite series by another.
[ "Divide", "one", "Hermite", "series", "by", "another", "." ]
def hermediv(c1, c2): """ Divide one Hermite series by another. Returns the quotient-with-remainder of two Hermite series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of Hermite series coefficients representing the quotient and remainder. See Also -------- hermeadd, hermesub, hermemulx, hermemul, hermepow Notes ----- In general, the (polynomial) division of one Hermite series by another results in quotient and remainder terms that are not in the Hermite polynomial basis set. Thus, to express these results as a Hermite series, it is necessary to "reproject" the results onto the Hermite basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite_e import hermediv >>> hermediv([ 14., 15., 28., 7., 6.], [0, 1, 2]) (array([1., 2., 3.]), array([0.])) >>> hermediv([ 15., 17., 28., 7., 6.], [0, 1, 2]) (array([1., 2., 3.]), array([1., 2.])) """ return pu._div(hermemul, c1, c2)
[ "def", "hermediv", "(", "c1", ",", "c2", ")", ":", "return", "pu", ".", "_div", "(", "hermemul", ",", "c1", ",", "c2", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/hermite_e.py#L487-L530
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/seqan/auto_build.py
python
work
(options)
Run the steps.
Run the steps.
[ "Run", "the", "steps", "." ]
def work(options): """Run the steps.""" if options.src_tar: return workSrcTar(options) elif not options.build_trunk_as: return workTags(options) else: return workTrunk(options)
[ "def", "work", "(", "options", ")", ":", "if", "options", ".", "src_tar", ":", "return", "workSrcTar", "(", "options", ")", "elif", "not", "options", ".", "build_trunk_as", ":", "return", "workTags", "(", "options", ")", "else", ":", "return", "workTrunk", "(", "options", ")" ]
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/auto_build.py#L476-L483
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py
python
find_distributions
(path_item, only=False)
return finder(importer, path_item, only)
Yield distributions accessible via `path_item`
Yield distributions accessible via `path_item`
[ "Yield", "distributions", "accessible", "via", "path_item" ]
def find_distributions(path_item, only=False): """Yield distributions accessible via `path_item`""" importer = get_importer(path_item) finder = _find_adapter(_distribution_finders, importer) return finder(importer, path_item, only)
[ "def", "find_distributions", "(", "path_item", ",", "only", "=", "False", ")", ":", "importer", "=", "get_importer", "(", "path_item", ")", "finder", "=", "_find_adapter", "(", "_distribution_finders", ",", "importer", ")", "return", "finder", "(", "importer", ",", "path_item", ",", "only", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py#L1804-L1808
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/cmdline.py
python
unglob_args
(args)
return args
Interpret shell wildcards for platforms that need it.
Interpret shell wildcards for platforms that need it.
[ "Interpret", "shell", "wildcards", "for", "platforms", "that", "need", "it", "." ]
def unglob_args(args): """Interpret shell wildcards for platforms that need it.""" if env.WINDOWS: globbed = [] for arg in args: if '?' in arg or '*' in arg: globbed.extend(glob.glob(arg)) else: globbed.append(arg) args = globbed return args
[ "def", "unglob_args", "(", "args", ")", ":", "if", "env", ".", "WINDOWS", ":", "globbed", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "'?'", "in", "arg", "or", "'*'", "in", "arg", ":", "globbed", ".", "extend", "(", "glob", ".", "glob", "(", "arg", ")", ")", "else", ":", "globbed", ".", "append", "(", "arg", ")", "args", "=", "globbed", "return", "args" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/cmdline.py#L687-L697
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ctypes/__init__.py
python
create_string_buffer
(init, size=None)
create_string_buffer(aBytes) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array
create_string_buffer(aBytes) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array
[ "create_string_buffer", "(", "aBytes", ")", "-", ">", "character", "array", "create_string_buffer", "(", "anInteger", ")", "-", ">", "character", "array", "create_string_buffer", "(", "aBytes", "anInteger", ")", "-", ">", "character", "array" ]
def create_string_buffer(init, size=None): """create_string_buffer(aBytes) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array """ if isinstance(init, bytes): if size is None: size = len(init)+1 _sys.audit("ctypes.create_string_buffer", init, size) buftype = c_char * size buf = buftype() buf.value = init return buf elif isinstance(init, int): _sys.audit("ctypes.create_string_buffer", None, init) buftype = c_char * init buf = buftype() return buf raise TypeError(init)
[ "def", "create_string_buffer", "(", "init", ",", "size", "=", "None", ")", ":", "if", "isinstance", "(", "init", ",", "bytes", ")", ":", "if", "size", "is", "None", ":", "size", "=", "len", "(", "init", ")", "+", "1", "_sys", ".", "audit", "(", "\"ctypes.create_string_buffer\"", ",", "init", ",", "size", ")", "buftype", "=", "c_char", "*", "size", "buf", "=", "buftype", "(", ")", "buf", ".", "value", "=", "init", "return", "buf", "elif", "isinstance", "(", "init", ",", "int", ")", ":", "_sys", ".", "audit", "(", "\"ctypes.create_string_buffer\"", ",", "None", ",", "init", ")", "buftype", "=", "c_char", "*", "init", "buf", "=", "buftype", "(", ")", "return", "buf", "raise", "TypeError", "(", "init", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ctypes/__init__.py#L49-L67
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
bin/jenkins/critique-gerrit-review.py
python
add_misc_comments_for_line
(comments, line, curr_file, curr_line_num)
Helper for get_misc_comments to generate comments for 'line' at 'curr_line_num' in 'curr_file' and append them to 'comments'.
Helper for get_misc_comments to generate comments for 'line' at 'curr_line_num' in 'curr_file' and append them to 'comments'.
[ "Helper", "for", "get_misc_comments", "to", "generate", "comments", "for", "line", "at", "curr_line_num", "in", "curr_file", "and", "append", "them", "to", "comments", "." ]
def add_misc_comments_for_line(comments, line, curr_file, curr_line_num): """Helper for get_misc_comments to generate comments for 'line' at 'curr_line_num' in 'curr_file' and append them to 'comments'.""" # Check for trailing whitespace. if line.rstrip() != line: comments[curr_file].append( {"message": "line has trailing whitespace", "line": curr_line_num}) # Check for long lines. Skip .py files since flake8 already flags long lines. if len(line) > LINE_LIMIT and os.path.splitext(curr_file)[1] != ".py": msg = "line too long ({0} > {1})".format(len(line), LINE_LIMIT) comments[curr_file].append( {"message": msg, "line": curr_line_num}) if '\t' in line: comments[curr_file].append( {"message": "tab used for whitespace", "line": curr_line_num}) if 'ThriftDebugString' in line: comments[curr_file].append( {"message": ("Please make sure you don't output sensitive data with " "ThriftDebugString(). If so, use impala::RedactedDebugString() " "instead."), "line": curr_line_num })
[ "def", "add_misc_comments_for_line", "(", "comments", ",", "line", ",", "curr_file", ",", "curr_line_num", ")", ":", "# Check for trailing whitespace.", "if", "line", ".", "rstrip", "(", ")", "!=", "line", ":", "comments", "[", "curr_file", "]", ".", "append", "(", "{", "\"message\"", ":", "\"line has trailing whitespace\"", ",", "\"line\"", ":", "curr_line_num", "}", ")", "# Check for long lines. Skip .py files since flake8 already flags long lines.", "if", "len", "(", "line", ")", ">", "LINE_LIMIT", "and", "os", ".", "path", ".", "splitext", "(", "curr_file", ")", "[", "1", "]", "!=", "\".py\"", ":", "msg", "=", "\"line too long ({0} > {1})\"", ".", "format", "(", "len", "(", "line", ")", ",", "LINE_LIMIT", ")", "comments", "[", "curr_file", "]", ".", "append", "(", "{", "\"message\"", ":", "msg", ",", "\"line\"", ":", "curr_line_num", "}", ")", "if", "'\\t'", "in", "line", ":", "comments", "[", "curr_file", "]", ".", "append", "(", "{", "\"message\"", ":", "\"tab used for whitespace\"", ",", "\"line\"", ":", "curr_line_num", "}", ")", "if", "'ThriftDebugString'", "in", "line", ":", "comments", "[", "curr_file", "]", ".", "append", "(", "{", "\"message\"", ":", "(", "\"Please make sure you don't output sensitive data with \"", "\"ThriftDebugString(). If so, use impala::RedactedDebugString() \"", "\"instead.\"", ")", ",", "\"line\"", ":", "curr_line_num", "}", ")" ]
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/jenkins/critique-gerrit-review.py#L174-L197
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/wsgiref/handlers.py
python
BaseHandler.add_cgi_vars
(self)
Override in subclass to insert CGI variables in 'self.environ
Override in subclass to insert CGI variables in 'self.environ
[ "Override", "in", "subclass", "to", "insert", "CGI", "variables", "in", "self", ".", "environ" ]
def add_cgi_vars(self): """Override in subclass to insert CGI variables in 'self.environ'""" raise NotImplementedError
[ "def", "add_cgi_vars", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/wsgiref/handlers.py#L428-L430
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
python
SequenceQueueingStateSaver.close
(self, cancel_pending_enqueues=False, name=None)
Closes the barrier and the FIFOQueue. This operation signals that no more segments of new sequences will be enqueued. New segments of already inserted sequences may still be enqueued and dequeued if there is a sufficient number filling a batch or allow_small_batch is true. Otherwise dequeue operations will fail immediately. Args: cancel_pending_enqueues: (Optional.) A boolean, defaulting to `False`. If `True`, all pending enqueues to the underlying queues will be cancelled, and completing already started sequences is not possible. name: Optional name for the op. Returns: The operation that closes the barrier and the FIFOQueue.
Closes the barrier and the FIFOQueue.
[ "Closes", "the", "barrier", "and", "the", "FIFOQueue", "." ]
def close(self, cancel_pending_enqueues=False, name=None): """Closes the barrier and the FIFOQueue. This operation signals that no more segments of new sequences will be enqueued. New segments of already inserted sequences may still be enqueued and dequeued if there is a sufficient number filling a batch or allow_small_batch is true. Otherwise dequeue operations will fail immediately. Args: cancel_pending_enqueues: (Optional.) A boolean, defaulting to `False`. If `True`, all pending enqueues to the underlying queues will be cancelled, and completing already started sequences is not possible. name: Optional name for the op. Returns: The operation that closes the barrier and the FIFOQueue. """ with ops.name_scope(name, "SQSSClose", [self._prefetch_op]) as name: barrier_close = self.barrier.close(cancel_pending_enqueues, "BarrierClose") fifo_queue_close = self._capacity_queue.close(cancel_pending_enqueues, "FIFOClose") return control_flow_ops.group(barrier_close, fifo_queue_close, name=name)
[ "def", "close", "(", "self", ",", "cancel_pending_enqueues", "=", "False", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"SQSSClose\"", ",", "[", "self", ".", "_prefetch_op", "]", ")", "as", "name", ":", "barrier_close", "=", "self", ".", "barrier", ".", "close", "(", "cancel_pending_enqueues", ",", "\"BarrierClose\"", ")", "fifo_queue_close", "=", "self", ".", "_capacity_queue", ".", "close", "(", "cancel_pending_enqueues", ",", "\"FIFOClose\"", ")", "return", "control_flow_ops", ".", "group", "(", "barrier_close", ",", "fifo_queue_close", ",", "name", "=", "name", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L953-L976
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/abc.py
python
ABCMeta.register
(cls, subclass)
Register a virtual subclass of an ABC.
Register a virtual subclass of an ABC.
[ "Register", "a", "virtual", "subclass", "of", "an", "ABC", "." ]
def register(cls, subclass): """Register a virtual subclass of an ABC.""" if not isinstance(cls, type): raise TypeError("Can only register classes") if issubclass(subclass, cls): return # Already a subclass # Subtle: test for cycles *after* testing for "already a subclass"; # this means we allow X.register(X) and interpret it as a no-op. if issubclass(cls, subclass): # This would create a cycle, which is bad for the algorithm below raise RuntimeError("Refusing to create an inheritance cycle") cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1
[ "def", "register", "(", "cls", ",", "subclass", ")", ":", "if", "not", "isinstance", "(", "cls", ",", "type", ")", ":", "raise", "TypeError", "(", "\"Can only register classes\"", ")", "if", "issubclass", "(", "subclass", ",", "cls", ")", ":", "return", "# Already a subclass", "# Subtle: test for cycles *after* testing for \"already a subclass\";", "# this means we allow X.register(X) and interpret it as a no-op.", "if", "issubclass", "(", "cls", ",", "subclass", ")", ":", "# This would create a cycle, which is bad for the algorithm below", "raise", "RuntimeError", "(", "\"Refusing to create an inheritance cycle\"", ")", "cls", ".", "_abc_registry", ".", "add", "(", "subclass", ")", "ABCMeta", ".", "_abc_invalidation_counter", "+=", "1" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/abc.py#L97-L109
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/callbacks.py
python
CallbackList._call_begin_hook
(self, mode)
Helper function for on_{train|test|predict}_begin methods.
Helper function for on_{train|test|predict}_begin methods.
[ "Helper", "function", "for", "on_", "{", "train|test|predict", "}", "_begin", "methods", "." ]
def _call_begin_hook(self, mode): """Helper function for on_{train|test|predict}_begin methods.""" if mode == ModeKeys.TRAIN: self.on_train_begin() elif mode == ModeKeys.TEST: self.on_test_begin() else: self.on_predict_begin()
[ "def", "_call_begin_hook", "(", "self", ",", "mode", ")", ":", "if", "mode", "==", "ModeKeys", ".", "TRAIN", ":", "self", ".", "on_train_begin", "(", ")", "elif", "mode", "==", "ModeKeys", ".", "TEST", ":", "self", ".", "on_test_begin", "(", ")", "else", ":", "self", ".", "on_predict_begin", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/callbacks.py#L247-L254
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/apitools/apitools/gen/message_registry.py
python
MessageRegistry.__AddAdditionalProperties
(self, message, schema, properties)
Add an additionalProperties field to message.
Add an additionalProperties field to message.
[ "Add", "an", "additionalProperties", "field", "to", "message", "." ]
def __AddAdditionalProperties(self, message, schema, properties): """Add an additionalProperties field to message.""" additional_properties_info = schema['additionalProperties'] entries_type_name = self.__AddAdditionalPropertyType( message.name, additional_properties_info) description = util.CleanDescription( additional_properties_info.get('description')) if description is None: description = 'Additional properties of type %s' % message.name attrs = { 'items': { '$ref': entries_type_name, }, 'description': description, 'type': 'array', } field_name = 'additionalProperties' message.fields.append(self.__FieldDescriptorFromProperties( field_name, len(properties) + 1, attrs)) self.__AddImport('from %s import encoding' % self.__base_files_package) message.decorators.append( 'encoding.MapUnrecognizedFields(%r)' % field_name)
[ "def", "__AddAdditionalProperties", "(", "self", ",", "message", ",", "schema", ",", "properties", ")", ":", "additional_properties_info", "=", "schema", "[", "'additionalProperties'", "]", "entries_type_name", "=", "self", ".", "__AddAdditionalPropertyType", "(", "message", ".", "name", ",", "additional_properties_info", ")", "description", "=", "util", ".", "CleanDescription", "(", "additional_properties_info", ".", "get", "(", "'description'", ")", ")", "if", "description", "is", "None", ":", "description", "=", "'Additional properties of type %s'", "%", "message", ".", "name", "attrs", "=", "{", "'items'", ":", "{", "'$ref'", ":", "entries_type_name", ",", "}", ",", "'description'", ":", "description", ",", "'type'", ":", "'array'", ",", "}", "field_name", "=", "'additionalProperties'", "message", ".", "fields", ".", "append", "(", "self", ".", "__FieldDescriptorFromProperties", "(", "field_name", ",", "len", "(", "properties", ")", "+", "1", ",", "attrs", ")", ")", "self", ".", "__AddImport", "(", "'from %s import encoding'", "%", "self", ".", "__base_files_package", ")", "message", ".", "decorators", ".", "append", "(", "'encoding.MapUnrecognizedFields(%r)'", "%", "field_name", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/gen/message_registry.py#L213-L234
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/engine/thermostats.py
python
ThermoPILE_L.bind
(self, nm=None, prng=None, bindcentroid=True, fixdof=None)
Binds the appropriate degrees of freedom to the thermostat. This takes a beads object with degrees of freedom, and makes its momentum and mass vectors members of the thermostat. It also then creates the objects that will hold the data needed in the thermostat algorithms and the dependency network. Gives the interface for both the PILE_L and PILE_G thermostats, which only differ in their treatment of the centroid coordinate momenta. Args: nm: An optional normal mode object to take the mass and momentum vectors from. prng: An optional pseudo random number generator object. Defaults to Random(). bindcentroid: An optional boolean which decides whether a Langevin thermostat is attached to the centroid mode of each atom separately, or the total kinetic energy. Defaults to True, which gives a thermostat bound to each centroid momentum. fixdof: An optional integer which can specify the number of constraints applied to the system. Defaults to zero. Raises: TypeError: Raised if no appropriate degree of freedom or object containing a momentum vector is specified for the thermostat to couple to.
Binds the appropriate degrees of freedom to the thermostat.
[ "Binds", "the", "appropriate", "degrees", "of", "freedom", "to", "the", "thermostat", "." ]
def bind(self, nm=None, prng=None, bindcentroid=True, fixdof=None): """Binds the appropriate degrees of freedom to the thermostat. This takes a beads object with degrees of freedom, and makes its momentum and mass vectors members of the thermostat. It also then creates the objects that will hold the data needed in the thermostat algorithms and the dependency network. Gives the interface for both the PILE_L and PILE_G thermostats, which only differ in their treatment of the centroid coordinate momenta. Args: nm: An optional normal mode object to take the mass and momentum vectors from. prng: An optional pseudo random number generator object. Defaults to Random(). bindcentroid: An optional boolean which decides whether a Langevin thermostat is attached to the centroid mode of each atom separately, or the total kinetic energy. Defaults to True, which gives a thermostat bound to each centroid momentum. fixdof: An optional integer which can specify the number of constraints applied to the system. Defaults to zero. Raises: TypeError: Raised if no appropriate degree of freedom or object containing a momentum vector is specified for the thermostat to couple to. """ if nm is None or not type(nm) is NormalModes: raise TypeError("ThermoPILE_L.bind expects a NormalModes argument to bind to") if prng is None: self.prng = Random() else: self.prng = prng prev_ethermo = self.ethermo # creates a set of thermostats to be applied to individual normal modes self._thermos = [ ThermoLangevin(temp=1, dt=1, tau=1) for b in range(nm.nbeads) ] # optionally does not bind the centroid, so we can re-use all of this # in the PILE_G case if not bindcentroid: self._thermos[0] = None self.nm = nm dset(self,"tauk", depend_array(name="tauk", value=np.zeros(nm.nbeads-1,float), func=self.get_tauk, dependencies=[dget(self,"pilescale"), dget(nm,"dynomegak")] ) ) # must pipe all the dependencies in such a way that values for the nm thermostats # are automatically updated based on the "master" thermostat def make_taugetter(k): return lambda: self.tauk[k-1] it = 0 for t in self._thermos: if t is None: it += 1 continue if it > 0: fixdof = None # only the centroid thermostat may have constraints # bind thermostat t to the it-th bead t.bind(pm=(nm.pnm[it,:],nm.dynm3[it,:]),prng=self.prng, fixdof=fixdof) # pipes temp and dt deppipe(self,"temp", t, "temp") deppipe(self,"dt", t, "dt") # for tau it is slightly more complex if it == 0: deppipe(self,"tau", t, "tau") else: # Here we manually connect _thermos[i].tau to tauk[i]. # Simple and clear. dget(t,"tau").add_dependency(dget(self,"tauk")) dget(t,"tau")._func = make_taugetter(it) dget(self,"ethermo").add_dependency(dget(t,"ethermo")) it += 1 # since the ethermo will be "delegated" to the normal modes thermostats, # one has to split # any previously-stored value between the sub-thermostats if bindcentroid: for t in self._thermos: t.ethermo = prev_ethermo/nm.nbeads dget(self,"ethermo")._func = self.get_ethermo;
[ "def", "bind", "(", "self", ",", "nm", "=", "None", ",", "prng", "=", "None", ",", "bindcentroid", "=", "True", ",", "fixdof", "=", "None", ")", ":", "if", "nm", "is", "None", "or", "not", "type", "(", "nm", ")", "is", "NormalModes", ":", "raise", "TypeError", "(", "\"ThermoPILE_L.bind expects a NormalModes argument to bind to\"", ")", "if", "prng", "is", "None", ":", "self", ".", "prng", "=", "Random", "(", ")", "else", ":", "self", ".", "prng", "=", "prng", "prev_ethermo", "=", "self", ".", "ethermo", "# creates a set of thermostats to be applied to individual normal modes", "self", ".", "_thermos", "=", "[", "ThermoLangevin", "(", "temp", "=", "1", ",", "dt", "=", "1", ",", "tau", "=", "1", ")", "for", "b", "in", "range", "(", "nm", ".", "nbeads", ")", "]", "# optionally does not bind the centroid, so we can re-use all of this", "# in the PILE_G case", "if", "not", "bindcentroid", ":", "self", ".", "_thermos", "[", "0", "]", "=", "None", "self", ".", "nm", "=", "nm", "dset", "(", "self", ",", "\"tauk\"", ",", "depend_array", "(", "name", "=", "\"tauk\"", ",", "value", "=", "np", ".", "zeros", "(", "nm", ".", "nbeads", "-", "1", ",", "float", ")", ",", "func", "=", "self", ".", "get_tauk", ",", "dependencies", "=", "[", "dget", "(", "self", ",", "\"pilescale\"", ")", ",", "dget", "(", "nm", ",", "\"dynomegak\"", ")", "]", ")", ")", "# must pipe all the dependencies in such a way that values for the nm thermostats", "# are automatically updated based on the \"master\" thermostat", "def", "make_taugetter", "(", "k", ")", ":", "return", "lambda", ":", "self", ".", "tauk", "[", "k", "-", "1", "]", "it", "=", "0", "for", "t", "in", "self", ".", "_thermos", ":", "if", "t", "is", "None", ":", "it", "+=", "1", "continue", "if", "it", ">", "0", ":", "fixdof", "=", "None", "# only the centroid thermostat may have constraints", "# bind thermostat t to the it-th bead", "t", ".", "bind", "(", "pm", "=", "(", "nm", ".", "pnm", "[", "it", ",", ":", "]", ",", "nm", ".", "dynm3", "[", "it", ",", ":", "]", ")", ",", "prng", "=", "self", ".", "prng", ",", "fixdof", "=", "fixdof", ")", "# pipes temp and dt", "deppipe", "(", "self", ",", "\"temp\"", ",", "t", ",", "\"temp\"", ")", "deppipe", "(", "self", ",", "\"dt\"", ",", "t", ",", "\"dt\"", ")", "# for tau it is slightly more complex", "if", "it", "==", "0", ":", "deppipe", "(", "self", ",", "\"tau\"", ",", "t", ",", "\"tau\"", ")", "else", ":", "# Here we manually connect _thermos[i].tau to tauk[i].", "# Simple and clear.", "dget", "(", "t", ",", "\"tau\"", ")", ".", "add_dependency", "(", "dget", "(", "self", ",", "\"tauk\"", ")", ")", "dget", "(", "t", ",", "\"tau\"", ")", ".", "_func", "=", "make_taugetter", "(", "it", ")", "dget", "(", "self", ",", "\"ethermo\"", ")", ".", "add_dependency", "(", "dget", "(", "t", ",", "\"ethermo\"", ")", ")", "it", "+=", "1", "# since the ethermo will be \"delegated\" to the normal modes thermostats,", "# one has to split", "# any previously-stored value between the sub-thermostats", "if", "bindcentroid", ":", "for", "t", "in", "self", ".", "_thermos", ":", "t", ".", "ethermo", "=", "prev_ethermo", "/", "nm", ".", "nbeads", "dget", "(", "self", ",", "\"ethermo\"", ")", ".", "_func", "=", "self", ".", "get_ethermo" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/thermostats.py#L265-L351
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.AutoSize
(*args, **kwargs)
return _grid.Grid_AutoSize(*args, **kwargs)
AutoSize(self)
AutoSize(self)
[ "AutoSize", "(", "self", ")" ]
def AutoSize(*args, **kwargs): """AutoSize(self)""" return _grid.Grid_AutoSize(*args, **kwargs)
[ "def", "AutoSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_AutoSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1898-L1900
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/BASIC/basparse.py
python
p_expr_unary
(p)
expr : MINUS expr %prec UMINUS
expr : MINUS expr %prec UMINUS
[ "expr", ":", "MINUS", "expr", "%prec", "UMINUS" ]
def p_expr_unary(p): '''expr : MINUS expr %prec UMINUS''' p[0] = ('UNARY','-',p[2])
[ "def", "p_expr_unary", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'UNARY'", ",", "'-'", ",", "p", "[", "2", "]", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/BASIC/basparse.py#L304-L306
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/MSCommon/vc.py
python
find_vc_pdir_vswhere
(msvc_version)
Find the MSVC product directory using vswhere.exe . Run it asking for specified version and get MSVS install location :param msvc_version: :return: MSVC install dir
Find the MSVC product directory using vswhere.exe . Run it asking for specified version and get MSVS install location :param msvc_version: :return: MSVC install dir
[ "Find", "the", "MSVC", "product", "directory", "using", "vswhere", ".", "exe", ".", "Run", "it", "asking", "for", "specified", "version", "and", "get", "MSVS", "install", "location", ":", "param", "msvc_version", ":", ":", "return", ":", "MSVC", "install", "dir" ]
def find_vc_pdir_vswhere(msvc_version): """ Find the MSVC product directory using vswhere.exe . Run it asking for specified version and get MSVS install location :param msvc_version: :return: MSVC install dir """ vswhere_path = os.path.join( 'C:\\', 'Program Files (x86)', 'Microsoft Visual Studio', 'Installer', 'vswhere.exe' ) vswhere_cmd = [vswhere_path, '-version', msvc_version, '-property', 'installationPath'] if os.path.exists(vswhere_path): sp = subprocess.Popen(vswhere_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) vsdir, err = sp.communicate() vsdir = vsdir.decode("mbcs") vsdir = vsdir.rstrip() vc_pdir = os.path.join(vsdir, 'VC') return vc_pdir else: # No vswhere on system, no install info available return None
[ "def", "find_vc_pdir_vswhere", "(", "msvc_version", ")", ":", "vswhere_path", "=", "os", ".", "path", ".", "join", "(", "'C:\\\\'", ",", "'Program Files (x86)'", ",", "'Microsoft Visual Studio'", ",", "'Installer'", ",", "'vswhere.exe'", ")", "vswhere_cmd", "=", "[", "vswhere_path", ",", "'-version'", ",", "msvc_version", ",", "'-property'", ",", "'installationPath'", "]", "if", "os", ".", "path", ".", "exists", "(", "vswhere_path", ")", ":", "sp", "=", "subprocess", ".", "Popen", "(", "vswhere_cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "vsdir", ",", "err", "=", "sp", ".", "communicate", "(", ")", "vsdir", "=", "vsdir", ".", "decode", "(", "\"mbcs\"", ")", "vsdir", "=", "vsdir", ".", "rstrip", "(", ")", "vc_pdir", "=", "os", ".", "path", ".", "join", "(", "vsdir", ",", "'VC'", ")", "return", "vc_pdir", "else", ":", "# No vswhere on system, no install info available", "return", "None" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/MSCommon/vc.py#L229-L254
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/summary/writer/writer.py
python
SummaryToEventTransformer.__init__
(self, event_writer, graph=None, graph_def=None)
Creates a `SummaryWriter` and an event file. On construction the summary writer creates a new event file in `logdir`. This event file will contain `Event` protocol buffers constructed when you call one of the following functions: `add_summary()`, `add_session_log()`, `add_event()`, or `add_graph()`. If you pass a `Graph` to the constructor it is added to the event file. (This is equivalent to calling `add_graph()` later). TensorBoard will pick the graph from the file and display it graphically so you can interactively explore the graph you built. You will usually pass the graph from the session in which you launched it: ```python ...create a graph... # Launch the graph in a session. sess = tf.compat.v1.Session() # Create a summary writer, add the 'graph' to the event file. writer = tf.compat.v1.summary.FileWriter(<some-directory>, sess.graph) ``` Args: event_writer: An EventWriter. Implements add_event and get_logdir. graph: A `Graph` object, such as `sess.graph`. graph_def: DEPRECATED: Use the `graph` argument instead.
Creates a `SummaryWriter` and an event file.
[ "Creates", "a", "SummaryWriter", "and", "an", "event", "file", "." ]
def __init__(self, event_writer, graph=None, graph_def=None): """Creates a `SummaryWriter` and an event file. On construction the summary writer creates a new event file in `logdir`. This event file will contain `Event` protocol buffers constructed when you call one of the following functions: `add_summary()`, `add_session_log()`, `add_event()`, or `add_graph()`. If you pass a `Graph` to the constructor it is added to the event file. (This is equivalent to calling `add_graph()` later). TensorBoard will pick the graph from the file and display it graphically so you can interactively explore the graph you built. You will usually pass the graph from the session in which you launched it: ```python ...create a graph... # Launch the graph in a session. sess = tf.compat.v1.Session() # Create a summary writer, add the 'graph' to the event file. writer = tf.compat.v1.summary.FileWriter(<some-directory>, sess.graph) ``` Args: event_writer: An EventWriter. Implements add_event and get_logdir. graph: A `Graph` object, such as `sess.graph`. graph_def: DEPRECATED: Use the `graph` argument instead. """ self.event_writer = event_writer # For storing used tags for session.run() outputs. self._session_run_tags = {} if graph is not None or graph_def is not None: # Calling it with both graph and graph_def for backward compatibility. self.add_graph(graph=graph, graph_def=graph_def) # Also export the meta_graph_def in this case. # graph may itself be a graph_def due to positional arguments maybe_graph_as_def = (graph.as_graph_def(add_shapes=True) if isinstance(graph, ops.Graph) else graph) self.add_meta_graph( meta_graph.create_meta_graph_def(graph_def=graph_def or maybe_graph_as_def)) # This set contains tags of Summary Values that have been encountered # already. The motivation here is that the SummaryWriter only keeps the # metadata property (which is a SummaryMetadata proto) of the first Summary # Value encountered for each tag. The SummaryWriter strips away the # SummaryMetadata for all subsequent Summary Values with tags seen # previously. This saves space. self._seen_summary_tags = set()
[ "def", "__init__", "(", "self", ",", "event_writer", ",", "graph", "=", "None", ",", "graph_def", "=", "None", ")", ":", "self", ".", "event_writer", "=", "event_writer", "# For storing used tags for session.run() outputs.", "self", ".", "_session_run_tags", "=", "{", "}", "if", "graph", "is", "not", "None", "or", "graph_def", "is", "not", "None", ":", "# Calling it with both graph and graph_def for backward compatibility.", "self", ".", "add_graph", "(", "graph", "=", "graph", ",", "graph_def", "=", "graph_def", ")", "# Also export the meta_graph_def in this case.", "# graph may itself be a graph_def due to positional arguments", "maybe_graph_as_def", "=", "(", "graph", ".", "as_graph_def", "(", "add_shapes", "=", "True", ")", "if", "isinstance", "(", "graph", ",", "ops", ".", "Graph", ")", "else", "graph", ")", "self", ".", "add_meta_graph", "(", "meta_graph", ".", "create_meta_graph_def", "(", "graph_def", "=", "graph_def", "or", "maybe_graph_as_def", ")", ")", "# This set contains tags of Summary Values that have been encountered", "# already. The motivation here is that the SummaryWriter only keeps the", "# metadata property (which is a SummaryMetadata proto) of the first Summary", "# Value encountered for each tag. The SummaryWriter strips away the", "# SummaryMetadata for all subsequent Summary Values with tags seen", "# previously. This saves space.", "self", ".", "_seen_summary_tags", "=", "set", "(", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/summary/writer/writer.py#L46-L95
GoSSIP-SJTU/Armariris
ad5d868482956b2194a77b39c8d543c7c2318200
bindings/python/llvm/common.py
python
LLVMObject.from_param
(self)
return self._as_parameter_
ctypes function that converts this object to a function parameter.
ctypes function that converts this object to a function parameter.
[ "ctypes", "function", "that", "converts", "this", "object", "to", "a", "function", "parameter", "." ]
def from_param(self): """ctypes function that converts this object to a function parameter.""" return self._as_parameter_
[ "def", "from_param", "(", "self", ")", ":", "return", "self", ".", "_as_parameter_" ]
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/bindings/python/llvm/common.py#L60-L62
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Wrapping/Python/vtkmodules/gtk/GtkVTKRenderWindowInteractor.py
python
GtkVTKRenderWindowInteractor.OnButtonUp
(self, wid, event)
return gtk.FALSE
Mouse button released.
Mouse button released.
[ "Mouse", "button", "released", "." ]
def OnButtonUp(self, wid, event): """Mouse button released.""" m = self.get_pointer() ctrl, shift = self._GetCtrlShift(event) self._Iren.SetEventInformationFlipY(m[0], m[1], ctrl, shift, chr(0), 0, None) button = event.button if button == 3: self._Iren.RightButtonReleaseEvent() return gtk.TRUE elif button == 1: self._Iren.LeftButtonReleaseEvent() return gtk.TRUE elif button == 2: self._Iren.MiddleButtonReleaseEvent() return gtk.TRUE return gtk.FALSE
[ "def", "OnButtonUp", "(", "self", ",", "wid", ",", "event", ")", ":", "m", "=", "self", ".", "get_pointer", "(", ")", "ctrl", ",", "shift", "=", "self", ".", "_GetCtrlShift", "(", "event", ")", "self", ".", "_Iren", ".", "SetEventInformationFlipY", "(", "m", "[", "0", "]", ",", "m", "[", "1", "]", ",", "ctrl", ",", "shift", ",", "chr", "(", "0", ")", ",", "0", ",", "None", ")", "button", "=", "event", ".", "button", "if", "button", "==", "3", ":", "self", ".", "_Iren", ".", "RightButtonReleaseEvent", "(", ")", "return", "gtk", ".", "TRUE", "elif", "button", "==", "1", ":", "self", ".", "_Iren", ".", "LeftButtonReleaseEvent", "(", ")", "return", "gtk", ".", "TRUE", "elif", "button", "==", "2", ":", "self", ".", "_Iren", ".", "MiddleButtonReleaseEvent", "(", ")", "return", "gtk", ".", "TRUE", "return", "gtk", ".", "FALSE" ]
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/gtk/GtkVTKRenderWindowInteractor.py#L169-L186
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/bullet/minitaur.py
python
Minitaur.ConvertFromLegModel
(self, actions)
return motor_angle
Convert the actions that use leg model to the real motor actions. Args: actions: The theta, phi of the leg model. Returns: The eight desired motor angles that can be used in ApplyActions().
Convert the actions that use leg model to the real motor actions.
[ "Convert", "the", "actions", "that", "use", "leg", "model", "to", "the", "real", "motor", "actions", "." ]
def ConvertFromLegModel(self, actions): """Convert the actions that use leg model to the real motor actions. Args: actions: The theta, phi of the leg model. Returns: The eight desired motor angles that can be used in ApplyActions(). """ motor_angle = copy.deepcopy(actions) scale_for_singularity = 1 offset_for_singularity = 1.5 half_num_motors = int(self.num_motors / 2) quater_pi = math.pi / 4 for i in range(self.num_motors): action_idx = i // 2 forward_backward_component = ( -scale_for_singularity * quater_pi * (actions[action_idx + half_num_motors] + offset_for_singularity)) extension_component = (-1)**i * quater_pi * actions[action_idx] if i >= half_num_motors: extension_component = -extension_component motor_angle[i] = (math.pi + forward_backward_component + extension_component) return motor_angle
[ "def", "ConvertFromLegModel", "(", "self", ",", "actions", ")", ":", "motor_angle", "=", "copy", ".", "deepcopy", "(", "actions", ")", "scale_for_singularity", "=", "1", "offset_for_singularity", "=", "1.5", "half_num_motors", "=", "int", "(", "self", ".", "num_motors", "/", "2", ")", "quater_pi", "=", "math", ".", "pi", "/", "4", "for", "i", "in", "range", "(", "self", ".", "num_motors", ")", ":", "action_idx", "=", "i", "//", "2", "forward_backward_component", "=", "(", "-", "scale_for_singularity", "*", "quater_pi", "*", "(", "actions", "[", "action_idx", "+", "half_num_motors", "]", "+", "offset_for_singularity", ")", ")", "extension_component", "=", "(", "-", "1", ")", "**", "i", "*", "quater_pi", "*", "actions", "[", "action_idx", "]", "if", "i", ">=", "half_num_motors", ":", "extension_component", "=", "-", "extension_component", "motor_angle", "[", "i", "]", "=", "(", "math", ".", "pi", "+", "forward_backward_component", "+", "extension_component", ")", "return", "motor_angle" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/bullet/minitaur.py#L431-L454
NeoGeographyToolkit/StereoPipeline
eedf54a919fb5cce1ab0e280bb0df4050763aa11
src/asp/IceBridge/full_processing_script.py
python
solveIntrinsics_Part1
(options, jpegFolder, cameraFolder, navCameraFolder, processedFolder, logger)
return (options, cameraFolder, navCameraFolder, processedFolder)
Some preliminary work before solving for intrinsics. Here we look up the default calibration file, and generate an RPC approximation of its distortion model with polynomials of degree 4. We will then create cameras and stereo DEMs using this initial camera file with RPC distortion.
Some preliminary work before solving for intrinsics. Here we look up the default calibration file, and generate an RPC approximation of its distortion model with polynomials of degree 4. We will then create cameras and stereo DEMs using this initial camera file with RPC distortion.
[ "Some", "preliminary", "work", "before", "solving", "for", "intrinsics", ".", "Here", "we", "look", "up", "the", "default", "calibration", "file", "and", "generate", "an", "RPC", "approximation", "of", "its", "distortion", "model", "with", "polynomials", "of", "degree", "4", ".", "We", "will", "then", "create", "cameras", "and", "stereo", "DEMs", "using", "this", "initial", "camera", "file", "with", "RPC", "distortion", "." ]
def solveIntrinsics_Part1(options, jpegFolder, cameraFolder, navCameraFolder, processedFolder, logger): '''Some preliminary work before solving for intrinsics. Here we look up the default calibration file, and generate an RPC approximation of its distortion model with polynomials of degree 4. We will then create cameras and stereo DEMs using this initial camera file with RPC distortion.''' # Sanity checks if options.startFrame == icebridge_common.getSmallestFrame() or \ options.stopFrame == icebridge_common.getLargestFrame(): raise Exception("When solving for intrinsics, must specify a frame range.") if options.bundleLength != 2: raise Exception("When solving for intrinsics, we assume bundle length of 2.") if (options.stopFrame - options.startFrame) % 2 == 0: raise Exception("When solving for intrinsics, must have an even number of frames, " + " so stopFrame - startFrame must be odd.") if options.processingSubfolder: raise Exception("Processing subfolder not supported when solving for intrinsics.") # Generate extra data we will use later to float intrinsics options.stereoArgs += " --num-matches-from-disp-triplets 10000 --unalign-disparity " # --enable-fill-holes " # Create separate directories for cameras and processed data, # as these will be distinct than what we will finally be # using to do the full run. suff = "_camgen" cameraFolder += suff navCameraFolder += suff processedFolder += suff # Get the input calibration file defaultCalibFile = "" for frame in range(options.startFrame, options.stopFrame+1): currCalibFile = input_conversions.getCalibrationFileForFrame(options.cameraLookupFile, options.inputCalFolder, frame, options.yyyymmdd, options.site, logger) if defaultCalibFile == "": defaultCalibFile = currCalibFile if defaultCalibFile != currCalibFile: # This is important, the calibration file must be unique raise Exception("Found two distinct calibration files: " + defaultCalibFile + \ " and " + currCalibFile) logger.info("Default calibration file: " + defaultCalibFile) if options.inputCalCamera != "": defaultCalibFile = options.inputCalCamera logger.info("Using instead the user-provided: " + defaultCalibFile) # Find the first image in the range jpegIndex = icebridge_common.csvIndexFile(jpegFolder) (jpegFrameDict, jpegUrlDict) = icebridge_common.readIndexFile(jpegIndex, prependFolder = True) if options.startFrame not in jpegFrameDict.keys(): raise Exception("Could not find jpeg image for frame: " + options.startFrame) firstImage = jpegFrameDict[options.startFrame] # Create the RPC file before optimization rpcCalibFile = os.path.join(processedFolder, os.path.basename(defaultCalibFile)) rpcCalibFile = rpcCalibFile.replace(".tsai", "_INIT_RPC.tsai") logger.info("Will approximate camera model " + defaultCalibFile + " with " + \ options.outputModelType + " model " + rpcCalibFile) if not os.path.exists(defaultCalibFile): raise Exception('Cannot find file: ' + defaultCalibFile) os.system("mkdir -p " + os.path.dirname(rpcCalibFile)) cmd = "convert_pinhole_model --input-file " + firstImage + ' --camera-file ' + \ defaultCalibFile + ' --output-type ' + options.outputModelType + \ ' --sample-spacing 50 -o ' + rpcCalibFile logger.info(cmd) os.system(cmd) # Use this one from now on options.inputCalCamera = rpcCalibFile # Return the modified values return (options, cameraFolder, navCameraFolder, processedFolder)
[ "def", "solveIntrinsics_Part1", "(", "options", ",", "jpegFolder", ",", "cameraFolder", ",", "navCameraFolder", ",", "processedFolder", ",", "logger", ")", ":", "# Sanity checks", "if", "options", ".", "startFrame", "==", "icebridge_common", ".", "getSmallestFrame", "(", ")", "or", "options", ".", "stopFrame", "==", "icebridge_common", ".", "getLargestFrame", "(", ")", ":", "raise", "Exception", "(", "\"When solving for intrinsics, must specify a frame range.\"", ")", "if", "options", ".", "bundleLength", "!=", "2", ":", "raise", "Exception", "(", "\"When solving for intrinsics, we assume bundle length of 2.\"", ")", "if", "(", "options", ".", "stopFrame", "-", "options", ".", "startFrame", ")", "%", "2", "==", "0", ":", "raise", "Exception", "(", "\"When solving for intrinsics, must have an even number of frames, \"", "+", "\" so stopFrame - startFrame must be odd.\"", ")", "if", "options", ".", "processingSubfolder", ":", "raise", "Exception", "(", "\"Processing subfolder not supported when solving for intrinsics.\"", ")", "# Generate extra data we will use later to float intrinsics", "options", ".", "stereoArgs", "+=", "\" --num-matches-from-disp-triplets 10000 --unalign-disparity \"", "# --enable-fill-holes \"", "# Create separate directories for cameras and processed data,", "# as these will be distinct than what we will finally be", "# using to do the full run.", "suff", "=", "\"_camgen\"", "cameraFolder", "+=", "suff", "navCameraFolder", "+=", "suff", "processedFolder", "+=", "suff", "# Get the input calibration file", "defaultCalibFile", "=", "\"\"", "for", "frame", "in", "range", "(", "options", ".", "startFrame", ",", "options", ".", "stopFrame", "+", "1", ")", ":", "currCalibFile", "=", "input_conversions", ".", "getCalibrationFileForFrame", "(", "options", ".", "cameraLookupFile", ",", "options", ".", "inputCalFolder", ",", "frame", ",", "options", ".", "yyyymmdd", ",", "options", ".", "site", ",", "logger", ")", "if", "defaultCalibFile", "==", "\"\"", ":", "defaultCalibFile", "=", "currCalibFile", "if", "defaultCalibFile", "!=", "currCalibFile", ":", "# This is important, the calibration file must be unique", "raise", "Exception", "(", "\"Found two distinct calibration files: \"", "+", "defaultCalibFile", "+", "\" and \"", "+", "currCalibFile", ")", "logger", ".", "info", "(", "\"Default calibration file: \"", "+", "defaultCalibFile", ")", "if", "options", ".", "inputCalCamera", "!=", "\"\"", ":", "defaultCalibFile", "=", "options", ".", "inputCalCamera", "logger", ".", "info", "(", "\"Using instead the user-provided: \"", "+", "defaultCalibFile", ")", "# Find the first image in the range", "jpegIndex", "=", "icebridge_common", ".", "csvIndexFile", "(", "jpegFolder", ")", "(", "jpegFrameDict", ",", "jpegUrlDict", ")", "=", "icebridge_common", ".", "readIndexFile", "(", "jpegIndex", ",", "prependFolder", "=", "True", ")", "if", "options", ".", "startFrame", "not", "in", "jpegFrameDict", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "\"Could not find jpeg image for frame: \"", "+", "options", ".", "startFrame", ")", "firstImage", "=", "jpegFrameDict", "[", "options", ".", "startFrame", "]", "# Create the RPC file before optimization", "rpcCalibFile", "=", "os", ".", "path", ".", "join", "(", "processedFolder", ",", "os", ".", "path", ".", "basename", "(", "defaultCalibFile", ")", ")", "rpcCalibFile", "=", "rpcCalibFile", ".", "replace", "(", "\".tsai\"", ",", "\"_INIT_RPC.tsai\"", ")", "logger", ".", "info", "(", "\"Will approximate camera model \"", "+", "defaultCalibFile", "+", "\" with \"", "+", "options", ".", "outputModelType", "+", "\" model \"", "+", "rpcCalibFile", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "defaultCalibFile", ")", ":", "raise", "Exception", "(", "'Cannot find file: '", "+", "defaultCalibFile", ")", "os", ".", "system", "(", "\"mkdir -p \"", "+", "os", ".", "path", ".", "dirname", "(", "rpcCalibFile", ")", ")", "cmd", "=", "\"convert_pinhole_model --input-file \"", "+", "firstImage", "+", "' --camera-file '", "+", "defaultCalibFile", "+", "' --output-type '", "+", "options", ".", "outputModelType", "+", "' --sample-spacing 50 -o '", "+", "rpcCalibFile", "logger", ".", "info", "(", "cmd", ")", "os", ".", "system", "(", "cmd", ")", "# Use this one from now on", "options", ".", "inputCalCamera", "=", "rpcCalibFile", "# Return the modified values", "return", "(", "options", ",", "cameraFolder", ",", "navCameraFolder", ",", "processedFolder", ")" ]
https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/full_processing_script.py#L376-L454
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
DateTime.IsLeapYear
(*args, **kwargs)
return _misc_.DateTime_IsLeapYear(*args, **kwargs)
IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool
IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool
[ "IsLeapYear", "(", "int", "year", "=", "Inv_Year", "int", "cal", "=", "Gregorian", ")", "-", ">", "bool" ]
def IsLeapYear(*args, **kwargs): """IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool""" return _misc_.DateTime_IsLeapYear(*args, **kwargs)
[ "def", "IsLeapYear", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_IsLeapYear", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3702-L3704
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
tools/diagnose.py
python
test_connection
(name, url, timeout=10)
Simple connection test
Simple connection test
[ "Simple", "connection", "test" ]
def test_connection(name, url, timeout=10): """Simple connection test""" urlinfo = urlparse(url) start = time.time() try: ip = socket.gethostbyname(urlinfo.netloc) except Exception as e: print('Error resolving DNS for {}: {}, {}'.format(name, url, e)) return dns_elapsed = time.time() - start start = time.time() try: _ = urlopen(url, timeout=timeout) except Exception as e: print("Error open {}: {}, {}, DNS finished in {} sec.".format(name, url, e, dns_elapsed)) return load_elapsed = time.time() - start print("Timing for {}: {}, DNS: {:.4f} sec, LOAD: {:.4f} sec.".format(name, url, dns_elapsed, load_elapsed))
[ "def", "test_connection", "(", "name", ",", "url", ",", "timeout", "=", "10", ")", ":", "urlinfo", "=", "urlparse", "(", "url", ")", "start", "=", "time", ".", "time", "(", ")", "try", ":", "ip", "=", "socket", ".", "gethostbyname", "(", "urlinfo", ".", "netloc", ")", "except", "Exception", "as", "e", ":", "print", "(", "'Error resolving DNS for {}: {}, {}'", ".", "format", "(", "name", ",", "url", ",", "e", ")", ")", "return", "dns_elapsed", "=", "time", ".", "time", "(", ")", "-", "start", "start", "=", "time", ".", "time", "(", ")", "try", ":", "_", "=", "urlopen", "(", "url", ",", "timeout", "=", "timeout", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"Error open {}: {}, {}, DNS finished in {} sec.\"", ".", "format", "(", "name", ",", "url", ",", "e", ",", "dns_elapsed", ")", ")", "return", "load_elapsed", "=", "time", ".", "time", "(", ")", "-", "start", "print", "(", "\"Timing for {}: {}, DNS: {:.4f} sec, LOAD: {:.4f} sec.\"", ".", "format", "(", "name", ",", "url", ",", "dns_elapsed", ",", "load_elapsed", ")", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/diagnose.py#L65-L82
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/proximal_adagrad.py
python
ProximalAdagradOptimizer.__init__
(self, learning_rate, initial_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name="ProximalAdagrad")
Construct a new ProximalAdagrad optimizer. Args: learning_rate: A `Tensor` or a floating point value. The learning rate. initial_accumulator_value: A floating point value. Starting value for the accumulators, must be positive. l1_regularization_strength: A float value, must be greater than or equal to zero. l2_regularization_strength: A float value, must be greater than or equal to zero. use_locking: If `True` use locks for update operations. name: Optional name prefix for the operations created when applying gradients. Defaults to "Adagrad". Raises: ValueError: If the `initial_accumulator_value` is invalid.
Construct a new ProximalAdagrad optimizer.
[ "Construct", "a", "new", "ProximalAdagrad", "optimizer", "." ]
def __init__(self, learning_rate, initial_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name="ProximalAdagrad"): """Construct a new ProximalAdagrad optimizer. Args: learning_rate: A `Tensor` or a floating point value. The learning rate. initial_accumulator_value: A floating point value. Starting value for the accumulators, must be positive. l1_regularization_strength: A float value, must be greater than or equal to zero. l2_regularization_strength: A float value, must be greater than or equal to zero. use_locking: If `True` use locks for update operations. name: Optional name prefix for the operations created when applying gradients. Defaults to "Adagrad". Raises: ValueError: If the `initial_accumulator_value` is invalid. """ if initial_accumulator_value <= 0.0: raise ValueError("initial_accumulator_value must be positive: %s" % initial_accumulator_value) super(ProximalAdagradOptimizer, self).__init__(use_locking, name) self._learning_rate = learning_rate self._initial_accumulator_value = initial_accumulator_value self._l1_regularization_strength = l1_regularization_strength self._l2_regularization_strength = l2_regularization_strength # Created in Initialize. self._l1_regularization_strength_tensor = None self._l2_regularization_strength_tensor = None self._learning_rate_tensor = None
[ "def", "__init__", "(", "self", ",", "learning_rate", ",", "initial_accumulator_value", "=", "0.1", ",", "l1_regularization_strength", "=", "0.0", ",", "l2_regularization_strength", "=", "0.0", ",", "use_locking", "=", "False", ",", "name", "=", "\"ProximalAdagrad\"", ")", ":", "if", "initial_accumulator_value", "<=", "0.0", ":", "raise", "ValueError", "(", "\"initial_accumulator_value must be positive: %s\"", "%", "initial_accumulator_value", ")", "super", "(", "ProximalAdagradOptimizer", ",", "self", ")", ".", "__init__", "(", "use_locking", ",", "name", ")", "self", ".", "_learning_rate", "=", "learning_rate", "self", ".", "_initial_accumulator_value", "=", "initial_accumulator_value", "self", ".", "_l1_regularization_strength", "=", "l1_regularization_strength", "self", ".", "_l2_regularization_strength", "=", "l2_regularization_strength", "# Created in Initialize.", "self", ".", "_l1_regularization_strength_tensor", "=", "None", "self", ".", "_l2_regularization_strength_tensor", "=", "None", "self", ".", "_learning_rate_tensor", "=", "None" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/proximal_adagrad.py#L36-L67
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythplugins/mytharchive/mythburn/scripts/mythburn.py
python
fatalError
(msg)
Display an error message and exit app
Display an error message and exit app
[ "Display", "an", "error", "message", "and", "exit", "app" ]
def fatalError(msg): """Display an error message and exit app""" write("*"*60) write("ERROR: " + msg) write("See mythburn.log for more information.") write("*"*60) write("") saveSetting("MythArchiveLastRunResult", "Failed: " + quoteString(msg)); saveSetting("MythArchiveLastRunEnd", time.strftime("%Y-%m-%d %H:%M:%S ")) sys.exit(0)
[ "def", "fatalError", "(", "msg", ")", ":", "write", "(", "\"*\"", "*", "60", ")", "write", "(", "\"ERROR: \"", "+", "msg", ")", "write", "(", "\"See mythburn.log for more information.\"", ")", "write", "(", "\"*\"", "*", "60", ")", "write", "(", "\"\"", ")", "saveSetting", "(", "\"MythArchiveLastRunResult\"", ",", "\"Failed: \"", "+", "quoteString", "(", "msg", ")", ")", "saveSetting", "(", "\"MythArchiveLastRunEnd\"", ",", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S \"", ")", ")", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythplugins/mytharchive/mythburn/scripts/mythburn.py#L324-L333
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Fem/ObjectsFem.py
python
makeMeshBoundaryLayer
( doc, base_mesh, name="MeshBoundaryLayer" )
return obj
makeMeshBoundaryLayer(document, base_mesh, [name]): creates a FEM mesh BoundaryLayer object to define boundary layer properties
makeMeshBoundaryLayer(document, base_mesh, [name]): creates a FEM mesh BoundaryLayer object to define boundary layer properties
[ "makeMeshBoundaryLayer", "(", "document", "base_mesh", "[", "name", "]", ")", ":", "creates", "a", "FEM", "mesh", "BoundaryLayer", "object", "to", "define", "boundary", "layer", "properties" ]
def makeMeshBoundaryLayer( doc, base_mesh, name="MeshBoundaryLayer" ): """makeMeshBoundaryLayer(document, base_mesh, [name]): creates a FEM mesh BoundaryLayer object to define boundary layer properties""" obj = doc.addObject("Fem::FeaturePython", name) from femobjects import mesh_boundarylayer mesh_boundarylayer.MeshBoundaryLayer(obj) # obj.BaseMesh = base_mesh # App::PropertyLinkList does not support append # we will use a temporary list to append the mesh BoundaryLayer obj. to the list tmplist = base_mesh.MeshBoundaryLayerList tmplist.append(obj) base_mesh.MeshBoundaryLayerList = tmplist if FreeCAD.GuiUp: from femviewprovider import view_mesh_boundarylayer view_mesh_boundarylayer.VPMeshBoundaryLayer(obj.ViewObject) return obj
[ "def", "makeMeshBoundaryLayer", "(", "doc", ",", "base_mesh", ",", "name", "=", "\"MeshBoundaryLayer\"", ")", ":", "obj", "=", "doc", ".", "addObject", "(", "\"Fem::FeaturePython\"", ",", "name", ")", "from", "femobjects", "import", "mesh_boundarylayer", "mesh_boundarylayer", ".", "MeshBoundaryLayer", "(", "obj", ")", "# obj.BaseMesh = base_mesh", "# App::PropertyLinkList does not support append", "# we will use a temporary list to append the mesh BoundaryLayer obj. to the list", "tmplist", "=", "base_mesh", ".", "MeshBoundaryLayerList", "tmplist", ".", "append", "(", "obj", ")", "base_mesh", ".", "MeshBoundaryLayerList", "=", "tmplist", "if", "FreeCAD", ".", "GuiUp", ":", "from", "femviewprovider", "import", "view_mesh_boundarylayer", "view_mesh_boundarylayer", ".", "VPMeshBoundaryLayer", "(", "obj", ".", "ViewObject", ")", "return", "obj" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/ObjectsFem.py#L493-L512
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib2to3/fixer_util.py
python
Name
(name, prefix=None)
return Leaf(token.NAME, name, prefix=prefix)
Return a NAME leaf
Return a NAME leaf
[ "Return", "a", "NAME", "leaf" ]
def Name(name, prefix=None): """Return a NAME leaf""" return Leaf(token.NAME, name, prefix=prefix)
[ "def", "Name", "(", "name", ",", "prefix", "=", "None", ")", ":", "return", "Leaf", "(", "token", ".", "NAME", ",", "name", ",", "prefix", "=", "prefix", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/fixer_util.py#L38-L40
isl-org/Open3D
79aec3ddde6a571ce2f28e4096477e52ec465244
python/open3d/visualization/tensorboard_plugin/util.py
python
RenderUpdate.apply
(self, o3dvis, geometry_name, geometry, inference_data_proto=None)
Apply the RenderUpdate to a geometry. Args: o3dvis (O3DVisualizer): Window containing the geometry. geometry_name (str): Geometry name in the window. geometry (o3d.t.geometry): Geometry whose rendering is to be updated. inference_data_proto : BoundingBox labels and confidences.
Apply the RenderUpdate to a geometry.
[ "Apply", "the", "RenderUpdate", "to", "a", "geometry", "." ]
def apply(self, o3dvis, geometry_name, geometry, inference_data_proto=None): """Apply the RenderUpdate to a geometry. Args: o3dvis (O3DVisualizer): Window containing the geometry. geometry_name (str): Geometry name in the window. geometry (o3d.t.geometry): Geometry whose rendering is to be updated. inference_data_proto : BoundingBox labels and confidences. """ if (len(self._updated) == 0 or geometry.is_empty()): _log.debug("No updates, or empty geometry.") return def get_labelLUT(): """Create {label: color} mapping from list of colors.""" return { label: self.LABELLUT_COLORS[k] for k, label in enumerate(self._label_to_names) } geometry_vertex = (geometry.point if hasattr(geometry, 'point') else geometry.vertex) have_colors = ("colors" in geometry.line if hasattr( geometry, 'line') else ("colors" in geometry.triangle if hasattr( geometry, 'triangle') else "colors" in geometry_vertex)) if inference_data_proto is not None: inference_result = inference_data_proto.inference_result else: inference_result = [] label_props, custom_props = _classify_properties(geometry_vertex) self._set_render_defaults(geometry, inference_result, label_props, custom_props) if o3dvis.scene.has_geometry(geometry_name): updated = self._updated # update_geometry() only accepts tPointCloud if not isinstance(geometry, o3d.t.geometry.PointCloud): o3dvis.remove_geometry(geometry_name) else: updated = deepcopy(self.ALL_UPDATED) geometry_update_flag = 0 material_update_flag = 0 swap = RenderUpdate.BackupRestore() material = o3dvis.get_geometry_material(geometry_name) # Visualize scalar / 3-vector property with color map if "property" in updated or "shader" in updated: # Float Scalar with colormap if ((self._property in custom_props or self._property in label_props) and self._shader.startswith("unlitGradient") and geometry_vertex[self._property].shape[1] > self._index): geometry_vertex["__visualization_scalar"] = geometry_vertex[ self._property][:, self._index].to( o3d.core.float32).contiguous() geometry_update_flag |= rendering.Scene.UPDATE_UV0_FLAG # 3-vector as RGB elif (self._property in custom_props and self._shader == "defaultUnlit" and geometry_vertex[self._property].shape[1] >= 3): swap.backup(geometry_vertex, "colors") geometry_vertex["colors"], min_val, max_val = _normalize( geometry_vertex[self._property][:, :3]) self._update_range(min_val, max_val) geometry_update_flag |= rendering.Scene.UPDATE_COLORS_FLAG # Bounding boxes / LineSet if isinstance(geometry, o3d.t.geometry.LineSet): if self._property == "" and self._shader == "unlitSolidColor": swap.backup(geometry.line, "colors", shape=(len(geometry.line["indices"]), 3), dtype=o3d.core.uint8) geometry.line["colors"][:] = next(iter( self._colormap.values()))[:3] elif self._property != "" and self._shader == "unlitGradient.LUT": if self._colormap is None: self._colormap = get_labelLUT() if "colormap" in updated: swap.backup(geometry.line, "indices", clone=True) swap.backup(geometry.line, "colors", shape=(len(geometry.line["indices"]), 3), dtype=o3d.core.uint8) t_lines = geometry.line["indices"] t_colors = geometry.line["colors"] idx = 0 for bbir in inference_result: col = self._colormap.setdefault(bbir.label, (128, 128, 128, 255)) t_colors[idx:idx + self._LINES_PER_BBOX] = col[:3] if col[3] == 0: # alpha t_lines[idx:idx + self._LINES_PER_BBOX] = 0 idx += self._LINES_PER_BBOX # PointCloud, Mesh, LineSet with colors elif (("shader" in updated or "colormap" in updated) and not geometry.has_valid_material()): material_update_flag = 1 material.base_color = ((1.0, 1.0, 1.0, 1.0) if have_colors else (0.5, 0.5, 0.5, 1.0)) if self._shader == "defaultLit": material.shader = "defaultLit" elif self._shader == "defaultUnlit": material.shader = "defaultUnlit" elif self._shader == "unlitSolidColor": material.shader = "unlitSolidColor" if self._colormap is None: self._colormap = {0.0: [128, 128, 128, 255]} material.base_color = _u8_to_float( next(iter(self._colormap.values()))) elif self._shader == "unlitGradient.LUT": # Label Colormap if self._colormap is None: self._colormap = get_labelLUT() material.shader = "unlitGradient" material.gradient = rendering.Gradient() material.gradient.mode = rendering.Gradient.LUT lmin = min(self._label_to_names.keys()) lmax = max(self._label_to_names.keys()) material.scalar_min, material.scalar_max = lmin, lmax if len(self._colormap) > 1: norm_cmap = list((float(label - lmin) / (lmax - lmin), _u8_to_float(color)) for label, color in self._colormap.items()) material.gradient.points = list( rendering.Gradient.Point(*lc) for lc in norm_cmap) else: material.gradient.points = [ rendering.Gradient.Point(0.0, [1.0, 0.0, 1.0, 1.0]) ] # Colormap (RAINBOW / GREYSCALE): continuous data elif self._shader.startswith("unlitGradient.GRADIENT."): if self._colormap is None: self._colormap = deepcopy( self.DICT_COLORMAPS[self._shader[23:]]) material.shader = "unlitGradient" material.gradient = rendering.Gradient() material.gradient.points = list( rendering.Gradient.Point(value, _u8_to_float(color[:3]) + (1.,)) for value, color in self._colormap.items()) material.gradient.mode = rendering.Gradient.GRADIENT self._set_vis_minmax(geometry_vertex, material) if o3dvis.scene.has_geometry(geometry_name): if material_update_flag > 0: self._gui.run_sync( o3dvis.modify_geometry_material, geometry_name, material ) # does not do force_redraw(), so also need update_geometry() self._gui.run_sync(o3dvis.update_geometry, geometry_name, geometry, geometry_update_flag) _log.debug( f"Geometry {geometry_name} updated with flags " f"Geo:{geometry_update_flag:b}, Mat:{material_update_flag:b}") else: self._gui.run_sync(o3dvis.add_geometry, geometry_name, geometry, material if material_update_flag else None) self._gui.run_sync(o3dvis.post_redraw) swap.restore() _log.debug(f"apply complete: {geometry_name} with " f"{self._property}[{self._index}]/{self._shader}")
[ "def", "apply", "(", "self", ",", "o3dvis", ",", "geometry_name", ",", "geometry", ",", "inference_data_proto", "=", "None", ")", ":", "if", "(", "len", "(", "self", ".", "_updated", ")", "==", "0", "or", "geometry", ".", "is_empty", "(", ")", ")", ":", "_log", ".", "debug", "(", "\"No updates, or empty geometry.\"", ")", "return", "def", "get_labelLUT", "(", ")", ":", "\"\"\"Create {label: color} mapping from list of colors.\"\"\"", "return", "{", "label", ":", "self", ".", "LABELLUT_COLORS", "[", "k", "]", "for", "k", ",", "label", "in", "enumerate", "(", "self", ".", "_label_to_names", ")", "}", "geometry_vertex", "=", "(", "geometry", ".", "point", "if", "hasattr", "(", "geometry", ",", "'point'", ")", "else", "geometry", ".", "vertex", ")", "have_colors", "=", "(", "\"colors\"", "in", "geometry", ".", "line", "if", "hasattr", "(", "geometry", ",", "'line'", ")", "else", "(", "\"colors\"", "in", "geometry", ".", "triangle", "if", "hasattr", "(", "geometry", ",", "'triangle'", ")", "else", "\"colors\"", "in", "geometry_vertex", ")", ")", "if", "inference_data_proto", "is", "not", "None", ":", "inference_result", "=", "inference_data_proto", ".", "inference_result", "else", ":", "inference_result", "=", "[", "]", "label_props", ",", "custom_props", "=", "_classify_properties", "(", "geometry_vertex", ")", "self", ".", "_set_render_defaults", "(", "geometry", ",", "inference_result", ",", "label_props", ",", "custom_props", ")", "if", "o3dvis", ".", "scene", ".", "has_geometry", "(", "geometry_name", ")", ":", "updated", "=", "self", ".", "_updated", "# update_geometry() only accepts tPointCloud", "if", "not", "isinstance", "(", "geometry", ",", "o3d", ".", "t", ".", "geometry", ".", "PointCloud", ")", ":", "o3dvis", ".", "remove_geometry", "(", "geometry_name", ")", "else", ":", "updated", "=", "deepcopy", "(", "self", ".", "ALL_UPDATED", ")", "geometry_update_flag", "=", "0", "material_update_flag", "=", "0", "swap", "=", "RenderUpdate", ".", "BackupRestore", "(", ")", "material", "=", "o3dvis", ".", "get_geometry_material", "(", "geometry_name", ")", "# Visualize scalar / 3-vector property with color map", "if", "\"property\"", "in", "updated", "or", "\"shader\"", "in", "updated", ":", "# Float Scalar with colormap", "if", "(", "(", "self", ".", "_property", "in", "custom_props", "or", "self", ".", "_property", "in", "label_props", ")", "and", "self", ".", "_shader", ".", "startswith", "(", "\"unlitGradient\"", ")", "and", "geometry_vertex", "[", "self", ".", "_property", "]", ".", "shape", "[", "1", "]", ">", "self", ".", "_index", ")", ":", "geometry_vertex", "[", "\"__visualization_scalar\"", "]", "=", "geometry_vertex", "[", "self", ".", "_property", "]", "[", ":", ",", "self", ".", "_index", "]", ".", "to", "(", "o3d", ".", "core", ".", "float32", ")", ".", "contiguous", "(", ")", "geometry_update_flag", "|=", "rendering", ".", "Scene", ".", "UPDATE_UV0_FLAG", "# 3-vector as RGB", "elif", "(", "self", ".", "_property", "in", "custom_props", "and", "self", ".", "_shader", "==", "\"defaultUnlit\"", "and", "geometry_vertex", "[", "self", ".", "_property", "]", ".", "shape", "[", "1", "]", ">=", "3", ")", ":", "swap", ".", "backup", "(", "geometry_vertex", ",", "\"colors\"", ")", "geometry_vertex", "[", "\"colors\"", "]", ",", "min_val", ",", "max_val", "=", "_normalize", "(", "geometry_vertex", "[", "self", ".", "_property", "]", "[", ":", ",", ":", "3", "]", ")", "self", ".", "_update_range", "(", "min_val", ",", "max_val", ")", "geometry_update_flag", "|=", "rendering", ".", "Scene", ".", "UPDATE_COLORS_FLAG", "# Bounding boxes / LineSet", "if", "isinstance", "(", "geometry", ",", "o3d", ".", "t", ".", "geometry", ".", "LineSet", ")", ":", "if", "self", ".", "_property", "==", "\"\"", "and", "self", ".", "_shader", "==", "\"unlitSolidColor\"", ":", "swap", ".", "backup", "(", "geometry", ".", "line", ",", "\"colors\"", ",", "shape", "=", "(", "len", "(", "geometry", ".", "line", "[", "\"indices\"", "]", ")", ",", "3", ")", ",", "dtype", "=", "o3d", ".", "core", ".", "uint8", ")", "geometry", ".", "line", "[", "\"colors\"", "]", "[", ":", "]", "=", "next", "(", "iter", "(", "self", ".", "_colormap", ".", "values", "(", ")", ")", ")", "[", ":", "3", "]", "elif", "self", ".", "_property", "!=", "\"\"", "and", "self", ".", "_shader", "==", "\"unlitGradient.LUT\"", ":", "if", "self", ".", "_colormap", "is", "None", ":", "self", ".", "_colormap", "=", "get_labelLUT", "(", ")", "if", "\"colormap\"", "in", "updated", ":", "swap", ".", "backup", "(", "geometry", ".", "line", ",", "\"indices\"", ",", "clone", "=", "True", ")", "swap", ".", "backup", "(", "geometry", ".", "line", ",", "\"colors\"", ",", "shape", "=", "(", "len", "(", "geometry", ".", "line", "[", "\"indices\"", "]", ")", ",", "3", ")", ",", "dtype", "=", "o3d", ".", "core", ".", "uint8", ")", "t_lines", "=", "geometry", ".", "line", "[", "\"indices\"", "]", "t_colors", "=", "geometry", ".", "line", "[", "\"colors\"", "]", "idx", "=", "0", "for", "bbir", "in", "inference_result", ":", "col", "=", "self", ".", "_colormap", ".", "setdefault", "(", "bbir", ".", "label", ",", "(", "128", ",", "128", ",", "128", ",", "255", ")", ")", "t_colors", "[", "idx", ":", "idx", "+", "self", ".", "_LINES_PER_BBOX", "]", "=", "col", "[", ":", "3", "]", "if", "col", "[", "3", "]", "==", "0", ":", "# alpha", "t_lines", "[", "idx", ":", "idx", "+", "self", ".", "_LINES_PER_BBOX", "]", "=", "0", "idx", "+=", "self", ".", "_LINES_PER_BBOX", "# PointCloud, Mesh, LineSet with colors", "elif", "(", "(", "\"shader\"", "in", "updated", "or", "\"colormap\"", "in", "updated", ")", "and", "not", "geometry", ".", "has_valid_material", "(", ")", ")", ":", "material_update_flag", "=", "1", "material", ".", "base_color", "=", "(", "(", "1.0", ",", "1.0", ",", "1.0", ",", "1.0", ")", "if", "have_colors", "else", "(", "0.5", ",", "0.5", ",", "0.5", ",", "1.0", ")", ")", "if", "self", ".", "_shader", "==", "\"defaultLit\"", ":", "material", ".", "shader", "=", "\"defaultLit\"", "elif", "self", ".", "_shader", "==", "\"defaultUnlit\"", ":", "material", ".", "shader", "=", "\"defaultUnlit\"", "elif", "self", ".", "_shader", "==", "\"unlitSolidColor\"", ":", "material", ".", "shader", "=", "\"unlitSolidColor\"", "if", "self", ".", "_colormap", "is", "None", ":", "self", ".", "_colormap", "=", "{", "0.0", ":", "[", "128", ",", "128", ",", "128", ",", "255", "]", "}", "material", ".", "base_color", "=", "_u8_to_float", "(", "next", "(", "iter", "(", "self", ".", "_colormap", ".", "values", "(", ")", ")", ")", ")", "elif", "self", ".", "_shader", "==", "\"unlitGradient.LUT\"", ":", "# Label Colormap", "if", "self", ".", "_colormap", "is", "None", ":", "self", ".", "_colormap", "=", "get_labelLUT", "(", ")", "material", ".", "shader", "=", "\"unlitGradient\"", "material", ".", "gradient", "=", "rendering", ".", "Gradient", "(", ")", "material", ".", "gradient", ".", "mode", "=", "rendering", ".", "Gradient", ".", "LUT", "lmin", "=", "min", "(", "self", ".", "_label_to_names", ".", "keys", "(", ")", ")", "lmax", "=", "max", "(", "self", ".", "_label_to_names", ".", "keys", "(", ")", ")", "material", ".", "scalar_min", ",", "material", ".", "scalar_max", "=", "lmin", ",", "lmax", "if", "len", "(", "self", ".", "_colormap", ")", ">", "1", ":", "norm_cmap", "=", "list", "(", "(", "float", "(", "label", "-", "lmin", ")", "/", "(", "lmax", "-", "lmin", ")", ",", "_u8_to_float", "(", "color", ")", ")", "for", "label", ",", "color", "in", "self", ".", "_colormap", ".", "items", "(", ")", ")", "material", ".", "gradient", ".", "points", "=", "list", "(", "rendering", ".", "Gradient", ".", "Point", "(", "*", "lc", ")", "for", "lc", "in", "norm_cmap", ")", "else", ":", "material", ".", "gradient", ".", "points", "=", "[", "rendering", ".", "Gradient", ".", "Point", "(", "0.0", ",", "[", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", "]", ")", "]", "# Colormap (RAINBOW / GREYSCALE): continuous data", "elif", "self", ".", "_shader", ".", "startswith", "(", "\"unlitGradient.GRADIENT.\"", ")", ":", "if", "self", ".", "_colormap", "is", "None", ":", "self", ".", "_colormap", "=", "deepcopy", "(", "self", ".", "DICT_COLORMAPS", "[", "self", ".", "_shader", "[", "23", ":", "]", "]", ")", "material", ".", "shader", "=", "\"unlitGradient\"", "material", ".", "gradient", "=", "rendering", ".", "Gradient", "(", ")", "material", ".", "gradient", ".", "points", "=", "list", "(", "rendering", ".", "Gradient", ".", "Point", "(", "value", ",", "_u8_to_float", "(", "color", "[", ":", "3", "]", ")", "+", "(", "1.", ",", ")", ")", "for", "value", ",", "color", "in", "self", ".", "_colormap", ".", "items", "(", ")", ")", "material", ".", "gradient", ".", "mode", "=", "rendering", ".", "Gradient", ".", "GRADIENT", "self", ".", "_set_vis_minmax", "(", "geometry_vertex", ",", "material", ")", "if", "o3dvis", ".", "scene", ".", "has_geometry", "(", "geometry_name", ")", ":", "if", "material_update_flag", ">", "0", ":", "self", ".", "_gui", ".", "run_sync", "(", "o3dvis", ".", "modify_geometry_material", ",", "geometry_name", ",", "material", ")", "# does not do force_redraw(), so also need update_geometry()", "self", ".", "_gui", ".", "run_sync", "(", "o3dvis", ".", "update_geometry", ",", "geometry_name", ",", "geometry", ",", "geometry_update_flag", ")", "_log", ".", "debug", "(", "f\"Geometry {geometry_name} updated with flags \"", "f\"Geo:{geometry_update_flag:b}, Mat:{material_update_flag:b}\"", ")", "else", ":", "self", ".", "_gui", ".", "run_sync", "(", "o3dvis", ".", "add_geometry", ",", "geometry_name", ",", "geometry", ",", "material", "if", "material_update_flag", "else", "None", ")", "self", ".", "_gui", ".", "run_sync", "(", "o3dvis", ".", "post_redraw", ")", "swap", ".", "restore", "(", ")", "_log", ".", "debug", "(", "f\"apply complete: {geometry_name} with \"", "f\"{self._property}[{self._index}]/{self._shader}\"", ")" ]
https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/python/open3d/visualization/tensorboard_plugin/util.py#L605-L769
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/image_analysis/image_analysis.py
python
get_deep_features
(images, model_name, batch_size=64, verbose=True)
return feature_extractor.extract_features(images_sf, "image", verbose=verbose, batch_size=batch_size)
Extracts features from images from a specific model. Parameters ---------- images : SArray Input data. model_name : string string optional Uses a pretrained model to bootstrap an image classifier: - "resnet-50" : Uses a pretrained resnet model. Exported Core ML model will be ~90M. - "squeezenet_v1.1" : Uses a pretrained squeezenet model. Exported Core ML model will be ~4.7M. - "VisionFeaturePrint_Scene": Uses an OS internal feature extractor. Only on available on iOS 12.0+, macOS 10.14+ and tvOS 12.0+. Exported Core ML model will be ~41K. Models are downloaded from the internet if not available locally. Once downloaded, the models are cached for future use. Returns ------- out : SArray Returns an SArray with all the extracted features. See Also -------- turicreate.image_classifier.create turicreate.image_similarity.create Examples -------- >>> url = 'https://static.turi.com/datasets/images/nested' >>> image_sframe = turicreate.load_images(url) >>> image_sarray = image_sframe["image"] >>> deep_features_sframe = turicreate.image_analysis.get_deep_features(image_sarray, model_name="resnet-50")
Extracts features from images from a specific model.
[ "Extracts", "features", "from", "images", "from", "a", "specific", "model", "." ]
def get_deep_features(images, model_name, batch_size=64, verbose=True): """ Extracts features from images from a specific model. Parameters ---------- images : SArray Input data. model_name : string string optional Uses a pretrained model to bootstrap an image classifier: - "resnet-50" : Uses a pretrained resnet model. Exported Core ML model will be ~90M. - "squeezenet_v1.1" : Uses a pretrained squeezenet model. Exported Core ML model will be ~4.7M. - "VisionFeaturePrint_Scene": Uses an OS internal feature extractor. Only on available on iOS 12.0+, macOS 10.14+ and tvOS 12.0+. Exported Core ML model will be ~41K. Models are downloaded from the internet if not available locally. Once downloaded, the models are cached for future use. Returns ------- out : SArray Returns an SArray with all the extracted features. See Also -------- turicreate.image_classifier.create turicreate.image_similarity.create Examples -------- >>> url = 'https://static.turi.com/datasets/images/nested' >>> image_sframe = turicreate.load_images(url) >>> image_sarray = image_sframe["image"] >>> deep_features_sframe = turicreate.image_analysis.get_deep_features(image_sarray, model_name="resnet-50") """ # Check model parameter allowed_models = list(_pre_trained_models.IMAGE_MODELS.keys()) if _mac_ver() >= (10, 14): allowed_models.append("VisionFeaturePrint_Scene") _tkutl._check_categorical_option_type("model", model_name, allowed_models) # Check images parameter if not isinstance(images, _tc.SArray): raise TypeError("Unrecognized type for 'images'. An SArray is expected.") if len(images) == 0: raise _ToolkitError("Unable to extract features on an empty SArray object") if batch_size < 1: raise ValueError("'batch_size' must be greater than or equal to 1") # Extract features feature_extractor = _image_feature_extractor._create_feature_extractor(model_name) images_sf = _tc.SFrame({"image":images}) return feature_extractor.extract_features(images_sf, "image", verbose=verbose, batch_size=batch_size)
[ "def", "get_deep_features", "(", "images", ",", "model_name", ",", "batch_size", "=", "64", ",", "verbose", "=", "True", ")", ":", "# Check model parameter", "allowed_models", "=", "list", "(", "_pre_trained_models", ".", "IMAGE_MODELS", ".", "keys", "(", ")", ")", "if", "_mac_ver", "(", ")", ">=", "(", "10", ",", "14", ")", ":", "allowed_models", ".", "append", "(", "\"VisionFeaturePrint_Scene\"", ")", "_tkutl", ".", "_check_categorical_option_type", "(", "\"model\"", ",", "model_name", ",", "allowed_models", ")", "# Check images parameter", "if", "not", "isinstance", "(", "images", ",", "_tc", ".", "SArray", ")", ":", "raise", "TypeError", "(", "\"Unrecognized type for 'images'. An SArray is expected.\"", ")", "if", "len", "(", "images", ")", "==", "0", ":", "raise", "_ToolkitError", "(", "\"Unable to extract features on an empty SArray object\"", ")", "if", "batch_size", "<", "1", ":", "raise", "ValueError", "(", "\"'batch_size' must be greater than or equal to 1\"", ")", "# Extract features", "feature_extractor", "=", "_image_feature_extractor", ".", "_create_feature_extractor", "(", "model_name", ")", "images_sf", "=", "_tc", ".", "SFrame", "(", "{", "\"image\"", ":", "images", "}", ")", "return", "feature_extractor", ".", "extract_features", "(", "images_sf", ",", "\"image\"", ",", "verbose", "=", "verbose", ",", "batch_size", "=", "batch_size", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/image_analysis/image_analysis.py#L196-L260
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
google_apis/google_api_keys.py
python
GetAPIKey
()
return _GetToken('GOOGLE_API_KEY')
Returns the simple API key.
Returns the simple API key.
[ "Returns", "the", "simple", "API", "key", "." ]
def GetAPIKey(): """Returns the simple API key.""" return _GetToken('GOOGLE_API_KEY')
[ "def", "GetAPIKey", "(", ")", ":", "return", "_GetToken", "(", "'GOOGLE_API_KEY'", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/google_apis/google_api_keys.py#L68-L70
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_v2.py
python
run_one_epoch
(model, iterator, execution_function, dataset_size=None, batch_size=None, strategy=None, steps_per_epoch=None, num_samples=None, mode=ModeKeys.TRAIN, training_context=None, total_epochs=None)
return aggregator.results
Run the execution function with the data from iterator. Given the dataset iterator and execution function, get the data from iterator and call it with the execution function to get the result (metric/loss). It will run for steps_per_epoch or until to the iterator is fully consumed. Args: model: The keras model to run. iterator: the dataset iterator to fetch the data. execution_function: a tf.function that can be called with data. dataset_size: the size of iterator, None when unknown. batch_size: The size of the current batch. strategy: the distribution strategy instance from the model. steps_per_epoch: the number of steps to run for the epoch. num_samples: the number of samples for the whole epoch if known. This can be used to calculate the final partial batch, and scale the loss. mode: the mode for the current epoch. training_context: the context that contains callbacks and progress bar. total_epochs: the total number of epochs that will be run. Used when throw error when the iterator unexpectedly reaches its end. Returns: The loss and metric value from the model.
Run the execution function with the data from iterator.
[ "Run", "the", "execution", "function", "with", "the", "data", "from", "iterator", "." ]
def run_one_epoch(model, iterator, execution_function, dataset_size=None, batch_size=None, strategy=None, steps_per_epoch=None, num_samples=None, mode=ModeKeys.TRAIN, training_context=None, total_epochs=None): """Run the execution function with the data from iterator. Given the dataset iterator and execution function, get the data from iterator and call it with the execution function to get the result (metric/loss). It will run for steps_per_epoch or until to the iterator is fully consumed. Args: model: The keras model to run. iterator: the dataset iterator to fetch the data. execution_function: a tf.function that can be called with data. dataset_size: the size of iterator, None when unknown. batch_size: The size of the current batch. strategy: the distribution strategy instance from the model. steps_per_epoch: the number of steps to run for the epoch. num_samples: the number of samples for the whole epoch if known. This can be used to calculate the final partial batch, and scale the loss. mode: the mode for the current epoch. training_context: the context that contains callbacks and progress bar. total_epochs: the total number of epochs that will be run. Used when throw error when the iterator unexpectedly reaches its end. Returns: The loss and metric value from the model. """ # Only use the sample to count if there is a partial batch at the end. use_steps = num_samples is None if mode == ModeKeys.PREDICT: aggregator = training_utils.OutputsAggregator( use_steps=use_steps, steps=steps_per_epoch, num_samples=num_samples, batch_size=batch_size) else: aggregator = training_utils.MetricsAggregator( use_steps=use_steps, steps=steps_per_epoch, num_samples=num_samples) callbacks = training_context.callbacks progbar = training_context.progbar if callbacks.model.stop_training: return target_steps = steps_per_epoch or np.inf step = 0 while step < target_steps: if use_steps: current_batch_size = 1 elif step < target_steps - 1: current_batch_size = batch_size else: current_batch_size = num_samples - step * batch_size with training_context.on_batch( step=step, mode=mode, size=current_batch_size) as batch_logs: try: batch_outs = execution_function(iterator) except (StopIteration, errors.OutOfRangeError): # TODO(kaftan): File bug about tf function and errors.OutOfRangeError? # Are there any other C++ errors tf function should recapture? # The only acceptable case here is that the input has a unknown # length, and configured to fully consume it. if (dataset_size is None and steps_per_epoch is None and step > 0): # The input passed by the user ran out of batches. # Now we know the cardinality of the input(dataset or generator). steps_per_epoch = step aggregator.steps = steps_per_epoch progbar.params['steps'] = steps_per_epoch progbar.progbar.target = steps_per_epoch else: callbacks.model.stop_training = True logging.warning( 'Your input ran out of data; interrupting training. ' 'Make sure that your dataset or generator can generate at ' 'least `steps_per_epoch * epochs` batches (in this case, ' '{} batches). You may need to use the repeat() function ' 'when building your dataset.'.format( total_epochs * steps_per_epoch)) # In either case, break out the loop for training batch. # Also note the training_context that data inputs are exhausted, so all # the post batch hooks can be skipped. batch_logs['data_exhausted'] = True break if mode != ModeKeys.PREDICT: data_batch_size = batch_outs['batch_size'] batch_outs = (batch_outs['total_loss'] + batch_outs['output_losses'] + batch_outs['metrics']) if current_batch_size != data_batch_size: batch_logs['size'] = data_batch_size current_batch_size = data_batch_size else: batch_outs = _aggregate_predict_results(strategy, batch_outs, model) if step == 0: aggregator.create(batch_outs) if use_steps: aggregator.aggregate(batch_outs) else: aggregator.aggregate( batch_outs, batch_start=step * batch_size, batch_end=step * batch_size + current_batch_size) cbks.make_logs(model, batch_logs, batch_outs, mode) step += 1 if callbacks.model.stop_training: break # End of an epoch. aggregator.finalize() return aggregator.results
[ "def", "run_one_epoch", "(", "model", ",", "iterator", ",", "execution_function", ",", "dataset_size", "=", "None", ",", "batch_size", "=", "None", ",", "strategy", "=", "None", ",", "steps_per_epoch", "=", "None", ",", "num_samples", "=", "None", ",", "mode", "=", "ModeKeys", ".", "TRAIN", ",", "training_context", "=", "None", ",", "total_epochs", "=", "None", ")", ":", "# Only use the sample to count if there is a partial batch at the end.", "use_steps", "=", "num_samples", "is", "None", "if", "mode", "==", "ModeKeys", ".", "PREDICT", ":", "aggregator", "=", "training_utils", ".", "OutputsAggregator", "(", "use_steps", "=", "use_steps", ",", "steps", "=", "steps_per_epoch", ",", "num_samples", "=", "num_samples", ",", "batch_size", "=", "batch_size", ")", "else", ":", "aggregator", "=", "training_utils", ".", "MetricsAggregator", "(", "use_steps", "=", "use_steps", ",", "steps", "=", "steps_per_epoch", ",", "num_samples", "=", "num_samples", ")", "callbacks", "=", "training_context", ".", "callbacks", "progbar", "=", "training_context", ".", "progbar", "if", "callbacks", ".", "model", ".", "stop_training", ":", "return", "target_steps", "=", "steps_per_epoch", "or", "np", ".", "inf", "step", "=", "0", "while", "step", "<", "target_steps", ":", "if", "use_steps", ":", "current_batch_size", "=", "1", "elif", "step", "<", "target_steps", "-", "1", ":", "current_batch_size", "=", "batch_size", "else", ":", "current_batch_size", "=", "num_samples", "-", "step", "*", "batch_size", "with", "training_context", ".", "on_batch", "(", "step", "=", "step", ",", "mode", "=", "mode", ",", "size", "=", "current_batch_size", ")", "as", "batch_logs", ":", "try", ":", "batch_outs", "=", "execution_function", "(", "iterator", ")", "except", "(", "StopIteration", ",", "errors", ".", "OutOfRangeError", ")", ":", "# TODO(kaftan): File bug about tf function and errors.OutOfRangeError?", "# Are there any other C++ errors tf function should recapture?", "# The only acceptable case here is that the input has a unknown", "# length, and configured to fully consume it.", "if", "(", "dataset_size", "is", "None", "and", "steps_per_epoch", "is", "None", "and", "step", ">", "0", ")", ":", "# The input passed by the user ran out of batches.", "# Now we know the cardinality of the input(dataset or generator).", "steps_per_epoch", "=", "step", "aggregator", ".", "steps", "=", "steps_per_epoch", "progbar", ".", "params", "[", "'steps'", "]", "=", "steps_per_epoch", "progbar", ".", "progbar", ".", "target", "=", "steps_per_epoch", "else", ":", "callbacks", ".", "model", ".", "stop_training", "=", "True", "logging", ".", "warning", "(", "'Your input ran out of data; interrupting training. '", "'Make sure that your dataset or generator can generate at '", "'least `steps_per_epoch * epochs` batches (in this case, '", "'{} batches). You may need to use the repeat() function '", "'when building your dataset.'", ".", "format", "(", "total_epochs", "*", "steps_per_epoch", ")", ")", "# In either case, break out the loop for training batch.", "# Also note the training_context that data inputs are exhausted, so all", "# the post batch hooks can be skipped.", "batch_logs", "[", "'data_exhausted'", "]", "=", "True", "break", "if", "mode", "!=", "ModeKeys", ".", "PREDICT", ":", "data_batch_size", "=", "batch_outs", "[", "'batch_size'", "]", "batch_outs", "=", "(", "batch_outs", "[", "'total_loss'", "]", "+", "batch_outs", "[", "'output_losses'", "]", "+", "batch_outs", "[", "'metrics'", "]", ")", "if", "current_batch_size", "!=", "data_batch_size", ":", "batch_logs", "[", "'size'", "]", "=", "data_batch_size", "current_batch_size", "=", "data_batch_size", "else", ":", "batch_outs", "=", "_aggregate_predict_results", "(", "strategy", ",", "batch_outs", ",", "model", ")", "if", "step", "==", "0", ":", "aggregator", ".", "create", "(", "batch_outs", ")", "if", "use_steps", ":", "aggregator", ".", "aggregate", "(", "batch_outs", ")", "else", ":", "aggregator", ".", "aggregate", "(", "batch_outs", ",", "batch_start", "=", "step", "*", "batch_size", ",", "batch_end", "=", "step", "*", "batch_size", "+", "current_batch_size", ")", "cbks", ".", "make_logs", "(", "model", ",", "batch_logs", ",", "batch_outs", ",", "mode", ")", "step", "+=", "1", "if", "callbacks", ".", "model", ".", "stop_training", ":", "break", "# End of an epoch.", "aggregator", ".", "finalize", "(", ")", "return", "aggregator", ".", "results" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_v2.py#L57-L181
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
MenuBar.FindItemById
(*args, **kwargs)
return _core_.MenuBar_FindItemById(*args, **kwargs)
FindItemById(self, int id) -> MenuItem
FindItemById(self, int id) -> MenuItem
[ "FindItemById", "(", "self", "int", "id", ")", "-", ">", "MenuItem" ]
def FindItemById(*args, **kwargs): """FindItemById(self, int id) -> MenuItem""" return _core_.MenuBar_FindItemById(*args, **kwargs)
[ "def", "FindItemById", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuBar_FindItemById", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L12323-L12325
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/op_callbacks.py
python
remove_op_callback
(op_callback)
Remove an already-added op callback. Args: op_callback: The op callback to be removed. Raises: KeyError: If `op_callback` has not been registered using `add_op_callback()` before.
Remove an already-added op callback.
[ "Remove", "an", "already", "-", "added", "op", "callback", "." ]
def remove_op_callback(op_callback): """Remove an already-added op callback. Args: op_callback: The op callback to be removed. Raises: KeyError: If `op_callback` has not been registered using `add_op_callback()` before. """ ctx = context.context() ctx.remove_op_callback(op_callback) if ctx.executing_eagerly() and not ctx.op_callbacks: # Undo monkey-patch of execute.execute if there are no more callbacks. execute.execute = execute.quick_execute
[ "def", "remove_op_callback", "(", "op_callback", ")", ":", "ctx", "=", "context", ".", "context", "(", ")", "ctx", ".", "remove_op_callback", "(", "op_callback", ")", "if", "ctx", ".", "executing_eagerly", "(", ")", "and", "not", "ctx", ".", "op_callbacks", ":", "# Undo monkey-patch of execute.execute if there are no more callbacks.", "execute", ".", "execute", "=", "execute", ".", "quick_execute" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/op_callbacks.py#L125-L139
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
Gauge.Pulse
(*args, **kwargs)
return _controls_.Gauge_Pulse(*args, **kwargs)
Pulse(self)
Pulse(self)
[ "Pulse", "(", "self", ")" ]
def Pulse(*args, **kwargs): """Pulse(self)""" return _controls_.Gauge_Pulse(*args, **kwargs)
[ "def", "Pulse", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Gauge_Pulse", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L763-L765
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/helpers/algebra.py
python
mat_mul
(model, blob_in, blob_out, **kwargs)
return model.net.MatMul(blob_in, blob_out, **kwargs)
Matrix multiplication
Matrix multiplication
[ "Matrix", "multiplication" ]
def mat_mul(model, blob_in, blob_out, **kwargs): """Matrix multiplication""" return model.net.MatMul(blob_in, blob_out, **kwargs)
[ "def", "mat_mul", "(", "model", ",", "blob_in", ",", "blob_out", ",", "*", "*", "kwargs", ")", ":", "return", "model", ".", "net", ".", "MatMul", "(", "blob_in", ",", "blob_out", ",", "*", "*", "kwargs", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/helpers/algebra.py#L31-L33
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/start_try_job.py
python
_GetTryServerBucket
(bisect_job)
return master_bucket_map.get(bisect_job.master_name, default)
Returns the bucket name to be used by buildbucket.
Returns the bucket name to be used by buildbucket.
[ "Returns", "the", "bucket", "name", "to", "be", "used", "by", "buildbucket", "." ]
def _GetTryServerBucket(bisect_job): """Returns the bucket name to be used by buildbucket.""" master_bucket_map = namespaced_stored_object.Get(_MASTER_BUILDBUCKET_MAP_KEY) default = 'master.tryserver.chromium.perf' if not master_bucket_map: logging.warning( 'Could not get bucket to be used by buildbucket, using default.') return default return master_bucket_map.get(bisect_job.master_name, default)
[ "def", "_GetTryServerBucket", "(", "bisect_job", ")", ":", "master_bucket_map", "=", "namespaced_stored_object", ".", "Get", "(", "_MASTER_BUILDBUCKET_MAP_KEY", ")", "default", "=", "'master.tryserver.chromium.perf'", "if", "not", "master_bucket_map", ":", "logging", ".", "warning", "(", "'Could not get bucket to be used by buildbucket, using default.'", ")", "return", "default", "return", "master_bucket_map", ".", "get", "(", "bisect_job", ".", "master_name", ",", "default", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/start_try_job.py#L882-L890
Illumina/manta
75b5c38d4fcd2f6961197b28a41eb61856f2d976
src/srcqc/run_cppcheck.py
python
compareVersions
(version1, version2)
return 0
Compare two version strings. Return < 0 if version1 is less than version2 > 0 if version2 is less than version1 0 if version1 == version2
Compare two version strings.
[ "Compare", "two", "version", "strings", "." ]
def compareVersions(version1, version2): """ Compare two version strings. Return < 0 if version1 is less than version2 > 0 if version2 is less than version1 0 if version1 == version2 """ def versionToIntArray(version) : return [int(i) for i in version.split('.')] # parse version components version1Nums = versionToIntArray(version1) version2Nums = versionToIntArray(version2) # pad versions to be the same length: maxlen = max(len(version1Nums), len(version2Nums)) while len(version1Nums) < maxlen : version1Nums.append(0) while len(version2Nums) < maxlen : version2Nums.append(0) # compare for v1,v2 in zip(version1Nums, version2Nums) : if v1 < v2 : return -1 if v1 > v2 : return 1 return 0
[ "def", "compareVersions", "(", "version1", ",", "version2", ")", ":", "def", "versionToIntArray", "(", "version", ")", ":", "return", "[", "int", "(", "i", ")", "for", "i", "in", "version", ".", "split", "(", "'.'", ")", "]", "# parse version components", "version1Nums", "=", "versionToIntArray", "(", "version1", ")", "version2Nums", "=", "versionToIntArray", "(", "version2", ")", "# pad versions to be the same length:", "maxlen", "=", "max", "(", "len", "(", "version1Nums", ")", ",", "len", "(", "version2Nums", ")", ")", "while", "len", "(", "version1Nums", ")", "<", "maxlen", ":", "version1Nums", ".", "append", "(", "0", ")", "while", "len", "(", "version2Nums", ")", "<", "maxlen", ":", "version2Nums", ".", "append", "(", "0", ")", "# compare", "for", "v1", ",", "v2", "in", "zip", "(", "version1Nums", ",", "version2Nums", ")", ":", "if", "v1", "<", "v2", ":", "return", "-", "1", "if", "v1", ">", "v2", ":", "return", "1", "return", "0" ]
https://github.com/Illumina/manta/blob/75b5c38d4fcd2f6961197b28a41eb61856f2d976/src/srcqc/run_cppcheck.py#L53-L80
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/markdown/extensions/footnotes.py
python
FootnoteExtension.makeFootnoteId
(self, id)
Return footnote link id.
Return footnote link id.
[ "Return", "footnote", "link", "id", "." ]
def makeFootnoteId(self, id): """ Return footnote link id. """ if self.getConfig("UNIQUE_IDS"): return 'fn%s%d-%s' % (self.sep, self.unique_prefix, id) else: return 'fn%s%s' % (self.sep, id)
[ "def", "makeFootnoteId", "(", "self", ",", "id", ")", ":", "if", "self", ".", "getConfig", "(", "\"UNIQUE_IDS\"", ")", ":", "return", "'fn%s%d-%s'", "%", "(", "self", ".", "sep", ",", "self", ".", "unique_prefix", ",", "id", ")", "else", ":", "return", "'fn%s%s'", "%", "(", "self", ".", "sep", ",", "id", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/markdown/extensions/footnotes.py#L148-L153
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/google/protobuf/internal/decoder.py
python
Decoder.ReadMessageInto
(self, msg)
Calls msg.MergeFromString() to merge length-delimited serialized message data into |msg|. REQUIRES: The decoder must be positioned at the serialized "length" prefix to a length-delmiited serialized message. POSTCONDITION: The decoder is positioned just after the serialized message, and we have merged those serialized contents into |msg|.
Calls msg.MergeFromString() to merge length-delimited serialized message data into |msg|.
[ "Calls", "msg", ".", "MergeFromString", "()", "to", "merge", "length", "-", "delimited", "serialized", "message", "data", "into", "|msg|", "." ]
def ReadMessageInto(self, msg): """Calls msg.MergeFromString() to merge length-delimited serialized message data into |msg|. REQUIRES: The decoder must be positioned at the serialized "length" prefix to a length-delmiited serialized message. POSTCONDITION: The decoder is positioned just after the serialized message, and we have merged those serialized contents into |msg|. """ length = self._stream.ReadVarUInt32() sub_buffer = self._stream.GetSubBuffer(length) num_bytes_used = msg.MergeFromString(sub_buffer) if num_bytes_used != length: raise message.DecodeError( 'Submessage told to deserialize from %d-byte encoding, ' 'but used only %d bytes' % (length, num_bytes_used)) self._stream.SkipBytes(num_bytes_used)
[ "def", "ReadMessageInto", "(", "self", ",", "msg", ")", ":", "length", "=", "self", ".", "_stream", ".", "ReadVarUInt32", "(", ")", "sub_buffer", "=", "self", ".", "_stream", ".", "GetSubBuffer", "(", "length", ")", "num_bytes_used", "=", "msg", ".", "MergeFromString", "(", "sub_buffer", ")", "if", "num_bytes_used", "!=", "length", ":", "raise", "message", ".", "DecodeError", "(", "'Submessage told to deserialize from %d-byte encoding, '", "'but used only %d bytes'", "%", "(", "length", ",", "num_bytes_used", ")", ")", "self", ".", "_stream", ".", "SkipBytes", "(", "num_bytes_used", ")" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/decoder.py#L164-L182
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/utils/benchmark/tools/gbench/report.py
python
calculate_change
(old_val, new_val)
return float(new_val - old_val) / abs(old_val)
Return a float representing the decimal change between old_val and new_val.
Return a float representing the decimal change between old_val and new_val.
[ "Return", "a", "float", "representing", "the", "decimal", "change", "between", "old_val", "and", "new_val", "." ]
def calculate_change(old_val, new_val): """ Return a float representing the decimal change between old_val and new_val. """ if old_val == 0 and new_val == 0: return 0.0 if old_val == 0: return float(new_val - old_val) / (float(old_val + new_val) / 2) return float(new_val - old_val) / abs(old_val)
[ "def", "calculate_change", "(", "old_val", ",", "new_val", ")", ":", "if", "old_val", "==", "0", "and", "new_val", "==", "0", ":", "return", "0.0", "if", "old_val", "==", "0", ":", "return", "float", "(", "new_val", "-", "old_val", ")", "/", "(", "float", "(", "old_val", "+", "new_val", ")", "/", "2", ")", "return", "float", "(", "new_val", "-", "old_val", ")", "/", "abs", "(", "old_val", ")" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/benchmark/tools/gbench/report.py#L60-L68
Ifsttar/I-Simpa
2283385f4cac769a92e265edabb9c79cb6c42d03
currentRelease/ExperimentalCore/md_octave/kdtree.py
python
KDNode.search_nn_dist
(self, point, distance, best=None)
return results
Search the n nearest nodes of the given point which are within given distance point must be a location, not a node. A list containing the n nearest nodes to the point within the distance will be returned.
Search the n nearest nodes of the given point which are within given distance
[ "Search", "the", "n", "nearest", "nodes", "of", "the", "given", "point", "which", "are", "within", "given", "distance" ]
def search_nn_dist(self, point, distance, best=None): """ Search the n nearest nodes of the given point which are within given distance point must be a location, not a node. A list containing the n nearest nodes to the point within the distance will be returned. """ results = [] get_dist = lambda n: n.dist(point) self._search_nn_dist(point, distance, results, get_dist) return results
[ "def", "search_nn_dist", "(", "self", ",", "point", ",", "distance", ",", "best", "=", "None", ")", ":", "results", "=", "[", "]", "get_dist", "=", "lambda", "n", ":", "n", ".", "dist", "(", "point", ")", "self", ".", "_search_nn_dist", "(", "point", ",", "distance", ",", "results", ",", "get_dist", ")", "return", "results" ]
https://github.com/Ifsttar/I-Simpa/blob/2283385f4cac769a92e265edabb9c79cb6c42d03/currentRelease/ExperimentalCore/md_octave/kdtree.py#L517-L530
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.PositionAfter
(*args, **kwargs)
return _stc.StyledTextCtrl_PositionAfter(*args, **kwargs)
PositionAfter(self, int pos) -> int Given a valid document position, return the next position taking code page into account. Maximum value returned is the last position in the document.
PositionAfter(self, int pos) -> int
[ "PositionAfter", "(", "self", "int", "pos", ")", "-", ">", "int" ]
def PositionAfter(*args, **kwargs): """ PositionAfter(self, int pos) -> int Given a valid document position, return the next position taking code page into account. Maximum value returned is the last position in the document. """ return _stc.StyledTextCtrl_PositionAfter(*args, **kwargs)
[ "def", "PositionAfter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_PositionAfter", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L5309-L5316
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/cpplint.py
python
CheckSpacingForFunctionCall
(filename, clean_lines, linenum, error)
Checks for the correctness of various spacing around function calls. 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 the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing around function calls. 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] # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and not Search(r'\bcase\s+\(', fncall)): # TODO(unknown): Space after an operator function seem to be a common # error, silence those for now by restricting them to highest verbosity. if Search(r'\boperator_*\b', line): error(filename, linenum, 'whitespace/parens', 0, 'Extra space before ( in function call') else: error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have their own, more liberal conventions - we", "# first see if we should be looking inside such an expression for a", "# function call, to which we can apply more strict standards.", "fncall", "=", "line", "# if there's no control flow construct, look at whole line", "for", "pattern", "in", "(", "r'\\bif\\s*\\((.*)\\)\\s*{'", ",", "r'\\bfor\\s*\\((.*)\\)\\s*{'", ",", "r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'", ",", "r'\\bswitch\\s*\\((.*)\\)\\s*{'", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "match", ":", "fncall", "=", "match", ".", "group", "(", "1", ")", "# look inside the parens for function calls", "break", "# Except in if/for/while/switch, there should never be space", "# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception", "# for nested parens ( (a+b) + c ). Likewise, there should never be", "# a space before a ( when it's a function argument. I assume it's a", "# function argument when the char before the whitespace is legal in", "# a function name (alnum + _) and we're not starting a macro. Also ignore", "# pointers and references to arrays and functions coz they're too tricky:", "# we use a very simple way to recognize these:", "# \" (something)(maybe-something)\" or", "# \" (something)(maybe-something,\" or", "# \" (something)[something]\"", "# Note that we assume the contents of [] to be short enough that", "# they'll never need to wrap.", "if", "(", "# Ignore control structures.", "not", "Search", "(", "r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'", ",", "fncall", ")", "and", "# Ignore pointers/references to functions.", "not", "Search", "(", "r' \\([^)]+\\)\\([^)]*(\\)|,$)'", ",", "fncall", ")", "and", "# Ignore pointers/references to arrays.", "not", "Search", "(", "r' \\([^)]+\\)\\[[^\\]]+\\]'", ",", "fncall", ")", ")", ":", "if", "Search", "(", "r'\\w\\s*\\(\\s(?!\\s*\\\\$)'", ",", "fncall", ")", ":", "# a ( used for a fn call", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space after ( in function call'", ")", "elif", "Search", "(", "r'\\(\\s+(?!(\\s*\\\\)|\\()'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space after ('", ")", "if", "(", "Search", "(", "r'\\w\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'_{0,2}asm_{0,2}\\s+_{0,2}volatile_{0,2}\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'#\\s*define|typedef|using\\s+\\w+\\s*='", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\bcase\\s+\\('", ",", "fncall", ")", ")", ":", "# TODO(unknown): Space after an operator function seem to be a common", "# error, silence those for now by restricting them to highest verbosity.", "if", "Search", "(", "r'\\boperator_*\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "0", ",", "'Extra space before ( in function call'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space before ( in function call'", ")", "# If the ) is followed only by a newline or a { + newline, assume it's", "# part of a control statement (if/while/etc), and don't complain", "if", "Search", "(", "r'[^)]\\s+\\)\\s*[^{\\s]'", ",", "fncall", ")", ":", "# If the closing parenthesis is preceded by only whitespaces,", "# try to give a more descriptive error message.", "if", "Search", "(", "r'^\\s+\\)'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Closing ) should be moved to the previous line'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space before )'", ")" ]
https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L2940-L3014
omnisci/omniscidb
b9c95f1bd602b4ffc8b0edf18bfad61031e08d86
ThirdParty/googlebenchmark/mingw.py
python
root
(location = None, arch = None, version = None, threading = None, exceptions = None, revision = None, log = EmptyLogger())
return root_dir
Returns the root folder of a specific version of the mingw-builds variant of gcc. Will download the compiler if needed
Returns the root folder of a specific version of the mingw-builds variant of gcc. Will download the compiler if needed
[ "Returns", "the", "root", "folder", "of", "a", "specific", "version", "of", "the", "mingw", "-", "builds", "variant", "of", "gcc", ".", "Will", "download", "the", "compiler", "if", "needed" ]
def root(location = None, arch = None, version = None, threading = None, exceptions = None, revision = None, log = EmptyLogger()): ''' Returns the root folder of a specific version of the mingw-builds variant of gcc. Will download the compiler if needed ''' # Get the repository if we don't have all the information if not (arch and version and threading and exceptions and revision): versions = repository(log = log) # Determine some defaults version = version or max(versions.keys()) if not arch: arch = platform.machine().lower() if arch == 'x86': arch = 'i686' elif arch == 'amd64': arch = 'x86_64' if not threading: keys = versions[version][arch].keys() if 'posix' in keys: threading = 'posix' elif 'win32' in keys: threading = 'win32' else: threading = keys[0] if not exceptions: keys = versions[version][arch][threading].keys() if 'seh' in keys: exceptions = 'seh' elif 'sjlj' in keys: exceptions = 'sjlj' else: exceptions = keys[0] if revision == None: revision = max(versions[version][arch][threading][exceptions].keys()) if not location: location = os.path.join(tempfile.gettempdir(), 'mingw-builds') # Get the download url url = versions[version][arch][threading][exceptions][revision] # Tell the user whatzzup log.info('finding MinGW %s', '.'.join(str(v) for v in version)) log.debug(' - arch: %s', arch) log.debug(' - threading: %s', threading) log.debug(' - exceptions: %s', exceptions) log.debug(' - revision: %s', revision) log.debug(' - url: %s', url) # Store each specific revision differently slug = '{version}-{arch}-{threading}-{exceptions}-rev{revision}' slug = slug.format( version = '.'.join(str(v) for v in version), arch = arch, threading = threading, exceptions = exceptions, revision = revision ) if arch == 'x86_64': root_dir = os.path.join(location, slug, 'mingw64') elif arch == 'i686': root_dir = os.path.join(location, slug, 'mingw32') else: raise ValueError('Unknown MinGW arch: ' + arch) # Download if needed if not os.path.exists(root_dir): downloaded = download(url, os.path.join(location, slug), log = log) if downloaded != root_dir: raise ValueError('The location of mingw did not match\n%s\n%s' % (downloaded, root_dir)) return root_dir
[ "def", "root", "(", "location", "=", "None", ",", "arch", "=", "None", ",", "version", "=", "None", ",", "threading", "=", "None", ",", "exceptions", "=", "None", ",", "revision", "=", "None", ",", "log", "=", "EmptyLogger", "(", ")", ")", ":", "# Get the repository if we don't have all the information", "if", "not", "(", "arch", "and", "version", "and", "threading", "and", "exceptions", "and", "revision", ")", ":", "versions", "=", "repository", "(", "log", "=", "log", ")", "# Determine some defaults", "version", "=", "version", "or", "max", "(", "versions", ".", "keys", "(", ")", ")", "if", "not", "arch", ":", "arch", "=", "platform", ".", "machine", "(", ")", ".", "lower", "(", ")", "if", "arch", "==", "'x86'", ":", "arch", "=", "'i686'", "elif", "arch", "==", "'amd64'", ":", "arch", "=", "'x86_64'", "if", "not", "threading", ":", "keys", "=", "versions", "[", "version", "]", "[", "arch", "]", ".", "keys", "(", ")", "if", "'posix'", "in", "keys", ":", "threading", "=", "'posix'", "elif", "'win32'", "in", "keys", ":", "threading", "=", "'win32'", "else", ":", "threading", "=", "keys", "[", "0", "]", "if", "not", "exceptions", ":", "keys", "=", "versions", "[", "version", "]", "[", "arch", "]", "[", "threading", "]", ".", "keys", "(", ")", "if", "'seh'", "in", "keys", ":", "exceptions", "=", "'seh'", "elif", "'sjlj'", "in", "keys", ":", "exceptions", "=", "'sjlj'", "else", ":", "exceptions", "=", "keys", "[", "0", "]", "if", "revision", "==", "None", ":", "revision", "=", "max", "(", "versions", "[", "version", "]", "[", "arch", "]", "[", "threading", "]", "[", "exceptions", "]", ".", "keys", "(", ")", ")", "if", "not", "location", ":", "location", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "'mingw-builds'", ")", "# Get the download url", "url", "=", "versions", "[", "version", "]", "[", "arch", "]", "[", "threading", "]", "[", "exceptions", "]", "[", "revision", "]", "# Tell the user whatzzup", "log", ".", "info", "(", "'finding MinGW %s'", ",", "'.'", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "version", ")", ")", "log", ".", "debug", "(", "' - arch: %s'", ",", "arch", ")", "log", ".", "debug", "(", "' - threading: %s'", ",", "threading", ")", "log", ".", "debug", "(", "' - exceptions: %s'", ",", "exceptions", ")", "log", ".", "debug", "(", "' - revision: %s'", ",", "revision", ")", "log", ".", "debug", "(", "' - url: %s'", ",", "url", ")", "# Store each specific revision differently", "slug", "=", "'{version}-{arch}-{threading}-{exceptions}-rev{revision}'", "slug", "=", "slug", ".", "format", "(", "version", "=", "'.'", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "version", ")", ",", "arch", "=", "arch", ",", "threading", "=", "threading", ",", "exceptions", "=", "exceptions", ",", "revision", "=", "revision", ")", "if", "arch", "==", "'x86_64'", ":", "root_dir", "=", "os", ".", "path", ".", "join", "(", "location", ",", "slug", ",", "'mingw64'", ")", "elif", "arch", "==", "'i686'", ":", "root_dir", "=", "os", ".", "path", ".", "join", "(", "location", ",", "slug", ",", "'mingw32'", ")", "else", ":", "raise", "ValueError", "(", "'Unknown MinGW arch: '", "+", "arch", ")", "# Download if needed", "if", "not", "os", ".", "path", ".", "exists", "(", "root_dir", ")", ":", "downloaded", "=", "download", "(", "url", ",", "os", ".", "path", ".", "join", "(", "location", ",", "slug", ")", ",", "log", "=", "log", ")", "if", "downloaded", "!=", "root_dir", ":", "raise", "ValueError", "(", "'The location of mingw did not match\\n%s\\n%s'", "%", "(", "downloaded", ",", "root_dir", ")", ")", "return", "root_dir" ]
https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/ThirdParty/googlebenchmark/mingw.py#L172-L246
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/utils.py
python
evalcontextfunction
(f)
return f
This decorator can be used to mark a function or method as an eval context callable. This is similar to the :func:`contextfunction` but instead of passing the context, an evaluation context object is passed. For more information about the eval context, see :ref:`eval-context`. .. versionadded:: 2.4
This decorator can be used to mark a function or method as an eval context callable. This is similar to the :func:`contextfunction` but instead of passing the context, an evaluation context object is passed. For more information about the eval context, see :ref:`eval-context`.
[ "This", "decorator", "can", "be", "used", "to", "mark", "a", "function", "or", "method", "as", "an", "eval", "context", "callable", ".", "This", "is", "similar", "to", "the", ":", "func", ":", "contextfunction", "but", "instead", "of", "passing", "the", "context", "an", "evaluation", "context", "object", "is", "passed", ".", "For", "more", "information", "about", "the", "eval", "context", "see", ":", "ref", ":", "eval", "-", "context", "." ]
def evalcontextfunction(f): """This decorator can be used to mark a function or method as an eval context callable. This is similar to the :func:`contextfunction` but instead of passing the context, an evaluation context object is passed. For more information about the eval context, see :ref:`eval-context`. .. versionadded:: 2.4 """ f.evalcontextfunction = True return f
[ "def", "evalcontextfunction", "(", "f", ")", ":", "f", ".", "evalcontextfunction", "=", "True", "return", "f" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/utils.py#L56-L66
randombit/botan
e068d80953469fc8a3ec1715d0f64756d972daba
src/scripts/ci_build.py
python
determine_flags
(target, target_os, target_cpu, target_cc, cc_bin, ccache, root_dir, pkcs11_lib, use_gdb, disable_werror, extra_cxxflags, disabled_tests)
return flags, run_test_command, make_prefix
Return the configure.py flags as well as make/test running prefixes
Return the configure.py flags as well as make/test running prefixes
[ "Return", "the", "configure", ".", "py", "flags", "as", "well", "as", "make", "/", "test", "running", "prefixes" ]
def determine_flags(target, target_os, target_cpu, target_cc, cc_bin, ccache, root_dir, pkcs11_lib, use_gdb, disable_werror, extra_cxxflags, disabled_tests): # pylint: disable=too-many-branches,too-many-statements,too-many-arguments,too-many-locals """ Return the configure.py flags as well as make/test running prefixes """ is_cross_target = target.startswith('cross-') if target_os not in ['linux', 'osx', 'windows', 'freebsd']: print('Error unknown OS %s' % (target_os)) return (None, None, None) if is_cross_target: if target_os == 'osx': target_os = 'ios' elif target == 'cross-win64': target_os = 'mingw' elif target in ['cross-android-arm32', 'cross-android-arm64']: target_os = 'android' if target_os == 'windows' and target_cc == 'gcc': target_os = 'mingw' if target == 'baremetal': target_os = 'none' if target == 'emscripten': target_os = 'emscripten' make_prefix = [] test_prefix = [] test_cmd = [os.path.join(root_dir, 'botan-test')] install_prefix = tempfile.mkdtemp(prefix='botan-install-') flags = ['--prefix=%s' % (install_prefix), '--cc=%s' % (target_cc), '--os=%s' % (target_os), '--build-targets=%s' % ','.join(build_targets(target, target_os))] if ccache is not None: flags += ['--no-store-vc-rev', '--compiler-cache=%s' % (ccache)] if not disable_werror: flags += ['--werror-mode'] if target_cpu is not None: flags += ['--cpu=%s' % (target_cpu)] for flag in extra_cxxflags: flags += ['--extra-cxxflags=%s' % (flag)] if target in ['minimized']: flags += ['--minimized-build', '--enable-modules=system_rng,sha2_32,sha2_64,aes'] if target in ['amalgamation']: flags += ['--amalgamation'] if target in ['bsi', 'nist']: # tls is optional for bsi/nist but add it so verify tests work with these minimized configs flags += ['--module-policy=%s' % (target), '--enable-modules=tls'] if target == 'docs': flags += ['--with-doxygen', '--with-sphinx', '--with-rst2man'] test_cmd = None if target == 'cross-win64': # this test compiles under MinGW but fails when run under Wine disabled_tests.append('certstor_system') if target == 'coverage': flags += ['--with-coverage-info', '--with-debug-info', '--test-mode'] if target == 'valgrind': flags += ['--with-valgrind'] test_prefix = ['valgrind', '--error-exitcode=9', '-v', '--leak-check=full', '--show-reachable=yes'] # valgrind is single threaded anyway test_cmd += ['--test-threads=1'] # valgrind is slow slow_tests = [ 'cryptobox', 'dh_invalid', 'dh_kat', 'dh_keygen', 'dl_group_gen', 'dlies', 'dsa_param', 'ecc_basemul', 'ecdsa_verify_wycheproof', 'mce_keygen', 'passhash9', 'rsa_encrypt', 'rsa_pss', 'rsa_pss_raw', 'scrypt', 'srp6_kat', 'x509_path_bsi', 'xmss_keygen', 'xmss_sign', 'pbkdf', 'argon2', 'bcrypt', 'bcrypt_pbkdf', 'compression', 'ed25519_sign', 'elgamal_keygen', 'x509_path_rsa_pss'] disabled_tests += slow_tests if target == 'fuzzers': flags += ['--unsafe-fuzzer-mode'] if target in ['fuzzers', 'coverage']: flags += ['--build-fuzzers=test'] if target in ['fuzzers', 'sanitizer']: flags += ['--with-debug-asserts'] if target_cc in ['clang', 'gcc']: flags += ['--enable-sanitizers=address,undefined'] else: flags += ['--with-sanitizers'] if target in ['valgrind', 'sanitizer', 'fuzzers']: flags += ['--disable-modules=locking_allocator'] if target == 'baremetal': cc_bin = 'arm-none-eabi-c++' flags += ['--cpu=arm32', '--disable-neon', '--without-stack-protector', '--ldflags=-specs=nosys.specs'] test_cmd = None if target == 'emscripten': flags += ['--cpu=wasm'] # need to find a way to run the wasm-compiled tests w/o a browser test_cmd = None if is_cross_target: if target_os == 'ios': make_prefix = ['xcrun', '--sdk', 'iphoneos'] test_cmd = None if target == 'cross-ios-arm64': flags += ['--cpu=arm64', '--cc-abi-flags=-arch arm64 -stdlib=libc++'] else: raise Exception("Unknown cross target '%s' for iOS" % (target)) elif target_os == 'android': ndk = os.getenv('ANDROID_NDK') if ndk is None: raise Exception('Android CI build requires ANDROID_NDK env variable be set') api_lvl = int(os.getenv('ANDROID_API_LEVEL', '0')) if api_lvl == 0: # If not set arbitrarily choose API 16 (Android 4.1) for ARMv7 and 28 (Android 9) for AArch64 api_lvl = 16 if target == 'cross-android-arm32' else 28 toolchain_dir = os.path.join(ndk, 'toolchains/llvm/prebuilt/linux-x86_64/bin') test_cmd = None if target == 'cross-android-arm32': cc_bin = os.path.join(toolchain_dir, 'armv7a-linux-androideabi%d-clang++' % (api_lvl)) flags += ['--cpu=armv7', '--ar-command=%s' % (os.path.join(toolchain_dir, 'arm-linux-androideabi-ar'))] elif target == 'cross-android-arm64': cc_bin = os.path.join(toolchain_dir, 'aarch64-linux-android%d-clang++' % (api_lvl)) flags += ['--cpu=arm64', '--ar-command=%s' % (os.path.join(toolchain_dir, 'aarch64-linux-android-ar'))] if api_lvl < 18: flags += ['--without-os-features=getauxval'] if api_lvl >= 28: flags += ['--with-os-features=getentropy'] elif target == 'cross-i386': flags += ['--cpu=x86_32'] elif target == 'cross-win64': # MinGW in 16.04 is lacking std::mutex for unknown reason cc_bin = 'x86_64-w64-mingw32-g++' flags += ['--cpu=x86_64', '--cc-abi-flags=-static', '--ar-command=x86_64-w64-mingw32-ar', '--without-os-feature=threads'] test_cmd = [os.path.join(root_dir, 'botan-test.exe')] + test_cmd[1:] test_prefix = ['wine'] else: if target == 'cross-arm32': flags += ['--cpu=armv7'] cc_bin = 'arm-linux-gnueabihf-g++' # Currently arm32 CI only runs on native AArch64 #test_prefix = ['qemu-arm', '-L', '/usr/arm-linux-gnueabihf/'] elif target == 'cross-arm64': flags += ['--cpu=aarch64'] cc_bin = 'aarch64-linux-gnu-g++' test_prefix = ['qemu-aarch64', '-L', '/usr/aarch64-linux-gnu/'] elif target == 'cross-ppc32': flags += ['--cpu=ppc32'] cc_bin = 'powerpc-linux-gnu-g++' test_prefix = ['qemu-ppc', '-L', '/usr/powerpc-linux-gnu/'] elif target == 'cross-ppc64': flags += ['--cpu=ppc64', '--with-endian=little'] cc_bin = 'powerpc64le-linux-gnu-g++' test_prefix = ['qemu-ppc64le', '-cpu', 'POWER8', '-L', '/usr/powerpc64le-linux-gnu/'] elif target == 'cross-mips64': flags += ['--cpu=mips64', '--with-endian=big'] cc_bin = 'mips64-linux-gnuabi64-g++' test_prefix = ['qemu-mips64', '-L', '/usr/mips64-linux-gnuabi64/'] test_cmd.remove('simd_32') # no SIMD on MIPS else: raise Exception("Unknown cross target '%s' for Linux" % (target)) else: # Flags specific to native targets if target_os in ['osx', 'linux']: flags += ['--with-bzip2', '--with-sqlite', '--with-zlib'] if target_os in ['osx', 'ios']: flags += ['--with-commoncrypto'] if target == 'coverage': flags += ['--with-boost'] if target_os == 'windows' and target in ['shared', 'static']: # ./configure.py needs extra hand-holding for boost on windows boost_root = os.environ.get('BOOST_ROOT') boost_libs = os.environ.get('BOOST_LIBRARYDIR') boost_system = os.environ.get('BOOST_SYSTEM_LIBRARY') if boost_root and boost_libs and boost_system: flags += ['--with-boost', '--with-external-includedir', boost_root, '--with-external-libdir', boost_libs, '--boost-library-name', boost_system] if target_os == 'linux': flags += ['--with-lzma'] if target in ['coverage']: flags += ['--with-tpm'] test_cmd += ['--run-online-tests'] if pkcs11_lib and os.access(pkcs11_lib, os.R_OK): test_cmd += ['--pkcs11-lib=%s' % (pkcs11_lib)] if target in ['coverage', 'sanitizer']: test_cmd += ['--run-long-tests'] flags += ['--cc-bin=%s' % (cc_bin)] if test_cmd is None: run_test_command = None else: if use_gdb: disabled_tests.append("os_utils") # render 'disabled_tests' array into test_cmd if disabled_tests: test_cmd += ['--skip-tests=%s' % (','.join(disabled_tests))] if use_gdb: (cmd, args) = test_cmd[0], test_cmd[1:] run_test_command = test_prefix + ['gdb', cmd, '-ex', 'run %s' % (' '.join(args)), '-ex', 'bt', '-ex', 'quit'] else: run_test_command = test_prefix + test_cmd return flags, run_test_command, make_prefix
[ "def", "determine_flags", "(", "target", ",", "target_os", ",", "target_cpu", ",", "target_cc", ",", "cc_bin", ",", "ccache", ",", "root_dir", ",", "pkcs11_lib", ",", "use_gdb", ",", "disable_werror", ",", "extra_cxxflags", ",", "disabled_tests", ")", ":", "# pylint: disable=too-many-branches,too-many-statements,too-many-arguments,too-many-locals", "is_cross_target", "=", "target", ".", "startswith", "(", "'cross-'", ")", "if", "target_os", "not", "in", "[", "'linux'", ",", "'osx'", ",", "'windows'", ",", "'freebsd'", "]", ":", "print", "(", "'Error unknown OS %s'", "%", "(", "target_os", ")", ")", "return", "(", "None", ",", "None", ",", "None", ")", "if", "is_cross_target", ":", "if", "target_os", "==", "'osx'", ":", "target_os", "=", "'ios'", "elif", "target", "==", "'cross-win64'", ":", "target_os", "=", "'mingw'", "elif", "target", "in", "[", "'cross-android-arm32'", ",", "'cross-android-arm64'", "]", ":", "target_os", "=", "'android'", "if", "target_os", "==", "'windows'", "and", "target_cc", "==", "'gcc'", ":", "target_os", "=", "'mingw'", "if", "target", "==", "'baremetal'", ":", "target_os", "=", "'none'", "if", "target", "==", "'emscripten'", ":", "target_os", "=", "'emscripten'", "make_prefix", "=", "[", "]", "test_prefix", "=", "[", "]", "test_cmd", "=", "[", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'botan-test'", ")", "]", "install_prefix", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'botan-install-'", ")", "flags", "=", "[", "'--prefix=%s'", "%", "(", "install_prefix", ")", ",", "'--cc=%s'", "%", "(", "target_cc", ")", ",", "'--os=%s'", "%", "(", "target_os", ")", ",", "'--build-targets=%s'", "%", "','", ".", "join", "(", "build_targets", "(", "target", ",", "target_os", ")", ")", "]", "if", "ccache", "is", "not", "None", ":", "flags", "+=", "[", "'--no-store-vc-rev'", ",", "'--compiler-cache=%s'", "%", "(", "ccache", ")", "]", "if", "not", "disable_werror", ":", "flags", "+=", "[", "'--werror-mode'", "]", "if", "target_cpu", "is", "not", "None", ":", "flags", "+=", "[", "'--cpu=%s'", "%", "(", "target_cpu", ")", "]", "for", "flag", "in", "extra_cxxflags", ":", "flags", "+=", "[", "'--extra-cxxflags=%s'", "%", "(", "flag", ")", "]", "if", "target", "in", "[", "'minimized'", "]", ":", "flags", "+=", "[", "'--minimized-build'", ",", "'--enable-modules=system_rng,sha2_32,sha2_64,aes'", "]", "if", "target", "in", "[", "'amalgamation'", "]", ":", "flags", "+=", "[", "'--amalgamation'", "]", "if", "target", "in", "[", "'bsi'", ",", "'nist'", "]", ":", "# tls is optional for bsi/nist but add it so verify tests work with these minimized configs", "flags", "+=", "[", "'--module-policy=%s'", "%", "(", "target", ")", ",", "'--enable-modules=tls'", "]", "if", "target", "==", "'docs'", ":", "flags", "+=", "[", "'--with-doxygen'", ",", "'--with-sphinx'", ",", "'--with-rst2man'", "]", "test_cmd", "=", "None", "if", "target", "==", "'cross-win64'", ":", "# this test compiles under MinGW but fails when run under Wine", "disabled_tests", ".", "append", "(", "'certstor_system'", ")", "if", "target", "==", "'coverage'", ":", "flags", "+=", "[", "'--with-coverage-info'", ",", "'--with-debug-info'", ",", "'--test-mode'", "]", "if", "target", "==", "'valgrind'", ":", "flags", "+=", "[", "'--with-valgrind'", "]", "test_prefix", "=", "[", "'valgrind'", ",", "'--error-exitcode=9'", ",", "'-v'", ",", "'--leak-check=full'", ",", "'--show-reachable=yes'", "]", "# valgrind is single threaded anyway", "test_cmd", "+=", "[", "'--test-threads=1'", "]", "# valgrind is slow", "slow_tests", "=", "[", "'cryptobox'", ",", "'dh_invalid'", ",", "'dh_kat'", ",", "'dh_keygen'", ",", "'dl_group_gen'", ",", "'dlies'", ",", "'dsa_param'", ",", "'ecc_basemul'", ",", "'ecdsa_verify_wycheproof'", ",", "'mce_keygen'", ",", "'passhash9'", ",", "'rsa_encrypt'", ",", "'rsa_pss'", ",", "'rsa_pss_raw'", ",", "'scrypt'", ",", "'srp6_kat'", ",", "'x509_path_bsi'", ",", "'xmss_keygen'", ",", "'xmss_sign'", ",", "'pbkdf'", ",", "'argon2'", ",", "'bcrypt'", ",", "'bcrypt_pbkdf'", ",", "'compression'", ",", "'ed25519_sign'", ",", "'elgamal_keygen'", ",", "'x509_path_rsa_pss'", "]", "disabled_tests", "+=", "slow_tests", "if", "target", "==", "'fuzzers'", ":", "flags", "+=", "[", "'--unsafe-fuzzer-mode'", "]", "if", "target", "in", "[", "'fuzzers'", ",", "'coverage'", "]", ":", "flags", "+=", "[", "'--build-fuzzers=test'", "]", "if", "target", "in", "[", "'fuzzers'", ",", "'sanitizer'", "]", ":", "flags", "+=", "[", "'--with-debug-asserts'", "]", "if", "target_cc", "in", "[", "'clang'", ",", "'gcc'", "]", ":", "flags", "+=", "[", "'--enable-sanitizers=address,undefined'", "]", "else", ":", "flags", "+=", "[", "'--with-sanitizers'", "]", "if", "target", "in", "[", "'valgrind'", ",", "'sanitizer'", ",", "'fuzzers'", "]", ":", "flags", "+=", "[", "'--disable-modules=locking_allocator'", "]", "if", "target", "==", "'baremetal'", ":", "cc_bin", "=", "'arm-none-eabi-c++'", "flags", "+=", "[", "'--cpu=arm32'", ",", "'--disable-neon'", ",", "'--without-stack-protector'", ",", "'--ldflags=-specs=nosys.specs'", "]", "test_cmd", "=", "None", "if", "target", "==", "'emscripten'", ":", "flags", "+=", "[", "'--cpu=wasm'", "]", "# need to find a way to run the wasm-compiled tests w/o a browser", "test_cmd", "=", "None", "if", "is_cross_target", ":", "if", "target_os", "==", "'ios'", ":", "make_prefix", "=", "[", "'xcrun'", ",", "'--sdk'", ",", "'iphoneos'", "]", "test_cmd", "=", "None", "if", "target", "==", "'cross-ios-arm64'", ":", "flags", "+=", "[", "'--cpu=arm64'", ",", "'--cc-abi-flags=-arch arm64 -stdlib=libc++'", "]", "else", ":", "raise", "Exception", "(", "\"Unknown cross target '%s' for iOS\"", "%", "(", "target", ")", ")", "elif", "target_os", "==", "'android'", ":", "ndk", "=", "os", ".", "getenv", "(", "'ANDROID_NDK'", ")", "if", "ndk", "is", "None", ":", "raise", "Exception", "(", "'Android CI build requires ANDROID_NDK env variable be set'", ")", "api_lvl", "=", "int", "(", "os", ".", "getenv", "(", "'ANDROID_API_LEVEL'", ",", "'0'", ")", ")", "if", "api_lvl", "==", "0", ":", "# If not set arbitrarily choose API 16 (Android 4.1) for ARMv7 and 28 (Android 9) for AArch64", "api_lvl", "=", "16", "if", "target", "==", "'cross-android-arm32'", "else", "28", "toolchain_dir", "=", "os", ".", "path", ".", "join", "(", "ndk", ",", "'toolchains/llvm/prebuilt/linux-x86_64/bin'", ")", "test_cmd", "=", "None", "if", "target", "==", "'cross-android-arm32'", ":", "cc_bin", "=", "os", ".", "path", ".", "join", "(", "toolchain_dir", ",", "'armv7a-linux-androideabi%d-clang++'", "%", "(", "api_lvl", ")", ")", "flags", "+=", "[", "'--cpu=armv7'", ",", "'--ar-command=%s'", "%", "(", "os", ".", "path", ".", "join", "(", "toolchain_dir", ",", "'arm-linux-androideabi-ar'", ")", ")", "]", "elif", "target", "==", "'cross-android-arm64'", ":", "cc_bin", "=", "os", ".", "path", ".", "join", "(", "toolchain_dir", ",", "'aarch64-linux-android%d-clang++'", "%", "(", "api_lvl", ")", ")", "flags", "+=", "[", "'--cpu=arm64'", ",", "'--ar-command=%s'", "%", "(", "os", ".", "path", ".", "join", "(", "toolchain_dir", ",", "'aarch64-linux-android-ar'", ")", ")", "]", "if", "api_lvl", "<", "18", ":", "flags", "+=", "[", "'--without-os-features=getauxval'", "]", "if", "api_lvl", ">=", "28", ":", "flags", "+=", "[", "'--with-os-features=getentropy'", "]", "elif", "target", "==", "'cross-i386'", ":", "flags", "+=", "[", "'--cpu=x86_32'", "]", "elif", "target", "==", "'cross-win64'", ":", "# MinGW in 16.04 is lacking std::mutex for unknown reason", "cc_bin", "=", "'x86_64-w64-mingw32-g++'", "flags", "+=", "[", "'--cpu=x86_64'", ",", "'--cc-abi-flags=-static'", ",", "'--ar-command=x86_64-w64-mingw32-ar'", ",", "'--without-os-feature=threads'", "]", "test_cmd", "=", "[", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'botan-test.exe'", ")", "]", "+", "test_cmd", "[", "1", ":", "]", "test_prefix", "=", "[", "'wine'", "]", "else", ":", "if", "target", "==", "'cross-arm32'", ":", "flags", "+=", "[", "'--cpu=armv7'", "]", "cc_bin", "=", "'arm-linux-gnueabihf-g++'", "# Currently arm32 CI only runs on native AArch64", "#test_prefix = ['qemu-arm', '-L', '/usr/arm-linux-gnueabihf/']", "elif", "target", "==", "'cross-arm64'", ":", "flags", "+=", "[", "'--cpu=aarch64'", "]", "cc_bin", "=", "'aarch64-linux-gnu-g++'", "test_prefix", "=", "[", "'qemu-aarch64'", ",", "'-L'", ",", "'/usr/aarch64-linux-gnu/'", "]", "elif", "target", "==", "'cross-ppc32'", ":", "flags", "+=", "[", "'--cpu=ppc32'", "]", "cc_bin", "=", "'powerpc-linux-gnu-g++'", "test_prefix", "=", "[", "'qemu-ppc'", ",", "'-L'", ",", "'/usr/powerpc-linux-gnu/'", "]", "elif", "target", "==", "'cross-ppc64'", ":", "flags", "+=", "[", "'--cpu=ppc64'", ",", "'--with-endian=little'", "]", "cc_bin", "=", "'powerpc64le-linux-gnu-g++'", "test_prefix", "=", "[", "'qemu-ppc64le'", ",", "'-cpu'", ",", "'POWER8'", ",", "'-L'", ",", "'/usr/powerpc64le-linux-gnu/'", "]", "elif", "target", "==", "'cross-mips64'", ":", "flags", "+=", "[", "'--cpu=mips64'", ",", "'--with-endian=big'", "]", "cc_bin", "=", "'mips64-linux-gnuabi64-g++'", "test_prefix", "=", "[", "'qemu-mips64'", ",", "'-L'", ",", "'/usr/mips64-linux-gnuabi64/'", "]", "test_cmd", ".", "remove", "(", "'simd_32'", ")", "# no SIMD on MIPS", "else", ":", "raise", "Exception", "(", "\"Unknown cross target '%s' for Linux\"", "%", "(", "target", ")", ")", "else", ":", "# Flags specific to native targets", "if", "target_os", "in", "[", "'osx'", ",", "'linux'", "]", ":", "flags", "+=", "[", "'--with-bzip2'", ",", "'--with-sqlite'", ",", "'--with-zlib'", "]", "if", "target_os", "in", "[", "'osx'", ",", "'ios'", "]", ":", "flags", "+=", "[", "'--with-commoncrypto'", "]", "if", "target", "==", "'coverage'", ":", "flags", "+=", "[", "'--with-boost'", "]", "if", "target_os", "==", "'windows'", "and", "target", "in", "[", "'shared'", ",", "'static'", "]", ":", "# ./configure.py needs extra hand-holding for boost on windows", "boost_root", "=", "os", ".", "environ", ".", "get", "(", "'BOOST_ROOT'", ")", "boost_libs", "=", "os", ".", "environ", ".", "get", "(", "'BOOST_LIBRARYDIR'", ")", "boost_system", "=", "os", ".", "environ", ".", "get", "(", "'BOOST_SYSTEM_LIBRARY'", ")", "if", "boost_root", "and", "boost_libs", "and", "boost_system", ":", "flags", "+=", "[", "'--with-boost'", ",", "'--with-external-includedir'", ",", "boost_root", ",", "'--with-external-libdir'", ",", "boost_libs", ",", "'--boost-library-name'", ",", "boost_system", "]", "if", "target_os", "==", "'linux'", ":", "flags", "+=", "[", "'--with-lzma'", "]", "if", "target", "in", "[", "'coverage'", "]", ":", "flags", "+=", "[", "'--with-tpm'", "]", "test_cmd", "+=", "[", "'--run-online-tests'", "]", "if", "pkcs11_lib", "and", "os", ".", "access", "(", "pkcs11_lib", ",", "os", ".", "R_OK", ")", ":", "test_cmd", "+=", "[", "'--pkcs11-lib=%s'", "%", "(", "pkcs11_lib", ")", "]", "if", "target", "in", "[", "'coverage'", ",", "'sanitizer'", "]", ":", "test_cmd", "+=", "[", "'--run-long-tests'", "]", "flags", "+=", "[", "'--cc-bin=%s'", "%", "(", "cc_bin", ")", "]", "if", "test_cmd", "is", "None", ":", "run_test_command", "=", "None", "else", ":", "if", "use_gdb", ":", "disabled_tests", ".", "append", "(", "\"os_utils\"", ")", "# render 'disabled_tests' array into test_cmd", "if", "disabled_tests", ":", "test_cmd", "+=", "[", "'--skip-tests=%s'", "%", "(", "','", ".", "join", "(", "disabled_tests", ")", ")", "]", "if", "use_gdb", ":", "(", "cmd", ",", "args", ")", "=", "test_cmd", "[", "0", "]", ",", "test_cmd", "[", "1", ":", "]", "run_test_command", "=", "test_prefix", "+", "[", "'gdb'", ",", "cmd", ",", "'-ex'", ",", "'run %s'", "%", "(", "' '", ".", "join", "(", "args", ")", ")", ",", "'-ex'", ",", "'bt'", ",", "'-ex'", ",", "'quit'", "]", "else", ":", "run_test_command", "=", "test_prefix", "+", "test_cmd", "return", "flags", ",", "run_test_command", ",", "make_prefix" ]
https://github.com/randombit/botan/blob/e068d80953469fc8a3ec1715d0f64756d972daba/src/scripts/ci_build.py#L75-L322
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
elle/drake/src/drake/__init__.py
python
Path.without_suffix
(self, rhs)
return drake.Path(path, absolute = self.__absolute, virtual = self.__virtual, volume = self.__volume)
Remove rhs suffix from self. rhs -- the suffix to strip, as a Path or a string. >>> p = Path('foo/bar/baz/quux') >>> p Path("foo/bar/baz/quux") >>> p.without_suffix("baz/quux") Path("foo/bar") Throws if rhs is not a prefix of self. >>> p.without_suffix("baz") Traceback (most recent call last): ... Exception: baz is not a suffix of foo/bar/baz/quux
Remove rhs suffix from self.
[ "Remove", "rhs", "suffix", "from", "self", "." ]
def without_suffix(self, rhs): """Remove rhs suffix from self. rhs -- the suffix to strip, as a Path or a string. >>> p = Path('foo/bar/baz/quux') >>> p Path("foo/bar/baz/quux") >>> p.without_suffix("baz/quux") Path("foo/bar") Throws if rhs is not a prefix of self. >>> p.without_suffix("baz") Traceback (most recent call last): ... Exception: baz is not a suffix of foo/bar/baz/quux """ rhs = drake.Path(rhs) if self.__path[-len(rhs.__path):] != rhs.__path: raise Exception("%s is not a suffix of %s" % (rhs, self)) path = self.__path[0:-len(rhs.__path):] if not path: path = ('.',) return drake.Path(path, absolute = self.__absolute, virtual = self.__virtual, volume = self.__volume)
[ "def", "without_suffix", "(", "self", ",", "rhs", ")", ":", "rhs", "=", "drake", ".", "Path", "(", "rhs", ")", "if", "self", ".", "__path", "[", "-", "len", "(", "rhs", ".", "__path", ")", ":", "]", "!=", "rhs", ".", "__path", ":", "raise", "Exception", "(", "\"%s is not a suffix of %s\"", "%", "(", "rhs", ",", "self", ")", ")", "path", "=", "self", ".", "__path", "[", "0", ":", "-", "len", "(", "rhs", ".", "__path", ")", ":", "]", "if", "not", "path", ":", "path", "=", "(", "'.'", ",", ")", "return", "drake", ".", "Path", "(", "path", ",", "absolute", "=", "self", ".", "__absolute", ",", "virtual", "=", "self", ".", "__virtual", ",", "volume", "=", "self", ".", "__volume", ")" ]
https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L1019-L1046
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/inspect.py
python
getsourcelines
(object)
Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.
Return a list of source lines and starting line number for an object.
[ "Return", "a", "list", "of", "source", "lines", "and", "starting", "line", "number", "for", "an", "object", "." ]
def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1
[ "def", "getsourcelines", "(", "object", ")", ":", "lines", ",", "lnum", "=", "findsource", "(", "object", ")", "if", "ismodule", "(", "object", ")", ":", "return", "lines", ",", "0", "else", ":", "return", "getblock", "(", "lines", "[", "lnum", ":", "]", ")", ",", "lnum", "+", "1" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/inspect.py#L682-L693
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/util.py
python
_websocket_mask_python
(mask: bytes, data: bytes)
return unmasked_arr.tobytes()
Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available.
Websocket masking function.
[ "Websocket", "masking", "function", "." ]
def _websocket_mask_python(mask: bytes, data: bytes) -> bytes: """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available. """ mask_arr = array.array("B", mask) unmasked_arr = array.array("B", data) for i in range(len(data)): unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4] return unmasked_arr.tobytes()
[ "def", "_websocket_mask_python", "(", "mask", ":", "bytes", ",", "data", ":", "bytes", ")", "->", "bytes", ":", "mask_arr", "=", "array", ".", "array", "(", "\"B\"", ",", "mask", ")", "unmasked_arr", "=", "array", ".", "array", "(", "\"B\"", ",", "data", ")", "for", "i", "in", "range", "(", "len", "(", "data", ")", ")", ":", "unmasked_arr", "[", "i", "]", "=", "unmasked_arr", "[", "i", "]", "^", "mask_arr", "[", "i", "%", "4", "]", "return", "unmasked_arr", ".", "tobytes", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/util.py#L441-L454
Netflix/NfWebCrypto
499faf4eb9f9ccf0b21dc728e974970f54bd6c52
plugin/ppapi/ppapi/generators/idl_gen_wrapper.py
python
WrapperGen.OwnHeaderFile
(self)
Return the header file that specifies the API of this wrapper. We do not generate the header files.
Return the header file that specifies the API of this wrapper. We do not generate the header files.
[ "Return", "the", "header", "file", "that", "specifies", "the", "API", "of", "this", "wrapper", ".", "We", "do", "not", "generate", "the", "header", "files", "." ]
def OwnHeaderFile(self): """Return the header file that specifies the API of this wrapper. We do not generate the header files. """ raise Exception('Child class must implement this')
[ "def", "OwnHeaderFile", "(", "self", ")", ":", "raise", "Exception", "(", "'Child class must implement this'", ")" ]
https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/generators/idl_gen_wrapper.py#L208-L211
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_data.py
python
Data.put_uint
(self, ui: Union[uint, int])
Puts an unsigned int value. :param ui: an integral value in the range :math:`0` to :math:`2^{32} - 1` inclusive. :raise: * ``AssertionError`` if parameter is out of the range :math:`0` to :math:`2^{32} - 1` inclusive. * :exc:`DataException` if there is a Proton error.
Puts an unsigned int value.
[ "Puts", "an", "unsigned", "int", "value", "." ]
def put_uint(self, ui: Union[uint, int]) -> None: """ Puts an unsigned int value. :param ui: an integral value in the range :math:`0` to :math:`2^{32} - 1` inclusive. :raise: * ``AssertionError`` if parameter is out of the range :math:`0` to :math:`2^{32} - 1` inclusive. * :exc:`DataException` if there is a Proton error. """ self._check(pn_data_put_uint(self._data, ui))
[ "def", "put_uint", "(", "self", ",", "ui", ":", "Union", "[", "uint", ",", "int", "]", ")", "->", "None", ":", "self", ".", "_check", "(", "pn_data_put_uint", "(", "self", ".", "_data", ",", "ui", ")", ")" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_data.py#L959-L967
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
PyApp_SetMacPreferencesMenuItemId
(*args, **kwargs)
return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)
PyApp_SetMacPreferencesMenuItemId(long val)
PyApp_SetMacPreferencesMenuItemId(long val)
[ "PyApp_SetMacPreferencesMenuItemId", "(", "long", "val", ")" ]
def PyApp_SetMacPreferencesMenuItemId(*args, **kwargs): """PyApp_SetMacPreferencesMenuItemId(long val)""" return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)
[ "def", "PyApp_SetMacPreferencesMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_SetMacPreferencesMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8302-L8304
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/check_ops.py
python
_assert_rank_condition
(x, rank, static_condition, dynamic_condition, data, summarize, name)
return logging_ops.Assert(condition, data, summarize=summarize)
Assert `x` has a rank that satisfies a given condition. Args: x: Numeric `Tensor`. rank: Scalar `Tensor`. static_condition: A python function that takes `[actual_rank, given_rank]` and returns `True` if the condition is satisfied, `False` otherwise. dynamic_condition: An `op` that takes [actual_rank, given_rank] and return `True` if the condition is satisfied, `False` otherwise. data: The tensors to print out if the condition is false. Defaults to error message and first few entries of `x`. summarize: Print this many entries of each tensor. name: A name for this operation (optional). Defaults to "assert_rank_at_least". Returns: Op raising `InvalidArgumentError` if `x` fails dynamic_condition. Raises: ValueError: If static checks determine `x` fails static_condition.
Assert `x` has a rank that satisfies a given condition.
[ "Assert", "x", "has", "a", "rank", "that", "satisfies", "a", "given", "condition", "." ]
def _assert_rank_condition(x, rank, static_condition, dynamic_condition, data, summarize, name): """Assert `x` has a rank that satisfies a given condition. Args: x: Numeric `Tensor`. rank: Scalar `Tensor`. static_condition: A python function that takes `[actual_rank, given_rank]` and returns `True` if the condition is satisfied, `False` otherwise. dynamic_condition: An `op` that takes [actual_rank, given_rank] and return `True` if the condition is satisfied, `False` otherwise. data: The tensors to print out if the condition is false. Defaults to error message and first few entries of `x`. summarize: Print this many entries of each tensor. name: A name for this operation (optional). Defaults to "assert_rank_at_least". Returns: Op raising `InvalidArgumentError` if `x` fails dynamic_condition. Raises: ValueError: If static checks determine `x` fails static_condition. """ with ops.op_scope([x], name, 'assert_rank'): x = ops.convert_to_tensor(x, name='x') rank = ops.convert_to_tensor(rank, name='rank') # Attempt to statically defined rank. x_rank_static = x.get_shape().ndims rank_static = tensor_util.constant_value(rank) assert_type(rank, dtypes.int32) if rank_static is not None: if rank_static.ndim != 0: raise ValueError('Rank must be a scalar') if x_rank_static is not None: if not static_condition(x_rank_static, rank_static): raise ValueError( 'Static rank condition failed', x_rank_static, rank_static) return control_flow_ops.no_op(name='static_checks_determined_all_ok') condition = dynamic_condition(array_ops.rank(x), rank) # Add the condition that `rank` must have rank zero. Prevents the bug where # someone does assert_rank(x, [n]), rather than assert_rank(x, n). if rank_static is None: this_data = ['Rank must be a scalar. Received rank: ', rank] rank_check = assert_rank(rank, 0, data=this_data) condition = control_flow_ops.with_dependencies([rank_check], condition) return logging_ops.Assert(condition, data, summarize=summarize)
[ "def", "_assert_rank_condition", "(", "x", ",", "rank", ",", "static_condition", ",", "dynamic_condition", ",", "data", ",", "summarize", ",", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "x", "]", ",", "name", ",", "'assert_rank'", ")", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ",", "name", "=", "'x'", ")", "rank", "=", "ops", ".", "convert_to_tensor", "(", "rank", ",", "name", "=", "'rank'", ")", "# Attempt to statically defined rank.", "x_rank_static", "=", "x", ".", "get_shape", "(", ")", ".", "ndims", "rank_static", "=", "tensor_util", ".", "constant_value", "(", "rank", ")", "assert_type", "(", "rank", ",", "dtypes", ".", "int32", ")", "if", "rank_static", "is", "not", "None", ":", "if", "rank_static", ".", "ndim", "!=", "0", ":", "raise", "ValueError", "(", "'Rank must be a scalar'", ")", "if", "x_rank_static", "is", "not", "None", ":", "if", "not", "static_condition", "(", "x_rank_static", ",", "rank_static", ")", ":", "raise", "ValueError", "(", "'Static rank condition failed'", ",", "x_rank_static", ",", "rank_static", ")", "return", "control_flow_ops", ".", "no_op", "(", "name", "=", "'static_checks_determined_all_ok'", ")", "condition", "=", "dynamic_condition", "(", "array_ops", ".", "rank", "(", "x", ")", ",", "rank", ")", "# Add the condition that `rank` must have rank zero. Prevents the bug where", "# someone does assert_rank(x, [n]), rather than assert_rank(x, n).", "if", "rank_static", "is", "None", ":", "this_data", "=", "[", "'Rank must be a scalar. Received rank: '", ",", "rank", "]", "rank_check", "=", "assert_rank", "(", "rank", ",", "0", ",", "data", "=", "this_data", ")", "condition", "=", "control_flow_ops", ".", "with_dependencies", "(", "[", "rank_check", "]", ",", "condition", ")", "return", "logging_ops", ".", "Assert", "(", "condition", ",", "data", ",", "summarize", "=", "summarize", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/check_ops.py#L403-L455
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/graph_editor/util.py
python
ControlOutputs.__init__
(self, graph)
Create a dictionary of control-output dependencies. Args: graph: a tf.Graph. Returns: A dictionary where a key is a tf.Operation instance and the corresponding value is a list of all the ops which have the key as one of their control-input dependencies. Raises: TypeError: graph is not a tf.Graph.
Create a dictionary of control-output dependencies.
[ "Create", "a", "dictionary", "of", "control", "-", "output", "dependencies", "." ]
def __init__(self, graph): """Create a dictionary of control-output dependencies. Args: graph: a tf.Graph. Returns: A dictionary where a key is a tf.Operation instance and the corresponding value is a list of all the ops which have the key as one of their control-input dependencies. Raises: TypeError: graph is not a tf.Graph. """ if not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(graph))) self._control_outputs = {} self._graph = graph self._version = None self._build()
[ "def", "__init__", "(", "self", ",", "graph", ")", ":", "if", "not", "isinstance", "(", "graph", ",", "tf_ops", ".", "Graph", ")", ":", "raise", "TypeError", "(", "\"Expected a tf.Graph, got: {}\"", ".", "format", "(", "type", "(", "graph", ")", ")", ")", "self", ".", "_control_outputs", "=", "{", "}", "self", ".", "_graph", "=", "graph", "self", ".", "_version", "=", "None", "self", ".", "_build", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/util.py#L235-L252
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site.py
python
setquit
()
Define new builtins 'quit' and 'exit'. These are objects which make the interpreter exit when called. The repr of each object contains a hint at how it works.
Define new builtins 'quit' and 'exit'.
[ "Define", "new", "builtins", "quit", "and", "exit", "." ]
def setquit(): """Define new builtins 'quit' and 'exit'. These are objects which make the interpreter exit when called. The repr of each object contains a hint at how it works. """ if os.sep == ':': eof = 'Cmd-Q' elif os.sep == '\\': eof = 'Ctrl-Z plus Return' else: eof = 'Ctrl-D (i.e. EOF)' class Quitter(object): def __init__(self, name): self.name = name def __repr__(self): return 'Use %s() or %s to exit' % (self.name, eof) def __call__(self, code=None): # Shells like IDLE catch the SystemExit, but listen when their # stdin wrapper is closed. try: sys.stdin.close() except: pass raise SystemExit(code) __builtin__.quit = Quitter('quit') __builtin__.exit = Quitter('exit')
[ "def", "setquit", "(", ")", ":", "if", "os", ".", "sep", "==", "':'", ":", "eof", "=", "'Cmd-Q'", "elif", "os", ".", "sep", "==", "'\\\\'", ":", "eof", "=", "'Ctrl-Z plus Return'", "else", ":", "eof", "=", "'Ctrl-D (i.e. EOF)'", "class", "Quitter", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "name", ")", ":", "self", ".", "name", "=", "name", "def", "__repr__", "(", "self", ")", ":", "return", "'Use %s() or %s to exit'", "%", "(", "self", ".", "name", ",", "eof", ")", "def", "__call__", "(", "self", ",", "code", "=", "None", ")", ":", "# Shells like IDLE catch the SystemExit, but listen when their", "# stdin wrapper is closed.", "try", ":", "sys", ".", "stdin", ".", "close", "(", ")", "except", ":", "pass", "raise", "SystemExit", "(", "code", ")", "__builtin__", ".", "quit", "=", "Quitter", "(", "'quit'", ")", "__builtin__", ".", "exit", "=", "Quitter", "(", "'exit'", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site.py#L334-L362
llvm-mirror/libcxx
78d6a7767ed57b50122a161b91f59f19c9bd0d19
utils/google-benchmark/tools/gbench/util.py
python
load_benchmark_results
(fname)
Read benchmark output from a file and return the JSON object. REQUIRES: 'fname' names a file containing JSON benchmark output.
Read benchmark output from a file and return the JSON object. REQUIRES: 'fname' names a file containing JSON benchmark output.
[ "Read", "benchmark", "output", "from", "a", "file", "and", "return", "the", "JSON", "object", ".", "REQUIRES", ":", "fname", "names", "a", "file", "containing", "JSON", "benchmark", "output", "." ]
def load_benchmark_results(fname): """ Read benchmark output from a file and return the JSON object. REQUIRES: 'fname' names a file containing JSON benchmark output. """ with open(fname, 'r') as f: return json.load(f)
[ "def", "load_benchmark_results", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "return", "json", ".", "load", "(", "f", ")" ]
https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/utils/google-benchmark/tools/gbench/util.py#L113-L119
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetLibFlags
(self, config, gyp_to_build_path)
return libflags
Returns the flags that need to be added to lib commands.
Returns the flags that need to be added to lib commands.
[ "Returns", "the", "flags", "that", "need", "to", "be", "added", "to", "lib", "commands", "." ]
def GetLibFlags(self, config, gyp_to_build_path): """Returns the flags that need to be added to lib commands.""" config = self._RealConfig(config) libflags = [] lib = self._GetWrapper(self, self.msvs_settings[config], 'VCLibrarianTool', append=libflags) libflags.extend(self._GetAdditionalLibraryDirectories( 'VCLibrarianTool', config, gyp_to_build_path)) lib('AdditionalOptions') return libflags
[ "def", "GetLibFlags", "(", "self", ",", "config", ",", "gyp_to_build_path", ")", ":", "config", "=", "self", ".", "_RealConfig", "(", "config", ")", "libflags", "=", "[", "]", "lib", "=", "self", ".", "_GetWrapper", "(", "self", ",", "self", ".", "msvs_settings", "[", "config", "]", ",", "'VCLibrarianTool'", ",", "append", "=", "libflags", ")", "libflags", ".", "extend", "(", "self", ".", "_GetAdditionalLibraryDirectories", "(", "'VCLibrarianTool'", ",", "config", ",", "gyp_to_build_path", ")", ")", "lib", "(", "'AdditionalOptions'", ")", "return", "libflags" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/msvs_emulation.py#L351-L360
MicBosi/VisualizationLibrary
d2a0e321288152008957e29a0bc270ad192f75be
src/external/freetype/src/tools/docmaker/content.py
python
ContentProcessor.add_markup
( self )
add a new markup section
add a new markup section
[ "add", "a", "new", "markup", "section" ]
def add_markup( self ): """add a new markup section""" if self.markup and self.markup_lines: # get rid of last line of markup if it's empty marks = self.markup_lines if len( marks ) > 0 and not string.strip( marks[-1] ): self.markup_lines = marks[:-1] m = DocMarkup( self.markup, self.markup_lines ) self.markups.append( m ) self.markup = None self.markup_lines = []
[ "def", "add_markup", "(", "self", ")", ":", "if", "self", ".", "markup", "and", "self", ".", "markup_lines", ":", "# get rid of last line of markup if it's empty", "marks", "=", "self", ".", "markup_lines", "if", "len", "(", "marks", ")", ">", "0", "and", "not", "string", ".", "strip", "(", "marks", "[", "-", "1", "]", ")", ":", "self", ".", "markup_lines", "=", "marks", "[", ":", "-", "1", "]", "m", "=", "DocMarkup", "(", "self", ".", "markup", ",", "self", ".", "markup_lines", ")", "self", ".", "markups", ".", "append", "(", "m", ")", "self", ".", "markup", "=", "None", "self", ".", "markup_lines", "=", "[", "]" ]
https://github.com/MicBosi/VisualizationLibrary/blob/d2a0e321288152008957e29a0bc270ad192f75be/src/external/freetype/src/tools/docmaker/content.py#L373-L387
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showbase/PythonUtil.py
python
listToItem2index
(L)
return d
converts list to dict of list item->list index This is lossy if there are duplicate list items
converts list to dict of list item->list index This is lossy if there are duplicate list items
[ "converts", "list", "to", "dict", "of", "list", "item", "-", ">", "list", "index", "This", "is", "lossy", "if", "there", "are", "duplicate", "list", "items" ]
def listToItem2index(L): """converts list to dict of list item->list index This is lossy if there are duplicate list items""" d = {} for i, item in enumerate(L): d[item] = i return d
[ "def", "listToItem2index", "(", "L", ")", ":", "d", "=", "{", "}", "for", "i", ",", "item", "in", "enumerate", "(", "L", ")", ":", "d", "[", "item", "]", "=", "i", "return", "d" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/PythonUtil.py#L389-L395
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py
python
StreamHandler.flush
(self)
Flushes the stream.
Flushes the stream.
[ "Flushes", "the", "stream", "." ]
def flush(self): """ Flushes the stream. """ self.acquire() try: if self.stream and hasattr(self.stream, "flush"): self.stream.flush() finally: self.release()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "stream", "and", "hasattr", "(", "self", ".", "stream", ",", "\"flush\"", ")", ":", "self", ".", "stream", ".", "flush", "(", ")", "finally", ":", "self", ".", "release", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L828-L837
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/mox.py
python
MockAnything._Replay
(self)
Start replaying expected method calls.
Start replaying expected method calls.
[ "Start", "replaying", "expected", "method", "calls", "." ]
def _Replay(self): """Start replaying expected method calls.""" self._replay_mode = True
[ "def", "_Replay", "(", "self", ")", ":", "self", ".", "_replay_mode", "=", "True" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/mox.py#L326-L329
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/tools/clang/tools/scan-build-py/libear/__init__.py
python
Toolset.add_definitions
(self, defines)
part of public interface
part of public interface
[ "part", "of", "public", "interface" ]
def add_definitions(self, defines): """ part of public interface """ self.c_flags.extend(defines)
[ "def", "add_definitions", "(", "self", ",", "defines", ")", ":", "self", ".", "c_flags", ".", "extend", "(", "defines", ")" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/tools/scan-build-py/libear/__init__.py#L94-L96
dmlc/dmlc-core
20ec5bee3a655e8d66e50e3abf7ab5c35ea028fe
tracker/dmlc_tracker/opts.py
python
get_cache_file_set
(args)
return fset, cmds
Get the list of files to be cached. Parameters ---------- args: ArgumentParser.Argument The arguments returned by the parser. Returns ------- cache_file_set: set of str The set of files to be cached to local execution environment. command: list of str The commands that get rewritten after the file cache is used.
Get the list of files to be cached.
[ "Get", "the", "list", "of", "files", "to", "be", "cached", "." ]
def get_cache_file_set(args): """Get the list of files to be cached. Parameters ---------- args: ArgumentParser.Argument The arguments returned by the parser. Returns ------- cache_file_set: set of str The set of files to be cached to local execution environment. command: list of str The commands that get rewritten after the file cache is used. """ fset = set() cmds = [] if args.auto_file_cache: for i in range(len(args.command)): fname = args.command[i] if os.path.exists(fname): fset.add(fname) cmds.append('./' + fname.split('/')[-1]) else: cmds.append(fname) for fname in args.files: if os.path.exists(fname): fset.add(fname) return fset, cmds
[ "def", "get_cache_file_set", "(", "args", ")", ":", "fset", "=", "set", "(", ")", "cmds", "=", "[", "]", "if", "args", ".", "auto_file_cache", ":", "for", "i", "in", "range", "(", "len", "(", "args", ".", "command", ")", ")", ":", "fname", "=", "args", ".", "command", "[", "i", "]", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "fset", ".", "add", "(", "fname", ")", "cmds", ".", "append", "(", "'./'", "+", "fname", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "else", ":", "cmds", ".", "append", "(", "fname", ")", "for", "fname", "in", "args", ".", "files", ":", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "fset", ".", "add", "(", "fname", ")", "return", "fset", ",", "cmds" ]
https://github.com/dmlc/dmlc-core/blob/20ec5bee3a655e8d66e50e3abf7ab5c35ea028fe/tracker/dmlc_tracker/opts.py#L6-L36
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/RunDescriptor.py
python
RunList.get_run_list2sum
(self,num_to_sum=None)
return self._run_numbers[:num_to_sum]
Get run numbers of the files to be summed together from the list of defined run numbers
Get run numbers of the files to be summed together from the list of defined run numbers
[ "Get", "run", "numbers", "of", "the", "files", "to", "be", "summed", "together", "from", "the", "list", "of", "defined", "run", "numbers" ]
def get_run_list2sum(self,num_to_sum=None): """Get run numbers of the files to be summed together from the list of defined run numbers """ n_runs = len(self._run_numbers) if num_to_sum: if num_to_sum <= 0: num_to_sum = 1 if num_to_sum > n_runs: num_to_sum = n_runs else: num_to_sum = n_runs if self._last_ind2sum >= 0 and self._last_ind2sum < num_to_sum: num_to_sum = self._last_ind2sum + 1 return self._run_numbers[:num_to_sum]
[ "def", "get_run_list2sum", "(", "self", ",", "num_to_sum", "=", "None", ")", ":", "n_runs", "=", "len", "(", "self", ".", "_run_numbers", ")", "if", "num_to_sum", ":", "if", "num_to_sum", "<=", "0", ":", "num_to_sum", "=", "1", "if", "num_to_sum", ">", "n_runs", ":", "num_to_sum", "=", "n_runs", "else", ":", "num_to_sum", "=", "n_runs", "if", "self", ".", "_last_ind2sum", ">=", "0", "and", "self", ".", "_last_ind2sum", "<", "num_to_sum", ":", "num_to_sum", "=", "self", ".", "_last_ind2sum", "+", "1", "return", "self", ".", "_run_numbers", "[", ":", "num_to_sum", "]" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/RunDescriptor.py#L268-L284
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.utime
(self, tarinfo, targetpath)
Set modification time of targetpath according to tarinfo.
Set modification time of targetpath according to tarinfo.
[ "Set", "modification", "time", "of", "targetpath", "according", "to", "tarinfo", "." ]
def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) except EnvironmentError as e: raise ExtractError("could not change modification time")
[ "def", "utime", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "not", "hasattr", "(", "os", ",", "'utime'", ")", ":", "return", "try", ":", "os", ".", "utime", "(", "targetpath", ",", "(", "tarinfo", ".", "mtime", ",", "tarinfo", ".", "mtime", ")", ")", "except", "EnvironmentError", "as", "e", ":", "raise", "ExtractError", "(", "\"could not change modification time\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L4805-L4821
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py
python
FlagValues._AssertValidators
(self, validators)
Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator
Assert if all validators in the list are satisfied.
[ "Assert", "if", "all", "validators", "in", "the", "list", "are", "satisfied", "." ]
def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error, e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e)))
[ "def", "_AssertValidators", "(", "self", ",", "validators", ")", ":", "for", "validator", "in", "sorted", "(", "validators", ",", "key", "=", "lambda", "validator", ":", "validator", ".", "insertion_index", ")", ":", "try", ":", "validator", ".", "Verify", "(", "self", ")", "except", "gflags_validators", ".", "Error", ",", "e", ":", "message", "=", "validator", ".", "PrintFlagsWithValues", "(", "self", ")", "raise", "IllegalFlagValue", "(", "'%s: %s'", "%", "(", "message", ",", "str", "(", "e", ")", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py#L1076-L1093
ARM-software/armnn
5e9965cae1cc6162649910f423ebd86001fc1931
python/pyarmnn/examples/image_classification/example_utils.py
python
unzip_file
(filename: str)
Unzips a file. Args: filename(str): Name of the file Returns: None
Unzips a file.
[ "Unzips", "a", "file", "." ]
def unzip_file(filename: str): """Unzips a file. Args: filename(str): Name of the file Returns: None """ with ZipFile(filename, 'r') as zip_obj: zip_obj.extractall()
[ "def", "unzip_file", "(", "filename", ":", "str", ")", ":", "with", "ZipFile", "(", "filename", ",", "'r'", ")", "as", "zip_obj", ":", "zip_obj", ".", "extractall", "(", ")" ]
https://github.com/ARM-software/armnn/blob/5e9965cae1cc6162649910f423ebd86001fc1931/python/pyarmnn/examples/image_classification/example_utils.py#L47-L57
facebookincubator/fizz
bd0ba1b80f72023cb7ede671a4caa85f6664d3f6
build/fbcode_builder/getdeps/cargo.py
python
CargoBuilder._patchup_workspace
(self)
This method makes some assumptions about the state of the project and its cargo dependendies: 1. Crates from cargo dependencies can be extracted from Cargo.toml files using _extract_crates function. It is using a heuristic so check its code to understand how it is done. 2. The extracted cargo dependencies crates can be found in the dependency's install dir using _resolve_crate_to_path function which again is using a heuristic. Notice that many things might go wrong here. E.g. if someone depends on another getdeps crate by writing in their Cargo.toml file: my-rename-of-crate = { package = "crate", git = "..." } they can count themselves lucky because the code will raise an Exception. There migh be more cases where the code will silently pass producing bad results.
This method makes some assumptions about the state of the project and its cargo dependendies: 1. Crates from cargo dependencies can be extracted from Cargo.toml files using _extract_crates function. It is using a heuristic so check its code to understand how it is done. 2. The extracted cargo dependencies crates can be found in the dependency's install dir using _resolve_crate_to_path function which again is using a heuristic.
[ "This", "method", "makes", "some", "assumptions", "about", "the", "state", "of", "the", "project", "and", "its", "cargo", "dependendies", ":", "1", ".", "Crates", "from", "cargo", "dependencies", "can", "be", "extracted", "from", "Cargo", ".", "toml", "files", "using", "_extract_crates", "function", ".", "It", "is", "using", "a", "heuristic", "so", "check", "its", "code", "to", "understand", "how", "it", "is", "done", ".", "2", ".", "The", "extracted", "cargo", "dependencies", "crates", "can", "be", "found", "in", "the", "dependency", "s", "install", "dir", "using", "_resolve_crate_to_path", "function", "which", "again", "is", "using", "a", "heuristic", "." ]
def _patchup_workspace(self): """ This method makes some assumptions about the state of the project and its cargo dependendies: 1. Crates from cargo dependencies can be extracted from Cargo.toml files using _extract_crates function. It is using a heuristic so check its code to understand how it is done. 2. The extracted cargo dependencies crates can be found in the dependency's install dir using _resolve_crate_to_path function which again is using a heuristic. Notice that many things might go wrong here. E.g. if someone depends on another getdeps crate by writing in their Cargo.toml file: my-rename-of-crate = { package = "crate", git = "..." } they can count themselves lucky because the code will raise an Exception. There migh be more cases where the code will silently pass producing bad results. """ workspace_dir = self.workspace_dir() config = self._resolve_config() if config: with open(os.path.join(workspace_dir, "Cargo.toml"), "r+") as f: manifest_content = f.read() if "[package]" not in manifest_content: # A fake manifest has to be crated to change the virtual # manifest into a non-virtual. The virtual manifests are limited # in many ways and the inability to define patches on them is # one. Check https://github.com/rust-lang/cargo/issues/4934 to # see if it is resolved. f.write( """ [package] name = "fake_manifest_of_{}" version = "0.0.0" [lib] path = "/dev/null" """.format( self.manifest.name ) ) else: f.write("\n") f.write(config)
[ "def", "_patchup_workspace", "(", "self", ")", ":", "workspace_dir", "=", "self", ".", "workspace_dir", "(", ")", "config", "=", "self", ".", "_resolve_config", "(", ")", "if", "config", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "workspace_dir", ",", "\"Cargo.toml\"", ")", ",", "\"r+\"", ")", "as", "f", ":", "manifest_content", "=", "f", ".", "read", "(", ")", "if", "\"[package]\"", "not", "in", "manifest_content", ":", "# A fake manifest has to be crated to change the virtual", "# manifest into a non-virtual. The virtual manifests are limited", "# in many ways and the inability to define patches on them is", "# one. Check https://github.com/rust-lang/cargo/issues/4934 to", "# see if it is resolved.", "f", ".", "write", "(", "\"\"\"\n [package]\n name = \"fake_manifest_of_{}\"\n version = \"0.0.0\"\n [lib]\n path = \"/dev/null\"\n \"\"\"", ".", "format", "(", "self", ".", "manifest", ".", "name", ")", ")", "else", ":", "f", ".", "write", "(", "\"\\n\"", ")", "f", ".", "write", "(", "config", ")" ]
https://github.com/facebookincubator/fizz/blob/bd0ba1b80f72023cb7ede671a4caa85f6664d3f6/build/fbcode_builder/getdeps/cargo.py#L141-L185
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/message.py
python
Message.ListFields
(self)
Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number
Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number
[ "Returns", "a", "list", "of", "(", "FieldDescriptor", "value", ")", "tuples", "for", "all", "fields", "in", "the", "message", "which", "are", "not", "empty", ".", "A", "singular", "field", "is", "non", "-", "empty", "if", "HasField", "()", "would", "return", "true", "and", "a", "repeated", "field", "is", "non", "-", "empty", "if", "it", "contains", "at", "least", "one", "element", ".", "The", "fields", "are", "ordered", "by", "field", "number" ]
def ListFields(self): """Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number""" raise NotImplementedError
[ "def", "ListFields", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/message.py#L226-L232
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/preprocessing/image.py
python
array_to_img
(x, data_format=None, scale=True)
Converts a 3D Numpy array to a PIL Image instance. Arguments: x: Input Numpy array. data_format: Image data format. scale: Whether to rescale image values to be within [0, 255]. Returns: A PIL Image instance. Raises: ImportError: if PIL is not available. ValueError: if invalid `x` or `data_format` is passed.
Converts a 3D Numpy array to a PIL Image instance.
[ "Converts", "a", "3D", "Numpy", "array", "to", "a", "PIL", "Image", "instance", "." ]
def array_to_img(x, data_format=None, scale=True): """Converts a 3D Numpy array to a PIL Image instance. Arguments: x: Input Numpy array. data_format: Image data format. scale: Whether to rescale image values to be within [0, 255]. Returns: A PIL Image instance. Raises: ImportError: if PIL is not available. ValueError: if invalid `x` or `data_format` is passed. """ if pil_image is None: raise ImportError('Could not import PIL.Image. ' 'The use of `array_to_img` requires PIL.') x = np.asarray(x, dtype=K.floatx()) if x.ndim != 3: raise ValueError('Expected image array to have rank 3 (single image). ' 'Got array with shape:', x.shape) if data_format is None: data_format = K.image_data_format() if data_format not in {'channels_first', 'channels_last'}: raise ValueError('Invalid data_format:', data_format) # Original Numpy array x has format (height, width, channel) # or (channel, height, width) # but target PIL image has format (width, height, channel) if data_format == 'channels_first': x = x.transpose(1, 2, 0) if scale: x = x + max(-np.min(x), 0) # pylint: disable=g-no-augmented-assignment x_max = np.max(x) if x_max != 0: x /= x_max x *= 255 if x.shape[2] == 3: # RGB return pil_image.fromarray(x.astype('uint8'), 'RGB') elif x.shape[2] == 1: # grayscale return pil_image.fromarray(x[:, :, 0].astype('uint8'), 'L') else: raise ValueError('Unsupported channel number: ', x.shape[2])
[ "def", "array_to_img", "(", "x", ",", "data_format", "=", "None", ",", "scale", "=", "True", ")", ":", "if", "pil_image", "is", "None", ":", "raise", "ImportError", "(", "'Could not import PIL.Image. '", "'The use of `array_to_img` requires PIL.'", ")", "x", "=", "np", ".", "asarray", "(", "x", ",", "dtype", "=", "K", ".", "floatx", "(", ")", ")", "if", "x", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "'Expected image array to have rank 3 (single image). '", "'Got array with shape:'", ",", "x", ".", "shape", ")", "if", "data_format", "is", "None", ":", "data_format", "=", "K", ".", "image_data_format", "(", ")", "if", "data_format", "not", "in", "{", "'channels_first'", ",", "'channels_last'", "}", ":", "raise", "ValueError", "(", "'Invalid data_format:'", ",", "data_format", ")", "# Original Numpy array x has format (height, width, channel)", "# or (channel, height, width)", "# but target PIL image has format (width, height, channel)", "if", "data_format", "==", "'channels_first'", ":", "x", "=", "x", ".", "transpose", "(", "1", ",", "2", ",", "0", ")", "if", "scale", ":", "x", "=", "x", "+", "max", "(", "-", "np", ".", "min", "(", "x", ")", ",", "0", ")", "# pylint: disable=g-no-augmented-assignment", "x_max", "=", "np", ".", "max", "(", "x", ")", "if", "x_max", "!=", "0", ":", "x", "/=", "x_max", "x", "*=", "255", "if", "x", ".", "shape", "[", "2", "]", "==", "3", ":", "# RGB", "return", "pil_image", ".", "fromarray", "(", "x", ".", "astype", "(", "'uint8'", ")", ",", "'RGB'", ")", "elif", "x", ".", "shape", "[", "2", "]", "==", "1", ":", "# grayscale", "return", "pil_image", ".", "fromarray", "(", "x", "[", ":", ",", ":", ",", "0", "]", ".", "astype", "(", "'uint8'", ")", ",", "'L'", ")", "else", ":", "raise", "ValueError", "(", "'Unsupported channel number: '", ",", "x", ".", "shape", "[", "2", "]", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/preprocessing/image.py#L263-L310
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/schema.py
python
Field.__init__
(self, children)
Derived classes must call this after their initialization.
Derived classes must call this after their initialization.
[ "Derived", "classes", "must", "call", "this", "after", "their", "initialization", "." ]
def __init__(self, children): """Derived classes must call this after their initialization.""" self._parent = (None, 0) offset = 0 self._field_offsets = [] for child in children: self._field_offsets.append(offset) offset += len(child.field_names()) self._field_offsets.append(offset)
[ "def", "__init__", "(", "self", ",", "children", ")", ":", "self", ".", "_parent", "=", "(", "None", ",", "0", ")", "offset", "=", "0", "self", ".", "_field_offsets", "=", "[", "]", "for", "child", "in", "children", ":", "self", ".", "_field_offsets", ".", "append", "(", "offset", ")", "offset", "+=", "len", "(", "child", ".", "field_names", "(", ")", ")", "self", ".", "_field_offsets", ".", "append", "(", "offset", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/schema.py#L105-L113
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/environments/cliff_walking.py
python
Environment._is_goal
(self, pos)
return pos[0] == self._height - 1 and pos[1] == self._width - 1
Check if position is bottom right corner of grid.
Check if position is bottom right corner of grid.
[ "Check", "if", "position", "is", "bottom", "right", "corner", "of", "grid", "." ]
def _is_goal(self, pos): """Check if position is bottom right corner of grid.""" return pos[0] == self._height - 1 and pos[1] == self._width - 1
[ "def", "_is_goal", "(", "self", ",", "pos", ")", ":", "return", "pos", "[", "0", "]", "==", "self", ".", "_height", "-", "1", "and", "pos", "[", "1", "]", "==", "self", ".", "_width", "-", "1" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/environments/cliff_walking.py#L149-L151
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/distutils/ccompiler.py
python
CCompiler._fix_object_args
(self, objects, output_dir)
return (objects, output_dir)
Typecheck and fix up some arguments supplied to various methods. Specifically: ensure that 'objects' is a list; if output_dir is None, replace with self.output_dir. Return fixed versions of 'objects' and 'output_dir'.
Typecheck and fix up some arguments supplied to various methods. Specifically: ensure that 'objects' is a list; if output_dir is None, replace with self.output_dir. Return fixed versions of 'objects' and 'output_dir'.
[ "Typecheck", "and", "fix", "up", "some", "arguments", "supplied", "to", "various", "methods", ".", "Specifically", ":", "ensure", "that", "objects", "is", "a", "list", ";", "if", "output_dir", "is", "None", "replace", "with", "self", ".", "output_dir", ".", "Return", "fixed", "versions", "of", "objects", "and", "output_dir", "." ]
def _fix_object_args (self, objects, output_dir): """Typecheck and fix up some arguments supplied to various methods. Specifically: ensure that 'objects' is a list; if output_dir is None, replace with self.output_dir. Return fixed versions of 'objects' and 'output_dir'. """ if type (objects) not in (ListType, TupleType): raise TypeError, \ "'objects' must be a list or tuple of strings" objects = list (objects) if output_dir is None: output_dir = self.output_dir elif type (output_dir) is not StringType: raise TypeError, "'output_dir' must be a string or None" return (objects, output_dir)
[ "def", "_fix_object_args", "(", "self", ",", "objects", ",", "output_dir", ")", ":", "if", "type", "(", "objects", ")", "not", "in", "(", "ListType", ",", "TupleType", ")", ":", "raise", "TypeError", ",", "\"'objects' must be a list or tuple of strings\"", "objects", "=", "list", "(", "objects", ")", "if", "output_dir", "is", "None", ":", "output_dir", "=", "self", ".", "output_dir", "elif", "type", "(", "output_dir", ")", "is", "not", "StringType", ":", "raise", "TypeError", ",", "\"'output_dir' must be a string or None\"", "return", "(", "objects", ",", "output_dir", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/ccompiler.py#L442-L458
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pytree.py
python
Leaf.clone
(self)
return Leaf(self.type, self.value, (self.prefix, (self.lineno, self.column)), fixers_applied=self.fixers_applied)
Return a cloned (deep) copy of self.
Return a cloned (deep) copy of self.
[ "Return", "a", "cloned", "(", "deep", ")", "copy", "of", "self", "." ]
def clone(self): """Return a cloned (deep) copy of self.""" return Leaf(self.type, self.value, (self.prefix, (self.lineno, self.column)), fixers_applied=self.fixers_applied)
[ "def", "clone", "(", "self", ")", ":", "return", "Leaf", "(", "self", ".", "type", ",", "self", ".", "value", ",", "(", "self", ".", "prefix", ",", "(", "self", ".", "lineno", ",", "self", ".", "column", ")", ")", ",", "fixers_applied", "=", "self", ".", "fixers_applied", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pytree.py#L400-L404
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
TextAttr.IsParagraphStyle
(*args, **kwargs)
return _controls_.TextAttr_IsParagraphStyle(*args, **kwargs)
IsParagraphStyle(self) -> bool
IsParagraphStyle(self) -> bool
[ "IsParagraphStyle", "(", "self", ")", "-", ">", "bool" ]
def IsParagraphStyle(*args, **kwargs): """IsParagraphStyle(self) -> bool""" return _controls_.TextAttr_IsParagraphStyle(*args, **kwargs)
[ "def", "IsParagraphStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_IsParagraphStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1904-L1906
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/count-vowel-substrings-of-a-string.py
python
Solution.countVowelSubstrings
(self, word)
return atLeastK(word, k)
:type word: str :rtype: int
:type word: str :rtype: int
[ ":", "type", "word", ":", "str", ":", "rtype", ":", "int" ]
def countVowelSubstrings(self, word): """ :type word: str :rtype: int """ VOWELS = set("aeiou") k = 5 def atLeastK(word, k): cnt = collections.Counter() result = left = right = 0 for i, c in enumerate(word): if c not in VOWELS: cnt = collections.Counter() left = right = i+1 continue cnt[c] += 1 while len(cnt) > k-1: cnt[word[right]] -= 1 if not cnt[word[right]]: del cnt[word[right]] right += 1 result += right-left return result return atLeastK(word, k)
[ "def", "countVowelSubstrings", "(", "self", ",", "word", ")", ":", "VOWELS", "=", "set", "(", "\"aeiou\"", ")", "k", "=", "5", "def", "atLeastK", "(", "word", ",", "k", ")", ":", "cnt", "=", "collections", ".", "Counter", "(", ")", "result", "=", "left", "=", "right", "=", "0", "for", "i", ",", "c", "in", "enumerate", "(", "word", ")", ":", "if", "c", "not", "in", "VOWELS", ":", "cnt", "=", "collections", ".", "Counter", "(", ")", "left", "=", "right", "=", "i", "+", "1", "continue", "cnt", "[", "c", "]", "+=", "1", "while", "len", "(", "cnt", ")", ">", "k", "-", "1", ":", "cnt", "[", "word", "[", "right", "]", "]", "-=", "1", "if", "not", "cnt", "[", "word", "[", "right", "]", "]", ":", "del", "cnt", "[", "word", "[", "right", "]", "]", "right", "+=", "1", "result", "+=", "right", "-", "left", "return", "result", "return", "atLeastK", "(", "word", ",", "k", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/count-vowel-substrings-of-a-string.py#L8-L32
niwinz/phantompy
ae25ddb6791e13cb7c35126971c410030ee5dfda
phantompy/context.py
python
Context.process_events
(self, timeout=200)
Method like a `time.sleep` but while waiths a timeout process qt events.
Method like a `time.sleep` but while waiths a timeout process qt events.
[ "Method", "like", "a", "time", ".", "sleep", "but", "while", "waiths", "a", "timeout", "process", "qt", "events", "." ]
def process_events(self, timeout=200): """ Method like a `time.sleep` but while waiths a timeout process qt events. """ lib.ph_context_process_events(timeout)
[ "def", "process_events", "(", "self", ",", "timeout", "=", "200", ")", ":", "lib", ".", "ph_context_process_events", "(", "timeout", ")" ]
https://github.com/niwinz/phantompy/blob/ae25ddb6791e13cb7c35126971c410030ee5dfda/phantompy/context.py#L98-L104
bingwin/MicroChat
81d9a71a212c1cbca5bba497ec42659a7d25dccf
mars/lint/cpplint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "r'\\\"'", ")", "-", "line", ".", "count", "(", "\"'\\\"'\"", ")", ")", "&", "1", ")", "==", "1" ]
https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L1152-L1166
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/controls/InputState.py
python
InputState.debugPrint
(self, message)
return self.notify.debug( "%s (%s) %s"%(id(self), len(self._state), message))
for debugging
for debugging
[ "for", "debugging" ]
def debugPrint(self, message): """for debugging""" return self.notify.debug( "%s (%s) %s"%(id(self), len(self._state), message))
[ "def", "debugPrint", "(", "self", ",", "message", ")", ":", "return", "self", ".", "notify", ".", "debug", "(", "\"%s (%s) %s\"", "%", "(", "id", "(", "self", ")", ",", "len", "(", "self", ".", "_state", ")", ",", "message", ")", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/controls/InputState.py#L244-L247
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/msvccompiler.py
python
get_build_architecture
()
return sys.version[i+len(prefix):j]
Return the processor architecture. Possible results are "Intel" or "AMD64".
Return the processor architecture.
[ "Return", "the", "processor", "architecture", "." ]
def get_build_architecture(): """Return the processor architecture. Possible results are "Intel" or "AMD64". """ prefix = " bit (" i = sys.version.find(prefix) if i == -1: return "Intel" j = sys.version.find(")", i) return sys.version[i+len(prefix):j]
[ "def", "get_build_architecture", "(", ")", ":", "prefix", "=", "\" bit (\"", "i", "=", "sys", ".", "version", ".", "find", "(", "prefix", ")", "if", "i", "==", "-", "1", ":", "return", "\"Intel\"", "j", "=", "sys", ".", "version", ".", "find", "(", "\")\"", ",", "i", ")", "return", "sys", ".", "version", "[", "i", "+", "len", "(", "prefix", ")", ":", "j", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/msvccompiler.py#L172-L183
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/distributions/python/ops/bijectors/sinh_arcsinh_impl.py
python
SinhArcsinh.tailweight
(self)
return self._tailweight
The `tailweight` in: `Y = Sinh((Arcsinh(X) + skewness) * tailweight)`.
The `tailweight` in: `Y = Sinh((Arcsinh(X) + skewness) * tailweight)`.
[ "The", "tailweight", "in", ":", "Y", "=", "Sinh", "((", "Arcsinh", "(", "X", ")", "+", "skewness", ")", "*", "tailweight", ")", "." ]
def tailweight(self): """The `tailweight` in: `Y = Sinh((Arcsinh(X) + skewness) * tailweight)`.""" return self._tailweight
[ "def", "tailweight", "(", "self", ")", ":", "return", "self", ".", "_tailweight" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/bijectors/sinh_arcsinh_impl.py#L112-L114
BSVino/DoubleAction
c550b168a3e919926c198c30240f506538b92e75
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/encoder.py
python
_SignedVarintEncoder
()
return EncodeSignedVarint
Return an encoder for a basic signed varint value (does not include tag).
Return an encoder for a basic signed varint value (does not include tag).
[ "Return", "an", "encoder", "for", "a", "basic", "signed", "varint", "value", "(", "does", "not", "include", "tag", ")", "." ]
def _SignedVarintEncoder(): """Return an encoder for a basic signed varint value (does not include tag).""" local_chr = chr def EncodeSignedVarint(write, value): if value < 0: value += (1 << 64) bits = value & 0x7f value >>= 7 while value: write(local_chr(0x80|bits)) bits = value & 0x7f value >>= 7 return write(local_chr(bits)) return EncodeSignedVarint
[ "def", "_SignedVarintEncoder", "(", ")", ":", "local_chr", "=", "chr", "def", "EncodeSignedVarint", "(", "write", ",", "value", ")", ":", "if", "value", "<", "0", ":", "value", "+=", "(", "1", "<<", "64", ")", "bits", "=", "value", "&", "0x7f", "value", ">>=", "7", "while", "value", ":", "write", "(", "local_chr", "(", "0x80", "|", "bits", ")", ")", "bits", "=", "value", "&", "0x7f", "value", ">>=", "7", "return", "write", "(", "local_chr", "(", "bits", ")", ")", "return", "EncodeSignedVarint" ]
https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/encoder.py#L350-L366
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/yapf/yapf/yapflib/pytree_visitor.py
python
DumpPyTree
(tree, target_stream=sys.stdout)
Convenience function for dumping a given pytree. This function presents a very minimal interface. For more configurability (for example, controlling how specific node types are displayed), use PyTreeDumper directly. Arguments: tree: the tree to dump. target_stream: the stream to dump the tree to. A file-like object. By default will dump into stdout.
Convenience function for dumping a given pytree.
[ "Convenience", "function", "for", "dumping", "a", "given", "pytree", "." ]
def DumpPyTree(tree, target_stream=sys.stdout): """Convenience function for dumping a given pytree. This function presents a very minimal interface. For more configurability (for example, controlling how specific node types are displayed), use PyTreeDumper directly. Arguments: tree: the tree to dump. target_stream: the stream to dump the tree to. A file-like object. By default will dump into stdout. """ dumper = PyTreeDumper(target_stream) dumper.Visit(tree)
[ "def", "DumpPyTree", "(", "tree", ",", "target_stream", "=", "sys", ".", "stdout", ")", ":", "dumper", "=", "PyTreeDumper", "(", "target_stream", ")", "dumper", ".", "Visit", "(", "tree", ")" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/pytree_visitor.py#L91-L104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Point2D.GetDotProduct
(*args, **kwargs)
return _core_.Point2D_GetDotProduct(*args, **kwargs)
GetDotProduct(self, Point2D vec) -> double
GetDotProduct(self, Point2D vec) -> double
[ "GetDotProduct", "(", "self", "Point2D", "vec", ")", "-", ">", "double" ]
def GetDotProduct(*args, **kwargs): """GetDotProduct(self, Point2D vec) -> double""" return _core_.Point2D_GetDotProduct(*args, **kwargs)
[ "def", "GetDotProduct", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Point2D_GetDotProduct", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1702-L1704
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
GIFHandler.__init__
(self, *args, **kwargs)
__init__(self) -> GIFHandler A `wx.ImageHandler` for GIF image files.
__init__(self) -> GIFHandler
[ "__init__", "(", "self", ")", "-", ">", "GIFHandler" ]
def __init__(self, *args, **kwargs): """ __init__(self) -> GIFHandler A `wx.ImageHandler` for GIF image files. """ _core_.GIFHandler_swiginit(self,_core_.new_GIFHandler(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "GIFHandler_swiginit", "(", "self", ",", "_core_", ".", "new_GIFHandler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3992-L3998
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/binder.py
python
_bind_expression
(expr, allow_literal_string=True)
return None
Bind an expression.
Bind an expression.
[ "Bind", "an", "expression", "." ]
def _bind_expression(expr, allow_literal_string=True): # type: (syntax.Expression, bool) -> ast.Expression """Bind an expression.""" node = ast.Expression(expr.file_name, expr.line, expr.column) if expr.literal is None: node.expr = expr.expr node.validate_constexpr = expr.is_constexpr node.export = expr.is_constexpr return node node.validate_constexpr = False node.export = True # bool if (expr.literal == "true") or (expr.literal == "false"): node.expr = expr.literal return node # int32_t try: intval = int(expr.literal) if intval >= -0x80000000 and intval <= 0x7FFFFFFF: # pylint: disable=chained-comparison node.expr = repr(intval) return node except ValueError: pass # float try: node.expr = repr(float(expr.literal)) return node except ValueError: pass # std::string if allow_literal_string: strval = expr.literal for i in ['\\', '"', "'"]: if i in strval: strval = strval.replace(i, '\\' + i) node.expr = '"' + strval + '"' return node # Unable to bind expression. return None
[ "def", "_bind_expression", "(", "expr", ",", "allow_literal_string", "=", "True", ")", ":", "# type: (syntax.Expression, bool) -> ast.Expression", "node", "=", "ast", ".", "Expression", "(", "expr", ".", "file_name", ",", "expr", ".", "line", ",", "expr", ".", "column", ")", "if", "expr", ".", "literal", "is", "None", ":", "node", ".", "expr", "=", "expr", ".", "expr", "node", ".", "validate_constexpr", "=", "expr", ".", "is_constexpr", "node", ".", "export", "=", "expr", ".", "is_constexpr", "return", "node", "node", ".", "validate_constexpr", "=", "False", "node", ".", "export", "=", "True", "# bool", "if", "(", "expr", ".", "literal", "==", "\"true\"", ")", "or", "(", "expr", ".", "literal", "==", "\"false\"", ")", ":", "node", ".", "expr", "=", "expr", ".", "literal", "return", "node", "# int32_t", "try", ":", "intval", "=", "int", "(", "expr", ".", "literal", ")", "if", "intval", ">=", "-", "0x80000000", "and", "intval", "<=", "0x7FFFFFFF", ":", "# pylint: disable=chained-comparison", "node", ".", "expr", "=", "repr", "(", "intval", ")", "return", "node", "except", "ValueError", ":", "pass", "# float", "try", ":", "node", ".", "expr", "=", "repr", "(", "float", "(", "expr", ".", "literal", ")", ")", "return", "node", "except", "ValueError", ":", "pass", "# std::string", "if", "allow_literal_string", ":", "strval", "=", "expr", ".", "literal", "for", "i", "in", "[", "'\\\\'", ",", "'\"'", ",", "\"'\"", "]", ":", "if", "i", "in", "strval", ":", "strval", "=", "strval", ".", "replace", "(", "i", ",", "'\\\\'", "+", "i", ")", "node", ".", "expr", "=", "'\"'", "+", "strval", "+", "'\"'", "return", "node", "# Unable to bind expression.", "return", "None" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/binder.py#L864-L909
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
StaticBitmap_GetClassDefaultAttributes
(*args, **kwargs)
return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs)
StaticBitmap_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
StaticBitmap_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "StaticBitmap_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def StaticBitmap_GetClassDefaultAttributes(*args, **kwargs): """ StaticBitmap_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "StaticBitmap_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "StaticBitmap_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L1125-L1140
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge2.py
python
ExodusModel._get_local_index
(self, this_id, id_list, entity='entity')
return id_list.index(this_id)
Return the local index corresponding to the given id. If an entity is not present, throw an error. Example: >>> model._get_local_index(10, [10, 20, 30]) 0 >>> model._get_local_index('first', [10, 20, 30]) 10
Return the local index corresponding to the given id.
[ "Return", "the", "local", "index", "corresponding", "to", "the", "given", "id", "." ]
def _get_local_index(self, this_id, id_list, entity='entity'): """ Return the local index corresponding to the given id. If an entity is not present, throw an error. Example: >>> model._get_local_index(10, [10, 20, 30]) 0 >>> model._get_local_index('first', [10, 20, 30]) 10 """ if this_id == 'first': if not id_list: self._error('Undefined %s reference.' % entity, 'A reference to the first %s was encountered but ' 'no %ss are defined.' % (entity, entity)) return 0 if this_id == 'last': if not id_list: self._error('Undefined %s reference.' % entity, 'A reference to the last %s was encountered but ' 'no %ss are defined.' % (entity, entity)) return len(id_list) - 1 if this_id not in id_list: entity_list = ', '.join([str(x) for x in id_list]) self._error('Reference to undefined %s.' % entity, 'A reference to %s "%s" was encountered but is not ' 'defined in the model. There are %d defined %ss: %s' % (entity, str(this_id), len(id_list), entity, entity_list)) return id_list.index(this_id)
[ "def", "_get_local_index", "(", "self", ",", "this_id", ",", "id_list", ",", "entity", "=", "'entity'", ")", ":", "if", "this_id", "==", "'first'", ":", "if", "not", "id_list", ":", "self", ".", "_error", "(", "'Undefined %s reference.'", "%", "entity", ",", "'A reference to the first %s was encountered but '", "'no %ss are defined.'", "%", "(", "entity", ",", "entity", ")", ")", "return", "0", "if", "this_id", "==", "'last'", ":", "if", "not", "id_list", ":", "self", ".", "_error", "(", "'Undefined %s reference.'", "%", "entity", ",", "'A reference to the last %s was encountered but '", "'no %ss are defined.'", "%", "(", "entity", ",", "entity", ")", ")", "return", "len", "(", "id_list", ")", "-", "1", "if", "this_id", "not", "in", "id_list", ":", "entity_list", "=", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "id_list", "]", ")", "self", ".", "_error", "(", "'Reference to undefined %s.'", "%", "entity", ",", "'A reference to %s \"%s\" was encountered but is not '", "'defined in the model. There are %d defined %ss: %s'", "%", "(", "entity", ",", "str", "(", "this_id", ")", ",", "len", "(", "id_list", ")", ",", "entity", ",", "entity_list", ")", ")", "return", "id_list", ".", "index", "(", "this_id", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L3086-L3118
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
third_party/gpus/find_cuda_config.py
python
_library_paths
()
return [ "", "lib64", "lib", "lib/*-linux-gnu", "lib/x64", "extras/CUPTI/*", "local/cuda/lib64", "local/cuda/extras/CUPTI/lib64", ]
Returns hard-coded set of relative paths to look for library files.
Returns hard-coded set of relative paths to look for library files.
[ "Returns", "hard", "-", "coded", "set", "of", "relative", "paths", "to", "look", "for", "library", "files", "." ]
def _library_paths(): """Returns hard-coded set of relative paths to look for library files.""" return [ "", "lib64", "lib", "lib/*-linux-gnu", "lib/x64", "extras/CUPTI/*", "local/cuda/lib64", "local/cuda/extras/CUPTI/lib64", ]
[ "def", "_library_paths", "(", ")", ":", "return", "[", "\"\"", ",", "\"lib64\"", ",", "\"lib\"", ",", "\"lib/*-linux-gnu\"", ",", "\"lib/x64\"", ",", "\"extras/CUPTI/*\"", ",", "\"local/cuda/lib64\"", ",", "\"local/cuda/extras/CUPTI/lib64\"", ",", "]" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/third_party/gpus/find_cuda_config.py#L170-L181
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/type.py
python
base
(type)
return __types[type]['base']
Returns a base type for the given type or nothing in case the given type is not derived.
Returns a base type for the given type or nothing in case the given type is not derived.
[ "Returns", "a", "base", "type", "for", "the", "given", "type", "or", "nothing", "in", "case", "the", "given", "type", "is", "not", "derived", "." ]
def base(type): """Returns a base type for the given type or nothing in case the given type is not derived.""" assert isinstance(type, basestring) return __types[type]['base']
[ "def", "base", "(", "type", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "return", "__types", "[", "type", "]", "[", "'base'", "]" ]
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/type.py#L175-L179
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
PyDataViewCustomRenderer.Activate
(*args, **kwargs)
return _dataview.PyDataViewCustomRenderer_Activate(*args, **kwargs)
Activate(self, Rect cell, DataViewModel model, DataViewItem item, unsigned int col) -> bool Override this to react to double clicks or <ENTER>.
Activate(self, Rect cell, DataViewModel model, DataViewItem item, unsigned int col) -> bool
[ "Activate", "(", "self", "Rect", "cell", "DataViewModel", "model", "DataViewItem", "item", "unsigned", "int", "col", ")", "-", ">", "bool" ]
def Activate(*args, **kwargs): """ Activate(self, Rect cell, DataViewModel model, DataViewItem item, unsigned int col) -> bool Override this to react to double clicks or <ENTER>. """ return _dataview.PyDataViewCustomRenderer_Activate(*args, **kwargs)
[ "def", "Activate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "PyDataViewCustomRenderer_Activate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L1475-L1482
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/probability/distributions/negative_binomial.py
python
NegativeBinomial.logit
(self)
return prob2logit(self.prob, True)
Get the log-odds of sampling `1`. Returns ------- Tensor Parameter tensor.
Get the log-odds of sampling `1`.
[ "Get", "the", "log", "-", "odds", "of", "sampling", "1", "." ]
def logit(self): """Get the log-odds of sampling `1`. Returns ------- Tensor Parameter tensor. """ # pylint: disable=method-hidden return prob2logit(self.prob, True)
[ "def", "logit", "(", "self", ")", ":", "# pylint: disable=method-hidden", "return", "prob2logit", "(", "self", ".", "prob", ",", "True", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/negative_binomial.py#L78-L87
google/fhir
d77f57706c1a168529b0b87ca7ccb1c0113e83c2
py/google/fhir/utils/proto_utils.py
python
are_same_message_type
(descriptor_a: descriptor.Descriptor, descriptor_b: descriptor.Descriptor)
return (descriptor_a == descriptor_b or descriptor_a.full_name == descriptor_b.full_name)
Returns True if descriptor_a is the same type as descriptor_b.
Returns True if descriptor_a is the same type as descriptor_b.
[ "Returns", "True", "if", "descriptor_a", "is", "the", "same", "type", "as", "descriptor_b", "." ]
def are_same_message_type(descriptor_a: descriptor.Descriptor, descriptor_b: descriptor.Descriptor) -> bool: """Returns True if descriptor_a is the same type as descriptor_b.""" return (descriptor_a == descriptor_b or descriptor_a.full_name == descriptor_b.full_name)
[ "def", "are_same_message_type", "(", "descriptor_a", ":", "descriptor", ".", "Descriptor", ",", "descriptor_b", ":", "descriptor", ".", "Descriptor", ")", "->", "bool", ":", "return", "(", "descriptor_a", "==", "descriptor_b", "or", "descriptor_a", ".", "full_name", "==", "descriptor_b", ".", "full_name", ")" ]
https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/utils/proto_utils.py#L38-L42
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/utils/check_cfc/check_cfc.py
python
replace_output_file
(args, new_name)
return args
Replaces the specified name of an output file with the specified name. Assumes that the output file name is specified in the command line args.
Replaces the specified name of an output file with the specified name. Assumes that the output file name is specified in the command line args.
[ "Replaces", "the", "specified", "name", "of", "an", "output", "file", "with", "the", "specified", "name", ".", "Assumes", "that", "the", "output", "file", "name", "is", "specified", "in", "the", "command", "line", "args", "." ]
def replace_output_file(args, new_name): """Replaces the specified name of an output file with the specified name. Assumes that the output file name is specified in the command line args.""" replaceidx = None attached = False for idx, val in enumerate(args): if val == '-o': replaceidx = idx + 1 attached = False elif val.startswith('-o'): replaceidx = idx attached = True if replaceidx is None: raise Exception replacement = new_name if attached == True: replacement = '-o' + new_name args[replaceidx] = replacement return args
[ "def", "replace_output_file", "(", "args", ",", "new_name", ")", ":", "replaceidx", "=", "None", "attached", "=", "False", "for", "idx", ",", "val", "in", "enumerate", "(", "args", ")", ":", "if", "val", "==", "'-o'", ":", "replaceidx", "=", "idx", "+", "1", "attached", "=", "False", "elif", "val", ".", "startswith", "(", "'-o'", ")", ":", "replaceidx", "=", "idx", "attached", "=", "True", "if", "replaceidx", "is", "None", ":", "raise", "Exception", "replacement", "=", "new_name", "if", "attached", "==", "True", ":", "replacement", "=", "'-o'", "+", "new_name", "args", "[", "replaceidx", "]", "=", "replacement", "return", "args" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/utils/check_cfc/check_cfc.py#L151-L170
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/generator/analyzer.py
python
_ToGypPath
(path)
return path
Converts a path to the format used by gyp.
Converts a path to the format used by gyp.
[ "Converts", "a", "path", "to", "the", "format", "used", "by", "gyp", "." ]
def _ToGypPath(path): """Converts a path to the format used by gyp.""" if os.sep == '\\' and os.altsep == '/': return path.replace('\\', '/') return path
[ "def", "_ToGypPath", "(", "path", ")", ":", "if", "os", ".", "sep", "==", "'\\\\'", "and", "os", ".", "altsep", "==", "'/'", ":", "return", "path", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "return", "path" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/analyzer.py#L112-L116
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/pickle.py
python
Pickler.__init__
(self, file, protocol=None)
This takes a file-like object for writing a pickle data stream. The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text mode and read back successfully. When using a protocol higher than 0, make sure the file is opened in binary mode, both when pickling and unpickling.) Protocol 1 is more efficient than protocol 0; protocol 2 is more efficient than protocol 1. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The file parameter must have a write() method that accepts a single string argument. It can thus be an open file object, a StringIO object, or any other custom object that meets this interface.
This takes a file-like object for writing a pickle data stream.
[ "This", "takes", "a", "file", "-", "like", "object", "for", "writing", "a", "pickle", "data", "stream", "." ]
def __init__(self, file, protocol=None): """This takes a file-like object for writing a pickle data stream. The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text mode and read back successfully. When using a protocol higher than 0, make sure the file is opened in binary mode, both when pickling and unpickling.) Protocol 1 is more efficient than protocol 0; protocol 2 is more efficient than protocol 1. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The file parameter must have a write() method that accepts a single string argument. It can thus be an open file object, a StringIO object, or any other custom object that meets this interface. """ if protocol is None: protocol = 0 if protocol < 0: protocol = HIGHEST_PROTOCOL elif not 0 <= protocol <= HIGHEST_PROTOCOL: raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) self.write = file.write self.memo = {} self.proto = int(protocol) self.bin = protocol >= 1 self.fast = 0
[ "def", "__init__", "(", "self", ",", "file", ",", "protocol", "=", "None", ")", ":", "if", "protocol", "is", "None", ":", "protocol", "=", "0", "if", "protocol", "<", "0", ":", "protocol", "=", "HIGHEST_PROTOCOL", "elif", "not", "0", "<=", "protocol", "<=", "HIGHEST_PROTOCOL", ":", "raise", "ValueError", "(", "\"pickle protocol must be <= %d\"", "%", "HIGHEST_PROTOCOL", ")", "self", ".", "write", "=", "file", ".", "write", "self", ".", "memo", "=", "{", "}", "self", ".", "proto", "=", "int", "(", "protocol", ")", "self", ".", "bin", "=", "protocol", ">=", "1", "self", ".", "fast", "=", "0" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pickle.py#L173-L207
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
python/lbann/modules/rnn.py
python
GRU.forward
(self, x, prev_state)
return ht, ht
Apply GRU step. Args: x (Layer): Input. prev_state: State from previous GRU step. Returns: (Layer, Layer): The output (out) and state (hn). The state can be passed directly into the next GRU step.
Apply GRU step.
[ "Apply", "GRU", "step", "." ]
def forward(self, x, prev_state): """Apply GRU step. Args: x (Layer): Input. prev_state: State from previous GRU step. Returns: (Layer, Layer): The output (out) and state (hn). The state can be passed directly into the next GRU step. """ self.step += 1 name = '{0}_step{1}'.format(self.name, self.step) fc1 = self.ih_fc(x) #input_fc fc2 = self.hh_fc(prev_state) #hidden_fc # Get gates and cell update fc1_slice = lbann.Slice(fc1, slice_points=str_list([0, self.size, 2*self.size, 3*self.size]), name=name + '_fc1_slice', data_layout=self.data_layout) Wir_x = lbann.Identity(fc1_slice, name=name + '_Wrx', data_layout=self.data_layout) Wiz_x = lbann.Identity(fc1_slice, name=name + '_Wzx', data_layout=self.data_layout) Win_x = lbann.Identity(fc1_slice, name=name + '_Wnx', data_layout=self.data_layout) fc2_slice = lbann.Slice(fc2, slice_points=str_list([0, self.size, 2*self.size, 3*self.size]), name=name + '_fc2_slice', data_layout=self.data_layout) Whr_prev = lbann.Identity(fc2_slice, name=name + '_Wrh', data_layout=self.data_layout) Whz_prev = lbann.Identity(fc2_slice, name=name + '_Wzh', data_layout=self.data_layout) Whn_prev = lbann.Identity(fc2_slice, name=name + '_Wnh', data_layout=self.data_layout) rt = \ lbann.Sigmoid( lbann.Add(Wir_x, Whr_prev, data_layout=self.data_layout), name=name + '_reset_gate', data_layout=self.data_layout ) zt = \ lbann.Sigmoid( lbann.Add(Wiz_x, Whz_prev, data_layout=self.data_layout), name=name + '_update_gate', data_layout=self.data_layout, ) nt = \ lbann.Tanh( lbann.Add( Win_x, lbann.Multiply(rt, Whn_prev, data_layout=self.data_layout), data_layout=self.data_layout, ), name=name + '_new_gate', data_layout=self.data_layout, ) ht = \ lbann.Add( lbann.Multiply( lbann.WeightedSum( self.ones, zt, scaling_factors='1 -1', data_layout=self.data_layout ), nt, data_layout=self.data_layout ), lbann.Multiply(zt, prev_state, data_layout=self.data_layout), name=name+ '_output', data_layout=self.data_layout, ) # Return output return ht, ht
[ "def", "forward", "(", "self", ",", "x", ",", "prev_state", ")", ":", "self", ".", "step", "+=", "1", "name", "=", "'{0}_step{1}'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "step", ")", "fc1", "=", "self", ".", "ih_fc", "(", "x", ")", "#input_fc", "fc2", "=", "self", ".", "hh_fc", "(", "prev_state", ")", "#hidden_fc", "# Get gates and cell update", "fc1_slice", "=", "lbann", ".", "Slice", "(", "fc1", ",", "slice_points", "=", "str_list", "(", "[", "0", ",", "self", ".", "size", ",", "2", "*", "self", ".", "size", ",", "3", "*", "self", ".", "size", "]", ")", ",", "name", "=", "name", "+", "'_fc1_slice'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "Wir_x", "=", "lbann", ".", "Identity", "(", "fc1_slice", ",", "name", "=", "name", "+", "'_Wrx'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "Wiz_x", "=", "lbann", ".", "Identity", "(", "fc1_slice", ",", "name", "=", "name", "+", "'_Wzx'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "Win_x", "=", "lbann", ".", "Identity", "(", "fc1_slice", ",", "name", "=", "name", "+", "'_Wnx'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "fc2_slice", "=", "lbann", ".", "Slice", "(", "fc2", ",", "slice_points", "=", "str_list", "(", "[", "0", ",", "self", ".", "size", ",", "2", "*", "self", ".", "size", ",", "3", "*", "self", ".", "size", "]", ")", ",", "name", "=", "name", "+", "'_fc2_slice'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "Whr_prev", "=", "lbann", ".", "Identity", "(", "fc2_slice", ",", "name", "=", "name", "+", "'_Wrh'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "Whz_prev", "=", "lbann", ".", "Identity", "(", "fc2_slice", ",", "name", "=", "name", "+", "'_Wzh'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "Whn_prev", "=", "lbann", ".", "Identity", "(", "fc2_slice", ",", "name", "=", "name", "+", "'_Wnh'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "rt", "=", "lbann", ".", "Sigmoid", "(", "lbann", ".", "Add", "(", "Wir_x", ",", "Whr_prev", ",", "data_layout", "=", "self", ".", "data_layout", ")", ",", "name", "=", "name", "+", "'_reset_gate'", ",", "data_layout", "=", "self", ".", "data_layout", ")", "zt", "=", "lbann", ".", "Sigmoid", "(", "lbann", ".", "Add", "(", "Wiz_x", ",", "Whz_prev", ",", "data_layout", "=", "self", ".", "data_layout", ")", ",", "name", "=", "name", "+", "'_update_gate'", ",", "data_layout", "=", "self", ".", "data_layout", ",", ")", "nt", "=", "lbann", ".", "Tanh", "(", "lbann", ".", "Add", "(", "Win_x", ",", "lbann", ".", "Multiply", "(", "rt", ",", "Whn_prev", ",", "data_layout", "=", "self", ".", "data_layout", ")", ",", "data_layout", "=", "self", ".", "data_layout", ",", ")", ",", "name", "=", "name", "+", "'_new_gate'", ",", "data_layout", "=", "self", ".", "data_layout", ",", ")", "ht", "=", "lbann", ".", "Add", "(", "lbann", ".", "Multiply", "(", "lbann", ".", "WeightedSum", "(", "self", ".", "ones", ",", "zt", ",", "scaling_factors", "=", "'1 -1'", ",", "data_layout", "=", "self", ".", "data_layout", ")", ",", "nt", ",", "data_layout", "=", "self", ".", "data_layout", ")", ",", "lbann", ".", "Multiply", "(", "zt", ",", "prev_state", ",", "data_layout", "=", "self", ".", "data_layout", ")", ",", "name", "=", "name", "+", "'_output'", ",", "data_layout", "=", "self", ".", "data_layout", ",", ")", "# Return output", "return", "ht", ",", "ht" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/modules/rnn.py#L223-L307