nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/copy_helper.py
python
FilterExistingComponents
(dst_args, existing_components, bucket_url, gsutil_api)
return (components_to_upload, uploaded_components, existing_objects_to_delete)
Determines course of action for component objects. Given the list of all target objects based on partitioning the file and the list of objects that have already been uploaded successfully, this function determines which objects should be uploaded, which existing components are still valid, and which existing components should be deleted. Args: dst_args: The map of file_name -> PerformParallelUploadFileToObjectArgs calculated by partitioning the file. existing_components: A list of ObjectFromTracker objects that have been uploaded in the past. bucket_url: CloudUrl of the bucket in which the components exist. gsutil_api: gsutil Cloud API instance to use for retrieving object metadata. Returns: components_to_upload: List of components that need to be uploaded. uploaded_components: List of components that have already been uploaded and are still valid. existing_objects_to_delete: List of components that have already been uploaded, but are no longer valid and are in a versioned bucket, and therefore should be deleted.
Determines course of action for component objects.
[ "Determines", "course", "of", "action", "for", "component", "objects", "." ]
def FilterExistingComponents(dst_args, existing_components, bucket_url, gsutil_api): """Determines course of action for component objects. Given the list of all target objects based on partitioning the file and the list of objects that have already been uploaded successfully, this function determines which objects should be uploaded, which existing components are still valid, and which existing components should be deleted. Args: dst_args: The map of file_name -> PerformParallelUploadFileToObjectArgs calculated by partitioning the file. existing_components: A list of ObjectFromTracker objects that have been uploaded in the past. bucket_url: CloudUrl of the bucket in which the components exist. gsutil_api: gsutil Cloud API instance to use for retrieving object metadata. Returns: components_to_upload: List of components that need to be uploaded. uploaded_components: List of components that have already been uploaded and are still valid. existing_objects_to_delete: List of components that have already been uploaded, but are no longer valid and are in a versioned bucket, and therefore should be deleted. """ components_to_upload = [] existing_component_names = [component.object_name for component in existing_components] for component_name in dst_args: if component_name not in existing_component_names: components_to_upload.append(dst_args[component_name]) objects_already_chosen = [] # Don't reuse any temporary components whose MD5 doesn't match the current # MD5 of the corresponding part of the file. If the bucket is versioned, # also make sure that we delete the existing temporary version. existing_objects_to_delete = [] uploaded_components = [] for tracker_object in existing_components: if (tracker_object.object_name not in dst_args.keys() or tracker_object.object_name in objects_already_chosen): # This could happen if the component size has changed. This also serves # to handle object names that get duplicated in the tracker file due # to people doing things they shouldn't (e.g., overwriting an existing # temporary component in a versioned bucket). url = bucket_url.Clone() url.object_name = tracker_object.object_name url.generation = tracker_object.generation existing_objects_to_delete.append(url) continue dst_arg = dst_args[tracker_object.object_name] file_part = FilePart(dst_arg.filename, dst_arg.file_start, dst_arg.file_length) # TODO: calculate MD5's in parallel when possible. content_md5 = CalculateB64EncodedMd5FromContents(file_part) try: # Get the MD5 of the currently-existing component. dst_url = dst_arg.dst_url dst_metadata = gsutil_api.GetObjectMetadata( dst_url.bucket_name, dst_url.object_name, generation=dst_url.generation, provider=dst_url.scheme, fields=['md5Hash', 'etag']) cloud_md5 = dst_metadata.md5Hash except Exception: # pylint: disable=broad-except # We don't actually care what went wrong - we couldn't retrieve the # object to check the MD5, so just upload it again. cloud_md5 = None if cloud_md5 != content_md5: components_to_upload.append(dst_arg) objects_already_chosen.append(tracker_object.object_name) if tracker_object.generation: # If the old object doesn't have a generation (i.e., it isn't in a # versioned bucket), then we will just overwrite it anyway. invalid_component_with_generation = dst_arg.dst_url.Clone() invalid_component_with_generation.generation = tracker_object.generation existing_objects_to_delete.append(invalid_component_with_generation) else: url = dst_arg.dst_url.Clone() url.generation = tracker_object.generation uploaded_components.append(url) objects_already_chosen.append(tracker_object.object_name) if uploaded_components: logging.info('Found %d existing temporary components to reuse.', len(uploaded_components)) return (components_to_upload, uploaded_components, existing_objects_to_delete)
[ "def", "FilterExistingComponents", "(", "dst_args", ",", "existing_components", ",", "bucket_url", ",", "gsutil_api", ")", ":", "components_to_upload", "=", "[", "]", "existing_component_names", "=", "[", "component", ".", "object_name", "for", "component", "in", "existing_components", "]", "for", "component_name", "in", "dst_args", ":", "if", "component_name", "not", "in", "existing_component_names", ":", "components_to_upload", ".", "append", "(", "dst_args", "[", "component_name", "]", ")", "objects_already_chosen", "=", "[", "]", "# Don't reuse any temporary components whose MD5 doesn't match the current", "# MD5 of the corresponding part of the file. If the bucket is versioned,", "# also make sure that we delete the existing temporary version.", "existing_objects_to_delete", "=", "[", "]", "uploaded_components", "=", "[", "]", "for", "tracker_object", "in", "existing_components", ":", "if", "(", "tracker_object", ".", "object_name", "not", "in", "dst_args", ".", "keys", "(", ")", "or", "tracker_object", ".", "object_name", "in", "objects_already_chosen", ")", ":", "# This could happen if the component size has changed. This also serves", "# to handle object names that get duplicated in the tracker file due", "# to people doing things they shouldn't (e.g., overwriting an existing", "# temporary component in a versioned bucket).", "url", "=", "bucket_url", ".", "Clone", "(", ")", "url", ".", "object_name", "=", "tracker_object", ".", "object_name", "url", ".", "generation", "=", "tracker_object", ".", "generation", "existing_objects_to_delete", ".", "append", "(", "url", ")", "continue", "dst_arg", "=", "dst_args", "[", "tracker_object", ".", "object_name", "]", "file_part", "=", "FilePart", "(", "dst_arg", ".", "filename", ",", "dst_arg", ".", "file_start", ",", "dst_arg", ".", "file_length", ")", "# TODO: calculate MD5's in parallel when possible.", "content_md5", "=", "CalculateB64EncodedMd5FromContents", "(", "file_part", ")", "try", ":", "# Get the MD5 of the currently-existing component.", "dst_url", "=", "dst_arg", ".", "dst_url", "dst_metadata", "=", "gsutil_api", ".", "GetObjectMetadata", "(", "dst_url", ".", "bucket_name", ",", "dst_url", ".", "object_name", ",", "generation", "=", "dst_url", ".", "generation", ",", "provider", "=", "dst_url", ".", "scheme", ",", "fields", "=", "[", "'md5Hash'", ",", "'etag'", "]", ")", "cloud_md5", "=", "dst_metadata", ".", "md5Hash", "except", "Exception", ":", "# pylint: disable=broad-except", "# We don't actually care what went wrong - we couldn't retrieve the", "# object to check the MD5, so just upload it again.", "cloud_md5", "=", "None", "if", "cloud_md5", "!=", "content_md5", ":", "components_to_upload", ".", "append", "(", "dst_arg", ")", "objects_already_chosen", ".", "append", "(", "tracker_object", ".", "object_name", ")", "if", "tracker_object", ".", "generation", ":", "# If the old object doesn't have a generation (i.e., it isn't in a", "# versioned bucket), then we will just overwrite it anyway.", "invalid_component_with_generation", "=", "dst_arg", ".", "dst_url", ".", "Clone", "(", ")", "invalid_component_with_generation", ".", "generation", "=", "tracker_object", ".", "generation", "existing_objects_to_delete", ".", "append", "(", "invalid_component_with_generation", ")", "else", ":", "url", "=", "dst_arg", ".", "dst_url", ".", "Clone", "(", ")", "url", ".", "generation", "=", "tracker_object", ".", "generation", "uploaded_components", ".", "append", "(", "url", ")", "objects_already_chosen", ".", "append", "(", "tracker_object", ".", "object_name", ")", "if", "uploaded_components", ":", "logging", ".", "info", "(", "'Found %d existing temporary components to reuse.'", ",", "len", "(", "uploaded_components", ")", ")", "return", "(", "components_to_upload", ",", "uploaded_components", ",", "existing_objects_to_delete", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/copy_helper.py#L3181-L3275
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hypertreelist.py
python
TreeListColumnInfo.GetSelectedImage
(self)
return self._selected_image
Returns the column image index in the selected state.
Returns the column image index in the selected state.
[ "Returns", "the", "column", "image", "index", "in", "the", "selected", "state", "." ]
def GetSelectedImage(self): """ Returns the column image index in the selected state. """ return self._selected_image
[ "def", "GetSelectedImage", "(", "self", ")", ":", "return", "self", ".", "_selected_image" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L531-L534
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py
python
_BaseNetwork.is_reserved
(self)
return (self.network_address.is_reserved and self.broadcast_address.is_reserved)
Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.
Test if the address is otherwise IETF reserved.
[ "Test", "if", "the", "address", "is", "otherwise", "IETF", "reserved", "." ]
def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved)
[ "def", "is_reserved", "(", "self", ")", ":", "return", "(", "self", ".", "network_address", ".", "is_reserved", "and", "self", ".", "broadcast_address", ".", "is_reserved", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py#L1122-L1131
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
Dialog_GetLayoutAdapter
(*args)
return _windows_.Dialog_GetLayoutAdapter(*args)
Dialog_GetLayoutAdapter() -> DialogLayoutAdapter
Dialog_GetLayoutAdapter() -> DialogLayoutAdapter
[ "Dialog_GetLayoutAdapter", "()", "-", ">", "DialogLayoutAdapter" ]
def Dialog_GetLayoutAdapter(*args): """Dialog_GetLayoutAdapter() -> DialogLayoutAdapter""" return _windows_.Dialog_GetLayoutAdapter(*args)
[ "def", "Dialog_GetLayoutAdapter", "(", "*", "args", ")", ":", "return", "_windows_", ".", "Dialog_GetLayoutAdapter", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L928-L930
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
bindings/python/htcondor/htchirp/htchirp.py
python
HTChirp._read
(self, fd, length, offset=None, stride_length=None, stride_skip=None)
return self._get_fixed_data(rb)
Read from a file on the Chirp server :param fd: File descriptor :param length: Number of bytes to read :param offset: Skip this many bytes when reading :param stride_length: Read this many bytes every stride_skip bytes :param stride_skip: Skip this many bytes between reads :returns: Data read from file
Read from a file on the Chirp server
[ "Read", "from", "a", "file", "on", "the", "Chirp", "server" ]
def _read(self, fd, length, offset=None, stride_length=None, stride_skip=None): """Read from a file on the Chirp server :param fd: File descriptor :param length: Number of bytes to read :param offset: Skip this many bytes when reading :param stride_length: Read this many bytes every stride_skip bytes :param stride_skip: Skip this many bytes between reads :returns: Data read from file """ if offset is None and (stride_length, stride_skip) != (None, None): offset = 0 # assume offset is 0 if stride given but not offset if (offset, stride_length, stride_skip) == (None, None, None): # read rb = int( self._simple_command("read {0} {1}\n".format(int(fd), int(length))) ) elif (offset != None) and (stride_length, stride_skip) == (None, None): # pread rb = int( self._simple_command( "pread {0} {1} {2}\n".format(int(fd), int(length), int(offset)) ) ) elif (stride_length, stride_skip) != (None, None): # sread rb = int( self._simple_command( "sread {0} {1} {2} {3} {4}\n".format( int(fd), int(length), int(offset), int(stride_length), int(stride_skip), ) ) ) else: raise self.InvalidRequest( "Both stride_length and stride_skip must be specified" ) return self._get_fixed_data(rb)
[ "def", "_read", "(", "self", ",", "fd", ",", "length", ",", "offset", "=", "None", ",", "stride_length", "=", "None", ",", "stride_skip", "=", "None", ")", ":", "if", "offset", "is", "None", "and", "(", "stride_length", ",", "stride_skip", ")", "!=", "(", "None", ",", "None", ")", ":", "offset", "=", "0", "# assume offset is 0 if stride given but not offset", "if", "(", "offset", ",", "stride_length", ",", "stride_skip", ")", "==", "(", "None", ",", "None", ",", "None", ")", ":", "# read", "rb", "=", "int", "(", "self", ".", "_simple_command", "(", "\"read {0} {1}\\n\"", ".", "format", "(", "int", "(", "fd", ")", ",", "int", "(", "length", ")", ")", ")", ")", "elif", "(", "offset", "!=", "None", ")", "and", "(", "stride_length", ",", "stride_skip", ")", "==", "(", "None", ",", "None", ")", ":", "# pread", "rb", "=", "int", "(", "self", ".", "_simple_command", "(", "\"pread {0} {1} {2}\\n\"", ".", "format", "(", "int", "(", "fd", ")", ",", "int", "(", "length", ")", ",", "int", "(", "offset", ")", ")", ")", ")", "elif", "(", "stride_length", ",", "stride_skip", ")", "!=", "(", "None", ",", "None", ")", ":", "# sread", "rb", "=", "int", "(", "self", ".", "_simple_command", "(", "\"sread {0} {1} {2} {3} {4}\\n\"", ".", "format", "(", "int", "(", "fd", ")", ",", "int", "(", "length", ")", ",", "int", "(", "offset", ")", ",", "int", "(", "stride_length", ")", ",", "int", "(", "stride_skip", ")", ",", ")", ")", ")", "else", ":", "raise", "self", ".", "InvalidRequest", "(", "\"Both stride_length and stride_skip must be specified\"", ")", "return", "self", ".", "_get_fixed_data", "(", "rb", ")" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/htchirp/htchirp.py#L410-L458
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/api.py
python
to_device
(obj, stream=0, copy=True, to=None)
return to
to_device(obj, stream=0, copy=True, to=None) Allocate and transfer a numpy ndarray or structured scalar to the device. To copy host->device a numpy array:: ary = np.arange(10) d_ary = cuda.to_device(ary) To enqueue the transfer to a stream:: stream = cuda.stream() d_ary = cuda.to_device(ary, stream=stream) The resulting ``d_ary`` is a ``DeviceNDArray``. To copy device->host:: hary = d_ary.copy_to_host() To copy device->host to an existing array:: ary = np.empty(shape=d_ary.shape, dtype=d_ary.dtype) d_ary.copy_to_host(ary) To enqueue the transfer to a stream:: hary = d_ary.copy_to_host(stream=stream)
to_device(obj, stream=0, copy=True, to=None)
[ "to_device", "(", "obj", "stream", "=", "0", "copy", "=", "True", "to", "=", "None", ")" ]
def to_device(obj, stream=0, copy=True, to=None): """to_device(obj, stream=0, copy=True, to=None) Allocate and transfer a numpy ndarray or structured scalar to the device. To copy host->device a numpy array:: ary = np.arange(10) d_ary = cuda.to_device(ary) To enqueue the transfer to a stream:: stream = cuda.stream() d_ary = cuda.to_device(ary, stream=stream) The resulting ``d_ary`` is a ``DeviceNDArray``. To copy device->host:: hary = d_ary.copy_to_host() To copy device->host to an existing array:: ary = np.empty(shape=d_ary.shape, dtype=d_ary.dtype) d_ary.copy_to_host(ary) To enqueue the transfer to a stream:: hary = d_ary.copy_to_host(stream=stream) """ if to is None: to, new = devicearray.auto_device(obj, stream=stream, copy=copy) return to if copy: to.copy_to_device(obj, stream=stream) return to
[ "def", "to_device", "(", "obj", ",", "stream", "=", "0", ",", "copy", "=", "True", ",", "to", "=", "None", ")", ":", "if", "to", "is", "None", ":", "to", ",", "new", "=", "devicearray", ".", "auto_device", "(", "obj", ",", "stream", "=", "stream", ",", "copy", "=", "copy", ")", "return", "to", "if", "copy", ":", "to", ".", "copy_to_device", "(", "obj", ",", "stream", "=", "stream", ")", "return", "to" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/api.py#L80-L115
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/pycc/compiler.py
python
_ModuleCompiler._emit_method_array
(self, llvm_module)
return method_array_ptr
Collect exported methods and emit a PyMethodDef array. :returns: a pointer to the PyMethodDef array.
Collect exported methods and emit a PyMethodDef array.
[ "Collect", "exported", "methods", "and", "emit", "a", "PyMethodDef", "array", "." ]
def _emit_method_array(self, llvm_module): """ Collect exported methods and emit a PyMethodDef array. :returns: a pointer to the PyMethodDef array. """ method_defs = [] for entry in self.export_entries: name = entry.symbol llvm_func_name = self._mangle_method_symbol(name) fnty = self.exported_function_types[entry] lfunc = llvm_module.add_function(fnty, name=llvm_func_name) method_name = self.context.insert_const_string(llvm_module, name) method_def_const = lc.Constant.struct((method_name, lc.Constant.bitcast(lfunc, lt._void_star), METH_VARARGS_AND_KEYWORDS, NULL)) method_defs.append(method_def_const) sentinel = lc.Constant.struct([NULL, NULL, ZERO, NULL]) method_defs.append(sentinel) method_array_init = lc.Constant.array(self.method_def_ty, method_defs) method_array = llvm_module.add_global_variable(method_array_init.type, '.module_methods') method_array.initializer = method_array_init method_array.linkage = lc.LINKAGE_INTERNAL method_array_ptr = lc.Constant.gep(method_array, [ZERO, ZERO]) return method_array_ptr
[ "def", "_emit_method_array", "(", "self", ",", "llvm_module", ")", ":", "method_defs", "=", "[", "]", "for", "entry", "in", "self", ".", "export_entries", ":", "name", "=", "entry", ".", "symbol", "llvm_func_name", "=", "self", ".", "_mangle_method_symbol", "(", "name", ")", "fnty", "=", "self", ".", "exported_function_types", "[", "entry", "]", "lfunc", "=", "llvm_module", ".", "add_function", "(", "fnty", ",", "name", "=", "llvm_func_name", ")", "method_name", "=", "self", ".", "context", ".", "insert_const_string", "(", "llvm_module", ",", "name", ")", "method_def_const", "=", "lc", ".", "Constant", ".", "struct", "(", "(", "method_name", ",", "lc", ".", "Constant", ".", "bitcast", "(", "lfunc", ",", "lt", ".", "_void_star", ")", ",", "METH_VARARGS_AND_KEYWORDS", ",", "NULL", ")", ")", "method_defs", ".", "append", "(", "method_def_const", ")", "sentinel", "=", "lc", ".", "Constant", ".", "struct", "(", "[", "NULL", ",", "NULL", ",", "ZERO", ",", "NULL", "]", ")", "method_defs", ".", "append", "(", "sentinel", ")", "method_array_init", "=", "lc", ".", "Constant", ".", "array", "(", "self", ".", "method_def_ty", ",", "method_defs", ")", "method_array", "=", "llvm_module", ".", "add_global_variable", "(", "method_array_init", ".", "type", ",", "'.module_methods'", ")", "method_array", ".", "initializer", "=", "method_array_init", "method_array", ".", "linkage", "=", "lc", ".", "LINKAGE_INTERNAL", "method_array_ptr", "=", "lc", ".", "Constant", ".", "gep", "(", "method_array", ",", "[", "ZERO", ",", "ZERO", "]", ")", "return", "method_array_ptr" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/pycc/compiler.py#L225-L253
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/variables.py
python
Variable.op
(self)
return self._variable.op
The `Operation` of this variable.
The `Operation` of this variable.
[ "The", "Operation", "of", "this", "variable", "." ]
def op(self): """The `Operation` of this variable.""" return self._variable.op
[ "def", "op", "(", "self", ")", ":", "return", "self", ".", "_variable", ".", "op" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/variables.py#L665-L667
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/callback/_landscape.py
python
SummaryLandscape._check_json_file_data
(self, json_file_data)
Check json file data.
Check json file data.
[ "Check", "json", "file", "data", "." ]
def _check_json_file_data(self, json_file_data): """Check json file data.""" file_key = ["epoch_group", "model_params_file_map", "step_per_epoch", "unit", "num_samples", "landscape_size", "create_landscape"] for key in json_file_data.keys(): if key not in file_key: raise ValueError(f'"train_metadata" json file should be {file_key}, but got the: {key}') epoch_group = json_file_data["epoch_group"] model_params_file_map = json_file_data["model_params_file_map"] step_per_epoch = json_file_data["step_per_epoch"] unit = json_file_data["unit"] num_samples = json_file_data["num_samples"] landscape_size = json_file_data["landscape_size"] create_landscape = json_file_data["create_landscape"] for _, epochs in enumerate(epoch_group.values()): # Each epoch_group have at least three epochs. if len(epochs) < 3: raise ValueError(f'This group epochs length should not be less than 3' f'but got: {len(epochs)}. ') for epoch in epochs: if str(epoch) not in model_params_file_map.keys(): raise ValueError(f'The model_params_file_map does not exist {epoch}th checkpoint in intervals.') check_value_type('step_per_epoch', step_per_epoch, int) self._check_landscape_size(landscape_size) self._check_unit(unit) check_value_type("num_samples", num_samples, int) self._check_create_landscape(create_landscape)
[ "def", "_check_json_file_data", "(", "self", ",", "json_file_data", ")", ":", "file_key", "=", "[", "\"epoch_group\"", ",", "\"model_params_file_map\"", ",", "\"step_per_epoch\"", ",", "\"unit\"", ",", "\"num_samples\"", ",", "\"landscape_size\"", ",", "\"create_landscape\"", "]", "for", "key", "in", "json_file_data", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "file_key", ":", "raise", "ValueError", "(", "f'\"train_metadata\" json file should be {file_key}, but got the: {key}'", ")", "epoch_group", "=", "json_file_data", "[", "\"epoch_group\"", "]", "model_params_file_map", "=", "json_file_data", "[", "\"model_params_file_map\"", "]", "step_per_epoch", "=", "json_file_data", "[", "\"step_per_epoch\"", "]", "unit", "=", "json_file_data", "[", "\"unit\"", "]", "num_samples", "=", "json_file_data", "[", "\"num_samples\"", "]", "landscape_size", "=", "json_file_data", "[", "\"landscape_size\"", "]", "create_landscape", "=", "json_file_data", "[", "\"create_landscape\"", "]", "for", "_", ",", "epochs", "in", "enumerate", "(", "epoch_group", ".", "values", "(", ")", ")", ":", "# Each epoch_group have at least three epochs.", "if", "len", "(", "epochs", ")", "<", "3", ":", "raise", "ValueError", "(", "f'This group epochs length should not be less than 3'", "f'but got: {len(epochs)}. '", ")", "for", "epoch", "in", "epochs", ":", "if", "str", "(", "epoch", ")", "not", "in", "model_params_file_map", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "f'The model_params_file_map does not exist {epoch}th checkpoint in intervals.'", ")", "check_value_type", "(", "'step_per_epoch'", ",", "step_per_epoch", ",", "int", ")", "self", ".", "_check_landscape_size", "(", "landscape_size", ")", "self", ".", "_check_unit", "(", "unit", ")", "check_value_type", "(", "\"num_samples\"", ",", "num_samples", ",", "int", ")", "self", ".", "_check_create_landscape", "(", "create_landscape", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/callback/_landscape.py#L845-L873
bitconch/bitconch-core
5537f3215b3e3b76f6720d6f908676a6c34bc5db
deploy-stable.py
python
execute_shell
(command, silent=False, cwd=None, shell=True, env=None)
Execute a system command
Execute a system command
[ "Execute", "a", "system", "command" ]
def execute_shell(command, silent=False, cwd=None, shell=True, env=None): """ Execute a system command """ if env is not None: env = dict(**os.environ, **env) if silent: p = Popen( command, shell=shell, stdout=PIPE, stderr=PIPE, cwd=cwd, env=env) stdout, _ = p.communicate() return stdout else: check_call(command, shell=shell, cwd=cwd, env=env)
[ "def", "execute_shell", "(", "command", ",", "silent", "=", "False", ",", "cwd", "=", "None", ",", "shell", "=", "True", ",", "env", "=", "None", ")", ":", "if", "env", "is", "not", "None", ":", "env", "=", "dict", "(", "*", "*", "os", ".", "environ", ",", "*", "*", "env", ")", "if", "silent", ":", "p", "=", "Popen", "(", "command", ",", "shell", "=", "shell", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "cwd", "=", "cwd", ",", "env", "=", "env", ")", "stdout", ",", "_", "=", "p", ".", "communicate", "(", ")", "return", "stdout", "else", ":", "check_call", "(", "command", ",", "shell", "=", "shell", ",", "cwd", "=", "cwd", ",", "env", "=", "env", ")" ]
https://github.com/bitconch/bitconch-core/blob/5537f3215b3e3b76f6720d6f908676a6c34bc5db/deploy-stable.py#L39-L54
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/browser/extensions/PRESUBMIT.py
python
HistogramValueChecker.CheckForFileDeletion
(self, affected_file)
return True
Emits a warning notification if file has been deleted
Emits a warning notification if file has been deleted
[ "Emits", "a", "warning", "notification", "if", "file", "has", "been", "deleted" ]
def CheckForFileDeletion(self, affected_file): """Emits a warning notification if file has been deleted """ if not affected_file.NewContents(): self.EmitWarning("The file seems to be deleted in the changelist. If " "your intent is to really delete the file, the code in " "PRESUBMIT.py should be updated to remove the " "|HistogramValueChecker| class."); return False return True
[ "def", "CheckForFileDeletion", "(", "self", ",", "affected_file", ")", ":", "if", "not", "affected_file", ".", "NewContents", "(", ")", ":", "self", ".", "EmitWarning", "(", "\"The file seems to be deleted in the changelist. If \"", "\"your intent is to really delete the file, the code in \"", "\"PRESUBMIT.py should be updated to remove the \"", "\"|HistogramValueChecker| class.\"", ")", "return", "False", "return", "True" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/browser/extensions/PRESUBMIT.py#L175-L183
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sframe.py
python
SFrame.to_rdd
(self, sc, number_of_partitions=4)
return output_rdd
Convert the current SFrame to the Spark RDD. Parameters ---------- sc : SparkContext sc is an existing SparkContext. number_of_partitions: int number of partitions for the output rdd Returns ---------- out: pyspark.rdd.RDD Notes ---------- - Look at from_rdd(). - Look at to_spark_dataframe(). Examples -------- >>> from pyspark import SparkContext >>> from graphlab import SFrame >>> sc = SparkContext('local') >>> sf = SFrame({'x': [1,2,3], 'y': ['fish', 'chips', 'salad']}) >>> rdd = sf.to_rdd(sc) >>> rdd.collect() [{'x': 1L, 'y': 'fish'}, {'x': 2L, 'y': 'chips'}, {'x': 3L, 'y': 'salad'}]
Convert the current SFrame to the Spark RDD.
[ "Convert", "the", "current", "SFrame", "to", "the", "Spark", "RDD", "." ]
def to_rdd(self, sc, number_of_partitions=4): """ Convert the current SFrame to the Spark RDD. Parameters ---------- sc : SparkContext sc is an existing SparkContext. number_of_partitions: int number of partitions for the output rdd Returns ---------- out: pyspark.rdd.RDD Notes ---------- - Look at from_rdd(). - Look at to_spark_dataframe(). Examples -------- >>> from pyspark import SparkContext >>> from graphlab import SFrame >>> sc = SparkContext('local') >>> sf = SFrame({'x': [1,2,3], 'y': ['fish', 'chips', 'salad']}) >>> rdd = sf.to_rdd(sc) >>> rdd.collect() [{'x': 1L, 'y': 'fish'}, {'x': 2L, 'y': 'chips'}, {'x': 3L, 'y': 'salad'}] """ _mt._get_metric_tracker().track('sframe.to_rdd') if not RDD_SUPPORT: raise Exception("Support for translation to Spark RDDs not enabled.") for _type in self.column_types(): if(_type.__name__ == 'Image'): raise TypeError("Support for translation to Spark RDDs not enabled for Image type.") if number_of_partitions is None: number_of_partitions = sc.defaultParallelism if type(number_of_partitions) is not int: raise ValueError("number_of_partitions parameter expects an integer type") if number_of_partitions == 0: raise ValueError("number_of_partitions can not be initialized to zero") # get a handle to GraphLabUtil java object graphlab_util_ref = self.__get_graphlabutil_reference_on_spark_unity_jar(sc) # Save SFrame in a temporary place tmp_loc = self.__get_staging_dir__(sc,graphlab_util_ref) sf_loc = os.path.join(tmp_loc, str(uuid.uuid4())) # Following substring replace is required to make # to_rdd() works on Azure blob storage accounts. if sf_loc.startswith("wasb://"): sf_loc = sf_loc.replace(graphlab_util_ref.getHadoopNameNode(),"hdfs://") self.save(sf_loc) print(sf_loc) # Keep track of the temporary sframe that is saved(). We need to delete it eventually. dummysf = load_sframe(sf_loc) dummysf.__proxy__.delete_on_close() SFRAME_GARBAGE_COLLECTOR.append(dummysf) # Run the spark job javaRDD = graphlab_util_ref.pySparkToRDD( sc._jsc.sc(),sf_loc,number_of_partitions,"") from pyspark import RDD import pyspark output_rdd = RDD(javaRDD,sc,pyspark.serializers.PickleSerializer()) return output_rdd
[ "def", "to_rdd", "(", "self", ",", "sc", ",", "number_of_partitions", "=", "4", ")", ":", "_mt", ".", "_get_metric_tracker", "(", ")", ".", "track", "(", "'sframe.to_rdd'", ")", "if", "not", "RDD_SUPPORT", ":", "raise", "Exception", "(", "\"Support for translation to Spark RDDs not enabled.\"", ")", "for", "_type", "in", "self", ".", "column_types", "(", ")", ":", "if", "(", "_type", ".", "__name__", "==", "'Image'", ")", ":", "raise", "TypeError", "(", "\"Support for translation to Spark RDDs not enabled for Image type.\"", ")", "if", "number_of_partitions", "is", "None", ":", "number_of_partitions", "=", "sc", ".", "defaultParallelism", "if", "type", "(", "number_of_partitions", ")", "is", "not", "int", ":", "raise", "ValueError", "(", "\"number_of_partitions parameter expects an integer type\"", ")", "if", "number_of_partitions", "==", "0", ":", "raise", "ValueError", "(", "\"number_of_partitions can not be initialized to zero\"", ")", "# get a handle to GraphLabUtil java object", "graphlab_util_ref", "=", "self", ".", "__get_graphlabutil_reference_on_spark_unity_jar", "(", "sc", ")", "# Save SFrame in a temporary place", "tmp_loc", "=", "self", ".", "__get_staging_dir__", "(", "sc", ",", "graphlab_util_ref", ")", "sf_loc", "=", "os", ".", "path", ".", "join", "(", "tmp_loc", ",", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "# Following substring replace is required to make", "# to_rdd() works on Azure blob storage accounts. ", "if", "sf_loc", ".", "startswith", "(", "\"wasb://\"", ")", ":", "sf_loc", "=", "sf_loc", ".", "replace", "(", "graphlab_util_ref", ".", "getHadoopNameNode", "(", ")", ",", "\"hdfs://\"", ")", "self", ".", "save", "(", "sf_loc", ")", "print", "(", "sf_loc", ")", "# Keep track of the temporary sframe that is saved(). We need to delete it eventually.", "dummysf", "=", "load_sframe", "(", "sf_loc", ")", "dummysf", ".", "__proxy__", ".", "delete_on_close", "(", ")", "SFRAME_GARBAGE_COLLECTOR", ".", "append", "(", "dummysf", ")", "# Run the spark job", "javaRDD", "=", "graphlab_util_ref", ".", "pySparkToRDD", "(", "sc", ".", "_jsc", ".", "sc", "(", ")", ",", "sf_loc", ",", "number_of_partitions", ",", "\"\"", ")", "from", "pyspark", "import", "RDD", "import", "pyspark", "output_rdd", "=", "RDD", "(", "javaRDD", ",", "sc", ",", "pyspark", ".", "serializers", ".", "PickleSerializer", "(", ")", ")", "return", "output_rdd" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sframe.py#L1824-L1897
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/auth.py
python
HTTPDigestAuth.handle_redirect
(self, r, **kwargs)
Reset num_401_calls counter on redirects.
Reset num_401_calls counter on redirects.
[ "Reset", "num_401_calls", "counter", "on", "redirects", "." ]
def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self._thread_local.num_401_calls = 1
[ "def", "handle_redirect", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "if", "r", ".", "is_redirect", ":", "self", ".", "_thread_local", ".", "num_401_calls", "=", "1" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/auth.py#L229-L232
gklz1982/caffe-yolov2
ebb27029db4ddc0d40e520634633b0fa9cdcc10d
scripts/cpp_lint.py
python
_CppLintState.SetFilters
(self, filters)
Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
Sets the error-message filters.
[ "Sets", "the", "error", "-", "message", "filters", "." ]
def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt)
[ "def", "SetFilters", "(", "self", ",", "filters", ")", ":", "# Default filters always have less priority than the flag ones.", "self", ".", "filters", "=", "_DEFAULT_FILTERS", "[", ":", "]", "for", "filt", "in", "filters", ".", "split", "(", "','", ")", ":", "clean_filt", "=", "filt", ".", "strip", "(", ")", "if", "clean_filt", ":", "self", ".", "filters", ".", "append", "(", "clean_filt", ")", "for", "filt", "in", "self", ".", "filters", ":", "if", "not", "(", "filt", ".", "startswith", "(", "'+'", ")", "or", "filt", ".", "startswith", "(", "'-'", ")", ")", ":", "raise", "ValueError", "(", "'Every filter in --filters must start with + or -'", "' (%s does not)'", "%", "filt", ")" ]
https://github.com/gklz1982/caffe-yolov2/blob/ebb27029db4ddc0d40e520634633b0fa9cdcc10d/scripts/cpp_lint.py#L717-L740
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py
python
Context.max_mag
(self, a, b)
return a.max_mag(b, context=self)
Compares the values numerically with their sign ignored. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) Decimal('-10') >>> ExtendedContext.max_mag(1, -2) Decimal('-2') >>> ExtendedContext.max_mag(Decimal(1), -2) Decimal('-2') >>> ExtendedContext.max_mag(1, Decimal(-2)) Decimal('-2')
Compares the values numerically with their sign ignored.
[ "Compares", "the", "values", "numerically", "with", "their", "sign", "ignored", "." ]
def max_mag(self, a, b): """Compares the values numerically with their sign ignored. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) Decimal('-10') >>> ExtendedContext.max_mag(1, -2) Decimal('-2') >>> ExtendedContext.max_mag(Decimal(1), -2) Decimal('-2') >>> ExtendedContext.max_mag(1, Decimal(-2)) Decimal('-2') """ a = _convert_other(a, raiseit=True) return a.max_mag(b, context=self)
[ "def", "max_mag", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "max_mag", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L4865-L4880
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xpathParserContext.xpathLastFunction
(self, nargs)
Implement the last() XPath function number last() The last function returns the number of nodes in the context node list.
Implement the last() XPath function number last() The last function returns the number of nodes in the context node list.
[ "Implement", "the", "last", "()", "XPath", "function", "number", "last", "()", "The", "last", "function", "returns", "the", "number", "of", "nodes", "in", "the", "context", "node", "list", "." ]
def xpathLastFunction(self, nargs): """Implement the last() XPath function number last() The last function returns the number of nodes in the context node list. """ libxml2mod.xmlXPathLastFunction(self._o, nargs)
[ "def", "xpathLastFunction", "(", "self", ",", "nargs", ")", ":", "libxml2mod", ".", "xmlXPathLastFunction", "(", "self", ".", "_o", ",", "nargs", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L7559-L7563
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/cpplint.py
python
FindStartOfExpressionInLine
(line, endpos, stack)
return (-1, stack)
Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line)
Find position at the matching start of current expression.
[ "Find", "position", "at", "the", "matching", "start", "of", "current", "expression", "." ]
def FindStartOfExpressionInLine(line, endpos, stack): """Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line) """ i = endpos while i >= 0: char = line[i] if char in ')]}': # Found end of expression, push to expression stack stack.append(char) elif char == '>': # Found potential end of template argument list. # # Ignore it if it's a "->" or ">=" or "operator>" if (i > 0 and (line[i - 1] == '-' or Match(r'\s>=\s', line[i - 1:]) or Search(r'\boperator\s*$', line[0:i]))): i -= 1 else: stack.append('>') elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator i -= 1 else: # If there is a matching '>', we can pop the expression stack. # Otherwise, ignore this '<' since it must be an operator. if stack and stack[-1] == '>': stack.pop() if not stack: return (i, None) elif char in '([{': # Found start of expression. # # If there are any unmatched '>' on the stack, they must be # operators. Remove those. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) if ((char == '(' and stack[-1] == ')') or (char == '[' and stack[-1] == ']') or (char == '{' and stack[-1] == '}')): stack.pop() if not stack: return (i, None) else: # Mismatched parentheses return (-1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '<', the matching '>' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) i -= 1 return (-1, stack)
[ "def", "FindStartOfExpressionInLine", "(", "line", ",", "endpos", ",", "stack", ")", ":", "i", "=", "endpos", "while", "i", ">=", "0", ":", "char", "=", "line", "[", "i", "]", "if", "char", "in", "')]}'", ":", "# Found end of expression, push to expression stack", "stack", ".", "append", "(", "char", ")", "elif", "char", "==", "'>'", ":", "# Found potential end of template argument list.", "#", "# Ignore it if it's a \"->\" or \">=\" or \"operator>\"", "if", "(", "i", ">", "0", "and", "(", "line", "[", "i", "-", "1", "]", "==", "'-'", "or", "Match", "(", "r'\\s>=\\s'", ",", "line", "[", "i", "-", "1", ":", "]", ")", "or", "Search", "(", "r'\\boperator\\s*$'", ",", "line", "[", "0", ":", "i", "]", ")", ")", ")", ":", "i", "-=", "1", "else", ":", "stack", ".", "append", "(", "'>'", ")", "elif", "char", "==", "'<'", ":", "# Found potential start of template argument list", "if", "i", ">", "0", "and", "line", "[", "i", "-", "1", "]", "==", "'<'", ":", "# Left shift operator", "i", "-=", "1", "else", ":", "# If there is a matching '>', we can pop the expression stack.", "# Otherwise, ignore this '<' since it must be an operator.", "if", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", ",", "None", ")", "elif", "char", "in", "'([{'", ":", "# Found start of expression.", "#", "# If there are any unmatched '>' on the stack, they must be", "# operators. Remove those.", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "if", "(", "(", "char", "==", "'('", "and", "stack", "[", "-", "1", "]", "==", "')'", ")", "or", "(", "char", "==", "'['", "and", "stack", "[", "-", "1", "]", "==", "']'", ")", "or", "(", "char", "==", "'{'", "and", "stack", "[", "-", "1", "]", "==", "'}'", ")", ")", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", ",", "None", ")", "else", ":", "# Mismatched parentheses", "return", "(", "-", "1", ",", "None", ")", "elif", "char", "==", "';'", ":", "# Found something that look like end of statements. If we are currently", "# expecting a '<', the matching '>' must have been an operator, since", "# template argument list should not contain statements.", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "i", "-=", "1", "return", "(", "-", "1", ",", "stack", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L1790-L1864
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntV.Del
(self, *args)
return _snap.TIntV_Del(self, *args)
Del(TIntV self, int const & ValN) Parameters: ValN: int const & Del(TIntV self, int const & MnValN, int const & MxValN) Parameters: MnValN: int const & MxValN: int const &
Del(TIntV self, int const & ValN)
[ "Del", "(", "TIntV", "self", "int", "const", "&", "ValN", ")" ]
def Del(self, *args): """ Del(TIntV self, int const & ValN) Parameters: ValN: int const & Del(TIntV self, int const & MnValN, int const & MxValN) Parameters: MnValN: int const & MxValN: int const & """ return _snap.TIntV_Del(self, *args)
[ "def", "Del", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TIntV_Del", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L15785-L15799
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/configure/libstdcxx.py
python
find_version
(e)
return encode_ver(last_version)
Given the value of environment variable CXX or HOST_CXX, find the version of the libstdc++ it uses.
Given the value of environment variable CXX or HOST_CXX, find the version of the libstdc++ it uses.
[ "Given", "the", "value", "of", "environment", "variable", "CXX", "or", "HOST_CXX", "find", "the", "version", "of", "the", "libstdc", "++", "it", "uses", "." ]
def find_version(e): """Given the value of environment variable CXX or HOST_CXX, find the version of the libstdc++ it uses. """ args = e.split() args += ['-shared', '-Wl,-t'] p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) candidates = [x for x in p.stdout if 'libstdc++.so' in x] if not candidates: return '' assert len(candidates) == 1 libstdcxx = parse_ld_line(candidates[-1]) p = subprocess.Popen(['readelf', '-V', libstdcxx], stdout=subprocess.PIPE) versions = [parse_readelf_line(x) for x in p.stdout.readlines() if 'Name: GLIBCXX' in x] last_version = sorted(versions, cmp = cmp_ver)[-1] return encode_ver(last_version)
[ "def", "find_version", "(", "e", ")", ":", "args", "=", "e", ".", "split", "(", ")", "args", "+=", "[", "'-shared'", ",", "'-Wl,-t'", "]", "p", "=", "subprocess", ".", "Popen", "(", "args", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "candidates", "=", "[", "x", "for", "x", "in", "p", ".", "stdout", "if", "'libstdc++.so'", "in", "x", "]", "if", "not", "candidates", ":", "return", "''", "assert", "len", "(", "candidates", ")", "==", "1", "libstdcxx", "=", "parse_ld_line", "(", "candidates", "[", "-", "1", "]", ")", "p", "=", "subprocess", ".", "Popen", "(", "[", "'readelf'", ",", "'-V'", ",", "libstdcxx", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "versions", "=", "[", "parse_readelf_line", "(", "x", ")", "for", "x", "in", "p", ".", "stdout", ".", "readlines", "(", ")", "if", "'Name: GLIBCXX'", "in", "x", "]", "last_version", "=", "sorted", "(", "versions", ",", "cmp", "=", "cmp_ver", ")", "[", "-", "1", "]", "return", "encode_ver", "(", "last_version", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/configure/libstdcxx.py#L56-L73
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/MQTTLib.py
python
AWSIoTMQTTThingJobsClient.sendJobsUpdate
(self, jobId, status, statusDetails=None, expectedVersion=0, executionNumber=0, includeJobExecutionState=False, includeJobDocument=False, stepTimeoutInMinutes=None)
return self._AWSIoTMQTTClient.publish(topic, payload, self._QoS)
**Description** Publishes an MQTT message to a corresponding job execution specific topic to update its status according to the parameters. Can be used to change a job from QUEUED to IN_PROGRESS to SUCEEDED or FAILED. **Syntax** .. code:: python #Update job with id 'jobId123' to succeeded state, specifying new status details, with expectedVersion=1, executionNumber=2. #For the response, include job execution state and not the job document myAWSIoTMQTTJobsClient.sendJobsUpdate('jobId123', jobExecutionStatus.JOB_EXECUTION_SUCCEEDED, statusDetailsMap, 1, 2, True, False) #Update job with id 'jobId456' to failed state myAWSIoTMQTTJobsClient.sendJobsUpdate('jobId456', jobExecutionStatus.JOB_EXECUTION_FAILED) **Parameters** *jobId* - JobID String of the execution to update the status of *status* - job execution status to change the job execution to. Member of jobExecutionStatus *statusDetails* - new status details to set on the job execution *expectedVersion* - The expected current version of the job execution. IoT jobs increments expectedVersion each time you update the job execution. If the version of the job execution stored in Jobs does not match, the update is rejected with a VersionMismatch error, and an ErrorResponse that contains the current job execution status data is returned. (This makes it unnecessary to perform a separate DescribeJobExecution request n order to obtain the job execution status data.) *executionNumber* - A number that identifies a particular job execution on a particular device. If not specified, the latest job execution is used. *includeJobExecutionState* - When included and set to True, the response contains the JobExecutionState field. The default is False. *includeJobDocument* - When included and set to True, the response contains the JobDocument. The default is False. *stepTimeoutInMinutes - Specifies the amount of time this device has to finish execution of this job. **Returns** True if the publish request has been sent to paho. False if the request did not reach paho.
**Description**
[ "**", "Description", "**" ]
def sendJobsUpdate(self, jobId, status, statusDetails=None, expectedVersion=0, executionNumber=0, includeJobExecutionState=False, includeJobDocument=False, stepTimeoutInMinutes=None): """ **Description** Publishes an MQTT message to a corresponding job execution specific topic to update its status according to the parameters. Can be used to change a job from QUEUED to IN_PROGRESS to SUCEEDED or FAILED. **Syntax** .. code:: python #Update job with id 'jobId123' to succeeded state, specifying new status details, with expectedVersion=1, executionNumber=2. #For the response, include job execution state and not the job document myAWSIoTMQTTJobsClient.sendJobsUpdate('jobId123', jobExecutionStatus.JOB_EXECUTION_SUCCEEDED, statusDetailsMap, 1, 2, True, False) #Update job with id 'jobId456' to failed state myAWSIoTMQTTJobsClient.sendJobsUpdate('jobId456', jobExecutionStatus.JOB_EXECUTION_FAILED) **Parameters** *jobId* - JobID String of the execution to update the status of *status* - job execution status to change the job execution to. Member of jobExecutionStatus *statusDetails* - new status details to set on the job execution *expectedVersion* - The expected current version of the job execution. IoT jobs increments expectedVersion each time you update the job execution. If the version of the job execution stored in Jobs does not match, the update is rejected with a VersionMismatch error, and an ErrorResponse that contains the current job execution status data is returned. (This makes it unnecessary to perform a separate DescribeJobExecution request n order to obtain the job execution status data.) *executionNumber* - A number that identifies a particular job execution on a particular device. If not specified, the latest job execution is used. *includeJobExecutionState* - When included and set to True, the response contains the JobExecutionState field. The default is False. *includeJobDocument* - When included and set to True, the response contains the JobDocument. The default is False. *stepTimeoutInMinutes - Specifies the amount of time this device has to finish execution of this job. **Returns** True if the publish request has been sent to paho. False if the request did not reach paho. """ topic = self._thingJobManager.getJobTopic(jobExecutionTopicType.JOB_UPDATE_TOPIC, jobExecutionTopicReplyType.JOB_REQUEST_TYPE, jobId) payload = self._thingJobManager.serializeJobExecutionUpdatePayload(status, statusDetails, expectedVersion, executionNumber, includeJobExecutionState, includeJobDocument, stepTimeoutInMinutes) return self._AWSIoTMQTTClient.publish(topic, payload, self._QoS)
[ "def", "sendJobsUpdate", "(", "self", ",", "jobId", ",", "status", ",", "statusDetails", "=", "None", ",", "expectedVersion", "=", "0", ",", "executionNumber", "=", "0", ",", "includeJobExecutionState", "=", "False", ",", "includeJobDocument", "=", "False", ",", "stepTimeoutInMinutes", "=", "None", ")", ":", "topic", "=", "self", ".", "_thingJobManager", ".", "getJobTopic", "(", "jobExecutionTopicType", ".", "JOB_UPDATE_TOPIC", ",", "jobExecutionTopicReplyType", ".", "JOB_REQUEST_TYPE", ",", "jobId", ")", "payload", "=", "self", ".", "_thingJobManager", ".", "serializeJobExecutionUpdatePayload", "(", "status", ",", "statusDetails", ",", "expectedVersion", ",", "executionNumber", ",", "includeJobExecutionState", ",", "includeJobDocument", ",", "stepTimeoutInMinutes", ")", "return", "self", ".", "_AWSIoTMQTTClient", ".", "publish", "(", "topic", ",", "payload", ",", "self", ".", "_QoS", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/MQTTLib.py#L1699-L1746
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/topics.py
python
_PublisherImpl.publish
(self, message, connection_override=None)
Publish the data to the topic. If the topic has no subscribers, the method will return without any affect. Access to publish() should be locked using acquire() and release() in order to ensure proper message publish ordering. @param message: message data instance to publish @type message: L{Message} @param connection_override: publish to this connection instead of all @type connection_override: L{Transport} @return: True if the data was published, False otherwise. @rtype: bool @raise genpy.SerializationError: if L{Message} instance is unable to serialize itself @raise rospy.ROSException: if topic has been closed or was closed during publish()
Publish the data to the topic. If the topic has no subscribers, the method will return without any affect. Access to publish() should be locked using acquire() and release() in order to ensure proper message publish ordering.
[ "Publish", "the", "data", "to", "the", "topic", ".", "If", "the", "topic", "has", "no", "subscribers", "the", "method", "will", "return", "without", "any", "affect", ".", "Access", "to", "publish", "()", "should", "be", "locked", "using", "acquire", "()", "and", "release", "()", "in", "order", "to", "ensure", "proper", "message", "publish", "ordering", "." ]
def publish(self, message, connection_override=None): """ Publish the data to the topic. If the topic has no subscribers, the method will return without any affect. Access to publish() should be locked using acquire() and release() in order to ensure proper message publish ordering. @param message: message data instance to publish @type message: L{Message} @param connection_override: publish to this connection instead of all @type connection_override: L{Transport} @return: True if the data was published, False otherwise. @rtype: bool @raise genpy.SerializationError: if L{Message} instance is unable to serialize itself @raise rospy.ROSException: if topic has been closed or was closed during publish() """ #TODO: should really just use IOError instead of rospy.ROSException if self.closed: # during shutdown, the topic can get closed, which creates # a race condition with user code testing is_shutdown if not is_shutdown(): raise ROSException("publish() to a closed topic") else: return if self.is_latch: self.latch = message if not self.has_connections(): #publish() falls through return False if connection_override is None: #copy connections so we can iterate safely conns = self.connections else: conns = [connection_override] # #2128 test our buffer. I don't now how this got closed in # that case, but we can at least diagnose the problem. b = self.buff try: b.tell() # serialize the message self.seq += 1 #count messages published to the topic serialize_message(b, self.seq, message) # send the buffer to all connections err_con = [] data = b.getvalue() for c in conns: try: if not is_shutdown(): c.write_data(data) except TransportTerminated as e: logdebug("publisher connection to [%s] terminated, see errorlog for details:\n%s"%(c.endpoint_id, traceback.format_exc())) err_con.append(c) except Exception as e: # greater severity level logdebug("publisher connection to [%s] terminated, see errorlog for details:\n%s"%(c.endpoint_id, traceback.format_exc())) err_con.append(c) # reset the buffer and update stats self.message_data_sent += b.tell() #STATS b.seek(0) b.truncate(0) except ValueError: # operations on self.buff can fail if topic is closed # during publish, which often happens during Ctrl-C. # diagnose the error and report accordingly. if self.closed: if is_shutdown(): # we offer no guarantees on publishes that occur # during shutdown, so this is not exceptional. return else: # this indicates that user-level code most likely # closed the topic, which is exceptional. raise ROSException("topic was closed during publish()") else: # unexpected, so re-raise original error raise # remove any bad connections for c in err_con: try: # connection will callback into remove_connection when # we close it c.close() except: pass
[ "def", "publish", "(", "self", ",", "message", ",", "connection_override", "=", "None", ")", ":", "#TODO: should really just use IOError instead of rospy.ROSException", "if", "self", ".", "closed", ":", "# during shutdown, the topic can get closed, which creates", "# a race condition with user code testing is_shutdown", "if", "not", "is_shutdown", "(", ")", ":", "raise", "ROSException", "(", "\"publish() to a closed topic\"", ")", "else", ":", "return", "if", "self", ".", "is_latch", ":", "self", ".", "latch", "=", "message", "if", "not", "self", ".", "has_connections", "(", ")", ":", "#publish() falls through", "return", "False", "if", "connection_override", "is", "None", ":", "#copy connections so we can iterate safely", "conns", "=", "self", ".", "connections", "else", ":", "conns", "=", "[", "connection_override", "]", "# #2128 test our buffer. I don't now how this got closed in", "# that case, but we can at least diagnose the problem.", "b", "=", "self", ".", "buff", "try", ":", "b", ".", "tell", "(", ")", "# serialize the message", "self", ".", "seq", "+=", "1", "#count messages published to the topic", "serialize_message", "(", "b", ",", "self", ".", "seq", ",", "message", ")", "# send the buffer to all connections", "err_con", "=", "[", "]", "data", "=", "b", ".", "getvalue", "(", ")", "for", "c", "in", "conns", ":", "try", ":", "if", "not", "is_shutdown", "(", ")", ":", "c", ".", "write_data", "(", "data", ")", "except", "TransportTerminated", "as", "e", ":", "logdebug", "(", "\"publisher connection to [%s] terminated, see errorlog for details:\\n%s\"", "%", "(", "c", ".", "endpoint_id", ",", "traceback", ".", "format_exc", "(", ")", ")", ")", "err_con", ".", "append", "(", "c", ")", "except", "Exception", "as", "e", ":", "# greater severity level", "logdebug", "(", "\"publisher connection to [%s] terminated, see errorlog for details:\\n%s\"", "%", "(", "c", ".", "endpoint_id", ",", "traceback", ".", "format_exc", "(", ")", ")", ")", "err_con", ".", "append", "(", "c", ")", "# reset the buffer and update stats", "self", ".", "message_data_sent", "+=", "b", ".", "tell", "(", ")", "#STATS", "b", ".", "seek", "(", "0", ")", "b", ".", "truncate", "(", "0", ")", "except", "ValueError", ":", "# operations on self.buff can fail if topic is closed", "# during publish, which often happens during Ctrl-C.", "# diagnose the error and report accordingly.", "if", "self", ".", "closed", ":", "if", "is_shutdown", "(", ")", ":", "# we offer no guarantees on publishes that occur", "# during shutdown, so this is not exceptional.", "return", "else", ":", "# this indicates that user-level code most likely", "# closed the topic, which is exceptional.", "raise", "ROSException", "(", "\"topic was closed during publish()\"", ")", "else", ":", "# unexpected, so re-raise original error", "raise", "# remove any bad connections", "for", "c", "in", "err_con", ":", "try", ":", "# connection will callback into remove_connection when", "# we close it", "c", ".", "close", "(", ")", "except", ":", "pass" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/topics.py#L1017-L1111
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/lldb/lldb_commands.py
python
__lldb_init_module
(debugger, *_args)
Register custom commands.
Register custom commands.
[ "Register", "custom", "commands", "." ]
def __lldb_init_module(debugger, *_args): """Register custom commands.""" debugger.HandleCommand( "command script add -f lldb_commands.PrintGlobalServiceContext mongodb-service-context") debugger.HandleCommand( "command script add -f lldb_commands.PrintGlobalServiceContext mongodb-dump-locks") debugger.HandleCommand("command alias mongodb-help help")
[ "def", "__lldb_init_module", "(", "debugger", ",", "*", "_args", ")", ":", "debugger", ".", "HandleCommand", "(", "\"command script add -f lldb_commands.PrintGlobalServiceContext mongodb-service-context\"", ")", "debugger", ".", "HandleCommand", "(", "\"command script add -f lldb_commands.PrintGlobalServiceContext mongodb-dump-locks\"", ")", "debugger", ".", "HandleCommand", "(", "\"command alias mongodb-help help\"", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/lldb/lldb_commands.py#L6-L12
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/commands.py
python
BuildExt.initialize_options
(self)
Prepare for new options
Prepare for new options
[ "Prepare", "for", "new", "options" ]
def initialize_options(self): """ Prepare for new options """ _build_ext.build_ext.initialize_options(self) if _option_defaults.has_key('build_ext'): for opt_name, default in _option_defaults['build_ext']: setattr(self, opt_name, default)
[ "def", "initialize_options", "(", "self", ")", ":", "_build_ext", ".", "build_ext", ".", "initialize_options", "(", "self", ")", "if", "_option_defaults", ".", "has_key", "(", "'build_ext'", ")", ":", "for", "opt_name", ",", "default", "in", "_option_defaults", "[", "'build_ext'", "]", ":", "setattr", "(", "self", ",", "opt_name", ",", "default", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/commands.py#L182-L187
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py
python
MacTool._CopyStringsFile
(self, source, dest)
Copies a .strings file using iconv to reconvert the input into UTF-16.
Copies a .strings file using iconv to reconvert the input into UTF-16.
[ "Copies", "a", ".", "strings", "file", "using", "iconv", "to", "reconvert", "the", "input", "into", "UTF", "-", "16", "." ]
def _CopyStringsFile(self, source, dest): """Copies a .strings file using iconv to reconvert the input into UTF-16.""" input_code = self._DetectInputEncoding(source) or "UTF-8" # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing # semicolon in dictionary. # on invalid files. Do the same kind of validation. import CoreFoundation with open(source, "rb") as in_file: s = in_file.read() d = CoreFoundation.CFDataCreate(None, s, len(s)) _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) if error: return with open(dest, "wb") as fp: fp.write(s.decode(input_code).encode("UTF-16"))
[ "def", "_CopyStringsFile", "(", "self", ",", "source", ",", "dest", ")", ":", "input_code", "=", "self", ".", "_DetectInputEncoding", "(", "source", ")", "or", "\"UTF-8\"", "# Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call", "# CFPropertyListCreateFromXMLData() behind the scenes; at least it prints", "# CFPropertyListCreateFromXMLData(): Old-style plist parser: missing", "# semicolon in dictionary.", "# on invalid files. Do the same kind of validation.", "import", "CoreFoundation", "with", "open", "(", "source", ",", "\"rb\"", ")", "as", "in_file", ":", "s", "=", "in_file", ".", "read", "(", ")", "d", "=", "CoreFoundation", ".", "CFDataCreate", "(", "None", ",", "s", ",", "len", "(", "s", ")", ")", "_", ",", "error", "=", "CoreFoundation", ".", "CFPropertyListCreateFromXMLData", "(", "None", ",", "d", ",", "0", ",", "None", ")", "if", "error", ":", "return", "with", "open", "(", "dest", ",", "\"wb\"", ")", "as", "fp", ":", "fp", ".", "write", "(", "s", ".", "decode", "(", "input_code", ")", ".", "encode", "(", "\"UTF-16\"", ")", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py#L138-L157
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/plugin.py
python
PluginData.SetClass
(self, cls)
Set the class used to create this plugins instance @param cls: class
Set the class used to create this plugins instance @param cls: class
[ "Set", "the", "class", "used", "to", "create", "this", "plugins", "instance", "@param", "cls", ":", "class" ]
def SetClass(self, cls): """Set the class used to create this plugins instance @param cls: class """ self._cls = cls
[ "def", "SetClass", "(", "self", ",", "cls", ")", ":", "self", ".", "_cls", "=", "cls" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/plugin.py#L380-L385
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/normalization.py
python
SyncBatchNorm.__init__
(self, num_features, eps=1e-5, momentum=0.9, affine=True, gamma_init='ones', beta_init='zeros', moving_mean_init='zeros', moving_var_init='ones', use_batch_statistics=None, process_groups=None)
Initialize SyncBatchNorm.
Initialize SyncBatchNorm.
[ "Initialize", "SyncBatchNorm", "." ]
def __init__(self, num_features, eps=1e-5, momentum=0.9, affine=True, gamma_init='ones', beta_init='zeros', moving_mean_init='zeros', moving_var_init='ones', use_batch_statistics=None, process_groups=None): """Initialize SyncBatchNorm.""" super(SyncBatchNorm, self).__init__(num_features, eps, momentum, affine, gamma_init, beta_init, moving_mean_init, moving_var_init, use_batch_statistics, process_groups=process_groups, input_dims='both')
[ "def", "__init__", "(", "self", ",", "num_features", ",", "eps", "=", "1e-5", ",", "momentum", "=", "0.9", ",", "affine", "=", "True", ",", "gamma_init", "=", "'ones'", ",", "beta_init", "=", "'zeros'", ",", "moving_mean_init", "=", "'zeros'", ",", "moving_var_init", "=", "'ones'", ",", "use_batch_statistics", "=", "None", ",", "process_groups", "=", "None", ")", ":", "super", "(", "SyncBatchNorm", ",", "self", ")", ".", "__init__", "(", "num_features", ",", "eps", ",", "momentum", ",", "affine", ",", "gamma_init", ",", "beta_init", ",", "moving_mean_init", ",", "moving_var_init", ",", "use_batch_statistics", ",", "process_groups", "=", "process_groups", ",", "input_dims", "=", "'both'", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/normalization.py#L730-L752
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/msvc.py
python
_augment_exception
(exc, version, arch='')
Add details to the exception message to help guide the user as to what action will resolve it.
Add details to the exception message to help guide the user as to what action will resolve it.
[ "Add", "details", "to", "the", "exception", "message", "to", "help", "guide", "the", "user", "as", "to", "what", "action", "will", "resolve", "it", "." ]
def _augment_exception(exc, version, arch=''): """ Add details to the exception message to help guide the user as to what action will resolve it. """ # Error if MSVC++ directory not found or environment not set message = exc.args[0] if "vcvarsall" in message.lower() or "visual c" in message.lower(): # Special error message if MSVC++ not installed tmpl = 'Microsoft Visual C++ {version:0.1f} is required.' message = tmpl.format(**locals()) msdownload = 'www.microsoft.com/download/details.aspx?id=%d' if version == 9.0: if arch.lower().find('ia64') > -1: # For VC++ 9.0, if IA64 support is needed, redirect user # to Windows SDK 7.0. # Note: No download link available from Microsoft. message += ' Get it with "Microsoft Windows SDK 7.0"' else: # For VC++ 9.0 redirect user to Vc++ for Python 2.7 : # This redirection link is maintained by Microsoft. # Contact vspython@microsoft.com if it needs updating. message += ' Get it from http://aka.ms/vcpython27' elif version == 10.0: # For VC++ 10.0 Redirect user to Windows SDK 7.1 message += ' Get it with "Microsoft Windows SDK 7.1": ' message += msdownload % 8279 elif version >= 14.0: # For VC++ 14.X Redirect user to latest Visual C++ Build Tools message += (' Get it with "Build Tools for Visual Studio": ' r'https://visualstudio.microsoft.com/downloads/') exc.args = (message, )
[ "def", "_augment_exception", "(", "exc", ",", "version", ",", "arch", "=", "''", ")", ":", "# Error if MSVC++ directory not found or environment not set", "message", "=", "exc", ".", "args", "[", "0", "]", "if", "\"vcvarsall\"", "in", "message", ".", "lower", "(", ")", "or", "\"visual c\"", "in", "message", ".", "lower", "(", ")", ":", "# Special error message if MSVC++ not installed", "tmpl", "=", "'Microsoft Visual C++ {version:0.1f} is required.'", "message", "=", "tmpl", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "msdownload", "=", "'www.microsoft.com/download/details.aspx?id=%d'", "if", "version", "==", "9.0", ":", "if", "arch", ".", "lower", "(", ")", ".", "find", "(", "'ia64'", ")", ">", "-", "1", ":", "# For VC++ 9.0, if IA64 support is needed, redirect user", "# to Windows SDK 7.0.", "# Note: No download link available from Microsoft.", "message", "+=", "' Get it with \"Microsoft Windows SDK 7.0\"'", "else", ":", "# For VC++ 9.0 redirect user to Vc++ for Python 2.7 :", "# This redirection link is maintained by Microsoft.", "# Contact vspython@microsoft.com if it needs updating.", "message", "+=", "' Get it from http://aka.ms/vcpython27'", "elif", "version", "==", "10.0", ":", "# For VC++ 10.0 Redirect user to Windows SDK 7.1", "message", "+=", "' Get it with \"Microsoft Windows SDK 7.1\": '", "message", "+=", "msdownload", "%", "8279", "elif", "version", ">=", "14.0", ":", "# For VC++ 14.X Redirect user to latest Visual C++ Build Tools", "message", "+=", "(", "' Get it with \"Build Tools for Visual Studio\": '", "r'https://visualstudio.microsoft.com/downloads/'", ")", "exc", ".", "args", "=", "(", "message", ",", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/msvc.py#L333-L366
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/scripts/cpp_lint.py
python
CheckSpacing
(filename, clean_lines, linenum, nesting_state, error)
Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for the correctness of various spacing issues in the code.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "issues", "in", "the", "code", "." ]
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. if IsBlankLine(line) and not nesting_state.InNamespaceBody(): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, we complain if there's a comment too near the text commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not Match(r'^\s*{ //', line) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # There should always be a space between the // and the comment commentend = commentpos + 2 if commentend < len(line) and not line[commentend] == ' ': # but some lines are exceptions -- e.g. if they're big # comment delimiters like: # //---------------------------------------------------------- # or are an empty C++ style Doxygen comment, like: # /// # or C++ style Doxygen comments placed after the variable: # ///< Header comment # //!< Header comment # or they begin with multiple slashes followed by a space: # //////// Header comment match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or Search(r'^/$', line[commentend:]) or Search(r'^!< ', line[commentend:]) or Search(r'^/< ', line[commentend:]) or Search(r'^/+ ', line[commentend:])) if not match: error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') CheckComment(line[commentpos:], filename, linenum, error) line = clean_lines.elided[linenum] # get rid of comments and strings # Don't try to do spacing checks for operator methods line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # Also ignore using ns::operator<<; match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') elif not Match(r'#.*include', line): # Avoid false positives on -> reduced_line = line.replace('->', '') # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) if (match and not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) if (match and not FindPreviousMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) # A pet peeve of mine: no spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') # Next we will look for issues with function calls. CheckSpacingForFunctionCall(filename, line, linenum, error) # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. match = Match(r'^(.*[^ ({]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<]". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'new char * []'. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search('for *\(.*[^:]:[^: ]', line) or Search('for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop')
[ "def", "CheckSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Don't use \"elided\" lines here, otherwise we can't check commented lines.", "# Don't want to use \"raw\" either, because we don't want to check inside C++11", "# raw strings,", "raw", "=", "clean_lines", ".", "lines_without_raw_strings", "line", "=", "raw", "[", "linenum", "]", "# Before nixing comments, check if the line is blank for no good", "# reason. This includes the first line after a block is opened, and", "# blank lines at the end of a function (ie, right before a line like '}'", "#", "# Skip all the blank line checks if we are immediately inside a", "# namespace body. In other words, don't issue blank line warnings", "# for this block:", "# namespace {", "#", "# }", "#", "# A warning about missing end of namespace comments will be issued instead.", "if", "IsBlankLine", "(", "line", ")", "and", "not", "nesting_state", ".", "InNamespaceBody", "(", ")", ":", "elided", "=", "clean_lines", ".", "elided", "prev_line", "=", "elided", "[", "linenum", "-", "1", "]", "prevbrace", "=", "prev_line", ".", "rfind", "(", "'{'", ")", "# TODO(unknown): Don't complain if line before blank line, and line after,", "# both start with alnums and are indented the same amount.", "# This ignores whitespace at the start of a namespace block", "# because those are not usually indented.", "if", "prevbrace", "!=", "-", "1", "and", "prev_line", "[", "prevbrace", ":", "]", ".", "find", "(", "'}'", ")", "==", "-", "1", ":", "# OK, we have a blank line at the start of a code block. Before we", "# complain, we check if it is an exception to the rule: The previous", "# non-empty line has the parameters of a function header that are indented", "# 4 spaces (because they did not fit in a 80 column line when placed on", "# the same line as the function name). We also check for the case where", "# the previous line is indented 6 spaces, which may happen when the", "# initializers of a constructor do not fit into a 80 column line.", "exception", "=", "False", "if", "Match", "(", "r' {6}\\w'", ",", "prev_line", ")", ":", "# Initializer list?", "# We are looking for the opening column of initializer list, which", "# should be indented 4 spaces to cause 6 space indentation afterwards.", "search_position", "=", "linenum", "-", "2", "while", "(", "search_position", ">=", "0", "and", "Match", "(", "r' {6}\\w'", ",", "elided", "[", "search_position", "]", ")", ")", ":", "search_position", "-=", "1", "exception", "=", "(", "search_position", ">=", "0", "and", "elided", "[", "search_position", "]", "[", ":", "5", "]", "==", "' :'", ")", "else", ":", "# Search for the function arguments or an initializer list. We use a", "# simple heuristic here: If the line is indented 4 spaces; and we have a", "# closing paren, without the opening paren, followed by an opening brace", "# or colon (for initializer lists) we assume that it is the last line of", "# a function header. If we have a colon indented 4 spaces, it is an", "# initializer list.", "exception", "=", "(", "Match", "(", "r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)'", ",", "prev_line", ")", "or", "Match", "(", "r' {4}:'", ",", "prev_line", ")", ")", "if", "not", "exception", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "2", ",", "'Redundant blank line at the start of a code block '", "'should be deleted.'", ")", "# Ignore blank lines at the end of a block in a long if-else", "# chain, like this:", "# if (condition1) {", "# // Something followed by a blank line", "#", "# } else if (condition2) {", "# // Something else", "# }", "if", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "next_line", "=", "raw", "[", "linenum", "+", "1", "]", "if", "(", "next_line", "and", "Match", "(", "r'\\s*}'", ",", "next_line", ")", "and", "next_line", ".", "find", "(", "'} else '", ")", "==", "-", "1", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Redundant blank line at the end of a code block '", "'should be deleted.'", ")", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "prev_line", ")", "if", "matched", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Do not leave a blank line after \"%s:\"'", "%", "matched", ".", "group", "(", "1", ")", ")", "# Next, we complain if there's a comment too near the text", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", ":", "# Check if the // may be in quotes. If so, ignore it", "# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison", "if", "(", "line", ".", "count", "(", "'\"'", ",", "0", ",", "commentpos", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ",", "0", ",", "commentpos", ")", ")", "%", "2", "==", "0", ":", "# not in quotes", "# Allow one space for new scopes, two spaces otherwise:", "if", "(", "not", "Match", "(", "r'^\\s*{ //'", ",", "line", ")", "and", "(", "(", "commentpos", ">=", "1", "and", "line", "[", "commentpos", "-", "1", "]", "not", "in", "string", ".", "whitespace", ")", "or", "(", "commentpos", ">=", "2", "and", "line", "[", "commentpos", "-", "2", "]", "not", "in", "string", ".", "whitespace", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "2", ",", "'At least two spaces is best between code and comments'", ")", "# There should always be a space between the // and the comment", "commentend", "=", "commentpos", "+", "2", "if", "commentend", "<", "len", "(", "line", ")", "and", "not", "line", "[", "commentend", "]", "==", "' '", ":", "# but some lines are exceptions -- e.g. if they're big", "# comment delimiters like:", "# //----------------------------------------------------------", "# or are an empty C++ style Doxygen comment, like:", "# ///", "# or C++ style Doxygen comments placed after the variable:", "# ///< Header comment", "# //!< Header comment", "# or they begin with multiple slashes followed by a space:", "# //////// Header comment", "match", "=", "(", "Search", "(", "r'[=/-]{4,}\\s*$'", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/$'", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^!< '", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/< '", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/+ '", ",", "line", "[", "commentend", ":", "]", ")", ")", "if", "not", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "4", ",", "'Should have a space between // and comment'", ")", "CheckComment", "(", "line", "[", "commentpos", ":", "]", ",", "filename", ",", "linenum", ",", "error", ")", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "# Don't try to do spacing checks for operator methods", "line", "=", "re", ".", "sub", "(", "r'operator(==|!=|<|<<|<=|>=|>>|>)\\('", ",", "'operator\\('", ",", "line", ")", "# We allow no-spaces around = within an if: \"if ( (a=Foo()) == 0 )\".", "# Otherwise not. Note we only check for non-spaces on *both* sides;", "# sometimes people put non-spaces on one side when aligning ='s among", "# many lines (not that this is behavior that I approve of...)", "if", "Search", "(", "r'[\\w.]=[\\w.]'", ",", "line", ")", "and", "not", "Search", "(", "r'\\b(if|while) '", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "4", ",", "'Missing spaces around ='", ")", "# It's ok not to have spaces around binary operators like + - * /, but if", "# there's too little whitespace, we get concerned. It's hard to tell,", "# though, so we punt on this one for now. TODO.", "# You should always have whitespace around binary operators.", "#", "# Check <= and >= first to avoid false positives with < and >, then", "# check non-include lines for spacing around < and >.", "match", "=", "Search", "(", "r'[^<>=!\\s](==|!=|<=|>=)[^<>=!\\s]'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# We allow no-spaces around << when used like this: 10<<20, but", "# not otherwise (particularly, not when used as streams)", "# Also ignore using ns::operator<<;", "match", "=", "Search", "(", "r'(operator|\\S)(?:L|UL|ULL|l|ul|ull)?<<(\\S)'", ",", "line", ")", "if", "(", "match", "and", "not", "(", "match", ".", "group", "(", "1", ")", ".", "isdigit", "(", ")", "and", "match", ".", "group", "(", "2", ")", ".", "isdigit", "(", ")", ")", "and", "not", "(", "match", ".", "group", "(", "1", ")", "==", "'operator'", "and", "match", ".", "group", "(", "2", ")", "==", "';'", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around <<'", ")", "elif", "not", "Match", "(", "r'#.*include'", ",", "line", ")", ":", "# Avoid false positives on ->", "reduced_line", "=", "line", ".", "replace", "(", "'->'", ",", "''", ")", "# Look for < that is not surrounded by spaces. This is only", "# triggered if both sides are missing spaces, even though", "# technically should should flag if at least one side is missing a", "# space. This is done to avoid some false positives with shifts.", "match", "=", "Search", "(", "r'[^\\s<]<([^\\s=<].*)'", ",", "reduced_line", ")", "if", "(", "match", "and", "not", "FindNextMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "match", ".", "group", "(", "1", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around <'", ")", "# Look for > that is not surrounded by spaces. Similar to the", "# above, we only trigger if both sides are missing spaces to avoid", "# false positives with shifts.", "match", "=", "Search", "(", "r'^(.*[^\\s>])>[^\\s=>]'", ",", "reduced_line", ")", "if", "(", "match", "and", "not", "FindPreviousMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "match", ".", "group", "(", "1", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around >'", ")", "# We allow no-spaces around >> for almost anything. This is because", "# C++11 allows \">>\" to close nested templates, which accounts for", "# most cases when \">>\" is not followed by a space.", "#", "# We still warn on \">>\" followed by alpha character, because that is", "# likely due to \">>\" being used for right shifts, e.g.:", "# value >> alpha", "#", "# When \">>\" is used to close templates, the alphanumeric letter that", "# follows would be part of an identifier, and there should still be", "# a space separating the template type and the identifier.", "# type<type<type>> alpha", "match", "=", "Search", "(", "r'>>[a-zA-Z_]'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around >>'", ")", "# There shouldn't be space around unary operators", "match", "=", "Search", "(", "r'(!\\s|~\\s|[\\s]--[\\s;]|[\\s]\\+\\+[\\s;])'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "4", ",", "'Extra space for operator %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# A pet peeve of mine: no spaces after an if, while, switch, or for", "match", "=", "Search", "(", "r' (if\\(|for\\(|while\\(|switch\\()'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Missing space before ( in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# For if/for/while/switch, the left and right parens should be", "# consistent about how many spaces are inside the parens, and", "# there should either be zero or one spaces inside the parens.", "# We don't want: \"if ( foo)\" or \"if ( foo )\".", "# Exception: \"for ( ; foo; bar)\" and \"for (foo; bar; )\" are allowed.", "match", "=", "Search", "(", "r'\\b(if|for|while|switch)\\s*'", "r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$'", ",", "line", ")", "if", "match", ":", "if", "len", "(", "match", ".", "group", "(", "2", ")", ")", "!=", "len", "(", "match", ".", "group", "(", "4", ")", ")", ":", "if", "not", "(", "match", ".", "group", "(", "3", ")", "==", "';'", "and", "len", "(", "match", ".", "group", "(", "2", ")", ")", "==", "1", "+", "len", "(", "match", ".", "group", "(", "4", ")", ")", "or", "not", "match", ".", "group", "(", "2", ")", "and", "Search", "(", "r'\\bfor\\s*\\(.*; \\)'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Mismatching spaces inside () in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "if", "len", "(", "match", ".", "group", "(", "2", ")", ")", "not", "in", "[", "0", ",", "1", "]", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Should have zero or one spaces inside ( and ) in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# You should always have a space after a comma (either as fn arg or operator)", "#", "# This does not apply when the non-space character following the", "# comma is another comma, since the only time when that happens is", "# for empty macro arguments.", "#", "# We run this check in two passes: first pass on elided lines to", "# verify that lines contain missing whitespaces, second pass on raw", "# lines to confirm that those missing whitespaces are not due to", "# elided comments.", "if", "Search", "(", "r',[^,\\s]'", ",", "line", ")", "and", "Search", "(", "r',[^,\\s]'", ",", "raw", "[", "linenum", "]", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comma'", ",", "3", ",", "'Missing space after ,'", ")", "# You should always have a space after a semicolon", "# except for few corner cases", "# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more", "# space after ;", "if", "Search", "(", "r';[^\\s};\\\\)/]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "3", ",", "'Missing space after ;'", ")", "# Next we will look for issues with function calls.", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", "# Except after an opening paren, or after another opening brace (in case of", "# an initializer list, for instance), you should have spaces before your", "# braces. And since you should never have braces at the beginning of a line,", "# this is an easy test.", "match", "=", "Match", "(", "r'^(.*[^ ({]){'", ",", "line", ")", "if", "match", ":", "# Try a bit harder to check for brace initialization. This", "# happens in one of the following forms:", "# Constructor() : initializer_list_{} { ... }", "# Constructor{}.MemberFunction()", "# Type variable{};", "# FunctionCall(type{}, ...);", "# LastArgument(..., type{});", "# LOG(INFO) << type{} << \" ...\";", "# map_of_type[{...}] = ...;", "#", "# We check for the character following the closing brace, and", "# silence the warning if it's one of those listed above, i.e.", "# \"{.;,)<]\".", "#", "# To account for nested initializer list, we allow any number of", "# closing braces up to \"{;,)<\". We can't simply silence the", "# warning on first sight of closing brace, because that would", "# cause false negatives for things that are not initializer lists.", "# Silence this: But not this:", "# Outer{ if (...) {", "# Inner{...} if (...){ // Missing space before {", "# }; }", "#", "# There is a false negative with this approach if people inserted", "# spurious semicolons, e.g. \"if (cond){};\", but we will catch the", "# spurious semicolon with a separate check.", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "trailing_text", "=", "''", "if", "endpos", ">", "-", "1", ":", "trailing_text", "=", "endline", "[", "endpos", ":", "]", "for", "offset", "in", "xrange", "(", "endlinenum", "+", "1", ",", "min", "(", "endlinenum", "+", "3", ",", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ")", ")", ":", "trailing_text", "+=", "clean_lines", ".", "elided", "[", "offset", "]", "if", "not", "Match", "(", "r'^[\\s}]*[{.;,)<\\]]'", ",", "trailing_text", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before {'", ")", "# Make sure '} else {' has spaces.", "if", "Search", "(", "r'}else'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before else'", ")", "# You shouldn't have spaces before your brackets, except maybe after", "# 'delete []' or 'new char * []'.", "if", "Search", "(", "r'\\w\\s+\\['", ",", "line", ")", "and", "not", "Search", "(", "r'delete\\s+\\['", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Extra space before ['", ")", "# You shouldn't have a space before a semicolon at the end of the line.", "# There's a special case for \"for\" since the style guide allows space before", "# the semicolon there.", "if", "Search", "(", "r':\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Semicolon defining empty statement. Use {} instead.'", ")", "elif", "Search", "(", "r'^\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Line contains only semicolon. If this should be an empty statement, '", "'use {} instead.'", ")", "elif", "(", "Search", "(", "r'\\s+;\\s*$'", ",", "line", ")", "and", "not", "Search", "(", "r'\\bfor\\b'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Extra space before last semicolon. If this should be an empty '", "'statement, use {} instead.'", ")", "# In range-based for, we wanted spaces before and after the colon, but", "# not around \"::\" tokens that might appear.", "if", "(", "Search", "(", "'for *\\(.*[^:]:[^: ]'", ",", "line", ")", "or", "Search", "(", "'for *\\(.*[^: ]:[^:]'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/forcolon'", ",", "2", ",", "'Missing space around colon in range-based for loop'", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/scripts/cpp_lint.py#L2643-L2988
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
PageSetupDialogData.SetMarginBottomRight
(*args, **kwargs)
return _windows_.PageSetupDialogData_SetMarginBottomRight(*args, **kwargs)
SetMarginBottomRight(self, Point pt)
SetMarginBottomRight(self, Point pt)
[ "SetMarginBottomRight", "(", "self", "Point", "pt", ")" ]
def SetMarginBottomRight(*args, **kwargs): """SetMarginBottomRight(self, Point pt)""" return _windows_.PageSetupDialogData_SetMarginBottomRight(*args, **kwargs)
[ "def", "SetMarginBottomRight", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PageSetupDialogData_SetMarginBottomRight", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L4959-L4961
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/image/detection.py
python
CreateMultiRandCropAugmenter
(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_prob=0)
return DetRandomSelectAug(augs, skip_prob=skip_prob)
Helper function to create multiple random crop augmenters. Parameters ---------- min_object_covered : float or list of float, default=0.1 The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float or list of float, default=0.3 The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33) The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0) The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int or list of int, default=50 Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. Examples -------- >>> # An example of creating multiple random crop augmenters >>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters >>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters >>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)] >>> min_eject_coverage = 0.3 >>> max_attempts = 50 >>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, min_eject_coverage=min_eject_coverage, max_attempts=max_attempts, skip_prob=0) >>> aug.dumps() # show some details
Helper function to create multiple random crop augmenters.
[ "Helper", "function", "to", "create", "multiple", "random", "crop", "augmenters", "." ]
def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_prob=0): """Helper function to create multiple random crop augmenters. Parameters ---------- min_object_covered : float or list of float, default=0.1 The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. min_eject_coverage : float or list of float, default=0.3 The minimum coverage of cropped sample w.r.t its original size. With this constraint, objects that have marginal area after crop will be discarded. aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33) The cropped area of the image must have an aspect ratio = width / height within this range. area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0) The cropped area of the image must contain a fraction of the supplied image within in this range. max_attempts : int or list of int, default=50 Number of attempts at generating a cropped/padded region of the image of the specified constraints. After max_attempts failures, return the original image. Examples -------- >>> # An example of creating multiple random crop augmenters >>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters >>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters >>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)] >>> min_eject_coverage = 0.3 >>> max_attempts = 50 >>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, min_eject_coverage=min_eject_coverage, max_attempts=max_attempts, skip_prob=0) >>> aug.dumps() # show some details """ def align_parameters(params): """Align parameters as pairs""" out_params = [] num = 1 for p in params: if not isinstance(p, list): p = [p] out_params.append(p) num = max(num, len(p)) # align for each param for k, p in enumerate(out_params): if len(p) != num: assert len(p) == 1 out_params[k] = p * num return out_params aligned_params = align_parameters([min_object_covered, aspect_ratio_range, area_range, min_eject_coverage, max_attempts]) augs = [] for moc, arr, ar, mec, ma in zip(*aligned_params): augs.append(DetRandomCropAug(min_object_covered=moc, aspect_ratio_range=arr, area_range=ar, min_eject_coverage=mec, max_attempts=ma)) return DetRandomSelectAug(augs, skip_prob=skip_prob)
[ "def", "CreateMultiRandCropAugmenter", "(", "min_object_covered", "=", "0.1", ",", "aspect_ratio_range", "=", "(", "0.75", ",", "1.33", ")", ",", "area_range", "=", "(", "0.05", ",", "1.0", ")", ",", "min_eject_coverage", "=", "0.3", ",", "max_attempts", "=", "50", ",", "skip_prob", "=", "0", ")", ":", "def", "align_parameters", "(", "params", ")", ":", "\"\"\"Align parameters as pairs\"\"\"", "out_params", "=", "[", "]", "num", "=", "1", "for", "p", "in", "params", ":", "if", "not", "isinstance", "(", "p", ",", "list", ")", ":", "p", "=", "[", "p", "]", "out_params", ".", "append", "(", "p", ")", "num", "=", "max", "(", "num", ",", "len", "(", "p", ")", ")", "# align for each param", "for", "k", ",", "p", "in", "enumerate", "(", "out_params", ")", ":", "if", "len", "(", "p", ")", "!=", "num", ":", "assert", "len", "(", "p", ")", "==", "1", "out_params", "[", "k", "]", "=", "p", "*", "num", "return", "out_params", "aligned_params", "=", "align_parameters", "(", "[", "min_object_covered", ",", "aspect_ratio_range", ",", "area_range", ",", "min_eject_coverage", ",", "max_attempts", "]", ")", "augs", "=", "[", "]", "for", "moc", ",", "arr", ",", "ar", ",", "mec", ",", "ma", "in", "zip", "(", "*", "aligned_params", ")", ":", "augs", ".", "append", "(", "DetRandomCropAug", "(", "min_object_covered", "=", "moc", ",", "aspect_ratio_range", "=", "arr", ",", "area_range", "=", "ar", ",", "min_eject_coverage", "=", "mec", ",", "max_attempts", "=", "ma", ")", ")", "return", "DetRandomSelectAug", "(", "augs", ",", "skip_prob", "=", "skip_prob", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/image/detection.py#L418-L480
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/traveltime/TravelTimeManager.py
python
TravelTimeManager.createForwardOperator
(self, **kwargs)
return fop
Create default forward operator for Traveltime modelling. Your want your Manager use a special forward operator you can add them here on default Dijkstra is used.
Create default forward operator for Traveltime modelling.
[ "Create", "default", "forward", "operator", "for", "Traveltime", "modelling", "." ]
def createForwardOperator(self, **kwargs): """Create default forward operator for Traveltime modelling. Your want your Manager use a special forward operator you can add them here on default Dijkstra is used. """ fop = TravelTimeDijkstraModelling(**kwargs) return fop
[ "def", "createForwardOperator", "(", "self", ",", "*", "*", "kwargs", ")", ":", "fop", "=", "TravelTimeDijkstraModelling", "(", "*", "*", "kwargs", ")", "return", "fop" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/traveltime/TravelTimeManager.py#L47-L54
irods/irods
ed6328646cee87182098d569919004049bf4ce21
scripts/irods/pyparsing.py
python
ParserElement.__sub__
(self, other)
return And( [ self, And._ErrorStop(), other ] )
Implementation of - operator, returns C{L{And}} with error stop
Implementation of - operator, returns C{L{And}} with error stop
[ "Implementation", "of", "-", "operator", "returns", "C", "{", "L", "{", "And", "}}", "with", "error", "stop" ]
def __sub__(self, other): """Implementation of - operator, returns C{L{And}} with error stop""" if isinstance( other, basestring ): other = ParserElement.literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, And._ErrorStop(), other ] )
[ "def", "__sub__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "And", "(", "[", "self", ",", "And", ".", "_ErrorStop", "(", ")", ",", "other", "]", ")" ]
https://github.com/irods/irods/blob/ed6328646cee87182098d569919004049bf4ce21/scripts/irods/pyparsing.py#L1283-L1291
google/omaha
61e8c2833fd69c9a13978400108e5b9ebff24a09
omaha/site_scons/site_tools/atlmfc_vc12_0.py
python
_FindLocalInstall
()
Returns the directory containing the local install of the tool. Returns: Path to tool (as a string), or None if not found.
Returns the directory containing the local install of the tool.
[ "Returns", "the", "directory", "containing", "the", "local", "install", "of", "the", "tool", "." ]
def _FindLocalInstall(): """Returns the directory containing the local install of the tool. Returns: Path to tool (as a string), or None if not found. """ default_dir = os.environ['VCINSTALLDIR'] + 'atlmfc' if os.path.exists(default_dir): return default_dir else: return None
[ "def", "_FindLocalInstall", "(", ")", ":", "default_dir", "=", "os", ".", "environ", "[", "'VCINSTALLDIR'", "]", "+", "'atlmfc'", "if", "os", ".", "path", ".", "exists", "(", "default_dir", ")", ":", "return", "default_dir", "else", ":", "return", "None" ]
https://github.com/google/omaha/blob/61e8c2833fd69c9a13978400108e5b9ebff24a09/omaha/site_scons/site_tools/atlmfc_vc12_0.py#L25-L35
MiniZinc/libminizinc
0848ce7ec78d3051cbe0f9e558af3c9dcfe65606
docs/utils/sphinxtogithub.py
python
sphinx_extension
(app, exception)
Wrapped up as a Sphinx Extension
Wrapped up as a Sphinx Extension
[ "Wrapped", "up", "as", "a", "Sphinx", "Extension" ]
def sphinx_extension(app, exception): "Wrapped up as a Sphinx Extension" if not app.builder.name in ("html", "dirhtml"): return if not app.config.sphinx_to_github: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Disabled, doing nothing.") return if exception: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Exception raised in main build, doing nothing.") return dir_helper = DirHelper( os.path.isdir, os.listdir, os.walk, shutil.rmtree ) file_helper = FileSystemHelper( lambda f, mode: codecs.open(f, mode, app.config.sphinx_to_github_encoding), os.path.join, shutil.move, os.path.exists ) operations_factory = OperationsFactory() handler_factory = HandlerFactory() layout_factory = LayoutFactory( operations_factory, handler_factory, file_helper, dir_helper, app.config.sphinx_to_github_verbose, sys.stdout, force=True ) layout = layout_factory.create_layout(app.outdir) layout.process()
[ "def", "sphinx_extension", "(", "app", ",", "exception", ")", ":", "if", "not", "app", ".", "builder", ".", "name", "in", "(", "\"html\"", ",", "\"dirhtml\"", ")", ":", "return", "if", "not", "app", ".", "config", ".", "sphinx_to_github", ":", "if", "app", ".", "config", ".", "sphinx_to_github_verbose", ":", "print", "(", "\"Sphinx-to-github: Disabled, doing nothing.\"", ")", "return", "if", "exception", ":", "if", "app", ".", "config", ".", "sphinx_to_github_verbose", ":", "print", "(", "\"Sphinx-to-github: Exception raised in main build, doing nothing.\"", ")", "return", "dir_helper", "=", "DirHelper", "(", "os", ".", "path", ".", "isdir", ",", "os", ".", "listdir", ",", "os", ".", "walk", ",", "shutil", ".", "rmtree", ")", "file_helper", "=", "FileSystemHelper", "(", "lambda", "f", ",", "mode", ":", "codecs", ".", "open", "(", "f", ",", "mode", ",", "app", ".", "config", ".", "sphinx_to_github_encoding", ")", ",", "os", ".", "path", ".", "join", ",", "shutil", ".", "move", ",", "os", ".", "path", ".", "exists", ")", "operations_factory", "=", "OperationsFactory", "(", ")", "handler_factory", "=", "HandlerFactory", "(", ")", "layout_factory", "=", "LayoutFactory", "(", "operations_factory", ",", "handler_factory", ",", "file_helper", ",", "dir_helper", ",", "app", ".", "config", ".", "sphinx_to_github_verbose", ",", "sys", ".", "stdout", ",", "force", "=", "True", ")", "layout", "=", "layout_factory", ".", "create_layout", "(", "app", ".", "outdir", ")", "layout", ".", "process", "(", ")" ]
https://github.com/MiniZinc/libminizinc/blob/0848ce7ec78d3051cbe0f9e558af3c9dcfe65606/docs/utils/sphinxtogithub.py#L300-L344
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
GridSizer.GetCols
(*args, **kwargs)
return _core_.GridSizer_GetCols(*args, **kwargs)
GetCols(self) -> int Returns the number of columns in the sizer.
GetCols(self) -> int
[ "GetCols", "(", "self", ")", "-", ">", "int" ]
def GetCols(*args, **kwargs): """ GetCols(self) -> int Returns the number of columns in the sizer. """ return _core_.GridSizer_GetCols(*args, **kwargs)
[ "def", "GetCols", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GridSizer_GetCols", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L15237-L15243
Ardour/ardour
a63a18a3387b90c0920d9b1668d2a50bd6302b83
tools/autowaf.py
python
set_options
(opt, debug_by_default=False)
Add standard autowaf options if they havn't been added yet
Add standard autowaf options if they havn't been added yet
[ "Add", "standard", "autowaf", "options", "if", "they", "havn", "t", "been", "added", "yet" ]
def set_options(opt, debug_by_default=False): "Add standard autowaf options if they havn't been added yet" global g_step if g_step > 0: return # Install directory options dirs_options = opt.add_option_group('Installation directories', '') # Move --prefix and --destdir to directory options group for k in ('--prefix', '--destdir'): option = opt.parser.get_option(k) if option: opt.parser.remove_option(k) dirs_options.add_option(option) # Standard directory options dirs_options.add_option('--bindir', type='string', help="Executable programs [Default: PREFIX/bin]") dirs_options.add_option('--configdir', type='string', help="Configuration data [Default: PREFIX/etc]") dirs_options.add_option('--datadir', type='string', help="Shared data [Default: PREFIX/share]") dirs_options.add_option('--includedir', type='string', help="Header files [Default: PREFIX/include]") dirs_options.add_option('--libdir', type='string', help="Libraries [Default: PREFIX/lib]") dirs_options.add_option('--mandir', type='string', help="Manual pages [Default: DATADIR/man]") dirs_options.add_option('--docdir', type='string', help="HTML documentation [Default: DATADIR/doc]") # Build options if debug_by_default: opt.add_option('--optimize', action='store_false', default=True, dest='debug', help="Build optimized binaries") else: opt.add_option('--debug', action='store_true', default=False, dest='debug', help="Build debuggable binaries") opt.add_option('--pardebug', action='store_true', default=False, dest='pardebug', help="Build parallel-installable debuggable libraries with D suffix") opt.add_option('--grind', action='store_true', default=False, dest='grind', help="Run tests in valgrind") opt.add_option('--strict', action='store_true', default=False, dest='strict', help="Use strict compiler flags and show all warnings") opt.add_option('--ultra-strict', action='store_true', default=False, dest='ultra_strict', help="Use even stricter compiler flags (likely to trigger many warnings in library headers)") opt.add_option('--docs', action='store_true', default=False, dest='docs', help="Build documentation - requires doxygen") g_step = 1
[ "def", "set_options", "(", "opt", ",", "debug_by_default", "=", "False", ")", ":", "global", "g_step", "if", "g_step", ">", "0", ":", "return", "# Install directory options", "dirs_options", "=", "opt", ".", "add_option_group", "(", "'Installation directories'", ",", "''", ")", "# Move --prefix and --destdir to directory options group", "for", "k", "in", "(", "'--prefix'", ",", "'--destdir'", ")", ":", "option", "=", "opt", ".", "parser", ".", "get_option", "(", "k", ")", "if", "option", ":", "opt", ".", "parser", ".", "remove_option", "(", "k", ")", "dirs_options", ".", "add_option", "(", "option", ")", "# Standard directory options", "dirs_options", ".", "add_option", "(", "'--bindir'", ",", "type", "=", "'string'", ",", "help", "=", "\"Executable programs [Default: PREFIX/bin]\"", ")", "dirs_options", ".", "add_option", "(", "'--configdir'", ",", "type", "=", "'string'", ",", "help", "=", "\"Configuration data [Default: PREFIX/etc]\"", ")", "dirs_options", ".", "add_option", "(", "'--datadir'", ",", "type", "=", "'string'", ",", "help", "=", "\"Shared data [Default: PREFIX/share]\"", ")", "dirs_options", ".", "add_option", "(", "'--includedir'", ",", "type", "=", "'string'", ",", "help", "=", "\"Header files [Default: PREFIX/include]\"", ")", "dirs_options", ".", "add_option", "(", "'--libdir'", ",", "type", "=", "'string'", ",", "help", "=", "\"Libraries [Default: PREFIX/lib]\"", ")", "dirs_options", ".", "add_option", "(", "'--mandir'", ",", "type", "=", "'string'", ",", "help", "=", "\"Manual pages [Default: DATADIR/man]\"", ")", "dirs_options", ".", "add_option", "(", "'--docdir'", ",", "type", "=", "'string'", ",", "help", "=", "\"HTML documentation [Default: DATADIR/doc]\"", ")", "# Build options", "if", "debug_by_default", ":", "opt", ".", "add_option", "(", "'--optimize'", ",", "action", "=", "'store_false'", ",", "default", "=", "True", ",", "dest", "=", "'debug'", ",", "help", "=", "\"Build optimized binaries\"", ")", "else", ":", "opt", ".", "add_option", "(", "'--debug'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'debug'", ",", "help", "=", "\"Build debuggable binaries\"", ")", "opt", ".", "add_option", "(", "'--pardebug'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'pardebug'", ",", "help", "=", "\"Build parallel-installable debuggable libraries with D suffix\"", ")", "opt", ".", "add_option", "(", "'--grind'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'grind'", ",", "help", "=", "\"Run tests in valgrind\"", ")", "opt", ".", "add_option", "(", "'--strict'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'strict'", ",", "help", "=", "\"Use strict compiler flags and show all warnings\"", ")", "opt", ".", "add_option", "(", "'--ultra-strict'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'ultra_strict'", ",", "help", "=", "\"Use even stricter compiler flags (likely to trigger many warnings in library headers)\"", ")", "opt", ".", "add_option", "(", "'--docs'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'docs'", ",", "help", "=", "\"Build documentation - requires doxygen\"", ")", "g_step", "=", "1" ]
https://github.com/Ardour/ardour/blob/a63a18a3387b90c0920d9b1668d2a50bd6302b83/tools/autowaf.py#L34-L86
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.SetSizeWH
(*args, **kwargs)
return _core_.Window_SetSizeWH(*args, **kwargs)
SetSizeWH(self, int width, int height) Sets the size of the window in pixels.
SetSizeWH(self, int width, int height)
[ "SetSizeWH", "(", "self", "int", "width", "int", "height", ")" ]
def SetSizeWH(*args, **kwargs): """ SetSizeWH(self, int width, int height) Sets the size of the window in pixels. """ return _core_.Window_SetSizeWH(*args, **kwargs)
[ "def", "SetSizeWH", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_SetSizeWH", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L9365-L9371
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/ltisys.py
python
TransferFunction.__new__
(cls, *system, **kwargs)
return super(TransferFunction, cls).__new__(cls)
Handle object conversion if input is an instance of lti.
Handle object conversion if input is an instance of lti.
[ "Handle", "object", "conversion", "if", "input", "is", "an", "instance", "of", "lti", "." ]
def __new__(cls, *system, **kwargs): """Handle object conversion if input is an instance of lti.""" if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): return system[0].to_tf() # Choose whether to inherit from `lti` or from `dlti` if cls is TransferFunction: if kwargs.get('dt') is None: return TransferFunctionContinuous.__new__( TransferFunctionContinuous, *system, **kwargs) else: return TransferFunctionDiscrete.__new__( TransferFunctionDiscrete, *system, **kwargs) # No special conversion needed return super(TransferFunction, cls).__new__(cls)
[ "def", "__new__", "(", "cls", ",", "*", "system", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "system", ")", "==", "1", "and", "isinstance", "(", "system", "[", "0", "]", ",", "LinearTimeInvariant", ")", ":", "return", "system", "[", "0", "]", ".", "to_tf", "(", ")", "# Choose whether to inherit from `lti` or from `dlti`", "if", "cls", "is", "TransferFunction", ":", "if", "kwargs", ".", "get", "(", "'dt'", ")", "is", "None", ":", "return", "TransferFunctionContinuous", ".", "__new__", "(", "TransferFunctionContinuous", ",", "*", "system", ",", "*", "*", "kwargs", ")", "else", ":", "return", "TransferFunctionDiscrete", ".", "__new__", "(", "TransferFunctionDiscrete", ",", "*", "system", ",", "*", "*", "kwargs", ")", "# No special conversion needed", "return", "super", "(", "TransferFunction", ",", "cls", ")", ".", "__new__", "(", "cls", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L559-L578
PaddlePaddle/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
tools/external_converter_v2/utils/net/net_parser.py
python
NetParser._funcs_dict
(self)
The dict of funcs.
The dict of funcs.
[ "The", "dict", "of", "funcs", "." ]
def _funcs_dict(self): """ The dict of funcs. """ for func_io in self.func_io_list: func_type = func_io.get_type() if func_type not in self.funcs.keys(): self.funcs[func_type] = list() self.funcs[func_type].append(func_io)
[ "def", "_funcs_dict", "(", "self", ")", ":", "for", "func_io", "in", "self", ".", "func_io_list", ":", "func_type", "=", "func_io", ".", "get_type", "(", ")", "if", "func_type", "not", "in", "self", ".", "funcs", ".", "keys", "(", ")", ":", "self", ".", "funcs", "[", "func_type", "]", "=", "list", "(", ")", "self", ".", "funcs", "[", "func_type", "]", ".", "append", "(", "func_io", ")" ]
https://github.com/PaddlePaddle/Anakin/blob/5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730/tools/external_converter_v2/utils/net/net_parser.py#L79-L87
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISSumBanks.py
python
ReflectometryISISSumBanks.name
(self)
return 'ReflectometryISISSumBanks'
Return the name of the algorithm.
Return the name of the algorithm.
[ "Return", "the", "name", "of", "the", "algorithm", "." ]
def name(self): """Return the name of the algorithm.""" return 'ReflectometryISISSumBanks'
[ "def", "name", "(", "self", ")", ":", "return", "'ReflectometryISISSumBanks'" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISSumBanks.py#L22-L24
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
demo/HuggingFace/NNDF/torch_utils.py
python
use_cuda
(func: Callable)
return wrapper
Tries to send all parameters of a given function to cuda device if user supports it. Object must have a "to(device: str)" and maps to target device "cuda" Basically, uses torch implementation. Wrapped functions musts have keyword argument "use_cuda: bool" which enables or disables toggling of cuda.
Tries to send all parameters of a given function to cuda device if user supports it. Object must have a "to(device: str)" and maps to target device "cuda" Basically, uses torch implementation.
[ "Tries", "to", "send", "all", "parameters", "of", "a", "given", "function", "to", "cuda", "device", "if", "user", "supports", "it", ".", "Object", "must", "have", "a", "to", "(", "device", ":", "str", ")", "and", "maps", "to", "target", "device", "cuda", "Basically", "uses", "torch", "implementation", "." ]
def use_cuda(func: Callable): """ Tries to send all parameters of a given function to cuda device if user supports it. Object must have a "to(device: str)" and maps to target device "cuda" Basically, uses torch implementation. Wrapped functions musts have keyword argument "use_cuda: bool" which enables or disables toggling of cuda. """ def _send_args_to_device(caller_kwargs, device): new_kwargs = {} for k, v in caller_kwargs.items(): if getattr(v, "to", False): new_kwargs[k] = v.to(device) else: new_kwargs[k] = v return new_kwargs def wrapper(*args, **kwargs): caller_kwargs = inspect.getcallargs(func, *args, **kwargs) assert ( "use_cuda" in caller_kwargs ), "Function must have 'use_cuda' as a parameter." if caller_kwargs["use_cuda"]: new_kwargs = {} used_cuda = False if torch.cuda.is_available() and caller_kwargs["use_cuda"]: new_kwargs = _send_args_to_device(caller_kwargs, "cuda") used_cuda = True else: new_kwargs = _send_args_to_device(caller_kwargs, "cpu") try: return func(**new_kwargs) except RuntimeError as e: # If a device has cuda installed but no compatible kernels, cuda.is_available() will still return True. # This exception is necessary to catch remaining incompat errors. if used_cuda: G_LOGGER.warning("Unable to execute program using cuda compatible device: {}".format(e)) G_LOGGER.warning("Retrying using CPU only.") new_kwargs = _send_args_to_device(caller_kwargs, "cpu") new_kwargs["use_cuda"] = False cpu_result = func(**new_kwargs) G_LOGGER.warning("Successfully obtained result using CPU.") return cpu_result else: raise e else: return func(**caller_kwargs) return wrapper
[ "def", "use_cuda", "(", "func", ":", "Callable", ")", ":", "def", "_send_args_to_device", "(", "caller_kwargs", ",", "device", ")", ":", "new_kwargs", "=", "{", "}", "for", "k", ",", "v", "in", "caller_kwargs", ".", "items", "(", ")", ":", "if", "getattr", "(", "v", ",", "\"to\"", ",", "False", ")", ":", "new_kwargs", "[", "k", "]", "=", "v", ".", "to", "(", "device", ")", "else", ":", "new_kwargs", "[", "k", "]", "=", "v", "return", "new_kwargs", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "caller_kwargs", "=", "inspect", ".", "getcallargs", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "assert", "(", "\"use_cuda\"", "in", "caller_kwargs", ")", ",", "\"Function must have 'use_cuda' as a parameter.\"", "if", "caller_kwargs", "[", "\"use_cuda\"", "]", ":", "new_kwargs", "=", "{", "}", "used_cuda", "=", "False", "if", "torch", ".", "cuda", ".", "is_available", "(", ")", "and", "caller_kwargs", "[", "\"use_cuda\"", "]", ":", "new_kwargs", "=", "_send_args_to_device", "(", "caller_kwargs", ",", "\"cuda\"", ")", "used_cuda", "=", "True", "else", ":", "new_kwargs", "=", "_send_args_to_device", "(", "caller_kwargs", ",", "\"cpu\"", ")", "try", ":", "return", "func", "(", "*", "*", "new_kwargs", ")", "except", "RuntimeError", "as", "e", ":", "# If a device has cuda installed but no compatible kernels, cuda.is_available() will still return True.", "# This exception is necessary to catch remaining incompat errors.", "if", "used_cuda", ":", "G_LOGGER", ".", "warning", "(", "\"Unable to execute program using cuda compatible device: {}\"", ".", "format", "(", "e", ")", ")", "G_LOGGER", ".", "warning", "(", "\"Retrying using CPU only.\"", ")", "new_kwargs", "=", "_send_args_to_device", "(", "caller_kwargs", ",", "\"cpu\"", ")", "new_kwargs", "[", "\"use_cuda\"", "]", "=", "False", "cpu_result", "=", "func", "(", "*", "*", "new_kwargs", ")", "G_LOGGER", ".", "warning", "(", "\"Successfully obtained result using CPU.\"", ")", "return", "cpu_result", "else", ":", "raise", "e", "else", ":", "return", "func", "(", "*", "*", "caller_kwargs", ")", "return", "wrapper" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/HuggingFace/NNDF/torch_utils.py#L29-L81
lawy623/SVS
b7c7ae367c82a4797ff4a896a2ff304f02e7f724
caffe/scripts/cpp_lint.py
python
CheckCStyleCast
(filename, linenum, line, raw_line, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ match = Search(pattern, line) if not match: return False # Exclude lines with sizeof, since sizeof looks like a cast. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) if sizeof_match: return False # operator++(int) and operator--(int) if (line[0:match.start(1) - 1].endswith(' operator++') or line[0:match.start(1) - 1].endswith(' operator--')): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "linenum", ",", "line", ",", "raw_line", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "# Exclude lines with sizeof, since sizeof looks like a cast.", "sizeof_match", "=", "Match", "(", "r'.*sizeof\\s*$'", ",", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ")", "if", "sizeof_match", ":", "return", "False", "# operator++(int) and operator--(int)", "if", "(", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ".", "endswith", "(", "' operator++'", ")", "or", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ".", "endswith", "(", "' operator--'", ")", ")", ":", "return", "False", "# A single unnamed argument for a function tends to look like old", "# style cast. If we see those, don't issue warnings for deprecated", "# casts, instead issue warnings for unnamed arguments where", "# appropriate.", "#", "# These are things that we want warnings for, since the style guide", "# explicitly require all parameters to be named:", "# Function(int);", "# Function(int) {", "# ConstMember(int) const;", "# ConstMember(int) const {", "# ExceptionMember(int) throw (...);", "# ExceptionMember(int) throw (...) {", "# PureVirtual(int) = 0;", "#", "# These are functions of some sort, where the compiler would be fine", "# if they had named parameters, but people often omit those", "# identifiers to reduce clutter:", "# (FunctionPointer)(int);", "# (FunctionPointer)(int) = value;", "# Function((function_pointer_arg)(int))", "# <TemplateArgument(int)>;", "# <(FunctionPointerTemplateArgument)(int)>;", "remainder", "=", "line", "[", "match", ".", "end", "(", "0", ")", ":", "]", "if", "Match", "(", "r'^\\s*(?:;|const\\b|throw\\b|=|>|\\{|\\))'", ",", "remainder", ")", ":", "# Looks like an unnamed parameter.", "# Don't warn on any kind of template arguments.", "if", "Match", "(", "r'^\\s*>'", ",", "remainder", ")", ":", "return", "False", "# Don't warn on assignments to function pointers, but keep warnings for", "# unnamed parameters to pure virtual functions. Note that this pattern", "# will also pass on assignments of \"0\" to function pointers, but the", "# preferred values for those would be \"nullptr\" or \"NULL\".", "matched_zero", "=", "Match", "(", "r'^\\s=\\s*(\\S+)\\s*;'", ",", "remainder", ")", "if", "matched_zero", "and", "matched_zero", ".", "group", "(", "1", ")", "!=", "'0'", ":", "return", "False", "# Don't warn on function pointer declarations. For this we need", "# to check what came before the \"(type)\" string.", "if", "Match", "(", "r'.*\\)\\s*$'", ",", "line", "[", "0", ":", "match", ".", "start", "(", "0", ")", "]", ")", ":", "return", "False", "# Don't warn if the parameter is named with block comments, e.g.:", "# Function(int /*unused_param*/);", "if", "'/*'", "in", "raw_line", ":", "return", "False", "# Passed all filters, issue warning here.", "error", "(", "filename", ",", "linenum", ",", "'readability/function'", ",", "3", ",", "'All parameters should be named in a function'", ")", "return", "True", "# At this point, all that should be left is actual casts.", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using C-style cast. Use %s<%s>(...) instead'", "%", "(", "cast_type", ",", "match", ".", "group", "(", "1", ")", ")", ")", "return", "True" ]
https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/scripts/cpp_lint.py#L4247-L4338
syoyo/tinygltf
e7f1ff5c59d3ca2489923beb239bdf93d863498f
deps/cpplint.py
python
IsInitializerList
(clean_lines, linenum)
return False
Check if current line is inside constructor initializer list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line appears to be inside constructor initializer list, False otherwise.
Check if current line is inside constructor initializer list.
[ "Check", "if", "current", "line", "is", "inside", "constructor", "initializer", "list", "." ]
def IsInitializerList(clean_lines, linenum): """Check if current line is inside constructor initializer list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line appears to be inside constructor initializer list, False otherwise. """ for i in xrange(linenum, 1, -1): line = clean_lines.elided[i] if i == linenum: remove_function_body = Match(r'^(.*)\{\s*$', line) if remove_function_body: line = remove_function_body.group(1) if Search(r'\s:\s*\w+[({]', line): # A lone colon tend to indicate the start of a constructor # initializer list. It could also be a ternary operator, which # also tend to appear in constructor initializer lists as # opposed to parameter lists. return True if Search(r'\}\s*,\s*$', line): # A closing brace followed by a comma is probably the end of a # brace-initialized member in constructor initializer list. return True if Search(r'[{};]\s*$', line): # Found one of the following: # - A closing brace or semicolon, probably the end of the previous # function. # - An opening brace, probably the start of current class or namespace. # # Current line is probably not inside an initializer list since # we saw one of those things without seeing the starting colon. return False # Got to the beginning of the file without seeing the start of # constructor initializer list. return False
[ "def", "IsInitializerList", "(", "clean_lines", ",", "linenum", ")", ":", "for", "i", "in", "xrange", "(", "linenum", ",", "1", ",", "-", "1", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "i", "==", "linenum", ":", "remove_function_body", "=", "Match", "(", "r'^(.*)\\{\\s*$'", ",", "line", ")", "if", "remove_function_body", ":", "line", "=", "remove_function_body", ".", "group", "(", "1", ")", "if", "Search", "(", "r'\\s:\\s*\\w+[({]'", ",", "line", ")", ":", "# A lone colon tend to indicate the start of a constructor", "# initializer list. It could also be a ternary operator, which", "# also tend to appear in constructor initializer lists as", "# opposed to parameter lists.", "return", "True", "if", "Search", "(", "r'\\}\\s*,\\s*$'", ",", "line", ")", ":", "# A closing brace followed by a comma is probably the end of a", "# brace-initialized member in constructor initializer list.", "return", "True", "if", "Search", "(", "r'[{};]\\s*$'", ",", "line", ")", ":", "# Found one of the following:", "# - A closing brace or semicolon, probably the end of the previous", "# function.", "# - An opening brace, probably the start of current class or namespace.", "#", "# Current line is probably not inside an initializer list since", "# we saw one of those things without seeing the starting colon.", "return", "False", "# Got to the beginning of the file without seeing the start of", "# constructor initializer list.", "return", "False" ]
https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L5038-L5077
stitchEm/stitchEm
0f399501d41ab77933677f2907f41f80ceb704d7
lib/bindings/samples/server/deprecated/nginx.py
python
RTMPServer.gen_output
(self)
return instance.gen_output()
Generate RTMP output
Generate RTMP output
[ "Generate", "RTMP", "output" ]
def gen_output(self): """Generate RTMP output """ return instance.gen_output()
[ "def", "gen_output", "(", "self", ")", ":", "return", "instance", ".", "gen_output", "(", ")" ]
https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/deprecated/nginx.py#L61-L64
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/aio/_base_server.py
python
ServicerContext.peer_identities
(self)
Gets one or more peer identity(s). Equivalent to servicer_context.auth_context().get(servicer_context.peer_identity_key()) Returns: An iterable of the identities, or None if the call is not authenticated. Each identity is returned as a raw bytes type.
Gets one or more peer identity(s).
[ "Gets", "one", "or", "more", "peer", "identity", "(", "s", ")", "." ]
def peer_identities(self) -> Optional[Iterable[bytes]]: """Gets one or more peer identity(s). Equivalent to servicer_context.auth_context().get(servicer_context.peer_identity_key()) Returns: An iterable of the identities, or None if the call is not authenticated. Each identity is returned as a raw bytes type. """
[ "def", "peer_identities", "(", "self", ")", "->", "Optional", "[", "Iterable", "[", "bytes", "]", "]", ":" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_base_server.py#L273-L282
OGRECave/ogre-next
287307980e6de8910f04f3cc0994451b075071fd
Tools/BlenderExport/ogrepkg/gui.py
python
MenuItem.__init__
(self, text, action=Action())
return
Constructor. @param text Item string. @param action Action to execute on selection.
Constructor.
[ "Constructor", "." ]
def __init__(self, text, action=Action()): """Constructor. @param text Item string. @param action Action to execute on selection. """ ValueModel.__init__(self, text) self.action = action return
[ "def", "__init__", "(", "self", ",", "text", ",", "action", "=", "Action", "(", ")", ")", ":", "ValueModel", ".", "__init__", "(", "self", ",", "text", ")", "self", ".", "action", "=", "action", "return" ]
https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/BlenderExport/ogrepkg/gui.py#L917-L925
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/multiprocessing/managers.py
python
BaseManager._number_of_objects
(self)
Return the number of shared objects
Return the number of shared objects
[ "Return", "the", "number", "of", "shared", "objects" ]
def _number_of_objects(self): ''' Return the number of shared objects ''' conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'number_of_objects') finally: conn.close()
[ "def", "_number_of_objects", "(", "self", ")", ":", "conn", "=", "self", ".", "_Client", "(", "self", ".", "_address", ",", "authkey", "=", "self", ".", "_authkey", ")", "try", ":", "return", "dispatch", "(", "conn", ",", "None", ",", "'number_of_objects'", ")", "finally", ":", "conn", ".", "close", "(", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/multiprocessing/managers.py#L555-L563
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
FieldDefn.SetType
(self, *args)
return _ogr.FieldDefn_SetType(self, *args)
r""" SetType(FieldDefn self, OGRFieldType type) void OGR_Fld_SetType(OGRFieldDefnH hDefn, OGRFieldType eType) Set the type of this field. This should never be done to an OGRFieldDefn that is already part of an OGRFeatureDefn. This function is the same as the CPP method OGRFieldDefn::SetType(). Parameters: ----------- hDefn: handle to the field definition to set type to. eType: the new field type.
r""" SetType(FieldDefn self, OGRFieldType type) void OGR_Fld_SetType(OGRFieldDefnH hDefn, OGRFieldType eType)
[ "r", "SetType", "(", "FieldDefn", "self", "OGRFieldType", "type", ")", "void", "OGR_Fld_SetType", "(", "OGRFieldDefnH", "hDefn", "OGRFieldType", "eType", ")" ]
def SetType(self, *args): r""" SetType(FieldDefn self, OGRFieldType type) void OGR_Fld_SetType(OGRFieldDefnH hDefn, OGRFieldType eType) Set the type of this field. This should never be done to an OGRFieldDefn that is already part of an OGRFeatureDefn. This function is the same as the CPP method OGRFieldDefn::SetType(). Parameters: ----------- hDefn: handle to the field definition to set type to. eType: the new field type. """ return _ogr.FieldDefn_SetType(self, *args)
[ "def", "SetType", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "FieldDefn_SetType", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L5083-L5103
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/cluster/hierarchy.py
python
ClusterNode.is_leaf
(self)
return self.left is None
Return True if the target node is a leaf. Returns ------- leafness : bool True if the target node is a leaf node.
Return True if the target node is a leaf.
[ "Return", "True", "if", "the", "target", "node", "is", "a", "leaf", "." ]
def is_leaf(self): """ Return True if the target node is a leaf. Returns ------- leafness : bool True if the target node is a leaf node. """ return self.left is None
[ "def", "is_leaf", "(", "self", ")", ":", "return", "self", ".", "left", "is", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/cluster/hierarchy.py#L1254-L1264
coinapi/coinapi-sdk
854f21e7f69ea8599ae35c5403565cf299d8b795
oeml-sdk/python/openapi_client/model/position_data.py
python
PositionData._from_openapi_data
(cls, *args, **kwargs)
return self
PositionData - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) symbol_id_exchange (str): Exchange symbol.. [optional] # noqa: E501 symbol_id_coinapi (str): CoinAPI symbol.. [optional] # noqa: E501 avg_entry_price (float): Calculated average price of all fills on this position.. [optional] # noqa: E501 quantity (float): The current position quantity.. [optional] # noqa: E501 side (OrdSide): [optional] # noqa: E501 unrealized_pnl (float): Unrealised profit or loss (PNL) of this position.. [optional] # noqa: E501 leverage (float): Leverage for this position reported by the exchange.. [optional] # noqa: E501 cross_margin (bool): Is cross margin mode enable for this position?. [optional] # noqa: E501 liquidation_price (float): Liquidation price. If mark price will reach this value, the position will be liquidated.. [optional] # noqa: E501 raw_data ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501
PositionData - a model defined in OpenAPI
[ "PositionData", "-", "a", "model", "defined", "in", "OpenAPI" ]
def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """PositionData - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) symbol_id_exchange (str): Exchange symbol.. [optional] # noqa: E501 symbol_id_coinapi (str): CoinAPI symbol.. [optional] # noqa: E501 avg_entry_price (float): Calculated average price of all fills on this position.. [optional] # noqa: E501 quantity (float): The current position quantity.. [optional] # noqa: E501 side (OrdSide): [optional] # noqa: E501 unrealized_pnl (float): Unrealised profit or loss (PNL) of this position.. [optional] # noqa: E501 leverage (float): Leverage for this position reported by the exchange.. [optional] # noqa: E501 cross_margin (bool): Is cross margin mode enable for this position?. [optional] # noqa: E501 liquidation_price (float): Liquidation price. If mark price will reach this value, the position will be liquidated.. [optional] # noqa: E501 raw_data ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self
[ "def", "_from_openapi_data", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "_check_type", "=", "kwargs", ".", "pop", "(", "'_check_type'", ",", "True", ")", "_spec_property_naming", "=", "kwargs", ".", "pop", "(", "'_spec_property_naming'", ",", "False", ")", "_path_to_item", "=", "kwargs", ".", "pop", "(", "'_path_to_item'", ",", "(", ")", ")", "_configuration", "=", "kwargs", ".", "pop", "(", "'_configuration'", ",", "None", ")", "_visited_composed_classes", "=", "kwargs", ".", "pop", "(", "'_visited_composed_classes'", ",", "(", ")", ")", "self", "=", "super", "(", "OpenApiModel", ",", "cls", ")", ".", "__new__", "(", "cls", ")", "if", "args", ":", "raise", "ApiTypeError", "(", "\"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.\"", "%", "(", "args", ",", "self", ".", "__class__", ".", "__name__", ",", ")", ",", "path_to_item", "=", "_path_to_item", ",", "valid_classes", "=", "(", "self", ".", "__class__", ",", ")", ",", ")", "self", ".", "_data_store", "=", "{", "}", "self", ".", "_check_type", "=", "_check_type", "self", ".", "_spec_property_naming", "=", "_spec_property_naming", "self", ".", "_path_to_item", "=", "_path_to_item", "self", ".", "_configuration", "=", "_configuration", "self", ".", "_visited_composed_classes", "=", "_visited_composed_classes", "+", "(", "self", ".", "__class__", ",", ")", "for", "var_name", ",", "var_value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "var_name", "not", "in", "self", ".", "attribute_map", "and", "self", ".", "_configuration", "is", "not", "None", "and", "self", ".", "_configuration", ".", "discard_unknown_keys", "and", "self", ".", "additional_properties_type", "is", "None", ":", "# discard variable.", "continue", "setattr", "(", "self", ",", "var_name", ",", "var_value", ")", "return", "self" ]
https://github.com/coinapi/coinapi-sdk/blob/854f21e7f69ea8599ae35c5403565cf299d8b795/oeml-sdk/python/openapi_client/model/position_data.py#L128-L207
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/_dbr/utils.py
python
unwrap_observers_from_placeholders
(module: torch.nn.Module)
Restores observers back to their original state.
Restores observers back to their original state.
[ "Restores", "observers", "back", "to", "their", "original", "state", "." ]
def unwrap_observers_from_placeholders(module: torch.nn.Module) -> None: """ Restores observers back to their original state. """ # Note: we cannot use module.named_children() because we can # have two different names refer to the same module, for example # when we are reusing observers for torch.add scalar version. for name, child in module._modules.items(): if child is None: continue if isinstance(child, ObserverWrapper): unwrapped = child.child setattr(module, name, unwrapped) else: unwrap_observers_from_placeholders(child)
[ "def", "unwrap_observers_from_placeholders", "(", "module", ":", "torch", ".", "nn", ".", "Module", ")", "->", "None", ":", "# Note: we cannot use module.named_children() because we can", "# have two different names refer to the same module, for example", "# when we are reusing observers for torch.add scalar version.", "for", "name", ",", "child", "in", "module", ".", "_modules", ".", "items", "(", ")", ":", "if", "child", "is", "None", ":", "continue", "if", "isinstance", "(", "child", ",", "ObserverWrapper", ")", ":", "unwrapped", "=", "child", ".", "child", "setattr", "(", "module", ",", "name", ",", "unwrapped", ")", "else", ":", "unwrap_observers_from_placeholders", "(", "child", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/_dbr/utils.py#L167-L181
marbl/canu
08b0347f8655ed977a2ac75d35be198601bd7b3d
src/pipelines/dx-canu/resources/bin/dx-get-instance-info.py
python
parse_args
()
return args
Parse the input arguments.
Parse the input arguments.
[ "Parse", "the", "input", "arguments", "." ]
def parse_args(): '''Parse the input arguments.''' ap = argparse.ArgumentParser(description='Get a list of known instance types') ap.add_argument('-m', '--min-memory', help='Minimum memory in GB.', type=int, required=False) ap.add_argument('-c', '--min-cores', help='Minimum number of cores.', type=int, required=False) ap.add_argument('-s', '--min-storage', help='Minimum storage in GB.', type=int, required=False) ap.add_argument('-p', '--project', help='Restrict to instances valid for current project.', action='store_true', required=False) args = ap.parse_args() return args
[ "def", "parse_args", "(", ")", ":", "ap", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Get a list of known instance types'", ")", "ap", ".", "add_argument", "(", "'-m'", ",", "'--min-memory'", ",", "help", "=", "'Minimum memory in GB.'", ",", "type", "=", "int", ",", "required", "=", "False", ")", "ap", ".", "add_argument", "(", "'-c'", ",", "'--min-cores'", ",", "help", "=", "'Minimum number of cores.'", ",", "type", "=", "int", ",", "required", "=", "False", ")", "ap", ".", "add_argument", "(", "'-s'", ",", "'--min-storage'", ",", "help", "=", "'Minimum storage in GB.'", ",", "type", "=", "int", ",", "required", "=", "False", ")", "ap", ".", "add_argument", "(", "'-p'", ",", "'--project'", ",", "help", "=", "'Restrict to instances valid for current project.'", ",", "action", "=", "'store_true'", ",", "required", "=", "False", ")", "args", "=", "ap", ".", "parse_args", "(", ")", "return", "args" ]
https://github.com/marbl/canu/blob/08b0347f8655ed977a2ac75d35be198601bd7b3d/src/pipelines/dx-canu/resources/bin/dx-get-instance-info.py#L10-L36
xiaolonw/caffe-video_triplet
c39ea1ad6e937ccf7deba4510b7e555165abf05f
scripts/cpp_lint.py
python
CheckCaffeRandom
(filename, clean_lines, linenum, error)
Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for calls to C random functions (rand, rand_r, random, ...).
[ "Checks", "for", "calls", "to", "C", "random", "functions", "(", "rand", "rand_r", "random", "...", ")", "." ]
def CheckCaffeRandom(filename, clean_lines, linenum, error): """Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for function in c_random_function_list: ix = line.find(function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'caffe/random_fn', 2, 'Use caffe_rng_rand() (or other caffe_rng_* function) instead of ' + function + ') to ensure results are deterministic for a fixed Caffe seed.')
[ "def", "CheckCaffeRandom", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "function", "in", "c_random_function_list", ":", "ix", "=", "line", ".", "find", "(", "function", ")", "# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison", "if", "ix", ">=", "0", "and", "(", "ix", "==", "0", "or", "(", "not", "line", "[", "ix", "-", "1", "]", ".", "isalnum", "(", ")", "and", "line", "[", "ix", "-", "1", "]", "not", "in", "(", "'_'", ",", "'.'", ",", "'>'", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'caffe/random_fn'", ",", "2", ",", "'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '", "+", "function", "+", "') to ensure results are deterministic for a fixed Caffe seed.'", ")" ]
https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/scripts/cpp_lint.py#L1640-L1663
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py
python
Distribution.exclude
(self, **attrs)
Remove items from distribution that are named in keyword arguments For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from the distribution's 'py_modules' attribute. Excluding packages uses the 'exclude_package()' method, so all of the package's contained packages, modules, and extensions are also excluded. Currently, this method only supports exclusion from attributes that are lists or tuples. If you need to add support for excluding from other attributes in this or a subclass, you can add an '_exclude_X' method, where 'X' is the name of the attribute. The method will be called with the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})' will try to call 'dist._exclude_foo({"bar":"baz"})', which can then handle whatever special exclusion logic is needed.
Remove items from distribution that are named in keyword arguments
[ "Remove", "items", "from", "distribution", "that", "are", "named", "in", "keyword", "arguments" ]
def exclude(self, **attrs): """Remove items from distribution that are named in keyword arguments For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from the distribution's 'py_modules' attribute. Excluding packages uses the 'exclude_package()' method, so all of the package's contained packages, modules, and extensions are also excluded. Currently, this method only supports exclusion from attributes that are lists or tuples. If you need to add support for excluding from other attributes in this or a subclass, you can add an '_exclude_X' method, where 'X' is the name of the attribute. The method will be called with the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})' will try to call 'dist._exclude_foo({"bar":"baz"})', which can then handle whatever special exclusion logic is needed. """ for k, v in attrs.items(): exclude = getattr(self, '_exclude_' + k, None) if exclude: exclude(v) else: self._exclude_misc(k, v)
[ "def", "exclude", "(", "self", ",", "*", "*", "attrs", ")", ":", "for", "k", ",", "v", "in", "attrs", ".", "items", "(", ")", ":", "exclude", "=", "getattr", "(", "self", ",", "'_exclude_'", "+", "k", ",", "None", ")", "if", "exclude", ":", "exclude", "(", "v", ")", "else", ":", "self", ".", "_exclude_misc", "(", "k", ",", "v", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py#L880-L901
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/stone-game-v.py
python
Solution.stoneGameV
(self, stoneValue)
return max_score
:type stoneValue: List[int] :rtype: int
:type stoneValue: List[int] :rtype: int
[ ":", "type", "stoneValue", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def stoneGameV(self, stoneValue): """ :type stoneValue: List[int] :rtype: int """ n = len(stoneValue) prefix = [0] for v in stoneValue: prefix.append(prefix[-1] + v) mid = range(n) dp = [[0]*n for _ in xrange(n)] for i in xrange(n): dp[i][i] = stoneValue[i] max_score = 0 for l in xrange(2, n+1): for i in xrange(n-l+1): j = i+l-1 while prefix[mid[i]]-prefix[i] < prefix[j+1]-prefix[mid[i]]: mid[i] += 1 # Time: O(n^2) in total p = mid[i] max_score = 0 if prefix[p]-prefix[i] == prefix[j+1]-prefix[p]: max_score = max(dp[i][p-1], dp[j][p]) else: if i <= p-2: max_score = max(max_score, dp[i][p-2]) if p <= j: max_score = max(max_score, dp[j][p]) dp[i][j] = max(dp[i][j-1], (prefix[j+1]-prefix[i]) + max_score) dp[j][i] = max(dp[j][i+1], (prefix[j+1]-prefix[i]) + max_score) return max_score
[ "def", "stoneGameV", "(", "self", ",", "stoneValue", ")", ":", "n", "=", "len", "(", "stoneValue", ")", "prefix", "=", "[", "0", "]", "for", "v", "in", "stoneValue", ":", "prefix", ".", "append", "(", "prefix", "[", "-", "1", "]", "+", "v", ")", "mid", "=", "range", "(", "n", ")", "dp", "=", "[", "[", "0", "]", "*", "n", "for", "_", "in", "xrange", "(", "n", ")", "]", "for", "i", "in", "xrange", "(", "n", ")", ":", "dp", "[", "i", "]", "[", "i", "]", "=", "stoneValue", "[", "i", "]", "max_score", "=", "0", "for", "l", "in", "xrange", "(", "2", ",", "n", "+", "1", ")", ":", "for", "i", "in", "xrange", "(", "n", "-", "l", "+", "1", ")", ":", "j", "=", "i", "+", "l", "-", "1", "while", "prefix", "[", "mid", "[", "i", "]", "]", "-", "prefix", "[", "i", "]", "<", "prefix", "[", "j", "+", "1", "]", "-", "prefix", "[", "mid", "[", "i", "]", "]", ":", "mid", "[", "i", "]", "+=", "1", "# Time: O(n^2) in total", "p", "=", "mid", "[", "i", "]", "max_score", "=", "0", "if", "prefix", "[", "p", "]", "-", "prefix", "[", "i", "]", "==", "prefix", "[", "j", "+", "1", "]", "-", "prefix", "[", "p", "]", ":", "max_score", "=", "max", "(", "dp", "[", "i", "]", "[", "p", "-", "1", "]", ",", "dp", "[", "j", "]", "[", "p", "]", ")", "else", ":", "if", "i", "<=", "p", "-", "2", ":", "max_score", "=", "max", "(", "max_score", ",", "dp", "[", "i", "]", "[", "p", "-", "2", "]", ")", "if", "p", "<=", "j", ":", "max_score", "=", "max", "(", "max_score", ",", "dp", "[", "j", "]", "[", "p", "]", ")", "dp", "[", "i", "]", "[", "j", "]", "=", "max", "(", "dp", "[", "i", "]", "[", "j", "-", "1", "]", ",", "(", "prefix", "[", "j", "+", "1", "]", "-", "prefix", "[", "i", "]", ")", "+", "max_score", ")", "dp", "[", "j", "]", "[", "i", "]", "=", "max", "(", "dp", "[", "j", "]", "[", "i", "+", "1", "]", ",", "(", "prefix", "[", "j", "+", "1", "]", "-", "prefix", "[", "i", "]", ")", "+", "max_score", ")", "return", "max_score" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/stone-game-v.py#L5-L38
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/jinja2/ext.py
python
Extension.attr
(self, name, lineno=None)
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno)
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code.
[ "Return", "an", "attribute", "node", "for", "the", "current", "extension", ".", "This", "is", "useful", "to", "pass", "constants", "on", "extensions", "to", "generated", "template", "code", "." ]
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
[ "def", "attr", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "nodes", ".", "ExtensionAttribute", "(", "self", ".", "identifier", ",", "name", ",", "lineno", "=", "lineno", ")" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/ext.py#L104-L112
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/text_format.py
python
_Tokenizer.ConsumeBool
(self)
return result
Consumes a boolean value. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed.
Consumes a boolean value.
[ "Consumes", "a", "boolean", "value", "." ]
def ConsumeBool(self): """Consumes a boolean value. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed. """ try: result = ParseBool(self.token) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result
[ "def", "ConsumeBool", "(", "self", ")", ":", "try", ":", "result", "=", "ParseBool", "(", "self", ".", "token", ")", "except", "ValueError", ",", "e", ":", "raise", "self", ".", "_ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken", "(", ")", "return", "result" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/text_format.py#L475-L489
zerollzeng/tiny-tensorrt
e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2
third_party/pybind11/tools/clang/cindex.py
python
SourceLocation.column
(self)
return self._get_instantiation()[2]
Get the column represented by this source location.
Get the column represented by this source location.
[ "Get", "the", "column", "represented", "by", "this", "source", "location", "." ]
def column(self): """Get the column represented by this source location.""" return self._get_instantiation()[2]
[ "def", "column", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "2", "]" ]
https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L208-L210
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/ert/ertModelling.py
python
ERTModellingReference.createRHS
(self, mesh, elecs)
return rhs
Create right-hand-side vector.
Create right-hand-side vector.
[ "Create", "right", "-", "hand", "-", "side", "vector", "." ]
def createRHS(self, mesh, elecs): """Create right-hand-side vector.""" rhs = np.zeros((len(elecs), mesh.nodeCount())) for i, e in enumerate(elecs): c = mesh.findCell(e) rhs[i][c.ids()] = c.N(c.shape().rst(e)) return rhs
[ "def", "createRHS", "(", "self", ",", "mesh", ",", "elecs", ")", ":", "rhs", "=", "np", ".", "zeros", "(", "(", "len", "(", "elecs", ")", ",", "mesh", ".", "nodeCount", "(", ")", ")", ")", "for", "i", ",", "e", "in", "enumerate", "(", "elecs", ")", ":", "c", "=", "mesh", ".", "findCell", "(", "e", ")", "rhs", "[", "i", "]", "[", "c", ".", "ids", "(", ")", "]", "=", "c", ".", "N", "(", "c", ".", "shape", "(", ")", ".", "rst", "(", "e", ")", ")", "return", "rhs" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ertModelling.py#L442-L448
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
DocChildFrame.SetView
(self, view)
Sets the view for this frame.
Sets the view for this frame.
[ "Sets", "the", "view", "for", "this", "frame", "." ]
def SetView(self, view): """ Sets the view for this frame. """ self._childView = view
[ "def", "SetView", "(", "self", ",", "view", ")", ":", "self", ".", "_childView", "=", "view" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L2603-L2607
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/pep425tags.py
python
get_impl_version_info
()
Return sys.version_info-like tuple for use in decrementing the minor version.
Return sys.version_info-like tuple for use in decrementing the minor version.
[ "Return", "sys", ".", "version_info", "-", "like", "tuple", "for", "use", "in", "decrementing", "the", "minor", "version", "." ]
def get_impl_version_info(): """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 return (sys.version_info[0], sys.pypy_version_info.major, sys.pypy_version_info.minor) else: return sys.version_info[0], sys.version_info[1]
[ "def", "get_impl_version_info", "(", ")", ":", "if", "get_abbr_impl", "(", ")", "==", "'pp'", ":", "# as per https://github.com/pypa/pip/issues/2882", "return", "(", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "pypy_version_info", ".", "major", ",", "sys", ".", "pypy_version_info", ".", "minor", ")", "else", ":", "return", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/pep425tags.py#L51-L59
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/datetimes.py
python
DatetimeArray.normalize
(self)
return type(self)(new_values)._with_freq("infer").tz_localize(self.tz)
Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the ``.dt`` accessor, and directly on Datetime Array/Index. Returns ------- DatetimeArray, DatetimeIndex or Series The same type as the original data. Series will have the same name and index. DatetimeIndex will have the same name. See Also -------- floor : Floor the datetimes to the specified freq. ceil : Ceil the datetimes to the specified freq. round : Round the datetimes to the specified freq. Examples -------- >>> idx = pd.date_range(start='2014-08-01 10:00', freq='H', ... periods=3, tz='Asia/Calcutta') >>> idx DatetimeIndex(['2014-08-01 10:00:00+05:30', '2014-08-01 11:00:00+05:30', '2014-08-01 12:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq='H') >>> idx.normalize() DatetimeIndex(['2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq=None)
Convert times to midnight.
[ "Convert", "times", "to", "midnight", "." ]
def normalize(self) -> DatetimeArray: """ Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the ``.dt`` accessor, and directly on Datetime Array/Index. Returns ------- DatetimeArray, DatetimeIndex or Series The same type as the original data. Series will have the same name and index. DatetimeIndex will have the same name. See Also -------- floor : Floor the datetimes to the specified freq. ceil : Ceil the datetimes to the specified freq. round : Round the datetimes to the specified freq. Examples -------- >>> idx = pd.date_range(start='2014-08-01 10:00', freq='H', ... periods=3, tz='Asia/Calcutta') >>> idx DatetimeIndex(['2014-08-01 10:00:00+05:30', '2014-08-01 11:00:00+05:30', '2014-08-01 12:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq='H') >>> idx.normalize() DatetimeIndex(['2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq=None) """ new_values = normalize_i8_timestamps(self.asi8, self.tz) return type(self)(new_values)._with_freq("infer").tz_localize(self.tz)
[ "def", "normalize", "(", "self", ")", "->", "DatetimeArray", ":", "new_values", "=", "normalize_i8_timestamps", "(", "self", ".", "asi8", ",", "self", ".", "tz", ")", "return", "type", "(", "self", ")", "(", "new_values", ")", ".", "_with_freq", "(", "\"infer\"", ")", ".", "tz_localize", "(", "self", ".", "tz", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/datetimes.py#L1054-L1093
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/msvs_emulation.py
python
_AddPrefix
(element, prefix)
Add |prefix| to |element| or each subelement if element is iterable.
Add |prefix| to |element| or each subelement if element is iterable.
[ "Add", "|prefix|", "to", "|element|", "or", "each", "subelement", "if", "element", "is", "iterable", "." ]
def _AddPrefix(element, prefix): """Add |prefix| to |element| or each subelement if element is iterable.""" if element is None: return element # Note, not Iterable because we don't want to handle strings like that. if isinstance(element, list) or isinstance(element, tuple): return [prefix + e for e in element] else: return prefix + element
[ "def", "_AddPrefix", "(", "element", ",", "prefix", ")", ":", "if", "element", "is", "None", ":", "return", "element", "# Note, not Iterable because we don't want to handle strings like that.", "if", "isinstance", "(", "element", ",", "list", ")", "or", "isinstance", "(", "element", ",", "tuple", ")", ":", "return", "[", "prefix", "+", "e", "for", "e", "in", "element", "]", "else", ":", "return", "prefix", "+", "element" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L79-L87
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
AuiDockingGuideInfo.__init__
(self, other=None)
Default class constructor. Used internally, do not call it in your code! :param `other`: another instance of :class:`AuiDockingGuideInfo`.
Default class constructor. Used internally, do not call it in your code!
[ "Default", "class", "constructor", ".", "Used", "internally", "do", "not", "call", "it", "in", "your", "code!" ]
def __init__(self, other=None): """ Default class constructor. Used internally, do not call it in your code! :param `other`: another instance of :class:`AuiDockingGuideInfo`. """ if other: self.Assign(other) else: # window representing the docking target self.host = None # dock direction (top, bottom, left, right, center) self.dock_direction = AUI_DOCK_NONE
[ "def", "__init__", "(", "self", ",", "other", "=", "None", ")", ":", "if", "other", ":", "self", ".", "Assign", "(", "other", ")", "else", ":", "# window representing the docking target", "self", ".", "host", "=", "None", "# dock direction (top, bottom, left, right, center)", "self", ".", "dock_direction", "=", "AUI_DOCK_NONE" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L222-L236
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiPaneInfo.CenterPane
(*args, **kwargs)
return _aui.AuiPaneInfo_CenterPane(*args, **kwargs)
CenterPane(self) -> AuiPaneInfo
CenterPane(self) -> AuiPaneInfo
[ "CenterPane", "(", "self", ")", "-", ">", "AuiPaneInfo" ]
def CenterPane(*args, **kwargs): """CenterPane(self) -> AuiPaneInfo""" return _aui.AuiPaneInfo_CenterPane(*args, **kwargs)
[ "def", "CenterPane", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_CenterPane", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L517-L519
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/util.py
python
Substituter.__init__
(self)
Create an empty substituter.
Create an empty substituter.
[ "Create", "an", "empty", "substituter", "." ]
def __init__(self): '''Create an empty substituter.''' self.substitutions_ = {} self.dirty_ = True
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "substitutions_", "=", "{", "}", "self", ".", "dirty_", "=", "True" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/util.py#L543-L546
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/categorical.py
python
Categorical.min
(self, skipna=True)
return self.categories[pointer]
The minimum value of the object. Only ordered `Categoricals` have a minimum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError If the `Categorical` is not `ordered`. Returns ------- min : the minimum of this `Categorical`
The minimum value of the object.
[ "The", "minimum", "value", "of", "the", "object", "." ]
def min(self, skipna=True): """ The minimum value of the object. Only ordered `Categoricals` have a minimum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError If the `Categorical` is not `ordered`. Returns ------- min : the minimum of this `Categorical` """ self.check_for_ordered("min") if not len(self._codes): return self.dtype.na_value good = self._codes != -1 if not good.all(): if skipna: pointer = self._codes[good].min() else: return np.nan else: pointer = self._codes.min() return self.categories[pointer]
[ "def", "min", "(", "self", ",", "skipna", "=", "True", ")", ":", "self", ".", "check_for_ordered", "(", "\"min\"", ")", "if", "not", "len", "(", "self", ".", "_codes", ")", ":", "return", "self", ".", "dtype", ".", "na_value", "good", "=", "self", ".", "_codes", "!=", "-", "1", "if", "not", "good", ".", "all", "(", ")", ":", "if", "skipna", ":", "pointer", "=", "self", ".", "_codes", "[", "good", "]", ".", "min", "(", ")", "else", ":", "return", "np", ".", "nan", "else", ":", "pointer", "=", "self", ".", "_codes", ".", "min", "(", ")", "return", "self", ".", "categories", "[", "pointer", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/categorical.py#L2128-L2160
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
tools/extra/summarize.py
python
print_table
(table, max_width)
Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.
Print a simple nicely-aligned table.
[ "Print", "a", "simple", "nicely", "-", "aligned", "table", "." ]
def print_table(table, max_width): """Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.""" max_widths = [max_width] * len(table[0]) column_widths = [max(printed_len(row[j]) + 1 for row in table) for j in range(len(table[0]))] column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)] for row in table: row_str = '' right_col = 0 for cell, width in zip(row, column_widths): right_col += width row_str += cell + ' ' row_str += ' ' * max(right_col - printed_len(row_str), 0) print row_str
[ "def", "print_table", "(", "table", ",", "max_width", ")", ":", "max_widths", "=", "[", "max_width", "]", "*", "len", "(", "table", "[", "0", "]", ")", "column_widths", "=", "[", "max", "(", "printed_len", "(", "row", "[", "j", "]", ")", "+", "1", "for", "row", "in", "table", ")", "for", "j", "in", "range", "(", "len", "(", "table", "[", "0", "]", ")", ")", "]", "column_widths", "=", "[", "min", "(", "w", ",", "max_w", ")", "for", "w", ",", "max_w", "in", "zip", "(", "column_widths", ",", "max_widths", ")", "]", "for", "row", "in", "table", ":", "row_str", "=", "''", "right_col", "=", "0", "for", "cell", ",", "width", "in", "zip", "(", "row", ",", "column_widths", ")", ":", "right_col", "+=", "width", "row_str", "+=", "cell", "+", "' '", "row_str", "+=", "' '", "*", "max", "(", "right_col", "-", "printed_len", "(", "row_str", ")", ",", "0", ")", "print", "row_str" ]
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/tools/extra/summarize.py#L41-L61
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/struct_types.py
python
MethodInfo.get_declaration
(self)
return common.template_args( "${pre_modifiers}${return_type}${method_name}(${args})${post_modifiers};", pre_modifiers=pre_modifiers, return_type=return_type_str, method_name=self.method_name, args=', '.join([str(arg) for arg in self.args]), post_modifiers=post_modifiers)
Get a declaration for a method.
Get a declaration for a method.
[ "Get", "a", "declaration", "for", "a", "method", "." ]
def get_declaration(self): # type: () -> unicode """Get a declaration for a method.""" pre_modifiers = '' post_modifiers = '' return_type_str = '' if self.static: pre_modifiers = 'static ' if self.const: post_modifiers = ' const' if self.explicit: pre_modifiers += 'explicit ' if self.return_type: return_type_str = self.return_type + ' ' return common.template_args( "${pre_modifiers}${return_type}${method_name}(${args})${post_modifiers};", pre_modifiers=pre_modifiers, return_type=return_type_str, method_name=self.method_name, args=', '.join([str(arg) for arg in self.args]), post_modifiers=post_modifiers)
[ "def", "get_declaration", "(", "self", ")", ":", "# type: () -> unicode", "pre_modifiers", "=", "''", "post_modifiers", "=", "''", "return_type_str", "=", "''", "if", "self", ".", "static", ":", "pre_modifiers", "=", "'static '", "if", "self", ".", "const", ":", "post_modifiers", "=", "' const'", "if", "self", ".", "explicit", ":", "pre_modifiers", "+=", "'explicit '", "if", "self", ".", "return_type", ":", "return_type_str", "=", "self", ".", "return_type", "+", "' '", "return", "common", ".", "template_args", "(", "\"${pre_modifiers}${return_type}${method_name}(${args})${post_modifiers};\"", ",", "pre_modifiers", "=", "pre_modifiers", ",", "return_type", "=", "return_type_str", ",", "method_name", "=", "self", ".", "method_name", ",", "args", "=", "', '", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "self", ".", "args", "]", ")", ",", "post_modifiers", "=", "post_modifiers", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/struct_types.py#L65-L90
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
SplitterWindow.GetSashPosition
(*args, **kwargs)
return _windows_.SplitterWindow_GetSashPosition(*args, **kwargs)
GetSashPosition(self) -> int Returns the surrent sash position.
GetSashPosition(self) -> int
[ "GetSashPosition", "(", "self", ")", "-", ">", "int" ]
def GetSashPosition(*args, **kwargs): """ GetSashPosition(self) -> int Returns the surrent sash position. """ return _windows_.SplitterWindow_GetSashPosition(*args, **kwargs)
[ "def", "GetSashPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "SplitterWindow_GetSashPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1566-L1572
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
GraphicsContext.GetDPI
(*args, **kwargs)
return _gdi_.GraphicsContext_GetDPI(*args, **kwargs)
GetDPI(self) --> (dpiX, dpiY) Returns the resolution of the graphics context in device points per inch
GetDPI(self) --> (dpiX, dpiY)
[ "GetDPI", "(", "self", ")", "--", ">", "(", "dpiX", "dpiY", ")" ]
def GetDPI(*args, **kwargs): """ GetDPI(self) --> (dpiX, dpiY) Returns the resolution of the graphics context in device points per inch """ return _gdi_.GraphicsContext_GetDPI(*args, **kwargs)
[ "def", "GetDPI", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "GraphicsContext_GetDPI", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L6257-L6263
3drobotics/ardupilot-solo
05a123b002c11dccc905d4d7703a38e5f36ee723
Tools/scripts/update_wiki.py
python
list_posts
()
list posts
list posts
[ "list", "posts" ]
def list_posts(): '''list posts''' posts = server.wp.getPosts(opts.blog_id, opts.username, opts.password, { 'post_type' : 'wiki', 'number' : 1000000 }, [ 'post_title', 'post_id' ]) for p in posts: try: print('post_id=%s post_title="%s"' % (p['post_id'], p['post_title'])) except Exception: pass
[ "def", "list_posts", "(", ")", ":", "posts", "=", "server", ".", "wp", ".", "getPosts", "(", "opts", ".", "blog_id", ",", "opts", ".", "username", ",", "opts", ".", "password", ",", "{", "'post_type'", ":", "'wiki'", ",", "'number'", ":", "1000000", "}", ",", "[", "'post_title'", ",", "'post_id'", "]", ")", "for", "p", "in", "posts", ":", "try", ":", "print", "(", "'post_id=%s post_title=\"%s\"'", "%", "(", "p", "[", "'post_id'", "]", ",", "p", "[", "'post_title'", "]", ")", ")", "except", "Exception", ":", "pass" ]
https://github.com/3drobotics/ardupilot-solo/blob/05a123b002c11dccc905d4d7703a38e5f36ee723/Tools/scripts/update_wiki.py#L38-L47
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/graph_actions.py
python
infer
(restore_checkpoint_path, output_dict, feed_dict=None)
return run_feeds(output_dict=output_dict, feed_dicts=[feed_dict] if feed_dict is not None else [None], restore_checkpoint_path=restore_checkpoint_path)[0]
Restore graph from `restore_checkpoint_path` and run `output_dict` tensors. If `restore_checkpoint_path` is supplied, restore from checkpoint. Otherwise, init all variables. Args: restore_checkpoint_path: A string containing the path to a checkpoint to restore. output_dict: A `dict` mapping string names to `Tensor` objects to run. Tensors must all be from the same graph. feed_dict: `dict` object mapping `Tensor` objects to input values to feed. Returns: Dict of values read from `output_dict` tensors. Keys are the same as `output_dict`, values are the results read from the corresponding `Tensor` in `output_dict`. Raises: ValueError: if `output_dict` or `feed_dicts` is None or empty.
Restore graph from `restore_checkpoint_path` and run `output_dict` tensors.
[ "Restore", "graph", "from", "restore_checkpoint_path", "and", "run", "output_dict", "tensors", "." ]
def infer(restore_checkpoint_path, output_dict, feed_dict=None): """Restore graph from `restore_checkpoint_path` and run `output_dict` tensors. If `restore_checkpoint_path` is supplied, restore from checkpoint. Otherwise, init all variables. Args: restore_checkpoint_path: A string containing the path to a checkpoint to restore. output_dict: A `dict` mapping string names to `Tensor` objects to run. Tensors must all be from the same graph. feed_dict: `dict` object mapping `Tensor` objects to input values to feed. Returns: Dict of values read from `output_dict` tensors. Keys are the same as `output_dict`, values are the results read from the corresponding `Tensor` in `output_dict`. Raises: ValueError: if `output_dict` or `feed_dicts` is None or empty. """ return run_feeds(output_dict=output_dict, feed_dicts=[feed_dict] if feed_dict is not None else [None], restore_checkpoint_path=restore_checkpoint_path)[0]
[ "def", "infer", "(", "restore_checkpoint_path", ",", "output_dict", ",", "feed_dict", "=", "None", ")", ":", "return", "run_feeds", "(", "output_dict", "=", "output_dict", ",", "feed_dicts", "=", "[", "feed_dict", "]", "if", "feed_dict", "is", "not", "None", "else", "[", "None", "]", ",", "restore_checkpoint_path", "=", "restore_checkpoint_path", ")", "[", "0", "]" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/graph_actions.py#L706-L729
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/common.py
python
infer_compression
( filepath_or_buffer: FilePathOrBuffer, compression: Optional[str] )
Get the compression method for filepath_or_buffer. If compression='infer', the inferred compression method is returned. Otherwise, the input compression method is returned unchanged, unless it's invalid, in which case an error is raised. Parameters ---------- filepath_or_buffer : str or file handle File path or object. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None} If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). Returns ------- string or None Raises ------ ValueError on invalid compression specified.
Get the compression method for filepath_or_buffer. If compression='infer', the inferred compression method is returned. Otherwise, the input compression method is returned unchanged, unless it's invalid, in which case an error is raised.
[ "Get", "the", "compression", "method", "for", "filepath_or_buffer", ".", "If", "compression", "=", "infer", "the", "inferred", "compression", "method", "is", "returned", ".", "Otherwise", "the", "input", "compression", "method", "is", "returned", "unchanged", "unless", "it", "s", "invalid", "in", "which", "case", "an", "error", "is", "raised", "." ]
def infer_compression( filepath_or_buffer: FilePathOrBuffer, compression: Optional[str] ) -> Optional[str]: """ Get the compression method for filepath_or_buffer. If compression='infer', the inferred compression method is returned. Otherwise, the input compression method is returned unchanged, unless it's invalid, in which case an error is raised. Parameters ---------- filepath_or_buffer : str or file handle File path or object. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None} If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). Returns ------- string or None Raises ------ ValueError on invalid compression specified. """ # No compression has been explicitly specified if compression is None: return None # Infer compression if compression == "infer": # Convert all path types (e.g. pathlib.Path) to strings filepath_or_buffer = stringify_path(filepath_or_buffer) if not isinstance(filepath_or_buffer, str): # Cannot infer compression of a buffer, assume no compression return None # Infer compression from the filename/URL extension for compression, extension in _compression_to_extension.items(): if filepath_or_buffer.endswith(extension): return compression return None # Compression has been specified. Check that it's valid if compression in _compression_to_extension: return compression msg = f"Unrecognized compression type: {compression}" valid = ["infer", None] + sorted(_compression_to_extension) msg += f"\nValid compression types are {valid}" raise ValueError(msg)
[ "def", "infer_compression", "(", "filepath_or_buffer", ":", "FilePathOrBuffer", ",", "compression", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "str", "]", ":", "# No compression has been explicitly specified", "if", "compression", "is", "None", ":", "return", "None", "# Infer compression", "if", "compression", "==", "\"infer\"", ":", "# Convert all path types (e.g. pathlib.Path) to strings", "filepath_or_buffer", "=", "stringify_path", "(", "filepath_or_buffer", ")", "if", "not", "isinstance", "(", "filepath_or_buffer", ",", "str", ")", ":", "# Cannot infer compression of a buffer, assume no compression", "return", "None", "# Infer compression from the filename/URL extension", "for", "compression", ",", "extension", "in", "_compression_to_extension", ".", "items", "(", ")", ":", "if", "filepath_or_buffer", ".", "endswith", "(", "extension", ")", ":", "return", "compression", "return", "None", "# Compression has been specified. Check that it's valid", "if", "compression", "in", "_compression_to_extension", ":", "return", "compression", "msg", "=", "f\"Unrecognized compression type: {compression}\"", "valid", "=", "[", "\"infer\"", ",", "None", "]", "+", "sorted", "(", "_compression_to_extension", ")", "msg", "+=", "f\"\\nValid compression types are {valid}\"", "raise", "ValueError", "(", "msg", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/common.py#L259-L311
Caffe-MPI/Caffe-MPI.github.io
df5992af571a2a19981b69635115c393f18d1c76
python/caffe/draw.py
python
get_pydot_graph
(caffe_net, rankdir, label_edges=True)
return pydot_graph
Create a data structure which represents the `caffe_net`. Parameters ---------- caffe_net : object rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. label_edges : boolean, optional Label the edges (default is True). Returns ------- pydot graph object
Create a data structure which represents the `caffe_net`.
[ "Create", "a", "data", "structure", "which", "represents", "the", "caffe_net", "." ]
def get_pydot_graph(caffe_net, rankdir, label_edges=True): """Create a data structure which represents the `caffe_net`. Parameters ---------- caffe_net : object rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. label_edges : boolean, optional Label the edges (default is True). Returns ------- pydot graph object """ pydot_graph = pydot.Dot(caffe_net.name if caffe_net.name else 'Net', graph_type='digraph', rankdir=rankdir) pydot_nodes = {} pydot_edges = [] for layer in caffe_net.layer: node_label = get_layer_label(layer, rankdir) node_name = "%s_%s" % (layer.name, layer.type) if (len(layer.bottom) == 1 and len(layer.top) == 1 and layer.bottom[0] == layer.top[0]): # We have an in-place neuron layer. pydot_nodes[node_name] = pydot.Node(node_label, **NEURON_LAYER_STYLE) else: layer_style = LAYER_STYLE_DEFAULT layer_style['fillcolor'] = choose_color_by_layertype(layer.type) pydot_nodes[node_name] = pydot.Node(node_label, **layer_style) for bottom_blob in layer.bottom: pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob, **BLOB_STYLE) edge_label = '""' pydot_edges.append({'src': bottom_blob + '_blob', 'dst': node_name, 'label': edge_label}) for top_blob in layer.top: pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob)) if label_edges: edge_label = get_edge_label(layer) else: edge_label = '""' pydot_edges.append({'src': node_name, 'dst': top_blob + '_blob', 'label': edge_label}) # Now, add the nodes and edges to the graph. for node in pydot_nodes.values(): pydot_graph.add_node(node) for edge in pydot_edges: pydot_graph.add_edge( pydot.Edge(pydot_nodes[edge['src']], pydot_nodes[edge['dst']], label=edge['label'])) return pydot_graph
[ "def", "get_pydot_graph", "(", "caffe_net", ",", "rankdir", ",", "label_edges", "=", "True", ")", ":", "pydot_graph", "=", "pydot", ".", "Dot", "(", "caffe_net", ".", "name", "if", "caffe_net", ".", "name", "else", "'Net'", ",", "graph_type", "=", "'digraph'", ",", "rankdir", "=", "rankdir", ")", "pydot_nodes", "=", "{", "}", "pydot_edges", "=", "[", "]", "for", "layer", "in", "caffe_net", ".", "layer", ":", "node_label", "=", "get_layer_label", "(", "layer", ",", "rankdir", ")", "node_name", "=", "\"%s_%s\"", "%", "(", "layer", ".", "name", ",", "layer", ".", "type", ")", "if", "(", "len", "(", "layer", ".", "bottom", ")", "==", "1", "and", "len", "(", "layer", ".", "top", ")", "==", "1", "and", "layer", ".", "bottom", "[", "0", "]", "==", "layer", ".", "top", "[", "0", "]", ")", ":", "# We have an in-place neuron layer.", "pydot_nodes", "[", "node_name", "]", "=", "pydot", ".", "Node", "(", "node_label", ",", "*", "*", "NEURON_LAYER_STYLE", ")", "else", ":", "layer_style", "=", "LAYER_STYLE_DEFAULT", "layer_style", "[", "'fillcolor'", "]", "=", "choose_color_by_layertype", "(", "layer", ".", "type", ")", "pydot_nodes", "[", "node_name", "]", "=", "pydot", ".", "Node", "(", "node_label", ",", "*", "*", "layer_style", ")", "for", "bottom_blob", "in", "layer", ".", "bottom", ":", "pydot_nodes", "[", "bottom_blob", "+", "'_blob'", "]", "=", "pydot", ".", "Node", "(", "'%s'", "%", "bottom_blob", ",", "*", "*", "BLOB_STYLE", ")", "edge_label", "=", "'\"\"'", "pydot_edges", ".", "append", "(", "{", "'src'", ":", "bottom_blob", "+", "'_blob'", ",", "'dst'", ":", "node_name", ",", "'label'", ":", "edge_label", "}", ")", "for", "top_blob", "in", "layer", ".", "top", ":", "pydot_nodes", "[", "top_blob", "+", "'_blob'", "]", "=", "pydot", ".", "Node", "(", "'%s'", "%", "(", "top_blob", ")", ")", "if", "label_edges", ":", "edge_label", "=", "get_edge_label", "(", "layer", ")", "else", ":", "edge_label", "=", "'\"\"'", "pydot_edges", ".", "append", "(", "{", "'src'", ":", "node_name", ",", "'dst'", ":", "top_blob", "+", "'_blob'", ",", "'label'", ":", "edge_label", "}", ")", "# Now, add the nodes and edges to the graph.", "for", "node", "in", "pydot_nodes", ".", "values", "(", ")", ":", "pydot_graph", ".", "add_node", "(", "node", ")", "for", "edge", "in", "pydot_edges", ":", "pydot_graph", ".", "add_edge", "(", "pydot", ".", "Edge", "(", "pydot_nodes", "[", "edge", "[", "'src'", "]", "]", ",", "pydot_nodes", "[", "edge", "[", "'dst'", "]", "]", ",", "label", "=", "edge", "[", "'label'", "]", ")", ")", "return", "pydot_graph" ]
https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/python/caffe/draw.py#L130-L186
imharrywu/fastcoin
ed7f9152c1409cb88fadd9c1c4b903a194681a94
contrib/devtools/update-translations.py
python
remove_invalid_characters
(s)
return FIX_RE.sub(b'', s)
Remove invalid characters from translation string
Remove invalid characters from translation string
[ "Remove", "invalid", "characters", "from", "translation", "string" ]
def remove_invalid_characters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s)
[ "def", "remove_invalid_characters", "(", "s", ")", ":", "return", "FIX_RE", ".", "sub", "(", "b''", ",", "s", ")" ]
https://github.com/imharrywu/fastcoin/blob/ed7f9152c1409cb88fadd9c1c4b903a194681a94/contrib/devtools/update-translations.py#L100-L102
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armoryengine/ArmoryUtils.py
python
addWalletToList
(inWltPath, inWltList)
Helper function that checks to see if a path contains a valid wallet. If so, the wallet will be added to the incoming list.
Helper function that checks to see if a path contains a valid wallet. If so, the wallet will be added to the incoming list.
[ "Helper", "function", "that", "checks", "to", "see", "if", "a", "path", "contains", "a", "valid", "wallet", ".", "If", "so", "the", "wallet", "will", "be", "added", "to", "the", "incoming", "list", "." ]
def addWalletToList(inWltPath, inWltList): '''Helper function that checks to see if a path contains a valid wallet. If so, the wallet will be added to the incoming list.''' if os.path.isfile(inWltPath): if not inWltPath.endswith('backup.wallet'): openfile = open(inWltPath, 'rb') first8 = openfile.read(8) openfile.close() if first8=='\xbaWALLET\x00': inWltList.append(inWltPath) else: if not os.path.isdir(inWltPath): LOGWARN('Path %s does not exist.' % inWltPath) else: LOGDEBUG('%s is a directory.' % inWltPath)
[ "def", "addWalletToList", "(", "inWltPath", ",", "inWltList", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "inWltPath", ")", ":", "if", "not", "inWltPath", ".", "endswith", "(", "'backup.wallet'", ")", ":", "openfile", "=", "open", "(", "inWltPath", ",", "'rb'", ")", "first8", "=", "openfile", ".", "read", "(", "8", ")", "openfile", ".", "close", "(", ")", "if", "first8", "==", "'\\xbaWALLET\\x00'", ":", "inWltList", ".", "append", "(", "inWltPath", ")", "else", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "inWltPath", ")", ":", "LOGWARN", "(", "'Path %s does not exist.'", "%", "inWltPath", ")", "else", ":", "LOGDEBUG", "(", "'%s is a directory.'", "%", "inWltPath", ")" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/ArmoryUtils.py#L1032-L1046
google/usd_from_gltf
6d288cce8b68744494a226574ae1d7ba6a9c46eb
tools/ufgbatch/ufgcommon/util.py
python
TagTracker.add_from_output
(self, output)
Add totals from tags in log output text.
Add totals from tags in log output text.
[ "Add", "totals", "from", "tags", "in", "log", "output", "text", "." ]
def add_from_output(self, output): """Add totals from tags in log output text.""" for line in output.splitlines(): (severity, tag) = get_message_tag(line) if tag: add_in_dictionary(self.tag_totals[severity], tag, 1) if severity != SEVERITY_UNKNOWN: self.totals[severity] += 1
[ "def", "add_from_output", "(", "self", ",", "output", ")", ":", "for", "line", "in", "output", ".", "splitlines", "(", ")", ":", "(", "severity", ",", "tag", ")", "=", "get_message_tag", "(", "line", ")", "if", "tag", ":", "add_in_dictionary", "(", "self", ".", "tag_totals", "[", "severity", "]", ",", "tag", ",", "1", ")", "if", "severity", "!=", "SEVERITY_UNKNOWN", ":", "self", ".", "totals", "[", "severity", "]", "+=", "1" ]
https://github.com/google/usd_from_gltf/blob/6d288cce8b68744494a226574ae1d7ba6a9c46eb/tools/ufgbatch/ufgcommon/util.py#L263-L270
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/layers/python/layers/feature_column.py
python
_BucketizedColumn.insert_transformed_feature
(self, columns_to_tensors)
Handles sparse column to id conversion.
Handles sparse column to id conversion.
[ "Handles", "sparse", "column", "to", "id", "conversion", "." ]
def insert_transformed_feature(self, columns_to_tensors): """Handles sparse column to id conversion.""" columns_to_tensors[self] = self._transform_feature( _LazyBuilderByColumnsToTensor(columns_to_tensors))
[ "def", "insert_transformed_feature", "(", "self", ",", "columns_to_tensors", ")", ":", "columns_to_tensors", "[", "self", "]", "=", "self", ".", "_transform_feature", "(", "_LazyBuilderByColumnsToTensor", "(", "columns_to_tensors", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/feature_column.py#L2078-L2081
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/VMM/VMMAll/IEMAllInstructionsPython.py
python
SimpleParser.parseTagOpTestNum
(self, sTag, aasSections, iTagLine, iEndLine)
return self.parseTagOpTest(sTag, aasSections, iTagLine, iEndLine)
Numbered \@optest tag. Either \@optest42 or \@optest[42].
Numbered \
[ "Numbered", "\\" ]
def parseTagOpTestNum(self, sTag, aasSections, iTagLine, iEndLine): """ Numbered \@optest tag. Either \@optest42 or \@optest[42]. """ oInstr = self.ensureInstructionForOpTag(iTagLine); iTest = 0; if sTag[-1] == ']': iTest = int(sTag[8:-1]); else: iTest = int(sTag[7:]); if iTest != len(oInstr.aoTests): self.errorComment(iTagLine, '%s: incorrect test number: %u, actual %u' % (sTag, iTest, len(oInstr.aoTests),)); return self.parseTagOpTest(sTag, aasSections, iTagLine, iEndLine);
[ "def", "parseTagOpTestNum", "(", "self", ",", "sTag", ",", "aasSections", ",", "iTagLine", ",", "iEndLine", ")", ":", "oInstr", "=", "self", ".", "ensureInstructionForOpTag", "(", "iTagLine", ")", "iTest", "=", "0", "if", "sTag", "[", "-", "1", "]", "==", "']'", ":", "iTest", "=", "int", "(", "sTag", "[", "8", ":", "-", "1", "]", ")", "else", ":", "iTest", "=", "int", "(", "sTag", "[", "7", ":", "]", ")", "if", "iTest", "!=", "len", "(", "oInstr", ".", "aoTests", ")", ":", "self", ".", "errorComment", "(", "iTagLine", ",", "'%s: incorrect test number: %u, actual %u'", "%", "(", "sTag", ",", "iTest", ",", "len", "(", "oInstr", ".", "aoTests", ")", ",", ")", ")", "return", "self", ".", "parseTagOpTest", "(", "sTag", ",", "aasSections", ",", "iTagLine", ",", "iEndLine", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/VMM/VMMAll/IEMAllInstructionsPython.py#L2612-L2626
opengauss-mirror/openGauss-server
e383f1b77720a00ddbe4c0655bc85914d9b02a2b
src/gausskernel/dbmind/tools/anomaly_detection/detector/algorithm/fb_prophet.py
python
FbProphet.fit
(self, timeseries)
:param timeseries: list, it should include timestamp and value like [[111111111, 2222222222, ...], [4.0, 5.0, ...]]. :return: NA
:param timeseries: list, it should include timestamp and value like [[111111111, 2222222222, ...], [4.0, 5.0, ...]]. :return: NA
[ ":", "param", "timeseries", ":", "list", "it", "should", "include", "timestamp", "and", "value", "like", "[[", "111111111", "2222222222", "...", "]", "[", "4", ".", "0", "5", ".", "0", "...", "]]", ".", ":", "return", ":", "NA" ]
def fit(self, timeseries): """ :param timeseries: list, it should include timestamp and value like [[111111111, 2222222222, ...], [4.0, 5.0, ...]]. :return: NA """ timeseries = pd.DataFrame(timeseries, columns=['ds', 'y']) timeseries['ds'] = timeseries['ds'].map( lambda x: time.strftime(AlgModel.DATE_FORMAT, time.localtime(x))) self.train_length = len(timeseries) self.model = Prophet(yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=True) self.model.fit(timeseries)
[ "def", "fit", "(", "self", ",", "timeseries", ")", ":", "timeseries", "=", "pd", ".", "DataFrame", "(", "timeseries", ",", "columns", "=", "[", "'ds'", ",", "'y'", "]", ")", "timeseries", "[", "'ds'", "]", "=", "timeseries", "[", "'ds'", "]", ".", "map", "(", "lambda", "x", ":", "time", ".", "strftime", "(", "AlgModel", ".", "DATE_FORMAT", ",", "time", ".", "localtime", "(", "x", ")", ")", ")", "self", ".", "train_length", "=", "len", "(", "timeseries", ")", "self", ".", "model", "=", "Prophet", "(", "yearly_seasonality", "=", "True", ",", "weekly_seasonality", "=", "True", ",", "daily_seasonality", "=", "True", ")", "self", ".", "model", ".", "fit", "(", "timeseries", ")" ]
https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/anomaly_detection/detector/algorithm/fb_prophet.py#L35-L48
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel._input_check_error
(self, argument, arg_format)
Report an error that the argument is not of the expected format. This is a helper function which gets called by _input_check in several places.
Report an error that the argument is not of the expected format.
[ "Report", "an", "error", "that", "the", "argument", "is", "not", "of", "the", "expected", "format", "." ]
def _input_check_error(self, argument, arg_format): """ Report an error that the argument is not of the expected format. This is a helper function which gets called by _input_check in several places. """ argument_string = '%s' % argument if len(argument_string) > 50: argument_string = argument_string[:47] + '...' format_string = '%s' % arg_format if len(format_string) > 50: format_string = format_string[:47] + '...' self._error( 'Unexpected argument type', 'The argument to a function failed an input check. This ' 'is most likely due to passing an invalid argument to ' 'the function.\n\n' 'Argument: %s\n' 'Expected type: %s' % (argument_string, format_string))
[ "def", "_input_check_error", "(", "self", ",", "argument", ",", "arg_format", ")", ":", "argument_string", "=", "'%s'", "%", "argument", "if", "len", "(", "argument_string", ")", ">", "50", ":", "argument_string", "=", "argument_string", "[", ":", "47", "]", "+", "'...'", "format_string", "=", "'%s'", "%", "arg_format", "if", "len", "(", "format_string", ")", ">", "50", ":", "format_string", "=", "format_string", "[", ":", "47", "]", "+", "'...'", "self", ".", "_error", "(", "'Unexpected argument type'", ",", "'The argument to a function failed an input check. This '", "'is most likely due to passing an invalid argument to '", "'the function.\\n\\n'", "'Argument: %s\\n'", "'Expected type: %s'", "%", "(", "argument_string", ",", "format_string", ")", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L8249-L8269
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
Process.GetErrorStream
(*args, **kwargs)
return _misc_.Process_GetErrorStream(*args, **kwargs)
GetErrorStream(self) -> InputStream
GetErrorStream(self) -> InputStream
[ "GetErrorStream", "(", "self", ")", "-", ">", "InputStream" ]
def GetErrorStream(*args, **kwargs): """GetErrorStream(self) -> InputStream""" return _misc_.Process_GetErrorStream(*args, **kwargs)
[ "def", "GetErrorStream", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Process_GetErrorStream", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L2023-L2025
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TVoid.__eq__
(self, *args)
return _snap.TVoid___eq__(self, *args)
__eq__(TVoid self, TVoid arg2) -> bool Parameters: arg2: TVoid const &
__eq__(TVoid self, TVoid arg2) -> bool
[ "__eq__", "(", "TVoid", "self", "TVoid", "arg2", ")", "-", ">", "bool" ]
def __eq__(self, *args): """ __eq__(TVoid self, TVoid arg2) -> bool Parameters: arg2: TVoid const & """ return _snap.TVoid___eq__(self, *args)
[ "def", "__eq__", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TVoid___eq__", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L12045-L12053
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
Dialog.CanDoLayoutAdaptation
(*args, **kwargs)
return _windows_.Dialog_CanDoLayoutAdaptation(*args, **kwargs)
CanDoLayoutAdaptation(self) -> bool
CanDoLayoutAdaptation(self) -> bool
[ "CanDoLayoutAdaptation", "(", "self", ")", "-", ">", "bool" ]
def CanDoLayoutAdaptation(*args, **kwargs): """CanDoLayoutAdaptation(self) -> bool""" return _windows_.Dialog_CanDoLayoutAdaptation(*args, **kwargs)
[ "def", "CanDoLayoutAdaptation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "Dialog_CanDoLayoutAdaptation", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L823-L825
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
ez_setup.py
python
_python_cmd
(*args)
return subprocess.call(args) == 0
Execute a command. Return True if the command succeeded.
Execute a command.
[ "Execute", "a", "command", "." ]
def _python_cmd(*args): """ Execute a command. Return True if the command succeeded. """ args = (sys.executable,) + args return subprocess.call(args) == 0
[ "def", "_python_cmd", "(", "*", "args", ")", ":", "args", "=", "(", "sys", ".", "executable", ",", ")", "+", "args", "return", "subprocess", ".", "call", "(", "args", ")", "==", "0" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/ez_setup.py#L47-L54
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/gluon/data/dataset.py
python
Dataset.transform
(self, fn, lazy=True)
return SimpleDataset([i for i in trans])
Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False, transforms all samples at once. Otherwise, transforms each sample on demand. Note that if `fn` is stochastic, you must set lazy to True or you will get the same result on all epochs. Returns ------- Dataset The transformed dataset.
Returns a new dataset with each sample transformed by the transformer function `fn`.
[ "Returns", "a", "new", "dataset", "with", "each", "sample", "transformed", "by", "the", "transformer", "function", "fn", "." ]
def transform(self, fn, lazy=True): """Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False, transforms all samples at once. Otherwise, transforms each sample on demand. Note that if `fn` is stochastic, you must set lazy to True or you will get the same result on all epochs. Returns ------- Dataset The transformed dataset. """ trans = _LazyTransformDataset(self, fn) if lazy: return trans return SimpleDataset([i for i in trans])
[ "def", "transform", "(", "self", ",", "fn", ",", "lazy", "=", "True", ")", ":", "trans", "=", "_LazyTransformDataset", "(", "self", ",", "fn", ")", "if", "lazy", ":", "return", "trans", "return", "SimpleDataset", "(", "[", "i", "for", "i", "in", "trans", "]", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/data/dataset.py#L43-L66
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/docbook/__init__.py
python
DocbookMan
(env, target, source=None, *args, **kw)
return result
A pseudo-Builder, providing a Docbook toolchain for Man page output.
A pseudo-Builder, providing a Docbook toolchain for Man page output.
[ "A", "pseudo", "-", "Builder", "providing", "a", "Docbook", "toolchain", "for", "Man", "page", "output", "." ]
def DocbookMan(env, target, source=None, *args, **kw): """ A pseudo-Builder, providing a Docbook toolchain for Man page output. """ # Init list of targets/sources target, source = __extend_targets_sources(target, source) # Init XSL stylesheet __init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_MAN', ['manpages','docbook.xsl']) # Setup builder __builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder) # Create targets result = [] for t,s in zip(target,source): volnum = "1" outfiles = [] srcfile = __ensure_suffix(str(s),'.xml') if os.path.isfile(srcfile): try: import xml.dom.minidom dom = xml.dom.minidom.parse(__ensure_suffix(str(s),'.xml')) # Extract volume number, default is 1 for node in dom.getElementsByTagName('refmeta'): for vol in node.getElementsByTagName('manvolnum'): volnum = __get_xml_text(vol) # Extract output filenames for node in dom.getElementsByTagName('refnamediv'): for ref in node.getElementsByTagName('refname'): outfiles.append(__get_xml_text(ref)+'.'+volnum) except: # Use simple regex parsing f = open(__ensure_suffix(str(s),'.xml'), 'r') content = f.read() f.close() for m in re_manvolnum.finditer(content): volnum = m.group(1) for m in re_refname.finditer(content): outfiles.append(m.group(1)+'.'+volnum) if not outfiles: # Use stem of the source file spath = str(s) if not spath.endswith('.xml'): outfiles.append(spath+'.'+volnum) else: stem, ext = os.path.splitext(spath) outfiles.append(stem+'.'+volnum) else: # We have to completely rely on the given target name outfiles.append(t) __builder.__call__(env, outfiles[0], s, **kw) env.Depends(outfiles[0], kw['DOCBOOK_XSL']) result.append(outfiles[0]) if len(outfiles) > 1: env.Clean(outfiles[0], outfiles[1:]) return result
[ "def", "DocbookMan", "(", "env", ",", "target", ",", "source", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# Init list of targets/sources", "target", ",", "source", "=", "__extend_targets_sources", "(", "target", ",", "source", ")", "# Init XSL stylesheet", "__init_xsl_stylesheet", "(", "kw", ",", "env", ",", "'$DOCBOOK_DEFAULT_XSL_MAN'", ",", "[", "'manpages'", ",", "'docbook.xsl'", "]", ")", "# Setup builder", "__builder", "=", "__select_builder", "(", "__lxml_builder", ",", "__libxml2_builder", ",", "__xsltproc_builder", ")", "# Create targets", "result", "=", "[", "]", "for", "t", ",", "s", "in", "zip", "(", "target", ",", "source", ")", ":", "volnum", "=", "\"1\"", "outfiles", "=", "[", "]", "srcfile", "=", "__ensure_suffix", "(", "str", "(", "s", ")", ",", "'.xml'", ")", "if", "os", ".", "path", ".", "isfile", "(", "srcfile", ")", ":", "try", ":", "import", "xml", ".", "dom", ".", "minidom", "dom", "=", "xml", ".", "dom", ".", "minidom", ".", "parse", "(", "__ensure_suffix", "(", "str", "(", "s", ")", ",", "'.xml'", ")", ")", "# Extract volume number, default is 1", "for", "node", "in", "dom", ".", "getElementsByTagName", "(", "'refmeta'", ")", ":", "for", "vol", "in", "node", ".", "getElementsByTagName", "(", "'manvolnum'", ")", ":", "volnum", "=", "__get_xml_text", "(", "vol", ")", "# Extract output filenames", "for", "node", "in", "dom", ".", "getElementsByTagName", "(", "'refnamediv'", ")", ":", "for", "ref", "in", "node", ".", "getElementsByTagName", "(", "'refname'", ")", ":", "outfiles", ".", "append", "(", "__get_xml_text", "(", "ref", ")", "+", "'.'", "+", "volnum", ")", "except", ":", "# Use simple regex parsing ", "f", "=", "open", "(", "__ensure_suffix", "(", "str", "(", "s", ")", ",", "'.xml'", ")", ",", "'r'", ")", "content", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "for", "m", "in", "re_manvolnum", ".", "finditer", "(", "content", ")", ":", "volnum", "=", "m", ".", "group", "(", "1", ")", "for", "m", "in", "re_refname", ".", "finditer", "(", "content", ")", ":", "outfiles", ".", "append", "(", "m", ".", "group", "(", "1", ")", "+", "'.'", "+", "volnum", ")", "if", "not", "outfiles", ":", "# Use stem of the source file", "spath", "=", "str", "(", "s", ")", "if", "not", "spath", ".", "endswith", "(", "'.xml'", ")", ":", "outfiles", ".", "append", "(", "spath", "+", "'.'", "+", "volnum", ")", "else", ":", "stem", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "spath", ")", "outfiles", ".", "append", "(", "stem", "+", "'.'", "+", "volnum", ")", "else", ":", "# We have to completely rely on the given target name", "outfiles", ".", "append", "(", "t", ")", "__builder", ".", "__call__", "(", "env", ",", "outfiles", "[", "0", "]", ",", "s", ",", "*", "*", "kw", ")", "env", ".", "Depends", "(", "outfiles", "[", "0", "]", ",", "kw", "[", "'DOCBOOK_XSL'", "]", ")", "result", ".", "append", "(", "outfiles", "[", "0", "]", ")", "if", "len", "(", "outfiles", ")", ">", "1", ":", "env", ".", "Clean", "(", "outfiles", "[", "0", "]", ",", "outfiles", "[", "1", ":", "]", ")", "return", "result" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/docbook/__init__.py#L666-L731
microsoft/Azure-Kinect-Sensor-SDK
d87ef578676c05b9a5d23c097502942753bf3777
src/python/k4a/src/k4a/_bindings/device.py
python
Device.get_imu_sample
(self, timeout_ms:int)
return imu_sample
! Reads an IMU sample. @param timeout_ms (int): Specifies the time in milliseconds the function should block waiting for the sample. If set to 0, the function will return without blocking. Passing a negative number will block indefinitely until data is available, the device is disconnected, or another error occurs. @returns An instance of an ImuSample class that contains data from the IMU. If data is not available in the configured @p timeout_ms, then None is returned. @remarks - Gets the next sample in the streamed sequence of IMU samples from the device. If a new sample is not currently available, this function will block until the timeout is reached. The API will buffer at least two camera capture intervals worth of samples before dropping the oldest sample. Callers needing to capture all data need to ensure they read the data as fast as the data is being produced on average. @remarks - Upon successfully reading a sample this function will return an ImuSample. If a sample is not available in the configured @p timeout_ms, then the API will return None. @remarks - This function needs to be called while the device is in a running state; after start_imu() is called and before stop_imu() is called. @remarks - This function returns None when an internal problem is encountered, such as loss of the USB connection, inability to allocate enough memory, and other unexpected issues. Any error returned by this function signals the end of streaming data, and the caller should stop the stream using stop_imu(). @remarks - If this function is waiting for data (non-zero timeout) when stop_imu() or close() is called on another thread, this function will encounter an error and return None.
! Reads an IMU sample.
[ "!", "Reads", "an", "IMU", "sample", "." ]
def get_imu_sample(self, timeout_ms:int)->ImuSample: '''! Reads an IMU sample. @param timeout_ms (int): Specifies the time in milliseconds the function should block waiting for the sample. If set to 0, the function will return without blocking. Passing a negative number will block indefinitely until data is available, the device is disconnected, or another error occurs. @returns An instance of an ImuSample class that contains data from the IMU. If data is not available in the configured @p timeout_ms, then None is returned. @remarks - Gets the next sample in the streamed sequence of IMU samples from the device. If a new sample is not currently available, this function will block until the timeout is reached. The API will buffer at least two camera capture intervals worth of samples before dropping the oldest sample. Callers needing to capture all data need to ensure they read the data as fast as the data is being produced on average. @remarks - Upon successfully reading a sample this function will return an ImuSample. If a sample is not available in the configured @p timeout_ms, then the API will return None. @remarks - This function needs to be called while the device is in a running state; after start_imu() is called and before stop_imu() is called. @remarks - This function returns None when an internal problem is encountered, such as loss of the USB connection, inability to allocate enough memory, and other unexpected issues. Any error returned by this function signals the end of streaming data, and the caller should stop the stream using stop_imu(). @remarks - If this function is waiting for data (non-zero timeout) when stop_imu() or close() is called on another thread, this function will encounter an error and return None. ''' imu_sample = ImuSample() wait_status = k4a_device_get_imu_sample( self.__device_handle, _ctypes.byref(imu_sample), _ctypes.c_int32(timeout_ms) ) if wait_status != EWaitStatus.SUCCEEDED: imu_sample = None return imu_sample
[ "def", "get_imu_sample", "(", "self", ",", "timeout_ms", ":", "int", ")", "->", "ImuSample", ":", "imu_sample", "=", "ImuSample", "(", ")", "wait_status", "=", "k4a_device_get_imu_sample", "(", "self", ".", "__device_handle", ",", "_ctypes", ".", "byref", "(", "imu_sample", ")", ",", "_ctypes", ".", "c_int32", "(", "timeout_ms", ")", ")", "if", "wait_status", "!=", "EWaitStatus", ".", "SUCCEEDED", ":", "imu_sample", "=", "None", "return", "imu_sample" ]
https://github.com/microsoft/Azure-Kinect-Sensor-SDK/blob/d87ef578676c05b9a5d23c097502942753bf3777/src/python/k4a/src/k4a/_bindings/device.py#L345-L400
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/web_perf/metrics/rendering_stats.py
python
GetTimestampEventName
(process)
return 'BenchmarkInstrumentation::ImplThreadRenderingStats'
Returns the name of the events used to count frame timestamps.
Returns the name of the events used to count frame timestamps.
[ "Returns", "the", "name", "of", "the", "events", "used", "to", "count", "frame", "timestamps", "." ]
def GetTimestampEventName(process): """ Returns the name of the events used to count frame timestamps. """ if process.name == 'SurfaceFlinger': return 'vsync_before' event_name = 'BenchmarkInstrumentation::DisplayRenderingStats' for event in process.IterAllSlicesOfName(event_name): if 'data' in event.args and event.args['data']['frame_count'] == 1: return event_name return 'BenchmarkInstrumentation::ImplThreadRenderingStats'
[ "def", "GetTimestampEventName", "(", "process", ")", ":", "if", "process", ".", "name", "==", "'SurfaceFlinger'", ":", "return", "'vsync_before'", "event_name", "=", "'BenchmarkInstrumentation::DisplayRenderingStats'", "for", "event", "in", "process", ".", "IterAllSlicesOfName", "(", "event_name", ")", ":", "if", "'data'", "in", "event", ".", "args", "and", "event", ".", "args", "[", "'data'", "]", "[", "'frame_count'", "]", "==", "1", ":", "return", "event_name", "return", "'BenchmarkInstrumentation::ImplThreadRenderingStats'" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/web_perf/metrics/rendering_stats.py#L124-L134
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Menu.DestroyId
(*args, **kwargs)
return _core_.Menu_DestroyId(*args, **kwargs)
DestroyId(self, int id) -> bool
DestroyId(self, int id) -> bool
[ "DestroyId", "(", "self", "int", "id", ")", "-", ">", "bool" ]
def DestroyId(*args, **kwargs): """DestroyId(self, int id) -> bool""" return _core_.Menu_DestroyId(*args, **kwargs)
[ "def", "DestroyId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_DestroyId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L12126-L12128
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/tools/scan-build-py/libscanbuild/analyze.py
python
need_analyzer
(args)
return len(args) and not re.search('configure|autogen', args[0])
Check the intent of the build command. When static analyzer run against project configure step, it should be silent and no need to run the analyzer or generate report. To run `scan-build` against the configure step might be necessary, when compiler wrappers are used. That's the moment when build setup check the compiler and capture the location for the build process.
Check the intent of the build command.
[ "Check", "the", "intent", "of", "the", "build", "command", "." ]
def need_analyzer(args): """ Check the intent of the build command. When static analyzer run against project configure step, it should be silent and no need to run the analyzer or generate report. To run `scan-build` against the configure step might be necessary, when compiler wrappers are used. That's the moment when build setup check the compiler and capture the location for the build process. """ return len(args) and not re.search('configure|autogen', args[0])
[ "def", "need_analyzer", "(", "args", ")", ":", "return", "len", "(", "args", ")", "and", "not", "re", ".", "search", "(", "'configure|autogen'", ",", "args", "[", "0", "]", ")" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libscanbuild/analyze.py#L91-L101
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/lib/pretty.py
python
RepresentationPrinter._in_deferred_types
(self, cls)
return printer
Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future use.
Check if the given class is specified in the deferred type registry.
[ "Check", "if", "the", "given", "class", "is", "specified", "in", "the", "deferred", "type", "registry", "." ]
def _in_deferred_types(self, cls): """ Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future use. """ mod = _safe_getattr(cls, '__module__', None) name = _safe_getattr(cls, '__name__', None) key = (mod, name) printer = None if key in self.deferred_pprinters: # Move the printer over to the regular registry. printer = self.deferred_pprinters.pop(key) self.type_pprinters[cls] = printer return printer
[ "def", "_in_deferred_types", "(", "self", ",", "cls", ")", ":", "mod", "=", "_safe_getattr", "(", "cls", ",", "'__module__'", ",", "None", ")", "name", "=", "_safe_getattr", "(", "cls", ",", "'__name__'", ",", "None", ")", "key", "=", "(", "mod", ",", "name", ")", "printer", "=", "None", "if", "key", "in", "self", ".", "deferred_pprinters", ":", "# Move the printer over to the regular registry.", "printer", "=", "self", ".", "deferred_pprinters", ".", "pop", "(", "key", ")", "self", ".", "type_pprinters", "[", "cls", "]", "=", "printer", "return", "printer" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/lib/pretty.py#L401-L417
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/settings.py
python
Settings.setAndSave
(self, **kwargs)
Sets keyword arguments as settings and quietly saves
Sets keyword arguments as settings and quietly saves
[ "Sets", "keyword", "arguments", "as", "settings", "and", "quietly", "saves" ]
def setAndSave(self, **kwargs): """Sets keyword arguments as settings and quietly saves """ if self._ephemeral: return self.update(kwargs) self.save(ignoreErrors=True)
[ "def", "setAndSave", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_ephemeral", ":", "return", "self", ".", "update", "(", "kwargs", ")", "self", ".", "save", "(", "ignoreErrors", "=", "True", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/settings.py#L119-L126
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/gyp/util/md5_check.py
python
_Metadata.GetTag
(self, path, subpath=None)
return ret and ret['tag']
Returns the tag for the given path / subpath.
Returns the tag for the given path / subpath.
[ "Returns", "the", "tag", "for", "the", "given", "path", "/", "subpath", "." ]
def GetTag(self, path, subpath=None): """Returns the tag for the given path / subpath.""" ret = self._GetEntry(path, subpath) return ret and ret['tag']
[ "def", "GetTag", "(", "self", ",", "path", ",", "subpath", "=", "None", ")", ":", "ret", "=", "self", ".", "_GetEntry", "(", "path", ",", "subpath", ")", "return", "ret", "and", "ret", "[", "'tag'", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/gyp/util/md5_check.py#L339-L342
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Validator.IsSilent
(*args, **kwargs)
return _core_.Validator_IsSilent(*args, **kwargs)
IsSilent() -> bool
IsSilent() -> bool
[ "IsSilent", "()", "-", ">", "bool" ]
def IsSilent(*args, **kwargs): """IsSilent() -> bool""" return _core_.Validator_IsSilent(*args, **kwargs)
[ "def", "IsSilent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Validator_IsSilent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L11900-L11902
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/ops.py
python
Tensor.__iter__
(self)
Dummy method to prevent iteration. Do not call. NOTE(mrry): If we register __getitem__ as an overloaded operator, Python will valiantly attempt to iterate over the Tensor from 0 to infinity. Declaring this method prevents this unintended behavior. Raises: TypeError: when invoked.
Dummy method to prevent iteration. Do not call.
[ "Dummy", "method", "to", "prevent", "iteration", ".", "Do", "not", "call", "." ]
def __iter__(self): """Dummy method to prevent iteration. Do not call. NOTE(mrry): If we register __getitem__ as an overloaded operator, Python will valiantly attempt to iterate over the Tensor from 0 to infinity. Declaring this method prevents this unintended behavior. Raises: TypeError: when invoked. """ raise TypeError("'Tensor' object is not iterable.")
[ "def", "__iter__", "(", "self", ")", ":", "raise", "TypeError", "(", "\"'Tensor' object is not iterable.\"", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L488-L499
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.GetDefaultCellOverflow
(*args, **kwargs)
return _grid.Grid_GetDefaultCellOverflow(*args, **kwargs)
GetDefaultCellOverflow(self) -> bool
GetDefaultCellOverflow(self) -> bool
[ "GetDefaultCellOverflow", "(", "self", ")", "-", ">", "bool" ]
def GetDefaultCellOverflow(*args, **kwargs): """GetDefaultCellOverflow(self) -> bool""" return _grid.Grid_GetDefaultCellOverflow(*args, **kwargs)
[ "def", "GetDefaultCellOverflow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetDefaultCellOverflow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1802-L1804
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/ultisnips/plugin/UltiSnips/__init__.py
python
SnippetManager._find_snippets
(self, ft, trigger, potentially = False, seen=None)
return parent_results + snips.get_matching_snippets( trigger, potentially)
Find snippets matching trigger ft - file type to search trigger - trigger to match against potentially - also returns snippets that could potentially match; that is which triggers start with the current trigger
Find snippets matching trigger
[ "Find", "snippets", "matching", "trigger" ]
def _find_snippets(self, ft, trigger, potentially = False, seen=None): """ Find snippets matching trigger ft - file type to search trigger - trigger to match against potentially - also returns snippets that could potentially match; that is which triggers start with the current trigger """ snips = self._snippets.get(ft,None) if not snips: return [] if not seen: seen = [] seen.append(ft) parent_results = [] for p in snips.extends: if p not in seen: seen.append(p) parent_results += self._find_snippets(p, trigger, potentially, seen) return parent_results + snips.get_matching_snippets( trigger, potentially)
[ "def", "_find_snippets", "(", "self", ",", "ft", ",", "trigger", ",", "potentially", "=", "False", ",", "seen", "=", "None", ")", ":", "snips", "=", "self", ".", "_snippets", ".", "get", "(", "ft", ",", "None", ")", "if", "not", "snips", ":", "return", "[", "]", "if", "not", "seen", ":", "seen", "=", "[", "]", "seen", ".", "append", "(", "ft", ")", "parent_results", "=", "[", "]", "for", "p", "in", "snips", ".", "extends", ":", "if", "p", "not", "in", "seen", ":", "seen", ".", "append", "(", "p", ")", "parent_results", "+=", "self", ".", "_find_snippets", "(", "p", ",", "trigger", ",", "potentially", ",", "seen", ")", "return", "parent_results", "+", "snips", ".", "get_matching_snippets", "(", "trigger", ",", "potentially", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/ultisnips/plugin/UltiSnips/__init__.py#L1058-L1084
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextLine.GetParent
(*args, **kwargs)
return _richtext.RichTextLine_GetParent(*args, **kwargs)
GetParent(self) -> RichTextParagraph
GetParent(self) -> RichTextParagraph
[ "GetParent", "(", "self", ")", "-", ">", "RichTextParagraph" ]
def GetParent(*args, **kwargs): """GetParent(self) -> RichTextParagraph""" return _richtext.RichTextLine_GetParent(*args, **kwargs)
[ "def", "GetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextLine_GetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1907-L1909