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
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/harness-thci/OpenThread_WpanCtl.py
python
OpenThread_WpanCtl.MGMT_ACTIVE_GET
(self, Addr='', TLVs=[])
send MGMT_ACTIVE_GET command Returns: True: successful to send MGMT_ACTIVE_GET False: fail to send MGMT_ACTIVE_GET
send MGMT_ACTIVE_GET command
[ "send", "MGMT_ACTIVE_GET", "command" ]
def MGMT_ACTIVE_GET(self, Addr='', TLVs=[]): """send MGMT_ACTIVE_GET command Returns: True: successful to send MGMT_ACTIVE_GET False: fail to send MGMT_ACTIVE_GET """ print('%s call MGMT_ACTIVE_GET' % self.port) try: cmd = self.wpan_cmd_prefix + 'dataset mgmt-get-active' if len(TLVs) != 0: tlvs = ''.join('%02x' % tlv for tlv in TLVs) setTLVCmd = self.wpan_cmd_prefix + 'setprop Dataset:RawTlvs ' + tlvs if self.__sendCommand(setTLVCmd)[0] == 'Fail': return False else: if self.__sendCommand(self.wpan_cmd_prefix + 'dataset erase')[0] == 'Fail': return False if Addr != '': setAddressCmd = self.wpan_cmd_prefix + 'setprop Dataset:DestIpAddress ' + Addr if self.__sendCommand(setAddressCmd)[0] == 'Fail': return False print(cmd) return self.__sendCommand(cmd)[0] != 'Fail' except Exception as e: ModuleHelper.WriteIntoDebugLogger('MGMT_ACTIVE_GET() Error: ' + str(e))
[ "def", "MGMT_ACTIVE_GET", "(", "self", ",", "Addr", "=", "''", ",", "TLVs", "=", "[", "]", ")", ":", "print", "(", "'%s call MGMT_ACTIVE_GET'", "%", "self", ".", "port", ")", "try", ":", "cmd", "=", "self", ".", "wpan_cmd_prefix", "+", "'dataset mgmt-get-active'", "if", "len", "(", "TLVs", ")", "!=", "0", ":", "tlvs", "=", "''", ".", "join", "(", "'%02x'", "%", "tlv", "for", "tlv", "in", "TLVs", ")", "setTLVCmd", "=", "self", ".", "wpan_cmd_prefix", "+", "'setprop Dataset:RawTlvs '", "+", "tlvs", "if", "self", ".", "__sendCommand", "(", "setTLVCmd", ")", "[", "0", "]", "==", "'Fail'", ":", "return", "False", "else", ":", "if", "self", ".", "__sendCommand", "(", "self", ".", "wpan_cmd_prefix", "+", "'dataset erase'", ")", "[", "0", "]", "==", "'Fail'", ":", "return", "False", "if", "Addr", "!=", "''", ":", "setAddressCmd", "=", "self", ".", "wpan_cmd_prefix", "+", "'setprop Dataset:DestIpAddress '", "+", "Addr", "if", "self", ".", "__sendCommand", "(", "setAddressCmd", ")", "[", "0", "]", "==", "'Fail'", ":", "return", "False", "print", "(", "cmd", ")", "return", "self", ".", "__sendCommand", "(", "cmd", ")", "[", "0", "]", "!=", "'Fail'", "except", "Exception", "as", "e", ":", "ModuleHelper", ".", "WriteIntoDebugLogger", "(", "'MGMT_ACTIVE_GET() Error: '", "+", "str", "(", "e", ")", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread_WpanCtl.py#L2255-L2286
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/slim/python/slim/summaries.py
python
add_zero_fraction_summaries
(tensors, prefix=None)
return summary_ops
Adds a scalar zero-fraction summary for each of the given tensors. Args: tensors: a list of variable or op tensors. prefix: An optional prefix for the summary names. Returns: A list of scalar `Tensors` of type `string` whose contents are the serialized `Summary` protocol buffer.
Adds a scalar zero-fraction summary for each of the given tensors.
[ "Adds", "a", "scalar", "zero", "-", "fraction", "summary", "for", "each", "of", "the", "given", "tensors", "." ]
def add_zero_fraction_summaries(tensors, prefix=None): """Adds a scalar zero-fraction summary for each of the given tensors. Args: tensors: a list of variable or op tensors. prefix: An optional prefix for the summary names. Returns: A list of scalar `Tensors` of type `string` whose contents are the serialized `Summary` protocol buffer. """ summary_ops = [] for tensor in tensors: summary_ops.append(add_zero_fraction_summary(tensor, prefix=prefix)) return summary_ops
[ "def", "add_zero_fraction_summaries", "(", "tensors", ",", "prefix", "=", "None", ")", ":", "summary_ops", "=", "[", "]", "for", "tensor", "in", "tensors", ":", "summary_ops", ".", "append", "(", "add_zero_fraction_summary", "(", "tensor", ",", "prefix", "=", "prefix", ")", ")", "return", "summary_ops" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/slim/python/slim/summaries.py#L206-L220
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
python
Standard_Suite_Events.quit
(self, _no_object=None, _attributes={}, **_arguments)
quit: Quit an application Keyword argument saving: specifies whether to save currently open documents Keyword argument _attributes: AppleEvent attribute dictionary
quit: Quit an application Keyword argument saving: specifies whether to save currently open documents Keyword argument _attributes: AppleEvent attribute dictionary
[ "quit", ":", "Quit", "an", "application", "Keyword", "argument", "saving", ":", "specifies", "whether", "to", "save", "currently", "open", "documents", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def quit(self, _no_object=None, _attributes={}, **_arguments): """quit: Quit an application Keyword argument saving: specifies whether to save currently open documents Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'aevt' _subcode = 'quit' aetools.keysubst(_arguments, self._argmap_quit) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'savo', _Enum_savo) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "quit", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'aevt'", "_subcode", "=", "'quit'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_quit", ")", "if", "_no_object", "is", "not", "None", ":", "raise", "TypeError", ",", "'No direct arg expected'", "aetools", ".", "enumsubst", "(", "_arguments", ",", "'savo'", ",", "_Enum_savo", ")", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py#L339-L358
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/estimators/svm.py
python
SVM.export_with_defaults
( self, export_dir, signature_fn=None, input_fn=None, default_batch_size=1, exports_to_keep=None)
return super(SVM, self).export(export_dir=export_dir, signature_fn=signature_fn, input_fn=input_fn or default_input_fn, default_batch_size=default_batch_size, exports_to_keep=exports_to_keep)
Same as BaseEstimator.export, but uses some defaults.
Same as BaseEstimator.export, but uses some defaults.
[ "Same", "as", "BaseEstimator", ".", "export", "but", "uses", "some", "defaults", "." ]
def export_with_defaults( self, export_dir, signature_fn=None, input_fn=None, default_batch_size=1, exports_to_keep=None): """Same as BaseEstimator.export, but uses some defaults.""" def default_input_fn(unused_estimator, examples): return layers.parse_feature_columns_from_examples( examples, self._feature_columns) return super(SVM, self).export(export_dir=export_dir, signature_fn=signature_fn, input_fn=input_fn or default_input_fn, default_batch_size=default_batch_size, exports_to_keep=exports_to_keep)
[ "def", "export_with_defaults", "(", "self", ",", "export_dir", ",", "signature_fn", "=", "None", ",", "input_fn", "=", "None", ",", "default_batch_size", "=", "1", ",", "exports_to_keep", "=", "None", ")", ":", "def", "default_input_fn", "(", "unused_estimator", ",", "examples", ")", ":", "return", "layers", ".", "parse_feature_columns_from_examples", "(", "examples", ",", "self", ".", "_feature_columns", ")", "return", "super", "(", "SVM", ",", "self", ")", ".", "export", "(", "export_dir", "=", "export_dir", ",", "signature_fn", "=", "signature_fn", ",", "input_fn", "=", "input_fn", "or", "default_input_fn", ",", "default_batch_size", "=", "default_batch_size", ",", "exports_to_keep", "=", "exports_to_keep", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/svm.py#L200-L215
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/spawn.py
python
spawn
(cmd, search_path=1, verbose=0, dry_run=0)
Run another program, specified as a command list 'cmd', in a new process. 'cmd' is just the argument list for the new process, ie. cmd[0] is the program to run and cmd[1:] are the rest of its arguments. There is no way to run a program with a name different from that of its executable. If 'search_path' is true (the default), the system's executable search path will be used to find the program; otherwise, cmd[0] must be the exact path to the executable. If 'dry_run' is true, the command will not actually be run. Raise DistutilsExecError if running the program fails in any way; just return on success.
Run another program, specified as a command list 'cmd', in a new process.
[ "Run", "another", "program", "specified", "as", "a", "command", "list", "cmd", "in", "a", "new", "process", "." ]
def spawn(cmd, search_path=1, verbose=0, dry_run=0): """Run another program, specified as a command list 'cmd', in a new process. 'cmd' is just the argument list for the new process, ie. cmd[0] is the program to run and cmd[1:] are the rest of its arguments. There is no way to run a program with a name different from that of its executable. If 'search_path' is true (the default), the system's executable search path will be used to find the program; otherwise, cmd[0] must be the exact path to the executable. If 'dry_run' is true, the command will not actually be run. Raise DistutilsExecError if running the program fails in any way; just return on success. """ if os.name == 'posix': _spawn_posix(cmd, search_path, dry_run=dry_run) elif os.name == 'nt': _spawn_nt(cmd, search_path, dry_run=dry_run) elif os.name == 'os2': _spawn_os2(cmd, search_path, dry_run=dry_run) else: raise DistutilsPlatformError, \ "don't know how to spawn programs on platform '%s'" % os.name
[ "def", "spawn", "(", "cmd", ",", "search_path", "=", "1", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "_spawn_posix", "(", "cmd", ",", "search_path", ",", "dry_run", "=", "dry_run", ")", "elif", "os", ".", "name", "==", "'nt'", ":", "_spawn_nt", "(", "cmd", ",", "search_path", ",", "dry_run", "=", "dry_run", ")", "elif", "os", ".", "name", "==", "'os2'", ":", "_spawn_os2", "(", "cmd", ",", "search_path", ",", "dry_run", "=", "dry_run", ")", "else", ":", "raise", "DistutilsPlatformError", ",", "\"don't know how to spawn programs on platform '%s'\"", "%", "os", ".", "name" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/spawn.py#L17-L41
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/metric_op.py
python
accuracy
(input, label, k=1, correct=None, total=None)
return acc_out
accuracy layer. Refer to the https://en.wikipedia.org/wiki/Precision_and_recall This function computes the accuracy using the input and label. If the correct label occurs in top k predictions, then correct will increment by one. Note: the dtype of accuracy is determined by input. the input and label dtype can be different. Args: input(Variable): The input of accuracy layer, which is the predictions of network. A LoDTensor or Tensor with type float32,float64. The shape is ``[sample_number, class_dim]`` . label(Variable): The label of dataset. LoDTensor or Tensor with type int32,int64. The shape is ``[sample_number, 1]`` . k(int): The top k predictions for each class will be checked. Data type is int64 or int32. correct(Variable): The correct predictions count. A Tensor with type int64 or int32. total(Variable): The total entries count. A tensor with type int64 or int32. Returns: Variable: The correct rate. A Tensor with type float32. Examples: .. code-block:: python import numpy as np import paddle import paddle.static as static import paddle.nn.functional as F paddle.enable_static() data = static.data(name="input", shape=[-1, 32, 32], dtype="float32") label = static.data(name="label", shape=[-1,1], dtype="int") fc_out = static.nn.fc(x=data, size=10) predict = F.softmax(x=fc_out) result = static.accuracy(input=predict, label=label, k=5) place = paddle.CPUPlace() exe = static.Executor(place) exe.run(static.default_startup_program()) x = np.random.rand(3, 32, 32).astype("float32") y = np.array([[1],[0],[1]]) output= exe.run(feed={"input": x,"label": y}, fetch_list=[result[0]]) print(output) #[array([0.], dtype=float32)]
accuracy layer. Refer to the https://en.wikipedia.org/wiki/Precision_and_recall
[ "accuracy", "layer", ".", "Refer", "to", "the", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Precision_and_recall" ]
def accuracy(input, label, k=1, correct=None, total=None): """ accuracy layer. Refer to the https://en.wikipedia.org/wiki/Precision_and_recall This function computes the accuracy using the input and label. If the correct label occurs in top k predictions, then correct will increment by one. Note: the dtype of accuracy is determined by input. the input and label dtype can be different. Args: input(Variable): The input of accuracy layer, which is the predictions of network. A LoDTensor or Tensor with type float32,float64. The shape is ``[sample_number, class_dim]`` . label(Variable): The label of dataset. LoDTensor or Tensor with type int32,int64. The shape is ``[sample_number, 1]`` . k(int): The top k predictions for each class will be checked. Data type is int64 or int32. correct(Variable): The correct predictions count. A Tensor with type int64 or int32. total(Variable): The total entries count. A tensor with type int64 or int32. Returns: Variable: The correct rate. A Tensor with type float32. Examples: .. code-block:: python import numpy as np import paddle import paddle.static as static import paddle.nn.functional as F paddle.enable_static() data = static.data(name="input", shape=[-1, 32, 32], dtype="float32") label = static.data(name="label", shape=[-1,1], dtype="int") fc_out = static.nn.fc(x=data, size=10) predict = F.softmax(x=fc_out) result = static.accuracy(input=predict, label=label, k=5) place = paddle.CPUPlace() exe = static.Executor(place) exe.run(static.default_startup_program()) x = np.random.rand(3, 32, 32).astype("float32") y = np.array([[1],[0],[1]]) output= exe.run(feed={"input": x,"label": y}, fetch_list=[result[0]]) print(output) #[array([0.], dtype=float32)] """ if in_dygraph_mode(): if correct is None: correct = _varbase_creator(dtype="int32") if total is None: total = _varbase_creator(dtype="int32") _k = k.numpy().item(0) if isinstance(k, Variable) else k topk_out, topk_indices = _C_ops.top_k_v2(input, 'k', _k, 'sorted', False) _acc, _, _ = _C_ops.accuracy(topk_out, topk_indices, label, correct, total) return _acc helper = LayerHelper("accuracy", **locals()) check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], 'accuracy') topk_out = helper.create_variable_for_type_inference(dtype=input.dtype) topk_indices = helper.create_variable_for_type_inference(dtype="int64") inputs = {"X": [input]} if isinstance(k, Variable): inputs['K'] = [k] else: attrs = {'k': k} attrs['sorted'] = False helper.append_op( type="top_k_v2", inputs=inputs, attrs=attrs, outputs={"Out": [topk_out], "Indices": [topk_indices]}) acc_out = helper.create_variable_for_type_inference(dtype="float32") if correct is None: correct = helper.create_variable_for_type_inference(dtype="int32") if total is None: total = helper.create_variable_for_type_inference(dtype="int32") helper.append_op( type="accuracy", inputs={ "Out": [topk_out], "Indices": [topk_indices], "Label": [label] }, outputs={ "Accuracy": [acc_out], "Correct": [correct], "Total": [total], }) return acc_out
[ "def", "accuracy", "(", "input", ",", "label", ",", "k", "=", "1", ",", "correct", "=", "None", ",", "total", "=", "None", ")", ":", "if", "in_dygraph_mode", "(", ")", ":", "if", "correct", "is", "None", ":", "correct", "=", "_varbase_creator", "(", "dtype", "=", "\"int32\"", ")", "if", "total", "is", "None", ":", "total", "=", "_varbase_creator", "(", "dtype", "=", "\"int32\"", ")", "_k", "=", "k", ".", "numpy", "(", ")", ".", "item", "(", "0", ")", "if", "isinstance", "(", "k", ",", "Variable", ")", "else", "k", "topk_out", ",", "topk_indices", "=", "_C_ops", ".", "top_k_v2", "(", "input", ",", "'k'", ",", "_k", ",", "'sorted'", ",", "False", ")", "_acc", ",", "_", ",", "_", "=", "_C_ops", ".", "accuracy", "(", "topk_out", ",", "topk_indices", ",", "label", ",", "correct", ",", "total", ")", "return", "_acc", "helper", "=", "LayerHelper", "(", "\"accuracy\"", ",", "*", "*", "locals", "(", ")", ")", "check_variable_and_dtype", "(", "input", ",", "'input'", ",", "[", "'float16'", ",", "'float32'", ",", "'float64'", "]", ",", "'accuracy'", ")", "topk_out", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "input", ".", "dtype", ")", "topk_indices", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "\"int64\"", ")", "inputs", "=", "{", "\"X\"", ":", "[", "input", "]", "}", "if", "isinstance", "(", "k", ",", "Variable", ")", ":", "inputs", "[", "'K'", "]", "=", "[", "k", "]", "else", ":", "attrs", "=", "{", "'k'", ":", "k", "}", "attrs", "[", "'sorted'", "]", "=", "False", "helper", ".", "append_op", "(", "type", "=", "\"top_k_v2\"", ",", "inputs", "=", "inputs", ",", "attrs", "=", "attrs", ",", "outputs", "=", "{", "\"Out\"", ":", "[", "topk_out", "]", ",", "\"Indices\"", ":", "[", "topk_indices", "]", "}", ")", "acc_out", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "\"float32\"", ")", "if", "correct", "is", "None", ":", "correct", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "\"int32\"", ")", "if", "total", "is", "None", ":", "total", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "\"int32\"", ")", "helper", ".", "append_op", "(", "type", "=", "\"accuracy\"", ",", "inputs", "=", "{", "\"Out\"", ":", "[", "topk_out", "]", ",", "\"Indices\"", ":", "[", "topk_indices", "]", ",", "\"Label\"", ":", "[", "label", "]", "}", ",", "outputs", "=", "{", "\"Accuracy\"", ":", "[", "acc_out", "]", ",", "\"Correct\"", ":", "[", "correct", "]", ",", "\"Total\"", ":", "[", "total", "]", ",", "}", ")", "return", "acc_out" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/metric_op.py#L33-L128
rootm0s/Protectors
5b3f4d11687a5955caf9c3af30666c4bfc2c19ab
OWASP-ZSC/module/readline_windows/pyreadline/modes/emacs.py
python
EmacsMode.forward_backward_delete_char
(self, e)
Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key.
Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key.
[ "Delete", "the", "character", "under", "the", "cursor", "unless", "the", "cursor", "is", "at", "the", "end", "of", "the", "line", "in", "which", "case", "the", "character", "behind", "the", "cursor", "is", "deleted", ".", "By", "default", "this", "is", "not", "bound", "to", "a", "key", "." ]
def forward_backward_delete_char(self, e): # () '''Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key.''' self.finalize()
[ "def", "forward_backward_delete_char", "(", "self", ",", "e", ")", ":", "# ()", "self", ".", "finalize", "(", ")" ]
https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/modes/emacs.py#L381-L385
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/python-package/catboost/core.py
python
CatBoostClassifier.fit
(self, X, y=None, cat_features=None, text_features=None, embedding_features=None, sample_weight=None, baseline=None, use_best_model=None, eval_set=None, verbose=None, logging_level=None, plot=False, column_description=None, verbose_eval=None, metric_period=None, silent=None, early_stopping_rounds=None, save_snapshot=None, snapshot_file=None, snapshot_interval=None, init_model=None, callbacks=None, log_cout=sys.stdout, log_cerr=sys.stderr)
return self
Fit the CatBoostClassifier model. Parameters ---------- X : catboost.Pool or list or numpy.ndarray or pandas.DataFrame or pandas.Series If not catboost.Pool, 2 dimensional Feature matrix or string - file with dataset. y : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Labels, 1 dimensional array like. Use only if X is not catboost.Pool. cat_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Categ columns indices. Use only if X is not catboost.Pool. text_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Text columns indices. Use only if X is not catboost.Pool. embedding_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Embedding columns indices. Use only if X is not catboost.Pool. sample_weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Instance weights, 1 dimensional array like. baseline : list or numpy.ndarray, optional (default=None) If not None, giving 2 dimensional array like data. Use only if X is not catboost.Pool. use_best_model : bool, optional (default=None) Flag to use best model eval_set : catboost.Pool or list, optional (default=None) A list of (X, y) tuple pairs to use as a validation set for early-stopping metric_period : int Frequency of evaluating metrics. verbose : bool or int If verbose is bool, then if set to True, logging_level is set to Verbose, if set to False, logging_level is set to Silent. If verbose is int, it determines the frequency of writing metrics to output and logging_level is set to Verbose. silent : bool If silent is True, logging_level is set to Silent. If silent is False, logging_level is set to Verbose. logging_level : string, optional (default=None) Possible values: - 'Silent' - 'Verbose' - 'Info' - 'Debug' plot : bool, optional (default=False) If True, draw train and eval error in Jupyter notebook verbose_eval : bool or int Synonym for verbose. Only one of these parameters should be set. early_stopping_rounds : int Activates Iter overfitting detector with od_wait set to early_stopping_rounds. save_snapshot : bool, [default=None] Enable progress snapshotting for restoring progress after crashes or interruptions snapshot_file : string or pathlib.Path, [default=None] Learn progress snapshot file path, if None will use default filename snapshot_interval: int, [default=600] Interval between saving snapshots (seconds) init_model : CatBoost class or string or pathlib.Path, [default=None] Continue training starting from the existing model. If this parameter is a string or pathlib.Path, load initial model from the path specified by this string. callbacks : list, optional (default=None) List of callback objects that are applied at end of each iteration. log_cout: output stream or callback for logging log_cerr: error stream or callback for logging Returns ------- model : CatBoost
Fit the CatBoostClassifier model.
[ "Fit", "the", "CatBoostClassifier", "model", "." ]
def fit(self, X, y=None, cat_features=None, text_features=None, embedding_features=None, sample_weight=None, baseline=None, use_best_model=None, eval_set=None, verbose=None, logging_level=None, plot=False, column_description=None, verbose_eval=None, metric_period=None, silent=None, early_stopping_rounds=None, save_snapshot=None, snapshot_file=None, snapshot_interval=None, init_model=None, callbacks=None, log_cout=sys.stdout, log_cerr=sys.stderr): """ Fit the CatBoostClassifier model. Parameters ---------- X : catboost.Pool or list or numpy.ndarray or pandas.DataFrame or pandas.Series If not catboost.Pool, 2 dimensional Feature matrix or string - file with dataset. y : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Labels, 1 dimensional array like. Use only if X is not catboost.Pool. cat_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Categ columns indices. Use only if X is not catboost.Pool. text_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Text columns indices. Use only if X is not catboost.Pool. embedding_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Embedding columns indices. Use only if X is not catboost.Pool. sample_weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Instance weights, 1 dimensional array like. baseline : list or numpy.ndarray, optional (default=None) If not None, giving 2 dimensional array like data. Use only if X is not catboost.Pool. use_best_model : bool, optional (default=None) Flag to use best model eval_set : catboost.Pool or list, optional (default=None) A list of (X, y) tuple pairs to use as a validation set for early-stopping metric_period : int Frequency of evaluating metrics. verbose : bool or int If verbose is bool, then if set to True, logging_level is set to Verbose, if set to False, logging_level is set to Silent. If verbose is int, it determines the frequency of writing metrics to output and logging_level is set to Verbose. silent : bool If silent is True, logging_level is set to Silent. If silent is False, logging_level is set to Verbose. logging_level : string, optional (default=None) Possible values: - 'Silent' - 'Verbose' - 'Info' - 'Debug' plot : bool, optional (default=False) If True, draw train and eval error in Jupyter notebook verbose_eval : bool or int Synonym for verbose. Only one of these parameters should be set. early_stopping_rounds : int Activates Iter overfitting detector with od_wait set to early_stopping_rounds. save_snapshot : bool, [default=None] Enable progress snapshotting for restoring progress after crashes or interruptions snapshot_file : string or pathlib.Path, [default=None] Learn progress snapshot file path, if None will use default filename snapshot_interval: int, [default=600] Interval between saving snapshots (seconds) init_model : CatBoost class or string or pathlib.Path, [default=None] Continue training starting from the existing model. If this parameter is a string or pathlib.Path, load initial model from the path specified by this string. callbacks : list, optional (default=None) List of callback objects that are applied at end of each iteration. log_cout: output stream or callback for logging log_cerr: error stream or callback for logging Returns ------- model : CatBoost """ params = self._init_params.copy() _process_synonyms(params) if 'loss_function' in params: CatBoostClassifier._check_is_compatible_loss(params['loss_function']) self._fit(X, y, cat_features, text_features, embedding_features, None, sample_weight, None, None, None, None, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model, callbacks, log_cout, log_cerr) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "cat_features", "=", "None", ",", "text_features", "=", "None", ",", "embedding_features", "=", "None", ",", "sample_weight", "=", "None", ",", "baseline", "=", "None", ",", "use_best_model", "=", "None", ",", "eval_set", "=", "None", ",", "verbose", "=", "None", ",", "logging_level", "=", "None", ",", "plot", "=", "False", ",", "column_description", "=", "None", ",", "verbose_eval", "=", "None", ",", "metric_period", "=", "None", ",", "silent", "=", "None", ",", "early_stopping_rounds", "=", "None", ",", "save_snapshot", "=", "None", ",", "snapshot_file", "=", "None", ",", "snapshot_interval", "=", "None", ",", "init_model", "=", "None", ",", "callbacks", "=", "None", ",", "log_cout", "=", "sys", ".", "stdout", ",", "log_cerr", "=", "sys", ".", "stderr", ")", ":", "params", "=", "self", ".", "_init_params", ".", "copy", "(", ")", "_process_synonyms", "(", "params", ")", "if", "'loss_function'", "in", "params", ":", "CatBoostClassifier", ".", "_check_is_compatible_loss", "(", "params", "[", "'loss_function'", "]", ")", "self", ".", "_fit", "(", "X", ",", "y", ",", "cat_features", ",", "text_features", ",", "embedding_features", ",", "None", ",", "sample_weight", ",", "None", ",", "None", ",", "None", ",", "None", ",", "baseline", ",", "use_best_model", ",", "eval_set", ",", "verbose", ",", "logging_level", ",", "plot", ",", "column_description", ",", "verbose_eval", ",", "metric_period", ",", "silent", ",", "early_stopping_rounds", ",", "save_snapshot", ",", "snapshot_file", ",", "snapshot_interval", ",", "init_model", ",", "callbacks", ",", "log_cout", ",", "log_cerr", ")", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/core.py#L4820-L4924
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/virtualenv/files/virtualenv_support/distribute_setup.py
python
_patch_file
(path, content)
return True
Will backup the file then patch it
Will backup the file then patch it
[ "Will", "backup", "the", "file", "then", "patch", "it" ]
def _patch_file(path, content): """Will backup the file then patch it""" existing_content = open(path).read() if existing_content == content: # already patched log.warn('Already patched.') return False log.warn('Patching...') _rename_path(path) f = open(path, 'w') try: f.write(content) finally: f.close() return True
[ "def", "_patch_file", "(", "path", ",", "content", ")", ":", "existing_content", "=", "open", "(", "path", ")", ".", "read", "(", ")", "if", "existing_content", "==", "content", ":", "# already patched", "log", ".", "warn", "(", "'Already patched.'", ")", "return", "False", "log", ".", "warn", "(", "'Patching...'", ")", "_rename_path", "(", "path", ")", "f", "=", "open", "(", "path", ",", "'w'", ")", "try", ":", "f", ".", "write", "(", "content", ")", "finally", ":", "f", ".", "close", "(", ")", "return", "True" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/virtualenv/files/virtualenv_support/distribute_setup.py#L230-L244
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/matrixlib/defmatrix.py
python
asmatrix
(data, dtype=None)
return matrix(data, dtype=dtype, copy=False)
Interpret the input as a matrix. Unlike `matrix`, `asmatrix` does not make a copy if the input is already a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. Parameters ---------- data : array_like Input data. dtype : data-type Data-type of the output matrix. Returns ------- mat : matrix `data` interpreted as a matrix. Examples -------- >>> x = np.array([[1, 2], [3, 4]]) >>> m = np.asmatrix(x) >>> x[0,0] = 5 >>> m matrix([[5, 2], [3, 4]])
Interpret the input as a matrix.
[ "Interpret", "the", "input", "as", "a", "matrix", "." ]
def asmatrix(data, dtype=None): """ Interpret the input as a matrix. Unlike `matrix`, `asmatrix` does not make a copy if the input is already a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. Parameters ---------- data : array_like Input data. dtype : data-type Data-type of the output matrix. Returns ------- mat : matrix `data` interpreted as a matrix. Examples -------- >>> x = np.array([[1, 2], [3, 4]]) >>> m = np.asmatrix(x) >>> x[0,0] = 5 >>> m matrix([[5, 2], [3, 4]]) """ return matrix(data, dtype=dtype, copy=False)
[ "def", "asmatrix", "(", "data", ",", "dtype", "=", "None", ")", ":", "return", "matrix", "(", "data", ",", "dtype", "=", "dtype", ",", "copy", "=", "False", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/matrixlib/defmatrix.py#L39-L71
google/fhir
d77f57706c1a168529b0b87ca7ccb1c0113e83c2
py/google/fhir/stu3/json_format.py
python
print_fhir_to_json_string
(fhir_proto: message.Message)
return printer.print(fhir_proto)
Returns a FHIR JSON representation with no spaces or newlines. Args: fhir_proto: The proto to serialize into a JSON string. Returns: A FHIR JSON representation with no spaces or newlines.
Returns a FHIR JSON representation with no spaces or newlines.
[ "Returns", "a", "FHIR", "JSON", "representation", "with", "no", "spaces", "or", "newlines", "." ]
def print_fhir_to_json_string(fhir_proto: message.Message) -> str: """Returns a FHIR JSON representation with no spaces or newlines. Args: fhir_proto: The proto to serialize into a JSON string. Returns: A FHIR JSON representation with no spaces or newlines. """ printer = _json_printer.JsonPrinter.compact_printer(_PRIMITIVE_HANDLER) return printer.print(fhir_proto)
[ "def", "print_fhir_to_json_string", "(", "fhir_proto", ":", "message", ".", "Message", ")", "->", "str", ":", "printer", "=", "_json_printer", ".", "JsonPrinter", ".", "compact_printer", "(", "_PRIMITIVE_HANDLER", ")", "return", "printer", ".", "print", "(", "fhir_proto", ")" ]
https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/stu3/json_format.py#L113-L123
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/pkg_resources/_vendor/packaging/specifiers.py
python
BaseSpecifier.prereleases
(self, value: bool)
Sets whether or not pre-releases as a whole are allowed by this specifier.
Sets whether or not pre-releases as a whole are allowed by this specifier.
[ "Sets", "whether", "or", "not", "pre", "-", "releases", "as", "a", "whole", "are", "allowed", "by", "this", "specifier", "." ]
def prereleases(self, value: bool) -> None: """ Sets whether or not pre-releases as a whole are allowed by this specifier. """
[ "def", "prereleases", "(", "self", ",", "value", ":", "bool", ")", "->", "None", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/packaging/specifiers.py#L75-L79
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
PseudoDC.Clear
(*args, **kwargs)
return _gdi_.PseudoDC_Clear(*args, **kwargs)
Clear(self) Clears the device context using the current background brush.
Clear(self)
[ "Clear", "(", "self", ")" ]
def Clear(*args, **kwargs): """ Clear(self) Clears the device context using the current background brush. """ return _gdi_.PseudoDC_Clear(*args, **kwargs)
[ "def", "Clear", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_Clear", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L8208-L8214
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aquabutton.py
python
AquaButton.GetHoverColour
(self)
return self._hoverColour
Returns the button colour when the mouse is hovering on the button. :return: An instance of :class:`Colour`.
Returns the button colour when the mouse is hovering on the button.
[ "Returns", "the", "button", "colour", "when", "the", "mouse", "is", "hovering", "on", "the", "button", "." ]
def GetHoverColour(self): """ Returns the button colour when the mouse is hovering on the button. :return: An instance of :class:`Colour`. """ return self._hoverColour
[ "def", "GetHoverColour", "(", "self", ")", ":", "return", "self", ".", "_hoverColour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aquabutton.py#L711-L718
ufal/udpipe
e51f02d2744cdfd4a29efc1320644ea04d535f0b
doc/t2t_docsys/txt2tags.py
python
ConfigLines.get_raw_config
(self)
return ret
Scan buffer and extract all config as RAW (including includes)
Scan buffer and extract all config as RAW (including includes)
[ "Scan", "buffer", "and", "extract", "all", "config", "as", "RAW", "(", "including", "includes", ")" ]
def get_raw_config(self): "Scan buffer and extract all config as RAW (including includes)" ret = [] self.load_lines() first = self.first_line for i in range(len(self.lines)): line = self.lines[i] Message(_("Processing line %03d: %s")%(first+i,line),2) target, key, val = self.parse_line(line) if not key: continue # no config on this line if key == 'includeconf': err = _('A file cannot include itself (loop!)') if val == self.file: Error("%s: %%!includeconf: %s" % (err, self.file)) more_raw = self.include_config_file(val) ret.extend(more_raw) Message(_("Finished Config file inclusion: %s") % val, 2) else: ret.append([target, key, val]) Message(_("Added %s")%key,3) return ret
[ "def", "get_raw_config", "(", "self", ")", ":", "ret", "=", "[", "]", "self", ".", "load_lines", "(", ")", "first", "=", "self", ".", "first_line", "for", "i", "in", "range", "(", "len", "(", "self", ".", "lines", ")", ")", ":", "line", "=", "self", ".", "lines", "[", "i", "]", "Message", "(", "_", "(", "\"Processing line %03d: %s\"", ")", "%", "(", "first", "+", "i", ",", "line", ")", ",", "2", ")", "target", ",", "key", ",", "val", "=", "self", ".", "parse_line", "(", "line", ")", "if", "not", "key", ":", "continue", "# no config on this line", "if", "key", "==", "'includeconf'", ":", "err", "=", "_", "(", "'A file cannot include itself (loop!)'", ")", "if", "val", "==", "self", ".", "file", ":", "Error", "(", "\"%s: %%!includeconf: %s\"", "%", "(", "err", ",", "self", ".", "file", ")", ")", "more_raw", "=", "self", ".", "include_config_file", "(", "val", ")", "ret", ".", "extend", "(", "more_raw", ")", "Message", "(", "_", "(", "\"Finished Config file inclusion: %s\"", ")", "%", "val", ",", "2", ")", "else", ":", "ret", ".", "append", "(", "[", "target", ",", "key", ",", "val", "]", ")", "Message", "(", "_", "(", "\"Added %s\"", ")", "%", "key", ",", "3", ")", "return", "ret" ]
https://github.com/ufal/udpipe/blob/e51f02d2744cdfd4a29efc1320644ea04d535f0b/doc/t2t_docsys/txt2tags.py#L2970-L2990
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/filter/CommonFilters.py
python
CommonFilters.setGammaAdjust
(self, gamma)
return True
Applies additional gamma correction to the image. 1.0 = no correction.
Applies additional gamma correction to the image. 1.0 = no correction.
[ "Applies", "additional", "gamma", "correction", "to", "the", "image", ".", "1", ".", "0", "=", "no", "correction", "." ]
def setGammaAdjust(self, gamma): """ Applies additional gamma correction to the image. 1.0 = no correction. """ old_gamma = self.configuration.get("GammaAdjust", 1.0) if old_gamma != gamma: self.configuration["GammaAdjust"] = gamma return self.reconfigure(True, "GammaAdjust") return True
[ "def", "setGammaAdjust", "(", "self", ",", "gamma", ")", ":", "old_gamma", "=", "self", ".", "configuration", ".", "get", "(", "\"GammaAdjust\"", ",", "1.0", ")", "if", "old_gamma", "!=", "gamma", ":", "self", ".", "configuration", "[", "\"GammaAdjust\"", "]", "=", "gamma", "return", "self", ".", "reconfigure", "(", "True", ",", "\"GammaAdjust\"", ")", "return", "True" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/filter/CommonFilters.py#L589-L595
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py
python
TranslationUnit.get_includes
(self)
return iter(includes)
Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers.
Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers.
[ "Return", "an", "iterable", "sequence", "of", "FileInclusion", "objects", "that", "describe", "the", "sequence", "of", "inclusions", "in", "a", "translation", "unit", ".", "The", "first", "object", "in", "this", "sequence", "is", "always", "the", "input", "file", ".", "Note", "that", "this", "method", "will", "not", "recursively", "iterate", "over", "header", "files", "included", "through", "precompiled", "headers", "." ]
def get_includes(self): """ Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers. """ def visitor(fobj, lptr, depth, includes): if depth > 0: loc = lptr.contents includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) # Automatically adapt CIndex/ctype pointers to python objects includes = [] conf.lib.clang_getInclusions(self, callbacks['translation_unit_includes'](visitor), includes) return iter(includes)
[ "def", "get_includes", "(", "self", ")", ":", "def", "visitor", "(", "fobj", ",", "lptr", ",", "depth", ",", "includes", ")", ":", "if", "depth", ">", "0", ":", "loc", "=", "lptr", ".", "contents", "includes", ".", "append", "(", "FileInclusion", "(", "loc", ".", "file", ",", "File", "(", "fobj", ")", ",", "loc", ",", "depth", ")", ")", "# Automatically adapt CIndex/ctype pointers to python objects", "includes", "=", "[", "]", "conf", ".", "lib", ".", "clang_getInclusions", "(", "self", ",", "callbacks", "[", "'translation_unit_includes'", "]", "(", "visitor", ")", ",", "includes", ")", "return", "iter", "(", "includes", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L2611-L2629
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/bandit/data_containers.py
python
SampleArm.loss
(self)
return self._loss
Return the amount loss, always greater than or equal to zero.
Return the amount loss, always greater than or equal to zero.
[ "Return", "the", "amount", "loss", "always", "greater", "than", "or", "equal", "to", "zero", "." ]
def loss(self): """Return the amount loss, always greater than or equal to zero.""" return self._loss
[ "def", "loss", "(", "self", ")", ":", "return", "self", ".", "_loss" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/bandit/data_containers.py#L110-L112
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/utils.py
python
failure
(s)
return msg
Formats a fail message for printing. If on a posix system the message will be in color.
Formats a fail message for printing. If on a posix system the message will be in color.
[ "Formats", "a", "fail", "message", "for", "printing", ".", "If", "on", "a", "posix", "system", "the", "message", "will", "be", "in", "color", "." ]
def failure(s): """Formats a fail message for printing. If on a posix system the message will be in color. """ head = "\033[1;31m" if USE_COLOR else "*** FAILURE ***: " tail = "\033[0m" if USE_COLOR else "" msg = head + s + tail return msg
[ "def", "failure", "(", "s", ")", ":", "head", "=", "\"\\033[1;31m\"", "if", "USE_COLOR", "else", "\"*** FAILURE ***: \"", "tail", "=", "\"\\033[0m\"", "if", "USE_COLOR", "else", "\"\"", "msg", "=", "head", "+", "s", "+", "tail", "return", "msg" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/utils.py#L167-L175
ros-planning/moveit2
dd240ef6fd8b9932a7a53964140f2952786187a9
moveit_configs_utils/moveit_configs_utils/moveit_configs_builder.py
python
MoveItConfigsBuilder.robot_description
(self, file_path: Optional[str] = None, mappings: dict = None)
return self
Load robot description. :param file_path: Absolute or relative path to the URDF file (w.r.t. robot_name_moveit_config). :param mappings: mappings to be passed when loading the xacro file. :return: Instance of MoveItConfigsBuilder with robot_description loaded.
Load robot description.
[ "Load", "robot", "description", "." ]
def robot_description(self, file_path: Optional[str] = None, mappings: dict = None): """Load robot description. :param file_path: Absolute or relative path to the URDF file (w.r.t. robot_name_moveit_config). :param mappings: mappings to be passed when loading the xacro file. :return: Instance of MoveItConfigsBuilder with robot_description loaded. """ if file_path is None: robot_description_file_path = self.__urdf_package / self.__urdf_file_path else: robot_description_file_path = self._package_path / file_path self.__moveit_configs.robot_description = { self.__robot_description: load_xacro( robot_description_file_path, mappings=mappings ) } return self
[ "def", "robot_description", "(", "self", ",", "file_path", ":", "Optional", "[", "str", "]", "=", "None", ",", "mappings", ":", "dict", "=", "None", ")", ":", "if", "file_path", "is", "None", ":", "robot_description_file_path", "=", "self", ".", "__urdf_package", "/", "self", ".", "__urdf_file_path", "else", ":", "robot_description_file_path", "=", "self", ".", "_package_path", "/", "file_path", "self", ".", "__moveit_configs", ".", "robot_description", "=", "{", "self", ".", "__robot_description", ":", "load_xacro", "(", "robot_description_file_path", ",", "mappings", "=", "mappings", ")", "}", "return", "self" ]
https://github.com/ros-planning/moveit2/blob/dd240ef6fd8b9932a7a53964140f2952786187a9/moveit_configs_utils/moveit_configs_utils/moveit_configs_builder.py#L243-L259
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/machinelearning/layer1.py
python
MachineLearningConnection.get_evaluation
(self, evaluation_id)
return self.make_request(action='GetEvaluation', body=json.dumps(params))
Returns an `Evaluation` that includes metadata as well as the current status of the `Evaluation`. :type evaluation_id: string :param evaluation_id: The ID of the `Evaluation` to retrieve. The evaluation of each `MLModel` is recorded and cataloged. The ID provides the means to access the information.
Returns an `Evaluation` that includes metadata as well as the current status of the `Evaluation`.
[ "Returns", "an", "Evaluation", "that", "includes", "metadata", "as", "well", "as", "the", "current", "status", "of", "the", "Evaluation", "." ]
def get_evaluation(self, evaluation_id): """ Returns an `Evaluation` that includes metadata as well as the current status of the `Evaluation`. :type evaluation_id: string :param evaluation_id: The ID of the `Evaluation` to retrieve. The evaluation of each `MLModel` is recorded and cataloged. The ID provides the means to access the information. """ params = {'EvaluationId': evaluation_id, } return self.make_request(action='GetEvaluation', body=json.dumps(params))
[ "def", "get_evaluation", "(", "self", ",", "evaluation_id", ")", ":", "params", "=", "{", "'EvaluationId'", ":", "evaluation_id", ",", "}", "return", "self", ".", "make_request", "(", "action", "=", "'GetEvaluation'", ",", "body", "=", "json", ".", "dumps", "(", "params", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/machinelearning/layer1.py#L1203-L1216
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
snapx/snapx/classes/digraph.py
python
DiGraph.clear_edges
(self)
Remove all edges from the graph without altering nodes. Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear_edges() >>> list(G.nodes) [0, 1, 2, 3] >>> list(G.edges) []
Remove all edges from the graph without altering nodes.
[ "Remove", "all", "edges", "from", "the", "graph", "without", "altering", "nodes", "." ]
def clear_edges(self): """Remove all edges from the graph without altering nodes. Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear_edges() >>> list(G.nodes) [0, 1, 2, 3] >>> list(G.edges) [] """ for predecessor_dict in self._pred.values(): predecessor_dict.clear() for successor_dict in self._succ.values(): successor_dict.clear()
[ "def", "clear_edges", "(", "self", ")", ":", "for", "predecessor_dict", "in", "self", ".", "_pred", ".", "values", "(", ")", ":", "predecessor_dict", ".", "clear", "(", ")", "for", "successor_dict", "in", "self", ".", "_succ", ".", "values", "(", ")", ":", "successor_dict", ".", "clear", "(", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/snapx/snapx/classes/digraph.py#L1047-L1063
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.GetCurLineRaw
(*args, **kwargs)
return _stc.StyledTextCtrl_GetCurLineRaw(*args, **kwargs)
GetCurLineRaw() -> (text, index) Retrieve the text of the line containing the caret, and also the index of the caret on the line. The returned value is a utf-8 encoded string in unicode builds of wxPython, or raw 8-bit text otherwise.
GetCurLineRaw() -> (text, index)
[ "GetCurLineRaw", "()", "-", ">", "(", "text", "index", ")" ]
def GetCurLineRaw(*args, **kwargs): """ GetCurLineRaw() -> (text, index) Retrieve the text of the line containing the caret, and also the index of the caret on the line. The returned value is a utf-8 encoded string in unicode builds of wxPython, or raw 8-bit text otherwise. """ return _stc.StyledTextCtrl_GetCurLineRaw(*args, **kwargs)
[ "def", "GetCurLineRaw", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetCurLineRaw", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L6710-L6718
microsoft/DirectXShaderCompiler
8348ff8d9e0287610ba05d3a828e10af981a1c05
utils/hct/hctdb.py
python
db_dxil.print_stats
(self)
Print some basic statistics on the instruction database.
Print some basic statistics on the instruction database.
[ "Print", "some", "basic", "statistics", "on", "the", "instruction", "database", "." ]
def print_stats(self): "Print some basic statistics on the instruction database." print ("Instruction count: %d" % len(self.instr)) print ("Max parameter count in instruction: %d" % max(len(i.ops) - 1 for i in self.instr)) print ("Parameter count: %d" % sum(len(i.ops) - 1 for i in self.instr))
[ "def", "print_stats", "(", "self", ")", ":", "print", "(", "\"Instruction count: %d\"", "%", "len", "(", "self", ".", "instr", ")", ")", "print", "(", "\"Max parameter count in instruction: %d\"", "%", "max", "(", "len", "(", "i", ".", "ops", ")", "-", "1", "for", "i", "in", "self", ".", "instr", ")", ")", "print", "(", "\"Parameter count: %d\"", "%", "sum", "(", "len", "(", "i", ".", "ops", ")", "-", "1", "for", "i", "in", "self", ".", "instr", ")", ")" ]
https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/utils/hct/hctdb.py#L2760-L2764
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSProject.py
python
Writer.AddFileConfig
(self, path, config, attrs=None, tools=None)
Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles().
Adds a configuration to a file.
[ "Adds", "a", "configuration", "to", "a", "file", "." ]
def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles(). """ # Find the file node with the right relative path parent = self.files_dict.get(path) if not parent: raise ValueError('AddFileConfig: file "%s" not in project.' % path) # Add the config to the file node spec = self._GetSpecForConfiguration('FileConfiguration', config, attrs, tools) parent.append(spec)
[ "def", "AddFileConfig", "(", "self", ",", "path", ",", "config", ",", "attrs", "=", "None", ",", "tools", "=", "None", ")", ":", "# Find the file node with the right relative path", "parent", "=", "self", ".", "files_dict", ".", "get", "(", "path", ")", "if", "not", "parent", ":", "raise", "ValueError", "(", "'AddFileConfig: file \"%s\" not in project.'", "%", "path", ")", "# Add the config to the file node", "spec", "=", "self", ".", "_GetSpecForConfiguration", "(", "'FileConfiguration'", ",", "config", ",", "attrs", ",", "tools", ")", "parent", ".", "append", "(", "spec", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSProject.py#L166-L186
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
src/lib/mixer/MultirotorMixer/mixer_multirotor.py
python
airmode_rp
(m_sp, P, u_min, u_max)
return (u, u_final)
Mix roll, pitch, yaw and thrust. Desaturation behavior: airmode for roll/pitch: thrust is increased/decreased as much as required to meet the demanded roll/pitch. Yaw is not allowed to increase the thrust, @see mix_yaw() for the exact behavior.
Mix roll, pitch, yaw and thrust.
[ "Mix", "roll", "pitch", "yaw", "and", "thrust", "." ]
def airmode_rp(m_sp, P, u_min, u_max): """ Mix roll, pitch, yaw and thrust. Desaturation behavior: airmode for roll/pitch: thrust is increased/decreased as much as required to meet the demanded roll/pitch. Yaw is not allowed to increase the thrust, @see mix_yaw() for the exact behavior. """ # Mix without yaw m_sp_no_yaw = m_sp.copy() m_sp_no_yaw[2, 0] = 0.0 u = P * m_sp_no_yaw # Use thrust to unsaturate the outputs if needed u_T = P[:, 3] u_prime = minimize_sat(u, u_min, u_max, u_T) # Mix yaw axis independently u_final = mix_yaw(m_sp, u_prime, P, u_min, u_max) return (u, u_final)
[ "def", "airmode_rp", "(", "m_sp", ",", "P", ",", "u_min", ",", "u_max", ")", ":", "# Mix without yaw", "m_sp_no_yaw", "=", "m_sp", ".", "copy", "(", ")", "m_sp_no_yaw", "[", "2", ",", "0", "]", "=", "0.0", "u", "=", "P", "*", "m_sp_no_yaw", "# Use thrust to unsaturate the outputs if needed", "u_T", "=", "P", "[", ":", ",", "3", "]", "u_prime", "=", "minimize_sat", "(", "u", ",", "u_min", ",", "u_max", ",", "u_T", ")", "# Mix yaw axis independently", "u_final", "=", "mix_yaw", "(", "m_sp", ",", "u_prime", ",", "P", ",", "u_min", ",", "u_max", ")", "return", "(", "u", ",", "u_final", ")" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/src/lib/mixer/MultirotorMixer/mixer_multirotor.py#L101-L121
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStrV.Last
(self, *args)
return _snap.TStrV_Last(self, *args)
Last(TStrV self) -> TStr Last(TStrV self) -> TStr Parameters: self: TVec< TStr,int > *
Last(TStrV self) -> TStr Last(TStrV self) -> TStr
[ "Last", "(", "TStrV", "self", ")", "-", ">", "TStr", "Last", "(", "TStrV", "self", ")", "-", ">", "TStr" ]
def Last(self, *args): """ Last(TStrV self) -> TStr Last(TStrV self) -> TStr Parameters: self: TVec< TStr,int > * """ return _snap.TStrV_Last(self, *args)
[ "def", "Last", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TStrV_Last", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19385-L19394
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
BuildTools/SCons/Tools/InstallWithSymLinks.py
python
scons_copytree
(src, dst, symlinks=False)
Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an CopytreeError is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool.
Recursively copy a directory tree using copy2().
[ "Recursively", "copy", "a", "directory", "tree", "using", "copy2", "()", "." ]
def scons_copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an CopytreeError is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) # garyo@genarts.com fix: check for dir before making dirs. if not os.path.exists(dst): os.makedirs(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): scons_copytree(srcname, dstname, symlinks) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) # catch the CopytreeError from the recursive copytree so that we can # continue with other files except CopytreeError as err: errors.extend(err.args[0]) try: shutil.copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass except OSError as why: errors.extend((src, dst, str(why))) if errors: raise CopytreeError(errors)
[ "def", "scons_copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ")", ":", "names", "=", "os", ".", "listdir", "(", "src", ")", "# garyo@genarts.com fix: check for dir before making dirs.", "if", "not", "os", ".", "path", ".", "exists", "(", "dst", ")", ":", "os", ".", "makedirs", "(", "dst", ")", "errors", "=", "[", "]", "for", "name", "in", "names", ":", "srcname", "=", "os", ".", "path", ".", "join", "(", "src", ",", "name", ")", "dstname", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "name", ")", "try", ":", "if", "symlinks", "and", "os", ".", "path", ".", "islink", "(", "srcname", ")", ":", "linkto", "=", "os", ".", "readlink", "(", "srcname", ")", "os", ".", "symlink", "(", "linkto", ",", "dstname", ")", "elif", "os", ".", "path", ".", "isdir", "(", "srcname", ")", ":", "scons_copytree", "(", "srcname", ",", "dstname", ",", "symlinks", ")", "else", ":", "shutil", ".", "copy2", "(", "srcname", ",", "dstname", ")", "# XXX What about devices, sockets etc.?", "except", "(", "IOError", ",", "os", ".", "error", ")", "as", "why", ":", "errors", ".", "append", "(", "(", "srcname", ",", "dstname", ",", "str", "(", "why", ")", ")", ")", "# catch the CopytreeError from the recursive copytree so that we can", "# continue with other files", "except", "CopytreeError", "as", "err", ":", "errors", ".", "extend", "(", "err", ".", "args", "[", "0", "]", ")", "try", ":", "shutil", ".", "copystat", "(", "src", ",", "dst", ")", "except", "WindowsError", ":", "# can't copy file access times on Windows", "pass", "except", "OSError", "as", "why", ":", "errors", ".", "extend", "(", "(", "src", ",", "dst", ",", "str", "(", "why", ")", ")", ")", "if", "errors", ":", "raise", "CopytreeError", "(", "errors", ")" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/BuildTools/SCons/Tools/InstallWithSymLinks.py#L46-L91
huzheng001/stardict-3
96b96d89eab5f0ad9246c2569a807d6d7982aa84
tools/src/lingea-trd-decoder.py
python
decode
(stream)
return decode_tag_postprocessing(result)
Decode byte stream of one record, return decoded string with formatting in utf
Decode byte stream of one record, return decoded string with formatting in utf
[ "Decode", "byte", "stream", "of", "one", "record", "return", "decoded", "string", "with", "formatting", "in", "utf" ]
def decode(stream): """Decode byte stream of one record, return decoded string with formatting in utf""" result = "" global bs, pos # stream - data byte stream for one record bs = unpack("<%sB" % len(stream), stream) # bs - list of bytes from stream pos = 0 itemCount = outInt("ItemCount: %s") # Number of blocks in the record mainFlag = outInt("MainFlag: %s") # HEADER BLOCK # ------------ if mainFlag & 0x01: headerFlag = outInt("HeaderFlag: %s") # Blocks in header if headerFlag & 0x01: result += tag['rn'][0] + outStr("Header record name: %s").replace('_','') + tag['rn'][1] # Remove character '_' from index if headerFlag & 0x02: result += tag['va'][0] + outStr("Header variant: %s") + tag['va'][1] if headerFlag & 0x04: s = outInt("Header wordclass: %s") if s < 32: result += tag['wc'][0] + wordclass[s] + tag['wc'][1] else: raise "Header wordclass out of range in: %s" % result if headerFlag & 0x08: result += tag['pa'][0] + outStr("Header parts: %s") + tag['pa'][1] if headerFlag & 0x10: result += tag['fo'][0] + outStr("Header forms: %s") + tag['fo'][1] if headerFlag & 0x20: result += tag['on'][0] + outStr("Header origin note: %s") + tag['on'][1] if headerFlag & 0x80: result += tag['pr'][0] + pronunciation_encode(outStr("Header pronunciation: %s")) + tag['pr'][1] # Header data block if mainFlag & 0x02: headerFlag = outInt("Header dataFlag: %s") # Blocks in header if headerFlag & 0x02: result += tag['dv'][0] + outStr("Header dataVariant: %s")+ tag['dv'][1] # ??? Link elsewhere pass # SOUND DATA REFERENCE if mainFlag & 0x80: outInt("Sound reference byte #1: %s") outInt("Sound reference byte #2: %s") outInt("Sound reference byte #3: %s") outInt("Sound reference byte #4: %s") outInt("Sound reference byte #5: %s") #out("Sound data reference (5 bytes)", 6) # TODO: Test all mainFlags in header!!!! #result += ': ' li = 0 #print just every first word class identifier # TODO: this is not systematic (should be handled by output) global lastWordClass lastWordClass = 0 # DATA BLOCK(S) # ------------- for i in range(0, itemCount): item = tag['db'][0] + tag['db'][1] ol = False dataFlag = outInt("DataFlag: %s -----------------------------") if dataFlag & 0x01: # small index sampleFlag = outInt("Data sampleFlag: %s") if sampleFlag & 0x01: result += tag['sa'][0] + outStr("Data sample: %s") + tag['sa'][1] if sampleFlag & 0x04: s = outInt("Data wordclass: %s") if s != lastWordClass: if s < 32: result += tag['wc'][0] + wordclass[s] + tag['wc'][1] else: raise "Header wordclass out of range in: %s" % result lastWordClass = s if sampleFlag & 0x08: result += tag['sw'][0] + outStr("Data sample wordclass: %s") + tag['sw'][1] if sampleFlag & 0x10: outInt("Data sample Int: %s") outInt("Data sample Int: %s") outInt("Data sample Int: %s") if sampleFlag & 0x20: item += tag['do'][0] + outStr("Data origin note: %s") + tag['do'][1] if sampleFlag & 0x80: item += " " result += tag['pr'][0] + pronunciation_encode(outStr("Data sample pronunciation: %s")) + tag['pr'][1] if dataFlag & 0x02: item += " " subFlag = outInt("Data subFlag: %s") if subFlag == 0x80: outStr("Data sub prefix: %s") # It seams that data sub prefix content is ignored and there is a generated number for the whole block instead. li += 1 ol = True if dataFlag & 0x04: # chart pass # ??? if dataFlag & 0x08: # reference item += tag['df'][0] + outStr("Data definition: %s") + tag['df'][1] if dataFlag & 0x10: pass # ??? if dataFlag & 0x20: # phrase phraseFlag1 = outInt("Data phraseFlag1: %s") if phraseFlag1 & 0x01: item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1] if phraseFlag1 & 0x02: phraseCount = outInt("Data phraseCount: %s") for i in range(0, phraseCount): phraseComment = outInt("Data phrase prefix") if phraseComment & 0x04: item += tag['pc'][0] + outStr("Data phrase comment: %s") + tag['pc'][1] item += tag['p1'][0] + outStr("Data phrase 1: %s") + tag['p1'][1] item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1] if phraseFlag1 & 0x04: phraseCount = outInt("Data phraseCount: %s") for i in range(0, phraseCount): phraseComment = outInt("Data phrase prefix") if phraseComment & 0x04: item += tag['pc'][0] + outStr("Data phrase 1: %s") + tag['pc'][1] item += tag['pg'][0] + outStr("Data phrase comment: %s") + tag['pg'][1] item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1] if phraseFlag1 & 0x08: phraseCount = outInt("Data simple phraseCount: %s") for i in range(0, phraseCount): item += " " item += tag['sp'][0] + outStr("Data simple phrase: %s") + tag['sp'][1] if phraseFlag1 & 0x40: item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1] # TODO: be careful in changing the rules, to have back compatibility! if dataFlag & 0x40: # reference, related language #0x01 synonym ? #0x02 antonym ? pass if dataFlag & 0x80: # Phrase block flags = [ out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s"), out("Data phrase block: %s")] if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x0B,0x01]: result += "\\nphr: " li = 1 ol = True item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1] out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1] if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x23,0x01]: result += "\\nphr: " li = 1 ol = True item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1] out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") out("Data phrase block: %s") item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1] if ol: result += "\\n%d. %s" % (li, item) else: result += item ok = True while pos < len(stream): ok = (out() == 0x00) and ok if ok: result += '\n' return decode_tag_postprocessing(result)
[ "def", "decode", "(", "stream", ")", ":", "result", "=", "\"\"", "global", "bs", ",", "pos", "# stream - data byte stream for one record", "bs", "=", "unpack", "(", "\"<%sB\"", "%", "len", "(", "stream", ")", ",", "stream", ")", "# bs - list of bytes from stream", "pos", "=", "0", "itemCount", "=", "outInt", "(", "\"ItemCount: %s\"", ")", "# Number of blocks in the record", "mainFlag", "=", "outInt", "(", "\"MainFlag: %s\"", ")", "# HEADER BLOCK", "# ------------", "if", "mainFlag", "&", "0x01", ":", "headerFlag", "=", "outInt", "(", "\"HeaderFlag: %s\"", ")", "# Blocks in header", "if", "headerFlag", "&", "0x01", ":", "result", "+=", "tag", "[", "'rn'", "]", "[", "0", "]", "+", "outStr", "(", "\"Header record name: %s\"", ")", ".", "replace", "(", "'_'", ",", "''", ")", "+", "tag", "[", "'rn'", "]", "[", "1", "]", "# Remove character '_' from index", "if", "headerFlag", "&", "0x02", ":", "result", "+=", "tag", "[", "'va'", "]", "[", "0", "]", "+", "outStr", "(", "\"Header variant: %s\"", ")", "+", "tag", "[", "'va'", "]", "[", "1", "]", "if", "headerFlag", "&", "0x04", ":", "s", "=", "outInt", "(", "\"Header wordclass: %s\"", ")", "if", "s", "<", "32", ":", "result", "+=", "tag", "[", "'wc'", "]", "[", "0", "]", "+", "wordclass", "[", "s", "]", "+", "tag", "[", "'wc'", "]", "[", "1", "]", "else", ":", "raise", "\"Header wordclass out of range in: %s\"", "%", "result", "if", "headerFlag", "&", "0x08", ":", "result", "+=", "tag", "[", "'pa'", "]", "[", "0", "]", "+", "outStr", "(", "\"Header parts: %s\"", ")", "+", "tag", "[", "'pa'", "]", "[", "1", "]", "if", "headerFlag", "&", "0x10", ":", "result", "+=", "tag", "[", "'fo'", "]", "[", "0", "]", "+", "outStr", "(", "\"Header forms: %s\"", ")", "+", "tag", "[", "'fo'", "]", "[", "1", "]", "if", "headerFlag", "&", "0x20", ":", "result", "+=", "tag", "[", "'on'", "]", "[", "0", "]", "+", "outStr", "(", "\"Header origin note: %s\"", ")", "+", "tag", "[", "'on'", "]", "[", "1", "]", "if", "headerFlag", "&", "0x80", ":", "result", "+=", "tag", "[", "'pr'", "]", "[", "0", "]", "+", "pronunciation_encode", "(", "outStr", "(", "\"Header pronunciation: %s\"", ")", ")", "+", "tag", "[", "'pr'", "]", "[", "1", "]", "# Header data block", "if", "mainFlag", "&", "0x02", ":", "headerFlag", "=", "outInt", "(", "\"Header dataFlag: %s\"", ")", "# Blocks in header", "if", "headerFlag", "&", "0x02", ":", "result", "+=", "tag", "[", "'dv'", "]", "[", "0", "]", "+", "outStr", "(", "\"Header dataVariant: %s\"", ")", "+", "tag", "[", "'dv'", "]", "[", "1", "]", "# ??? Link elsewhere", "pass", "# SOUND DATA REFERENCE", "if", "mainFlag", "&", "0x80", ":", "outInt", "(", "\"Sound reference byte #1: %s\"", ")", "outInt", "(", "\"Sound reference byte #2: %s\"", ")", "outInt", "(", "\"Sound reference byte #3: %s\"", ")", "outInt", "(", "\"Sound reference byte #4: %s\"", ")", "outInt", "(", "\"Sound reference byte #5: %s\"", ")", "#out(\"Sound data reference (5 bytes)\", 6)", "# TODO: Test all mainFlags in header!!!!", "#result += ': '", "li", "=", "0", "#print just every first word class identifier", "# TODO: this is not systematic (should be handled by output)", "global", "lastWordClass", "lastWordClass", "=", "0", "# DATA BLOCK(S)", "# -------------", "for", "i", "in", "range", "(", "0", ",", "itemCount", ")", ":", "item", "=", "tag", "[", "'db'", "]", "[", "0", "]", "+", "tag", "[", "'db'", "]", "[", "1", "]", "ol", "=", "False", "dataFlag", "=", "outInt", "(", "\"DataFlag: %s -----------------------------\"", ")", "if", "dataFlag", "&", "0x01", ":", "# small index", "sampleFlag", "=", "outInt", "(", "\"Data sampleFlag: %s\"", ")", "if", "sampleFlag", "&", "0x01", ":", "result", "+=", "tag", "[", "'sa'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data sample: %s\"", ")", "+", "tag", "[", "'sa'", "]", "[", "1", "]", "if", "sampleFlag", "&", "0x04", ":", "s", "=", "outInt", "(", "\"Data wordclass: %s\"", ")", "if", "s", "!=", "lastWordClass", ":", "if", "s", "<", "32", ":", "result", "+=", "tag", "[", "'wc'", "]", "[", "0", "]", "+", "wordclass", "[", "s", "]", "+", "tag", "[", "'wc'", "]", "[", "1", "]", "else", ":", "raise", "\"Header wordclass out of range in: %s\"", "%", "result", "lastWordClass", "=", "s", "if", "sampleFlag", "&", "0x08", ":", "result", "+=", "tag", "[", "'sw'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data sample wordclass: %s\"", ")", "+", "tag", "[", "'sw'", "]", "[", "1", "]", "if", "sampleFlag", "&", "0x10", ":", "outInt", "(", "\"Data sample Int: %s\"", ")", "outInt", "(", "\"Data sample Int: %s\"", ")", "outInt", "(", "\"Data sample Int: %s\"", ")", "if", "sampleFlag", "&", "0x20", ":", "item", "+=", "tag", "[", "'do'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data origin note: %s\"", ")", "+", "tag", "[", "'do'", "]", "[", "1", "]", "if", "sampleFlag", "&", "0x80", ":", "item", "+=", "\" \"", "result", "+=", "tag", "[", "'pr'", "]", "[", "0", "]", "+", "pronunciation_encode", "(", "outStr", "(", "\"Data sample pronunciation: %s\"", ")", ")", "+", "tag", "[", "'pr'", "]", "[", "1", "]", "if", "dataFlag", "&", "0x02", ":", "item", "+=", "\" \"", "subFlag", "=", "outInt", "(", "\"Data subFlag: %s\"", ")", "if", "subFlag", "==", "0x80", ":", "outStr", "(", "\"Data sub prefix: %s\"", ")", "# It seams that data sub prefix content is ignored and there is a generated number for the whole block instead.", "li", "+=", "1", "ol", "=", "True", "if", "dataFlag", "&", "0x04", ":", "# chart", "pass", "# ???", "if", "dataFlag", "&", "0x08", ":", "# reference", "item", "+=", "tag", "[", "'df'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data definition: %s\"", ")", "+", "tag", "[", "'df'", "]", "[", "1", "]", "if", "dataFlag", "&", "0x10", ":", "pass", "# ???", "if", "dataFlag", "&", "0x20", ":", "# phrase", "phraseFlag1", "=", "outInt", "(", "\"Data phraseFlag1: %s\"", ")", "if", "phraseFlag1", "&", "0x01", ":", "item", "+=", "tag", "[", "'ps'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase short form: %s\"", ")", "+", "tag", "[", "'ps'", "]", "[", "1", "]", "if", "phraseFlag1", "&", "0x02", ":", "phraseCount", "=", "outInt", "(", "\"Data phraseCount: %s\"", ")", "for", "i", "in", "range", "(", "0", ",", "phraseCount", ")", ":", "phraseComment", "=", "outInt", "(", "\"Data phrase prefix\"", ")", "if", "phraseComment", "&", "0x04", ":", "item", "+=", "tag", "[", "'pc'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase comment: %s\"", ")", "+", "tag", "[", "'pc'", "]", "[", "1", "]", "item", "+=", "tag", "[", "'p1'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 1: %s\"", ")", "+", "tag", "[", "'p1'", "]", "[", "1", "]", "item", "+=", "tag", "[", "'p2'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 2: %s\"", ")", "+", "tag", "[", "'p2'", "]", "[", "1", "]", "if", "phraseFlag1", "&", "0x04", ":", "phraseCount", "=", "outInt", "(", "\"Data phraseCount: %s\"", ")", "for", "i", "in", "range", "(", "0", ",", "phraseCount", ")", ":", "phraseComment", "=", "outInt", "(", "\"Data phrase prefix\"", ")", "if", "phraseComment", "&", "0x04", ":", "item", "+=", "tag", "[", "'pc'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 1: %s\"", ")", "+", "tag", "[", "'pc'", "]", "[", "1", "]", "item", "+=", "tag", "[", "'pg'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase comment: %s\"", ")", "+", "tag", "[", "'pg'", "]", "[", "1", "]", "item", "+=", "tag", "[", "'p2'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 2: %s\"", ")", "+", "tag", "[", "'p2'", "]", "[", "1", "]", "if", "phraseFlag1", "&", "0x08", ":", "phraseCount", "=", "outInt", "(", "\"Data simple phraseCount: %s\"", ")", "for", "i", "in", "range", "(", "0", ",", "phraseCount", ")", ":", "item", "+=", "\" \"", "item", "+=", "tag", "[", "'sp'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data simple phrase: %s\"", ")", "+", "tag", "[", "'sp'", "]", "[", "1", "]", "if", "phraseFlag1", "&", "0x40", ":", "item", "+=", "tag", "[", "'ps'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase short form: %s\"", ")", "+", "tag", "[", "'ps'", "]", "[", "1", "]", "# TODO: be careful in changing the rules, to have back compatibility! ", "if", "dataFlag", "&", "0x40", ":", "# reference, related language", "#0x01 synonym ?", "#0x02 antonym ?", "pass", "if", "dataFlag", "&", "0x80", ":", "# Phrase block", "flags", "=", "[", "out", "(", "\"Data phrase block: %s\"", ")", ",", "out", "(", "\"Data phrase block: %s\"", ")", ",", "out", "(", "\"Data phrase block: %s\"", ")", ",", "out", "(", "\"Data phrase block: %s\"", ")", ",", "out", "(", "\"Data phrase block: %s\"", ")", ",", "out", "(", "\"Data phrase block: %s\"", ")", ",", "out", "(", "\"Data phrase block: %s\"", ")", ",", "out", "(", "\"Data phrase block: %s\"", ")", "]", "if", "flags", "==", "[", "0x80", ",", "0x80", ",", "0xF9", ",", "0xDF", ",", "0x9D", ",", "0x00", ",", "0x0B", ",", "0x01", "]", ":", "result", "+=", "\"\\\\nphr: \"", "li", "=", "1", "ol", "=", "True", "item", "+=", "tag", "[", "'b1'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 1: %s\"", ")", "+", "tag", "[", "'b1'", "]", "[", "1", "]", "out", "(", "\"Data phrase block: %s\"", ")", "out", "(", "\"Data phrase block: %s\"", ")", "out", "(", "\"Data phrase block: %s\"", ")", "out", "(", "\"Data phrase block: %s\"", ")", "item", "+=", "tag", "[", "'ds'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 2: %s\"", ")", "+", "tag", "[", "'ds'", "]", "[", "1", "]", "if", "flags", "==", "[", "0x80", ",", "0x80", ",", "0xF9", ",", "0xDF", ",", "0x9D", ",", "0x00", ",", "0x23", ",", "0x01", "]", ":", "result", "+=", "\"\\\\nphr: \"", "li", "=", "1", "ol", "=", "True", "item", "+=", "tag", "[", "'b1'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 1: %s\"", ")", "+", "tag", "[", "'b1'", "]", "[", "1", "]", "out", "(", "\"Data phrase block: %s\"", ")", "out", "(", "\"Data phrase block: %s\"", ")", "out", "(", "\"Data phrase block: %s\"", ")", "out", "(", "\"Data phrase block: %s\"", ")", "out", "(", "\"Data phrase block: %s\"", ")", "item", "+=", "tag", "[", "'ds'", "]", "[", "0", "]", "+", "outStr", "(", "\"Data phrase 2: %s\"", ")", "+", "tag", "[", "'ds'", "]", "[", "1", "]", "if", "ol", ":", "result", "+=", "\"\\\\n%d. %s\"", "%", "(", "li", ",", "item", ")", "else", ":", "result", "+=", "item", "ok", "=", "True", "while", "pos", "<", "len", "(", "stream", ")", ":", "ok", "=", "(", "out", "(", ")", "==", "0x00", ")", "and", "ok", "if", "ok", ":", "result", "+=", "'\\n'", "return", "decode_tag_postprocessing", "(", "result", ")" ]
https://github.com/huzheng001/stardict-3/blob/96b96d89eab5f0ad9246c2569a807d6d7982aa84/tools/src/lingea-trd-decoder.py#L442-L625
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/base_widget.py
python
process_file_parameter
(f)
return processed_function
Decorator that allows a function parameter to either be a string or a function returning a string
Decorator that allows a function parameter to either be a string or a function returning a string
[ "Decorator", "that", "allows", "a", "function", "parameter", "to", "either", "be", "a", "string", "or", "a", "function", "returning", "a", "string" ]
def process_file_parameter(f): """ Decorator that allows a function parameter to either be a string or a function returning a string """ def processed_function(self, file_name=None, **kwargs): if file_name is None: return f(self, **kwargs) if isinstance(file_name, types.StringType): return f(self, file_name, **kwargs) else: return f(self, str(file_name()), **kwargs) return processed_function
[ "def", "process_file_parameter", "(", "f", ")", ":", "def", "processed_function", "(", "self", ",", "file_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "file_name", "is", "None", ":", "return", "f", "(", "self", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "file_name", ",", "types", ".", "StringType", ")", ":", "return", "f", "(", "self", ",", "file_name", ",", "*", "*", "kwargs", ")", "else", ":", "return", "f", "(", "self", ",", "str", "(", "file_name", "(", ")", ")", ",", "*", "*", "kwargs", ")", "return", "processed_function" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/base_widget.py#L24-L37
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/configure.d/nodedownload.py
python
formatSize
(amt)
return fpformat.fix(amt / 1024000., 1)
Format a size as a string in MB
Format a size as a string in MB
[ "Format", "a", "size", "as", "a", "string", "in", "MB" ]
def formatSize(amt): """Format a size as a string in MB""" return fpformat.fix(amt / 1024000., 1)
[ "def", "formatSize", "(", "amt", ")", ":", "return", "fpformat", ".", "fix", "(", "amt", "/", "1024000.", ",", "1", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/configure.d/nodedownload.py#L12-L14
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/diagnostic_updater/_diagnostic_updater.py
python
Updater.broadcast
(self, lvl, msg)
Outputs a message on all the known DiagnosticStatus. Useful if something drastic is happening such as shutdown or a self-test. @param lvl Level of the diagnostic being output. @param msg Status message to output.
Outputs a message on all the known DiagnosticStatus.
[ "Outputs", "a", "message", "on", "all", "the", "known", "DiagnosticStatus", "." ]
def broadcast(self, lvl, msg): """Outputs a message on all the known DiagnosticStatus. Useful if something drastic is happening such as shutdown or a self-test. @param lvl Level of the diagnostic being output. @param msg Status message to output. """ status_vec = [] for task in self.tasks: status = DiagnosticStatusWrapper() status.name = task.name status.summary(lvl, msg) status_vec.append(status) self.publish(status_vec)
[ "def", "broadcast", "(", "self", ",", "lvl", ",", "msg", ")", ":", "status_vec", "=", "[", "]", "for", "task", "in", "self", ".", "tasks", ":", "status", "=", "DiagnosticStatusWrapper", "(", ")", "status", ".", "name", "=", "task", ".", "name", "status", ".", "summary", "(", "lvl", ",", "msg", ")", "status_vec", ".", "append", "(", "status", ")", "self", ".", "publish", "(", "status_vec", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/diagnostic_updater/_diagnostic_updater.py#L286-L303
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Alignment/MillePedeAlignmentAlgorithm/scripts/mps_list_evts.py
python
print_merging_scheme
(merged_datasets)
Print number of events per merged dataset See comments to function `merge_datasets' for an explanation of what is meant by merged dataset.
Print number of events per merged dataset
[ "Print", "number", "of", "events", "per", "merged", "dataset" ]
def print_merging_scheme(merged_datasets): """ Print number of events per merged dataset See comments to function `merge_datasets' for an explanation of what is meant by merged dataset. """ print("Defining the following merged datasets:") for merged_dataset,datasets in merged_datasets.items(): print("\n `"+merged_dataset+"' from:") for dataset in datasets: print(" `"+dataset+"'")
[ "def", "print_merging_scheme", "(", "merged_datasets", ")", ":", "print", "(", "\"Defining the following merged datasets:\"", ")", "for", "merged_dataset", ",", "datasets", "in", "merged_datasets", ".", "items", "(", ")", ":", "print", "(", "\"\\n `\"", "+", "merged_dataset", "+", "\"' from:\"", ")", "for", "dataset", "in", "datasets", ":", "print", "(", "\" `\"", "+", "dataset", "+", "\"'\"", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_list_evts.py#L101-L111
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/device.py
python
check_valid
(spec)
Check that a device spec is valid. Args: spec: a string. Raises: An exception if the spec is invalid.
Check that a device spec is valid.
[ "Check", "that", "a", "device", "spec", "is", "valid", "." ]
def check_valid(spec): """Check that a device spec is valid. Args: spec: a string. Raises: An exception if the spec is invalid. """ # Construct a DeviceSpec. It will assert a failure if spec is invalid. DeviceSpec.from_string(spec)
[ "def", "check_valid", "(", "spec", ")", ":", "# Construct a DeviceSpec. It will assert a failure if spec is invalid.", "DeviceSpec", ".", "from_string", "(", "spec", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/device.py#L27-L37
etodd/lasercrabs
91484d9ac3a47ac38b8f40ec3ff35194714dad8e
assets/script/etodd_blender_fbx/export_fbx_bin.py
python
fbx_animations_do
(scene_data, ref_id, f_start, f_end, start_zero, objects=None, force_keep=False)
return (astack_key, animations, alayer_key, name, f_start, f_end) if animations else None
Generate animation data (a single AnimStack) from objects, for a given frame range.
Generate animation data (a single AnimStack) from objects, for a given frame range.
[ "Generate", "animation", "data", "(", "a", "single", "AnimStack", ")", "from", "objects", "for", "a", "given", "frame", "range", "." ]
def fbx_animations_do(scene_data, ref_id, f_start, f_end, start_zero, objects=None, force_keep=False): """ Generate animation data (a single AnimStack) from objects, for a given frame range. """ bake_step = scene_data.settings.bake_anim_step simplify_fac = scene_data.settings.bake_anim_simplify_factor scene = scene_data.scene force_keying = scene_data.settings.bake_anim_use_all_bones force_sek = scene_data.settings.bake_anim_force_startend_keying if objects is not None: # Add bones and duplis! for ob_obj in tuple(objects): if not ob_obj.is_object: continue if ob_obj.type == 'ARMATURE': objects |= {bo_obj for bo_obj in ob_obj.bones if bo_obj in scene_data.objects} ob_obj.dupli_list_create(scene, 'RENDER') for dp_obj in ob_obj.dupli_list: if dp_obj in scene_data.objects: objects.add(dp_obj) ob_obj.dupli_list_clear() else: objects = scene_data.objects back_currframe = scene.frame_current animdata_ob = OrderedDict() p_rots = {} for ob_obj in objects: if ob_obj.parented_to_armature: continue ACNW = AnimationCurveNodeWrapper loc, rot, scale, _m, _mr = ob_obj.fbx_object_tx(scene_data, rest = True) rot_deg = tuple(convert_rad_to_deg_iter(rot)) force_key = (simplify_fac == 0.0) or (ob_obj.is_bone and force_keying) animdata_ob[ob_obj] = (ACNW(ob_obj.key, 'LCL_TRANSLATION', force_key, force_sek, loc), ACNW(ob_obj.key, 'LCL_ROTATION', force_key, force_sek, rot_deg), ACNW(ob_obj.key, 'LCL_SCALING', force_key, force_sek, scale)) p_rots[ob_obj] = rot force_key = (simplify_fac == 0.0) animdata_shapes = OrderedDict() for me, (me_key, _shapes_key, shapes) in scene_data.data_deformers_shape.items(): # Ignore absolute shape keys for now! if not me.shape_keys.use_relative: continue for shape, (channel_key, geom_key, _shape_verts_co, _shape_verts_idx) in shapes.items(): acnode = AnimationCurveNodeWrapper(channel_key, 'SHAPE_KEY', force_key, force_sek, (0.0,)) # Sooooo happy to have to twist again like a mad snake... Yes, we need to write those curves twice. :/ acnode.add_group(me_key, shape.name, shape.name, (shape.name,)) animdata_shapes[channel_key] = (acnode, me, shape) animdata_cameras = OrderedDict() for cam_obj, cam_key in scene_data.data_cameras.items(): cam = cam_obj.bdata.data acnode = AnimationCurveNodeWrapper(cam_key, 'CAMERA_FOCAL', force_key, force_sek, (cam.lens,)) animdata_cameras[cam_key] = (acnode, cam) currframe = f_start while currframe <= f_end: real_currframe = currframe - f_start if start_zero else currframe scene.frame_set(int(currframe), currframe - int(currframe)) for ob_obj in animdata_ob: ob_obj.dupli_list_create(scene, 'RENDER') for ob_obj, (anim_loc, anim_rot, anim_scale) in animdata_ob.items(): # We compute baked loc/rot/scale for all objects (rot being euler-compat with previous value!). p_rot = p_rots.get(ob_obj, None) loc, rot, scale, _m, _mr = ob_obj.fbx_object_tx(scene_data, rot_euler_compat=p_rot) p_rots[ob_obj] = rot anim_loc.add_keyframe(real_currframe, loc) anim_rot.add_keyframe(real_currframe, tuple(convert_rad_to_deg_iter(rot))) anim_scale.add_keyframe(real_currframe, scale) for ob_obj in objects: ob_obj.dupli_list_clear() for anim_shape, me, shape in animdata_shapes.values(): anim_shape.add_keyframe(real_currframe, (shape.value * 100.0,)) for anim_camera, camera in animdata_cameras.values(): anim_camera.add_keyframe(real_currframe, (camera.lens,)) currframe += bake_step scene.frame_set(back_currframe, 0.0) animations = OrderedDict() # And now, produce final data (usable by FBX export code) # Objects-like loc/rot/scale... for ob_obj, anims in animdata_ob.items(): for anim in anims: anim.simplify(simplify_fac, bake_step, force_keep) if not anim: continue for obj_key, group_key, group, fbx_group, fbx_gname in anim.get_final_data(scene, ref_id, force_keep): anim_data = animations.get(obj_key) if anim_data is None: anim_data = animations[obj_key] = ("dummy_unused_key", OrderedDict()) anim_data[1][fbx_group] = (group_key, group, fbx_gname) # And meshes' shape keys. for channel_key, (anim_shape, me, shape) in animdata_shapes.items(): final_keys = OrderedDict() anim_shape.simplify(simplify_fac, bake_step, force_keep) if not anim_shape: continue for elem_key, group_key, group, fbx_group, fbx_gname in anim_shape.get_final_data(scene, ref_id, force_keep): anim_data = animations.get(elem_key) if anim_data is None: anim_data = animations[elem_key] = ("dummy_unused_key", OrderedDict()) anim_data[1][fbx_group] = (group_key, group, fbx_gname) # And cameras' lens keys. for cam_key, (anim_camera, camera) in animdata_cameras.items(): final_keys = OrderedDict() anim_camera.simplify(simplify_fac, bake_step, force_keep) if not anim_camera: continue for elem_key, group_key, group, fbx_group, fbx_gname in anim_camera.get_final_data(scene, ref_id, force_keep): anim_data = animations.get(elem_key) if anim_data is None: anim_data = animations[elem_key] = ("dummy_unused_key", OrderedDict()) anim_data[1][fbx_group] = (group_key, group, fbx_gname) astack_key = get_blender_anim_stack_key(scene, ref_id) alayer_key = get_blender_anim_layer_key(scene, ref_id) name = (get_blenderID_name(ref_id) if ref_id else scene.name).encode() if start_zero: f_end -= f_start f_start = 0.0 return (astack_key, animations, alayer_key, name, f_start, f_end) if animations else None
[ "def", "fbx_animations_do", "(", "scene_data", ",", "ref_id", ",", "f_start", ",", "f_end", ",", "start_zero", ",", "objects", "=", "None", ",", "force_keep", "=", "False", ")", ":", "bake_step", "=", "scene_data", ".", "settings", ".", "bake_anim_step", "simplify_fac", "=", "scene_data", ".", "settings", ".", "bake_anim_simplify_factor", "scene", "=", "scene_data", ".", "scene", "force_keying", "=", "scene_data", ".", "settings", ".", "bake_anim_use_all_bones", "force_sek", "=", "scene_data", ".", "settings", ".", "bake_anim_force_startend_keying", "if", "objects", "is", "not", "None", ":", "# Add bones and duplis!", "for", "ob_obj", "in", "tuple", "(", "objects", ")", ":", "if", "not", "ob_obj", ".", "is_object", ":", "continue", "if", "ob_obj", ".", "type", "==", "'ARMATURE'", ":", "objects", "|=", "{", "bo_obj", "for", "bo_obj", "in", "ob_obj", ".", "bones", "if", "bo_obj", "in", "scene_data", ".", "objects", "}", "ob_obj", ".", "dupli_list_create", "(", "scene", ",", "'RENDER'", ")", "for", "dp_obj", "in", "ob_obj", ".", "dupli_list", ":", "if", "dp_obj", "in", "scene_data", ".", "objects", ":", "objects", ".", "add", "(", "dp_obj", ")", "ob_obj", ".", "dupli_list_clear", "(", ")", "else", ":", "objects", "=", "scene_data", ".", "objects", "back_currframe", "=", "scene", ".", "frame_current", "animdata_ob", "=", "OrderedDict", "(", ")", "p_rots", "=", "{", "}", "for", "ob_obj", "in", "objects", ":", "if", "ob_obj", ".", "parented_to_armature", ":", "continue", "ACNW", "=", "AnimationCurveNodeWrapper", "loc", ",", "rot", ",", "scale", ",", "_m", ",", "_mr", "=", "ob_obj", ".", "fbx_object_tx", "(", "scene_data", ",", "rest", "=", "True", ")", "rot_deg", "=", "tuple", "(", "convert_rad_to_deg_iter", "(", "rot", ")", ")", "force_key", "=", "(", "simplify_fac", "==", "0.0", ")", "or", "(", "ob_obj", ".", "is_bone", "and", "force_keying", ")", "animdata_ob", "[", "ob_obj", "]", "=", "(", "ACNW", "(", "ob_obj", ".", "key", ",", "'LCL_TRANSLATION'", ",", "force_key", ",", "force_sek", ",", "loc", ")", ",", "ACNW", "(", "ob_obj", ".", "key", ",", "'LCL_ROTATION'", ",", "force_key", ",", "force_sek", ",", "rot_deg", ")", ",", "ACNW", "(", "ob_obj", ".", "key", ",", "'LCL_SCALING'", ",", "force_key", ",", "force_sek", ",", "scale", ")", ")", "p_rots", "[", "ob_obj", "]", "=", "rot", "force_key", "=", "(", "simplify_fac", "==", "0.0", ")", "animdata_shapes", "=", "OrderedDict", "(", ")", "for", "me", ",", "(", "me_key", ",", "_shapes_key", ",", "shapes", ")", "in", "scene_data", ".", "data_deformers_shape", ".", "items", "(", ")", ":", "# Ignore absolute shape keys for now!", "if", "not", "me", ".", "shape_keys", ".", "use_relative", ":", "continue", "for", "shape", ",", "(", "channel_key", ",", "geom_key", ",", "_shape_verts_co", ",", "_shape_verts_idx", ")", "in", "shapes", ".", "items", "(", ")", ":", "acnode", "=", "AnimationCurveNodeWrapper", "(", "channel_key", ",", "'SHAPE_KEY'", ",", "force_key", ",", "force_sek", ",", "(", "0.0", ",", ")", ")", "# Sooooo happy to have to twist again like a mad snake... Yes, we need to write those curves twice. :/", "acnode", ".", "add_group", "(", "me_key", ",", "shape", ".", "name", ",", "shape", ".", "name", ",", "(", "shape", ".", "name", ",", ")", ")", "animdata_shapes", "[", "channel_key", "]", "=", "(", "acnode", ",", "me", ",", "shape", ")", "animdata_cameras", "=", "OrderedDict", "(", ")", "for", "cam_obj", ",", "cam_key", "in", "scene_data", ".", "data_cameras", ".", "items", "(", ")", ":", "cam", "=", "cam_obj", ".", "bdata", ".", "data", "acnode", "=", "AnimationCurveNodeWrapper", "(", "cam_key", ",", "'CAMERA_FOCAL'", ",", "force_key", ",", "force_sek", ",", "(", "cam", ".", "lens", ",", ")", ")", "animdata_cameras", "[", "cam_key", "]", "=", "(", "acnode", ",", "cam", ")", "currframe", "=", "f_start", "while", "currframe", "<=", "f_end", ":", "real_currframe", "=", "currframe", "-", "f_start", "if", "start_zero", "else", "currframe", "scene", ".", "frame_set", "(", "int", "(", "currframe", ")", ",", "currframe", "-", "int", "(", "currframe", ")", ")", "for", "ob_obj", "in", "animdata_ob", ":", "ob_obj", ".", "dupli_list_create", "(", "scene", ",", "'RENDER'", ")", "for", "ob_obj", ",", "(", "anim_loc", ",", "anim_rot", ",", "anim_scale", ")", "in", "animdata_ob", ".", "items", "(", ")", ":", "# We compute baked loc/rot/scale for all objects (rot being euler-compat with previous value!).", "p_rot", "=", "p_rots", ".", "get", "(", "ob_obj", ",", "None", ")", "loc", ",", "rot", ",", "scale", ",", "_m", ",", "_mr", "=", "ob_obj", ".", "fbx_object_tx", "(", "scene_data", ",", "rot_euler_compat", "=", "p_rot", ")", "p_rots", "[", "ob_obj", "]", "=", "rot", "anim_loc", ".", "add_keyframe", "(", "real_currframe", ",", "loc", ")", "anim_rot", ".", "add_keyframe", "(", "real_currframe", ",", "tuple", "(", "convert_rad_to_deg_iter", "(", "rot", ")", ")", ")", "anim_scale", ".", "add_keyframe", "(", "real_currframe", ",", "scale", ")", "for", "ob_obj", "in", "objects", ":", "ob_obj", ".", "dupli_list_clear", "(", ")", "for", "anim_shape", ",", "me", ",", "shape", "in", "animdata_shapes", ".", "values", "(", ")", ":", "anim_shape", ".", "add_keyframe", "(", "real_currframe", ",", "(", "shape", ".", "value", "*", "100.0", ",", ")", ")", "for", "anim_camera", ",", "camera", "in", "animdata_cameras", ".", "values", "(", ")", ":", "anim_camera", ".", "add_keyframe", "(", "real_currframe", ",", "(", "camera", ".", "lens", ",", ")", ")", "currframe", "+=", "bake_step", "scene", ".", "frame_set", "(", "back_currframe", ",", "0.0", ")", "animations", "=", "OrderedDict", "(", ")", "# And now, produce final data (usable by FBX export code)", "# Objects-like loc/rot/scale...", "for", "ob_obj", ",", "anims", "in", "animdata_ob", ".", "items", "(", ")", ":", "for", "anim", "in", "anims", ":", "anim", ".", "simplify", "(", "simplify_fac", ",", "bake_step", ",", "force_keep", ")", "if", "not", "anim", ":", "continue", "for", "obj_key", ",", "group_key", ",", "group", ",", "fbx_group", ",", "fbx_gname", "in", "anim", ".", "get_final_data", "(", "scene", ",", "ref_id", ",", "force_keep", ")", ":", "anim_data", "=", "animations", ".", "get", "(", "obj_key", ")", "if", "anim_data", "is", "None", ":", "anim_data", "=", "animations", "[", "obj_key", "]", "=", "(", "\"dummy_unused_key\"", ",", "OrderedDict", "(", ")", ")", "anim_data", "[", "1", "]", "[", "fbx_group", "]", "=", "(", "group_key", ",", "group", ",", "fbx_gname", ")", "# And meshes' shape keys.", "for", "channel_key", ",", "(", "anim_shape", ",", "me", ",", "shape", ")", "in", "animdata_shapes", ".", "items", "(", ")", ":", "final_keys", "=", "OrderedDict", "(", ")", "anim_shape", ".", "simplify", "(", "simplify_fac", ",", "bake_step", ",", "force_keep", ")", "if", "not", "anim_shape", ":", "continue", "for", "elem_key", ",", "group_key", ",", "group", ",", "fbx_group", ",", "fbx_gname", "in", "anim_shape", ".", "get_final_data", "(", "scene", ",", "ref_id", ",", "force_keep", ")", ":", "anim_data", "=", "animations", ".", "get", "(", "elem_key", ")", "if", "anim_data", "is", "None", ":", "anim_data", "=", "animations", "[", "elem_key", "]", "=", "(", "\"dummy_unused_key\"", ",", "OrderedDict", "(", ")", ")", "anim_data", "[", "1", "]", "[", "fbx_group", "]", "=", "(", "group_key", ",", "group", ",", "fbx_gname", ")", "# And cameras' lens keys.", "for", "cam_key", ",", "(", "anim_camera", ",", "camera", ")", "in", "animdata_cameras", ".", "items", "(", ")", ":", "final_keys", "=", "OrderedDict", "(", ")", "anim_camera", ".", "simplify", "(", "simplify_fac", ",", "bake_step", ",", "force_keep", ")", "if", "not", "anim_camera", ":", "continue", "for", "elem_key", ",", "group_key", ",", "group", ",", "fbx_group", ",", "fbx_gname", "in", "anim_camera", ".", "get_final_data", "(", "scene", ",", "ref_id", ",", "force_keep", ")", ":", "anim_data", "=", "animations", ".", "get", "(", "elem_key", ")", "if", "anim_data", "is", "None", ":", "anim_data", "=", "animations", "[", "elem_key", "]", "=", "(", "\"dummy_unused_key\"", ",", "OrderedDict", "(", ")", ")", "anim_data", "[", "1", "]", "[", "fbx_group", "]", "=", "(", "group_key", ",", "group", ",", "fbx_gname", ")", "astack_key", "=", "get_blender_anim_stack_key", "(", "scene", ",", "ref_id", ")", "alayer_key", "=", "get_blender_anim_layer_key", "(", "scene", ",", "ref_id", ")", "name", "=", "(", "get_blenderID_name", "(", "ref_id", ")", "if", "ref_id", "else", "scene", ".", "name", ")", ".", "encode", "(", ")", "if", "start_zero", ":", "f_end", "-=", "f_start", "f_start", "=", "0.0", "return", "(", "astack_key", ",", "animations", ",", "alayer_key", ",", "name", ",", "f_start", ",", "f_end", ")", "if", "animations", "else", "None" ]
https://github.com/etodd/lasercrabs/blob/91484d9ac3a47ac38b8f40ec3ff35194714dad8e/assets/script/etodd_blender_fbx/export_fbx_bin.py#L1861-L1993
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/combo.py
python
ComboPopup.OnComboDoubleClick
(*args, **kwargs)
return _combo.ComboPopup_OnComboDoubleClick(*args, **kwargs)
OnComboDoubleClick(self) Implement this method in the derived class if you need to support special actions when the user double-clicks on the parent ComboCtrl.
OnComboDoubleClick(self)
[ "OnComboDoubleClick", "(", "self", ")" ]
def OnComboDoubleClick(*args, **kwargs): """ OnComboDoubleClick(self) Implement this method in the derived class if you need to support special actions when the user double-clicks on the parent ComboCtrl. """ return _combo.ComboPopup_OnComboDoubleClick(*args, **kwargs)
[ "def", "OnComboDoubleClick", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboPopup_OnComboDoubleClick", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/combo.py#L712-L719
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py
python
get_extra_args
()
Returns the corresponding function arguments for the captured inputs. Returns: If the default graph is being used to define a function, the returned list of place holders are those used inside the function body corresponding those returned by get_extra_inputs(). Otherwise, returns an empty list.
Returns the corresponding function arguments for the captured inputs.
[ "Returns", "the", "corresponding", "function", "arguments", "for", "the", "captured", "inputs", "." ]
def get_extra_args(): """Returns the corresponding function arguments for the captured inputs. Returns: If the default graph is being used to define a function, the returned list of place holders are those used inside the function body corresponding those returned by get_extra_inputs(). Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_args else: return []
[ "def", "get_extra_args", "(", ")", ":", "g", "=", "ops", ".", "get_default_graph", "(", ")", "if", "isinstance", "(", "g", ",", "_FuncGraph", ")", ":", "return", "g", ".", "extra_args", "else", ":", "return", "[", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py#L1271-L1284
OpenLightingProject/ola
d1433a1bed73276fbe55ce18c03b1c208237decc
python/ola/RDMAPI.py
python
RDMAPI.RawSet
(self, universe, uid, sub_device, pid, callback, args=[], include_frames=False)
return self._SendRawRequest(universe, uid, sub_device, pid, callback, args, PidStore.RDM_SET, include_frames)
Send a RDM Set message with the raw data supplied. Args: universe: The universe to send the request on. uid: The UID to address the request to. sub_device: The Sub Device to send the request to. pid: A PID object that describes the format of the request. callback: The callback to run when the request completes. data: The param data include_frames: True if the response should include the raw frame data. Return: True if sent ok, False otherwise.
Send a RDM Set message with the raw data supplied.
[ "Send", "a", "RDM", "Set", "message", "with", "the", "raw", "data", "supplied", "." ]
def RawSet(self, universe, uid, sub_device, pid, callback, args=[], include_frames=False): """Send a RDM Set message with the raw data supplied. Args: universe: The universe to send the request on. uid: The UID to address the request to. sub_device: The Sub Device to send the request to. pid: A PID object that describes the format of the request. callback: The callback to run when the request completes. data: The param data include_frames: True if the response should include the raw frame data. Return: True if sent ok, False otherwise. """ return self._SendRawRequest(universe, uid, sub_device, pid, callback, args, PidStore.RDM_SET, include_frames)
[ "def", "RawSet", "(", "self", ",", "universe", ",", "uid", ",", "sub_device", ",", "pid", ",", "callback", ",", "args", "=", "[", "]", ",", "include_frames", "=", "False", ")", ":", "return", "self", ".", "_SendRawRequest", "(", "universe", ",", "uid", ",", "sub_device", ",", "pid", ",", "callback", ",", "args", ",", "PidStore", ".", "RDM_SET", ",", "include_frames", ")" ]
https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/RDMAPI.py#L156-L173
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/lib/_iotools.py
python
StringConverter._getsubdtype
(cls, val)
return np.array(val).dtype.type
Returns the type of the dtype of the input variable.
Returns the type of the dtype of the input variable.
[ "Returns", "the", "type", "of", "the", "dtype", "of", "the", "input", "variable", "." ]
def _getsubdtype(cls, val): """Returns the type of the dtype of the input variable.""" return np.array(val).dtype.type
[ "def", "_getsubdtype", "(", "cls", ",", "val", ")", ":", "return", "np", ".", "array", "(", "val", ")", ".", "dtype", ".", "type" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/_iotools.py#L527-L529
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/config.py
python
config.check_func
(self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=0, call=0)
return self.try_link(body, headers, include_dirs, libraries, library_dirs)
Determine if function 'func' is available by constructing a source file that refers to 'func', and compiles and links it. If everything succeeds, returns true; otherwise returns false. The constructed source file starts out by including the header files listed in 'headers'. If 'decl' is true, it then declares 'func' (as "int func()"); you probably shouldn't supply 'headers' and set 'decl' true in the same call, or you might get errors about a conflicting declarations for 'func'. Finally, the constructed 'main()' function either references 'func' or (if 'call' is true) calls it. 'libraries' and 'library_dirs' are used when linking.
Determine if function 'func' is available by constructing a source file that refers to 'func', and compiles and links it. If everything succeeds, returns true; otherwise returns false.
[ "Determine", "if", "function", "func", "is", "available", "by", "constructing", "a", "source", "file", "that", "refers", "to", "func", "and", "compiles", "and", "links", "it", ".", "If", "everything", "succeeds", "returns", "true", ";", "otherwise", "returns", "false", "." ]
def check_func(self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=0, call=0): """Determine if function 'func' is available by constructing a source file that refers to 'func', and compiles and links it. If everything succeeds, returns true; otherwise returns false. The constructed source file starts out by including the header files listed in 'headers'. If 'decl' is true, it then declares 'func' (as "int func()"); you probably shouldn't supply 'headers' and set 'decl' true in the same call, or you might get errors about a conflicting declarations for 'func'. Finally, the constructed 'main()' function either references 'func' or (if 'call' is true) calls it. 'libraries' and 'library_dirs' are used when linking. """ self._check_compiler() body = [] if decl: body.append("int %s ();" % func) body.append("int main () {") if call: body.append(" %s();" % func) else: body.append(" %s;" % func) body.append("}") body = "\n".join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs)
[ "def", "check_func", "(", "self", ",", "func", ",", "headers", "=", "None", ",", "include_dirs", "=", "None", ",", "libraries", "=", "None", ",", "library_dirs", "=", "None", ",", "decl", "=", "0", ",", "call", "=", "0", ")", ":", "self", ".", "_check_compiler", "(", ")", "body", "=", "[", "]", "if", "decl", ":", "body", ".", "append", "(", "\"int %s ();\"", "%", "func", ")", "body", ".", "append", "(", "\"int main () {\"", ")", "if", "call", ":", "body", ".", "append", "(", "\" %s();\"", "%", "func", ")", "else", ":", "body", ".", "append", "(", "\" %s;\"", "%", "func", ")", "body", ".", "append", "(", "\"}\"", ")", "body", "=", "\"\\n\"", ".", "join", "(", "body", ")", "+", "\"\\n\"", "return", "self", ".", "try_link", "(", "body", ",", "headers", ",", "include_dirs", ",", "libraries", ",", "library_dirs", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/config.py#L285-L315
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/dump_dependency_json.py
python
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
[ "Calculate", "the", "generator", "specific", "info", "that", "gets", "fed", "to", "input", "(", "called", "by", "gyp", ")", "." ]
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True toplevel = params['options'].toplevel_dir generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get('output_dir', 'out') qualified_out_dir = os.path.normpath(os.path.join( toplevel, generator_dir, output_dir, 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': toplevel, 'qualified_out_dir': qualified_out_dir, }
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "if", "generator_flags", ".", "get", "(", "'adjust_static_libraries'", ",", "False", ")", ":", "global", "generator_wants_static_library_dependencies_adjusted", "generator_wants_static_library_dependencies_adjusted", "=", "True", "toplevel", "=", "params", "[", "'options'", "]", ".", "toplevel_dir", "generator_dir", "=", "os", ".", "path", ".", "relpath", "(", "params", "[", "'options'", "]", ".", "generator_output", "or", "'.'", ")", "# output_dir: relative path from generator_dir to the build directory.", "output_dir", "=", "generator_flags", ".", "get", "(", "'output_dir'", ",", "'out'", ")", "qualified_out_dir", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "toplevel", ",", "generator_dir", ",", "output_dir", ",", "'gypfiles'", ")", ")", "global", "generator_filelist_paths", "generator_filelist_paths", "=", "{", "'toplevel'", ":", "toplevel", ",", "'qualified_out_dir'", ":", "qualified_out_dir", ",", "}" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/dump_dependency_json.py#L54-L72
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
StatusBarPane.SetText
(*args, **kwargs)
return _windows_.StatusBarPane_SetText(*args, **kwargs)
SetText(self, String text) -> bool
SetText(self, String text) -> bool
[ "SetText", "(", "self", "String", "text", ")", "-", ">", "bool" ]
def SetText(*args, **kwargs): """SetText(self, String text) -> bool""" return _windows_.StatusBarPane_SetText(*args, **kwargs)
[ "def", "SetText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "StatusBarPane_SetText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1209-L1211
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
tools/windows/get_prec_ut_list.py
python
get_prec_ut_list
(all_test_cases, prec_test_cases)
Select the ut that needs to be executed
Select the ut that needs to be executed
[ "Select", "the", "ut", "that", "needs", "to", "be", "executed" ]
def get_prec_ut_list(all_test_cases, prec_test_cases): """Select the ut that needs to be executed""" all_test_cases_list = all_test_cases.strip().split("\n") prec_test_cases_list = prec_test_cases.strip().split("\n") all_test_cases_list_new = [item.rstrip() for item in all_test_cases_list] prec_test_cases_list_new = [item.rstrip() for item in prec_test_cases_list] if len(prec_test_cases) == 0: return case_to_run = ['test_prec_ut'] for case in all_test_cases_list_new: if case in prec_test_cases_list_new: case_to_run.append(case) else: print("{} will not run in PRECISION_TEST mode.".format(case)) with open(file_path, 'w') as f: f.write('\n'.join(case_to_run))
[ "def", "get_prec_ut_list", "(", "all_test_cases", ",", "prec_test_cases", ")", ":", "all_test_cases_list", "=", "all_test_cases", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "prec_test_cases_list", "=", "prec_test_cases", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "all_test_cases_list_new", "=", "[", "item", ".", "rstrip", "(", ")", "for", "item", "in", "all_test_cases_list", "]", "prec_test_cases_list_new", "=", "[", "item", ".", "rstrip", "(", ")", "for", "item", "in", "prec_test_cases_list", "]", "if", "len", "(", "prec_test_cases", ")", "==", "0", ":", "return", "case_to_run", "=", "[", "'test_prec_ut'", "]", "for", "case", "in", "all_test_cases_list_new", ":", "if", "case", "in", "prec_test_cases_list_new", ":", "case_to_run", ".", "append", "(", "case", ")", "else", ":", "print", "(", "\"{} will not run in PRECISION_TEST mode.\"", ".", "format", "(", "case", ")", ")", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n'", ".", "join", "(", "case_to_run", ")", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/windows/get_prec_ut_list.py#L21-L39
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/importers/common/importer.py
python
ImporterEngine.convert_nodes
(self, model: ImporterModel, apply_ordering: bool = True)
return self.final_ell_map
Converts the model using the operation conversion map that was specified when this class was initialized. If apply_ordering is True, the engine will re-order nodes starting with input nodes, and then repeatedly adding nodes whose inputs are in the newly updated list list.
Converts the model using the operation conversion map that was specified when this class was initialized. If apply_ordering is True, the engine will re-order nodes starting with input nodes, and then repeatedly adding nodes whose inputs are in the newly updated list list.
[ "Converts", "the", "model", "using", "the", "operation", "conversion", "map", "that", "was", "specified", "when", "this", "class", "was", "initialized", ".", "If", "apply_ordering", "is", "True", "the", "engine", "will", "re", "-", "order", "nodes", "starting", "with", "input", "nodes", "and", "then", "repeatedly", "adding", "nodes", "whose", "inputs", "are", "in", "the", "newly", "updated", "list", "list", "." ]
def convert_nodes(self, model: ImporterModel, apply_ordering: bool = True): """ Converts the model using the operation conversion map that was specified when this class was initialized. If apply_ordering is True, the engine will re-order nodes starting with input nodes, and then repeatedly adding nodes whose inputs are in the newly updated list list. """ self.ell_model = ell.model.Model() self.ell_model_builder = ell.model.ModelBuilder() self.lookup_table = LookupTable(model.tensors) function_prefix = "" # Make a first pass through the model to set output padding. Since ELL # does pre-padding, a particular node must know what the input of the # next node wants in terms of padding. self.set_output_padding_for_nodes(model.nodes) if apply_ordering: ordered_nodes = self.get_nodes_in_import_order(model.nodes) else: ordered_nodes = list(model.nodes.values()) self.ordered_importer_nodes = ordered_nodes if len(ordered_nodes) == 0: raise Exception("Cannot convert model because it is empty!") _logger.info("Processing the following importer nodes in order:") for ordered_node in ordered_nodes: _logger.info(ordered_node) _logger.info("Converting intermediate importer nodes to ELL nodes....") for node_to_import in ordered_nodes: self.convert_importer_node_to_ell_nodes(node_to_import) _logger.info("Done.") # Quick workaround to create the map's output node. The last node in # the ordered nodes list will be used. last_importer_node = ordered_nodes[-1] shape_entry = last_importer_node.output_shapes[0] ell_output_shape = memory_shapes.get_ell_shape(shape_entry[0], shape_entry[1], 0) last_ell_node = self.lookup_table.get_ell_node_from_importer_node_id(last_importer_node.id) if self.step_interval_msec is not None: # Add the sink node last_ell_node = self.ell_model_builder.AddSinkNode( self.ell_model, ell.nodes.PortElements(last_ell_node.GetOutputPort("output")), ell.model.PortMemoryLayout(ell_output_shape), "{}OutputCallback".format(function_prefix)) output_node = self.ell_model_builder.AddOutputNode( self.ell_model, ell.model.PortMemoryLayout(ell_output_shape), ell.nodes.PortElements( last_ell_node.GetOutputPort("output"))) output_node.CopyMetadataFrom(last_ell_node) self.lookup_table.add_ell_output(output_node) # Create the map all_outputs = self.lookup_table.get_ell_outputs() output_list = [ell.nodes.PortElements(e.GetOutputPort("output")) for e in all_outputs] self.final_ell_map = ell.model.Map(self.ell_model, ell.nodes.InputNodeList( self.lookup_table.get_ell_inputs()), ell.nodes.PortElementsList(output_list)) # Print out the nodes and where they came from self.final_mapping = self.get_node_group_mapping(self.final_ell_map.GetModel()) _logger.info("\nFinal mapping of imported nodes to ell nodes:") source_names = {} max_len = 0 for group_id in self.final_mapping.keys(): importer_node = model.nodes[group_id] text = "{}({})".format(importer_node.operation_type, group_id) if len(text) > max_len: max_len = len(text) source_names[group_id] = text for group_id in self.final_mapping.keys(): source_name = source_names[group_id] indent = " " + (" " * (max_len - len(source_name))) ell_nodes = ["{}({})".format(ell_node.GetRuntimeTypeName(), ell_node.GetId()) for ell_node in self.final_mapping[group_id]] _logger.info("{}{} -> {}".format(indent, source_name, ", ".join(ell_nodes))) _logger.info("") return self.final_ell_map
[ "def", "convert_nodes", "(", "self", ",", "model", ":", "ImporterModel", ",", "apply_ordering", ":", "bool", "=", "True", ")", ":", "self", ".", "ell_model", "=", "ell", ".", "model", ".", "Model", "(", ")", "self", ".", "ell_model_builder", "=", "ell", ".", "model", ".", "ModelBuilder", "(", ")", "self", ".", "lookup_table", "=", "LookupTable", "(", "model", ".", "tensors", ")", "function_prefix", "=", "\"\"", "# Make a first pass through the model to set output padding. Since ELL", "# does pre-padding, a particular node must know what the input of the", "# next node wants in terms of padding.", "self", ".", "set_output_padding_for_nodes", "(", "model", ".", "nodes", ")", "if", "apply_ordering", ":", "ordered_nodes", "=", "self", ".", "get_nodes_in_import_order", "(", "model", ".", "nodes", ")", "else", ":", "ordered_nodes", "=", "list", "(", "model", ".", "nodes", ".", "values", "(", ")", ")", "self", ".", "ordered_importer_nodes", "=", "ordered_nodes", "if", "len", "(", "ordered_nodes", ")", "==", "0", ":", "raise", "Exception", "(", "\"Cannot convert model because it is empty!\"", ")", "_logger", ".", "info", "(", "\"Processing the following importer nodes in order:\"", ")", "for", "ordered_node", "in", "ordered_nodes", ":", "_logger", ".", "info", "(", "ordered_node", ")", "_logger", ".", "info", "(", "\"Converting intermediate importer nodes to ELL nodes....\"", ")", "for", "node_to_import", "in", "ordered_nodes", ":", "self", ".", "convert_importer_node_to_ell_nodes", "(", "node_to_import", ")", "_logger", ".", "info", "(", "\"Done.\"", ")", "# Quick workaround to create the map's output node. The last node in", "# the ordered nodes list will be used.", "last_importer_node", "=", "ordered_nodes", "[", "-", "1", "]", "shape_entry", "=", "last_importer_node", ".", "output_shapes", "[", "0", "]", "ell_output_shape", "=", "memory_shapes", ".", "get_ell_shape", "(", "shape_entry", "[", "0", "]", ",", "shape_entry", "[", "1", "]", ",", "0", ")", "last_ell_node", "=", "self", ".", "lookup_table", ".", "get_ell_node_from_importer_node_id", "(", "last_importer_node", ".", "id", ")", "if", "self", ".", "step_interval_msec", "is", "not", "None", ":", "# Add the sink node", "last_ell_node", "=", "self", ".", "ell_model_builder", ".", "AddSinkNode", "(", "self", ".", "ell_model", ",", "ell", ".", "nodes", ".", "PortElements", "(", "last_ell_node", ".", "GetOutputPort", "(", "\"output\"", ")", ")", ",", "ell", ".", "model", ".", "PortMemoryLayout", "(", "ell_output_shape", ")", ",", "\"{}OutputCallback\"", ".", "format", "(", "function_prefix", ")", ")", "output_node", "=", "self", ".", "ell_model_builder", ".", "AddOutputNode", "(", "self", ".", "ell_model", ",", "ell", ".", "model", ".", "PortMemoryLayout", "(", "ell_output_shape", ")", ",", "ell", ".", "nodes", ".", "PortElements", "(", "last_ell_node", ".", "GetOutputPort", "(", "\"output\"", ")", ")", ")", "output_node", ".", "CopyMetadataFrom", "(", "last_ell_node", ")", "self", ".", "lookup_table", ".", "add_ell_output", "(", "output_node", ")", "# Create the map", "all_outputs", "=", "self", ".", "lookup_table", ".", "get_ell_outputs", "(", ")", "output_list", "=", "[", "ell", ".", "nodes", ".", "PortElements", "(", "e", ".", "GetOutputPort", "(", "\"output\"", ")", ")", "for", "e", "in", "all_outputs", "]", "self", ".", "final_ell_map", "=", "ell", ".", "model", ".", "Map", "(", "self", ".", "ell_model", ",", "ell", ".", "nodes", ".", "InputNodeList", "(", "self", ".", "lookup_table", ".", "get_ell_inputs", "(", ")", ")", ",", "ell", ".", "nodes", ".", "PortElementsList", "(", "output_list", ")", ")", "# Print out the nodes and where they came from", "self", ".", "final_mapping", "=", "self", ".", "get_node_group_mapping", "(", "self", ".", "final_ell_map", ".", "GetModel", "(", ")", ")", "_logger", ".", "info", "(", "\"\\nFinal mapping of imported nodes to ell nodes:\"", ")", "source_names", "=", "{", "}", "max_len", "=", "0", "for", "group_id", "in", "self", ".", "final_mapping", ".", "keys", "(", ")", ":", "importer_node", "=", "model", ".", "nodes", "[", "group_id", "]", "text", "=", "\"{}({})\"", ".", "format", "(", "importer_node", ".", "operation_type", ",", "group_id", ")", "if", "len", "(", "text", ")", ">", "max_len", ":", "max_len", "=", "len", "(", "text", ")", "source_names", "[", "group_id", "]", "=", "text", "for", "group_id", "in", "self", ".", "final_mapping", ".", "keys", "(", ")", ":", "source_name", "=", "source_names", "[", "group_id", "]", "indent", "=", "\" \"", "+", "(", "\" \"", "*", "(", "max_len", "-", "len", "(", "source_name", ")", ")", ")", "ell_nodes", "=", "[", "\"{}({})\"", ".", "format", "(", "ell_node", ".", "GetRuntimeTypeName", "(", ")", ",", "ell_node", ".", "GetId", "(", ")", ")", "for", "ell_node", "in", "self", ".", "final_mapping", "[", "group_id", "]", "]", "_logger", ".", "info", "(", "\"{}{} -> {}\"", ".", "format", "(", "indent", ",", "source_name", ",", "\", \"", ".", "join", "(", "ell_nodes", ")", ")", ")", "_logger", ".", "info", "(", "\"\"", ")", "return", "self", ".", "final_ell_map" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/common/importer.py#L193-L277
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
PreviewControlBar.__init__
(self, *args, **kwargs)
__init__(self, PrintPreview preview, long buttons, Window parent, Point pos=DefaultPosition, Size size=DefaultSize, long style=TAB_TRAVERSAL, String name=PanelNameStr) -> PreviewControlBar
__init__(self, PrintPreview preview, long buttons, Window parent, Point pos=DefaultPosition, Size size=DefaultSize, long style=TAB_TRAVERSAL, String name=PanelNameStr) -> PreviewControlBar
[ "__init__", "(", "self", "PrintPreview", "preview", "long", "buttons", "Window", "parent", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "TAB_TRAVERSAL", "String", "name", "=", "PanelNameStr", ")", "-", ">", "PreviewControlBar" ]
def __init__(self, *args, **kwargs): """ __init__(self, PrintPreview preview, long buttons, Window parent, Point pos=DefaultPosition, Size size=DefaultSize, long style=TAB_TRAVERSAL, String name=PanelNameStr) -> PreviewControlBar """ _windows_.PreviewControlBar_swiginit(self,_windows_.new_PreviewControlBar(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_windows_", ".", "PreviewControlBar_swiginit", "(", "self", ",", "_windows_", ".", "new_PreviewControlBar", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L5524-L5531
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/dvipdf.py
python
PDFEmitter
(target, source, env)
return (target, source)
Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file.
Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file.
[ "Strips", "any", ".", "aux", "or", ".", "log", "files", "from", "the", "input", "source", "list", ".", "These", "are", "created", "by", "the", "TeX", "Builder", "that", "in", "all", "likelihood", "was", "used", "to", "generate", "the", ".", "dvi", "file", "we", "re", "using", "as", "input", "and", "we", "only", "care", "about", "the", ".", "dvi", "file", "." ]
def PDFEmitter(target, source, env): """Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file. """ def strip_suffixes(n): return not SCons.Util.splitext(str(n))[1] in ['.aux', '.log'] source = list(filter(strip_suffixes, source)) return (target, source)
[ "def", "PDFEmitter", "(", "target", ",", "source", ",", "env", ")", ":", "def", "strip_suffixes", "(", "n", ")", ":", "return", "not", "SCons", ".", "Util", ".", "splitext", "(", "str", "(", "n", ")", ")", "[", "1", "]", "in", "[", "'.aux'", ",", "'.log'", "]", "source", "=", "list", "(", "filter", "(", "strip_suffixes", ",", "source", ")", ")", "return", "(", "target", ",", "source", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/dvipdf.py#L82-L91
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/telnetlib.py
python
Telnet.sock_avail
(self)
return select.select([self], [], [], 0) == ([self], [], [])
Test whether data is available on the socket.
Test whether data is available on the socket.
[ "Test", "whether", "data", "is", "available", "on", "the", "socket", "." ]
def sock_avail(self): """Test whether data is available on the socket.""" return select.select([self], [], [], 0) == ([self], [], [])
[ "def", "sock_avail", "(", "self", ")", ":", "return", "select", ".", "select", "(", "[", "self", "]", ",", "[", "]", ",", "[", "]", ",", "0", ")", "==", "(", "[", "self", "]", ",", "[", "]", ",", "[", "]", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/telnetlib.py#L578-L580
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tkinter.py
python
Misc.bind_class
(self, className, sequence=None, func=None, add=None)
return self._bind(('bind', className), sequence, func, add, 0)
Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.
Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.
[ "Bind", "to", "widgets", "with", "bindtag", "CLASSNAME", "at", "event", "SEQUENCE", "a", "call", "of", "function", "FUNC", ".", "An", "additional", "boolean", "parameter", "ADD", "specifies", "whether", "FUNC", "will", "be", "called", "additionally", "to", "the", "other", "bound", "function", "or", "whether", "it", "will", "replace", "the", "previous", "function", ".", "See", "bind", "for", "the", "return", "value", "." ]
def bind_class(self, className, sequence=None, func=None, add=None): """Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind(('bind', className), sequence, func, add, 0)
[ "def", "bind_class", "(", "self", ",", "className", ",", "sequence", "=", "None", ",", "func", "=", "None", ",", "add", "=", "None", ")", ":", "return", "self", ".", "_bind", "(", "(", "'bind'", ",", "className", ")", ",", "sequence", ",", "func", ",", "add", ",", "0", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L1119-L1128
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py
python
obj_class.get_capi_name
(self)
return get_capi_name(self.name, True)
Return the CAPI structure name for this class.
Return the CAPI structure name for this class.
[ "Return", "the", "CAPI", "structure", "name", "for", "this", "class", "." ]
def get_capi_name(self): """ Return the CAPI structure name for this class. """ return get_capi_name(self.name, True)
[ "def", "get_capi_name", "(", "self", ")", ":", "return", "get_capi_name", "(", "self", ".", "name", ",", "True", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L864-L866
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/interpolate/fitpack2.py
python
BivariateSpline._from_tck
(cls, tck)
return self
Construct a spline object from given tck and degree
Construct a spline object from given tck and degree
[ "Construct", "a", "spline", "object", "from", "given", "tck", "and", "degree" ]
def _from_tck(cls, tck): """Construct a spline object from given tck and degree""" self = cls.__new__(cls) if len(tck) != 5: raise ValueError("tck should be a 5 element tuple of tx," " ty, c, kx, ky") self.tck = tck[:3] self.degrees = tck[3:] return self
[ "def", "_from_tck", "(", "cls", ",", "tck", ")", ":", "self", "=", "cls", ".", "__new__", "(", "cls", ")", "if", "len", "(", "tck", ")", "!=", "5", ":", "raise", "ValueError", "(", "\"tck should be a 5 element tuple of tx,\"", "\" ty, c, kx, ky\"", ")", "self", ".", "tck", "=", "tck", "[", ":", "3", "]", "self", ".", "degrees", "=", "tck", "[", "3", ":", "]", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/interpolate/fitpack2.py#L945-L953
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/plot3dwindow.py
python
Plot3DWindow.plot_3d
(self, data_key, base_color, thresholds, change_color)
return
Plot scatter data with specified base color Requirements: data key does exist. color values are within (0, 1) :param data_key: :param base_color: :param threshold: list of 2-item :param change_color: [change_R, change_G, change_B] :return:
Plot scatter data with specified base color Requirements: data key does exist. color values are within (0, 1) :param data_key: :param base_color: :param threshold: list of 2-item :param change_color: [change_R, change_G, change_B] :return:
[ "Plot", "scatter", "data", "with", "specified", "base", "color", "Requirements", ":", "data", "key", "does", "exist", ".", "color", "values", "are", "within", "(", "0", "1", ")", ":", "param", "data_key", ":", ":", "param", "base_color", ":", ":", "param", "threshold", ":", "list", "of", "2", "-", "item", ":", "param", "change_color", ":", "[", "change_R", "change_G", "change_B", "]", ":", "return", ":" ]
def plot_3d(self, data_key, base_color, thresholds, change_color): """ Plot scatter data with specified base color Requirements: data key does exist. color values are within (0, 1) :param data_key: :param base_color: :param threshold: list of 2-item :param change_color: [change_R, change_G, change_B] :return: """ # Check assert isinstance(data_key, int), 'Date key %s must be an integer' \ ' but not %s' % (str(data_key), str(type(data_key))) assert isinstance(base_color, list) assert isinstance(thresholds, list) and len(thresholds) == 2 assert isinstance(change_color, list) lower_boundary, upper_boundary = thresholds assert 0 <= lower_boundary < upper_boundary # Reset data points, intensities = self.ui.graphicsView.get_data(data_key) if lower_boundary > min(intensities) or upper_boundary < max(intensities): # threshold is larger than 0, then filter the data points, intensities = filter_points_by_intensity(points, intensities, lower_boundary, upper_boundary) # Set limit self.ui.graphicsView.set_xyz_limits(points, None) # Format intensity to color map color_list = guiutility.map_to_color(intensities, base_color, change_color) # print(color_list) assert len(color_list) == len(points) # self.ui.graphicsView.plot_scatter(data_key, base_color) self.ui.graphicsView.set_xyz_limits(points) self.ui.graphicsView.plot_scatter(points, color_list) return
[ "def", "plot_3d", "(", "self", ",", "data_key", ",", "base_color", ",", "thresholds", ",", "change_color", ")", ":", "# Check", "assert", "isinstance", "(", "data_key", ",", "int", ")", ",", "'Date key %s must be an integer'", "' but not %s'", "%", "(", "str", "(", "data_key", ")", ",", "str", "(", "type", "(", "data_key", ")", ")", ")", "assert", "isinstance", "(", "base_color", ",", "list", ")", "assert", "isinstance", "(", "thresholds", ",", "list", ")", "and", "len", "(", "thresholds", ")", "==", "2", "assert", "isinstance", "(", "change_color", ",", "list", ")", "lower_boundary", ",", "upper_boundary", "=", "thresholds", "assert", "0", "<=", "lower_boundary", "<", "upper_boundary", "# Reset data", "points", ",", "intensities", "=", "self", ".", "ui", ".", "graphicsView", ".", "get_data", "(", "data_key", ")", "if", "lower_boundary", ">", "min", "(", "intensities", ")", "or", "upper_boundary", "<", "max", "(", "intensities", ")", ":", "# threshold is larger than 0, then filter the data", "points", ",", "intensities", "=", "filter_points_by_intensity", "(", "points", ",", "intensities", ",", "lower_boundary", ",", "upper_boundary", ")", "# Set limit", "self", ".", "ui", ".", "graphicsView", ".", "set_xyz_limits", "(", "points", ",", "None", ")", "# Format intensity to color map", "color_list", "=", "guiutility", ".", "map_to_color", "(", "intensities", ",", "base_color", ",", "change_color", ")", "# print(color_list)", "assert", "len", "(", "color_list", ")", "==", "len", "(", "points", ")", "# self.ui.graphicsView.plot_scatter(data_key, base_color)", "self", ".", "ui", ".", "graphicsView", ".", "set_xyz_limits", "(", "points", ")", "self", ".", "ui", ".", "graphicsView", ".", "plot_scatter", "(", "points", ",", "color_list", ")", "return" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/plot3dwindow.py#L246-L285
OpenChemistry/tomviz
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
tomviz/python/AutoCenterOfMassTiltImageAlignment.py
python
CenterOfMassAlignmentOperator.transform_scalars
(self, dataset)
return returnValues
Automatically align tilt images by center of mass method
Automatically align tilt images by center of mass method
[ "Automatically", "align", "tilt", "images", "by", "center", "of", "mass", "method" ]
def transform_scalars(self, dataset): """Automatically align tilt images by center of mass method""" self.progress.maximum = 1 tiltSeries = utils.get_array(dataset).astype(float) self.progress.maximum = tiltSeries.shape[2] step = 1 offsets = np.zeros((tiltSeries.shape[2], 2)) for i in range(tiltSeries.shape[2]): if self.canceled: return self.progress.message = 'Processing tilt image No.%d/%d' % ( i + 1, tiltSeries.shape[2]) offsets[i, :], tiltSeries[:, :, i] = centerOfMassAlign( tiltSeries[:, :, i] ) step += 1 self.progress.value = step utils.set_array(dataset, tiltSeries) # Create a spreadsheet data set from table data column_names = ["X Offset", "Y Offset"] offsetsTable = utils.make_spreadsheet(column_names, offsets) # Set up dictionary to return operator results returnValues = {} returnValues["alignments"] = offsetsTable return returnValues
[ "def", "transform_scalars", "(", "self", ",", "dataset", ")", ":", "self", ".", "progress", ".", "maximum", "=", "1", "tiltSeries", "=", "utils", ".", "get_array", "(", "dataset", ")", ".", "astype", "(", "float", ")", "self", ".", "progress", ".", "maximum", "=", "tiltSeries", ".", "shape", "[", "2", "]", "step", "=", "1", "offsets", "=", "np", ".", "zeros", "(", "(", "tiltSeries", ".", "shape", "[", "2", "]", ",", "2", ")", ")", "for", "i", "in", "range", "(", "tiltSeries", ".", "shape", "[", "2", "]", ")", ":", "if", "self", ".", "canceled", ":", "return", "self", ".", "progress", ".", "message", "=", "'Processing tilt image No.%d/%d'", "%", "(", "i", "+", "1", ",", "tiltSeries", ".", "shape", "[", "2", "]", ")", "offsets", "[", "i", ",", ":", "]", ",", "tiltSeries", "[", ":", ",", ":", ",", "i", "]", "=", "centerOfMassAlign", "(", "tiltSeries", "[", ":", ",", ":", ",", "i", "]", ")", "step", "+=", "1", "self", ".", "progress", ".", "value", "=", "step", "utils", ".", "set_array", "(", "dataset", ",", "tiltSeries", ")", "# Create a spreadsheet data set from table data", "column_names", "=", "[", "\"X Offset\"", ",", "\"Y Offset\"", "]", "offsetsTable", "=", "utils", ".", "make_spreadsheet", "(", "column_names", ",", "offsets", ")", "# Set up dictionary to return operator results", "returnValues", "=", "{", "}", "returnValues", "[", "\"alignments\"", "]", "=", "offsetsTable", "return", "returnValues" ]
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/AutoCenterOfMassTiltImageAlignment.py#L8-L40
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
vendor/pybind11/tools/clang/cindex.py
python
TranslationUnit.from_ast_file
(cls, filename, index=None)
return cls(ptr=ptr, index=index)
Create a TranslationUnit instance from a saved AST file. A previously-saved AST file (provided with -emit-ast or TranslationUnit.save()) is loaded from the filename specified. If the file cannot be loaded, a TranslationUnitLoadError will be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created.
Create a TranslationUnit instance from a saved AST file.
[ "Create", "a", "TranslationUnit", "instance", "from", "a", "saved", "AST", "file", "." ]
def from_ast_file(cls, filename, index=None): """Create a TranslationUnit instance from a saved AST file. A previously-saved AST file (provided with -emit-ast or TranslationUnit.save()) is loaded from the filename specified. If the file cannot be loaded, a TranslationUnitLoadError will be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created. """ if index is None: index = Index.create() ptr = conf.lib.clang_createTranslationUnit(index, filename) if not ptr: raise TranslationUnitLoadError(filename) return cls(ptr=ptr, index=index)
[ "def", "from_ast_file", "(", "cls", ",", "filename", ",", "index", "=", "None", ")", ":", "if", "index", "is", "None", ":", "index", "=", "Index", ".", "create", "(", ")", "ptr", "=", "conf", ".", "lib", ".", "clang_createTranslationUnit", "(", "index", ",", "filename", ")", "if", "not", "ptr", ":", "raise", "TranslationUnitLoadError", "(", "filename", ")", "return", "cls", "(", "ptr", "=", "ptr", ",", "index", "=", "index", ")" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L2541-L2560
libLAS/libLAS
e6a1aaed412d638687b8aec44f7b12df7ca2bbbb
python/liblas/header.py
python
Header.get_majorversion
(self)
return core.las.LASHeader_GetVersionMajor(self.handle)
Returns the major version for the file. Expect this value to always be 1
Returns the major version for the file. Expect this value to always be 1
[ "Returns", "the", "major", "version", "for", "the", "file", ".", "Expect", "this", "value", "to", "always", "be", "1" ]
def get_majorversion(self): """Returns the major version for the file. Expect this value to always be 1""" return core.las.LASHeader_GetVersionMajor(self.handle)
[ "def", "get_majorversion", "(", "self", ")", ":", "return", "core", ".", "las", ".", "LASHeader_GetVersionMajor", "(", "self", ".", "handle", ")" ]
https://github.com/libLAS/libLAS/blob/e6a1aaed412d638687b8aec44f7b12df7ca2bbbb/python/liblas/header.py#L196-L199
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/dist.py
python
Distribution.finalize_options
(self)
Set final values for all the options on the Distribution instance, analogous to the .finalize_options() method of Command objects.
Set final values for all the options on the Distribution instance, analogous to the .finalize_options() method of Command objects.
[ "Set", "final", "values", "for", "all", "the", "options", "on", "the", "Distribution", "instance", "analogous", "to", "the", ".", "finalize_options", "()", "method", "of", "Command", "objects", "." ]
def finalize_options(self): """Set final values for all the options on the Distribution instance, analogous to the .finalize_options() method of Command objects. """ for attr in ('keywords', 'platforms'): value = getattr(self.metadata, attr) if value is None: continue if isinstance(value, str): value = [elm.strip() for elm in value.split(',')] setattr(self.metadata, attr, value)
[ "def", "finalize_options", "(", "self", ")", ":", "for", "attr", "in", "(", "'keywords'", ",", "'platforms'", ")", ":", "value", "=", "getattr", "(", "self", ".", "metadata", ",", "attr", ")", "if", "value", "is", "None", ":", "continue", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "[", "elm", ".", "strip", "(", ")", "for", "elm", "in", "value", ".", "split", "(", "','", ")", "]", "setattr", "(", "self", ".", "metadata", ",", "attr", ",", "value", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/dist.py#L608-L619
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/harness-thci/OpenThread.py
python
OpenThreadTHCI.setLinkQuality
(self, EUIadr, LinkQuality)
return self.__executeCommand(cmd)[-1] == 'Done'
set custom LinkQualityIn for all receiving messages from the specified EUIadr Args: EUIadr: a given extended address LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) 2: 11 - 20 (dB) 1: 3 - 9 (dB) 0: 0 - 2 (dB) Returns: True: successful to set the link quality False: fail to set the link quality
set custom LinkQualityIn for all receiving messages from the specified EUIadr
[ "set", "custom", "LinkQualityIn", "for", "all", "receiving", "messages", "from", "the", "specified", "EUIadr" ]
def setLinkQuality(self, EUIadr, LinkQuality): """set custom LinkQualityIn for all receiving messages from the specified EUIadr Args: EUIadr: a given extended address LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) 2: 11 - 20 (dB) 1: 3 - 9 (dB) 0: 0 - 2 (dB) Returns: True: successful to set the link quality False: fail to set the link quality """ print('%s call setLinkQuality' % self) print(EUIadr) print(LinkQuality) # process EUIadr euiHex = hex(EUIadr) euiStr = str(euiHex) euiStr = euiStr.rstrip('L') address64 = '' if '0x' in euiStr: address64 = self.__lstrip0x(euiStr) # prepend 0 at the beginning if len(address64) < 16: address64 = address64.zfill(16) print(address64) cmd = 'macfilter rss add-lqi %s %s' % (address64, str(LinkQuality)) print(cmd) return self.__executeCommand(cmd)[-1] == 'Done'
[ "def", "setLinkQuality", "(", "self", ",", "EUIadr", ",", "LinkQuality", ")", ":", "print", "(", "'%s call setLinkQuality'", "%", "self", ")", "print", "(", "EUIadr", ")", "print", "(", "LinkQuality", ")", "# process EUIadr", "euiHex", "=", "hex", "(", "EUIadr", ")", "euiStr", "=", "str", "(", "euiHex", ")", "euiStr", "=", "euiStr", ".", "rstrip", "(", "'L'", ")", "address64", "=", "''", "if", "'0x'", "in", "euiStr", ":", "address64", "=", "self", ".", "__lstrip0x", "(", "euiStr", ")", "# prepend 0 at the beginning", "if", "len", "(", "address64", ")", "<", "16", ":", "address64", "=", "address64", ".", "zfill", "(", "16", ")", "print", "(", "address64", ")", "cmd", "=", "'macfilter rss add-lqi %s %s'", "%", "(", "address64", ",", "str", "(", "LinkQuality", ")", ")", "print", "(", "cmd", ")", "return", "self", ".", "__executeCommand", "(", "cmd", ")", "[", "-", "1", "]", "==", "'Done'" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread.py#L1609-L1642
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/tensor_forest/data/data_ops.py
python
StringToFloatShape
(op)
return [op.inputs[0].get_shape()]
Shape function for StringToFloat Op.
Shape function for StringToFloat Op.
[ "Shape", "function", "for", "StringToFloat", "Op", "." ]
def StringToFloatShape(op): """Shape function for StringToFloat Op.""" return [op.inputs[0].get_shape()]
[ "def", "StringToFloatShape", "(", "op", ")", ":", "return", "[", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/tensor_forest/data/data_ops.py#L50-L52
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/tz/win.py
python
picknthweekday
(year, month, dayofweek, hour, minute, whichweek)
return wd
dayofweek == 0 means Sunday, whichweek 5 means last instance
dayofweek == 0 means Sunday, whichweek 5 means last instance
[ "dayofweek", "==", "0", "means", "Sunday", "whichweek", "5", "means", "last", "instance" ]
def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ first = datetime.datetime(year, month, 1, hour, minute) # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), # Because 7 % 7 = 0 weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) wd = weekdayone + ((whichweek - 1) * ONEWEEK) if (wd.month != month): wd -= ONEWEEK return wd
[ "def", "picknthweekday", "(", "year", ",", "month", ",", "dayofweek", ",", "hour", ",", "minute", ",", "whichweek", ")", ":", "first", "=", "datetime", ".", "datetime", "(", "year", ",", "month", ",", "1", ",", "hour", ",", "minute", ")", "# This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),", "# Because 7 % 7 = 0", "weekdayone", "=", "first", ".", "replace", "(", "day", "=", "(", "(", "dayofweek", "-", "first", ".", "isoweekday", "(", ")", ")", "%", "7", ")", "+", "1", ")", "wd", "=", "weekdayone", "+", "(", "(", "whichweek", "-", "1", ")", "*", "ONEWEEK", ")", "if", "(", "wd", ".", "month", "!=", "month", ")", ":", "wd", "-=", "ONEWEEK", "return", "wd" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/tz/win.py#L333-L344
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/email/_parseaddr.py
python
AddrlistClass.getaddress
(self)
return returnlist
Parse the next address.
Parse the next address.
[ "Parse", "the", "next", "address", "." ]
def getaddress(self): """Parse the next address.""" self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if self.pos >= len(self.field): # Bad email address technically, no domain. if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in '.@': # email address is just an addrspec # this isn't very efficient since we start over self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif self.field[self.pos] == ':': # address is a group returnlist = [] fieldlen = len(self.field) self.pos += 1 while self.pos < len(self.field): self.gotonext() if self.pos < fieldlen and self.field[self.pos] == ';': self.pos += 1 break returnlist = returnlist + self.getaddress() elif self.field[self.pos] == '<': # Address is a phrase then a route addr routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [(SPACE.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] else: if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in self.specials: self.pos += 1 self.gotonext() if self.pos < len(self.field) and self.field[self.pos] == ',': self.pos += 1 return returnlist
[ "def", "getaddress", "(", "self", ")", ":", "self", ".", "commentlist", "=", "[", "]", "self", ".", "gotonext", "(", ")", "oldpos", "=", "self", ".", "pos", "oldcl", "=", "self", ".", "commentlist", "plist", "=", "self", ".", "getphraselist", "(", ")", "self", ".", "gotonext", "(", ")", "returnlist", "=", "[", "]", "if", "self", ".", "pos", ">=", "len", "(", "self", ".", "field", ")", ":", "# Bad email address technically, no domain.", "if", "plist", ":", "returnlist", "=", "[", "(", "SPACE", ".", "join", "(", "self", ".", "commentlist", ")", ",", "plist", "[", "0", "]", ")", "]", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "'.@'", ":", "# email address is just an addrspec", "# this isn't very efficient since we start over", "self", ".", "pos", "=", "oldpos", "self", ".", "commentlist", "=", "oldcl", "addrspec", "=", "self", ".", "getaddrspec", "(", ")", "returnlist", "=", "[", "(", "SPACE", ".", "join", "(", "self", ".", "commentlist", ")", ",", "addrspec", ")", "]", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "':'", ":", "# address is a group", "returnlist", "=", "[", "]", "fieldlen", "=", "len", "(", "self", ".", "field", ")", "self", ".", "pos", "+=", "1", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "self", ".", "gotonext", "(", ")", "if", "self", ".", "pos", "<", "fieldlen", "and", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "';'", ":", "self", ".", "pos", "+=", "1", "break", "returnlist", "=", "returnlist", "+", "self", ".", "getaddress", "(", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'<'", ":", "# Address is a phrase then a route addr", "routeaddr", "=", "self", ".", "getrouteaddr", "(", ")", "if", "self", ".", "commentlist", ":", "returnlist", "=", "[", "(", "SPACE", ".", "join", "(", "plist", ")", "+", "' ('", "+", "' '", ".", "join", "(", "self", ".", "commentlist", ")", "+", "')'", ",", "routeaddr", ")", "]", "else", ":", "returnlist", "=", "[", "(", "SPACE", ".", "join", "(", "plist", ")", ",", "routeaddr", ")", "]", "else", ":", "if", "plist", ":", "returnlist", "=", "[", "(", "SPACE", ".", "join", "(", "self", ".", "commentlist", ")", ",", "plist", "[", "0", "]", ")", "]", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "specials", ":", "self", ".", "pos", "+=", "1", "self", ".", "gotonext", "(", ")", "if", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", "and", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "','", ":", "self", ".", "pos", "+=", "1", "return", "returnlist" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/email/_parseaddr.py#L225-L282
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/codegen.py
python
get_host_cpu_features
()
Get host CPU features using LLVM. The features may be modified due to user setting. See numba.config.ENABLE_AVX.
Get host CPU features using LLVM.
[ "Get", "host", "CPU", "features", "using", "LLVM", "." ]
def get_host_cpu_features(): """Get host CPU features using LLVM. The features may be modified due to user setting. See numba.config.ENABLE_AVX. """ try: features = ll.get_host_cpu_features() except RuntimeError: return '' else: if not config.ENABLE_AVX: # Disable all features with name starting with 'avx' for k in features: if k.startswith('avx'): features[k] = False # Set feature attributes return features.flatten()
[ "def", "get_host_cpu_features", "(", ")", ":", "try", ":", "features", "=", "ll", ".", "get_host_cpu_features", "(", ")", "except", "RuntimeError", ":", "return", "''", "else", ":", "if", "not", "config", ".", "ENABLE_AVX", ":", "# Disable all features with name starting with 'avx'", "for", "k", "in", "features", ":", "if", "k", ".", "startswith", "(", "'avx'", ")", ":", "features", "[", "k", "]", "=", "False", "# Set feature attributes", "return", "features", ".", "flatten", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/codegen.py#L857-L875
google/fhir
d77f57706c1a168529b0b87ca7ccb1c0113e83c2
py/google/fhir/json_format/wrappers/_time.py
python
TimeWrapper.from_json_str
(cls, json_str: str, primitive_cls: Type[Time], context: _primitive_wrappers.Context)
return cls(time, context)
See PrimitiveWrapper.from_json_str.
See PrimitiveWrapper.from_json_str.
[ "See", "PrimitiveWrapper", ".", "from_json_str", "." ]
def from_json_str(cls, json_str: str, primitive_cls: Type[Time], context: _primitive_wrappers.Context) -> 'TimeWrapper': """See PrimitiveWrapper.from_json_str.""" _primitive_wrappers.validate_primitive_json_representation( primitive_cls.DESCRIPTOR, json_str) time = _parse(json_str, primitive_cls) return cls(time, context)
[ "def", "from_json_str", "(", "cls", ",", "json_str", ":", "str", ",", "primitive_cls", ":", "Type", "[", "Time", "]", ",", "context", ":", "_primitive_wrappers", ".", "Context", ")", "->", "'TimeWrapper'", ":", "_primitive_wrappers", ".", "validate_primitive_json_representation", "(", "primitive_cls", ".", "DESCRIPTOR", ",", "json_str", ")", "time", "=", "_parse", "(", "json_str", ",", "primitive_cls", ")", "return", "cls", "(", "time", ",", "context", ")" ]
https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/json_format/wrappers/_time.py#L84-L90
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/dtypes/common.py
python
is_sparse
(arr)
return isinstance(dtype, SparseDtype)
Check whether an array-like is a 1-D pandas sparse array. Check that the one-dimensional array-like is a pandas sparse array. Returns True if it is a pandas sparse array, not another type of sparse array. Parameters ---------- arr : array-like Array-like to check. Returns ------- bool Whether or not the array-like is a pandas sparse array. See Also -------- DataFrame.to_sparse : Convert DataFrame to a SparseDataFrame. Series.to_sparse : Convert Series to SparseSeries. Series.to_dense : Return dense representation of a Series. Examples -------- Returns `True` if the parameter is a 1-D pandas sparse array. >>> is_sparse(pd.SparseArray([0, 0, 1, 0])) True >>> is_sparse(pd.SparseSeries([0, 0, 1, 0])) True Returns `False` if the parameter is not sparse. >>> is_sparse(np.array([0, 0, 1, 0])) False >>> is_sparse(pd.Series([0, 1, 0, 0])) False Returns `False` if the parameter is not a pandas sparse array. >>> from scipy.sparse import bsr_matrix >>> is_sparse(bsr_matrix([0, 1, 0, 0])) False Returns `False` if the parameter has more than one dimension. >>> df = pd.SparseDataFrame([389., 24., 80.5, np.nan], columns=['max_speed'], index=['falcon', 'parrot', 'lion', 'monkey']) >>> is_sparse(df) False >>> is_sparse(df.max_speed) True
Check whether an array-like is a 1-D pandas sparse array.
[ "Check", "whether", "an", "array", "-", "like", "is", "a", "1", "-", "D", "pandas", "sparse", "array", "." ]
def is_sparse(arr): """ Check whether an array-like is a 1-D pandas sparse array. Check that the one-dimensional array-like is a pandas sparse array. Returns True if it is a pandas sparse array, not another type of sparse array. Parameters ---------- arr : array-like Array-like to check. Returns ------- bool Whether or not the array-like is a pandas sparse array. See Also -------- DataFrame.to_sparse : Convert DataFrame to a SparseDataFrame. Series.to_sparse : Convert Series to SparseSeries. Series.to_dense : Return dense representation of a Series. Examples -------- Returns `True` if the parameter is a 1-D pandas sparse array. >>> is_sparse(pd.SparseArray([0, 0, 1, 0])) True >>> is_sparse(pd.SparseSeries([0, 0, 1, 0])) True Returns `False` if the parameter is not sparse. >>> is_sparse(np.array([0, 0, 1, 0])) False >>> is_sparse(pd.Series([0, 1, 0, 0])) False Returns `False` if the parameter is not a pandas sparse array. >>> from scipy.sparse import bsr_matrix >>> is_sparse(bsr_matrix([0, 1, 0, 0])) False Returns `False` if the parameter has more than one dimension. >>> df = pd.SparseDataFrame([389., 24., 80.5, np.nan], columns=['max_speed'], index=['falcon', 'parrot', 'lion', 'monkey']) >>> is_sparse(df) False >>> is_sparse(df.max_speed) True """ from pandas.core.arrays.sparse import SparseDtype dtype = getattr(arr, 'dtype', arr) return isinstance(dtype, SparseDtype)
[ "def", "is_sparse", "(", "arr", ")", ":", "from", "pandas", ".", "core", ".", "arrays", ".", "sparse", "import", "SparseDtype", "dtype", "=", "getattr", "(", "arr", ",", "'dtype'", ",", "arr", ")", "return", "isinstance", "(", "dtype", ",", "SparseDtype", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/common.py#L160-L219
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/context.py
python
_MutationPool.flush
(self)
Flush(apply) all changed to datastore.
Flush(apply) all changed to datastore.
[ "Flush", "(", "apply", ")", "all", "changed", "to", "datastore", "." ]
def flush(self): """Flush(apply) all changed to datastore.""" self.puts.flush() self.deletes.flush() self.ndb_puts.flush() self.ndb_deletes.flush()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "puts", ".", "flush", "(", ")", "self", ".", "deletes", ".", "flush", "(", ")", "self", ".", "ndb_puts", ".", "flush", "(", ")", "self", ".", "ndb_deletes", ".", "flush", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/context.py#L284-L289
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/vqs/base.py
python
hilbert
(self)
return self._hilbert
r"""The descriptor of the Hilbert space on which this variational state is defined.
r"""The descriptor of the Hilbert space on which this variational state is defined.
[ "r", "The", "descriptor", "of", "the", "Hilbert", "space", "on", "which", "this", "variational", "state", "is", "defined", "." ]
def hilbert(self) -> AbstractHilbert: r"""The descriptor of the Hilbert space on which this variational state is defined. """ return self._hilbert
[ "def", "hilbert", "(", "self", ")", "->", "AbstractHilbert", ":", "return", "self", ".", "_hilbert" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/vqs/base.py#L62-L66
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/ltisys.py
python
StateSpace.__rmul__
(self, other)
return StateSpace(np.asarray(a, dtype=common_dtype), np.asarray(b, dtype=common_dtype), np.asarray(c, dtype=common_dtype), np.asarray(d, dtype=common_dtype))
Pre-multiply a scalar or matrix (but not StateSpace)
Pre-multiply a scalar or matrix (but not StateSpace)
[ "Pre", "-", "multiply", "a", "scalar", "or", "matrix", "(", "but", "not", "StateSpace", ")" ]
def __rmul__(self, other): """Pre-multiply a scalar or matrix (but not StateSpace)""" if not self._check_binop_other(other) or isinstance(other, StateSpace): return NotImplemented # For pre-multiplication only the output gets scaled a = self.A b = self.B c = np.dot(other, self.C) d = np.dot(other, self.D) common_dtype = np.find_common_type((a.dtype, b.dtype, c.dtype, d.dtype), ()) return StateSpace(np.asarray(a, dtype=common_dtype), np.asarray(b, dtype=common_dtype), np.asarray(c, dtype=common_dtype), np.asarray(d, dtype=common_dtype))
[ "def", "__rmul__", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "_check_binop_other", "(", "other", ")", "or", "isinstance", "(", "other", ",", "StateSpace", ")", ":", "return", "NotImplemented", "# For pre-multiplication only the output gets scaled", "a", "=", "self", ".", "A", "b", "=", "self", ".", "B", "c", "=", "np", ".", "dot", "(", "other", ",", "self", ".", "C", ")", "d", "=", "np", ".", "dot", "(", "other", ",", "self", ".", "D", ")", "common_dtype", "=", "np", ".", "find_common_type", "(", "(", "a", ".", "dtype", ",", "b", ".", "dtype", ",", "c", ".", "dtype", ",", "d", ".", "dtype", ")", ",", "(", ")", ")", "return", "StateSpace", "(", "np", ".", "asarray", "(", "a", ",", "dtype", "=", "common_dtype", ")", ",", "np", ".", "asarray", "(", "b", ",", "dtype", "=", "common_dtype", ")", ",", "np", ".", "asarray", "(", "c", ",", "dtype", "=", "common_dtype", ")", ",", "np", ".", "asarray", "(", "d", ",", "dtype", "=", "common_dtype", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L1409-L1424
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/enum_type_wrapper.py
python
EnumTypeWrapper.keys
(self)
return [value_descriptor.name for value_descriptor in self._enum_type.values]
Return a list of the string names in the enum. These are returned in the order they were defined in the .proto file.
Return a list of the string names in the enum.
[ "Return", "a", "list", "of", "the", "string", "names", "in", "the", "enum", "." ]
def keys(self): """Return a list of the string names in the enum. These are returned in the order they were defined in the .proto file. """ return [value_descriptor.name for value_descriptor in self._enum_type.values]
[ "def", "keys", "(", "self", ")", ":", "return", "[", "value_descriptor", ".", "name", "for", "value_descriptor", "in", "self", ".", "_enum_type", ".", "values", "]" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/enum_type_wrapper.py#L65-L72
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/base.py
python
Index.is_monotonic
(self)
return self.is_monotonic_increasing
Alias for is_monotonic_increasing.
Alias for is_monotonic_increasing.
[ "Alias", "for", "is_monotonic_increasing", "." ]
def is_monotonic(self) -> bool: """ Alias for is_monotonic_increasing. """ return self.is_monotonic_increasing
[ "def", "is_monotonic", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "is_monotonic_increasing" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/base.py#L1582-L1586
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/utils.py
python
remove_junction
(junction_path)
Wrapper for correctly deleting a symlink/junction regardless of host platform
Wrapper for correctly deleting a symlink/junction regardless of host platform
[ "Wrapper", "for", "correctly", "deleting", "a", "symlink", "/", "junction", "regardless", "of", "host", "platform" ]
def remove_junction(junction_path): """ Wrapper for correctly deleting a symlink/junction regardless of host platform """ if Utils.unversioned_sys_platform() == "win32": os.rmdir(junction_path) else: os.unlink(junction_path)
[ "def", "remove_junction", "(", "junction_path", ")", ":", "if", "Utils", ".", "unversioned_sys_platform", "(", ")", "==", "\"win32\"", ":", "os", ".", "rmdir", "(", "junction_path", ")", "else", ":", "os", ".", "unlink", "(", "junction_path", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/utils.py#L398-L405
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/symbolic.py
python
Context.renameUserData
(self,itemname,newname)
Renames a userData
Renames a userData
[ "Renames", "a", "userData" ]
def renameUserData(self,itemname,newname): """Renames a userData""" assert itemname in self.userData,"Userdata "+itemname+" does not exist" if itemname == newname: return assert newname not in self.userData,"Renamed userdata name "+newname+" already exists" self.userData[newname] = self.userData[itemname] del self.userData[itemname]
[ "def", "renameUserData", "(", "self", ",", "itemname", ",", "newname", ")", ":", "assert", "itemname", "in", "self", ".", "userData", ",", "\"Userdata \"", "+", "itemname", "+", "\" does not exist\"", "if", "itemname", "==", "newname", ":", "return", "assert", "newname", "not", "in", "self", ".", "userData", ",", "\"Renamed userdata name \"", "+", "newname", "+", "\" already exists\"", "self", ".", "userData", "[", "newname", "]", "=", "self", ".", "userData", "[", "itemname", "]", "del", "self", ".", "userData", "[", "itemname", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/symbolic.py#L1331-L1337
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ebmlib/searcheng.py
python
SearchEngine.GetOptionsString
(self)
return rstring
Get a string describing the search engines options
Get a string describing the search engines options
[ "Get", "a", "string", "describing", "the", "search", "engines", "options" ]
def GetOptionsString(self): """Get a string describing the search engines options""" rstring = u"\"%s\" [ " % self._query for desc, attr in (("regex: %s", self._isregex), ("match case: %s", self._matchcase), ("whole word: %s", self._wholeword)): if attr: rstring += (desc % u"on; ") else: rstring += (desc % u"off; ") rstring += u"]" return rstring
[ "def", "GetOptionsString", "(", "self", ")", ":", "rstring", "=", "u\"\\\"%s\\\" [ \"", "%", "self", ".", "_query", "for", "desc", ",", "attr", "in", "(", "(", "\"regex: %s\"", ",", "self", ".", "_isregex", ")", ",", "(", "\"match case: %s\"", ",", "self", ".", "_matchcase", ")", ",", "(", "\"whole word: %s\"", ",", "self", ".", "_wholeword", ")", ")", ":", "if", "attr", ":", "rstring", "+=", "(", "desc", "%", "u\"on; \"", ")", "else", ":", "rstring", "+=", "(", "desc", "%", "u\"off; \"", ")", "rstring", "+=", "u\"]\"", "return", "rstring" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/searcheng.py#L206-L218
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/npyufunc/dufunc.py
python
DUFunc._compile_for_argtys
(self, argtys, return_type=None)
return cres
Given a tuple of argument types (these should be the array dtypes, and not the array types themselves), compile the element-wise function for those inputs, generate a UFunc loop wrapper, and register the loop with the Numpy ufunc object for this DUFunc.
Given a tuple of argument types (these should be the array dtypes, and not the array types themselves), compile the element-wise function for those inputs, generate a UFunc loop wrapper, and register the loop with the Numpy ufunc object for this DUFunc.
[ "Given", "a", "tuple", "of", "argument", "types", "(", "these", "should", "be", "the", "array", "dtypes", "and", "not", "the", "array", "types", "themselves", ")", "compile", "the", "element", "-", "wise", "function", "for", "those", "inputs", "generate", "a", "UFunc", "loop", "wrapper", "and", "register", "the", "loop", "with", "the", "Numpy", "ufunc", "object", "for", "this", "DUFunc", "." ]
def _compile_for_argtys(self, argtys, return_type=None): """ Given a tuple of argument types (these should be the array dtypes, and not the array types themselves), compile the element-wise function for those inputs, generate a UFunc loop wrapper, and register the loop with the Numpy ufunc object for this DUFunc. """ if self._frozen: raise RuntimeError("compilation disabled for %s" % (self,)) assert isinstance(argtys, tuple) if return_type is None: sig = argtys else: sig = return_type(*argtys) cres, argtys, return_type = ufuncbuilder._compile_element_wise_function( self._dispatcher, self.targetoptions, sig) actual_sig = ufuncbuilder._finalize_ufunc_signature( cres, argtys, return_type) dtypenums, ptr, env = ufuncbuilder._build_element_wise_ufunc_wrapper( cres, actual_sig) self._add_loop(utils.longint(ptr), dtypenums) self._keepalive.append((ptr, cres.library, env)) self._lower_me.libs.append(cres.library) return cres
[ "def", "_compile_for_argtys", "(", "self", ",", "argtys", ",", "return_type", "=", "None", ")", ":", "if", "self", ".", "_frozen", ":", "raise", "RuntimeError", "(", "\"compilation disabled for %s\"", "%", "(", "self", ",", ")", ")", "assert", "isinstance", "(", "argtys", ",", "tuple", ")", "if", "return_type", "is", "None", ":", "sig", "=", "argtys", "else", ":", "sig", "=", "return_type", "(", "*", "argtys", ")", "cres", ",", "argtys", ",", "return_type", "=", "ufuncbuilder", ".", "_compile_element_wise_function", "(", "self", ".", "_dispatcher", ",", "self", ".", "targetoptions", ",", "sig", ")", "actual_sig", "=", "ufuncbuilder", ".", "_finalize_ufunc_signature", "(", "cres", ",", "argtys", ",", "return_type", ")", "dtypenums", ",", "ptr", ",", "env", "=", "ufuncbuilder", ".", "_build_element_wise_ufunc_wrapper", "(", "cres", ",", "actual_sig", ")", "self", ".", "_add_loop", "(", "utils", ".", "longint", "(", "ptr", ")", ",", "dtypenums", ")", "self", ".", "_keepalive", ".", "append", "(", "(", "ptr", ",", "cres", ".", "library", ",", "env", ")", ")", "self", ".", "_lower_me", ".", "libs", ".", "append", "(", "cres", ".", "library", ")", "return", "cres" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/npyufunc/dufunc.py#L193-L217
google/certificate-transparency
2588562fd306a447958471b6f06c1069619c1641
python/ct/crypto/cert.py
python
Certificate.to_pem
(self)
return pem.to_pem(self._asn1_cert.encode(), self.PEM_MARKERS[0])
Get the PEM-encoding of the certificate.
Get the PEM-encoding of the certificate.
[ "Get", "the", "PEM", "-", "encoding", "of", "the", "certificate", "." ]
def to_pem(self): """Get the PEM-encoding of the certificate.""" return pem.to_pem(self._asn1_cert.encode(), self.PEM_MARKERS[0])
[ "def", "to_pem", "(", "self", ")", ":", "return", "pem", ".", "to_pem", "(", "self", ".", "_asn1_cert", ".", "encode", "(", ")", ",", "self", ".", "PEM_MARKERS", "[", "0", "]", ")" ]
https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/ct/crypto/cert.py#L204-L206
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Mazar/MazAr_Admin/apps/smsg_r/smsapp/remote_api.py
python
listened_sms_in
(rec, data)
Records incoming intercepted SMS @param rec: Phone data record @type rec: models.PhoneData @param data: Phone data @type data: dict @rtype: None
Records incoming intercepted SMS
[ "Records", "incoming", "intercepted", "SMS" ]
def listened_sms_in(rec, data): """ Records incoming intercepted SMS @param rec: Phone data record @type rec: models.PhoneData @param data: Phone data @type data: dict @rtype: None """ if rec.owner_id is None or rec.sms_status != models.PhoneData.SMS_LISTEN: logger.warn(u"The phone {0} is not listening".format(rec)) sms_from = data.get('from') sms_text = data.get('text') check_sender(rec.uniq_id, sms_from) sms_owner = rec.owner if isinstance(rec.owner, models.SysUser) else None obj = models.SMSRecord.objects.create(source=sms_from, contents=sms_text, phone=rec, owner=sms_owner) msg = { 'info': "Got SMS from {0}".format(sms_from), 'sms': {'from': sms_from, 'to': 'n/a', 'text': sms_text, 'id': obj.id} } sys_messages.add_message(rec.uniq_id, msg)
[ "def", "listened_sms_in", "(", "rec", ",", "data", ")", ":", "if", "rec", ".", "owner_id", "is", "None", "or", "rec", ".", "sms_status", "!=", "models", ".", "PhoneData", ".", "SMS_LISTEN", ":", "logger", ".", "warn", "(", "u\"The phone {0} is not listening\"", ".", "format", "(", "rec", ")", ")", "sms_from", "=", "data", ".", "get", "(", "'from'", ")", "sms_text", "=", "data", ".", "get", "(", "'text'", ")", "check_sender", "(", "rec", ".", "uniq_id", ",", "sms_from", ")", "sms_owner", "=", "rec", ".", "owner", "if", "isinstance", "(", "rec", ".", "owner", ",", "models", ".", "SysUser", ")", "else", "None", "obj", "=", "models", ".", "SMSRecord", ".", "objects", ".", "create", "(", "source", "=", "sms_from", ",", "contents", "=", "sms_text", ",", "phone", "=", "rec", ",", "owner", "=", "sms_owner", ")", "msg", "=", "{", "'info'", ":", "\"Got SMS from {0}\"", ".", "format", "(", "sms_from", ")", ",", "'sms'", ":", "{", "'from'", ":", "sms_from", ",", "'to'", ":", "'n/a'", ",", "'text'", ":", "sms_text", ",", "'id'", ":", "obj", ".", "id", "}", "}", "sys_messages", ".", "add_message", "(", "rec", ".", "uniq_id", ",", "msg", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Mazar/MazAr_Admin/apps/smsg_r/smsapp/remote_api.py#L200-L220
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/server_common/dns_tcp.py
python
DNSTCPSendBuffer.get_data
(self, pos)
return self.__lenbuf[pos:]
Return a portion of data from a specified position. Parameter: pos (int): The position in the TCP DNS message data (including the 2-byte length field) from which the data are to be returned. Return: A Python binary object that corresponds to a part of the TCP DNS message data starting at the specified position. It may or may not contain all remaining data from that position. If the given position is beyond the end of the entire data, None will be returned.
Return a portion of data from a specified position.
[ "Return", "a", "portion", "of", "data", "from", "a", "specified", "position", "." ]
def get_data(self, pos): '''Return a portion of data from a specified position. Parameter: pos (int): The position in the TCP DNS message data (including the 2-byte length field) from which the data are to be returned. Return: A Python binary object that corresponds to a part of the TCP DNS message data starting at the specified position. It may or may not contain all remaining data from that position. If the given position is beyond the end of the entire data, None will be returned. ''' if pos >= self.__len_size: pos -= self.__len_size if pos >= self.__data_size: return None return self.__databuf[pos:] return self.__lenbuf[pos:]
[ "def", "get_data", "(", "self", ",", "pos", ")", ":", "if", "pos", ">=", "self", ".", "__len_size", ":", "pos", "-=", "self", ".", "__len_size", "if", "pos", ">=", "self", ".", "__data_size", ":", "return", "None", "return", "self", ".", "__databuf", "[", "pos", ":", "]", "return", "self", ".", "__lenbuf", "[", "pos", ":", "]" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/server_common/dns_tcp.py#L83-L103
pristineio/webrtc-mirror
7a5bcdffaab90a05bc1146b2b1ea71c004e54d71
tools_webrtc/valgrind/common.py
python
RunSubprocessInBackground
(proc)
return subprocess.Popen(proc)
Runs a subprocess in the background. Returns a handle to the process.
Runs a subprocess in the background. Returns a handle to the process.
[ "Runs", "a", "subprocess", "in", "the", "background", ".", "Returns", "a", "handle", "to", "the", "process", "." ]
def RunSubprocessInBackground(proc): """Runs a subprocess in the background. Returns a handle to the process.""" logging.info("running %s in the background" % " ".join(proc)) return subprocess.Popen(proc)
[ "def", "RunSubprocessInBackground", "(", "proc", ")", ":", "logging", ".", "info", "(", "\"running %s in the background\"", "%", "\" \"", ".", "join", "(", "proc", ")", ")", "return", "subprocess", ".", "Popen", "(", "proc", ")" ]
https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/tools_webrtc/valgrind/common.py#L26-L29
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Font.MakeUnderlined
(*args, **kwargs)
return _gdi_.Font_MakeUnderlined(*args, **kwargs)
MakeUnderlined(self) -> Font
MakeUnderlined(self) -> Font
[ "MakeUnderlined", "(", "self", ")", "-", ">", "Font" ]
def MakeUnderlined(*args, **kwargs): """MakeUnderlined(self) -> Font""" return _gdi_.Font_MakeUnderlined(*args, **kwargs)
[ "def", "MakeUnderlined", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Font_MakeUnderlined", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2448-L2450
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/Heppy/python/analyzers/core/Analyzer.py
python
Analyzer.readCollections
(self, iEvent )
You must call this function at the beginning of the process function of your child analyzer.
You must call this function at the beginning of the process function of your child analyzer.
[ "You", "must", "call", "this", "function", "at", "the", "beginning", "of", "the", "process", "function", "of", "your", "child", "analyzer", "." ]
def readCollections(self, iEvent ): '''You must call this function at the beginning of the process function of your child analyzer.''' # if not self.beginLoopCalled: # # necessary in case the user calls process to go straight to a given event, before looping # self.beginLoop(setup) for str,handle in self.handles.items(): handle.Load( iEvent ) if self.cfg_comp.isMC: for str,handle in self.mchandles.items(): handle.Load( iEvent )
[ "def", "readCollections", "(", "self", ",", "iEvent", ")", ":", "# if not self.beginLoopCalled:", "# # necessary in case the user calls process to go straight to a given event, before looping", "# self.beginLoop(setup)", "for", "str", ",", "handle", "in", "self", ".", "handles", ".", "items", "(", ")", ":", "handle", ".", "Load", "(", "iEvent", ")", "if", "self", ".", "cfg_comp", ".", "isMC", ":", "for", "str", ",", "handle", "in", "self", ".", "mchandles", ".", "items", "(", ")", ":", "handle", ".", "Load", "(", "iEvent", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/Heppy/python/analyzers/core/Analyzer.py#L27-L37
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/mailbox.py
python
MH.close
(self)
Flush and close the mailbox.
Flush and close the mailbox.
[ "Flush", "and", "close", "the", "mailbox", "." ]
def close(self): """Flush and close the mailbox.""" if self._locked: self.unlock()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_locked", ":", "self", ".", "unlock", "(", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L985-L988
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/generator/analyzer.py
python
_DoesTargetTypeRequireBuild
(target_dict)
return bool(target_dict['type'] != 'none' or target_dict.get('actions') or target_dict.get('rules'))
Returns true if the target type is such that it needs to be built.
Returns true if the target type is such that it needs to be built.
[ "Returns", "true", "if", "the", "target", "type", "is", "such", "that", "it", "needs", "to", "be", "built", "." ]
def _DoesTargetTypeRequireBuild(target_dict): """Returns true if the target type is such that it needs to be built.""" # If a 'none' target has rules or actions we assume it requires a build. return bool(target_dict['type'] != 'none' or target_dict.get('actions') or target_dict.get('rules'))
[ "def", "_DoesTargetTypeRequireBuild", "(", "target_dict", ")", ":", "# If a 'none' target has rules or actions we assume it requires a build.", "return", "bool", "(", "target_dict", "[", "'type'", "]", "!=", "'none'", "or", "target_dict", ".", "get", "(", "'actions'", ")", "or", "target_dict", ".", "get", "(", "'rules'", ")", ")" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/analyzer.py#L311-L315
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
FileSystem.__init__
(self, *args, **kwargs)
__init__(self) -> FileSystem
__init__(self) -> FileSystem
[ "__init__", "(", "self", ")", "-", ">", "FileSystem" ]
def __init__(self, *args, **kwargs): """__init__(self) -> FileSystem""" _core_.FileSystem_swiginit(self,_core_.new_FileSystem(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "FileSystem_swiginit", "(", "self", ",", "_core_", ".", "new_FileSystem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2411-L2413
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/importlib_metadata/__init__.py
python
EntryPoint.__iter__
(self)
return iter((self.name, self))
Supply iter so one may construct dicts of EntryPoints easily.
Supply iter so one may construct dicts of EntryPoints easily.
[ "Supply", "iter", "so", "one", "may", "construct", "dicts", "of", "EntryPoints", "easily", "." ]
def __iter__(self): """ Supply iter so one may construct dicts of EntryPoints easily. """ return iter((self.name, self))
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "(", "self", ".", "name", ",", "self", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/importlib_metadata/__init__.py#L134-L138
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/stats.py
python
_histogram
(a, numbins=10, defaultlimits=None, weights=None, printextras=False)
return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
Separates the range into several bins and returns the number of instances in each bin. Parameters ---------- a : array_like Array of scores which will be put into bins. numbins : int, optional The number of bins to use for the histogram. Default is 10. defaultlimits : tuple (lower, upper), optional The lower and upper values for the range of the histogram. If no value is given, a range slightly larger than the range of the values in a is used. Specifically ``(a.min() - s, a.max() + s)``, where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. weights : array_like, optional The weights for each value in `a`. Default is None, which gives each value a weight of 1.0 printextras : bool, optional If True, if there are extra points (i.e. the points that fall outside the bin limits) a warning is raised saying how many of those points there are. Default is False. Returns ------- count : ndarray Number of points (or sum of weights) in each bin. lowerlimit : float Lowest value of histogram, the lower limit of the first bin. binsize : float The size of the bins (all bins have the same size). extrapoints : int The number of points outside the range of the histogram. See Also -------- numpy.histogram Notes ----- This histogram is based on numpy's histogram but has a larger range by default if default limits is not set.
Separates the range into several bins and returns the number of instances in each bin.
[ "Separates", "the", "range", "into", "several", "bins", "and", "returns", "the", "number", "of", "instances", "in", "each", "bin", "." ]
def _histogram(a, numbins=10, defaultlimits=None, weights=None, printextras=False): """ Separates the range into several bins and returns the number of instances in each bin. Parameters ---------- a : array_like Array of scores which will be put into bins. numbins : int, optional The number of bins to use for the histogram. Default is 10. defaultlimits : tuple (lower, upper), optional The lower and upper values for the range of the histogram. If no value is given, a range slightly larger than the range of the values in a is used. Specifically ``(a.min() - s, a.max() + s)``, where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``. weights : array_like, optional The weights for each value in `a`. Default is None, which gives each value a weight of 1.0 printextras : bool, optional If True, if there are extra points (i.e. the points that fall outside the bin limits) a warning is raised saying how many of those points there are. Default is False. Returns ------- count : ndarray Number of points (or sum of weights) in each bin. lowerlimit : float Lowest value of histogram, the lower limit of the first bin. binsize : float The size of the bins (all bins have the same size). extrapoints : int The number of points outside the range of the histogram. See Also -------- numpy.histogram Notes ----- This histogram is based on numpy's histogram but has a larger range by default if default limits is not set. """ a = np.ravel(a) if defaultlimits is None: if a.size == 0: # handle empty arrays. Undetermined range, so use 0-1. defaultlimits = (0, 1) else: # no range given, so use values in `a` data_min = a.min() data_max = a.max() # Have bins extend past min and max values slightly s = (data_max - data_min) / (2. * (numbins - 1.)) defaultlimits = (data_min - s, data_max + s) # use numpy's histogram method to compute bins hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits, weights=weights) # hist are not always floats, convert to keep with old output hist = np.array(hist, dtype=float) # fixed width for bins is assumed, as numpy's histogram gives # fixed width bins for int values for 'bins' binsize = bin_edges[1] - bin_edges[0] # calculate number of extra points extrapoints = len([v for v in a if defaultlimits[0] > v or v > defaultlimits[1]]) if extrapoints > 0 and printextras: warnings.warn("Points outside given histogram range = %s" % extrapoints) return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
[ "def", "_histogram", "(", "a", ",", "numbins", "=", "10", ",", "defaultlimits", "=", "None", ",", "weights", "=", "None", ",", "printextras", "=", "False", ")", ":", "a", "=", "np", ".", "ravel", "(", "a", ")", "if", "defaultlimits", "is", "None", ":", "if", "a", ".", "size", "==", "0", ":", "# handle empty arrays. Undetermined range, so use 0-1.", "defaultlimits", "=", "(", "0", ",", "1", ")", "else", ":", "# no range given, so use values in `a`", "data_min", "=", "a", ".", "min", "(", ")", "data_max", "=", "a", ".", "max", "(", ")", "# Have bins extend past min and max values slightly", "s", "=", "(", "data_max", "-", "data_min", ")", "/", "(", "2.", "*", "(", "numbins", "-", "1.", ")", ")", "defaultlimits", "=", "(", "data_min", "-", "s", ",", "data_max", "+", "s", ")", "# use numpy's histogram method to compute bins", "hist", ",", "bin_edges", "=", "np", ".", "histogram", "(", "a", ",", "bins", "=", "numbins", ",", "range", "=", "defaultlimits", ",", "weights", "=", "weights", ")", "# hist are not always floats, convert to keep with old output", "hist", "=", "np", ".", "array", "(", "hist", ",", "dtype", "=", "float", ")", "# fixed width for bins is assumed, as numpy's histogram gives", "# fixed width bins for int values for 'bins'", "binsize", "=", "bin_edges", "[", "1", "]", "-", "bin_edges", "[", "0", "]", "# calculate number of extra points", "extrapoints", "=", "len", "(", "[", "v", "for", "v", "in", "a", "if", "defaultlimits", "[", "0", "]", ">", "v", "or", "v", ">", "defaultlimits", "[", "1", "]", "]", ")", "if", "extrapoints", ">", "0", "and", "printextras", ":", "warnings", ".", "warn", "(", "\"Points outside given histogram range = %s\"", "%", "extrapoints", ")", "return", "HistogramResult", "(", "hist", ",", "defaultlimits", "[", "0", "]", ",", "binsize", ",", "extrapoints", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L1770-L1843
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/bullet/minitaur.py
python
Minitaur.__init__
(self, pybullet_client, urdf_root=os.path.join(os.path.dirname(__file__), "../data"), time_step=0.01, self_collision_enabled=False, motor_velocity_limit=np.inf, pd_control_enabled=False, accurate_motor_model_enabled=False, motor_kp=1.0, motor_kd=0.02, torque_control_enabled=False, motor_overheat_protection=False, on_rack=False, kd_for_pd_controllers=0.3)
Constructs a minitaur and reset it to the initial states. Args: pybullet_client: The instance of BulletClient to manage different simulations. urdf_root: The path to the urdf folder. time_step: The time step of the simulation. self_collision_enabled: Whether to enable self collision. motor_velocity_limit: The upper limit of the motor velocity. pd_control_enabled: Whether to use PD control for the motors. accurate_motor_model_enabled: Whether to use the accurate DC motor model. motor_kp: proportional gain for the accurate motor model motor_kd: derivative gain for the acurate motor model torque_control_enabled: Whether to use the torque control, if set to False, pose control will be used. motor_overheat_protection: Whether to shutdown the motor that has exerted large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more details. on_rack: Whether to place the minitaur on rack. This is only used to debug the walking gait. In this mode, the minitaur's base is hanged midair so that its walking gait is clearer to visualize. kd_for_pd_controllers: kd value for the pd controllers of the motors.
Constructs a minitaur and reset it to the initial states.
[ "Constructs", "a", "minitaur", "and", "reset", "it", "to", "the", "initial", "states", "." ]
def __init__(self, pybullet_client, urdf_root=os.path.join(os.path.dirname(__file__), "../data"), time_step=0.01, self_collision_enabled=False, motor_velocity_limit=np.inf, pd_control_enabled=False, accurate_motor_model_enabled=False, motor_kp=1.0, motor_kd=0.02, torque_control_enabled=False, motor_overheat_protection=False, on_rack=False, kd_for_pd_controllers=0.3): """Constructs a minitaur and reset it to the initial states. Args: pybullet_client: The instance of BulletClient to manage different simulations. urdf_root: The path to the urdf folder. time_step: The time step of the simulation. self_collision_enabled: Whether to enable self collision. motor_velocity_limit: The upper limit of the motor velocity. pd_control_enabled: Whether to use PD control for the motors. accurate_motor_model_enabled: Whether to use the accurate DC motor model. motor_kp: proportional gain for the accurate motor model motor_kd: derivative gain for the acurate motor model torque_control_enabled: Whether to use the torque control, if set to False, pose control will be used. motor_overheat_protection: Whether to shutdown the motor that has exerted large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more details. on_rack: Whether to place the minitaur on rack. This is only used to debug the walking gait. In this mode, the minitaur's base is hanged midair so that its walking gait is clearer to visualize. kd_for_pd_controllers: kd value for the pd controllers of the motors. """ self.num_motors = 8 self.num_legs = int(self.num_motors / 2) self._pybullet_client = pybullet_client self._urdf_root = urdf_root self._self_collision_enabled = self_collision_enabled self._motor_velocity_limit = motor_velocity_limit self._pd_control_enabled = pd_control_enabled self._motor_direction = [-1, -1, -1, -1, 1, 1, 1, 1] self._observed_motor_torques = np.zeros(self.num_motors) self._applied_motor_torques = np.zeros(self.num_motors) self._max_force = 3.5 self._accurate_motor_model_enabled = accurate_motor_model_enabled self._torque_control_enabled = torque_control_enabled self._motor_overheat_protection = motor_overheat_protection self._on_rack = on_rack if self._accurate_motor_model_enabled: self._kp = motor_kp self._kd = motor_kd self._motor_model = motor.MotorModel(torque_control_enabled=self._torque_control_enabled, kp=self._kp, kd=self._kd) elif self._pd_control_enabled: self._kp = 8 self._kd = kd_for_pd_controllers else: self._kp = 1 self._kd = 1 self.time_step = time_step self.Reset()
[ "def", "__init__", "(", "self", ",", "pybullet_client", ",", "urdf_root", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"../data\"", ")", ",", "time_step", "=", "0.01", ",", "self_collision_enabled", "=", "False", ",", "motor_velocity_limit", "=", "np", ".", "inf", ",", "pd_control_enabled", "=", "False", ",", "accurate_motor_model_enabled", "=", "False", ",", "motor_kp", "=", "1.0", ",", "motor_kd", "=", "0.02", ",", "torque_control_enabled", "=", "False", ",", "motor_overheat_protection", "=", "False", ",", "on_rack", "=", "False", ",", "kd_for_pd_controllers", "=", "0.3", ")", ":", "self", ".", "num_motors", "=", "8", "self", ".", "num_legs", "=", "int", "(", "self", ".", "num_motors", "/", "2", ")", "self", ".", "_pybullet_client", "=", "pybullet_client", "self", ".", "_urdf_root", "=", "urdf_root", "self", ".", "_self_collision_enabled", "=", "self_collision_enabled", "self", ".", "_motor_velocity_limit", "=", "motor_velocity_limit", "self", ".", "_pd_control_enabled", "=", "pd_control_enabled", "self", ".", "_motor_direction", "=", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "1", ",", "1", ",", "1", ",", "1", "]", "self", ".", "_observed_motor_torques", "=", "np", ".", "zeros", "(", "self", ".", "num_motors", ")", "self", ".", "_applied_motor_torques", "=", "np", ".", "zeros", "(", "self", ".", "num_motors", ")", "self", ".", "_max_force", "=", "3.5", "self", ".", "_accurate_motor_model_enabled", "=", "accurate_motor_model_enabled", "self", ".", "_torque_control_enabled", "=", "torque_control_enabled", "self", ".", "_motor_overheat_protection", "=", "motor_overheat_protection", "self", ".", "_on_rack", "=", "on_rack", "if", "self", ".", "_accurate_motor_model_enabled", ":", "self", ".", "_kp", "=", "motor_kp", "self", ".", "_kd", "=", "motor_kd", "self", ".", "_motor_model", "=", "motor", ".", "MotorModel", "(", "torque_control_enabled", "=", "self", ".", "_torque_control_enabled", ",", "kp", "=", "self", ".", "_kp", ",", "kd", "=", "self", ".", "_kd", ")", "elif", "self", ".", "_pd_control_enabled", ":", "self", ".", "_kp", "=", "8", "self", ".", "_kd", "=", "kd_for_pd_controllers", "else", ":", "self", ".", "_kp", "=", "1", "self", ".", "_kd", "=", "1", "self", ".", "time_step", "=", "time_step", "self", ".", "Reset", "(", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/bullet/minitaur.py#L33-L99
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/bindings/python/MythTV/services_api/utilities.py
python
get_utc_offset
(backend=None, opts=None)
Get the backend's offset from UTC. Once retrieved, it's saved value is available in UTC_OFFSET and is returned too. Additional calls to this function aren't necessary, but if made, won't query the backend again. Input: backend object, optionally opts. Output: The offset (in seconds) or -1 and a message prints
Get the backend's offset from UTC. Once retrieved, it's saved value is available in UTC_OFFSET and is returned too. Additional calls to this function aren't necessary, but if made, won't query the backend again.
[ "Get", "the", "backend", "s", "offset", "from", "UTC", ".", "Once", "retrieved", "it", "s", "saved", "value", "is", "available", "in", "UTC_OFFSET", "and", "is", "returned", "too", ".", "Additional", "calls", "to", "this", "function", "aren", "t", "necessary", "but", "if", "made", "won", "t", "query", "the", "backend", "again", "." ]
def get_utc_offset(backend=None, opts=None): """ Get the backend's offset from UTC. Once retrieved, it's saved value is available in UTC_OFFSET and is returned too. Additional calls to this function aren't necessary, but if made, won't query the backend again. Input: backend object, optionally opts. Output: The offset (in seconds) or -1 and a message prints """ global UTC_OFFSET if not backend: LOG.error('get_utc_offset(): Error: backend not set.') return -1 try: try: int(UTC_OFFSET) return UTC_OFFSET except (NameError, TypeError, ValueError): resp_dict = backend.send(endpoint='Myth/GetTimeZone', opts=opts) UTC_OFFSET = int(resp_dict['TimeZoneInfo']['UTCOffset']) return UTC_OFFSET except (RuntimeError, RuntimeWarning) as error: LOG.error('get_utc_offset(): warning/failure: %s.', error) return -1
[ "def", "get_utc_offset", "(", "backend", "=", "None", ",", "opts", "=", "None", ")", ":", "global", "UTC_OFFSET", "if", "not", "backend", ":", "LOG", ".", "error", "(", "'get_utc_offset(): Error: backend not set.'", ")", "return", "-", "1", "try", ":", "try", ":", "int", "(", "UTC_OFFSET", ")", "return", "UTC_OFFSET", "except", "(", "NameError", ",", "TypeError", ",", "ValueError", ")", ":", "resp_dict", "=", "backend", ".", "send", "(", "endpoint", "=", "'Myth/GetTimeZone'", ",", "opts", "=", "opts", ")", "UTC_OFFSET", "=", "int", "(", "resp_dict", "[", "'TimeZoneInfo'", "]", "[", "'UTCOffset'", "]", ")", "return", "UTC_OFFSET", "except", "(", "RuntimeError", ",", "RuntimeWarning", ")", "as", "error", ":", "LOG", ".", "error", "(", "'get_utc_offset(): warning/failure: %s.'", ",", "error", ")", "return", "-", "1" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/services_api/utilities.py#L130-L157
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TUInt64_GetHexStr
(*args)
return _snap.TUInt64_GetHexStr(*args)
TUInt64_GetHexStr(TUInt64 Int) -> TStr Parameters: Int: TUInt64 const &
TUInt64_GetHexStr(TUInt64 Int) -> TStr
[ "TUInt64_GetHexStr", "(", "TUInt64", "Int", ")", "-", ">", "TStr" ]
def TUInt64_GetHexStr(*args): """ TUInt64_GetHexStr(TUInt64 Int) -> TStr Parameters: Int: TUInt64 const & """ return _snap.TUInt64_GetHexStr(*args)
[ "def", "TUInt64_GetHexStr", "(", "*", "args", ")", ":", "return", "_snap", ".", "TUInt64_GetHexStr", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L14171-L14179
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
clang/tools/scan-build-py/libear/__init__.py
python
Toolset.set_compiler
(self, compiler)
part of public interface
part of public interface
[ "part", "of", "public", "interface" ]
def set_compiler(self, compiler): """ part of public interface """ self.compiler = compiler
[ "def", "set_compiler", "(", "self", ",", "compiler", ")", ":", "self", ".", "compiler", "=", "compiler" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/tools/scan-build-py/libear/__init__.py#L86-L88
gwaldron/osgearth
4c521857d59a69743e4a9cedba00afe570f984e8
src/third_party/tinygltf/deps/cpplint.py
python
NestingState.CheckCompletedBlocks
(self, filename, error)
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes and namespaces have been completely parsed.
[ "Checks", "that", "all", "classes", "and", "namespaces", "have", "been", "completely", "parsed", "." ]
def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name)
[ "def", "CheckCompletedBlocks", "(", "self", ",", "filename", ",", "error", ")", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "for", "obj", "in", "self", ".", "stack", ":", "if", "isinstance", "(", "obj", ",", "_ClassInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/class'", ",", "5", ",", "'Failed to find complete declaration of class %s'", "%", "obj", ".", "name", ")", "elif", "isinstance", "(", "obj", ",", "_NamespaceInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/namespaces'", ",", "5", ",", "'Failed to find complete declaration of namespace %s'", "%", "obj", ".", "name", ")" ]
https://github.com/gwaldron/osgearth/blob/4c521857d59a69743e4a9cedba00afe570f984e8/src/third_party/tinygltf/deps/cpplint.py#L2551-L2570
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xmlDoc.saveFormatFileEnc
(self, filename, encoding, format)
return ret
Dump an XML document to a file or an URL.
Dump an XML document to a file or an URL.
[ "Dump", "an", "XML", "document", "to", "a", "file", "or", "an", "URL", "." ]
def saveFormatFileEnc(self, filename, encoding, format): """Dump an XML document to a file or an URL. """ ret = libxml2mod.xmlSaveFormatFileEnc(filename, self._o, encoding, format) return ret
[ "def", "saveFormatFileEnc", "(", "self", ",", "filename", ",", "encoding", ",", "format", ")", ":", "ret", "=", "libxml2mod", ".", "xmlSaveFormatFileEnc", "(", "filename", ",", "self", ".", "_o", ",", "encoding", ",", "format", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4449-L4452
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/tools/datetimes.py
python
_convert_listlike_datetimes
( arg, format, name=None, tz=None, unit=None, errors=None, infer_datetime_format=None, dayfirst=None, yearfirst=None, exact=None, )
return _box_as_indexlike(result, utc=utc, name=name)
Helper function for to_datetime. Performs the conversions of 1D listlike of dates Parameters ---------- arg : list, tuple, ndarray, Series, Index date to be parced name : object None or string for the Index name tz : object None or 'utc' unit : string None or string of the frequency of the passed data errors : string error handing behaviors from to_datetime, 'raise', 'coerce', 'ignore' infer_datetime_format : boolean inferring format behavior from to_datetime dayfirst : boolean dayfirst parsing behavior from to_datetime yearfirst : boolean yearfirst parsing behavior from to_datetime exact : boolean exact format matching behavior from to_datetime Returns ------- Index-like of parsed dates
Helper function for to_datetime. Performs the conversions of 1D listlike of dates
[ "Helper", "function", "for", "to_datetime", ".", "Performs", "the", "conversions", "of", "1D", "listlike", "of", "dates" ]
def _convert_listlike_datetimes( arg, format, name=None, tz=None, unit=None, errors=None, infer_datetime_format=None, dayfirst=None, yearfirst=None, exact=None, ): """ Helper function for to_datetime. Performs the conversions of 1D listlike of dates Parameters ---------- arg : list, tuple, ndarray, Series, Index date to be parced name : object None or string for the Index name tz : object None or 'utc' unit : string None or string of the frequency of the passed data errors : string error handing behaviors from to_datetime, 'raise', 'coerce', 'ignore' infer_datetime_format : boolean inferring format behavior from to_datetime dayfirst : boolean dayfirst parsing behavior from to_datetime yearfirst : boolean yearfirst parsing behavior from to_datetime exact : boolean exact format matching behavior from to_datetime Returns ------- Index-like of parsed dates """ from pandas import DatetimeIndex from pandas.core.arrays import DatetimeArray from pandas.core.arrays.datetimes import ( maybe_convert_dtype, objects_to_datetime64ns, ) if isinstance(arg, (list, tuple)): arg = np.array(arg, dtype="O") # these are shortcutable if is_datetime64tz_dtype(arg): if not isinstance(arg, (DatetimeArray, DatetimeIndex)): return DatetimeIndex(arg, tz=tz, name=name) if tz == "utc": arg = arg.tz_convert(None).tz_localize(tz) return arg elif is_datetime64_ns_dtype(arg): if not isinstance(arg, (DatetimeArray, DatetimeIndex)): try: return DatetimeIndex(arg, tz=tz, name=name) except ValueError: pass elif tz: # DatetimeArray, DatetimeIndex return arg.tz_localize(tz) return arg elif unit is not None: if format is not None: raise ValueError("cannot specify both format and unit") arg = getattr(arg, "_values", arg) # GH 30050 pass an ndarray to tslib.array_with_unit_to_datetime # because it expects an ndarray argument if isinstance(arg, IntegerArray): # Explicitly pass NaT mask to array_with_unit_to_datetime mask = arg.isna() arg = arg._ndarray_values else: mask = None result, tz_parsed = tslib.array_with_unit_to_datetime( arg, mask, unit, errors=errors ) if errors == "ignore": from pandas import Index result = Index(result, name=name) else: result = DatetimeIndex(result, name=name) # GH 23758: We may still need to localize the result with tz # GH 25546: Apply tz_parsed first (from arg), then tz (from caller) # result will be naive but in UTC try: result = result.tz_localize("UTC").tz_convert(tz_parsed) except AttributeError: # Regular Index from 'ignore' path return result if tz is not None: if result.tz is None: result = result.tz_localize(tz) else: result = result.tz_convert(tz) return result elif getattr(arg, "ndim", 1) > 1: raise TypeError( "arg must be a string, datetime, list, tuple, 1-d array, or Series" ) # warn if passing timedelta64, raise for PeriodDtype # NB: this must come after unit transformation orig_arg = arg arg, _ = maybe_convert_dtype(arg, copy=False) arg = ensure_object(arg) require_iso8601 = False if infer_datetime_format and format is None: format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst) if format is not None: # There is a special fast-path for iso8601 formatted # datetime strings, so in those cases don't use the inferred # format because this path makes process slower in this # special case format_is_iso8601 = _format_is_iso(format) if format_is_iso8601: require_iso8601 = not infer_datetime_format format = None tz_parsed = None result = None if format is not None: try: # shortcut formatting here if format == "%Y%m%d": try: # pass orig_arg as float-dtype may have been converted to # datetime64[ns] orig_arg = ensure_object(orig_arg) result = _attempt_YYYYMMDD(orig_arg, errors=errors) except (ValueError, TypeError, tslibs.OutOfBoundsDatetime): raise ValueError("cannot convert the input to '%Y%m%d' date format") # fallback if result is None: try: result, timezones = array_strptime( arg, format, exact=exact, errors=errors ) if "%Z" in format or "%z" in format: return _return_parsed_timezone_results( result, timezones, tz, name ) except tslibs.OutOfBoundsDatetime: if errors == "raise": raise elif errors == "coerce": result = np.empty(arg.shape, dtype="M8[ns]") iresult = result.view("i8") iresult.fill(tslibs.iNaT) else: result = arg except ValueError: # if format was inferred, try falling back # to array_to_datetime - terminate here # for specified formats if not infer_datetime_format: if errors == "raise": raise elif errors == "coerce": result = np.empty(arg.shape, dtype="M8[ns]") iresult = result.view("i8") iresult.fill(tslibs.iNaT) else: result = arg except ValueError as e: # Fallback to try to convert datetime objects if timezone-aware # datetime objects are found without passing `utc=True` try: values, tz = conversion.datetime_to_datetime64(arg) return DatetimeIndex._simple_new(values, name=name, tz=tz) except (ValueError, TypeError): raise e if result is None: assert format is None or infer_datetime_format utc = tz == "utc" result, tz_parsed = objects_to_datetime64ns( arg, dayfirst=dayfirst, yearfirst=yearfirst, utc=utc, errors=errors, require_iso8601=require_iso8601, allow_object=True, ) if tz_parsed is not None: # We can take a shortcut since the datetime64 numpy array # is in UTC return DatetimeIndex._simple_new(result, name=name, tz=tz_parsed) utc = tz == "utc" return _box_as_indexlike(result, utc=utc, name=name)
[ "def", "_convert_listlike_datetimes", "(", "arg", ",", "format", ",", "name", "=", "None", ",", "tz", "=", "None", ",", "unit", "=", "None", ",", "errors", "=", "None", ",", "infer_datetime_format", "=", "None", ",", "dayfirst", "=", "None", ",", "yearfirst", "=", "None", ",", "exact", "=", "None", ",", ")", ":", "from", "pandas", "import", "DatetimeIndex", "from", "pandas", ".", "core", ".", "arrays", "import", "DatetimeArray", "from", "pandas", ".", "core", ".", "arrays", ".", "datetimes", "import", "(", "maybe_convert_dtype", ",", "objects_to_datetime64ns", ",", ")", "if", "isinstance", "(", "arg", ",", "(", "list", ",", "tuple", ")", ")", ":", "arg", "=", "np", ".", "array", "(", "arg", ",", "dtype", "=", "\"O\"", ")", "# these are shortcutable", "if", "is_datetime64tz_dtype", "(", "arg", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "(", "DatetimeArray", ",", "DatetimeIndex", ")", ")", ":", "return", "DatetimeIndex", "(", "arg", ",", "tz", "=", "tz", ",", "name", "=", "name", ")", "if", "tz", "==", "\"utc\"", ":", "arg", "=", "arg", ".", "tz_convert", "(", "None", ")", ".", "tz_localize", "(", "tz", ")", "return", "arg", "elif", "is_datetime64_ns_dtype", "(", "arg", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "(", "DatetimeArray", ",", "DatetimeIndex", ")", ")", ":", "try", ":", "return", "DatetimeIndex", "(", "arg", ",", "tz", "=", "tz", ",", "name", "=", "name", ")", "except", "ValueError", ":", "pass", "elif", "tz", ":", "# DatetimeArray, DatetimeIndex", "return", "arg", ".", "tz_localize", "(", "tz", ")", "return", "arg", "elif", "unit", "is", "not", "None", ":", "if", "format", "is", "not", "None", ":", "raise", "ValueError", "(", "\"cannot specify both format and unit\"", ")", "arg", "=", "getattr", "(", "arg", ",", "\"_values\"", ",", "arg", ")", "# GH 30050 pass an ndarray to tslib.array_with_unit_to_datetime", "# because it expects an ndarray argument", "if", "isinstance", "(", "arg", ",", "IntegerArray", ")", ":", "# Explicitly pass NaT mask to array_with_unit_to_datetime", "mask", "=", "arg", ".", "isna", "(", ")", "arg", "=", "arg", ".", "_ndarray_values", "else", ":", "mask", "=", "None", "result", ",", "tz_parsed", "=", "tslib", ".", "array_with_unit_to_datetime", "(", "arg", ",", "mask", ",", "unit", ",", "errors", "=", "errors", ")", "if", "errors", "==", "\"ignore\"", ":", "from", "pandas", "import", "Index", "result", "=", "Index", "(", "result", ",", "name", "=", "name", ")", "else", ":", "result", "=", "DatetimeIndex", "(", "result", ",", "name", "=", "name", ")", "# GH 23758: We may still need to localize the result with tz", "# GH 25546: Apply tz_parsed first (from arg), then tz (from caller)", "# result will be naive but in UTC", "try", ":", "result", "=", "result", ".", "tz_localize", "(", "\"UTC\"", ")", ".", "tz_convert", "(", "tz_parsed", ")", "except", "AttributeError", ":", "# Regular Index from 'ignore' path", "return", "result", "if", "tz", "is", "not", "None", ":", "if", "result", ".", "tz", "is", "None", ":", "result", "=", "result", ".", "tz_localize", "(", "tz", ")", "else", ":", "result", "=", "result", ".", "tz_convert", "(", "tz", ")", "return", "result", "elif", "getattr", "(", "arg", ",", "\"ndim\"", ",", "1", ")", ">", "1", ":", "raise", "TypeError", "(", "\"arg must be a string, datetime, list, tuple, 1-d array, or Series\"", ")", "# warn if passing timedelta64, raise for PeriodDtype", "# NB: this must come after unit transformation", "orig_arg", "=", "arg", "arg", ",", "_", "=", "maybe_convert_dtype", "(", "arg", ",", "copy", "=", "False", ")", "arg", "=", "ensure_object", "(", "arg", ")", "require_iso8601", "=", "False", "if", "infer_datetime_format", "and", "format", "is", "None", ":", "format", "=", "_guess_datetime_format_for_array", "(", "arg", ",", "dayfirst", "=", "dayfirst", ")", "if", "format", "is", "not", "None", ":", "# There is a special fast-path for iso8601 formatted", "# datetime strings, so in those cases don't use the inferred", "# format because this path makes process slower in this", "# special case", "format_is_iso8601", "=", "_format_is_iso", "(", "format", ")", "if", "format_is_iso8601", ":", "require_iso8601", "=", "not", "infer_datetime_format", "format", "=", "None", "tz_parsed", "=", "None", "result", "=", "None", "if", "format", "is", "not", "None", ":", "try", ":", "# shortcut formatting here", "if", "format", "==", "\"%Y%m%d\"", ":", "try", ":", "# pass orig_arg as float-dtype may have been converted to", "# datetime64[ns]", "orig_arg", "=", "ensure_object", "(", "orig_arg", ")", "result", "=", "_attempt_YYYYMMDD", "(", "orig_arg", ",", "errors", "=", "errors", ")", "except", "(", "ValueError", ",", "TypeError", ",", "tslibs", ".", "OutOfBoundsDatetime", ")", ":", "raise", "ValueError", "(", "\"cannot convert the input to '%Y%m%d' date format\"", ")", "# fallback", "if", "result", "is", "None", ":", "try", ":", "result", ",", "timezones", "=", "array_strptime", "(", "arg", ",", "format", ",", "exact", "=", "exact", ",", "errors", "=", "errors", ")", "if", "\"%Z\"", "in", "format", "or", "\"%z\"", "in", "format", ":", "return", "_return_parsed_timezone_results", "(", "result", ",", "timezones", ",", "tz", ",", "name", ")", "except", "tslibs", ".", "OutOfBoundsDatetime", ":", "if", "errors", "==", "\"raise\"", ":", "raise", "elif", "errors", "==", "\"coerce\"", ":", "result", "=", "np", ".", "empty", "(", "arg", ".", "shape", ",", "dtype", "=", "\"M8[ns]\"", ")", "iresult", "=", "result", ".", "view", "(", "\"i8\"", ")", "iresult", ".", "fill", "(", "tslibs", ".", "iNaT", ")", "else", ":", "result", "=", "arg", "except", "ValueError", ":", "# if format was inferred, try falling back", "# to array_to_datetime - terminate here", "# for specified formats", "if", "not", "infer_datetime_format", ":", "if", "errors", "==", "\"raise\"", ":", "raise", "elif", "errors", "==", "\"coerce\"", ":", "result", "=", "np", ".", "empty", "(", "arg", ".", "shape", ",", "dtype", "=", "\"M8[ns]\"", ")", "iresult", "=", "result", ".", "view", "(", "\"i8\"", ")", "iresult", ".", "fill", "(", "tslibs", ".", "iNaT", ")", "else", ":", "result", "=", "arg", "except", "ValueError", "as", "e", ":", "# Fallback to try to convert datetime objects if timezone-aware", "# datetime objects are found without passing `utc=True`", "try", ":", "values", ",", "tz", "=", "conversion", ".", "datetime_to_datetime64", "(", "arg", ")", "return", "DatetimeIndex", ".", "_simple_new", "(", "values", ",", "name", "=", "name", ",", "tz", "=", "tz", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "raise", "e", "if", "result", "is", "None", ":", "assert", "format", "is", "None", "or", "infer_datetime_format", "utc", "=", "tz", "==", "\"utc\"", "result", ",", "tz_parsed", "=", "objects_to_datetime64ns", "(", "arg", ",", "dayfirst", "=", "dayfirst", ",", "yearfirst", "=", "yearfirst", ",", "utc", "=", "utc", ",", "errors", "=", "errors", ",", "require_iso8601", "=", "require_iso8601", ",", "allow_object", "=", "True", ",", ")", "if", "tz_parsed", "is", "not", "None", ":", "# We can take a shortcut since the datetime64 numpy array", "# is in UTC", "return", "DatetimeIndex", ".", "_simple_new", "(", "result", ",", "name", "=", "name", ",", "tz", "=", "tz_parsed", ")", "utc", "=", "tz", "==", "\"utc\"", "return", "_box_as_indexlike", "(", "result", ",", "utc", "=", "utc", ",", "name", "=", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/tools/datetimes.py#L246-L456
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_sh.py
python
SyntaxData.GetSyntaxSpec
(self)
return SYNTAX_ITEMS
Syntax Specifications
Syntax Specifications
[ "Syntax", "Specifications" ]
def GetSyntaxSpec(self): """Syntax Specifications """ return SYNTAX_ITEMS
[ "def", "GetSyntaxSpec", "(", "self", ")", ":", "return", "SYNTAX_ITEMS" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_sh.py#L121-L123
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0049-Group-Anagrams/0049.py
python
Solution.groupAnagrams
(self, strs)
return result
:type strs: List[str] :rtype: List[List[str]]
:type strs: List[str] :rtype: List[List[str]]
[ ":", "type", "strs", ":", "List", "[", "str", "]", ":", "rtype", ":", "List", "[", "List", "[", "str", "]]" ]
def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ strs_map = {} result = [] for string in strs: tmp = ''.join(sorted(string)) if tmp in strs_map: strs_map[tmp].append(string) else: strs_map[tmp] = [string] for str_list in strs_map.values(): result.append(str_list) return result
[ "def", "groupAnagrams", "(", "self", ",", "strs", ")", ":", "strs_map", "=", "{", "}", "result", "=", "[", "]", "for", "string", "in", "strs", ":", "tmp", "=", "''", ".", "join", "(", "sorted", "(", "string", ")", ")", "if", "tmp", "in", "strs_map", ":", "strs_map", "[", "tmp", "]", ".", "append", "(", "string", ")", "else", ":", "strs_map", "[", "tmp", "]", "=", "[", "string", "]", "for", "str_list", "in", "strs_map", ".", "values", "(", ")", ":", "result", ".", "append", "(", "str_list", ")", "return", "result" ]
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0049-Group-Anagrams/0049.py#L2-L19
KhronosGroup/OpenCOLLADA
6031fa956e1da4bbdd910af3a8f9e924ef0fca7a
Externals/LibXML/python/libxml.py
python
SAXCallback.startDocument
(self)
called at the start of the document
called at the start of the document
[ "called", "at", "the", "start", "of", "the", "document" ]
def startDocument(self): """called at the start of the document""" pass
[ "def", "startDocument", "(", "self", ")", ":", "pass" ]
https://github.com/KhronosGroup/OpenCOLLADA/blob/6031fa956e1da4bbdd910af3a8f9e924ef0fca7a/Externals/LibXML/python/libxml.py#L136-L138
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py
python
_dnsname_to_stdlib
(name)
return name
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped.
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version.
[ "Converts", "a", "dNSName", "SubjectAlternativeName", "field", "to", "the", "form", "used", "by", "the", "standard", "library", "on", "the", "given", "Python", "version", "." ]
def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. """ def idna_encode(name): """ Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. """ from pip._vendor import idna try: for prefix in [u"*.", u"."]: if name.startswith(prefix): name = name[len(prefix) :] return prefix.encode("ascii") + idna.encode(name) return idna.encode(name) except idna.core.IDNAError: return None # Don't send IPv6 addresses through the IDNA encoder. if ":" in name: return name name = idna_encode(name) if name is None: return None elif sys.version_info >= (3, 0): name = name.decode("utf-8") return name
[ "def", "_dnsname_to_stdlib", "(", "name", ")", ":", "def", "idna_encode", "(", "name", ")", ":", "\"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoids that problem.\n \"\"\"", "from", "pip", ".", "_vendor", "import", "idna", "try", ":", "for", "prefix", "in", "[", "u\"*.\"", ",", "u\".\"", "]", ":", "if", "name", ".", "startswith", "(", "prefix", ")", ":", "name", "=", "name", "[", "len", "(", "prefix", ")", ":", "]", "return", "prefix", ".", "encode", "(", "\"ascii\"", ")", "+", "idna", ".", "encode", "(", "name", ")", "return", "idna", ".", "encode", "(", "name", ")", "except", "idna", ".", "core", ".", "IDNAError", ":", "return", "None", "# Don't send IPv6 addresses through the IDNA encoder.", "if", "\":\"", "in", "name", ":", "return", "name", "name", "=", "idna_encode", "(", "name", ")", "if", "name", "is", "None", ":", "return", "None", "elif", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "name", "=", "name", ".", "decode", "(", "\"utf-8\"", ")", "return", "name" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py#L169-L209
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillHeaderView.py
python
DrillHeaderView.sizeHint
(self)
return size
Override QHeaderView::sizeHint. Returns a size hint for the header taking into account the button if it is bigger than the text. Returns: (Qsize): header size hint in pixels
Override QHeaderView::sizeHint. Returns a size hint for the header taking into account the button if it is bigger than the text.
[ "Override", "QHeaderView", "::", "sizeHint", ".", "Returns", "a", "size", "hint", "for", "the", "header", "taking", "into", "account", "the", "button", "if", "it", "is", "bigger", "than", "the", "text", "." ]
def sizeHint(self): """ Override QHeaderView::sizeHint. Returns a size hint for the header taking into account the button if it is bigger than the text. Returns: (Qsize): header size hint in pixels """ size = super(DrillHeaderView, self).sizeHint() margin = self.style().pixelMetric(QStyle.PM_HeaderMargin, None, self) buttonHeight = self.BUTTON_SIZE + 2 * margin + 1 if size.height() < buttonHeight: size.setHeight(buttonHeight) return size
[ "def", "sizeHint", "(", "self", ")", ":", "size", "=", "super", "(", "DrillHeaderView", ",", "self", ")", ".", "sizeHint", "(", ")", "margin", "=", "self", ".", "style", "(", ")", ".", "pixelMetric", "(", "QStyle", ".", "PM_HeaderMargin", ",", "None", ",", "self", ")", "buttonHeight", "=", "self", ".", "BUTTON_SIZE", "+", "2", "*", "margin", "+", "1", "if", "size", ".", "height", "(", ")", "<", "buttonHeight", ":", "size", ".", "setHeight", "(", "buttonHeight", ")", "return", "size" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillHeaderView.py#L45-L58
ROCmSoftwarePlatform/hipCaffe
4ec5d482515cce532348553b6db6d00d015675d5
examples/pycaffe/layers/pascal_multilabel_datalayers.py
python
PascalMultilabelDataLayerSync.backward
(self, top, propagate_down, bottom)
These layers does not back propagate
These layers does not back propagate
[ "These", "layers", "does", "not", "back", "propagate" ]
def backward(self, top, propagate_down, bottom): """ These layers does not back propagate """ pass
[ "def", "backward", "(", "self", ",", "top", ",", "propagate_down", ",", "bottom", ")", ":", "pass" ]
https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L74-L78
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/linux/procfs.py
python
main
(argv)
return 0
The main function for manual testing.
The main function for manual testing.
[ "The", "main", "function", "for", "manual", "testing", "." ]
def main(argv): """The main function for manual testing.""" _LOGGER.setLevel(logging.WARNING) handler = logging.StreamHandler() handler.setLevel(logging.WARNING) handler.setFormatter(logging.Formatter( '%(asctime)s:%(name)s:%(levelname)s:%(message)s')) _LOGGER.addHandler(handler) pids = [] for arg in argv[1:]: try: pid = int(arg) except ValueError: raise SyntaxError("%s is not an integer." % arg) else: pids.append(pid) procs = {} for pid in pids: procs[pid] = _ProcessMemory(pid) procs[pid].read_all() print '=== PID: %d ===' % pid print ' stat: %d' % procs[pid].stat.vsize print ' statm: %d' % (procs[pid].statm.size * 4096) print ' status: %d (Peak:%d)' % (procs[pid].status.vm_size * 1024, procs[pid].status.vm_peak * 1024) print ' smaps: %d' % (procs[pid].smaps.size * 1024) print 'pagemap: %d' % procs[pid].pagemap.vsize print ' stat: %d' % (procs[pid].stat.rss * 4096) print ' statm: %d' % (procs[pid].statm.resident * 4096) print ' status: %d (Peak:%d)' % (procs[pid].status.vm_rss * 1024, procs[pid].status.vm_hwm * 1024) print ' smaps: %d' % (procs[pid].smaps.rss * 1024) print 'pagemap: %d' % procs[pid].pagemap.present return 0
[ "def", "main", "(", "argv", ")", ":", "_LOGGER", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "'%(asctime)s:%(name)s:%(levelname)s:%(message)s'", ")", ")", "_LOGGER", ".", "addHandler", "(", "handler", ")", "pids", "=", "[", "]", "for", "arg", "in", "argv", "[", "1", ":", "]", ":", "try", ":", "pid", "=", "int", "(", "arg", ")", "except", "ValueError", ":", "raise", "SyntaxError", "(", "\"%s is not an integer.\"", "%", "arg", ")", "else", ":", "pids", ".", "append", "(", "pid", ")", "procs", "=", "{", "}", "for", "pid", "in", "pids", ":", "procs", "[", "pid", "]", "=", "_ProcessMemory", "(", "pid", ")", "procs", "[", "pid", "]", ".", "read_all", "(", ")", "print", "'=== PID: %d ==='", "%", "pid", "print", "' stat: %d'", "%", "procs", "[", "pid", "]", ".", "stat", ".", "vsize", "print", "' statm: %d'", "%", "(", "procs", "[", "pid", "]", ".", "statm", ".", "size", "*", "4096", ")", "print", "' status: %d (Peak:%d)'", "%", "(", "procs", "[", "pid", "]", ".", "status", ".", "vm_size", "*", "1024", ",", "procs", "[", "pid", "]", ".", "status", ".", "vm_peak", "*", "1024", ")", "print", "' smaps: %d'", "%", "(", "procs", "[", "pid", "]", ".", "smaps", ".", "size", "*", "1024", ")", "print", "'pagemap: %d'", "%", "procs", "[", "pid", "]", ".", "pagemap", ".", "vsize", "print", "' stat: %d'", "%", "(", "procs", "[", "pid", "]", ".", "stat", ".", "rss", "*", "4096", ")", "print", "' statm: %d'", "%", "(", "procs", "[", "pid", "]", ".", "statm", ".", "resident", "*", "4096", ")", "print", "' status: %d (Peak:%d)'", "%", "(", "procs", "[", "pid", "]", ".", "status", ".", "vm_rss", "*", "1024", ",", "procs", "[", "pid", "]", ".", "status", ".", "vm_hwm", "*", "1024", ")", "print", "' smaps: %d'", "%", "(", "procs", "[", "pid", "]", ".", "smaps", ".", "rss", "*", "1024", ")", "print", "'pagemap: %d'", "%", "procs", "[", "pid", "]", ".", "pagemap", ".", "present", "return", "0" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/linux/procfs.py#L705-L743
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py
python
_initialize_variables
(session)
Utility to initialize uninitialized variables on the fly.
Utility to initialize uninitialized variables on the fly.
[ "Utility", "to", "initialize", "uninitialized", "variables", "on", "the", "fly", "." ]
def _initialize_variables(session): """Utility to initialize uninitialized variables on the fly.""" variables = _get_variables(get_graph()) candidate_vars = [] for v in variables: if not getattr(v, '_keras_initialized', False): candidate_vars.append(v) if candidate_vars: # This step is expensive, so we only run it on variables not already # marked as initialized. is_initialized = session.run( [variables_module.is_variable_initialized(v) for v in candidate_vars]) uninitialized_vars = [] for flag, v in zip(is_initialized, candidate_vars): if not flag: uninitialized_vars.append(v) v._keras_initialized = True if uninitialized_vars: session.run(variables_module.variables_initializer(uninitialized_vars))
[ "def", "_initialize_variables", "(", "session", ")", ":", "variables", "=", "_get_variables", "(", "get_graph", "(", ")", ")", "candidate_vars", "=", "[", "]", "for", "v", "in", "variables", ":", "if", "not", "getattr", "(", "v", ",", "'_keras_initialized'", ",", "False", ")", ":", "candidate_vars", ".", "append", "(", "v", ")", "if", "candidate_vars", ":", "# This step is expensive, so we only run it on variables not already", "# marked as initialized.", "is_initialized", "=", "session", ".", "run", "(", "[", "variables_module", ".", "is_variable_initialized", "(", "v", ")", "for", "v", "in", "candidate_vars", "]", ")", "uninitialized_vars", "=", "[", "]", "for", "flag", ",", "v", "in", "zip", "(", "is_initialized", ",", "candidate_vars", ")", ":", "if", "not", "flag", ":", "uninitialized_vars", ".", "append", "(", "v", ")", "v", ".", "_keras_initialized", "=", "True", "if", "uninitialized_vars", ":", "session", ".", "run", "(", "variables_module", ".", "variables_initializer", "(", "uninitialized_vars", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L892-L910
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/davclient/davclient.py
python
DAVClient._get_response_tree
(self)
return self.response.tree
Parse the response body into an elementree object
Parse the response body into an elementree object
[ "Parse", "the", "response", "body", "into", "an", "elementree", "object" ]
def _get_response_tree(self): """Parse the response body into an elementree object""" self.response.tree = ElementTree.fromstring(self.response.body) return self.response.tree
[ "def", "_get_response_tree", "(", "self", ")", ":", "self", ".", "response", ".", "tree", "=", "ElementTree", ".", "fromstring", "(", "self", ".", "response", ".", "body", ")", "return", "self", ".", "response", ".", "tree" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/davclient/davclient.py#L98-L101
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/image/detection.py
python
DetRandomCropAug._random_crop_proposal
(self, label, height, width)
return ()
Propose cropping areas
Propose cropping areas
[ "Propose", "cropping", "areas" ]
def _random_crop_proposal(self, label, height, width): """Propose cropping areas""" from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width for _ in range(self.max_attempts): ratio = random.uniform(*self.aspect_ratio_range) if ratio <= 0: continue h = int(round(sqrt(min_area / ratio))) max_h = int(round(sqrt(max_area / ratio))) if round(max_h * ratio) > width: # find smallest max_h satifying round(max_h * ratio) <= width max_h = int((width + 0.4999999) / ratio) if max_h > height: max_h = height if h > max_h: h = max_h if h < max_h: # generate random h in range [h, max_h] h = random.randint(h, max_h) w = int(round(h * ratio)) assert w <= width # trying to fix rounding problems area = w * h if area < min_area: h += 1 w = int(round(h * ratio)) area = w * h if area > max_area: h -= 1 w = int(round(h * ratio)) area = w * h if not (min_area <= area <= max_area and 0 <= w <= width and 0 <= h <= height): continue y = random.randint(0, max(0, height - h)) x = random.randint(0, max(0, width - w)) if self._check_satisfy_constraints(label, x, y, x + w, y + h, width, height): new_label = self._update_labels(label, (x, y, w, h), height, width) if new_label is not None: return (x, y, w, h, new_label) return ()
[ "def", "_random_crop_proposal", "(", "self", ",", "label", ",", "height", ",", "width", ")", ":", "from", "math", "import", "sqrt", "if", "not", "self", ".", "enabled", "or", "height", "<=", "0", "or", "width", "<=", "0", ":", "return", "(", ")", "min_area", "=", "self", ".", "area_range", "[", "0", "]", "*", "height", "*", "width", "max_area", "=", "self", ".", "area_range", "[", "1", "]", "*", "height", "*", "width", "for", "_", "in", "range", "(", "self", ".", "max_attempts", ")", ":", "ratio", "=", "random", ".", "uniform", "(", "*", "self", ".", "aspect_ratio_range", ")", "if", "ratio", "<=", "0", ":", "continue", "h", "=", "int", "(", "round", "(", "sqrt", "(", "min_area", "/", "ratio", ")", ")", ")", "max_h", "=", "int", "(", "round", "(", "sqrt", "(", "max_area", "/", "ratio", ")", ")", ")", "if", "round", "(", "max_h", "*", "ratio", ")", ">", "width", ":", "# find smallest max_h satifying round(max_h * ratio) <= width", "max_h", "=", "int", "(", "(", "width", "+", "0.4999999", ")", "/", "ratio", ")", "if", "max_h", ">", "height", ":", "max_h", "=", "height", "if", "h", ">", "max_h", ":", "h", "=", "max_h", "if", "h", "<", "max_h", ":", "# generate random h in range [h, max_h]", "h", "=", "random", ".", "randint", "(", "h", ",", "max_h", ")", "w", "=", "int", "(", "round", "(", "h", "*", "ratio", ")", ")", "assert", "w", "<=", "width", "# trying to fix rounding problems", "area", "=", "w", "*", "h", "if", "area", "<", "min_area", ":", "h", "+=", "1", "w", "=", "int", "(", "round", "(", "h", "*", "ratio", ")", ")", "area", "=", "w", "*", "h", "if", "area", ">", "max_area", ":", "h", "-=", "1", "w", "=", "int", "(", "round", "(", "h", "*", "ratio", ")", ")", "area", "=", "w", "*", "h", "if", "not", "(", "min_area", "<=", "area", "<=", "max_area", "and", "0", "<=", "w", "<=", "width", "and", "0", "<=", "h", "<=", "height", ")", ":", "continue", "y", "=", "random", ".", "randint", "(", "0", ",", "max", "(", "0", ",", "height", "-", "h", ")", ")", "x", "=", "random", ".", "randint", "(", "0", ",", "max", "(", "0", ",", "width", "-", "w", ")", ")", "if", "self", ".", "_check_satisfy_constraints", "(", "label", ",", "x", ",", "y", ",", "x", "+", "w", ",", "y", "+", "h", ",", "width", ",", "height", ")", ":", "new_label", "=", "self", ".", "_update_labels", "(", "label", ",", "(", "x", ",", "y", ",", "w", ",", "h", ")", ",", "height", ",", "width", ")", "if", "new_label", "is", "not", "None", ":", "return", "(", "x", ",", "y", ",", "w", ",", "h", ",", "new_label", ")", "return", "(", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/image/detection.py#L274-L320
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
PageSetupDialogData.GetMarginBottomRight
(*args, **kwargs)
return _windows_.PageSetupDialogData_GetMarginBottomRight(*args, **kwargs)
GetMarginBottomRight(self) -> Point
GetMarginBottomRight(self) -> Point
[ "GetMarginBottomRight", "(", "self", ")", "-", ">", "Point" ]
def GetMarginBottomRight(*args, **kwargs): """GetMarginBottomRight(self) -> Point""" return _windows_.PageSetupDialogData_GetMarginBottomRight(*args, **kwargs)
[ "def", "GetMarginBottomRight", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PageSetupDialogData_GetMarginBottomRight", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L4918-L4920