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
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
matmul
(a, b, out=None, **kwargs)
return _mx_nd_np.matmul(a, b, out=out)
r"""Matrix product of two arrays. Parameters ---------- a, b : ndarray Input arrays, scalars not allowed. out : ndarray, optional A location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m). If not provided or None, a freshly-allocated array is returned. Returns ------- y : ndarray The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors. Raises ------ MXNetError If the last dimension of a is not the same size as the second-to-last dimension of b. If a scalar value is passed in. See Also -------- tensordot : Sum products over arbitrary axes. dot : alternative matrix product with different broadcasting rules. einsum : Einstein summation convention. .. note:: The behavior depends on the arguments in the following way. * If both arguments are ``2-D`` they are multiplied like conventional matrices. * If either argument is ``N-D``, ``N > 2``, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly. * If the first argument is ``1-D``, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. * If the second argument is ``1-D``, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. matmul differs from dot in two important ways: * Multiplication by scalars is not allowed, use multiply instead. * Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature ``(n,k),(k,m)->(n,m)``: >>> a = np.ones([9, 5, 7, 4]) >>> c = np.ones([9, 5, 4, 3]) >>> np.dot(a, c).shape (9, 5, 7, 9, 5, 3) >>> np.matmul(a, c).shape (9, 5, 7, 3) >>> # n is 7, k is 4, m is 3 Examples -------- For 2-D arrays it is the matrix product: >>> a = np.array([[1, 0], ... [0, 1]]) >>> b = np.array([[4, 1], ... [2, 2]]) >>> np.matmul(a, b) array([[4., 1.], [2., 2.]]) For 2-D mixed with 1-D, the result is the usual. >>> a = np.array([[1, 0], ... [0, 1]]) >>> b = np.array([1, 2]) >>> np.matmul(a, b) array([1., 2.]) >>> np.matmul(b, a) array([1., 2.]) Broadcasting is conventional for stacks of arrays >>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4)) >>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2)) >>> np.matmul(a, b).shape (2, 2, 2) >>> np.matmul(a, b)[0, 1, 1] array(98.) >>> sum(a[0, 1, :] * b[0, :, 1]) array(98.) Scalar multiplication raises an error. >>> np.matmul([1, 2], 3) Traceback (most recent call last): ... mxnet.base.MXNetError: ... : Multiplication by scalars is not allowed.
r"""Matrix product of two arrays.
[ "r", "Matrix", "product", "of", "two", "arrays", "." ]
def matmul(a, b, out=None, **kwargs): r"""Matrix product of two arrays. Parameters ---------- a, b : ndarray Input arrays, scalars not allowed. out : ndarray, optional A location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m). If not provided or None, a freshly-allocated array is returned. Returns ------- y : ndarray The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors. Raises ------ MXNetError If the last dimension of a is not the same size as the second-to-last dimension of b. If a scalar value is passed in. See Also -------- tensordot : Sum products over arbitrary axes. dot : alternative matrix product with different broadcasting rules. einsum : Einstein summation convention. .. note:: The behavior depends on the arguments in the following way. * If both arguments are ``2-D`` they are multiplied like conventional matrices. * If either argument is ``N-D``, ``N > 2``, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly. * If the first argument is ``1-D``, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. * If the second argument is ``1-D``, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. matmul differs from dot in two important ways: * Multiplication by scalars is not allowed, use multiply instead. * Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature ``(n,k),(k,m)->(n,m)``: >>> a = np.ones([9, 5, 7, 4]) >>> c = np.ones([9, 5, 4, 3]) >>> np.dot(a, c).shape (9, 5, 7, 9, 5, 3) >>> np.matmul(a, c).shape (9, 5, 7, 3) >>> # n is 7, k is 4, m is 3 Examples -------- For 2-D arrays it is the matrix product: >>> a = np.array([[1, 0], ... [0, 1]]) >>> b = np.array([[4, 1], ... [2, 2]]) >>> np.matmul(a, b) array([[4., 1.], [2., 2.]]) For 2-D mixed with 1-D, the result is the usual. >>> a = np.array([[1, 0], ... [0, 1]]) >>> b = np.array([1, 2]) >>> np.matmul(a, b) array([1., 2.]) >>> np.matmul(b, a) array([1., 2.]) Broadcasting is conventional for stacks of arrays >>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4)) >>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2)) >>> np.matmul(a, b).shape (2, 2, 2) >>> np.matmul(a, b)[0, 1, 1] array(98.) >>> sum(a[0, 1, :] * b[0, :, 1]) array(98.) Scalar multiplication raises an error. >>> np.matmul([1, 2], 3) Traceback (most recent call last): ... mxnet.base.MXNetError: ... : Multiplication by scalars is not allowed. """ return _mx_nd_np.matmul(a, b, out=out)
[ "def", "matmul", "(", "a", ",", "b", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_mx_nd_np", ".", "matmul", "(", "a", ",", "b", ",", "out", "=", "out", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L3719-L3816
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/internal/cpp_message.py
python
_IsMessageSetExtension
(field)
return (field.is_extension and field.containing_type.has_options and field.containing_type.GetOptions().message_set_wire_format and field.type == _TYPE_MESSAGE and field.message_type == field.extension_scope and field.label == _LABEL_OPTIONAL)
Checks if a field is a message set extension.
Checks if a field is a message set extension.
[ "Checks", "if", "a", "field", "is", "a", "message", "set", "extension", "." ]
def _IsMessageSetExtension(field): """Checks if a field is a message set extension.""" return (field.is_extension and field.containing_type.has_options and field.containing_type.GetOptions().message_set_wire_format and field.type == _TYPE_MESSAGE and field.message_type == field.extension_scope and field.label == _LABEL_OPTIONAL)
[ "def", "_IsMessageSetExtension", "(", "field", ")", ":", "return", "(", "field", ".", "is_extension", "and", "field", ".", "containing_type", ".", "has_options", "and", "field", ".", "containing_type", ".", "GetOptions", "(", ")", ".", "message_set_wire_format", "and", "field", ".", "type", "==", "_TYPE_MESSAGE", "and", "field", ".", "message_type", "==", "field", ".", "extension_scope", "and", "field", ".", "label", "==", "_LABEL_OPTIONAL", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/cpp_message.py#L498-L505
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/nn/qat/modules/conv_fused.py
python
_ConvBnNd.batch_stats
(self, x, bias=None)
return batch_mean, batch_var
Get the batch mean and variance of x and updates the BatchNorm's running mean and average. Args: x (torch.Tensor): input batch. bias (torch.Tensor): the bias that is to be applied to the batch. Returns: (mean, variance) Note: In case of `nn.Linear`, x may be of shape (N, C, L) or (N, L) where N is batch size, C is number of channels, L is the features size. The batch norm computes the stats over C in the first case or L on the second case. The batch normalization layer is (`nn.BatchNorm1d`)[https://pytorch.org/docs/stable/nn.html#batchnorm1d] In case of `nn.Conv2d`, x is of shape (N, C, H, W) where H,W are the image dimensions, and the batch norm computes the stats over C. The batch normalization layer is (`nn.BatchNorm2d`)[https://pytorch.org/docs/stable/nn.html#batchnorm2d] In case of `nn.Conv3d`, x is of shape (N, C, D, H, W) where H,W are the image dimensions, D is additional channel dimension, and the batch norm computes the stats over C. The batch normalization layer is (`nn.BatchNorm3d`)[https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm3d.html#torch.nn.BatchNorm3d]
Get the batch mean and variance of x and updates the BatchNorm's running mean and average.
[ "Get", "the", "batch", "mean", "and", "variance", "of", "x", "and", "updates", "the", "BatchNorm", "s", "running", "mean", "and", "average", "." ]
def batch_stats(self, x, bias=None): """Get the batch mean and variance of x and updates the BatchNorm's running mean and average. Args: x (torch.Tensor): input batch. bias (torch.Tensor): the bias that is to be applied to the batch. Returns: (mean, variance) Note: In case of `nn.Linear`, x may be of shape (N, C, L) or (N, L) where N is batch size, C is number of channels, L is the features size. The batch norm computes the stats over C in the first case or L on the second case. The batch normalization layer is (`nn.BatchNorm1d`)[https://pytorch.org/docs/stable/nn.html#batchnorm1d] In case of `nn.Conv2d`, x is of shape (N, C, H, W) where H,W are the image dimensions, and the batch norm computes the stats over C. The batch normalization layer is (`nn.BatchNorm2d`)[https://pytorch.org/docs/stable/nn.html#batchnorm2d] In case of `nn.Conv3d`, x is of shape (N, C, D, H, W) where H,W are the image dimensions, D is additional channel dimension, and the batch norm computes the stats over C. The batch normalization layer is (`nn.BatchNorm3d`)[https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm3d.html#torch.nn.BatchNorm3d] """ channel_size = self.bn.num_features self.bn.num_batches_tracked += 1 # Calculate current batch stats batch_mean = x.transpose(0, 1).contiguous().view(channel_size, -1).mean(1) # BatchNorm currently uses biased variance (without Bessel's correction) as was discussed at # https://github.com/pytorch/pytorch/issues/1410 # # also see the source code itself: # https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Normalization.cpp#L216 batch_var = x.transpose(0, 1).contiguous().view(channel_size, -1).var( 1, unbiased=False) # Update running stats with torch.no_grad(): biased_batch_mean = batch_mean + (bias if bias is not None else 0) # However - running_var is updated using unbiased variance! # https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Normalization.cpp#L223 n = x.numel() / channel_size corrected_var = batch_var * (n / float(n - 1)) momentum = self.bn.momentum if momentum is None: # momentum is None - we compute a cumulative moving average # as noted in https://pytorch.org/docs/stable/nn.html#batchnorm2d momentum = 1. / float(self.bn.num_batches_tracked) self.bn.running_mean.mul_(1 - momentum).add_(momentum * biased_batch_mean) self.bn.running_var.mul_(1 - momentum).add_(momentum * corrected_var) return batch_mean, batch_var
[ "def", "batch_stats", "(", "self", ",", "x", ",", "bias", "=", "None", ")", ":", "channel_size", "=", "self", ".", "bn", ".", "num_features", "self", ".", "bn", ".", "num_batches_tracked", "+=", "1", "# Calculate current batch stats", "batch_mean", "=", "x", ".", "transpose", "(", "0", ",", "1", ")", ".", "contiguous", "(", ")", ".", "view", "(", "channel_size", ",", "-", "1", ")", ".", "mean", "(", "1", ")", "# BatchNorm currently uses biased variance (without Bessel's correction) as was discussed at", "# https://github.com/pytorch/pytorch/issues/1410", "#", "# also see the source code itself:", "# https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Normalization.cpp#L216", "batch_var", "=", "x", ".", "transpose", "(", "0", ",", "1", ")", ".", "contiguous", "(", ")", ".", "view", "(", "channel_size", ",", "-", "1", ")", ".", "var", "(", "1", ",", "unbiased", "=", "False", ")", "# Update running stats", "with", "torch", ".", "no_grad", "(", ")", ":", "biased_batch_mean", "=", "batch_mean", "+", "(", "bias", "if", "bias", "is", "not", "None", "else", "0", ")", "# However - running_var is updated using unbiased variance!", "# https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Normalization.cpp#L223", "n", "=", "x", ".", "numel", "(", ")", "/", "channel_size", "corrected_var", "=", "batch_var", "*", "(", "n", "/", "float", "(", "n", "-", "1", ")", ")", "momentum", "=", "self", ".", "bn", ".", "momentum", "if", "momentum", "is", "None", ":", "# momentum is None - we compute a cumulative moving average", "# as noted in https://pytorch.org/docs/stable/nn.html#batchnorm2d", "momentum", "=", "1.", "/", "float", "(", "self", ".", "bn", ".", "num_batches_tracked", ")", "self", ".", "bn", ".", "running_mean", ".", "mul_", "(", "1", "-", "momentum", ")", ".", "add_", "(", "momentum", "*", "biased_batch_mean", ")", "self", ".", "bn", ".", "running_var", ".", "mul_", "(", "1", "-", "momentum", ")", ".", "add_", "(", "momentum", "*", "corrected_var", ")", "return", "batch_mean", ",", "batch_var" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/nn/qat/modules/conv_fused.py#L120-L176
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
QuoteShellArgument
(arg, flavor)
return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
Quote a string such that it will be interpreted as a single argument by the shell.
Quote a string such that it will be interpreted as a single argument by the shell.
[ "Quote", "a", "string", "such", "that", "it", "will", "be", "interpreted", "as", "a", "single", "argument", "by", "the", "shell", "." ]
def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
[ "def", "QuoteShellArgument", "(", "arg", ",", "flavor", ")", ":", "# Rather than attempting to enumerate the bad shell characters, just", "# whitelist common OK ones and quote anything else.", "if", "re", ".", "match", "(", "r'^[a-zA-Z0-9_=.\\\\/-]+$'", ",", "arg", ")", ":", "return", "arg", "# No quoting necessary.", "if", "flavor", "==", "'win'", ":", "return", "gyp", ".", "msvs_emulation", ".", "QuoteForRspFile", "(", "arg", ")", "return", "\"'\"", "+", "arg", ".", "replace", "(", "\"'\"", ",", "\"'\"", "+", "'\"\\'\"'", "+", "\"'\"", ")", "+", "\"'\"" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L73-L82
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
TextEntryDialog.SetValue
(*args, **kwargs)
return _windows_.TextEntryDialog_SetValue(*args, **kwargs)
SetValue(self, String value) Sets the default text value.
SetValue(self, String value)
[ "SetValue", "(", "self", "String", "value", ")" ]
def SetValue(*args, **kwargs): """ SetValue(self, String value) Sets the default text value. """ return _windows_.TextEntryDialog_SetValue(*args, **kwargs)
[ "def", "SetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TextEntryDialog_SetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L3393-L3399
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Initializer.py
python
Uniform.lower_bound
(self)
return self._internal.get_lower_bound()
Gets the distribution lower bound.
Gets the distribution lower bound.
[ "Gets", "the", "distribution", "lower", "bound", "." ]
def lower_bound(self): """Gets the distribution lower bound. """ return self._internal.get_lower_bound()
[ "def", "lower_bound", "(", "self", ")", ":", "return", "self", ".", "_internal", ".", "get_lower_bound", "(", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Initializer.py#L117-L120
scylladb/seastar
0cdd2329beb1cc4c0af8828598c26114397ffa9c
scripts/dpdk_nic_bind.py
python
find_module
(mod)
find the .ko file for kernel module named mod. Searches the $RTE_SDK/$RTE_TARGET directory, the kernel modules directory and finally under the parent directory of the script
find the .ko file for kernel module named mod. Searches the $RTE_SDK/$RTE_TARGET directory, the kernel modules directory and finally under the parent directory of the script
[ "find", "the", ".", "ko", "file", "for", "kernel", "module", "named", "mod", ".", "Searches", "the", "$RTE_SDK", "/", "$RTE_TARGET", "directory", "the", "kernel", "modules", "directory", "and", "finally", "under", "the", "parent", "directory", "of", "the", "script" ]
def find_module(mod): '''find the .ko file for kernel module named mod. Searches the $RTE_SDK/$RTE_TARGET directory, the kernel modules directory and finally under the parent directory of the script ''' # check $RTE_SDK/$RTE_TARGET directory if 'RTE_SDK' in os.environ and 'RTE_TARGET' in os.environ: path = "%s/%s/kmod/%s.ko" % (os.environ['RTE_SDK'],\ os.environ['RTE_TARGET'], mod) if exists(path): return path # check using depmod try: depmod_out = check_output(["modinfo", "-n", mod], \ stderr=subprocess.STDOUT).lower() if "error" not in depmod_out: path = depmod_out.strip() if exists(path): return path except: # if modinfo can't find module, it fails, so continue pass # check for a copy based off current path tools_dir = dirname(abspath(sys.argv[0])) if (tools_dir.endswith("tools")): base_dir = dirname(tools_dir) find_out = check_output(["find", base_dir, "-name", mod + ".ko"]) if len(find_out) > 0: #something matched path = find_out.splitlines()[0] if exists(path): return path
[ "def", "find_module", "(", "mod", ")", ":", "# check $RTE_SDK/$RTE_TARGET directory", "if", "'RTE_SDK'", "in", "os", ".", "environ", "and", "'RTE_TARGET'", "in", "os", ".", "environ", ":", "path", "=", "\"%s/%s/kmod/%s.ko\"", "%", "(", "os", ".", "environ", "[", "'RTE_SDK'", "]", ",", "os", ".", "environ", "[", "'RTE_TARGET'", "]", ",", "mod", ")", "if", "exists", "(", "path", ")", ":", "return", "path", "# check using depmod", "try", ":", "depmod_out", "=", "check_output", "(", "[", "\"modinfo\"", ",", "\"-n\"", ",", "mod", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "lower", "(", ")", "if", "\"error\"", "not", "in", "depmod_out", ":", "path", "=", "depmod_out", ".", "strip", "(", ")", "if", "exists", "(", "path", ")", ":", "return", "path", "except", ":", "# if modinfo can't find module, it fails, so continue", "pass", "# check for a copy based off current path", "tools_dir", "=", "dirname", "(", "abspath", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", "if", "(", "tools_dir", ".", "endswith", "(", "\"tools\"", ")", ")", ":", "base_dir", "=", "dirname", "(", "tools_dir", ")", "find_out", "=", "check_output", "(", "[", "\"find\"", ",", "base_dir", ",", "\"-name\"", ",", "mod", "+", "\".ko\"", "]", ")", "if", "len", "(", "find_out", ")", ">", "0", ":", "#something matched", "path", "=", "find_out", ".", "splitlines", "(", ")", "[", "0", "]", "if", "exists", "(", "path", ")", ":", "return", "path" ]
https://github.com/scylladb/seastar/blob/0cdd2329beb1cc4c0af8828598c26114397ffa9c/scripts/dpdk_nic_bind.py#L122-L153
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tpu/tpu_sharding.py
python
ShardingPolicy.number_of_shards
(self)
return self._number_of_shards
Returns the number of shards in the policy or None if unspecified.
Returns the number of shards in the policy or None if unspecified.
[ "Returns", "the", "number", "of", "shards", "in", "the", "policy", "or", "None", "if", "unspecified", "." ]
def number_of_shards(self): """Returns the number of shards in the policy or None if unspecified.""" return self._number_of_shards
[ "def", "number_of_shards", "(", "self", ")", ":", "return", "self", ".", "_number_of_shards" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/tpu_sharding.py#L59-L61
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/multiclass.py
python
OneVsOneClassifier.fit
(self, X, y)
return self
Fit underlying estimators. Parameters ---------- X : (sparse) array-like, shape = [n_samples, n_features] Data. y : array-like, shape = [n_samples] Multi-class targets. Returns ------- self
Fit underlying estimators.
[ "Fit", "underlying", "estimators", "." ]
def fit(self, X, y): """Fit underlying estimators. Parameters ---------- X : (sparse) array-like, shape = [n_samples, n_features] Data. y : array-like, shape = [n_samples] Multi-class targets. Returns ------- self """ X, y = check_X_y(X, y, accept_sparse=['csr', 'csc']) self.classes_ = np.unique(y) n_classes = self.classes_.shape[0] estimators_indices = list(zip(*(Parallel(n_jobs=self.n_jobs)( delayed(_fit_ovo_binary) (self.estimator, X, y, self.classes_[i], self.classes_[j]) for i in range(n_classes) for j in range(i + 1, n_classes))))) self.estimators_ = estimators_indices[0] try: self.pairwise_indices_ = estimators_indices[1] \ if self._pairwise else None except AttributeError: self.pairwise_indices_ = None return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "y", "=", "check_X_y", "(", "X", ",", "y", ",", "accept_sparse", "=", "[", "'csr'", ",", "'csc'", "]", ")", "self", ".", "classes_", "=", "np", ".", "unique", "(", "y", ")", "n_classes", "=", "self", ".", "classes_", ".", "shape", "[", "0", "]", "estimators_indices", "=", "list", "(", "zip", "(", "*", "(", "Parallel", "(", "n_jobs", "=", "self", ".", "n_jobs", ")", "(", "delayed", "(", "_fit_ovo_binary", ")", "(", "self", ".", "estimator", ",", "X", ",", "y", ",", "self", ".", "classes_", "[", "i", "]", ",", "self", ".", "classes_", "[", "j", "]", ")", "for", "i", "in", "range", "(", "n_classes", ")", "for", "j", "in", "range", "(", "i", "+", "1", ",", "n_classes", ")", ")", ")", ")", ")", "self", ".", "estimators_", "=", "estimators_indices", "[", "0", "]", "try", ":", "self", ".", "pairwise_indices_", "=", "estimators_indices", "[", "1", "]", "if", "self", ".", "_pairwise", "else", "None", "except", "AttributeError", ":", "self", ".", "pairwise_indices_", "=", "None", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/multiclass.py#L472-L503
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/socketserver.py
python
BaseServer.handle_error
(self, request, client_address)
Handle an error gracefully. May be overridden. The default is to print a traceback and continue.
Handle an error gracefully. May be overridden.
[ "Handle", "an", "error", "gracefully", ".", "May", "be", "overridden", "." ]
def handle_error(self, request, client_address): """Handle an error gracefully. May be overridden. The default is to print a traceback and continue. """ print('-'*40, file=sys.stderr) print('Exception happened during processing of request from', client_address, file=sys.stderr) import traceback traceback.print_exc() print('-'*40, file=sys.stderr)
[ "def", "handle_error", "(", "self", ",", "request", ",", "client_address", ")", ":", "print", "(", "'-'", "*", "40", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'Exception happened during processing of request from'", ",", "client_address", ",", "file", "=", "sys", ".", "stderr", ")", "import", "traceback", "traceback", ".", "print_exc", "(", ")", "print", "(", "'-'", "*", "40", ",", "file", "=", "sys", ".", "stderr", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/socketserver.py#L370-L381
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/req/req_install.py
python
_get_dist
(metadata_directory)
return dist_cls( base_dir, project_name=dist_name, metadata=metadata, )
Return a pkg_resources.Distribution for the provided metadata directory.
Return a pkg_resources.Distribution for the provided metadata directory.
[ "Return", "a", "pkg_resources", ".", "Distribution", "for", "the", "provided", "metadata", "directory", "." ]
def _get_dist(metadata_directory): # type: (str) -> Distribution """Return a pkg_resources.Distribution for the provided metadata directory. """ dist_dir = metadata_directory.rstrip(os.sep) # Build a PathMetadata object, from path to metadata. :wink: base_dir, dist_dir_name = os.path.split(dist_dir) metadata = pkg_resources.PathMetadata(base_dir, dist_dir) # Determine the correct Distribution object type. if dist_dir.endswith(".egg-info"): dist_cls = pkg_resources.Distribution dist_name = os.path.splitext(dist_dir_name)[0] else: assert dist_dir.endswith(".dist-info") dist_cls = pkg_resources.DistInfoDistribution dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0] return dist_cls( base_dir, project_name=dist_name, metadata=metadata, )
[ "def", "_get_dist", "(", "metadata_directory", ")", ":", "# type: (str) -> Distribution", "dist_dir", "=", "metadata_directory", ".", "rstrip", "(", "os", ".", "sep", ")", "# Build a PathMetadata object, from path to metadata. :wink:", "base_dir", ",", "dist_dir_name", "=", "os", ".", "path", ".", "split", "(", "dist_dir", ")", "metadata", "=", "pkg_resources", ".", "PathMetadata", "(", "base_dir", ",", "dist_dir", ")", "# Determine the correct Distribution object type.", "if", "dist_dir", ".", "endswith", "(", "\".egg-info\"", ")", ":", "dist_cls", "=", "pkg_resources", ".", "Distribution", "dist_name", "=", "os", ".", "path", ".", "splitext", "(", "dist_dir_name", ")", "[", "0", "]", "else", ":", "assert", "dist_dir", ".", "endswith", "(", "\".dist-info\"", ")", "dist_cls", "=", "pkg_resources", ".", "DistInfoDistribution", "dist_name", "=", "os", ".", "path", ".", "splitext", "(", "dist_dir_name", ")", "[", "0", "]", ".", "split", "(", "\"-\"", ")", "[", "0", "]", "return", "dist_cls", "(", "base_dir", ",", "project_name", "=", "dist_name", ",", "metadata", "=", "metadata", ",", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/req/req_install.py#L68-L92
CGRU/cgru
1881a4128530e3d31ac6c25314c18314fc50c2c7
afanasy/python/af.py
python
Job.fillBlocks
(self)
Missing DocString :return:
Missing DocString
[ "Missing", "DocString" ]
def fillBlocks(self): """Missing DocString :return: """ self.data["blocks"] = [] for block in self.blocks: block.fillTasks() self.data["blocks"].append(block.data)
[ "def", "fillBlocks", "(", "self", ")", ":", "self", ".", "data", "[", "\"blocks\"", "]", "=", "[", "]", "for", "block", "in", "self", ".", "blocks", ":", "block", ".", "fillTasks", "(", ")", "self", ".", "data", "[", "\"blocks\"", "]", ".", "append", "(", "block", ".", "data", ")" ]
https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L680-L688
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
cpp-package/scripts/lint.py
python
LintHelper.process_cpp
(self, path, suffix)
Process a cpp file.
Process a cpp file.
[ "Process", "a", "cpp", "file", "." ]
def process_cpp(self, path, suffix): """Process a cpp file.""" _cpplint_state.ResetErrorCounts() cpplint.ProcessFile(str(path), _cpplint_state.verbose_level) _cpplint_state.PrintErrorCounts() errors = _cpplint_state.errors_by_category.copy() if suffix == 'h': self.cpp_header_map[str(path)] = errors else: self.cpp_src_map[str(path)] = errors
[ "def", "process_cpp", "(", "self", ",", "path", ",", "suffix", ")", ":", "_cpplint_state", ".", "ResetErrorCounts", "(", ")", "cpplint", ".", "ProcessFile", "(", "str", "(", "path", ")", ",", "_cpplint_state", ".", "verbose_level", ")", "_cpplint_state", ".", "PrintErrorCounts", "(", ")", "errors", "=", "_cpplint_state", ".", "errors_by_category", ".", "copy", "(", ")", "if", "suffix", "==", "'h'", ":", "self", ".", "cpp_header_map", "[", "str", "(", "path", ")", "]", "=", "errors", "else", ":", "self", ".", "cpp_src_map", "[", "str", "(", "path", ")", "]", "=", "errors" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/cpp-package/scripts/lint.py#L77-L87
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
demo/HuggingFace/NNDF/interface.py
python
TRTInferenceCommand.args_to_network_models
(self, args)
Converts argparse arguments into a list of valid NetworkModel fpaths. Specifically for ONNX. Invokes conversion scripts if not. Return: List[NetworkModel]: List of network model names.
Converts argparse arguments into a list of valid NetworkModel fpaths. Specifically for ONNX. Invokes conversion scripts if not. Return: List[NetworkModel]: List of network model names.
[ "Converts", "argparse", "arguments", "into", "a", "list", "of", "valid", "NetworkModel", "fpaths", ".", "Specifically", "for", "ONNX", ".", "Invokes", "conversion", "scripts", "if", "not", ".", "Return", ":", "List", "[", "NetworkModel", "]", ":", "List", "of", "network", "model", "names", "." ]
def args_to_network_models(self, args) -> Tuple[NetworkModel]: """ Converts argparse arguments into a list of valid NetworkModel fpaths. Specifically for ONNX. Invokes conversion scripts if not. Return: List[NetworkModel]: List of network model names. """
[ "def", "args_to_network_models", "(", "self", ",", "args", ")", "->", "Tuple", "[", "NetworkModel", "]", ":" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/HuggingFace/NNDF/interface.py#L274-L280
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/python_solver.py
python
PythonSolver.AddDofs
(self)
This function add the Dofs needed by this PythonSolver to the the ModelPart It has to be called AFTER the ModelPart is read!
This function add the Dofs needed by this PythonSolver to the the ModelPart It has to be called AFTER the ModelPart is read!
[ "This", "function", "add", "the", "Dofs", "needed", "by", "this", "PythonSolver", "to", "the", "the", "ModelPart", "It", "has", "to", "be", "called", "AFTER", "the", "ModelPart", "is", "read!" ]
def AddDofs(self): """This function add the Dofs needed by this PythonSolver to the the ModelPart It has to be called AFTER the ModelPart is read! """ pass
[ "def", "AddDofs", "(", "self", ")", ":", "pass" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/python_solver.py#L57-L61
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/plan/robotcspace.py
python
RobotCSpace.sample
(self)
return res
Overload this to implement custom sampling strategies or to handle non-standard joints. This one will handle spin joints and rotational axes of floating bases.
Overload this to implement custom sampling strategies or to handle non-standard joints. This one will handle spin joints and rotational axes of floating bases.
[ "Overload", "this", "to", "implement", "custom", "sampling", "strategies", "or", "to", "handle", "non", "-", "standard", "joints", ".", "This", "one", "will", "handle", "spin", "joints", "and", "rotational", "axes", "of", "floating", "bases", "." ]
def sample(self): """Overload this to implement custom sampling strategies or to handle non-standard joints. This one will handle spin joints and rotational axes of floating bases.""" res = CSpace.sample(self) for i,x in enumerate(res): if math.isnan(x): res[i] = random.uniform(0,math.pi*2.0) return res
[ "def", "sample", "(", "self", ")", ":", "res", "=", "CSpace", ".", "sample", "(", "self", ")", "for", "i", ",", "x", "in", "enumerate", "(", "res", ")", ":", "if", "math", ".", "isnan", "(", "x", ")", ":", "res", "[", "i", "]", "=", "random", ".", "uniform", "(", "0", ",", "math", ".", "pi", "*", "2.0", ")", "return", "res" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/robotcspace.py#L70-L78
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/tools/scan-build-py/libscanbuild/analyze.py
python
print_active_checkers
(checkers)
Print active checkers to stdout.
Print active checkers to stdout.
[ "Print", "active", "checkers", "to", "stdout", "." ]
def print_active_checkers(checkers): """ Print active checkers to stdout. """ for name in sorted(name for name, (_, active) in checkers.items() if active): print(name)
[ "def", "print_active_checkers", "(", "checkers", ")", ":", "for", "name", "in", "sorted", "(", "name", "for", "name", ",", "(", "_", ",", "active", ")", "in", "checkers", ".", "items", "(", ")", "if", "active", ")", ":", "print", "(", "name", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/tools/scan-build-py/libscanbuild/analyze.py#L241-L246
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
Co-Simulation/Sumo/util/netconvert_carla.py
python
_netconvert_carla_impl
(xodr_file, output, tmpdir, guess_tls=False)
Implements netconvert carla.
Implements netconvert carla.
[ "Implements", "netconvert", "carla", "." ]
def _netconvert_carla_impl(xodr_file, output, tmpdir, guess_tls=False): """ Implements netconvert carla. """ # ---------- # netconvert # ---------- basename = os.path.splitext(os.path.basename(xodr_file))[0] tmp_sumo_net = os.path.join(tmpdir, basename + '.net.xml') try: basedir = os.path.dirname(os.path.realpath(__file__)) result = subprocess.call(['netconvert', '--opendrive', xodr_file, '--output-file', tmp_sumo_net, '--geometry.min-radius.fix', '--geometry.remove', '--opendrive.curve-resolution', '1', '--opendrive.import-all-lanes', '--type-files', os.path.join(basedir, 'data/opendrive_netconvert.typ.xml'), # Necessary to link odr and sumo ids. '--output.original-names', # Discard loading traffic lights as them will be inserted manually afterwards. '--tls.discard-loaded', 'true', ]) except subprocess.CalledProcessError: raise RuntimeError('There was an error when executing netconvert.') else: if result != 0: raise RuntimeError('There was an error when executing netconvert.') # -------- # Sumo net # -------- sumo_net = sumolib.net.readNet(tmp_sumo_net) sumo_topology = build_topology(sumo_net) # --------- # Carla map # --------- with open(xodr_file, 'r') as f: carla_map = carla.Map('netconvert', str(f.read())) # --------- # Landmarks # --------- tls = {} # {tlsid: SumoTrafficLight} landmarks = carla_map.get_all_landmarks_of_type('1000001') for landmark in landmarks: if landmark.name == '': # This is a workaround to avoid adding traffic lights without controllers. logging.warning('Landmark %s has not a valid name.', landmark.name) continue road_id = str(landmark.road_id) for from_lane, to_lane in landmark.get_lane_validities(): for lane_id in range(from_lane, to_lane + 1): if lane_id == 0: continue wp = carla_map.get_waypoint_xodr(landmark.road_id, lane_id, landmark.s) if wp is None: logging.warning( 'Could not find waypoint for landmark {} (road_id: {}, lane_id: {}, s:{}'. format(landmark.id, landmark.road_id, lane_id, landmark.s)) continue # When the landmark belongs to a junction, we place te traffic light at the # entrance of the junction. if wp.is_junction and sumo_topology.is_junction(road_id, lane_id): tlid = str(wp.get_junction().id) if tlid not in tls: tls[tlid] = SumoTrafficLight(tlid) tl = tls[tlid] if guess_tls: for from_edge, from_lane in sumo_topology.get_incoming(road_id, lane_id): successors = sumo_topology.get_successors(from_edge, from_lane) for to_edge, to_lane in successors: tl.add_landmark(landmark.id, tl.id, from_edge, to_edge, from_lane, to_lane) else: connections = sumo_topology.get_path_connectivity(road_id, lane_id) for from_, to_ in connections: from_edge, from_lane = from_ to_edge, to_lane = to_ tl.add_landmark(landmark.id, tl.id, from_edge, to_edge, from_lane, to_lane) # When the landmarks does not belong to a junction (i.e., belongs to a std road), # we place the traffic light between that std road and its successor. elif not wp.is_junction and not sumo_topology.is_junction(road_id, lane_id): from_edge, from_lane = sumo_topology.get_sumo_id(road_id, lane_id, landmark.s) for to_edge, to_lane in sumo_topology.get_successors(from_edge, from_lane): tlid = SumoTrafficLight.generate_tl_id(from_edge, to_edge) if tlid not in tls: tls[tlid] = SumoTrafficLight(tlid) tl = tls[tlid] tl.add_landmark(landmark.id, tl.id, from_edge, to_edge, from_lane, to_lane) else: logging.warning('Landmark %s could not be added.', landmark.id) # --------------- # Modify sumo net # --------------- parser = ET.XMLParser(remove_blank_text=True) tree = ET.parse(tmp_sumo_net, parser) root = tree.getroot() for tl in tls.values(): SumoTrafficLight.generate_default_program(tl) edges_tags = tree.xpath('//edge') if not edges_tags: raise RuntimeError('No edges found in sumo net.') root.insert(root.index(edges_tags[-1]) + 1, tl.to_xml()) for connection in tl.connections: tags = tree.xpath( '//connection[@from="{}" and @to="{}" and @fromLane="{}" and @toLane="{}"]'.format( connection.from_road, connection.to_road, connection.from_lane, connection.to_lane)) if tags: if len(tags) > 1: logging.warning( 'Found repeated connections from={} to={} fromLane={} toLane={}.'.format( connection.from_road, connection.to_road, connection.from_lane, connection.to_lane)) tags[0].set('tl', str(connection.tlid)) tags[0].set('linkIndex', str(connection.link_index)) else: logging.warning('Not found connection from={} to={} fromLane={} toLane={}.'.format( connection.from_road, connection.to_road, connection.from_lane, connection.to_lane)) tree.write(output, pretty_print=True, encoding='UTF-8', xml_declaration=True)
[ "def", "_netconvert_carla_impl", "(", "xodr_file", ",", "output", ",", "tmpdir", ",", "guess_tls", "=", "False", ")", ":", "# ----------", "# netconvert", "# ----------", "basename", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "xodr_file", ")", ")", "[", "0", "]", "tmp_sumo_net", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "basename", "+", "'.net.xml'", ")", "try", ":", "basedir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "result", "=", "subprocess", ".", "call", "(", "[", "'netconvert'", ",", "'--opendrive'", ",", "xodr_file", ",", "'--output-file'", ",", "tmp_sumo_net", ",", "'--geometry.min-radius.fix'", ",", "'--geometry.remove'", ",", "'--opendrive.curve-resolution'", ",", "'1'", ",", "'--opendrive.import-all-lanes'", ",", "'--type-files'", ",", "os", ".", "path", ".", "join", "(", "basedir", ",", "'data/opendrive_netconvert.typ.xml'", ")", ",", "# Necessary to link odr and sumo ids.", "'--output.original-names'", ",", "# Discard loading traffic lights as them will be inserted manually afterwards.", "'--tls.discard-loaded'", ",", "'true'", ",", "]", ")", "except", "subprocess", ".", "CalledProcessError", ":", "raise", "RuntimeError", "(", "'There was an error when executing netconvert.'", ")", "else", ":", "if", "result", "!=", "0", ":", "raise", "RuntimeError", "(", "'There was an error when executing netconvert.'", ")", "# --------", "# Sumo net", "# --------", "sumo_net", "=", "sumolib", ".", "net", ".", "readNet", "(", "tmp_sumo_net", ")", "sumo_topology", "=", "build_topology", "(", "sumo_net", ")", "# ---------", "# Carla map", "# ---------", "with", "open", "(", "xodr_file", ",", "'r'", ")", "as", "f", ":", "carla_map", "=", "carla", ".", "Map", "(", "'netconvert'", ",", "str", "(", "f", ".", "read", "(", ")", ")", ")", "# ---------", "# Landmarks", "# ---------", "tls", "=", "{", "}", "# {tlsid: SumoTrafficLight}", "landmarks", "=", "carla_map", ".", "get_all_landmarks_of_type", "(", "'1000001'", ")", "for", "landmark", "in", "landmarks", ":", "if", "landmark", ".", "name", "==", "''", ":", "# This is a workaround to avoid adding traffic lights without controllers.", "logging", ".", "warning", "(", "'Landmark %s has not a valid name.'", ",", "landmark", ".", "name", ")", "continue", "road_id", "=", "str", "(", "landmark", ".", "road_id", ")", "for", "from_lane", ",", "to_lane", "in", "landmark", ".", "get_lane_validities", "(", ")", ":", "for", "lane_id", "in", "range", "(", "from_lane", ",", "to_lane", "+", "1", ")", ":", "if", "lane_id", "==", "0", ":", "continue", "wp", "=", "carla_map", ".", "get_waypoint_xodr", "(", "landmark", ".", "road_id", ",", "lane_id", ",", "landmark", ".", "s", ")", "if", "wp", "is", "None", ":", "logging", ".", "warning", "(", "'Could not find waypoint for landmark {} (road_id: {}, lane_id: {}, s:{}'", ".", "format", "(", "landmark", ".", "id", ",", "landmark", ".", "road_id", ",", "lane_id", ",", "landmark", ".", "s", ")", ")", "continue", "# When the landmark belongs to a junction, we place te traffic light at the", "# entrance of the junction.", "if", "wp", ".", "is_junction", "and", "sumo_topology", ".", "is_junction", "(", "road_id", ",", "lane_id", ")", ":", "tlid", "=", "str", "(", "wp", ".", "get_junction", "(", ")", ".", "id", ")", "if", "tlid", "not", "in", "tls", ":", "tls", "[", "tlid", "]", "=", "SumoTrafficLight", "(", "tlid", ")", "tl", "=", "tls", "[", "tlid", "]", "if", "guess_tls", ":", "for", "from_edge", ",", "from_lane", "in", "sumo_topology", ".", "get_incoming", "(", "road_id", ",", "lane_id", ")", ":", "successors", "=", "sumo_topology", ".", "get_successors", "(", "from_edge", ",", "from_lane", ")", "for", "to_edge", ",", "to_lane", "in", "successors", ":", "tl", ".", "add_landmark", "(", "landmark", ".", "id", ",", "tl", ".", "id", ",", "from_edge", ",", "to_edge", ",", "from_lane", ",", "to_lane", ")", "else", ":", "connections", "=", "sumo_topology", ".", "get_path_connectivity", "(", "road_id", ",", "lane_id", ")", "for", "from_", ",", "to_", "in", "connections", ":", "from_edge", ",", "from_lane", "=", "from_", "to_edge", ",", "to_lane", "=", "to_", "tl", ".", "add_landmark", "(", "landmark", ".", "id", ",", "tl", ".", "id", ",", "from_edge", ",", "to_edge", ",", "from_lane", ",", "to_lane", ")", "# When the landmarks does not belong to a junction (i.e., belongs to a std road),", "# we place the traffic light between that std road and its successor.", "elif", "not", "wp", ".", "is_junction", "and", "not", "sumo_topology", ".", "is_junction", "(", "road_id", ",", "lane_id", ")", ":", "from_edge", ",", "from_lane", "=", "sumo_topology", ".", "get_sumo_id", "(", "road_id", ",", "lane_id", ",", "landmark", ".", "s", ")", "for", "to_edge", ",", "to_lane", "in", "sumo_topology", ".", "get_successors", "(", "from_edge", ",", "from_lane", ")", ":", "tlid", "=", "SumoTrafficLight", ".", "generate_tl_id", "(", "from_edge", ",", "to_edge", ")", "if", "tlid", "not", "in", "tls", ":", "tls", "[", "tlid", "]", "=", "SumoTrafficLight", "(", "tlid", ")", "tl", "=", "tls", "[", "tlid", "]", "tl", ".", "add_landmark", "(", "landmark", ".", "id", ",", "tl", ".", "id", ",", "from_edge", ",", "to_edge", ",", "from_lane", ",", "to_lane", ")", "else", ":", "logging", ".", "warning", "(", "'Landmark %s could not be added.'", ",", "landmark", ".", "id", ")", "# ---------------", "# Modify sumo net", "# ---------------", "parser", "=", "ET", ".", "XMLParser", "(", "remove_blank_text", "=", "True", ")", "tree", "=", "ET", ".", "parse", "(", "tmp_sumo_net", ",", "parser", ")", "root", "=", "tree", ".", "getroot", "(", ")", "for", "tl", "in", "tls", ".", "values", "(", ")", ":", "SumoTrafficLight", ".", "generate_default_program", "(", "tl", ")", "edges_tags", "=", "tree", ".", "xpath", "(", "'//edge'", ")", "if", "not", "edges_tags", ":", "raise", "RuntimeError", "(", "'No edges found in sumo net.'", ")", "root", ".", "insert", "(", "root", ".", "index", "(", "edges_tags", "[", "-", "1", "]", ")", "+", "1", ",", "tl", ".", "to_xml", "(", ")", ")", "for", "connection", "in", "tl", ".", "connections", ":", "tags", "=", "tree", ".", "xpath", "(", "'//connection[@from=\"{}\" and @to=\"{}\" and @fromLane=\"{}\" and @toLane=\"{}\"]'", ".", "format", "(", "connection", ".", "from_road", ",", "connection", ".", "to_road", ",", "connection", ".", "from_lane", ",", "connection", ".", "to_lane", ")", ")", "if", "tags", ":", "if", "len", "(", "tags", ")", ">", "1", ":", "logging", ".", "warning", "(", "'Found repeated connections from={} to={} fromLane={} toLane={}.'", ".", "format", "(", "connection", ".", "from_road", ",", "connection", ".", "to_road", ",", "connection", ".", "from_lane", ",", "connection", ".", "to_lane", ")", ")", "tags", "[", "0", "]", ".", "set", "(", "'tl'", ",", "str", "(", "connection", ".", "tlid", ")", ")", "tags", "[", "0", "]", ".", "set", "(", "'linkIndex'", ",", "str", "(", "connection", ".", "link_index", ")", ")", "else", ":", "logging", ".", "warning", "(", "'Not found connection from={} to={} fromLane={} toLane={}.'", ".", "format", "(", "connection", ".", "from_road", ",", "connection", ".", "to_road", ",", "connection", ".", "from_lane", ",", "connection", ".", "to_lane", ")", ")", "tree", ".", "write", "(", "output", ",", "pretty_print", "=", "True", ",", "encoding", "=", "'UTF-8'", ",", "xml_declaration", "=", "True", ")" ]
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/Co-Simulation/Sumo/util/netconvert_carla.py#L365-L507
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/__init__.py
python
_ensure_pynumpy
()
Make sure Python and Numpy have supported versions.
Make sure Python and Numpy have supported versions.
[ "Make", "sure", "Python", "and", "Numpy", "have", "supported", "versions", "." ]
def _ensure_pynumpy(): """ Make sure Python and Numpy have supported versions. """ import warnings from . import numpy_support pyver = sys.version_info[:2] if pyver < (2, 7) or ((3,) <= pyver < (3, 4)): raise ImportError("Numba needs Python 2.7 or greater, or 3.4 or greater") np_version = numpy_support.version[:2] if np_version < (1, 7): raise ImportError("Numba needs Numpy 1.7 or greater")
[ "def", "_ensure_pynumpy", "(", ")", ":", "import", "warnings", "from", ".", "import", "numpy_support", "pyver", "=", "sys", ".", "version_info", "[", ":", "2", "]", "if", "pyver", "<", "(", "2", ",", "7", ")", "or", "(", "(", "3", ",", ")", "<=", "pyver", "<", "(", "3", ",", "4", ")", ")", ":", "raise", "ImportError", "(", "\"Numba needs Python 2.7 or greater, or 3.4 or greater\"", ")", "np_version", "=", "numpy_support", ".", "version", "[", ":", "2", "]", "if", "np_version", "<", "(", "1", ",", "7", ")", ":", "raise", "ImportError", "(", "\"Numba needs Numpy 1.7 or greater\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/__init__.py#L112-L125
QMCPACK/qmcpack
d0948ab455e38364458740cc8e2239600a14c5cd
src/QMCTools/PyscfToQmcpack_Spline.py
python
InputXml.simulationcell_from_cell
(self,cell,bconds='p p p',lr_cut=15.0)
return sc_node
construct the <simulationcell> xml element from pyscf.pbc.gto.Cell class Inputs: cell: pyscf.pbc.gto.Cell class, should have lattice_vectors() and unit bconds: boundary conditions in each of the x,y,z directions, p for periodic, n for non-periodic, default to 'p p p ' lr_cut: long-range cutoff parameter rc*kc, default to 15 Output: etree.Element representing <simulationcell> Effect: none
construct the <simulationcell> xml element from pyscf.pbc.gto.Cell class Inputs: cell: pyscf.pbc.gto.Cell class, should have lattice_vectors() and unit bconds: boundary conditions in each of the x,y,z directions, p for periodic, n for non-periodic, default to 'p p p ' lr_cut: long-range cutoff parameter rc*kc, default to 15 Output: etree.Element representing <simulationcell> Effect: none
[ "construct", "the", "<simulationcell", ">", "xml", "element", "from", "pyscf", ".", "pbc", ".", "gto", ".", "Cell", "class", "Inputs", ":", "cell", ":", "pyscf", ".", "pbc", ".", "gto", ".", "Cell", "class", "should", "have", "lattice_vectors", "()", "and", "unit", "bconds", ":", "boundary", "conditions", "in", "each", "of", "the", "x", "y", "z", "directions", "p", "for", "periodic", "n", "for", "non", "-", "periodic", "default", "to", "p", "p", "p", "lr_cut", ":", "long", "-", "range", "cutoff", "parameter", "rc", "*", "kc", "default", "to", "15", "Output", ":", "etree", ".", "Element", "representing", "<simulationcell", ">", "Effect", ":", "none" ]
def simulationcell_from_cell(self,cell,bconds='p p p',lr_cut=15.0): """ construct the <simulationcell> xml element from pyscf.pbc.gto.Cell class Inputs: cell: pyscf.pbc.gto.Cell class, should have lattice_vectors() and unit bconds: boundary conditions in each of the x,y,z directions, p for periodic, n for non-periodic, default to 'p p p ' lr_cut: long-range cutoff parameter rc*kc, default to 15 Output: etree.Element representing <simulationcell> Effect: none """ # write primitive lattice vectors axes = cell.lattice_vectors() # rely on pyscf to return a.u. lat_node = etree.Element('parameter' ,attrib={'name':'lattice','units':'bohr'}) lat_node.text = self.arr2text(axes) + " " # write boundary conditions bconds_node = etree.Element('parameter',{'name':'bconds'}) bconds_node.text = bconds # write long-range cutoff parameter lr_node = etree.Element('parameter',{'name':'LR_dim_cutoff'}) lr_node.text = str(lr_cut) # build <simulationcell> sc_node = etree.Element('simulationcell') sc_node.append(lat_node) sc_node.append(bconds_node) sc_node.append(lr_node) return sc_node
[ "def", "simulationcell_from_cell", "(", "self", ",", "cell", ",", "bconds", "=", "'p p p'", ",", "lr_cut", "=", "15.0", ")", ":", "# write primitive lattice vectors", "axes", "=", "cell", ".", "lattice_vectors", "(", ")", "# rely on pyscf to return a.u.", "lat_node", "=", "etree", ".", "Element", "(", "'parameter'", ",", "attrib", "=", "{", "'name'", ":", "'lattice'", ",", "'units'", ":", "'bohr'", "}", ")", "lat_node", ".", "text", "=", "self", ".", "arr2text", "(", "axes", ")", "+", "\" \"", "# write boundary conditions", "bconds_node", "=", "etree", ".", "Element", "(", "'parameter'", ",", "{", "'name'", ":", "'bconds'", "}", ")", "bconds_node", ".", "text", "=", "bconds", "# write long-range cutoff parameter", "lr_node", "=", "etree", ".", "Element", "(", "'parameter'", ",", "{", "'name'", ":", "'LR_dim_cutoff'", "}", ")", "lr_node", ".", "text", "=", "str", "(", "lr_cut", ")", "# build <simulationcell>", "sc_node", "=", "etree", ".", "Element", "(", "'simulationcell'", ")", "sc_node", ".", "append", "(", "lat_node", ")", "sc_node", ".", "append", "(", "bconds_node", ")", "sc_node", ".", "append", "(", "lr_node", ")", "return", "sc_node" ]
https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/src/QMCTools/PyscfToQmcpack_Spline.py#L631-L662
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/cpplint.py
python
NestingState.Update
(self, filename, clean_lines, linenum, error)
Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Update nesting state with current line.
[ "Update", "nesting", "state", "with", "current", "line", "." ]
def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remember top of the previous nesting stack. # # The stack is always pushed/popped and not modified in place, so # we can just do a shallow copy instead of copy.deepcopy. Using # deepcopy would slow down cpplint by ~28%. if self.stack: self.previous_stack_top = self.stack[-1] else: self.previous_stack_top = None # Update pp_stack self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; class_decl_match = Match( r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?' r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' r'(.*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): # We do not want to accept classes that are actually template arguments: # template <class Ignore1, # class Ignore2 = Default<Args>, # template <Args> class Ignore3> # void Function() {}; # # To avoid template argument cases, we scan forward and look for # an unmatched '>'. If we see one, assume we are inside a # template argument list. end_declaration = len(class_decl_match.group(1)) if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): self.stack.append(_ClassInfo( class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(4) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True elif Match(r'^extern\s*"[^"]*"\s*\{', line): self.stack.append(_ExternCInfo()) else: self.stack.append(_BlockInfo(True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2)
[ "def", "Update", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remember top of the previous nesting stack.", "#", "# The stack is always pushed/popped and not modified in place, so", "# we can just do a shallow copy instead of copy.deepcopy. Using", "# deepcopy would slow down cpplint by ~28%.", "if", "self", ".", "stack", ":", "self", ".", "previous_stack_top", "=", "self", ".", "stack", "[", "-", "1", "]", "else", ":", "self", ".", "previous_stack_top", "=", "None", "# Update pp_stack", "self", ".", "UpdatePreprocessor", "(", "line", ")", "# Count parentheses. This is to avoid adding struct arguments to", "# the nesting stack.", "if", "self", ".", "stack", ":", "inner_block", "=", "self", ".", "stack", "[", "-", "1", "]", "depth_change", "=", "line", ".", "count", "(", "'('", ")", "-", "line", ".", "count", "(", "')'", ")", "inner_block", ".", "open_parentheses", "+=", "depth_change", "# Also check if we are starting or ending an inline assembly block.", "if", "inner_block", ".", "inline_asm", "in", "(", "_NO_ASM", ",", "_END_ASM", ")", ":", "if", "(", "depth_change", "!=", "0", "and", "inner_block", ".", "open_parentheses", "==", "1", "and", "_MATCH_ASM", ".", "match", "(", "line", ")", ")", ":", "# Enter assembly block", "inner_block", ".", "inline_asm", "=", "_INSIDE_ASM", "else", ":", "# Not entering assembly block. If previous line was _END_ASM,", "# we will now shift to _NO_ASM state.", "inner_block", ".", "inline_asm", "=", "_NO_ASM", "elif", "(", "inner_block", ".", "inline_asm", "==", "_INSIDE_ASM", "and", "inner_block", ".", "open_parentheses", "==", "0", ")", ":", "# Exit assembly block", "inner_block", ".", "inline_asm", "=", "_END_ASM", "# Consume namespace declaration at the beginning of the line. Do", "# this in a loop so that we catch same line declarations like this:", "# namespace proto2 { namespace bridge { class MessageSet; } }", "while", "True", ":", "# Match start of namespace. The \"\\b\\s*\" below catches namespace", "# declarations even if it weren't followed by a whitespace, this", "# is so that we don't confuse our namespace checker. The", "# missing spaces will be flagged by CheckSpacing.", "namespace_decl_match", "=", "Match", "(", "r'^\\s*namespace\\b\\s*([:\\w]+)?(.*)$'", ",", "line", ")", "if", "not", "namespace_decl_match", ":", "break", "new_namespace", "=", "_NamespaceInfo", "(", "namespace_decl_match", ".", "group", "(", "1", ")", ",", "linenum", ")", "self", ".", "stack", ".", "append", "(", "new_namespace", ")", "line", "=", "namespace_decl_match", ".", "group", "(", "2", ")", "if", "line", ".", "find", "(", "'{'", ")", "!=", "-", "1", ":", "new_namespace", ".", "seen_open_brace", "=", "True", "line", "=", "line", "[", "line", ".", "find", "(", "'{'", ")", "+", "1", ":", "]", "# Look for a class declaration in whatever is left of the line", "# after parsing namespaces. The regexp accounts for decorated classes", "# such as in:", "# class LOCKABLE API Object {", "# };", "class_decl_match", "=", "Match", "(", "r'^(\\s*(?:template\\s*<[\\w\\s<>,:]*>\\s*)?'", "r'(class|struct)\\s+(?:[A-Z_]+\\s+)*(\\w+(?:::\\w+)*))'", "r'(.*)$'", ",", "line", ")", "if", "(", "class_decl_match", "and", "(", "not", "self", ".", "stack", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "open_parentheses", "==", "0", ")", ")", ":", "# We do not want to accept classes that are actually template arguments:", "# template <class Ignore1,", "# class Ignore2 = Default<Args>,", "# template <Args> class Ignore3>", "# void Function() {};", "#", "# To avoid template argument cases, we scan forward and look for", "# an unmatched '>'. If we see one, assume we are inside a", "# template argument list.", "end_declaration", "=", "len", "(", "class_decl_match", ".", "group", "(", "1", ")", ")", "if", "not", "self", ".", "InTemplateArgumentList", "(", "clean_lines", ",", "linenum", ",", "end_declaration", ")", ":", "self", ".", "stack", ".", "append", "(", "_ClassInfo", "(", "class_decl_match", ".", "group", "(", "3", ")", ",", "class_decl_match", ".", "group", "(", "2", ")", ",", "clean_lines", ",", "linenum", ")", ")", "line", "=", "class_decl_match", ".", "group", "(", "4", ")", "# If we have not yet seen the opening brace for the innermost block,", "# run checks here.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "CheckBegin", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "# Update access control if we are inside a class/struct", "if", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "-", "1", "]", "access_match", "=", "Match", "(", "r'^(.*)\\b(public|private|protected|signals)(\\s+(?:slots\\s*)?)?'", "r':(?:[^:]|$)'", ",", "line", ")", "if", "access_match", ":", "classinfo", ".", "access", "=", "access_match", ".", "group", "(", "2", ")", "# Check that access keywords are indented +1 space. Skip this", "# check if the keywords are not preceded by whitespaces.", "indent", "=", "access_match", ".", "group", "(", "1", ")", "if", "(", "len", "(", "indent", ")", "!=", "classinfo", ".", "class_indent", "+", "1", "and", "Match", "(", "r'^\\s*$'", ",", "indent", ")", ")", ":", "if", "classinfo", ".", "is_struct", ":", "parent", "=", "'struct '", "+", "classinfo", ".", "name", "else", ":", "parent", "=", "'class '", "+", "classinfo", ".", "name", "slots", "=", "''", "if", "access_match", ".", "group", "(", "3", ")", ":", "slots", "=", "access_match", ".", "group", "(", "3", ")", "error", "(", "filename", ",", "linenum", ",", "'whitespace/indent'", ",", "3", ",", "'%s%s: should be indented +1 space inside %s'", "%", "(", "access_match", ".", "group", "(", "2", ")", ",", "slots", ",", "parent", ")", ")", "# Consume braces or semicolons from what's left of the line", "while", "True", ":", "# Match first brace, semicolon, or closed parenthesis.", "matched", "=", "Match", "(", "r'^[^{;)}]*([{;)}])(.*)$'", ",", "line", ")", "if", "not", "matched", ":", "break", "token", "=", "matched", ".", "group", "(", "1", ")", "if", "token", "==", "'{'", ":", "# If namespace or class hasn't seen a opening brace yet, mark", "# namespace/class head as complete. Push a new block onto the", "# stack otherwise.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace", "=", "True", "elif", "Match", "(", "r'^extern\\s*\"[^\"]*\"\\s*\\{'", ",", "line", ")", ":", "self", ".", "stack", ".", "append", "(", "_ExternCInfo", "(", ")", ")", "else", ":", "self", ".", "stack", ".", "append", "(", "_BlockInfo", "(", "True", ")", ")", "if", "_MATCH_ASM", ".", "match", "(", "line", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "inline_asm", "=", "_BLOCK_ASM", "elif", "token", "==", "';'", "or", "token", "==", "')'", ":", "# If we haven't seen an opening brace yet, but we already saw", "# a semicolon, this is probably a forward declaration. Pop", "# the stack for these.", "#", "# Similarly, if we haven't seen an opening brace yet, but we", "# already saw a closing parenthesis, then these are probably", "# function arguments with extra \"class\" or \"struct\" keywords.", "# Also pop these stack for these.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", ".", "pop", "(", ")", "else", ":", "# token == '}'", "# Perform end of block checks and pop the stack.", "if", "self", ".", "stack", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "CheckEnd", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "self", ".", "stack", ".", "pop", "(", ")", "line", "=", "matched", ".", "group", "(", "2", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L2364-L2526
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/numeric.py
python
ones_like
(a, dtype=None, order='K', subok=True)
return res
Return an array of ones with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional .. versionadded:: 1.6.0 Overrides the data type of the result. order : {'C', 'F', 'A', or 'K'}, optional .. versionadded:: 1.6.0 Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. Returns ------- out : ndarray Array of ones with the same shape and type as `a`. See Also -------- zeros_like : Return an array of zeros with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.ones_like(x) array([[1, 1, 1], [1, 1, 1]]) >>> y = np.arange(3, dtype=np.float) >>> y array([ 0., 1., 2.]) >>> np.ones_like(y) array([ 1., 1., 1.])
Return an array of ones with the same shape and type as a given array.
[ "Return", "an", "array", "of", "ones", "with", "the", "same", "shape", "and", "type", "as", "a", "given", "array", "." ]
def ones_like(a, dtype=None, order='K', subok=True): """ Return an array of ones with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional .. versionadded:: 1.6.0 Overrides the data type of the result. order : {'C', 'F', 'A', or 'K'}, optional .. versionadded:: 1.6.0 Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. Returns ------- out : ndarray Array of ones with the same shape and type as `a`. See Also -------- zeros_like : Return an array of zeros with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.ones_like(x) array([[1, 1, 1], [1, 1, 1]]) >>> y = np.arange(3, dtype=np.float) >>> y array([ 0., 1., 2.]) >>> np.ones_like(y) array([ 1., 1., 1.]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok) multiarray.copyto(res, 1, casting='unsafe') return res
[ "def", "ones_like", "(", "a", ",", "dtype", "=", "None", ",", "order", "=", "'K'", ",", "subok", "=", "True", ")", ":", "res", "=", "empty_like", "(", "a", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", "subok", "=", "subok", ")", "multiarray", ".", "copyto", "(", "res", ",", "1", ",", "casting", "=", "'unsafe'", ")", "return", "res" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/numeric.py#L182-L238
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/vcs/git.py
python
Git._get_subdirectory
(cls, location)
return os.path.relpath(location, root_dir)
Return the relative path of setup.py to the git repo root.
Return the relative path of setup.py to the git repo root.
[ "Return", "the", "relative", "path", "of", "setup", ".", "py", "to", "the", "git", "repo", "root", "." ]
def _get_subdirectory(cls, location): """Return the relative path of setup.py to the git repo root.""" # find the repo root git_dir = cls.run_command(['rev-parse', '--git-dir'], show_stdout=False, cwd=location).strip() if not os.path.isabs(git_dir): git_dir = os.path.join(location, git_dir) root_dir = os.path.join(git_dir, '..') # find setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None # relative path of setup.py to repo root if samefile(root_dir, location): return None return os.path.relpath(location, root_dir)
[ "def", "_get_subdirectory", "(", "cls", ",", "location", ")", ":", "# find the repo root", "git_dir", "=", "cls", ".", "run_command", "(", "[", "'rev-parse'", ",", "'--git-dir'", "]", ",", "show_stdout", "=", "False", ",", "cwd", "=", "location", ")", ".", "strip", "(", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "git_dir", ")", ":", "git_dir", "=", "os", ".", "path", ".", "join", "(", "location", ",", "git_dir", ")", "root_dir", "=", "os", ".", "path", ".", "join", "(", "git_dir", ",", "'..'", ")", "# find setup.py", "orig_location", "=", "location", "while", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "location", ",", "'setup.py'", ")", ")", ":", "last_location", "=", "location", "location", "=", "os", ".", "path", ".", "dirname", "(", "location", ")", "if", "location", "==", "last_location", ":", "# We've traversed up to the root of the filesystem without", "# finding setup.py", "logger", ".", "warning", "(", "\"Could not find setup.py for directory %s (tried all \"", "\"parent directories)\"", ",", "orig_location", ",", ")", "return", "None", "# relative path of setup.py to repo root", "if", "samefile", "(", "root_dir", ",", "location", ")", ":", "return", "None", "return", "os", ".", "path", ".", "relpath", "(", "location", ",", "root_dir", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/vcs/git.py#L289-L314
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/configure.d/nodedownload.py
python
parse
(opt)
return theRet
This function parses the options to --download and returns a set such as { icu: true }, etc.
This function parses the options to --download and returns a set such as { icu: true }, etc.
[ "This", "function", "parses", "the", "options", "to", "--", "download", "and", "returns", "a", "set", "such", "as", "{", "icu", ":", "true", "}", "etc", "." ]
def parse(opt): """This function parses the options to --download and returns a set such as { icu: true }, etc. """ if not opt: opt = download_default theOpts = set(opt.split(',')) if 'all' in theOpts: # all on return set2dict(download_types, True) elif 'none' in theOpts: # all off return set2dict(download_types, False) # OK. Now, process each of the opts. theRet = set2dict(download_types, False) for anOpt in opt.split(','): if not anOpt or anOpt == "": # ignore stray commas, etc. continue elif anOpt is 'all': # all on theRet = dict((key, True) for (key) in download_types) else: # turn this one on if anOpt in download_types: theRet[anOpt] = True else: # future proof: ignore unknown types print 'Warning: ignoring unknown --download= type "%s"' % anOpt # all done return theRet
[ "def", "parse", "(", "opt", ")", ":", "if", "not", "opt", ":", "opt", "=", "download_default", "theOpts", "=", "set", "(", "opt", ".", "split", "(", "','", ")", ")", "if", "'all'", "in", "theOpts", ":", "# all on", "return", "set2dict", "(", "download_types", ",", "True", ")", "elif", "'none'", "in", "theOpts", ":", "# all off", "return", "set2dict", "(", "download_types", ",", "False", ")", "# OK. Now, process each of the opts.", "theRet", "=", "set2dict", "(", "download_types", ",", "False", ")", "for", "anOpt", "in", "opt", ".", "split", "(", "','", ")", ":", "if", "not", "anOpt", "or", "anOpt", "==", "\"\"", ":", "# ignore stray commas, etc.", "continue", "elif", "anOpt", "is", "'all'", ":", "# all on", "theRet", "=", "dict", "(", "(", "key", ",", "True", ")", "for", "(", "key", ")", "in", "download_types", ")", "else", ":", "# turn this one on", "if", "anOpt", "in", "download_types", ":", "theRet", "[", "anOpt", "]", "=", "True", "else", ":", "# future proof: ignore unknown types", "print", "'Warning: ignoring unknown --download= type \"%s\"'", "%", "anOpt", "# all done", "return", "theRet" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/configure.d/nodedownload.py#L86-L117
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py
python
URLopener.addheader
(self, *args)
Add a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')
Add a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')
[ "Add", "a", "header", "to", "be", "used", "by", "the", "HTTP", "interface", "only", "e", ".", "g", ".", "u", ".", "addheader", "(", "Accept", "sound", "/", "basic", ")" ]
def addheader(self, *args): """Add a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')""" self.addheaders.append(args)
[ "def", "addheader", "(", "self", ",", "*", "args", ")", ":", "self", ".", "addheaders", ".", "append", "(", "args", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/urllib.py#L172-L175
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
FlagValues.__GetFlagFileLines
(self, filename, parsed_file_list)
return flag_line_list
Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile=<foo> tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//').
Returns the useful (!=comments, etc) lines from a file with flags.
[ "Returns", "the", "useful", "(", "!", "=", "comments", "etc", ")", "lines", "from", "a", "file", "with", "flags", "." ]
def __GetFlagFileLines(self, filename, parsed_file_list): """Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile=<foo> tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//'). """ line_list = [] # All line from flagfile. flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags. try: file_obj = open(filename, 'r') except IOError, e_msg: raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) # This is where we check each line in the file we just read. for line in line_list: if line.isspace(): pass # Checks for comment (a line that starts with '#'). elif line.startswith('#') or line.startswith('//'): pass # Checks for a nested "--flagfile=<bar>" flag in the current file. # If we find one, recursively parse down into that file. elif self.__IsFlagFileDirective(line): sub_filename = self.ExtractFilename(line) # We do a little safety check for reparsing a file we've already done. if not sub_filename in parsed_file_list: included_flags = self.__GetFlagFileLines(sub_filename, parsed_file_list) flag_line_list.extend(included_flags) else: # Case of hitting a circularly included file. sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' % (sub_filename,)) else: # Any line that's not a comment or a nested flagfile should get # copied into 2nd position. This leaves earlier arguments # further back in the list, thus giving them higher priority. flag_line_list.append(line.strip()) return flag_line_list
[ "def", "__GetFlagFileLines", "(", "self", ",", "filename", ",", "parsed_file_list", ")", ":", "line_list", "=", "[", "]", "# All line from flagfile.", "flag_line_list", "=", "[", "]", "# Subset of lines w/o comments, blanks, flagfile= tags.", "try", ":", "file_obj", "=", "open", "(", "filename", ",", "'r'", ")", "except", "IOError", ",", "e_msg", ":", "raise", "CantOpenFlagFileError", "(", "'ERROR:: Unable to open flagfile: %s'", "%", "e_msg", ")", "line_list", "=", "file_obj", ".", "readlines", "(", ")", "file_obj", ".", "close", "(", ")", "parsed_file_list", ".", "append", "(", "filename", ")", "# This is where we check each line in the file we just read.", "for", "line", "in", "line_list", ":", "if", "line", ".", "isspace", "(", ")", ":", "pass", "# Checks for comment (a line that starts with '#').", "elif", "line", ".", "startswith", "(", "'#'", ")", "or", "line", ".", "startswith", "(", "'//'", ")", ":", "pass", "# Checks for a nested \"--flagfile=<bar>\" flag in the current file.", "# If we find one, recursively parse down into that file.", "elif", "self", ".", "__IsFlagFileDirective", "(", "line", ")", ":", "sub_filename", "=", "self", ".", "ExtractFilename", "(", "line", ")", "# We do a little safety check for reparsing a file we've already done.", "if", "not", "sub_filename", "in", "parsed_file_list", ":", "included_flags", "=", "self", ".", "__GetFlagFileLines", "(", "sub_filename", ",", "parsed_file_list", ")", "flag_line_list", ".", "extend", "(", "included_flags", ")", "else", ":", "# Case of hitting a circularly included file.", "sys", ".", "stderr", ".", "write", "(", "'Warning: Hit circular flagfile dependency: %s\\n'", "%", "(", "sub_filename", ",", ")", ")", "else", ":", "# Any line that's not a comment or a nested flagfile should get", "# copied into 2nd position. This leaves earlier arguments", "# further back in the list, thus giving them higher priority.", "flag_line_list", ".", "append", "(", "line", ".", "strip", "(", ")", ")", "return", "flag_line_list" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1552-L1604
google/sandboxed-api
7004d59150c9fbfaa3e5fd1872affffd1ab14fe8
oss-internship-2020/libuv/generator/wrapper_generator.py
python
get_var_type
(string: str)
return " ".join(var.split(" ")[:-1]).strip()
Gets the type from an argument variable. Args: string: Input variable declaration Returns: The type of the argument variable as a string, e.g. "int x" -> "int".
Gets the type from an argument variable.
[ "Gets", "the", "type", "from", "an", "argument", "variable", "." ]
def get_var_type(string: str) -> str: """Gets the type from an argument variable. Args: string: Input variable declaration Returns: The type of the argument variable as a string, e.g. "int x" -> "int". """ var = string.strip() # Unnamed variable if var in ("void", "...") or var[-1] == "*": return var return " ".join(var.split(" ")[:-1]).strip()
[ "def", "get_var_type", "(", "string", ":", "str", ")", "->", "str", ":", "var", "=", "string", ".", "strip", "(", ")", "# Unnamed variable", "if", "var", "in", "(", "\"void\"", ",", "\"...\"", ")", "or", "var", "[", "-", "1", "]", "==", "\"*\"", ":", "return", "var", "return", "\" \"", ".", "join", "(", "var", ".", "split", "(", "\" \"", ")", "[", ":", "-", "1", "]", ")", ".", "strip", "(", ")" ]
https://github.com/google/sandboxed-api/blob/7004d59150c9fbfaa3e5fd1872affffd1ab14fe8/oss-internship-2020/libuv/generator/wrapper_generator.py#L27-L43
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
GridBagSizer.SetItemPosition
(*args)
return _core_.GridBagSizer_SetItemPosition(*args)
SetItemPosition(self, item, GBPosition pos) -> bool Set the grid position of the specified *item* where *item* is either a window or subsizer that is a member of this sizer, or a zero-based index of an item. Returns True on success. If the move is not allowed (because an item is already there) then False is returned.
SetItemPosition(self, item, GBPosition pos) -> bool
[ "SetItemPosition", "(", "self", "item", "GBPosition", "pos", ")", "-", ">", "bool" ]
def SetItemPosition(*args): """ SetItemPosition(self, item, GBPosition pos) -> bool Set the grid position of the specified *item* where *item* is either a window or subsizer that is a member of this sizer, or a zero-based index of an item. Returns True on success. If the move is not allowed (because an item is already there) then False is returned. """ return _core_.GridBagSizer_SetItemPosition(*args)
[ "def", "SetItemPosition", "(", "*", "args", ")", ":", "return", "_core_", ".", "GridBagSizer_SetItemPosition", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L15982-L15992
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiDockingGuideWindow.__init__
(self, parent, rect, direction=0, center=False, useAero=False)
Default class constructor. Used internally, do not call it in your code! :param `parent`: the :class:`AuiManager` parent; :param Rect `rect`: the window rect; :param integer `direction`: one of ``wx.TOP``, ``wx.BOTTOM``, ``wx.LEFT``, ``wx.RIGHT``, ``wx.CENTER``; :param bool `center`: whether the calling class is a :class:`AuiCenterDockingGuide`; :param bool `useAero`: whether to use the new Aero-style bitmaps or Whidbey-style bitmaps for the docking guide.
Default class constructor. Used internally, do not call it in your code!
[ "Default", "class", "constructor", ".", "Used", "internally", "do", "not", "call", "it", "in", "your", "code!" ]
def __init__(self, parent, rect, direction=0, center=False, useAero=False): """ Default class constructor. Used internally, do not call it in your code! :param `parent`: the :class:`AuiManager` parent; :param Rect `rect`: the window rect; :param integer `direction`: one of ``wx.TOP``, ``wx.BOTTOM``, ``wx.LEFT``, ``wx.RIGHT``, ``wx.CENTER``; :param bool `center`: whether the calling class is a :class:`AuiCenterDockingGuide`; :param bool `useAero`: whether to use the new Aero-style bitmaps or Whidbey-style bitmaps for the docking guide. """ wx.Window.__init__(self, parent, -1, rect.GetPosition(), rect.GetSize(), wx.NO_BORDER) self._direction = direction self._center = center self._valid = True self._useAero = useAero self._bmp_unfocus, self._bmp_focus = GetDockingImage(direction, useAero, center) self._currentImage = self._bmp_unfocus self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) self.Bind(wx.EVT_PAINT, self.OnPaint)
[ "def", "__init__", "(", "self", ",", "parent", ",", "rect", ",", "direction", "=", "0", ",", "center", "=", "False", ",", "useAero", "=", "False", ")", ":", "wx", ".", "Window", ".", "__init__", "(", "self", ",", "parent", ",", "-", "1", ",", "rect", ".", "GetPosition", "(", ")", ",", "rect", ".", "GetSize", "(", ")", ",", "wx", ".", "NO_BORDER", ")", "self", ".", "_direction", "=", "direction", "self", ".", "_center", "=", "center", "self", ".", "_valid", "=", "True", "self", ".", "_useAero", "=", "useAero", "self", ".", "_bmp_unfocus", ",", "self", ".", "_bmp_focus", "=", "GetDockingImage", "(", "direction", ",", "useAero", ",", "center", ")", "self", ".", "_currentImage", "=", "self", ".", "_bmp_unfocus", "self", ".", "SetBackgroundStyle", "(", "wx", ".", "BG_STYLE_CUSTOM", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_ERASE_BACKGROUND", ",", "self", ".", "OnEraseBackground", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_PAINT", ",", "self", ".", "OnPaint", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L1928-L1954
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/message.py
python
Message.ByteSize
(self)
Returns the serialized size of this message. Recursively calls ByteSize() on all contained messages.
Returns the serialized size of this message. Recursively calls ByteSize() on all contained messages.
[ "Returns", "the", "serialized", "size", "of", "this", "message", ".", "Recursively", "calls", "ByteSize", "()", "on", "all", "contained", "messages", "." ]
def ByteSize(self): """Returns the serialized size of this message. Recursively calls ByteSize() on all contained messages. """ raise NotImplementedError
[ "def", "ByteSize", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/message.py#L246-L250
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/generator.py
python
_CppSourceFileWriter.gen_field_list_entries_declaration
(self, field_list)
Generate the field list entries map for a generic argument or reply field list.
Generate the field list entries map for a generic argument or reply field list.
[ "Generate", "the", "field", "list", "entries", "map", "for", "a", "generic", "argument", "or", "reply", "field", "list", "." ]
def gen_field_list_entries_declaration(self, field_list): # type: (ast.FieldListBase) -> None """Generate the field list entries map for a generic argument or reply field list.""" klass = common.title_case(field_list.cpp_name) field_list_info = generic_field_list_types.get_field_list_info(field_list) self._writer.write_line( common.template_args('// Map: fieldName -> ${should_forward_name}', should_forward_name=field_list_info.get_should_forward_name())) block_name = common.template_args( 'const stdx::unordered_map<std::string, bool> ${klass}::_genericFields {', klass=klass) with self._block(block_name, "};"): sorted_entries = sorted(field_list.fields, key=lambda f: f.name) for entry in sorted_entries: self._writer.write_line( common.template_args( '{"${name}", ${should_forward}},', klass=klass, name=entry.name, should_forward='true' if entry.get_should_forward() else 'false'))
[ "def", "gen_field_list_entries_declaration", "(", "self", ",", "field_list", ")", ":", "# type: (ast.FieldListBase) -> None", "klass", "=", "common", ".", "title_case", "(", "field_list", ".", "cpp_name", ")", "field_list_info", "=", "generic_field_list_types", ".", "get_field_list_info", "(", "field_list", ")", "self", ".", "_writer", ".", "write_line", "(", "common", ".", "template_args", "(", "'// Map: fieldName -> ${should_forward_name}'", ",", "should_forward_name", "=", "field_list_info", ".", "get_should_forward_name", "(", ")", ")", ")", "block_name", "=", "common", ".", "template_args", "(", "'const stdx::unordered_map<std::string, bool> ${klass}::_genericFields {'", ",", "klass", "=", "klass", ")", "with", "self", ".", "_block", "(", "block_name", ",", "\"};\"", ")", ":", "sorted_entries", "=", "sorted", "(", "field_list", ".", "fields", ",", "key", "=", "lambda", "f", ":", "f", ".", "name", ")", "for", "entry", "in", "sorted_entries", ":", "self", ".", "_writer", ".", "write_line", "(", "common", ".", "template_args", "(", "'{\"${name}\", ${should_forward}},'", ",", "klass", "=", "klass", ",", "name", "=", "entry", ".", "name", ",", "should_forward", "=", "'true'", "if", "entry", ".", "get_should_forward", "(", ")", "else", "'false'", ")", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/generator.py#L2263-L2279
GXYM/DRRG
9e074fa9052de8d131f55ca1f6ae6673c1bfeca4
dataset/dataload.py
python
TextDataset.fill_polygon
(mask, pts, value)
fill polygon in the mask with value :param mask: input mask :param pts: polygon to draw :param value: fill value
fill polygon in the mask with value :param mask: input mask :param pts: polygon to draw :param value: fill value
[ "fill", "polygon", "in", "the", "mask", "with", "value", ":", "param", "mask", ":", "input", "mask", ":", "param", "pts", ":", "polygon", "to", "draw", ":", "param", "value", ":", "fill", "value" ]
def fill_polygon(mask, pts, value): """ fill polygon in the mask with value :param mask: input mask :param pts: polygon to draw :param value: fill value """ # cv2.drawContours(mask, [polygon.astype(np.int32)], -1, value, -1) cv2.fillPoly(mask, [pts.astype(np.int32)], color=(value,))
[ "def", "fill_polygon", "(", "mask", ",", "pts", ",", "value", ")", ":", "# cv2.drawContours(mask, [polygon.astype(np.int32)], -1, value, -1)", "cv2", ".", "fillPoly", "(", "mask", ",", "[", "pts", ".", "astype", "(", "np", ".", "int32", ")", "]", ",", "color", "=", "(", "value", ",", ")", ")" ]
https://github.com/GXYM/DRRG/blob/9e074fa9052de8d131f55ca1f6ae6673c1bfeca4/dataset/dataload.py#L123-L131
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/android_studio.py
python
android_studio.process_module
(self, project, target_name, android_root, module_type, task_generator)
Adds the module to the project. If it's an application, then it parse the json file for the Android Libraries and adds those modules to the project also.
Adds the module to the project. If it's an application, then it parse the json file for the Android Libraries and adds those modules to the project also.
[ "Adds", "the", "module", "to", "the", "project", ".", "If", "it", "s", "an", "application", "then", "it", "parse", "the", "json", "file", "for", "the", "Android", "Libraries", "and", "adds", "those", "modules", "to", "the", "project", "also", "." ]
def process_module(self, project, target_name, android_root, module_type, task_generator): ''' Adds the module to the project. If it's an application, then it parse the json file for the Android Libraries and adds those modules to the project also. ''' if module_type == Module.Type.Application: class _DummyTaskGenerator(object): def set_task_attribute(self, name, attr): if attr: setattr(self, name, attr) # Generate all the targets for the Android libraries android_java_libs = getattr(task_generator, 'android_java_libs', []) if android_java_libs: java_libs_json = self.root.make_node(android_java_libs) json_data = self.parse_json_file(java_libs_json) else: json_data = None if json_data: module_deps = [] for lib_name, value in json_data.items(): new_task_generator = _DummyTaskGenerator() # Check if the library was patched. If so, we need to look in a different folder. if 'patches' in value: lib_path = os.path.join(self.Path(self.get_android_patched_libraries_relative_path()), lib_name) else: # Search the multiple library paths where the library can be. lib_path = None for path in value['srcDir']: path = Template(path).substitute(self.env) path = to_gradle_path(path) if os.path.exists(path): lib_path = path break if not lib_path: paths = [ Template(path).substitute(self.env) for path in value['srcDir'] ] self.fatal('[ERROR] Failed to find library - {} - in path(s): {}. Please ' 'download the library from the Android SDK Manager and run the ' 'configure command again.'.format(lib_name, ", ".join(paths))) new_task_generator.set_task_attribute('path', self.path) new_task_generator.set_task_attribute('android_java_src_path', os.path.join(lib_path, 'src')) new_task_generator.set_task_attribute('android_res_path', os.path.join(lib_path, 'res')) new_task_generator.set_task_attribute('android_manifest_path', os.path.join(lib_path, 'AndroidManifest.xml')) new_task_generator.set_task_attribute('module_dependencies', value.get('dependencies', None)) if value.get('launcherDependency'): module_deps.append(lib_name) if value.get('libs'): # Get any java libs that are needed file_deps = [] for java_lib in value['libs']: file_path = Template(java_lib['path']).substitute(self.env) file_path = to_gradle_path(file_path) if os.path.exists(file_path): file_deps.append(file_path) elif java_lib['required']: self.fatal('[ERROR] Required java lib - {} - was not found'.format(file_path)) new_task_generator.set_task_attribute('file_dependencies', file_deps) project.add_target_to_project(lib_name, Module.Type.Library, new_task_generator) setattr(task_generator, 'module_dependencies', module_deps) project.add_target_to_project(target_name, module_type, task_generator)
[ "def", "process_module", "(", "self", ",", "project", ",", "target_name", ",", "android_root", ",", "module_type", ",", "task_generator", ")", ":", "if", "module_type", "==", "Module", ".", "Type", ".", "Application", ":", "class", "_DummyTaskGenerator", "(", "object", ")", ":", "def", "set_task_attribute", "(", "self", ",", "name", ",", "attr", ")", ":", "if", "attr", ":", "setattr", "(", "self", ",", "name", ",", "attr", ")", "# Generate all the targets for the Android libraries", "android_java_libs", "=", "getattr", "(", "task_generator", ",", "'android_java_libs'", ",", "[", "]", ")", "if", "android_java_libs", ":", "java_libs_json", "=", "self", ".", "root", ".", "make_node", "(", "android_java_libs", ")", "json_data", "=", "self", ".", "parse_json_file", "(", "java_libs_json", ")", "else", ":", "json_data", "=", "None", "if", "json_data", ":", "module_deps", "=", "[", "]", "for", "lib_name", ",", "value", "in", "json_data", ".", "items", "(", ")", ":", "new_task_generator", "=", "_DummyTaskGenerator", "(", ")", "# Check if the library was patched. If so, we need to look in a different folder.", "if", "'patches'", "in", "value", ":", "lib_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "Path", "(", "self", ".", "get_android_patched_libraries_relative_path", "(", ")", ")", ",", "lib_name", ")", "else", ":", "# Search the multiple library paths where the library can be.", "lib_path", "=", "None", "for", "path", "in", "value", "[", "'srcDir'", "]", ":", "path", "=", "Template", "(", "path", ")", ".", "substitute", "(", "self", ".", "env", ")", "path", "=", "to_gradle_path", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "lib_path", "=", "path", "break", "if", "not", "lib_path", ":", "paths", "=", "[", "Template", "(", "path", ")", ".", "substitute", "(", "self", ".", "env", ")", "for", "path", "in", "value", "[", "'srcDir'", "]", "]", "self", ".", "fatal", "(", "'[ERROR] Failed to find library - {} - in path(s): {}. Please '", "'download the library from the Android SDK Manager and run the '", "'configure command again.'", ".", "format", "(", "lib_name", ",", "\", \"", ".", "join", "(", "paths", ")", ")", ")", "new_task_generator", ".", "set_task_attribute", "(", "'path'", ",", "self", ".", "path", ")", "new_task_generator", ".", "set_task_attribute", "(", "'android_java_src_path'", ",", "os", ".", "path", ".", "join", "(", "lib_path", ",", "'src'", ")", ")", "new_task_generator", ".", "set_task_attribute", "(", "'android_res_path'", ",", "os", ".", "path", ".", "join", "(", "lib_path", ",", "'res'", ")", ")", "new_task_generator", ".", "set_task_attribute", "(", "'android_manifest_path'", ",", "os", ".", "path", ".", "join", "(", "lib_path", ",", "'AndroidManifest.xml'", ")", ")", "new_task_generator", ".", "set_task_attribute", "(", "'module_dependencies'", ",", "value", ".", "get", "(", "'dependencies'", ",", "None", ")", ")", "if", "value", ".", "get", "(", "'launcherDependency'", ")", ":", "module_deps", ".", "append", "(", "lib_name", ")", "if", "value", ".", "get", "(", "'libs'", ")", ":", "# Get any java libs that are needed", "file_deps", "=", "[", "]", "for", "java_lib", "in", "value", "[", "'libs'", "]", ":", "file_path", "=", "Template", "(", "java_lib", "[", "'path'", "]", ")", ".", "substitute", "(", "self", ".", "env", ")", "file_path", "=", "to_gradle_path", "(", "file_path", ")", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "file_deps", ".", "append", "(", "file_path", ")", "elif", "java_lib", "[", "'required'", "]", ":", "self", ".", "fatal", "(", "'[ERROR] Required java lib - {} - was not found'", ".", "format", "(", "file_path", ")", ")", "new_task_generator", ".", "set_task_attribute", "(", "'file_dependencies'", ",", "file_deps", ")", "project", ".", "add_target_to_project", "(", "lib_name", ",", "Module", ".", "Type", ".", "Library", ",", "new_task_generator", ")", "setattr", "(", "task_generator", ",", "'module_dependencies'", ",", "module_deps", ")", "project", ".", "add_target_to_project", "(", "target_name", ",", "module_type", ",", "task_generator", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/android_studio.py#L1486-L1556
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/keras/python/keras/backend.py
python
round
(x)
return math_ops.round(x)
Element-wise rounding to the closest integer. In case of tie, the rounding mode used is "half to even". Arguments: x: Tensor or variable. Returns: A tensor.
Element-wise rounding to the closest integer.
[ "Element", "-", "wise", "rounding", "to", "the", "closest", "integer", "." ]
def round(x): """Element-wise rounding to the closest integer. In case of tie, the rounding mode used is "half to even". Arguments: x: Tensor or variable. Returns: A tensor. """ return math_ops.round(x)
[ "def", "round", "(", "x", ")", ":", "return", "math_ops", ".", "round", "(", "x", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L1606-L1617
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
Geometry3D.setCurrentTransform
(self, R: "double const [9]", t: "double const [3]")
return _robotsim.Geometry3D_setCurrentTransform(self, R, t)
r""" setCurrentTransform(Geometry3D self, double const [9] R, double const [3] t) Sets the current transformation (not modifying the underlying data)
r""" setCurrentTransform(Geometry3D self, double const [9] R, double const [3] t)
[ "r", "setCurrentTransform", "(", "Geometry3D", "self", "double", "const", "[", "9", "]", "R", "double", "const", "[", "3", "]", "t", ")" ]
def setCurrentTransform(self, R: "double const [9]", t: "double const [3]") -> "void": r""" setCurrentTransform(Geometry3D self, double const [9] R, double const [3] t) Sets the current transformation (not modifying the underlying data) """ return _robotsim.Geometry3D_setCurrentTransform(self, R, t)
[ "def", "setCurrentTransform", "(", "self", ",", "R", ":", "\"double const [9]\"", ",", "t", ":", "\"double const [3]\"", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "Geometry3D_setCurrentTransform", "(", "self", ",", "R", ",", "t", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L2308-L2316
p4lang/behavioral-model
81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9
tools/cpplint.py
python
_SetFilters
(filters)
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Sets the module's error-message filters.
[ "Sets", "the", "module", "s", "error", "-", "message", "filters", "." ]
def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters)
[ "def", "_SetFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "SetFilters", "(", "filters", ")" ]
https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/cpplint.py#L1454-L1464
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
RobotModel.getVelocity
(self)
return _robotsim.RobotModel_getVelocity(self)
r""" Retreives the current velocity of the robot model.
r""" Retreives the current velocity of the robot model.
[ "r", "Retreives", "the", "current", "velocity", "of", "the", "robot", "model", "." ]
def getVelocity(self) ->None: r""" Retreives the current velocity of the robot model. """ return _robotsim.RobotModel_getVelocity(self)
[ "def", "getVelocity", "(", "self", ")", "->", "None", ":", "return", "_robotsim", ".", "RobotModel_getVelocity", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L4739-L4744
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/control_flow_ops.py
python
switch
(data, pred, dtype=None, name=None)
Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. dtype: Optional element type for the returned tensor. If missing, the type is inferred from the type of `value`. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`.
Forwards `data` to an output determined by `pred`.
[ "Forwards", "data", "to", "an", "output", "determined", "by", "pred", "." ]
def switch(data, pred, dtype=None, name=None): """Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. dtype: Optional element type for the returned tensor. If missing, the type is inferred from the type of `value`. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`. """ with ops.name_scope(name, "Switch", [data, pred]) as name: data = ops.internal_convert_to_tensor_or_composite( data, dtype=dtype, name="data", as_ref=True) pred = ops.convert_to_tensor(pred, name="pred") if isinstance(data, ops.Tensor): return gen_control_flow_ops.switch(data, pred, name=name) else: if not isinstance(data, composite_tensor.CompositeTensor): raise TypeError( "'data' must be a Tensor or CompositeTensor. " f"Received: {type(data)}.") tensors = nest.flatten(data, expand_composites=True) mapped = [gen_control_flow_ops.switch(tensor, pred) for tensor in tensors] mapped_f, mapped_t = zip(*mapped) return (nest.pack_sequence_as(data, mapped_f, expand_composites=True), nest.pack_sequence_as(data, mapped_t, expand_composites=True))
[ "def", "switch", "(", "data", ",", "pred", ",", "dtype", "=", "None", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"Switch\"", ",", "[", "data", ",", "pred", "]", ")", "as", "name", ":", "data", "=", "ops", ".", "internal_convert_to_tensor_or_composite", "(", "data", ",", "dtype", "=", "dtype", ",", "name", "=", "\"data\"", ",", "as_ref", "=", "True", ")", "pred", "=", "ops", ".", "convert_to_tensor", "(", "pred", ",", "name", "=", "\"pred\"", ")", "if", "isinstance", "(", "data", ",", "ops", ".", "Tensor", ")", ":", "return", "gen_control_flow_ops", ".", "switch", "(", "data", ",", "pred", ",", "name", "=", "name", ")", "else", ":", "if", "not", "isinstance", "(", "data", ",", "composite_tensor", ".", "CompositeTensor", ")", ":", "raise", "TypeError", "(", "\"'data' must be a Tensor or CompositeTensor. \"", "f\"Received: {type(data)}.\"", ")", "tensors", "=", "nest", ".", "flatten", "(", "data", ",", "expand_composites", "=", "True", ")", "mapped", "=", "[", "gen_control_flow_ops", ".", "switch", "(", "tensor", ",", "pred", ")", "for", "tensor", "in", "tensors", "]", "mapped_f", ",", "mapped_t", "=", "zip", "(", "*", "mapped", ")", "return", "(", "nest", ".", "pack_sequence_as", "(", "data", ",", "mapped_f", ",", "expand_composites", "=", "True", ")", ",", "nest", ".", "pack_sequence_as", "(", "data", ",", "mapped_t", ",", "expand_composites", "=", "True", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/control_flow_ops.py#L293-L327
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/utils/check_cfc/check_cfc.py
python
WrapperCheck.perform_check
(self, arguments, my_env)
Override this to perform the modified compilation and required checks.
Override this to perform the modified compilation and required checks.
[ "Override", "this", "to", "perform", "the", "modified", "compilation", "and", "required", "checks", "." ]
def perform_check(self, arguments, my_env): """Override this to perform the modified compilation and required checks.""" raise NotImplementedError("Please Implement this method")
[ "def", "perform_check", "(", "self", ",", "arguments", ",", "my_env", ")", ":", "raise", "NotImplementedError", "(", "\"Please Implement this method\"", ")" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/utils/check_cfc/check_cfc.py#L251-L254
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/WebIDL.py
python
Parser.p_ArgumentList
(self, p)
ArgumentList : Argument Arguments
ArgumentList : Argument Arguments
[ "ArgumentList", ":", "Argument", "Arguments" ]
def p_ArgumentList(self, p): """ ArgumentList : Argument Arguments """ p[0] = [p[1]] if p[1] else [] p[0].extend(p[2])
[ "def", "p_ArgumentList", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]", "if", "p", "[", "1", "]", "else", "[", "]", "p", "[", "0", "]", ".", "extend", "(", "p", "[", "2", "]", ")" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/WebIDL.py#L4328-L4333
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/util/ssl_.py
python
create_urllib3_context
(ssl_version=None, cert_reqs=None, options=None, ciphers=None)
return context
All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext
All arguments have the same meaning as ``ssl_wrap_socket``.
[ "All", "arguments", "have", "the", "same", "meaning", "as", "ssl_wrap_socket", "." ]
def create_urllib3_context(ssl_version=None, cert_reqs=None, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6 context.set_ciphers(ciphers or DEFAULT_CIPHERS) context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context
[ "def", "create_urllib3_context", "(", "ssl_version", "=", "None", ",", "cert_reqs", "=", "None", ",", "options", "=", "None", ",", "ciphers", "=", "None", ")", ":", "context", "=", "SSLContext", "(", "ssl_version", "or", "ssl", ".", "PROTOCOL_SSLv23", ")", "# Setting the default here, as we may have no ssl module on import", "cert_reqs", "=", "ssl", ".", "CERT_REQUIRED", "if", "cert_reqs", "is", "None", "else", "cert_reqs", "if", "options", "is", "None", ":", "options", "=", "0", "# SSLv2 is easily broken and is considered harmful and dangerous", "options", "|=", "OP_NO_SSLv2", "# SSLv3 has several problems and is now dangerous", "options", "|=", "OP_NO_SSLv3", "# Disable compression to prevent CRIME attacks for OpenSSL 1.0+", "# (issue #309)", "options", "|=", "OP_NO_COMPRESSION", "context", ".", "options", "|=", "options", "if", "getattr", "(", "context", ",", "'supports_set_ciphers'", ",", "True", ")", ":", "# Platform-specific: Python 2.6", "context", ".", "set_ciphers", "(", "ciphers", "or", "DEFAULT_CIPHERS", ")", "context", ".", "verify_mode", "=", "cert_reqs", "if", "getattr", "(", "context", ",", "'check_hostname'", ",", "None", ")", "is", "not", "None", ":", "# Platform-specific: Python 3.2", "# We do our own verification, including fingerprints and alternative", "# hostnames. So disable it here", "context", ".", "check_hostname", "=", "False", "return", "context" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/util/ssl_.py#L181-L241
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ParticleMechanicsApplication/python_scripts/apply_mpm_particle_neumann_condition_process.py
python
ApplyMPMParticleNeumannConditionProcess.ExecuteInitializeSolutionStep
(self)
This method is executed in order to initialize the current step Keyword arguments: self -- It signifies an instance of a class.
This method is executed in order to initialize the current step
[ "This", "method", "is", "executed", "in", "order", "to", "initialize", "the", "current", "step" ]
def ExecuteInitializeSolutionStep(self): """ This method is executed in order to initialize the current step Keyword arguments: self -- It signifies an instance of a class. """ for mpc in self.model_part.Conditions: current_time = self.model_part.ProcessInfo[KratosMultiphysics.TIME] mpc_coord = mpc.CalculateOnIntegrationPoints(KratosParticle.MPC_COORD,self.model_part.ProcessInfo)[0] if self.interval.IsInInterval(current_time): self.step_is_active = True for i in range(3): if not self.value_direction_is_numeric[i]: if self.aux_function_direction[i].DependsOnSpace() == False: #depends on time only self.vector_direction[i] = self.aux_function_direction[i].CallFunction(0.0,0.0,0.0,current_time,0.0,0.0,0.0) else: #most general case - space varying function (possibly also time varying) self.vector_direction[i]= self.aux_function_direction[i].CallFunction(mpc_coord[0],mpc_coord[1],mpc_coord[2],current_time,0.0,0.0,0.0) if not self.value_is_numeric: if self.aux_function.DependsOnSpace() == False: #depends on time only self.value = self.aux_function.CallFunction(0.0,0.0,0.0,current_time,0.0,0.0,0.0) * self.vector_direction else: #most general case - space varying function (possibly also time varying) self.value = self.aux_function.CallFunction(mpc_coord[0],mpc_coord[1],mpc_coord[2],current_time,0.0,0.0,0.0) * self.vector_direction else: self.value = self.vector_direction * self.modulus mpc.SetValuesOnIntegrationPoints(KratosParticle.POINT_LOAD,[self.value],self.model_part.ProcessInfo)
[ "def", "ExecuteInitializeSolutionStep", "(", "self", ")", ":", "for", "mpc", "in", "self", ".", "model_part", ".", "Conditions", ":", "current_time", "=", "self", ".", "model_part", ".", "ProcessInfo", "[", "KratosMultiphysics", ".", "TIME", "]", "mpc_coord", "=", "mpc", ".", "CalculateOnIntegrationPoints", "(", "KratosParticle", ".", "MPC_COORD", ",", "self", ".", "model_part", ".", "ProcessInfo", ")", "[", "0", "]", "if", "self", ".", "interval", ".", "IsInInterval", "(", "current_time", ")", ":", "self", ".", "step_is_active", "=", "True", "for", "i", "in", "range", "(", "3", ")", ":", "if", "not", "self", ".", "value_direction_is_numeric", "[", "i", "]", ":", "if", "self", ".", "aux_function_direction", "[", "i", "]", ".", "DependsOnSpace", "(", ")", "==", "False", ":", "#depends on time only", "self", ".", "vector_direction", "[", "i", "]", "=", "self", ".", "aux_function_direction", "[", "i", "]", ".", "CallFunction", "(", "0.0", ",", "0.0", ",", "0.0", ",", "current_time", ",", "0.0", ",", "0.0", ",", "0.0", ")", "else", ":", "#most general case - space varying function (possibly also time varying)", "self", ".", "vector_direction", "[", "i", "]", "=", "self", ".", "aux_function_direction", "[", "i", "]", ".", "CallFunction", "(", "mpc_coord", "[", "0", "]", ",", "mpc_coord", "[", "1", "]", ",", "mpc_coord", "[", "2", "]", ",", "current_time", ",", "0.0", ",", "0.0", ",", "0.0", ")", "if", "not", "self", ".", "value_is_numeric", ":", "if", "self", ".", "aux_function", ".", "DependsOnSpace", "(", ")", "==", "False", ":", "#depends on time only", "self", ".", "value", "=", "self", ".", "aux_function", ".", "CallFunction", "(", "0.0", ",", "0.0", ",", "0.0", ",", "current_time", ",", "0.0", ",", "0.0", ",", "0.0", ")", "*", "self", ".", "vector_direction", "else", ":", "#most general case - space varying function (possibly also time varying)", "self", ".", "value", "=", "self", ".", "aux_function", ".", "CallFunction", "(", "mpc_coord", "[", "0", "]", ",", "mpc_coord", "[", "1", "]", ",", "mpc_coord", "[", "2", "]", ",", "current_time", ",", "0.0", ",", "0.0", ",", "0.0", ")", "*", "self", ".", "vector_direction", "else", ":", "self", ".", "value", "=", "self", ".", "vector_direction", "*", "self", ".", "modulus", "mpc", ".", "SetValuesOnIntegrationPoints", "(", "KratosParticle", ".", "POINT_LOAD", ",", "[", "self", ".", "value", "]", ",", "self", ".", "model_part", ".", "ProcessInfo", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ParticleMechanicsApplication/python_scripts/apply_mpm_particle_neumann_condition_process.py#L127-L161
Tokutek/mongo
0653eabe2c5b9d12b4814617cb7fb2d799937a0f
buildscripts/cpplint.py
python
CheckSpacing
(filename, clean_lines, linenum, error)
Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing issues in the code.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "issues", "in", "the", "code", "." ]
def CheckSpacing(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ raw = clean_lines.raw_lines line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' if IsBlankLine(line): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1 and prev_line[:prevbrace].find('namespace') == -1): # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Blank line at the start of a code block. Is this needed?') # This doesn't ignore whitespace at the end of a namespace block # because that is too hard without pairing open/close braces; # however, a special exception is made for namespace closing # brackets which have a comment containing "namespace". # # Also, ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('namespace') == -1 and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Blank line at the end of a code block. Is this needed?') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, we complain if there's a comment too near the text commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not Match(r'^\s*{ //', line) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # There should always be a space between the // and the comment commentend = commentpos + 2 if commentend < len(line) and not line[commentend] == ' ': # but some lines are exceptions -- e.g. if they're big # comment delimiters like: # //---------------------------------------------------------- # or are an empty C++ style Doxygen comment, like: # /// # or they begin with multiple slashes followed by a space: # //////// Header comment match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or Search(r'^/$', line[commentend:]) or Search(r'^/+ ', line[commentend:])) if not match: error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') CheckComment(line[commentpos:], filename, linenum, error) line = clean_lines.elided[linenum] # get rid of comments and strings # Don't try to do spacing checks for operator methods line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # Alas, we can't test < or > because they're legitimately used sans spaces # (a->b, vector<int> a). The only time we can tell is a < with no >, and # only if it's not template params list spilling into the next line. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) if not match: # Note that while it seems that the '<[^<]*' term in the following # regexp could be simplified to '<.*', which would indeed match # the same class of strings, the [^<] means that searching for the # regexp takes linear rather than quadratic time. if not Search(r'<[^<]*,\s*$', line): # template params spill match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # We allow no-spaces around << and >> when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) # A pet peeve of mine: no spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if not len(match.group(2)) in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) # You should always have a space after a comma (either as fn arg or operator) if Search(r',[^\s]', line): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') # Next we will look for issues with function calls. CheckSpacingForFunctionCall(filename, line, linenum, error) # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. if Search(r'[^ ({]{', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'new char * []'. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use { } instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use { } instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use { } instead.')
[ "def", "CheckSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "raw", "=", "clean_lines", ".", "raw_lines", "line", "=", "raw", "[", "linenum", "]", "# Before nixing comments, check if the line is blank for no good", "# reason. This includes the first line after a block is opened, and", "# blank lines at the end of a function (ie, right before a line like '}'", "if", "IsBlankLine", "(", "line", ")", ":", "elided", "=", "clean_lines", ".", "elided", "prev_line", "=", "elided", "[", "linenum", "-", "1", "]", "prevbrace", "=", "prev_line", ".", "rfind", "(", "'{'", ")", "# TODO(unknown): Don't complain if line before blank line, and line after,", "# both start with alnums and are indented the same amount.", "# This ignores whitespace at the start of a namespace block", "# because those are not usually indented.", "if", "(", "prevbrace", "!=", "-", "1", "and", "prev_line", "[", "prevbrace", ":", "]", ".", "find", "(", "'}'", ")", "==", "-", "1", "and", "prev_line", "[", ":", "prevbrace", "]", ".", "find", "(", "'namespace'", ")", "==", "-", "1", ")", ":", "# OK, we have a blank line at the start of a code block. Before we", "# complain, we check if it is an exception to the rule: The previous", "# non-empty line has the parameters of a function header that are indented", "# 4 spaces (because they did not fit in a 80 column line when placed on", "# the same line as the function name). We also check for the case where", "# the previous line is indented 6 spaces, which may happen when the", "# initializers of a constructor do not fit into a 80 column line.", "exception", "=", "False", "if", "Match", "(", "r' {6}\\w'", ",", "prev_line", ")", ":", "# Initializer list?", "# We are looking for the opening column of initializer list, which", "# should be indented 4 spaces to cause 6 space indentation afterwards.", "search_position", "=", "linenum", "-", "2", "while", "(", "search_position", ">=", "0", "and", "Match", "(", "r' {6}\\w'", ",", "elided", "[", "search_position", "]", ")", ")", ":", "search_position", "-=", "1", "exception", "=", "(", "search_position", ">=", "0", "and", "elided", "[", "search_position", "]", "[", ":", "5", "]", "==", "' :'", ")", "else", ":", "# Search for the function arguments or an initializer list. We use a", "# simple heuristic here: If the line is indented 4 spaces; and we have a", "# closing paren, without the opening paren, followed by an opening brace", "# or colon (for initializer lists) we assume that it is the last line of", "# a function header. If we have a colon indented 4 spaces, it is an", "# initializer list.", "exception", "=", "(", "Match", "(", "r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)'", ",", "prev_line", ")", "or", "Match", "(", "r' {4}:'", ",", "prev_line", ")", ")", "if", "not", "exception", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "2", ",", "'Blank line at the start of a code block. Is this needed?'", ")", "# This doesn't ignore whitespace at the end of a namespace block", "# because that is too hard without pairing open/close braces;", "# however, a special exception is made for namespace closing", "# brackets which have a comment containing \"namespace\".", "#", "# Also, ignore blank lines at the end of a block in a long if-else", "# chain, like this:", "# if (condition1) {", "# // Something followed by a blank line", "#", "# } else if (condition2) {", "# // Something else", "# }", "if", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "next_line", "=", "raw", "[", "linenum", "+", "1", "]", "if", "(", "next_line", "and", "Match", "(", "r'\\s*}'", ",", "next_line", ")", "and", "next_line", ".", "find", "(", "'namespace'", ")", "==", "-", "1", "and", "next_line", ".", "find", "(", "'} else '", ")", "==", "-", "1", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Blank line at the end of a code block. Is this needed?'", ")", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "prev_line", ")", "if", "matched", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Do not leave a blank line after \"%s:\"'", "%", "matched", ".", "group", "(", "1", ")", ")", "# Next, we complain if there's a comment too near the text", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", ":", "# Check if the // may be in quotes. If so, ignore it", "# Comparisons made explicit for clarity -- pylint: disable-msg=C6403", "if", "(", "line", ".", "count", "(", "'\"'", ",", "0", ",", "commentpos", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ",", "0", ",", "commentpos", ")", ")", "%", "2", "==", "0", ":", "# not in quotes", "# Allow one space for new scopes, two spaces otherwise:", "if", "(", "not", "Match", "(", "r'^\\s*{ //'", ",", "line", ")", "and", "(", "(", "commentpos", ">=", "1", "and", "line", "[", "commentpos", "-", "1", "]", "not", "in", "string", ".", "whitespace", ")", "or", "(", "commentpos", ">=", "2", "and", "line", "[", "commentpos", "-", "2", "]", "not", "in", "string", ".", "whitespace", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "2", ",", "'At least two spaces is best between code and comments'", ")", "# There should always be a space between the // and the comment", "commentend", "=", "commentpos", "+", "2", "if", "commentend", "<", "len", "(", "line", ")", "and", "not", "line", "[", "commentend", "]", "==", "' '", ":", "# but some lines are exceptions -- e.g. if they're big", "# comment delimiters like:", "# //----------------------------------------------------------", "# or are an empty C++ style Doxygen comment, like:", "# ///", "# or they begin with multiple slashes followed by a space:", "# //////// Header comment", "match", "=", "(", "Search", "(", "r'[=/-]{4,}\\s*$'", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/$'", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/+ '", ",", "line", "[", "commentend", ":", "]", ")", ")", "if", "not", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "4", ",", "'Should have a space between // and comment'", ")", "CheckComment", "(", "line", "[", "commentpos", ":", "]", ",", "filename", ",", "linenum", ",", "error", ")", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "# Don't try to do spacing checks for operator methods", "line", "=", "re", ".", "sub", "(", "r'operator(==|!=|<|<<|<=|>=|>>|>)\\('", ",", "'operator\\('", ",", "line", ")", "# We allow no-spaces around = within an if: \"if ( (a=Foo()) == 0 )\".", "# Otherwise not. Note we only check for non-spaces on *both* sides;", "# sometimes people put non-spaces on one side when aligning ='s among", "# many lines (not that this is behavior that I approve of...)", "if", "Search", "(", "r'[\\w.]=[\\w.]'", ",", "line", ")", "and", "not", "Search", "(", "r'\\b(if|while) '", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "4", ",", "'Missing spaces around ='", ")", "# It's ok not to have spaces around binary operators like + - * /, but if", "# there's too little whitespace, we get concerned. It's hard to tell,", "# though, so we punt on this one for now. TODO.", "# You should always have whitespace around binary operators.", "# Alas, we can't test < or > because they're legitimately used sans spaces", "# (a->b, vector<int> a). The only time we can tell is a < with no >, and", "# only if it's not template params list spilling into the next line.", "match", "=", "Search", "(", "r'[^<>=!\\s](==|!=|<=|>=)[^<>=!\\s]'", ",", "line", ")", "if", "not", "match", ":", "# Note that while it seems that the '<[^<]*' term in the following", "# regexp could be simplified to '<.*', which would indeed match", "# the same class of strings, the [^<] means that searching for the", "# regexp takes linear rather than quadratic time.", "if", "not", "Search", "(", "r'<[^<]*,\\s*$'", ",", "line", ")", ":", "# template params spill", "match", "=", "Search", "(", "r'[^<>=!\\s](<)[^<>=!\\s]([^>]|->)*$'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# We allow no-spaces around << and >> when used like this: 10<<20, but", "# not otherwise (particularly, not when used as streams)", "match", "=", "Search", "(", "r'[^0-9\\s](<<|>>)[^0-9\\s]'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# There shouldn't be space around unary operators", "match", "=", "Search", "(", "r'(!\\s|~\\s|[\\s]--[\\s;]|[\\s]\\+\\+[\\s;])'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "4", ",", "'Extra space for operator %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# A pet peeve of mine: no spaces after an if, while, switch, or for", "match", "=", "Search", "(", "r' (if\\(|for\\(|while\\(|switch\\()'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Missing space before ( in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# For if/for/while/switch, the left and right parens should be", "# consistent about how many spaces are inside the parens, and", "# there should either be zero or one spaces inside the parens.", "# We don't want: \"if ( foo)\" or \"if ( foo )\".", "# Exception: \"for ( ; foo; bar)\" and \"for (foo; bar; )\" are allowed.", "match", "=", "Search", "(", "r'\\b(if|for|while|switch)\\s*'", "r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$'", ",", "line", ")", "if", "match", ":", "if", "len", "(", "match", ".", "group", "(", "2", ")", ")", "!=", "len", "(", "match", ".", "group", "(", "4", ")", ")", ":", "if", "not", "(", "match", ".", "group", "(", "3", ")", "==", "';'", "and", "len", "(", "match", ".", "group", "(", "2", ")", ")", "==", "1", "+", "len", "(", "match", ".", "group", "(", "4", ")", ")", "or", "not", "match", ".", "group", "(", "2", ")", "and", "Search", "(", "r'\\bfor\\s*\\(.*; \\)'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Mismatching spaces inside () in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "if", "not", "len", "(", "match", ".", "group", "(", "2", ")", ")", "in", "[", "0", ",", "1", "]", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Should have zero or one spaces inside ( and ) in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# You should always have a space after a comma (either as fn arg or operator)", "if", "Search", "(", "r',[^\\s]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comma'", ",", "3", ",", "'Missing space after ,'", ")", "# You should always have a space after a semicolon", "# except for few corner cases", "# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more", "# space after ;", "if", "Search", "(", "r';[^\\s};\\\\)/]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "3", ",", "'Missing space after ;'", ")", "# Next we will look for issues with function calls.", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", "# Except after an opening paren, or after another opening brace (in case of", "# an initializer list, for instance), you should have spaces before your", "# braces. And since you should never have braces at the beginning of a line,", "# this is an easy test.", "if", "Search", "(", "r'[^ ({]{'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before {'", ")", "# Make sure '} else {' has spaces.", "if", "Search", "(", "r'}else'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before else'", ")", "# You shouldn't have spaces before your brackets, except maybe after", "# 'delete []' or 'new char * []'.", "if", "Search", "(", "r'\\w\\s+\\['", ",", "line", ")", "and", "not", "Search", "(", "r'delete\\s+\\['", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Extra space before ['", ")", "# You shouldn't have a space before a semicolon at the end of the line.", "# There's a special case for \"for\" since the style guide allows space before", "# the semicolon there.", "if", "Search", "(", "r':\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Semicolon defining empty statement. Use { } instead.'", ")", "elif", "Search", "(", "r'^\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Line contains only semicolon. If this should be an empty statement, '", "'use { } instead.'", ")", "elif", "(", "Search", "(", "r'\\s+;\\s*$'", ",", "line", ")", "and", "not", "Search", "(", "r'\\bfor\\b'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Extra space before last semicolon. If this should be an empty '", "'statement, use { } instead.'", ")" ]
https://github.com/Tokutek/mongo/blob/0653eabe2c5b9d12b4814617cb7fb2d799937a0f/buildscripts/cpplint.py#L1672-L1915
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/gradients_impl.py
python
_IndexedSlicesToTensor
(value, dtype=None, name=None, as_ref=False)
return math_ops.unsorted_segment_sum( value.values, value.indices, value.dense_shape[0], name=name)
Converts an IndexedSlices object `value` to a Tensor. NOTE(mrry): This function is potentially expensive. Args: value: An ops.IndexedSlices object. dtype: The dtype of the Tensor to be returned. name: Optional name to use for the returned Tensor. as_ref: True if a ref is requested. Returns: A dense Tensor representing the values in the given IndexedSlices. Raises: ValueError: If the IndexedSlices does not have the same dtype.
Converts an IndexedSlices object `value` to a Tensor.
[ "Converts", "an", "IndexedSlices", "object", "value", "to", "a", "Tensor", "." ]
def _IndexedSlicesToTensor(value, dtype=None, name=None, as_ref=False): """Converts an IndexedSlices object `value` to a Tensor. NOTE(mrry): This function is potentially expensive. Args: value: An ops.IndexedSlices object. dtype: The dtype of the Tensor to be returned. name: Optional name to use for the returned Tensor. as_ref: True if a ref is requested. Returns: A dense Tensor representing the values in the given IndexedSlices. Raises: ValueError: If the IndexedSlices does not have the same dtype. """ _ = as_ref if dtype and not dtype.is_compatible_with(value.dtype): raise ValueError( "Tensor conversion requested dtype %s for IndexedSlices with dtype %s" % (dtype.name, value.dtype.name)) if value.dense_shape is None: raise ValueError( "Tensor conversion requested for IndexedSlices without dense_shape: %s" % str(value)) # TODO(mrry): Consider adding static shape information to # IndexedSlices, to avoid using numpy here. dense_shape_value = tensor_util.constant_value(value.dense_shape) if dense_shape_value is not None: num_elements = np.prod(dense_shape_value) if num_elements >= _LARGE_SPARSE_NUM_ELEMENTS: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor with %d elements. " "This may consume a large amount of memory." % num_elements) else: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor of unknown shape. " "This may consume a large amount of memory.") return math_ops.unsorted_segment_sum( value.values, value.indices, value.dense_shape[0], name=name)
[ "def", "_IndexedSlicesToTensor", "(", "value", ",", "dtype", "=", "None", ",", "name", "=", "None", ",", "as_ref", "=", "False", ")", ":", "_", "=", "as_ref", "if", "dtype", "and", "not", "dtype", ".", "is_compatible_with", "(", "value", ".", "dtype", ")", ":", "raise", "ValueError", "(", "\"Tensor conversion requested dtype %s for IndexedSlices with dtype %s\"", "%", "(", "dtype", ".", "name", ",", "value", ".", "dtype", ".", "name", ")", ")", "if", "value", ".", "dense_shape", "is", "None", ":", "raise", "ValueError", "(", "\"Tensor conversion requested for IndexedSlices without dense_shape: %s\"", "%", "str", "(", "value", ")", ")", "# TODO(mrry): Consider adding static shape information to", "# IndexedSlices, to avoid using numpy here.", "dense_shape_value", "=", "tensor_util", ".", "constant_value", "(", "value", ".", "dense_shape", ")", "if", "dense_shape_value", "is", "not", "None", ":", "num_elements", "=", "np", ".", "prod", "(", "dense_shape_value", ")", "if", "num_elements", ">=", "_LARGE_SPARSE_NUM_ELEMENTS", ":", "warnings", ".", "warn", "(", "\"Converting sparse IndexedSlices to a dense Tensor with %d elements. \"", "\"This may consume a large amount of memory.\"", "%", "num_elements", ")", "else", ":", "warnings", ".", "warn", "(", "\"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"", "\"This may consume a large amount of memory.\"", ")", "return", "math_ops", ".", "unsorted_segment_sum", "(", "value", ".", "values", ",", "value", ".", "indices", ",", "value", ".", "dense_shape", "[", "0", "]", ",", "name", "=", "name", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/gradients_impl.py#L58-L98
ZeroCM/zcm
a4f8a1c2d81414a13116a70c0979b1bf546866df
waftools/wafcache.py
python
fcache.copy_to_cache
(self, sig, files_from, files_to)
return OK
Copy files to the cache, existing files are overwritten, and the copy is atomic only for a given file, not for all files that belong to a given task object
Copy files to the cache, existing files are overwritten, and the copy is atomic only for a given file, not for all files that belong to a given task object
[ "Copy", "files", "to", "the", "cache", "existing", "files", "are", "overwritten", "and", "the", "copy", "is", "atomic", "only", "for", "a", "given", "file", "not", "for", "all", "files", "that", "belong", "to", "a", "given", "task", "object" ]
def copy_to_cache(self, sig, files_from, files_to): """ Copy files to the cache, existing files are overwritten, and the copy is atomic only for a given file, not for all files that belong to a given task object """ try: for i, x in enumerate(files_from): dest = os.path.join(CACHE_DIR, sig[:2], sig, str(i)) atomic_copy(x, dest) except Exception: return traceback.format_exc() else: # attempt trimming if caching was successful: # we may have things to trim! try: lru_evict() except Exception: return traceback.format_exc() return OK
[ "def", "copy_to_cache", "(", "self", ",", "sig", ",", "files_from", ",", "files_to", ")", ":", "try", ":", "for", "i", ",", "x", "in", "enumerate", "(", "files_from", ")", ":", "dest", "=", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "sig", "[", ":", "2", "]", ",", "sig", ",", "str", "(", "i", ")", ")", "atomic_copy", "(", "x", ",", "dest", ")", "except", "Exception", ":", "return", "traceback", ".", "format_exc", "(", ")", "else", ":", "# attempt trimming if caching was successful:", "# we may have things to trim!", "try", ":", "lru_evict", "(", ")", "except", "Exception", ":", "return", "traceback", ".", "format_exc", "(", ")", "return", "OK" ]
https://github.com/ZeroCM/zcm/blob/a4f8a1c2d81414a13116a70c0979b1bf546866df/waftools/wafcache.py#L463-L482
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/command/sdist.py
python
sdist.prune_file_list
(self)
Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
[ "Prune", "off", "branches", "that", "might", "slip", "into", "the", "file", "list", "as", "created", "by", "read_template", "()", "but", "really", "don", "t", "belong", "there", ":", "*", "the", "build", "tree", "(", "typically", "build", ")", "*", "the", "release", "tree", "itself", "(", "only", "an", "issue", "if", "we", "ran", "sdist", "previously", "with", "--", "keep", "-", "temp", "or", "it", "aborted", ")", "*", "any", "RCS", "CVS", ".", "svn", ".", "hg", ".", "git", ".", "bzr", "_darcs", "directories" ]
def prune_file_list(self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) # pruning out vcs directories # both separators are used under win32 if sys.platform == 'win32': seps = r'/|\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
[ "def", "prune_file_list", "(", "self", ")", ":", "build", "=", "self", ".", "get_finalized_command", "(", "'build'", ")", "base_dir", "=", "self", ".", "distribution", ".", "get_fullname", "(", ")", "self", ".", "filelist", ".", "exclude_pattern", "(", "None", ",", "prefix", "=", "build", ".", "build_base", ")", "self", ".", "filelist", ".", "exclude_pattern", "(", "None", ",", "prefix", "=", "base_dir", ")", "# pruning out vcs directories", "# both separators are used under win32", "if", "sys", ".", "platform", "==", "'win32'", ":", "seps", "=", "r'/|\\\\'", "else", ":", "seps", "=", "'/'", "vcs_dirs", "=", "[", "'RCS'", ",", "'CVS'", ",", "r'\\.svn'", ",", "r'\\.hg'", ",", "r'\\.git'", ",", "r'\\.bzr'", ",", "'_darcs'", "]", "vcs_ptrn", "=", "r'(^|%s)(%s)(%s).*'", "%", "(", "seps", ",", "'|'", ".", "join", "(", "vcs_dirs", ")", ",", "seps", ")", "self", ".", "filelist", ".", "exclude_pattern", "(", "vcs_ptrn", ",", "is_regex", "=", "1", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/command/sdist.py#L333-L357
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/graph/graph.py
python
Node.insert_node_with_data_before
(self, inp, new_op_class: callable, op_before_params: dict = None, infer_current: bool = False, additional_inputs: list = None)
Inserts operation node with op_before_params and data node before current operation :param inp: input data node of current node :param new_op_class: class of operation that will be inserted before current operation node :param op_before_params: parameters to be added to operation that will be inserted before current operation Before calling: [...] -> inp -> Cur_Op -> Cur_Data -> [...] After calling: [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> [...] [op_before_params]
Inserts operation node with op_before_params and data node before current operation
[ "Inserts", "operation", "node", "with", "op_before_params", "and", "data", "node", "before", "current", "operation" ]
def insert_node_with_data_before(self, inp, new_op_class: callable, op_before_params: dict = None, infer_current: bool = False, additional_inputs: list = None): """ Inserts operation node with op_before_params and data node before current operation :param inp: input data node of current node :param new_op_class: class of operation that will be inserted before current operation node :param op_before_params: parameters to be added to operation that will be inserted before current operation Before calling: [...] -> inp -> Cur_Op -> Cur_Data -> [...] After calling: [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> [...] [op_before_params] """ graph = self.graph node = Node(graph, self.node) cls_name = new_op_class.op op_before_params = {} if op_before_params is None else op_before_params # operating with input new_op_before = new_op_class(graph, op_before_params) edge_attrs = deepcopy(graph.get_edge_data(inp.id, node.id)[0]) graph.remove_edge(inp.id, node.id) # form a list of input nodes for a new op node combining new_out and additional_inputs inputs = [inp] + (additional_inputs if additional_inputs else []) new_inp = new_op_before.create_node_with_data(inputs, {'name': node.name + cls_name + '/Before'}) graph.add_edge(new_inp.id, node.id, **edge_attrs) if infer_current: node.infer(node)
[ "def", "insert_node_with_data_before", "(", "self", ",", "inp", ",", "new_op_class", ":", "callable", ",", "op_before_params", ":", "dict", "=", "None", ",", "infer_current", ":", "bool", "=", "False", ",", "additional_inputs", ":", "list", "=", "None", ")", ":", "graph", "=", "self", ".", "graph", "node", "=", "Node", "(", "graph", ",", "self", ".", "node", ")", "cls_name", "=", "new_op_class", ".", "op", "op_before_params", "=", "{", "}", "if", "op_before_params", "is", "None", "else", "op_before_params", "# operating with input", "new_op_before", "=", "new_op_class", "(", "graph", ",", "op_before_params", ")", "edge_attrs", "=", "deepcopy", "(", "graph", ".", "get_edge_data", "(", "inp", ".", "id", ",", "node", ".", "id", ")", "[", "0", "]", ")", "graph", ".", "remove_edge", "(", "inp", ".", "id", ",", "node", ".", "id", ")", "# form a list of input nodes for a new op node combining new_out and additional_inputs", "inputs", "=", "[", "inp", "]", "+", "(", "additional_inputs", "if", "additional_inputs", "else", "[", "]", ")", "new_inp", "=", "new_op_before", ".", "create_node_with_data", "(", "inputs", ",", "{", "'name'", ":", "node", ".", "name", "+", "cls_name", "+", "'/Before'", "}", ")", "graph", ".", "add_edge", "(", "new_inp", ".", "id", ",", "node", ".", "id", ",", "*", "*", "edge_attrs", ")", "if", "infer_current", ":", "node", ".", "infer", "(", "node", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/graph/graph.py#L321-L351
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
TextBoxAttr.CollectCommonAttributes
(*args, **kwargs)
return _richtext.TextBoxAttr_CollectCommonAttributes(*args, **kwargs)
CollectCommonAttributes(self, TextBoxAttr attr, TextBoxAttr clashingAttr, TextBoxAttr absentAttr)
CollectCommonAttributes(self, TextBoxAttr attr, TextBoxAttr clashingAttr, TextBoxAttr absentAttr)
[ "CollectCommonAttributes", "(", "self", "TextBoxAttr", "attr", "TextBoxAttr", "clashingAttr", "TextBoxAttr", "absentAttr", ")" ]
def CollectCommonAttributes(*args, **kwargs): """CollectCommonAttributes(self, TextBoxAttr attr, TextBoxAttr clashingAttr, TextBoxAttr absentAttr)""" return _richtext.TextBoxAttr_CollectCommonAttributes(*args, **kwargs)
[ "def", "CollectCommonAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextBoxAttr_CollectCommonAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L548-L550
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/gluon/block.py
python
Block.name_scope
(self)
return self._scope
Returns a name space object managing a child :py:class:`Block` and parameter names. Should be used within a ``with`` statement:: with self.name_scope(): self.dense = nn.Dense(20) Please refer to `naming tutorial <http://mxnet.incubator.apache.org/tutorials/gluon/naming.html>`_ for more info on prefix and naming.
Returns a name space object managing a child :py:class:`Block` and parameter names. Should be used within a ``with`` statement::
[ "Returns", "a", "name", "space", "object", "managing", "a", "child", ":", "py", ":", "class", ":", "Block", "and", "parameter", "names", ".", "Should", "be", "used", "within", "a", "with", "statement", "::" ]
def name_scope(self): """Returns a name space object managing a child :py:class:`Block` and parameter names. Should be used within a ``with`` statement:: with self.name_scope(): self.dense = nn.Dense(20) Please refer to `naming tutorial <http://mxnet.incubator.apache.org/tutorials/gluon/naming.html>`_ for more info on prefix and naming. """ return self._scope
[ "def", "name_scope", "(", "self", ")", ":", "return", "self", ".", "_scope" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/block.py#L254-L265
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py
python
DifferentialEvolutionSolver._best2
(self, samples)
return bprime
best2bin, best2exp
best2bin, best2exp
[ "best2bin", "best2exp" ]
def _best2(self, samples): """best2bin, best2exp""" r0, r1, r2, r3 = samples[:4] bprime = (self.population[0] + self.scale * (self.population[r0] + self.population[r1] - self.population[r2] - self.population[r3])) return bprime
[ "def", "_best2", "(", "self", ",", "samples", ")", ":", "r0", ",", "r1", ",", "r2", ",", "r3", "=", "samples", "[", ":", "4", "]", "bprime", "=", "(", "self", ".", "population", "[", "0", "]", "+", "self", ".", "scale", "*", "(", "self", ".", "population", "[", "r0", "]", "+", "self", ".", "population", "[", "r1", "]", "-", "self", ".", "population", "[", "r2", "]", "-", "self", ".", "population", "[", "r3", "]", ")", ")", "return", "bprime" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py#L975-L982
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
Button.GetDefaultSize
(*args, **kwargs)
return _controls_.Button_GetDefaultSize(*args, **kwargs)
GetDefaultSize() -> Size Returns the default button size for this platform.
GetDefaultSize() -> Size
[ "GetDefaultSize", "()", "-", ">", "Size" ]
def GetDefaultSize(*args, **kwargs): """ GetDefaultSize() -> Size Returns the default button size for this platform. """ return _controls_.Button_GetDefaultSize(*args, **kwargs)
[ "def", "GetDefaultSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Button_GetDefaultSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L223-L229
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/lib/deepreload.py
python
ensure_fromlist
(mod, fromlist, buf, recursive)
Handle 'from module import a, b, c' imports.
Handle 'from module import a, b, c' imports.
[ "Handle", "from", "module", "import", "a", "b", "c", "imports", "." ]
def ensure_fromlist(mod, fromlist, buf, recursive): """Handle 'from module import a, b, c' imports.""" if not hasattr(mod, '__path__'): return for item in fromlist: if not hasattr(item, 'rindex'): raise TypeError("Item in ``from list'' not a string") if item == '*': if recursive: continue # avoid endless recursion try: all = mod.__all__ except AttributeError: pass else: ret = ensure_fromlist(mod, all, buf, 1) if not ret: return 0 elif not hasattr(mod, item): import_submodule(mod, item, buf + '.' + item)
[ "def", "ensure_fromlist", "(", "mod", ",", "fromlist", ",", "buf", ",", "recursive", ")", ":", "if", "not", "hasattr", "(", "mod", ",", "'__path__'", ")", ":", "return", "for", "item", "in", "fromlist", ":", "if", "not", "hasattr", "(", "item", ",", "'rindex'", ")", ":", "raise", "TypeError", "(", "\"Item in ``from list'' not a string\"", ")", "if", "item", "==", "'*'", ":", "if", "recursive", ":", "continue", "# avoid endless recursion", "try", ":", "all", "=", "mod", ".", "__all__", "except", "AttributeError", ":", "pass", "else", ":", "ret", "=", "ensure_fromlist", "(", "mod", ",", "all", ",", "buf", ",", "1", ")", "if", "not", "ret", ":", "return", "0", "elif", "not", "hasattr", "(", "mod", ",", "item", ")", ":", "import_submodule", "(", "mod", ",", "item", ",", "buf", "+", "'.'", "+", "item", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/lib/deepreload.py#L227-L246
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/tools/pretty_vcproj.py
python
AbsoluteNode
(node)
Makes all the properties we know about in this node absolute.
Makes all the properties we know about in this node absolute.
[ "Makes", "all", "the", "properties", "we", "know", "about", "in", "this", "node", "absolute", "." ]
def AbsoluteNode(node): """Makes all the properties we know about in this node absolute.""" if node.attributes: for (name, value) in node.attributes.items(): if name in ['InheritedPropertySheets', 'RelativePath', 'AdditionalIncludeDirectories', 'IntermediateDirectory', 'OutputDirectory', 'AdditionalLibraryDirectories']: # We want to fix up these paths path_list = value.split(';') new_list = FixFilenames(path_list, os.path.dirname(ARGUMENTS[1])) node.setAttribute(name, ';'.join(new_list)) if not value: node.removeAttribute(name)
[ "def", "AbsoluteNode", "(", "node", ")", ":", "if", "node", ".", "attributes", ":", "for", "(", "name", ",", "value", ")", "in", "node", ".", "attributes", ".", "items", "(", ")", ":", "if", "name", "in", "[", "'InheritedPropertySheets'", ",", "'RelativePath'", ",", "'AdditionalIncludeDirectories'", ",", "'IntermediateDirectory'", ",", "'OutputDirectory'", ",", "'AdditionalLibraryDirectories'", "]", ":", "# We want to fix up these paths", "path_list", "=", "value", ".", "split", "(", "';'", ")", "new_list", "=", "FixFilenames", "(", "path_list", ",", "os", ".", "path", ".", "dirname", "(", "ARGUMENTS", "[", "1", "]", ")", ")", "node", ".", "setAttribute", "(", "name", ",", "';'", ".", "join", "(", "new_list", ")", ")", "if", "not", "value", ":", "node", ".", "removeAttribute", "(", "name", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/tools/pretty_vcproj.py#L128-L141
intel/linux-sgx
2ee53db4e8fd25437a817612d3bcb94b66a28373
sdk/debugger_interface/linux/gdb-sgx-plugin/printers.py
python
AbstractUnorderedCollectionPrinter._get_key_value
(self, node)
Subclasses should override to return a list of values to yield.
Subclasses should override to return a list of values to yield.
[ "Subclasses", "should", "override", "to", "return", "a", "list", "of", "values", "to", "yield", "." ]
def _get_key_value(self, node): """Subclasses should override to return a list of values to yield.""" raise NotImplementedError
[ "def", "_get_key_value", "(", "self", ",", "node", ")", ":", "raise", "NotImplementedError" ]
https://github.com/intel/linux-sgx/blob/2ee53db4e8fd25437a817612d3bcb94b66a28373/sdk/debugger_interface/linux/gdb-sgx-plugin/printers.py#L867-L869
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/lexer.py
python
Lexer.tokenize
(self, source, name=None, filename=None, state=None)
return TokenStream(self.wrap(stream, name, filename), name, filename)
Calls tokeniter + tokenize and wraps it in a token stream.
Calls tokeniter + tokenize and wraps it in a token stream.
[ "Calls", "tokeniter", "+", "tokenize", "and", "wraps", "it", "in", "a", "token", "stream", "." ]
def tokenize(self, source, name=None, filename=None, state=None): """Calls tokeniter + tokenize and wraps it in a token stream. """ stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name, filename), name, filename)
[ "def", "tokenize", "(", "self", ",", "source", ",", "name", "=", "None", ",", "filename", "=", "None", ",", "state", "=", "None", ")", ":", "stream", "=", "self", ".", "tokeniter", "(", "source", ",", "name", ",", "filename", ",", "state", ")", "return", "TokenStream", "(", "self", ".", "wrap", "(", "stream", ",", "name", ",", "filename", ")", ",", "name", ",", "filename", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/lexer.py#L552-L556
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/kratos_utilities.py
python
DeleteDirectoryIfExisting
(directory_name)
This function tries to delete a folder It uses try/except to also work in MPI
This function tries to delete a folder It uses try/except to also work in MPI
[ "This", "function", "tries", "to", "delete", "a", "folder", "It", "uses", "try", "/", "except", "to", "also", "work", "in", "MPI" ]
def DeleteDirectoryIfExisting(directory_name): """This function tries to delete a folder It uses try/except to also work in MPI """ try: shutil.rmtree(directory_name) except: pass
[ "def", "DeleteDirectoryIfExisting", "(", "directory_name", ")", ":", "try", ":", "shutil", ".", "rmtree", "(", "directory_name", ")", "except", ":", "pass" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/kratos_utilities.py#L16-L23
mysql/mysql-workbench
2f35f9034f015cbcd22139a60e1baa2e3e8e795c
res/scripts/python/wb.py
python
DefineModule.plugin
(self, name, caption= "", description="", type="standalone", input= [], groups= [], pluginMenu= None, accessibilityName="Plugin:ToBeDefined")
return setup_plugin
Decorator to declare a Plugin, used in addition to @wbexport Usage: @wbmodule.plugin("db.utils.mangleNames", caption="Mangle Names", description="Mangles all object names in current catalog beyond recognition.", input= [wbinputs.currentCatalog()], groups=["Menu/Catalog"]) @wbmodule.export(grt.INT, grt.classes.db_Catalog) def mangleNames(catalog): return 1
Decorator to declare a Plugin, used in addition to
[ "Decorator", "to", "declare", "a", "Plugin", "used", "in", "addition", "to" ]
def plugin(self, name, caption= "", description="", type="standalone", input= [], groups= [], pluginMenu= None, accessibilityName="Plugin:ToBeDefined"): """Decorator to declare a Plugin, used in addition to @wbexport Usage: @wbmodule.plugin("db.utils.mangleNames", caption="Mangle Names", description="Mangles all object names in current catalog beyond recognition.", input= [wbinputs.currentCatalog()], groups=["Menu/Catalog"]) @wbmodule.export(grt.INT, grt.classes.db_Catalog) def mangleNames(catalog): return 1 """ def setup_plugin(fn): # make sure getPluginInfo() is in the function list if "getPluginInfo" not in [x[0] for x in self.functions]: self.functions.append(("getPluginInfo", ((grt.LIST, (grt.OBJECT, "app.Plugin")), []), lambda: self._pluginList)) if "PluginInterface" not in self.implements: self.implements.append("PluginInterface") plug= grt.classes.app_Plugin() plug.name= name plug.caption= caption plug.accessibilityName = accessibilityName plug.description= description plug.pluginType= type plug.moduleName= self.name plug.moduleFunctionName= fn.__code__.co_name for i in input: i.owner= plug plug.inputValues.append(i) for g in groups: plug.groups.append(g) if pluginMenu: plug.groups.append("Menu/"+pluginMenu) plug.rating= 100 plug.showProgress= 0 self._pluginList.append(plug) return fn return setup_plugin
[ "def", "plugin", "(", "self", ",", "name", ",", "caption", "=", "\"\"", ",", "description", "=", "\"\"", ",", "type", "=", "\"standalone\"", ",", "input", "=", "[", "]", ",", "groups", "=", "[", "]", ",", "pluginMenu", "=", "None", ",", "accessibilityName", "=", "\"Plugin:ToBeDefined\"", ")", ":", "def", "setup_plugin", "(", "fn", ")", ":", "# make sure getPluginInfo() is in the function list", "if", "\"getPluginInfo\"", "not", "in", "[", "x", "[", "0", "]", "for", "x", "in", "self", ".", "functions", "]", ":", "self", ".", "functions", ".", "append", "(", "(", "\"getPluginInfo\"", ",", "(", "(", "grt", ".", "LIST", ",", "(", "grt", ".", "OBJECT", ",", "\"app.Plugin\"", ")", ")", ",", "[", "]", ")", ",", "lambda", ":", "self", ".", "_pluginList", ")", ")", "if", "\"PluginInterface\"", "not", "in", "self", ".", "implements", ":", "self", ".", "implements", ".", "append", "(", "\"PluginInterface\"", ")", "plug", "=", "grt", ".", "classes", ".", "app_Plugin", "(", ")", "plug", ".", "name", "=", "name", "plug", ".", "caption", "=", "caption", "plug", ".", "accessibilityName", "=", "accessibilityName", "plug", ".", "description", "=", "description", "plug", ".", "pluginType", "=", "type", "plug", ".", "moduleName", "=", "self", ".", "name", "plug", ".", "moduleFunctionName", "=", "fn", ".", "__code__", ".", "co_name", "for", "i", "in", "input", ":", "i", ".", "owner", "=", "plug", "plug", ".", "inputValues", ".", "append", "(", "i", ")", "for", "g", "in", "groups", ":", "plug", ".", "groups", ".", "append", "(", "g", ")", "if", "pluginMenu", ":", "plug", ".", "groups", ".", "append", "(", "\"Menu/\"", "+", "pluginMenu", ")", "plug", ".", "rating", "=", "100", "plug", ".", "showProgress", "=", "0", "self", ".", "_pluginList", ".", "append", "(", "plug", ")", "return", "fn", "return", "setup_plugin" ]
https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/res/scripts/python/wb.py#L61-L101
Manu343726/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
reference/cindex.py
python
Diagnostic.category_number
(self)
return conf.lib.clang_getDiagnosticCategory(self)
The category number for this diagnostic or 0 if unavailable.
The category number for this diagnostic or 0 if unavailable.
[ "The", "category", "number", "for", "this", "diagnostic", "or", "0", "if", "unavailable", "." ]
def category_number(self): """The category number for this diagnostic or 0 if unavailable.""" return conf.lib.clang_getDiagnosticCategory(self)
[ "def", "category_number", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getDiagnosticCategory", "(", "self", ")" ]
https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L363-L365
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/importers/CNTK/lib/cntk_utilities.py
python
plot_model
(root, output_file="model.svg")
Plots the CNTK model starting from the root node to an output image Pre-requisites: Install graphviz executables from graphviz.org Update your PATH environment variable to include the path to graphviz pip install graphviz pip install pydot_ng
Plots the CNTK model starting from the root node to an output image
[ "Plots", "the", "CNTK", "model", "starting", "from", "the", "root", "node", "to", "an", "output", "image" ]
def plot_model(root, output_file="model.svg"): """Plots the CNTK model starting from the root node to an output image Pre-requisites: Install graphviz executables from graphviz.org Update your PATH environment variable to include the path to graphviz pip install graphviz pip install pydot_ng """ text = graph.plot(root, output_file) logger.get().info(text)
[ "def", "plot_model", "(", "root", ",", "output_file", "=", "\"model.svg\"", ")", ":", "text", "=", "graph", ".", "plot", "(", "root", ",", "output_file", ")", "logger", ".", "get", "(", ")", ".", "info", "(", "text", ")" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/CNTK/lib/cntk_utilities.py#L190-L201
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
llvm/utils/benchmark/tools/gbench/report.py
python
filter_benchmark
(json_orig, family, replacement="")
return filtered
Apply a filter to the json, and only leave the 'family' of benchmarks.
Apply a filter to the json, and only leave the 'family' of benchmarks.
[ "Apply", "a", "filter", "to", "the", "json", "and", "only", "leave", "the", "family", "of", "benchmarks", "." ]
def filter_benchmark(json_orig, family, replacement=""): """ Apply a filter to the json, and only leave the 'family' of benchmarks. """ regex = re.compile(family) filtered = {} filtered['benchmarks'] = [] for be in json_orig['benchmarks']: if not regex.search(be['name']): continue filteredbench = copy.deepcopy(be) # Do NOT modify the old name! filteredbench['name'] = regex.sub(replacement, filteredbench['name']) filtered['benchmarks'].append(filteredbench) return filtered
[ "def", "filter_benchmark", "(", "json_orig", ",", "family", ",", "replacement", "=", "\"\"", ")", ":", "regex", "=", "re", ".", "compile", "(", "family", ")", "filtered", "=", "{", "}", "filtered", "[", "'benchmarks'", "]", "=", "[", "]", "for", "be", "in", "json_orig", "[", "'benchmarks'", "]", ":", "if", "not", "regex", ".", "search", "(", "be", "[", "'name'", "]", ")", ":", "continue", "filteredbench", "=", "copy", ".", "deepcopy", "(", "be", ")", "# Do NOT modify the old name!", "filteredbench", "[", "'name'", "]", "=", "regex", ".", "sub", "(", "replacement", ",", "filteredbench", "[", "'name'", "]", ")", "filtered", "[", "'benchmarks'", "]", ".", "append", "(", "filteredbench", ")", "return", "filtered" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/utils/benchmark/tools/gbench/report.py#L71-L84
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/template.py
python
Template.var_scope
(self)
return self._variable_scope
Returns the variable scope object created by this Template.
Returns the variable scope object created by this Template.
[ "Returns", "the", "variable", "scope", "object", "created", "by", "this", "Template", "." ]
def var_scope(self): """Returns the variable scope object created by this Template.""" return self._variable_scope
[ "def", "var_scope", "(", "self", ")", ":", "return", "self", ".", "_variable_scope" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/template.py#L495-L497
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py
python
__methodDict
(cls, _dict)
helper function for Scrolled Canvas
helper function for Scrolled Canvas
[ "helper", "function", "for", "Scrolled", "Canvas" ]
def __methodDict(cls, _dict): """helper function for Scrolled Canvas""" baseList = list(cls.__bases__) baseList.reverse() for _super in baseList: __methodDict(_super, _dict) for key, value in cls.__dict__.items(): if type(value) == types.FunctionType: _dict[key] = value
[ "def", "__methodDict", "(", "cls", ",", "_dict", ")", ":", "baseList", "=", "list", "(", "cls", ".", "__bases__", ")", "baseList", ".", "reverse", "(", ")", "for", "_super", "in", "baseList", ":", "__methodDict", "(", "_super", ",", "_dict", ")", "for", "key", ",", "value", "in", "cls", ".", "__dict__", ".", "items", "(", ")", ":", "if", "type", "(", "value", ")", "==", "types", ".", "FunctionType", ":", "_dict", "[", "key", "]", "=", "value" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py#L308-L316
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/json/decoder.py
python
JSONDecoder.decode
(self, s, _w=WHITESPACE.match)
return obj
Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document)
Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document)
[ "Return", "the", "Python", "representation", "of", "s", "(", "a", "str", "or", "unicode", "instance", "containing", "a", "JSON", "document", ")" ]
def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj
[ "def", "decode", "(", "self", ",", "s", ",", "_w", "=", "WHITESPACE", ".", "match", ")", ":", "obj", ",", "end", "=", "self", ".", "raw_decode", "(", "s", ",", "idx", "=", "_w", "(", "s", ",", "0", ")", ".", "end", "(", ")", ")", "end", "=", "_w", "(", "s", ",", "end", ")", ".", "end", "(", ")", "if", "end", "!=", "len", "(", "s", ")", ":", "raise", "ValueError", "(", "errmsg", "(", "\"Extra data\"", ",", "s", ",", "end", ",", "len", "(", "s", ")", ")", ")", "return", "obj" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/json/decoder.py#L360-L369
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextParagraphLayoutBox.SetPartialParagraph
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_SetPartialParagraph(*args, **kwargs)
SetPartialParagraph(self, bool partialPara)
SetPartialParagraph(self, bool partialPara)
[ "SetPartialParagraph", "(", "self", "bool", "partialPara", ")" ]
def SetPartialParagraph(*args, **kwargs): """SetPartialParagraph(self, bool partialPara)""" return _richtext.RichTextParagraphLayoutBox_SetPartialParagraph(*args, **kwargs)
[ "def", "SetPartialParagraph", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_SetPartialParagraph", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1620-L1622
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/utils/cpp_extension/extension_utils.py
python
find_rocm_home
()
return rocm_home
Use heuristic method to find rocm path
Use heuristic method to find rocm path
[ "Use", "heuristic", "method", "to", "find", "rocm", "path" ]
def find_rocm_home(): """ Use heuristic method to find rocm path """ # step 1. find in $ROCM_HOME or $ROCM_PATH rocm_home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH') # step 2. find path by `which nvcc` if rocm_home is None: which_cmd = 'where' if IS_WINDOWS else 'which' try: with open(os.devnull, 'w') as devnull: hipcc_path = subprocess.check_output( [which_cmd, 'hipcc'], stderr=devnull) hipcc_path = hipcc_path.decode() hipcc_path = hipcc_path.rstrip('\r\n') # for example: /opt/rocm/bin/hipcc rocm_home = os.path.dirname(os.path.dirname(hipcc_path)) except: rocm_home = "/opt/rocm" # step 3. check whether path is valid if rocm_home and not os.path.exists( rocm_home) and core.is_compiled_with_rocm(): rocm_home = None return rocm_home
[ "def", "find_rocm_home", "(", ")", ":", "# step 1. find in $ROCM_HOME or $ROCM_PATH", "rocm_home", "=", "os", ".", "environ", ".", "get", "(", "'ROCM_HOME'", ")", "or", "os", ".", "environ", ".", "get", "(", "'ROCM_PATH'", ")", "# step 2. find path by `which nvcc`", "if", "rocm_home", "is", "None", ":", "which_cmd", "=", "'where'", "if", "IS_WINDOWS", "else", "'which'", "try", ":", "with", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "as", "devnull", ":", "hipcc_path", "=", "subprocess", ".", "check_output", "(", "[", "which_cmd", ",", "'hipcc'", "]", ",", "stderr", "=", "devnull", ")", "hipcc_path", "=", "hipcc_path", ".", "decode", "(", ")", "hipcc_path", "=", "hipcc_path", ".", "rstrip", "(", "'\\r\\n'", ")", "# for example: /opt/rocm/bin/hipcc", "rocm_home", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "hipcc_path", ")", ")", "except", ":", "rocm_home", "=", "\"/opt/rocm\"", "# step 3. check whether path is valid", "if", "rocm_home", "and", "not", "os", ".", "path", ".", "exists", "(", "rocm_home", ")", "and", "core", ".", "is_compiled_with_rocm", "(", ")", ":", "rocm_home", "=", "None", "return", "rocm_home" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/utils/cpp_extension/extension_utils.py#L630-L656
openbabel/openbabel
f3ed2a9a5166dbd3b9ce386e636a176074a6c34c
scripts/python/openbabel/pybel.py
python
Molecule.write
(self, format="smi", filename=None, overwrite=False, opt=None)
Write the molecule to a file or return a string. Optional parameters: format -- see the informats variable for a list of available output formats (default is "smi") filename -- default is None overwite -- if the output file already exists, should it be overwritten? (default is False) opt -- a dictionary of format specific options For format options with no parameters, specify the value as None. If a filename is specified, the result is written to a file. Otherwise, a string is returned containing the result. To write multiple molecules to the same file you should use the Outputfile class.
Write the molecule to a file or return a string.
[ "Write", "the", "molecule", "to", "a", "file", "or", "return", "a", "string", "." ]
def write(self, format="smi", filename=None, overwrite=False, opt=None): """Write the molecule to a file or return a string. Optional parameters: format -- see the informats variable for a list of available output formats (default is "smi") filename -- default is None overwite -- if the output file already exists, should it be overwritten? (default is False) opt -- a dictionary of format specific options For format options with no parameters, specify the value as None. If a filename is specified, the result is written to a file. Otherwise, a string is returned containing the result. To write multiple molecules to the same file you should use the Outputfile class. """ if opt is None: opt = {} obconversion = ob.OBConversion() formatok = obconversion.SetOutFormat(format) if not formatok: raise ValueError("%s is not a recognised Open Babel format" % format) if filename: if isinstance(filename, bytes): gzextension = b'.gz' else: gzextension = '.gz' if os.path.splitext(filename)[1] == gzextension: obconversion.AddOption('z', self.obConversion.GENOPTIONS) for k, v in opt.items(): if v is None: obconversion.AddOption(k, obconversion.OUTOPTIONS) else: obconversion.AddOption(k, obconversion.OUTOPTIONS, str(v)) if filename: if not overwrite and os.path.isfile(filename): raise IOError(("%s already exists. Use 'overwrite=True' to " "overwrite it.") % filename) obconversion.WriteFile(self.OBMol, filename) obconversion.CloseOutFile() else: return obconversion.WriteString(self.OBMol)
[ "def", "write", "(", "self", ",", "format", "=", "\"smi\"", ",", "filename", "=", "None", ",", "overwrite", "=", "False", ",", "opt", "=", "None", ")", ":", "if", "opt", "is", "None", ":", "opt", "=", "{", "}", "obconversion", "=", "ob", ".", "OBConversion", "(", ")", "formatok", "=", "obconversion", ".", "SetOutFormat", "(", "format", ")", "if", "not", "formatok", ":", "raise", "ValueError", "(", "\"%s is not a recognised Open Babel format\"", "%", "format", ")", "if", "filename", ":", "if", "isinstance", "(", "filename", ",", "bytes", ")", ":", "gzextension", "=", "b'.gz'", "else", ":", "gzextension", "=", "'.gz'", "if", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "==", "gzextension", ":", "obconversion", ".", "AddOption", "(", "'z'", ",", "self", ".", "obConversion", ".", "GENOPTIONS", ")", "for", "k", ",", "v", "in", "opt", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "obconversion", ".", "AddOption", "(", "k", ",", "obconversion", ".", "OUTOPTIONS", ")", "else", ":", "obconversion", ".", "AddOption", "(", "k", ",", "obconversion", ".", "OUTOPTIONS", ",", "str", "(", "v", ")", ")", "if", "filename", ":", "if", "not", "overwrite", "and", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "IOError", "(", "(", "\"%s already exists. Use 'overwrite=True' to \"", "\"overwrite it.\"", ")", "%", "filename", ")", "obconversion", ".", "WriteFile", "(", "self", ".", "OBMol", ",", "filename", ")", "obconversion", ".", "CloseOutFile", "(", ")", "else", ":", "return", "obconversion", ".", "WriteString", "(", "self", ".", "OBMol", ")" ]
https://github.com/openbabel/openbabel/blob/f3ed2a9a5166dbd3b9ce386e636a176074a6c34c/scripts/python/openbabel/pybel.py#L516-L562
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/models/utils.py
python
_python_version
()
return tuple(version)
Return python version as a tuple of integers
Return python version as a tuple of integers
[ "Return", "python", "version", "as", "a", "tuple", "of", "integers" ]
def _python_version(): """ Return python version as a tuple of integers """ version = _sys.version.split(" ")[0] version = list(map(int, list(version.split(".")))) return tuple(version)
[ "def", "_python_version", "(", ")", ":", "version", "=", "_sys", ".", "version", ".", "split", "(", "\" \"", ")", "[", "0", "]", "version", "=", "list", "(", "map", "(", "int", ",", "list", "(", "version", ".", "split", "(", "\".\"", ")", ")", ")", ")", "return", "tuple", "(", "version", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L783-L789
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/viewer/mpl/overlayimage.py
python
getMapTile
(xtile, ytile, zoom, vendor='OSM', verbose=False)
return image
Get a map tile from public mapping server. Its not recommended to use the google maps tile server without the google maps api so if you use it to often your IP will be blacklisted TODO: look here for more vendors https://github.com/Leaflet/Leaflet TODO: Try http://scitools.org.uk/cartopy/docs/v0.14/index.html TODO: Try https://github.com/jwass/mplleaflet Parameters ---------- xtile : int ytile : int zoom : int vendor : str . 'OSM' or 'Open Street Map' (tile.openstreetmap.org) . 'GM' or 'Google Maps' (mt.google.com) (do not use it to much) verbose : bool [false] be verbose
Get a map tile from public mapping server.
[ "Get", "a", "map", "tile", "from", "public", "mapping", "server", "." ]
def getMapTile(xtile, ytile, zoom, vendor='OSM', verbose=False): """Get a map tile from public mapping server. Its not recommended to use the google maps tile server without the google maps api so if you use it to often your IP will be blacklisted TODO: look here for more vendors https://github.com/Leaflet/Leaflet TODO: Try http://scitools.org.uk/cartopy/docs/v0.14/index.html TODO: Try https://github.com/jwass/mplleaflet Parameters ---------- xtile : int ytile : int zoom : int vendor : str . 'OSM' or 'Open Street Map' (tile.openstreetmap.org) . 'GM' or 'Google Maps' (mt.google.com) (do not use it to much) verbose : bool [false] be verbose """ imagename = str(zoom) + '/' + str(xtile) + '/' + str(ytile) if vendor == 'OSM' or vendor == 'Open Street Map': # http://[abc].tile.openstreetmap.org serverName = 'tile.openstreetmap.org' url = 'http://a.' + serverName + '/' + imagename + '.png' imFormat = '.png' elif vendor == 'GM' or vendor == 'Google Maps': # its not recommended to use the google maps tile server without # google maps api .. if you use it to often your IP will be blacklisted # mt.google.com will balance itself serverName = 'http://mt.google.com' #nr = random.randint(1, 4) #serverName = 'http://mt' + str(nr) + '.google.com' # LAYERS: #h = roads only #m = standard roadmap #p = terrain #r = somehow altered roadmap #s = satellite only #t = terrain only #y = hybrid #,transit url = serverName + '/vt/lyrs=m' + \ '&x=' + str(xtile) + '&y=' + str(ytile) + \ '&hl=en' + '&z=' + str(zoom) imFormat = '.png' else: raise "Vendor: " + vendor + \ " not supported (currently only OSM (Open Street Map))" filename = cacheFileName(imagename, serverName) + imFormat image = __MatTilesCache__.get(filename) if image is None: if os.path.exists(filename): if verbose: print(("Read image from disk", filename)) image = mpimg.imread(filename) image = image[:, :, 0:3] else: if verbose: print(("Get map from url maps", url)) image = mpimg.imread(url) if verbose: print(imagename) mpimg.imsave(filename, image) if imFormat == '.jpeg': image = image[::-1, ...] / 256. __MatTilesCache__.add(filename, image) else: if verbose: print(("Took image from cache", filename)) return image
[ "def", "getMapTile", "(", "xtile", ",", "ytile", ",", "zoom", ",", "vendor", "=", "'OSM'", ",", "verbose", "=", "False", ")", ":", "imagename", "=", "str", "(", "zoom", ")", "+", "'/'", "+", "str", "(", "xtile", ")", "+", "'/'", "+", "str", "(", "ytile", ")", "if", "vendor", "==", "'OSM'", "or", "vendor", "==", "'Open Street Map'", ":", "# http://[abc].tile.openstreetmap.org", "serverName", "=", "'tile.openstreetmap.org'", "url", "=", "'http://a.'", "+", "serverName", "+", "'/'", "+", "imagename", "+", "'.png'", "imFormat", "=", "'.png'", "elif", "vendor", "==", "'GM'", "or", "vendor", "==", "'Google Maps'", ":", "# its not recommended to use the google maps tile server without", "# google maps api .. if you use it to often your IP will be blacklisted", "# mt.google.com will balance itself", "serverName", "=", "'http://mt.google.com'", "#nr = random.randint(1, 4)", "#serverName = 'http://mt' + str(nr) + '.google.com'", "# LAYERS:", "#h = roads only", "#m = standard roadmap", "#p = terrain", "#r = somehow altered roadmap", "#s = satellite only", "#t = terrain only", "#y = hybrid", "#,transit", "url", "=", "serverName", "+", "'/vt/lyrs=m'", "+", "'&x='", "+", "str", "(", "xtile", ")", "+", "'&y='", "+", "str", "(", "ytile", ")", "+", "'&hl=en'", "+", "'&z='", "+", "str", "(", "zoom", ")", "imFormat", "=", "'.png'", "else", ":", "raise", "\"Vendor: \"", "+", "vendor", "+", "\" not supported (currently only OSM (Open Street Map))\"", "filename", "=", "cacheFileName", "(", "imagename", ",", "serverName", ")", "+", "imFormat", "image", "=", "__MatTilesCache__", ".", "get", "(", "filename", ")", "if", "image", "is", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "if", "verbose", ":", "print", "(", "(", "\"Read image from disk\"", ",", "filename", ")", ")", "image", "=", "mpimg", ".", "imread", "(", "filename", ")", "image", "=", "image", "[", ":", ",", ":", ",", "0", ":", "3", "]", "else", ":", "if", "verbose", ":", "print", "(", "(", "\"Get map from url maps\"", ",", "url", ")", ")", "image", "=", "mpimg", ".", "imread", "(", "url", ")", "if", "verbose", ":", "print", "(", "imagename", ")", "mpimg", ".", "imsave", "(", "filename", ",", "image", ")", "if", "imFormat", "==", "'.jpeg'", ":", "image", "=", "image", "[", ":", ":", "-", "1", ",", "...", "]", "/", "256.", "__MatTilesCache__", ".", "add", "(", "filename", ",", "image", ")", "else", ":", "if", "verbose", ":", "print", "(", "(", "\"Took image from cache\"", ",", "filename", ")", ")", "return", "image" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/viewer/mpl/overlayimage.py#L162-L247
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/margin.py
python
Margin.excess_margin
(self)
return self._excess_margin
Gets the excess_margin of this Margin. # noqa: E501 :return: The excess_margin of this Margin. # noqa: E501 :rtype: float
Gets the excess_margin of this Margin. # noqa: E501
[ "Gets", "the", "excess_margin", "of", "this", "Margin", ".", "#", "noqa", ":", "E501" ]
def excess_margin(self): """Gets the excess_margin of this Margin. # noqa: E501 :return: The excess_margin of this Margin. # noqa: E501 :rtype: float """ return self._excess_margin
[ "def", "excess_margin", "(", "self", ")", ":", "return", "self", ".", "_excess_margin" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/margin.py#L967-L974
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/parser/WebIDL.py
python
Parser.p_Dictionary
(self, p)
Dictionary : DICTIONARY IDENTIFIER Inheritance LBRACE DictionaryMembers RBRACE SEMICOLON
Dictionary : DICTIONARY IDENTIFIER Inheritance LBRACE DictionaryMembers RBRACE SEMICOLON
[ "Dictionary", ":", "DICTIONARY", "IDENTIFIER", "Inheritance", "LBRACE", "DictionaryMembers", "RBRACE", "SEMICOLON" ]
def p_Dictionary(self, p): """ Dictionary : DICTIONARY IDENTIFIER Inheritance LBRACE DictionaryMembers RBRACE SEMICOLON """ location = self.getLocation(p, 1) identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2]) members = p[5] p[0] = IDLDictionary(location, self.globalScope(), identifier, p[3], members)
[ "def", "p_Dictionary", "(", "self", ",", "p", ")", ":", "location", "=", "self", ".", "getLocation", "(", "p", ",", "1", ")", "identifier", "=", "IDLUnresolvedIdentifier", "(", "self", ".", "getLocation", "(", "p", ",", "2", ")", ",", "p", "[", "2", "]", ")", "members", "=", "p", "[", "5", "]", "p", "[", "0", "]", "=", "IDLDictionary", "(", "location", ",", "self", ".", "globalScope", "(", ")", ",", "identifier", ",", "p", "[", "3", "]", ",", "members", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L4408-L4415
bingwin/MicroChat
81d9a71a212c1cbca5bba497ec42659a7d25dccf
mars/lint/cpplint.py
python
IsDeletedOrDefault
(clean_lines, linenum)
return Match(r'\s*=\s*(?:delete|default)\b', close_line[close_paren:])
Check if current constructor or operator is deleted or default. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if this is a deleted or default constructor.
Check if current constructor or operator is deleted or default.
[ "Check", "if", "current", "constructor", "or", "operator", "is", "deleted", "or", "default", "." ]
def IsDeletedOrDefault(clean_lines, linenum): """Check if current constructor or operator is deleted or default. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if this is a deleted or default constructor. """ open_paren = clean_lines.elided[linenum].find('(') if open_paren < 0: return False (close_line, _, close_paren) = CloseExpression( clean_lines, linenum, open_paren) if close_paren < 0: return False return Match(r'\s*=\s*(?:delete|default)\b', close_line[close_paren:])
[ "def", "IsDeletedOrDefault", "(", "clean_lines", ",", "linenum", ")", ":", "open_paren", "=", "clean_lines", ".", "elided", "[", "linenum", "]", ".", "find", "(", "'('", ")", "if", "open_paren", "<", "0", ":", "return", "False", "(", "close_line", ",", "_", ",", "close_paren", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "open_paren", ")", "if", "close_paren", "<", "0", ":", "return", "False", "return", "Match", "(", "r'\\s*=\\s*(?:delete|default)\\b'", ",", "close_line", "[", "close_paren", ":", "]", ")" ]
https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L3640-L3656
google/ion
ef47f3b824050499ce5c6f774b366f6c4dbce0af
ion/dev/zipasset_generator.py
python
GetPathToAsset
(asset, search_paths)
return None
Builds a list of (filename, asset) pairs from an asset file. Args: asset: string - a file to search for. search_paths: list of strings - paths to search for asset files Returns: The full path to the found file, or None if it does not exist.
Builds a list of (filename, asset) pairs from an asset file.
[ "Builds", "a", "list", "of", "(", "filename", "asset", ")", "pairs", "from", "an", "asset", "file", "." ]
def GetPathToAsset(asset, search_paths): """Builds a list of (filename, asset) pairs from an asset file. Args: asset: string - a file to search for. search_paths: list of strings - paths to search for asset files Returns: The full path to the found file, or None if it does not exist. """ if os.path.exists(asset): return asset else: for path in search_paths: asset_filename = os.path.join(path, asset) if os.path.exists(asset_filename): return asset_filename return None
[ "def", "GetPathToAsset", "(", "asset", ",", "search_paths", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "asset", ")", ":", "return", "asset", "else", ":", "for", "path", "in", "search_paths", ":", "asset_filename", "=", "os", ".", "path", ".", "join", "(", "path", ",", "asset", ")", "if", "os", ".", "path", ".", "exists", "(", "asset_filename", ")", ":", "return", "asset_filename", "return", "None" ]
https://github.com/google/ion/blob/ef47f3b824050499ce5c6f774b366f6c4dbce0af/ion/dev/zipasset_generator.py#L91-L108
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py
python
Base.AppendENVPath
(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=1)
Append path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the end (it will be left where it is).
Append path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string.
[ "Append", "path", "elements", "to", "the", "path", "name", "in", "the", "ENV", "dictionary", "for", "this", "environment", ".", "Will", "only", "add", "any", "particular", "path", "once", "and", "will", "normpath", "and", "normcase", "all", "paths", "to", "help", "assure", "this", ".", "This", "can", "also", "handle", "the", "case", "where", "the", "env", "variable", "is", "a", "list", "instead", "of", "a", "string", "." ]
def AppendENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=1): """Append path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the end (it will be left where it is). """ orig = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = SCons.Util.AppendPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv
[ "def", "AppendENVPath", "(", "self", ",", "name", ",", "newpath", ",", "envname", "=", "'ENV'", ",", "sep", "=", "os", ".", "pathsep", ",", "delete_existing", "=", "1", ")", ":", "orig", "=", "''", "if", "envname", "in", "self", ".", "_dict", "and", "name", "in", "self", ".", "_dict", "[", "envname", "]", ":", "orig", "=", "self", ".", "_dict", "[", "envname", "]", "[", "name", "]", "nv", "=", "SCons", ".", "Util", ".", "AppendPath", "(", "orig", ",", "newpath", ",", "sep", ",", "delete_existing", ",", "canonicalize", "=", "self", ".", "_canonicalize", ")", "if", "envname", "not", "in", "self", ".", "_dict", ":", "self", ".", "_dict", "[", "envname", "]", "=", "{", "}", "self", ".", "_dict", "[", "envname", "]", "[", "name", "]", "=", "nv" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py#L1219-L1241
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py
python
Distribution.as_requirement
(self)
return Requirement.parse(spec)
Return a ``Requirement`` that matches this distribution exactly
Return a ``Requirement`` that matches this distribution exactly
[ "Return", "a", "Requirement", "that", "matches", "this", "distribution", "exactly" ]
def as_requirement(self): """Return a ``Requirement`` that matches this distribution exactly""" if isinstance(self.parsed_version, packaging.version.Version): spec = "%s==%s" % (self.project_name, self.parsed_version) else: spec = "%s===%s" % (self.project_name, self.parsed_version) return Requirement.parse(spec)
[ "def", "as_requirement", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "parsed_version", ",", "packaging", ".", "version", ".", "Version", ")", ":", "spec", "=", "\"%s==%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "else", ":", "spec", "=", "\"%s===%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "return", "Requirement", ".", "parse", "(", "spec", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py#L2714-L2721
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetWrapperExtension
(self)
Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.
Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.
[ "Returns", "the", "bundle", "extension", "(", ".", "app", ".", "framework", ".", "plugin", "etc", ")", ".", "Only", "valid", "for", "bundles", "." ]
def GetWrapperExtension(self): """Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] in ('loadable_module', 'shared_library'): default_wrapper_extension = { 'loadable_module': 'bundle', 'shared_library': 'framework', }[self.spec['type']] wrapper_extension = self.GetPerTargetSetting( 'WRAPPER_EXTENSION', default=default_wrapper_extension) return '.' + self.spec.get('product_extension', wrapper_extension) elif self.spec['type'] == 'executable': return '.app' else: assert False, "Don't know extension for '%s', target '%s'" % ( self.spec['type'], self.spec['target_name'])
[ "def", "GetWrapperExtension", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "if", "self", ".", "spec", "[", "'type'", "]", "in", "(", "'loadable_module'", ",", "'shared_library'", ")", ":", "default_wrapper_extension", "=", "{", "'loadable_module'", ":", "'bundle'", ",", "'shared_library'", ":", "'framework'", ",", "}", "[", "self", ".", "spec", "[", "'type'", "]", "]", "wrapper_extension", "=", "self", ".", "GetPerTargetSetting", "(", "'WRAPPER_EXTENSION'", ",", "default", "=", "default_wrapper_extension", ")", "return", "'.'", "+", "self", ".", "spec", ".", "get", "(", "'product_extension'", ",", "wrapper_extension", ")", "elif", "self", ".", "spec", "[", "'type'", "]", "==", "'executable'", ":", "return", "'.app'", "else", ":", "assert", "False", ",", "\"Don't know extension for '%s', target '%s'\"", "%", "(", "self", ".", "spec", "[", "'type'", "]", ",", "self", ".", "spec", "[", "'target_name'", "]", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py#L66-L82
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_gui.py
python
GuiDomain.isSelected
(self, objID, objType="vehicle")
return self._getUniversal(tc.VAR_SELECT, objID, "s", objType)
isSelected(string, string) -> int Return 1 if the object of the given type and id is select, 0 otherwise
isSelected(string, string) -> int Return 1 if the object of the given type and id is select, 0 otherwise
[ "isSelected", "(", "string", "string", ")", "-", ">", "int", "Return", "1", "if", "the", "object", "of", "the", "given", "type", "and", "id", "is", "select", "0", "otherwise" ]
def isSelected(self, objID, objType="vehicle"): """isSelected(string, string) -> int Return 1 if the object of the given type and id is select, 0 otherwise """ return self._getUniversal(tc.VAR_SELECT, objID, "s", objType)
[ "def", "isSelected", "(", "self", ",", "objID", ",", "objType", "=", "\"vehicle\"", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_SELECT", ",", "objID", ",", "\"s\"", ",", "objType", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_gui.py#L132-L136
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Menu.post
(self, x, y)
Display a menu at position X,Y.
Display a menu at position X,Y.
[ "Display", "a", "menu", "at", "position", "X", "Y", "." ]
def post(self, x, y): """Display a menu at position X,Y.""" self.tk.call(self._w, 'post', x, y)
[ "def", "post", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'post'", ",", "x", ",", "y", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2740-L2742
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/run_benchmark.py
python
CaffeBenchmark._exec_command
(self, cmd)
return subprocess.check_output(cmd, stderr = subprocess.STDOUT, shell = True)
execute shell command
execute shell command
[ "execute", "shell", "command" ]
def _exec_command(self, cmd): '''execute shell command''' return subprocess.check_output(cmd, stderr = subprocess.STDOUT, shell = True)
[ "def", "_exec_command", "(", "self", ",", "cmd", ")", ":", "return", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "True", ")" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/run_benchmark.py#L62-L64
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/collector/ftrace.py
python
ftraceCollector.prepare
(self, conf: dict)
return conf
type: "kprobe" | "uprobe" | "event" list for kprobe: [name, mod, offset, fetchargs: []] list for uprobe: [func, lib, offset] list for event : [system, event, filter=""]
type: "kprobe" | "uprobe" | "event" list for kprobe: [name, mod, offset, fetchargs: []] list for uprobe: [func, lib, offset] list for event : [system, event, filter=""]
[ "type", ":", "kprobe", "|", "uprobe", "|", "event", "list", "for", "kprobe", ":", "[", "name", "mod", "offset", "fetchargs", ":", "[]", "]", "list", "for", "uprobe", ":", "[", "func", "lib", "offset", "]", "list", "for", "event", ":", "[", "system", "event", "filter", "=", "]" ]
def prepare(self, conf: dict) -> dict: """ type: "kprobe" | "uprobe" | "event" list for kprobe: [name, mod, offset, fetchargs: []] list for uprobe: [func, lib, offset] list for event : [system, event, filter=""] """ ftraceOption = conf.get('collector', {}).get('ftrace') if ftraceOption == None: return conf traceClock = conf.get('control', {}).get('traceClock', 'global') open(os.path.join(FTRACE_DIR, "trace_clock"), 'w').write(traceClock) for name in ftraceOption.keys(): instOption = ftraceOption[name] traceType = instOption.get('type') if instOption.get('name', None) != name: assert() _saveTo = instOption.get('saveTo', None) if _saveTo != None: _saveTo = os.path.abspath(_saveTo) traceInst = Ftrace(name, saveTo=_saveTo, _clk=traceClock, _type=traceType) if traceType == 'kprobe': # dpu.addKprobe("cu_start", "zocl", "zocl_hls_start", ["cu_idx=+0(%x0):u32"]) for t in instOption.get("traceList", None): traceInst.addKprobe(*t) elif traceType == 'uprobe': # addUprobe(func.name, func.libPath, "0x%x" % func.offset) for t in instOption.get("traceList", None): traceInst.addUprobe(*t) elif traceType == 'event': for t in instOption.get("traceList", None): traceInst.enableEvent(*t) else: assert() self.instances.append(traceInst) for ft in self.instances: ft.clearTracing() return conf
[ "def", "prepare", "(", "self", ",", "conf", ":", "dict", ")", "->", "dict", ":", "ftraceOption", "=", "conf", ".", "get", "(", "'collector'", ",", "{", "}", ")", ".", "get", "(", "'ftrace'", ")", "if", "ftraceOption", "==", "None", ":", "return", "conf", "traceClock", "=", "conf", ".", "get", "(", "'control'", ",", "{", "}", ")", ".", "get", "(", "'traceClock'", ",", "'global'", ")", "open", "(", "os", ".", "path", ".", "join", "(", "FTRACE_DIR", ",", "\"trace_clock\"", ")", ",", "'w'", ")", ".", "write", "(", "traceClock", ")", "for", "name", "in", "ftraceOption", ".", "keys", "(", ")", ":", "instOption", "=", "ftraceOption", "[", "name", "]", "traceType", "=", "instOption", ".", "get", "(", "'type'", ")", "if", "instOption", ".", "get", "(", "'name'", ",", "None", ")", "!=", "name", ":", "assert", "(", ")", "_saveTo", "=", "instOption", ".", "get", "(", "'saveTo'", ",", "None", ")", "if", "_saveTo", "!=", "None", ":", "_saveTo", "=", "os", ".", "path", ".", "abspath", "(", "_saveTo", ")", "traceInst", "=", "Ftrace", "(", "name", ",", "saveTo", "=", "_saveTo", ",", "_clk", "=", "traceClock", ",", "_type", "=", "traceType", ")", "if", "traceType", "==", "'kprobe'", ":", "# dpu.addKprobe(\"cu_start\", \"zocl\", \"zocl_hls_start\", [\"cu_idx=+0(%x0):u32\"])", "for", "t", "in", "instOption", ".", "get", "(", "\"traceList\"", ",", "None", ")", ":", "traceInst", ".", "addKprobe", "(", "*", "t", ")", "elif", "traceType", "==", "'uprobe'", ":", "# addUprobe(func.name, func.libPath, \"0x%x\" % func.offset)", "for", "t", "in", "instOption", ".", "get", "(", "\"traceList\"", ",", "None", ")", ":", "traceInst", ".", "addUprobe", "(", "*", "t", ")", "elif", "traceType", "==", "'event'", ":", "for", "t", "in", "instOption", ".", "get", "(", "\"traceList\"", ",", "None", ")", ":", "traceInst", ".", "enableEvent", "(", "*", "t", ")", "else", ":", "assert", "(", ")", "self", ".", "instances", ".", "append", "(", "traceInst", ")", "for", "ft", "in", "self", ".", "instances", ":", "ft", ".", "clearTracing", "(", ")", "return", "conf" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/collector/ftrace.py#L317-L365
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/dataview.py
python
DataViewIndexListModel.RowPrepended
(*args, **kwargs)
return _dataview.DataViewIndexListModel_RowPrepended(*args, **kwargs)
RowPrepended(self) Call this after a row has been prepended to the model.
RowPrepended(self)
[ "RowPrepended", "(", "self", ")" ]
def RowPrepended(*args, **kwargs): """ RowPrepended(self) Call this after a row has been prepended to the model. """ return _dataview.DataViewIndexListModel_RowPrepended(*args, **kwargs)
[ "def", "RowPrepended", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewIndexListModel_RowPrepended", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L829-L835
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py
python
parse_header_links
(value)
return links
Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list
Return a list of parsed link headers proxies.
[ "Return", "a", "list", "of", "parsed", "link", "headers", "proxies", "." ]
def parse_header_links(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = ' \'"' value = value.strip(replace_chars) if not value: return links for val in re.split(', *<', value): try: url, params = val.split(';', 1) except ValueError: url, params = val, '' link = {'url': url.strip('<> \'"')} for param in params.split(';'): try: key, value = param.split('=') except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links
[ "def", "parse_header_links", "(", "value", ")", ":", "links", "=", "[", "]", "replace_chars", "=", "' \\'\"'", "value", "=", "value", ".", "strip", "(", "replace_chars", ")", "if", "not", "value", ":", "return", "links", "for", "val", "in", "re", ".", "split", "(", "', *<'", ",", "value", ")", ":", "try", ":", "url", ",", "params", "=", "val", ".", "split", "(", "';'", ",", "1", ")", "except", "ValueError", ":", "url", ",", "params", "=", "val", ",", "''", "link", "=", "{", "'url'", ":", "url", ".", "strip", "(", "'<> \\'\"'", ")", "}", "for", "param", "in", "params", ".", "split", "(", "';'", ")", ":", "try", ":", "key", ",", "value", "=", "param", ".", "split", "(", "'='", ")", "except", "ValueError", ":", "break", "link", "[", "key", ".", "strip", "(", "replace_chars", ")", "]", "=", "value", ".", "strip", "(", "replace_chars", ")", "links", ".", "append", "(", "link", ")", "return", "links" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L829-L863
MTG/gaia
0f7214dbdec6f9b651ca34211824841ffba0bc77
src/doc/doxy2swig.py
python
Doxy2SWIG.generate
(self)
Parses the file set in the initialization. The resulting data is stored in `self.pieces`.
Parses the file set in the initialization. The resulting data is stored in `self.pieces`.
[ "Parses", "the", "file", "set", "in", "the", "initialization", ".", "The", "resulting", "data", "is", "stored", "in", "self", ".", "pieces", "." ]
def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc)
[ "def", "generate", "(", "self", ")", ":", "self", ".", "parse", "(", "self", ".", "xmldoc", ")" ]
https://github.com/MTG/gaia/blob/0f7214dbdec6f9b651ca34211824841ffba0bc77/src/doc/doxy2swig.py#L158-L163
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
third_party/gpus/find_cuda_config.py
python
_library_paths
()
return [ "", "lib64", "lib", "lib/*-linux-gnu", "lib/x64", "extras/CUPTI/*", "local/cuda/lib64", "local/cuda/extras/CUPTI/lib64", ]
Returns hard-coded set of relative paths to look for library files.
Returns hard-coded set of relative paths to look for library files.
[ "Returns", "hard", "-", "coded", "set", "of", "relative", "paths", "to", "look", "for", "library", "files", "." ]
def _library_paths(): """Returns hard-coded set of relative paths to look for library files.""" return [ "", "lib64", "lib", "lib/*-linux-gnu", "lib/x64", "extras/CUPTI/*", "local/cuda/lib64", "local/cuda/extras/CUPTI/lib64", ]
[ "def", "_library_paths", "(", ")", ":", "return", "[", "\"\"", ",", "\"lib64\"", ",", "\"lib\"", ",", "\"lib/*-linux-gnu\"", ",", "\"lib/x64\"", ",", "\"extras/CUPTI/*\"", ",", "\"local/cuda/lib64\"", ",", "\"local/cuda/extras/CUPTI/lib64\"", ",", "]" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/third_party/gpus/find_cuda_config.py#L183-L194
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/extras/resx.py
python
resx_file
(self, node)
Bind the .resx extension to a resgen task
Bind the .resx extension to a resgen task
[ "Bind", "the", ".", "resx", "extension", "to", "a", "resgen", "task" ]
def resx_file(self, node): """ Bind the .resx extension to a resgen task """ if not getattr(self, 'cs_task', None): self.bld.fatal('resx_file has no link task for use %r' % self) # Given assembly 'Foo' and file 'Sub/Dir/File.resx', create 'Foo.Sub.Dir.File.resources' assembly = os.path.splitext(self.gen)[0] res = os.path.splitext(node.path_from(self.path))[0].replace('/', '.') out = self.path.find_or_declare(assembly + '.' + res + '.resources') tsk = self.create_task('resgen', node, out) self.cs_task.dep_nodes.extend(tsk.outputs) # dependency self.env.append_value('RESOURCES', tsk.outputs[0].bldpath())
[ "def", "resx_file", "(", "self", ",", "node", ")", ":", "if", "not", "getattr", "(", "self", ",", "'cs_task'", ",", "None", ")", ":", "self", ".", "bld", ".", "fatal", "(", "'resx_file has no link task for use %r'", "%", "self", ")", "# Given assembly 'Foo' and file 'Sub/Dir/File.resx', create 'Foo.Sub.Dir.File.resources'", "assembly", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "gen", ")", "[", "0", "]", "res", "=", "os", ".", "path", ".", "splitext", "(", "node", ".", "path_from", "(", "self", ".", "path", ")", ")", "[", "0", "]", ".", "replace", "(", "'/'", ",", "'.'", ")", "out", "=", "self", ".", "path", ".", "find_or_declare", "(", "assembly", "+", "'.'", "+", "res", "+", "'.resources'", ")", "tsk", "=", "self", ".", "create_task", "(", "'resgen'", ",", "node", ",", "out", ")", "self", ".", "cs_task", ".", "dep_nodes", ".", "extend", "(", "tsk", ".", "outputs", ")", "# dependency", "self", ".", "env", ".", "append_value", "(", "'RESOURCES'", ",", "tsk", ".", "outputs", "[", "0", "]", ".", "bldpath", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/resx.py#L13-L28
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.py
python
_cf_data_from_bytes
(bytestring)
return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) )
Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller.
[]
def _cf_data_from_bytes(bytestring): """ Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. """ return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) )
[ "def", "_cf_data_from_bytes", "(", "bytestring", ")", ":", "return", "CoreFoundation", ".", "CFDataCreate", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "bytestring", ",", "len", "(", "bytestring", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.py#L53-L67
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
GridCellRenderer.Clone
(*args, **kwargs)
return _grid.GridCellRenderer_Clone(*args, **kwargs)
Clone(self) -> GridCellRenderer
Clone(self) -> GridCellRenderer
[ "Clone", "(", "self", ")", "-", ">", "GridCellRenderer" ]
def Clone(*args, **kwargs): """Clone(self) -> GridCellRenderer""" return _grid.GridCellRenderer_Clone(*args, **kwargs)
[ "def", "Clone", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellRenderer_Clone", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L120-L122
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/MooseDocs/common/build_class_database.py
python
_match_child
(objects, filename, match)
Child class match function.
Child class match function.
[ "Child", "class", "match", "function", "." ]
def _match_child(objects, filename, match): """Child class match function.""" key = match.group('key') if key in objects: filename = os.path.relpath(filename, MooseDocs.ROOT_DIR) objects[key].children.add(filename)
[ "def", "_match_child", "(", "objects", ",", "filename", ",", "match", ")", ":", "key", "=", "match", ".", "group", "(", "'key'", ")", "if", "key", "in", "objects", ":", "filename", "=", "os", ".", "path", ".", "relpath", "(", "filename", ",", "MooseDocs", ".", "ROOT_DIR", ")", "objects", "[", "key", "]", ".", "children", ".", "add", "(", "filename", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/common/build_class_database.py#L99-L104
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
tools/query_cmp/src/lib/compare_rrset.py
python
output
(sect, buf, rrset, isleft)
Format and return the rrset according to which section and which message it belongs to. @param sect: section name @type sect: string @param buf: passed by parameter, to store the formatted string @param buf: dict @param rrset: the rrset to be formatted @type rrset: RRset @param isleft: to be compared, the report has the content corresponding to the 1st message printed on the left, while the one corresponding to the 2nd message on the right. This is a flag to which one it is. @type isleft: BOOL
Format and return the rrset according to which section and which message it belongs to.
[ "Format", "and", "return", "the", "rrset", "according", "to", "which", "section", "and", "which", "message", "it", "belongs", "to", "." ]
def output(sect, buf, rrset, isleft): """ Format and return the rrset according to which section and which message it belongs to. @param sect: section name @type sect: string @param buf: passed by parameter, to store the formatted string @param buf: dict @param rrset: the rrset to be formatted @type rrset: RRset @param isleft: to be compared, the report has the content corresponding to the 1st message printed on the left, while the one corresponding to the 2nd message on the right. This is a flag to which one it is. @type isleft: BOOL """ if not sect in buf: buf[sect] = '' if sect == 'question': buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'name') if not isleft: buf[sect] = buf[sect] + ' ' * POS_LEFT buf[sect] = buf[sect] + rrset.get_name().to_text() + "\n" buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'class') if not isleft: buf[sect] = buf[sect] + ' ' * POS_LEFT buf[sect] = buf[sect] + rrset.get_class().to_text() + "\n" buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'type') if not isleft: buf[sect] = buf[sect] + ' ' * POS_LEFT buf[sect] = buf[sect] + rrset.get_type().to_text() + "\n" else: buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'ttl') if not isleft: buf[sect] = buf[sect] + ' ' * int(POS_LEFT) buf[sect] = buf[sect] + rrset.get_ttl().to_text() + "\n" buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'name') if not isleft: buf[sect] = buf[sect] + ' ' * int(POS_LEFT) buf[sect] = buf[sect] + rrset.get_name().to_text() + "\n" buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'class') if not isleft: buf[sect] = buf[sect] + ' ' * int(POS_LEFT) buf[sect] = buf[sect] + rrset.get_class().to_text() + "\n" buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'type') if not isleft: buf[sect] = buf[sect] + ' ' * int(POS_LEFT) buf[sect] = buf[sect] + rrset.get_type().to_text() + "\n" buf[sect] = buf[sect] + '%-*s' % (POS_TITLE, 'rdata') i = 0 rdata = rrset.get_rdata() for item in rdata: if i > 0: buf[sect] = buf[sect] + ' ' * POS_TITLE if not isleft: buf[sect] = buf[sect] + ' ' * POS_LEFT buf[sect] = buf[sect] + item.to_text() + "\n" i = i + 1 buf[sect] = buf[sect] + "\n"
[ "def", "output", "(", "sect", ",", "buf", ",", "rrset", ",", "isleft", ")", ":", "if", "not", "sect", "in", "buf", ":", "buf", "[", "sect", "]", "=", "''", "if", "sect", "==", "'question'", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'name'", ")", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "POS_LEFT", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "rrset", ".", "get_name", "(", ")", ".", "to_text", "(", ")", "+", "\"\\n\"", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'class'", ")", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "POS_LEFT", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "rrset", ".", "get_class", "(", ")", ".", "to_text", "(", ")", "+", "\"\\n\"", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'type'", ")", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "POS_LEFT", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "rrset", ".", "get_type", "(", ")", ".", "to_text", "(", ")", "+", "\"\\n\"", "else", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'ttl'", ")", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "int", "(", "POS_LEFT", ")", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "rrset", ".", "get_ttl", "(", ")", ".", "to_text", "(", ")", "+", "\"\\n\"", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'name'", ")", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "int", "(", "POS_LEFT", ")", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "rrset", ".", "get_name", "(", ")", ".", "to_text", "(", ")", "+", "\"\\n\"", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'class'", ")", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "int", "(", "POS_LEFT", ")", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "rrset", ".", "get_class", "(", ")", ".", "to_text", "(", ")", "+", "\"\\n\"", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'type'", ")", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "int", "(", "POS_LEFT", ")", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "rrset", ".", "get_type", "(", ")", ".", "to_text", "(", ")", "+", "\"\\n\"", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "'%-*s'", "%", "(", "POS_TITLE", ",", "'rdata'", ")", "i", "=", "0", "rdata", "=", "rrset", ".", "get_rdata", "(", ")", "for", "item", "in", "rdata", ":", "if", "i", ">", "0", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "POS_TITLE", "if", "not", "isleft", ":", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "' '", "*", "POS_LEFT", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "item", ".", "to_text", "(", ")", "+", "\"\\n\"", "i", "=", "i", "+", "1", "buf", "[", "sect", "]", "=", "buf", "[", "sect", "]", "+", "\"\\n\"" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/tools/query_cmp/src/lib/compare_rrset.py#L80-L147
ivansafrin/Polycode
37a40fefe194ec7f6e9d1257f3bb3517b0a168bc
Bindings/Scripts/create_lua_library/CppHeaderParser3.py
python
detect_lineno
(s)
return curLine
Detect the line number for a given token string
Detect the line number for a given token string
[ "Detect", "the", "line", "number", "for", "a", "given", "token", "string" ]
def detect_lineno(s): """Detect the line number for a given token string""" try: rtn = s.lineno() if rtn != -1: return rtn except: pass global curLine return curLine
[ "def", "detect_lineno", "(", "s", ")", ":", "try", ":", "rtn", "=", "s", ".", "lineno", "(", ")", "if", "rtn", "!=", "-", "1", ":", "return", "rtn", "except", ":", "pass", "global", "curLine", "return", "curLine" ]
https://github.com/ivansafrin/Polycode/blob/37a40fefe194ec7f6e9d1257f3bb3517b0a168bc/Bindings/Scripts/create_lua_library/CppHeaderParser3.py#L275-L283
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
llvm/bindings/python/llvm/object.py
python
Relocation.type_name
(self)
return lib.LLVMGetRelocationTypeName(self)
The relocation type's name, as a str.
The relocation type's name, as a str.
[ "The", "relocation", "type", "s", "name", "as", "a", "str", "." ]
def type_name(self): """The relocation type's name, as a str.""" if self.expired: raise Exception('Relocation instance has expired.') return lib.LLVMGetRelocationTypeName(self)
[ "def", "type_name", "(", "self", ")", ":", "if", "self", ".", "expired", ":", "raise", "Exception", "(", "'Relocation instance has expired.'", ")", "return", "lib", ".", "LLVMGetRelocationTypeName", "(", "self", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/llvm/bindings/python/llvm/object.py#L399-L404
milvus-io/milvus
3b1030de2b6c39e3512833e97f6044d63eb24237
internal/core/build-support/lintutils.py
python
chunk
(seq, n)
return chunks
divide a sequence into equal sized chunks (the last chunk may be smaller, but won't be empty)
divide a sequence into equal sized chunks (the last chunk may be smaller, but won't be empty)
[ "divide", "a", "sequence", "into", "equal", "sized", "chunks", "(", "the", "last", "chunk", "may", "be", "smaller", "but", "won", "t", "be", "empty", ")" ]
def chunk(seq, n): """ divide a sequence into equal sized chunks (the last chunk may be smaller, but won't be empty) """ chunks = [] some = [] for element in seq: if len(some) == n: chunks.append(some) some = [] some.append(element) if len(some) > 0: chunks.append(some) return chunks
[ "def", "chunk", "(", "seq", ",", "n", ")", ":", "chunks", "=", "[", "]", "some", "=", "[", "]", "for", "element", "in", "seq", ":", "if", "len", "(", "some", ")", "==", "n", ":", "chunks", ".", "append", "(", "some", ")", "some", "=", "[", "]", "some", ".", "append", "(", "element", ")", "if", "len", "(", "some", ")", ">", "0", ":", "chunks", ".", "append", "(", "some", ")", "return", "chunks" ]
https://github.com/milvus-io/milvus/blob/3b1030de2b6c39e3512833e97f6044d63eb24237/internal/core/build-support/lintutils.py#L24-L38
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
waf-tools/boost.py
python
check_boost
(self, *k, **kw)
Initialize boost libraries to be used. Keywords: you can pass the same parameters as with the command line (without "--boost-"). Note that the command line has the priority, and should preferably be used.
Initialize boost libraries to be used.
[ "Initialize", "boost", "libraries", "to", "be", "used", "." ]
def check_boost(self, *k, **kw): """ Initialize boost libraries to be used. Keywords: you can pass the same parameters as with the command line (without "--boost-"). Note that the command line has the priority, and should preferably be used. """ if not self.env['CXX']: self.fatal('load a c++ compiler first, conf.load("compiler_cxx")') params = { 'lib': k and k[0] or kw.get('lib', None), 'stlib': kw.get('stlib', None), 'required': kw.get('required', True) } for key, value in self.options.__dict__.items(): if not key.startswith('boost_'): continue key = key[len('boost_'):] params[key] = value and value or kw.get(key, '') var = kw.get('uselib_store', 'BOOST') self.start_msg('Checking boost includes') self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params) self.env.BOOST_VERSION = self.boost_get_version(inc) self.end_msg(self.env.BOOST_VERSION + ' ' + inc) if Logs.verbose: Logs.pprint('CYAN', ' path : %s' % self.env['INCLUDES_%s' % var]) if not params['lib'] and not params['stlib']: return if 'static' in kw or 'static' in params: Logs.warn('boost: static parameter is deprecated, use stlib instead.') self.start_msg('Checking boost libs') path, libs, stlibs = self.boost_get_libs(**params) self.env['LIBPATH_%s' % var] = [path] self.env['STLIBPATH_%s' % var] = [path] self.env['LIB_%s' % var] = libs self.env['STLIB_%s' % var] = stlibs self.end_msg('ok' + ' ' + path) if Logs.verbose: Logs.pprint('CYAN', ' path : %s' % path) Logs.pprint('CYAN', ' shared libs : %s' % libs) Logs.pprint('CYAN', ' static libs : %s' % stlibs) def try_link(): if (params['lib'] and 'system' in params['lib']) or \ params['stlib'] and 'system' in params['stlib']: self.check_cxx(fragment=BOOST_ERROR_CODE, use=var, execute=False) if (params['lib'] and 'thread' in params['lib']) or \ params['stlib'] and 'thread' in params['stlib']: self.check_cxx(fragment=BOOST_THREAD_CODE, use=var, execute=False) if params.get('linkage_autodetect', False): self.start_msg("Attempting to detect boost linkage flags") toolset = self.boost_get_toolset(kw.get('toolset', '')) if toolset in ('vc',): # disable auto-linking feature, causing error LNK1181 # because the code wants to be linked against self.env['DEFINES_%s' % var] += ['BOOST_ALL_NO_LIB'] # if no dlls are present, we guess the .lib files are not stubs has_dlls = False for x in Utils.listdir(path): if x.endswith(self.env.cxxshlib_PATTERN % ''): has_dlls = True break if not has_dlls: self.env['STLIBPATH_%s' % var] = [path] self.env['STLIB_%s' % var] = libs del self.env['LIB_%s' % var] del self.env['LIBPATH_%s' % var] # we attempt to play with some known-to-work CXXFLAGS combinations for cxxflags in (['/MD', '/EHsc'], []): self.env.stash() self.env["CXXFLAGS_%s" % var] += cxxflags try: try_link() self.end_msg("ok: winning cxxflags combination: %s" % (self.env["CXXFLAGS_%s" % var])) exc = None break except Errors.ConfigurationError as e: self.env.revert() exc = e if exc is not None: self.end_msg("Could not auto-detect boost linking flags combination, you may report it to boost.py author", ex=exc) self.fatal('The configuration failed') else: self.end_msg("Boost linkage flags auto-detection not implemented (needed ?) for this toolchain") self.fatal('The configuration failed') else: self.start_msg('Checking for boost linkage') try: try_link() except Errors.ConfigurationError as e: self.end_msg("Could not link against boost libraries using supplied options") self.fatal('The configuration failed') self.end_msg('ok')
[ "def", "check_boost", "(", "self", ",", "*", "k", ",", "*", "*", "kw", ")", ":", "if", "not", "self", ".", "env", "[", "'CXX'", "]", ":", "self", ".", "fatal", "(", "'load a c++ compiler first, conf.load(\"compiler_cxx\")'", ")", "params", "=", "{", "'lib'", ":", "k", "and", "k", "[", "0", "]", "or", "kw", ".", "get", "(", "'lib'", ",", "None", ")", ",", "'stlib'", ":", "kw", ".", "get", "(", "'stlib'", ",", "None", ")", ",", "'required'", ":", "kw", ".", "get", "(", "'required'", ",", "True", ")", "}", "for", "key", ",", "value", "in", "self", ".", "options", ".", "__dict__", ".", "items", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "'boost_'", ")", ":", "continue", "key", "=", "key", "[", "len", "(", "'boost_'", ")", ":", "]", "params", "[", "key", "]", "=", "value", "and", "value", "or", "kw", ".", "get", "(", "key", ",", "''", ")", "var", "=", "kw", ".", "get", "(", "'uselib_store'", ",", "'BOOST'", ")", "self", ".", "start_msg", "(", "'Checking boost includes'", ")", "self", ".", "env", "[", "'INCLUDES_%s'", "%", "var", "]", "=", "inc", "=", "self", ".", "boost_get_includes", "(", "*", "*", "params", ")", "self", ".", "env", ".", "BOOST_VERSION", "=", "self", ".", "boost_get_version", "(", "inc", ")", "self", ".", "end_msg", "(", "self", ".", "env", ".", "BOOST_VERSION", "+", "' '", "+", "inc", ")", "if", "Logs", ".", "verbose", ":", "Logs", ".", "pprint", "(", "'CYAN'", ",", "'\tpath : %s'", "%", "self", ".", "env", "[", "'INCLUDES_%s'", "%", "var", "]", ")", "if", "not", "params", "[", "'lib'", "]", "and", "not", "params", "[", "'stlib'", "]", ":", "return", "if", "'static'", "in", "kw", "or", "'static'", "in", "params", ":", "Logs", ".", "warn", "(", "'boost: static parameter is deprecated, use stlib instead.'", ")", "self", ".", "start_msg", "(", "'Checking boost libs'", ")", "path", ",", "libs", ",", "stlibs", "=", "self", ".", "boost_get_libs", "(", "*", "*", "params", ")", "self", ".", "env", "[", "'LIBPATH_%s'", "%", "var", "]", "=", "[", "path", "]", "self", ".", "env", "[", "'STLIBPATH_%s'", "%", "var", "]", "=", "[", "path", "]", "self", ".", "env", "[", "'LIB_%s'", "%", "var", "]", "=", "libs", "self", ".", "env", "[", "'STLIB_%s'", "%", "var", "]", "=", "stlibs", "self", ".", "end_msg", "(", "'ok'", "+", "' '", "+", "path", ")", "if", "Logs", ".", "verbose", ":", "Logs", ".", "pprint", "(", "'CYAN'", ",", "'\tpath : %s'", "%", "path", ")", "Logs", ".", "pprint", "(", "'CYAN'", ",", "'\tshared libs : %s'", "%", "libs", ")", "Logs", ".", "pprint", "(", "'CYAN'", ",", "'\tstatic libs : %s'", "%", "stlibs", ")", "def", "try_link", "(", ")", ":", "if", "(", "params", "[", "'lib'", "]", "and", "'system'", "in", "params", "[", "'lib'", "]", ")", "or", "params", "[", "'stlib'", "]", "and", "'system'", "in", "params", "[", "'stlib'", "]", ":", "self", ".", "check_cxx", "(", "fragment", "=", "BOOST_ERROR_CODE", ",", "use", "=", "var", ",", "execute", "=", "False", ")", "if", "(", "params", "[", "'lib'", "]", "and", "'thread'", "in", "params", "[", "'lib'", "]", ")", "or", "params", "[", "'stlib'", "]", "and", "'thread'", "in", "params", "[", "'stlib'", "]", ":", "self", ".", "check_cxx", "(", "fragment", "=", "BOOST_THREAD_CODE", ",", "use", "=", "var", ",", "execute", "=", "False", ")", "if", "params", ".", "get", "(", "'linkage_autodetect'", ",", "False", ")", ":", "self", ".", "start_msg", "(", "\"Attempting to detect boost linkage flags\"", ")", "toolset", "=", "self", ".", "boost_get_toolset", "(", "kw", ".", "get", "(", "'toolset'", ",", "''", ")", ")", "if", "toolset", "in", "(", "'vc'", ",", ")", ":", "# disable auto-linking feature, causing error LNK1181", "# because the code wants to be linked against", "self", ".", "env", "[", "'DEFINES_%s'", "%", "var", "]", "+=", "[", "'BOOST_ALL_NO_LIB'", "]", "# if no dlls are present, we guess the .lib files are not stubs", "has_dlls", "=", "False", "for", "x", "in", "Utils", ".", "listdir", "(", "path", ")", ":", "if", "x", ".", "endswith", "(", "self", ".", "env", ".", "cxxshlib_PATTERN", "%", "''", ")", ":", "has_dlls", "=", "True", "break", "if", "not", "has_dlls", ":", "self", ".", "env", "[", "'STLIBPATH_%s'", "%", "var", "]", "=", "[", "path", "]", "self", ".", "env", "[", "'STLIB_%s'", "%", "var", "]", "=", "libs", "del", "self", ".", "env", "[", "'LIB_%s'", "%", "var", "]", "del", "self", ".", "env", "[", "'LIBPATH_%s'", "%", "var", "]", "# we attempt to play with some known-to-work CXXFLAGS combinations", "for", "cxxflags", "in", "(", "[", "'/MD'", ",", "'/EHsc'", "]", ",", "[", "]", ")", ":", "self", ".", "env", ".", "stash", "(", ")", "self", ".", "env", "[", "\"CXXFLAGS_%s\"", "%", "var", "]", "+=", "cxxflags", "try", ":", "try_link", "(", ")", "self", ".", "end_msg", "(", "\"ok: winning cxxflags combination: %s\"", "%", "(", "self", ".", "env", "[", "\"CXXFLAGS_%s\"", "%", "var", "]", ")", ")", "exc", "=", "None", "break", "except", "Errors", ".", "ConfigurationError", "as", "e", ":", "self", ".", "env", ".", "revert", "(", ")", "exc", "=", "e", "if", "exc", "is", "not", "None", ":", "self", ".", "end_msg", "(", "\"Could not auto-detect boost linking flags combination, you may report it to boost.py author\"", ",", "ex", "=", "exc", ")", "self", ".", "fatal", "(", "'The configuration failed'", ")", "else", ":", "self", ".", "end_msg", "(", "\"Boost linkage flags auto-detection not implemented (needed ?) for this toolchain\"", ")", "self", ".", "fatal", "(", "'The configuration failed'", ")", "else", ":", "self", ".", "start_msg", "(", "'Checking for boost linkage'", ")", "try", ":", "try_link", "(", ")", "except", "Errors", ".", "ConfigurationError", "as", "e", ":", "self", ".", "end_msg", "(", "\"Could not link against boost libraries using supplied options\"", ")", "self", ".", "fatal", "(", "'The configuration failed'", ")", "self", ".", "end_msg", "(", "'ok'", ")" ]
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/waf-tools/boost.py#L296-L397
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/rexec.py
python
RExec.r_exec
(self, code)
Execute code within a restricted environment. The code parameter must either be a string containing one or more lines of Python code, or a compiled code object, which will be executed in the restricted environment's __main__ module.
Execute code within a restricted environment.
[ "Execute", "code", "within", "a", "restricted", "environment", "." ]
def r_exec(self, code): """Execute code within a restricted environment. The code parameter must either be a string containing one or more lines of Python code, or a compiled code object, which will be executed in the restricted environment's __main__ module. """ m = self.add_module('__main__') exec code in m.__dict__
[ "def", "r_exec", "(", "self", ",", "code", ")", ":", "m", "=", "self", ".", "add_module", "(", "'__main__'", ")", "exec", "code", "in", "m", ".", "__dict__" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/rexec.py#L307-L316
CaoWGG/TensorRT-YOLOv4
4d7c2edce99e8794a4cb4ea3540d51ce91158a36
tools/yolo_to_onnx.py
python
GraphBuilderONNX._make_input_tensor
(self, layer_name, layer_dict)
return layer_name, channels
Create an ONNX input tensor from a 'net' layer and store the batch size. Keyword arguments: layer_name -- the layer's name (also the corresponding key in layer_configs) layer_dict -- a layer parameter dictionary (one element of layer_configs)
Create an ONNX input tensor from a 'net' layer and store the batch size.
[ "Create", "an", "ONNX", "input", "tensor", "from", "a", "net", "layer", "and", "store", "the", "batch", "size", "." ]
def _make_input_tensor(self, layer_name, layer_dict): """Create an ONNX input tensor from a 'net' layer and store the batch size. Keyword arguments: layer_name -- the layer's name (also the corresponding key in layer_configs) layer_dict -- a layer parameter dictionary (one element of layer_configs) """ batch_size = layer_dict['batch'] channels = layer_dict['channels'] height = layer_dict['height'] width = layer_dict['width'] self.batch_size = batch_size input_tensor = helper.make_tensor_value_info( str(layer_name), TensorProto.FLOAT, [ batch_size, channels, height, width]) self.input_tensor = input_tensor return layer_name, channels
[ "def", "_make_input_tensor", "(", "self", ",", "layer_name", ",", "layer_dict", ")", ":", "batch_size", "=", "layer_dict", "[", "'batch'", "]", "channels", "=", "layer_dict", "[", "'channels'", "]", "height", "=", "layer_dict", "[", "'height'", "]", "width", "=", "layer_dict", "[", "'width'", "]", "self", ".", "batch_size", "=", "batch_size", "input_tensor", "=", "helper", ".", "make_tensor_value_info", "(", "str", "(", "layer_name", ")", ",", "TensorProto", ".", "FLOAT", ",", "[", "batch_size", ",", "channels", ",", "height", ",", "width", "]", ")", "self", ".", "input_tensor", "=", "input_tensor", "return", "layer_name", ",", "channels" ]
https://github.com/CaoWGG/TensorRT-YOLOv4/blob/4d7c2edce99e8794a4cb4ea3540d51ce91158a36/tools/yolo_to_onnx.py#L408-L424
MADEAPPS/newton-dynamics
4c4016f65d6b59acfaff915f74dc142d4f2b9a90
newton-4.00/applications/toolsAndWrapers/blender/fbxLoader/ndImportFbx.py
python
load
(context, filepath, *, global_clamp_size=0.0, use_smooth_groups=True, use_edges=True, use_split_objects=True, use_split_groups=False, use_image_search=True, use_groups_as_vgroups=False, relpath=None, global_matrix=None )
return {'FINISHED'}
Called by the user interface or another script. load_obj(path) - should give acceptable results. This function passes the file and sends the data off to be split into objects and then converted into mesh objects
Called by the user interface or another script. load_obj(path) - should give acceptable results. This function passes the file and sends the data off to be split into objects and then converted into mesh objects
[ "Called", "by", "the", "user", "interface", "or", "another", "script", ".", "load_obj", "(", "path", ")", "-", "should", "give", "acceptable", "results", ".", "This", "function", "passes", "the", "file", "and", "sends", "the", "data", "off", "to", "be", "split", "into", "objects", "and", "then", "converted", "into", "mesh", "objects" ]
def load(context, filepath, *, global_clamp_size=0.0, use_smooth_groups=True, use_edges=True, use_split_objects=True, use_split_groups=False, use_image_search=True, use_groups_as_vgroups=False, relpath=None, global_matrix=None ): """ Called by the user interface or another script. load_obj(path) - should give acceptable results. This function passes the file and sends the data off to be split into objects and then converted into mesh objects """ def unique_name(existing_names, name_orig): i = 0 if name_orig is None: name_orig = b"ObjObject" name = name_orig while name in existing_names: name = b"%s.%03d" % (name_orig, i) i += 1 existing_names.add(name) return name def handle_vec(line_start, context_multi_line, line_split, tag, data, vec, vec_len): ret_context_multi_line = tag if strip_slash(line_split) else b'' if line_start == tag: vec[:] = [float_func(v) for v in line_split[1:]] elif context_multi_line == tag: vec += [float_func(v) for v in line_split] if not ret_context_multi_line: data.append(tuple(vec[:vec_len])) return ret_context_multi_line def create_face(context_material, context_smooth_group, context_object_key): face_vert_loc_indices = [] face_vert_nor_indices = [] face_vert_tex_indices = [] return ( face_vert_loc_indices, face_vert_nor_indices, face_vert_tex_indices, context_material, context_smooth_group, context_object_key, [], # If non-empty, that face is a Blender-invalid ngon (holes...), need a mutable object for that... ) with ProgressReport(context.window_manager) as progress: progress.enter_substeps(1, "Importing OBJ %r..." % filepath) if global_matrix is None: global_matrix = mathutils.Matrix() if use_split_objects or use_split_groups: use_groups_as_vgroups = False verts_loc = [] verts_nor = [] verts_tex = [] faces = [] # tuples of the faces material_libs = set() # filenames to material libs this OBJ uses vertex_groups = {} # when use_groups_as_vgroups is true # Get the string to float conversion func for this file- is 'float' for almost all files. float_func = get_float_func(filepath) # Context variables context_material = None context_smooth_group = None context_object_key = None context_object_obpart = None context_vgroup = None objects_names = set() # Nurbs context_nurbs = {} nurbs = [] context_parm = b'' # used by nurbs too but could be used elsewhere # Until we can use sets use_default_material = False unique_materials = {} unique_smooth_groups = {} # unique_obects= {} - no use for this variable since the objects are stored in the face. # when there are faces that end with \ # it means they are multiline- # since we use xreadline we cant skip to the next line # so we need to know whether context_multi_line = b'' # Per-face handling data. face_vert_loc_indices = None face_vert_nor_indices = None face_vert_tex_indices = None verts_loc_len = verts_nor_len = verts_tex_len = 0 face_items_usage = set() face_invalid_blenpoly = None prev_vidx = None face = None vec = [] quick_vert_failures = 0 skip_quick_vert = False progress.enter_substeps(3, "Parsing OBJ file...") with open(filepath, 'rb') as f: for line in f: line_split = line.split() if not line_split: continue line_start = line_split[0] # we compare with this a _lot_ if len(line_split) == 1 and not context_multi_line and line_start != b'end': print("WARNING, skipping malformatted line: %s" % line.decode('UTF-8', 'replace').rstrip()) continue # Handling vertex data are pretty similar, factorize that. # Also, most OBJ files store all those on a single line, so try fast parsing for that first, # and only fallback to full multi-line parsing when needed, this gives significant speed-up # (~40% on affected code). if line_start == b'v': vdata, vdata_len, do_quick_vert = verts_loc, 3, not skip_quick_vert elif line_start == b'vn': vdata, vdata_len, do_quick_vert = verts_nor, 3, not skip_quick_vert elif line_start == b'vt': vdata, vdata_len, do_quick_vert = verts_tex, 2, not skip_quick_vert elif context_multi_line == b'v': vdata, vdata_len, do_quick_vert = verts_loc, 3, False elif context_multi_line == b'vn': vdata, vdata_len, do_quick_vert = verts_nor, 3, False elif context_multi_line == b'vt': vdata, vdata_len, do_quick_vert = verts_tex, 2, False else: vdata_len = 0 if vdata_len: if do_quick_vert: try: vdata.append(list(map(float_func, line_split[1:vdata_len + 1]))) except: do_quick_vert = False # In case we get too many failures on quick parsing, force fallback to full multi-line one. # Exception handling can become costly... quick_vert_failures += 1 if quick_vert_failures > 10000: skip_quick_vert = True if not do_quick_vert: context_multi_line = handle_vec(line_start, context_multi_line, line_split, context_multi_line or line_start, vdata, vec, vdata_len) elif line_start == b'f' or context_multi_line == b'f': if not context_multi_line: line_split = line_split[1:] # Instantiate a face face = create_face(context_material, context_smooth_group, context_object_key) (face_vert_loc_indices, face_vert_nor_indices, face_vert_tex_indices, _1, _2, _3, face_invalid_blenpoly) = face faces.append(face) face_items_usage.clear() verts_loc_len = len(verts_loc) verts_nor_len = len(verts_nor) verts_tex_len = len(verts_tex) if context_material is None: use_default_material = True # Else, use face_vert_loc_indices and face_vert_tex_indices previously defined and used the obj_face context_multi_line = b'f' if strip_slash(line_split) else b'' for v in line_split: obj_vert = v.split(b'/') idx = int(obj_vert[0]) # Note that we assume here we cannot get OBJ invalid 0 index... vert_loc_index = (idx + verts_loc_len) if (idx < 1) else idx - 1 # Add the vertex to the current group # *warning*, this wont work for files that have groups defined around verts if use_groups_as_vgroups and context_vgroup: vertex_groups[context_vgroup].append(vert_loc_index) # This a first round to quick-detect ngons that *may* use a same edge more than once. # Potential candidate will be re-checked once we have done parsing the whole face. if not face_invalid_blenpoly: # If we use more than once a same vertex, invalid ngon is suspected. if vert_loc_index in face_items_usage: face_invalid_blenpoly.append(True) else: face_items_usage.add(vert_loc_index) face_vert_loc_indices.append(vert_loc_index) # formatting for faces with normals and textures is # loc_index/tex_index/nor_index if len(obj_vert) > 1 and obj_vert[1] and obj_vert[1] != b'0': idx = int(obj_vert[1]) face_vert_tex_indices.append((idx + verts_tex_len) if (idx < 1) else idx - 1) else: face_vert_tex_indices.append(0) if len(obj_vert) > 2 and obj_vert[2] and obj_vert[2] != b'0': idx = int(obj_vert[2]) face_vert_nor_indices.append((idx + verts_nor_len) if (idx < 1) else idx - 1) else: face_vert_nor_indices.append(0) if not context_multi_line: # Means we have finished a face, we have to do final check if ngon is suspected to be blender-invalid... if face_invalid_blenpoly: face_invalid_blenpoly.clear() face_items_usage.clear() prev_vidx = face_vert_loc_indices[-1] for vidx in face_vert_loc_indices: edge_key = (prev_vidx, vidx) if (prev_vidx < vidx) else (vidx, prev_vidx) if edge_key in face_items_usage: face_invalid_blenpoly.append(True) break face_items_usage.add(edge_key) prev_vidx = vidx elif use_edges and (line_start == b'l' or context_multi_line == b'l'): # very similar to the face load function above with some parts removed if not context_multi_line: line_split = line_split[1:] # Instantiate a face face = create_face(context_material, context_smooth_group, context_object_key) face_vert_loc_indices = face[0] # XXX A bit hackish, we use special 'value' of face_vert_nor_indices (a single True item) to tag this # as a polyline, and not a regular face... face[1][:] = [True] faces.append(face) if context_material is None: use_default_material = True # Else, use face_vert_loc_indices previously defined and used the obj_face context_multi_line = b'l' if strip_slash(line_split) else b'' for v in line_split: obj_vert = v.split(b'/') idx = int(obj_vert[0]) - 1 face_vert_loc_indices.append((idx + len(verts_loc) + 1) if (idx < 0) else idx) elif line_start == b's': if use_smooth_groups: context_smooth_group = line_value(line_split) if context_smooth_group == b'off': context_smooth_group = None elif context_smooth_group: # is not None unique_smooth_groups[context_smooth_group] = None elif line_start == b'o': if use_split_objects: context_object_key = unique_name(objects_names, line_value(line_split)) context_object_obpart = context_object_key # unique_objects[context_object_key]= None elif line_start == b'g': if use_split_groups: grppart = line_value(line_split) context_object_key = (context_object_obpart, grppart) if context_object_obpart else grppart # print 'context_object_key', context_object_key # unique_objects[context_object_key]= None elif use_groups_as_vgroups: context_vgroup = line_value(line.split()) if context_vgroup and context_vgroup != b'(null)': vertex_groups.setdefault(context_vgroup, []) else: context_vgroup = None # dont assign a vgroup elif line_start == b'usemtl': context_material = line_value(line.split()) unique_materials[context_material] = None elif line_start == b'mtllib': # usemap or usemat # can have multiple mtllib filenames per line, mtllib can appear more than once, # so make sure only occurrence of material exists material_libs |= {os.fsdecode(f) for f in filenames_group_by_ext(line.lstrip()[7:].strip(), b'.mtl') } # Nurbs support elif line_start == b'cstype': context_nurbs[b'cstype'] = line_value(line.split()) # 'rat bspline' / 'bspline' elif line_start == b'curv' or context_multi_line == b'curv': curv_idx = context_nurbs[b'curv_idx'] = context_nurbs.get(b'curv_idx', []) # in case were multiline if not context_multi_line: context_nurbs[b'curv_range'] = float_func(line_split[1]), float_func(line_split[2]) line_split[0:3] = [] # remove first 3 items if strip_slash(line_split): context_multi_line = b'curv' else: context_multi_line = b'' for i in line_split: vert_loc_index = int(i) - 1 if vert_loc_index < 0: vert_loc_index = len(verts_loc) + vert_loc_index + 1 curv_idx.append(vert_loc_index) elif line_start == b'parm' or context_multi_line == b'parm': if context_multi_line: context_multi_line = b'' else: context_parm = line_split[1] line_split[0:2] = [] # remove first 2 if strip_slash(line_split): context_multi_line = b'parm' else: context_multi_line = b'' if context_parm.lower() == b'u': context_nurbs.setdefault(b'parm_u', []).extend([float_func(f) for f in line_split]) elif context_parm.lower() == b'v': # surfaces not supported yet context_nurbs.setdefault(b'parm_v', []).extend([float_func(f) for f in line_split]) # else: # may want to support other parm's ? elif line_start == b'deg': context_nurbs[b'deg'] = [int(i) for i in line.split()[1:]] elif line_start == b'end': # Add the nurbs curve if context_object_key: context_nurbs[b'name'] = context_object_key nurbs.append(context_nurbs) context_nurbs = {} context_parm = b'' ''' # How to use usemap? deprecated? elif line_start == b'usema': # usemap or usemat context_image= line_value(line_split) ''' progress.step("Done, loading materials and images...") if use_default_material: unique_materials[None] = None create_materials(filepath, relpath, material_libs, unique_materials, use_image_search, float_func) progress.step("Done, building geometries (verts:%i faces:%i materials: %i smoothgroups:%i) ..." % (len(verts_loc), len(faces), len(unique_materials), len(unique_smooth_groups))) # deselect all if bpy.ops.object.select_all.poll(): bpy.ops.object.select_all(action='DESELECT') new_objects = [] # put new objects here # Split the mesh by objects/materials, may SPLIT_OB_OR_GROUP = bool(use_split_objects or use_split_groups) for data in split_mesh(verts_loc, faces, unique_materials, filepath, SPLIT_OB_OR_GROUP): verts_loc_split, faces_split, unique_materials_split, dataname, use_vnor, use_vtex = data # Create meshes from the data, warning 'vertex_groups' wont support splitting #~ print(dataname, use_vnor, use_vtex) create_mesh(new_objects, use_edges, verts_loc_split, verts_nor if use_vnor else [], verts_tex if use_vtex else [], faces_split, unique_materials_split, unique_smooth_groups, vertex_groups, dataname, ) # nurbs support for context_nurbs in nurbs: create_nurbs(context_nurbs, verts_loc, new_objects) view_layer = context.view_layer collection = view_layer.active_layer_collection.collection # Create new obj for obj in new_objects: collection.objects.link(obj) obj.select_set(True) # we could apply this anywhere before scaling. obj.matrix_world = global_matrix view_layer.update() axis_min = [1000000000] * 3 axis_max = [-1000000000] * 3 if global_clamp_size: # Get all object bounds for ob in new_objects: for v in ob.bound_box: for axis, value in enumerate(v): if axis_min[axis] > value: axis_min[axis] = value if axis_max[axis] < value: axis_max[axis] = value # Scale objects max_axis = max(axis_max[0] - axis_min[0], axis_max[1] - axis_min[1], axis_max[2] - axis_min[2]) scale = 1.0 while global_clamp_size < max_axis * scale: scale = scale / 10.0 for obj in new_objects: obj.scale = scale, scale, scale progress.leave_substeps("Done.") progress.leave_substeps("Finished importing: %r" % filepath) return {'FINISHED'}
[ "def", "load", "(", "context", ",", "filepath", ",", "*", ",", "global_clamp_size", "=", "0.0", ",", "use_smooth_groups", "=", "True", ",", "use_edges", "=", "True", ",", "use_split_objects", "=", "True", ",", "use_split_groups", "=", "False", ",", "use_image_search", "=", "True", ",", "use_groups_as_vgroups", "=", "False", ",", "relpath", "=", "None", ",", "global_matrix", "=", "None", ")", ":", "def", "unique_name", "(", "existing_names", ",", "name_orig", ")", ":", "i", "=", "0", "if", "name_orig", "is", "None", ":", "name_orig", "=", "b\"ObjObject\"", "name", "=", "name_orig", "while", "name", "in", "existing_names", ":", "name", "=", "b\"%s.%03d\"", "%", "(", "name_orig", ",", "i", ")", "i", "+=", "1", "existing_names", ".", "add", "(", "name", ")", "return", "name", "def", "handle_vec", "(", "line_start", ",", "context_multi_line", ",", "line_split", ",", "tag", ",", "data", ",", "vec", ",", "vec_len", ")", ":", "ret_context_multi_line", "=", "tag", "if", "strip_slash", "(", "line_split", ")", "else", "b''", "if", "line_start", "==", "tag", ":", "vec", "[", ":", "]", "=", "[", "float_func", "(", "v", ")", "for", "v", "in", "line_split", "[", "1", ":", "]", "]", "elif", "context_multi_line", "==", "tag", ":", "vec", "+=", "[", "float_func", "(", "v", ")", "for", "v", "in", "line_split", "]", "if", "not", "ret_context_multi_line", ":", "data", ".", "append", "(", "tuple", "(", "vec", "[", ":", "vec_len", "]", ")", ")", "return", "ret_context_multi_line", "def", "create_face", "(", "context_material", ",", "context_smooth_group", ",", "context_object_key", ")", ":", "face_vert_loc_indices", "=", "[", "]", "face_vert_nor_indices", "=", "[", "]", "face_vert_tex_indices", "=", "[", "]", "return", "(", "face_vert_loc_indices", ",", "face_vert_nor_indices", ",", "face_vert_tex_indices", ",", "context_material", ",", "context_smooth_group", ",", "context_object_key", ",", "[", "]", ",", "# If non-empty, that face is a Blender-invalid ngon (holes...), need a mutable object for that...", ")", "with", "ProgressReport", "(", "context", ".", "window_manager", ")", "as", "progress", ":", "progress", ".", "enter_substeps", "(", "1", ",", "\"Importing OBJ %r...\"", "%", "filepath", ")", "if", "global_matrix", "is", "None", ":", "global_matrix", "=", "mathutils", ".", "Matrix", "(", ")", "if", "use_split_objects", "or", "use_split_groups", ":", "use_groups_as_vgroups", "=", "False", "verts_loc", "=", "[", "]", "verts_nor", "=", "[", "]", "verts_tex", "=", "[", "]", "faces", "=", "[", "]", "# tuples of the faces", "material_libs", "=", "set", "(", ")", "# filenames to material libs this OBJ uses", "vertex_groups", "=", "{", "}", "# when use_groups_as_vgroups is true", "# Get the string to float conversion func for this file- is 'float' for almost all files.", "float_func", "=", "get_float_func", "(", "filepath", ")", "# Context variables", "context_material", "=", "None", "context_smooth_group", "=", "None", "context_object_key", "=", "None", "context_object_obpart", "=", "None", "context_vgroup", "=", "None", "objects_names", "=", "set", "(", ")", "# Nurbs", "context_nurbs", "=", "{", "}", "nurbs", "=", "[", "]", "context_parm", "=", "b''", "# used by nurbs too but could be used elsewhere", "# Until we can use sets", "use_default_material", "=", "False", "unique_materials", "=", "{", "}", "unique_smooth_groups", "=", "{", "}", "# unique_obects= {} - no use for this variable since the objects are stored in the face.", "# when there are faces that end with \\", "# it means they are multiline-", "# since we use xreadline we cant skip to the next line", "# so we need to know whether", "context_multi_line", "=", "b''", "# Per-face handling data.", "face_vert_loc_indices", "=", "None", "face_vert_nor_indices", "=", "None", "face_vert_tex_indices", "=", "None", "verts_loc_len", "=", "verts_nor_len", "=", "verts_tex_len", "=", "0", "face_items_usage", "=", "set", "(", ")", "face_invalid_blenpoly", "=", "None", "prev_vidx", "=", "None", "face", "=", "None", "vec", "=", "[", "]", "quick_vert_failures", "=", "0", "skip_quick_vert", "=", "False", "progress", ".", "enter_substeps", "(", "3", ",", "\"Parsing OBJ file...\"", ")", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line_split", "=", "line", ".", "split", "(", ")", "if", "not", "line_split", ":", "continue", "line_start", "=", "line_split", "[", "0", "]", "# we compare with this a _lot_", "if", "len", "(", "line_split", ")", "==", "1", "and", "not", "context_multi_line", "and", "line_start", "!=", "b'end'", ":", "print", "(", "\"WARNING, skipping malformatted line: %s\"", "%", "line", ".", "decode", "(", "'UTF-8'", ",", "'replace'", ")", ".", "rstrip", "(", ")", ")", "continue", "# Handling vertex data are pretty similar, factorize that.", "# Also, most OBJ files store all those on a single line, so try fast parsing for that first,", "# and only fallback to full multi-line parsing when needed, this gives significant speed-up", "# (~40% on affected code).", "if", "line_start", "==", "b'v'", ":", "vdata", ",", "vdata_len", ",", "do_quick_vert", "=", "verts_loc", ",", "3", ",", "not", "skip_quick_vert", "elif", "line_start", "==", "b'vn'", ":", "vdata", ",", "vdata_len", ",", "do_quick_vert", "=", "verts_nor", ",", "3", ",", "not", "skip_quick_vert", "elif", "line_start", "==", "b'vt'", ":", "vdata", ",", "vdata_len", ",", "do_quick_vert", "=", "verts_tex", ",", "2", ",", "not", "skip_quick_vert", "elif", "context_multi_line", "==", "b'v'", ":", "vdata", ",", "vdata_len", ",", "do_quick_vert", "=", "verts_loc", ",", "3", ",", "False", "elif", "context_multi_line", "==", "b'vn'", ":", "vdata", ",", "vdata_len", ",", "do_quick_vert", "=", "verts_nor", ",", "3", ",", "False", "elif", "context_multi_line", "==", "b'vt'", ":", "vdata", ",", "vdata_len", ",", "do_quick_vert", "=", "verts_tex", ",", "2", ",", "False", "else", ":", "vdata_len", "=", "0", "if", "vdata_len", ":", "if", "do_quick_vert", ":", "try", ":", "vdata", ".", "append", "(", "list", "(", "map", "(", "float_func", ",", "line_split", "[", "1", ":", "vdata_len", "+", "1", "]", ")", ")", ")", "except", ":", "do_quick_vert", "=", "False", "# In case we get too many failures on quick parsing, force fallback to full multi-line one.", "# Exception handling can become costly...", "quick_vert_failures", "+=", "1", "if", "quick_vert_failures", ">", "10000", ":", "skip_quick_vert", "=", "True", "if", "not", "do_quick_vert", ":", "context_multi_line", "=", "handle_vec", "(", "line_start", ",", "context_multi_line", ",", "line_split", ",", "context_multi_line", "or", "line_start", ",", "vdata", ",", "vec", ",", "vdata_len", ")", "elif", "line_start", "==", "b'f'", "or", "context_multi_line", "==", "b'f'", ":", "if", "not", "context_multi_line", ":", "line_split", "=", "line_split", "[", "1", ":", "]", "# Instantiate a face", "face", "=", "create_face", "(", "context_material", ",", "context_smooth_group", ",", "context_object_key", ")", "(", "face_vert_loc_indices", ",", "face_vert_nor_indices", ",", "face_vert_tex_indices", ",", "_1", ",", "_2", ",", "_3", ",", "face_invalid_blenpoly", ")", "=", "face", "faces", ".", "append", "(", "face", ")", "face_items_usage", ".", "clear", "(", ")", "verts_loc_len", "=", "len", "(", "verts_loc", ")", "verts_nor_len", "=", "len", "(", "verts_nor", ")", "verts_tex_len", "=", "len", "(", "verts_tex", ")", "if", "context_material", "is", "None", ":", "use_default_material", "=", "True", "# Else, use face_vert_loc_indices and face_vert_tex_indices previously defined and used the obj_face", "context_multi_line", "=", "b'f'", "if", "strip_slash", "(", "line_split", ")", "else", "b''", "for", "v", "in", "line_split", ":", "obj_vert", "=", "v", ".", "split", "(", "b'/'", ")", "idx", "=", "int", "(", "obj_vert", "[", "0", "]", ")", "# Note that we assume here we cannot get OBJ invalid 0 index...", "vert_loc_index", "=", "(", "idx", "+", "verts_loc_len", ")", "if", "(", "idx", "<", "1", ")", "else", "idx", "-", "1", "# Add the vertex to the current group", "# *warning*, this wont work for files that have groups defined around verts", "if", "use_groups_as_vgroups", "and", "context_vgroup", ":", "vertex_groups", "[", "context_vgroup", "]", ".", "append", "(", "vert_loc_index", ")", "# This a first round to quick-detect ngons that *may* use a same edge more than once.", "# Potential candidate will be re-checked once we have done parsing the whole face.", "if", "not", "face_invalid_blenpoly", ":", "# If we use more than once a same vertex, invalid ngon is suspected.", "if", "vert_loc_index", "in", "face_items_usage", ":", "face_invalid_blenpoly", ".", "append", "(", "True", ")", "else", ":", "face_items_usage", ".", "add", "(", "vert_loc_index", ")", "face_vert_loc_indices", ".", "append", "(", "vert_loc_index", ")", "# formatting for faces with normals and textures is", "# loc_index/tex_index/nor_index", "if", "len", "(", "obj_vert", ")", ">", "1", "and", "obj_vert", "[", "1", "]", "and", "obj_vert", "[", "1", "]", "!=", "b'0'", ":", "idx", "=", "int", "(", "obj_vert", "[", "1", "]", ")", "face_vert_tex_indices", ".", "append", "(", "(", "idx", "+", "verts_tex_len", ")", "if", "(", "idx", "<", "1", ")", "else", "idx", "-", "1", ")", "else", ":", "face_vert_tex_indices", ".", "append", "(", "0", ")", "if", "len", "(", "obj_vert", ")", ">", "2", "and", "obj_vert", "[", "2", "]", "and", "obj_vert", "[", "2", "]", "!=", "b'0'", ":", "idx", "=", "int", "(", "obj_vert", "[", "2", "]", ")", "face_vert_nor_indices", ".", "append", "(", "(", "idx", "+", "verts_nor_len", ")", "if", "(", "idx", "<", "1", ")", "else", "idx", "-", "1", ")", "else", ":", "face_vert_nor_indices", ".", "append", "(", "0", ")", "if", "not", "context_multi_line", ":", "# Means we have finished a face, we have to do final check if ngon is suspected to be blender-invalid...", "if", "face_invalid_blenpoly", ":", "face_invalid_blenpoly", ".", "clear", "(", ")", "face_items_usage", ".", "clear", "(", ")", "prev_vidx", "=", "face_vert_loc_indices", "[", "-", "1", "]", "for", "vidx", "in", "face_vert_loc_indices", ":", "edge_key", "=", "(", "prev_vidx", ",", "vidx", ")", "if", "(", "prev_vidx", "<", "vidx", ")", "else", "(", "vidx", ",", "prev_vidx", ")", "if", "edge_key", "in", "face_items_usage", ":", "face_invalid_blenpoly", ".", "append", "(", "True", ")", "break", "face_items_usage", ".", "add", "(", "edge_key", ")", "prev_vidx", "=", "vidx", "elif", "use_edges", "and", "(", "line_start", "==", "b'l'", "or", "context_multi_line", "==", "b'l'", ")", ":", "# very similar to the face load function above with some parts removed", "if", "not", "context_multi_line", ":", "line_split", "=", "line_split", "[", "1", ":", "]", "# Instantiate a face", "face", "=", "create_face", "(", "context_material", ",", "context_smooth_group", ",", "context_object_key", ")", "face_vert_loc_indices", "=", "face", "[", "0", "]", "# XXX A bit hackish, we use special 'value' of face_vert_nor_indices (a single True item) to tag this", "# as a polyline, and not a regular face...", "face", "[", "1", "]", "[", ":", "]", "=", "[", "True", "]", "faces", ".", "append", "(", "face", ")", "if", "context_material", "is", "None", ":", "use_default_material", "=", "True", "# Else, use face_vert_loc_indices previously defined and used the obj_face", "context_multi_line", "=", "b'l'", "if", "strip_slash", "(", "line_split", ")", "else", "b''", "for", "v", "in", "line_split", ":", "obj_vert", "=", "v", ".", "split", "(", "b'/'", ")", "idx", "=", "int", "(", "obj_vert", "[", "0", "]", ")", "-", "1", "face_vert_loc_indices", ".", "append", "(", "(", "idx", "+", "len", "(", "verts_loc", ")", "+", "1", ")", "if", "(", "idx", "<", "0", ")", "else", "idx", ")", "elif", "line_start", "==", "b's'", ":", "if", "use_smooth_groups", ":", "context_smooth_group", "=", "line_value", "(", "line_split", ")", "if", "context_smooth_group", "==", "b'off'", ":", "context_smooth_group", "=", "None", "elif", "context_smooth_group", ":", "# is not None", "unique_smooth_groups", "[", "context_smooth_group", "]", "=", "None", "elif", "line_start", "==", "b'o'", ":", "if", "use_split_objects", ":", "context_object_key", "=", "unique_name", "(", "objects_names", ",", "line_value", "(", "line_split", ")", ")", "context_object_obpart", "=", "context_object_key", "# unique_objects[context_object_key]= None", "elif", "line_start", "==", "b'g'", ":", "if", "use_split_groups", ":", "grppart", "=", "line_value", "(", "line_split", ")", "context_object_key", "=", "(", "context_object_obpart", ",", "grppart", ")", "if", "context_object_obpart", "else", "grppart", "# print 'context_object_key', context_object_key", "# unique_objects[context_object_key]= None", "elif", "use_groups_as_vgroups", ":", "context_vgroup", "=", "line_value", "(", "line", ".", "split", "(", ")", ")", "if", "context_vgroup", "and", "context_vgroup", "!=", "b'(null)'", ":", "vertex_groups", ".", "setdefault", "(", "context_vgroup", ",", "[", "]", ")", "else", ":", "context_vgroup", "=", "None", "# dont assign a vgroup", "elif", "line_start", "==", "b'usemtl'", ":", "context_material", "=", "line_value", "(", "line", ".", "split", "(", ")", ")", "unique_materials", "[", "context_material", "]", "=", "None", "elif", "line_start", "==", "b'mtllib'", ":", "# usemap or usemat", "# can have multiple mtllib filenames per line, mtllib can appear more than once,", "# so make sure only occurrence of material exists", "material_libs", "|=", "{", "os", ".", "fsdecode", "(", "f", ")", "for", "f", "in", "filenames_group_by_ext", "(", "line", ".", "lstrip", "(", ")", "[", "7", ":", "]", ".", "strip", "(", ")", ",", "b'.mtl'", ")", "}", "# Nurbs support", "elif", "line_start", "==", "b'cstype'", ":", "context_nurbs", "[", "b'cstype'", "]", "=", "line_value", "(", "line", ".", "split", "(", ")", ")", "# 'rat bspline' / 'bspline'", "elif", "line_start", "==", "b'curv'", "or", "context_multi_line", "==", "b'curv'", ":", "curv_idx", "=", "context_nurbs", "[", "b'curv_idx'", "]", "=", "context_nurbs", ".", "get", "(", "b'curv_idx'", ",", "[", "]", ")", "# in case were multiline", "if", "not", "context_multi_line", ":", "context_nurbs", "[", "b'curv_range'", "]", "=", "float_func", "(", "line_split", "[", "1", "]", ")", ",", "float_func", "(", "line_split", "[", "2", "]", ")", "line_split", "[", "0", ":", "3", "]", "=", "[", "]", "# remove first 3 items", "if", "strip_slash", "(", "line_split", ")", ":", "context_multi_line", "=", "b'curv'", "else", ":", "context_multi_line", "=", "b''", "for", "i", "in", "line_split", ":", "vert_loc_index", "=", "int", "(", "i", ")", "-", "1", "if", "vert_loc_index", "<", "0", ":", "vert_loc_index", "=", "len", "(", "verts_loc", ")", "+", "vert_loc_index", "+", "1", "curv_idx", ".", "append", "(", "vert_loc_index", ")", "elif", "line_start", "==", "b'parm'", "or", "context_multi_line", "==", "b'parm'", ":", "if", "context_multi_line", ":", "context_multi_line", "=", "b''", "else", ":", "context_parm", "=", "line_split", "[", "1", "]", "line_split", "[", "0", ":", "2", "]", "=", "[", "]", "# remove first 2", "if", "strip_slash", "(", "line_split", ")", ":", "context_multi_line", "=", "b'parm'", "else", ":", "context_multi_line", "=", "b''", "if", "context_parm", ".", "lower", "(", ")", "==", "b'u'", ":", "context_nurbs", ".", "setdefault", "(", "b'parm_u'", ",", "[", "]", ")", ".", "extend", "(", "[", "float_func", "(", "f", ")", "for", "f", "in", "line_split", "]", ")", "elif", "context_parm", ".", "lower", "(", ")", "==", "b'v'", ":", "# surfaces not supported yet", "context_nurbs", ".", "setdefault", "(", "b'parm_v'", ",", "[", "]", ")", ".", "extend", "(", "[", "float_func", "(", "f", ")", "for", "f", "in", "line_split", "]", ")", "# else: # may want to support other parm's ?", "elif", "line_start", "==", "b'deg'", ":", "context_nurbs", "[", "b'deg'", "]", "=", "[", "int", "(", "i", ")", "for", "i", "in", "line", ".", "split", "(", ")", "[", "1", ":", "]", "]", "elif", "line_start", "==", "b'end'", ":", "# Add the nurbs curve", "if", "context_object_key", ":", "context_nurbs", "[", "b'name'", "]", "=", "context_object_key", "nurbs", ".", "append", "(", "context_nurbs", ")", "context_nurbs", "=", "{", "}", "context_parm", "=", "b''", "''' # How to use usemap? deprecated?\n elif line_start == b'usema': # usemap or usemat\n context_image= line_value(line_split)\n '''", "progress", ".", "step", "(", "\"Done, loading materials and images...\"", ")", "if", "use_default_material", ":", "unique_materials", "[", "None", "]", "=", "None", "create_materials", "(", "filepath", ",", "relpath", ",", "material_libs", ",", "unique_materials", ",", "use_image_search", ",", "float_func", ")", "progress", ".", "step", "(", "\"Done, building geometries (verts:%i faces:%i materials: %i smoothgroups:%i) ...\"", "%", "(", "len", "(", "verts_loc", ")", ",", "len", "(", "faces", ")", ",", "len", "(", "unique_materials", ")", ",", "len", "(", "unique_smooth_groups", ")", ")", ")", "# deselect all", "if", "bpy", ".", "ops", ".", "object", ".", "select_all", ".", "poll", "(", ")", ":", "bpy", ".", "ops", ".", "object", ".", "select_all", "(", "action", "=", "'DESELECT'", ")", "new_objects", "=", "[", "]", "# put new objects here", "# Split the mesh by objects/materials, may", "SPLIT_OB_OR_GROUP", "=", "bool", "(", "use_split_objects", "or", "use_split_groups", ")", "for", "data", "in", "split_mesh", "(", "verts_loc", ",", "faces", ",", "unique_materials", ",", "filepath", ",", "SPLIT_OB_OR_GROUP", ")", ":", "verts_loc_split", ",", "faces_split", ",", "unique_materials_split", ",", "dataname", ",", "use_vnor", ",", "use_vtex", "=", "data", "# Create meshes from the data, warning 'vertex_groups' wont support splitting", "#~ print(dataname, use_vnor, use_vtex)", "create_mesh", "(", "new_objects", ",", "use_edges", ",", "verts_loc_split", ",", "verts_nor", "if", "use_vnor", "else", "[", "]", ",", "verts_tex", "if", "use_vtex", "else", "[", "]", ",", "faces_split", ",", "unique_materials_split", ",", "unique_smooth_groups", ",", "vertex_groups", ",", "dataname", ",", ")", "# nurbs support", "for", "context_nurbs", "in", "nurbs", ":", "create_nurbs", "(", "context_nurbs", ",", "verts_loc", ",", "new_objects", ")", "view_layer", "=", "context", ".", "view_layer", "collection", "=", "view_layer", ".", "active_layer_collection", ".", "collection", "# Create new obj", "for", "obj", "in", "new_objects", ":", "collection", ".", "objects", ".", "link", "(", "obj", ")", "obj", ".", "select_set", "(", "True", ")", "# we could apply this anywhere before scaling.", "obj", ".", "matrix_world", "=", "global_matrix", "view_layer", ".", "update", "(", ")", "axis_min", "=", "[", "1000000000", "]", "*", "3", "axis_max", "=", "[", "-", "1000000000", "]", "*", "3", "if", "global_clamp_size", ":", "# Get all object bounds", "for", "ob", "in", "new_objects", ":", "for", "v", "in", "ob", ".", "bound_box", ":", "for", "axis", ",", "value", "in", "enumerate", "(", "v", ")", ":", "if", "axis_min", "[", "axis", "]", ">", "value", ":", "axis_min", "[", "axis", "]", "=", "value", "if", "axis_max", "[", "axis", "]", "<", "value", ":", "axis_max", "[", "axis", "]", "=", "value", "# Scale objects", "max_axis", "=", "max", "(", "axis_max", "[", "0", "]", "-", "axis_min", "[", "0", "]", ",", "axis_max", "[", "1", "]", "-", "axis_min", "[", "1", "]", ",", "axis_max", "[", "2", "]", "-", "axis_min", "[", "2", "]", ")", "scale", "=", "1.0", "while", "global_clamp_size", "<", "max_axis", "*", "scale", ":", "scale", "=", "scale", "/", "10.0", "for", "obj", "in", "new_objects", ":", "obj", ".", "scale", "=", "scale", ",", "scale", ",", "scale", "progress", ".", "leave_substeps", "(", "\"Done.\"", ")", "progress", ".", "leave_substeps", "(", "\"Finished importing: %r\"", "%", "filepath", ")", "return", "{", "'FINISHED'", "}" ]
https://github.com/MADEAPPS/newton-dynamics/blob/4c4016f65d6b59acfaff915f74dc142d4f2b9a90/newton-4.00/applications/toolsAndWrapers/blender/fbxLoader/ndImportFbx.py#L895-L1313
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py
python
MainWindow.do_mask_pt_2d
(self)
Save current in-edit ROI Mask a Pt and re-plot with current selected ROI or others :return:
Save current in-edit ROI Mask a Pt and re-plot with current selected ROI or others :return:
[ "Save", "current", "in", "-", "edit", "ROI", "Mask", "a", "Pt", "and", "re", "-", "plot", "with", "current", "selected", "ROI", "or", "others", ":", "return", ":" ]
def do_mask_pt_2d(self): """ Save current in-edit ROI Mask a Pt and re-plot with current selected ROI or others :return: """ # # get the experiment and scan value # status, par_val_list = gutil.parse_integers_editors([self.ui.lineEdit_exp, self.ui.lineEdit_run]) # if not status: # raise RuntimeError('Experiment number and Scan number must be given!') # exp_number = par_val_list[0] # scan_number = par_val_list[1] # get the user specified name from ... roi_name, ok = QInputDialog.getText(self, 'Input Mask Name', 'Enter mask name:') # return if cancelled if not ok: return roi_name = str(roi_name) # check whether this ROI name is used or not. If it is, warn user if the given ROI is used already current_roi_names = [str(self.ui.comboBox_maskNames1.itemText(i)) for i in range(self.ui.comboBox_maskNames1.count())] if roi_name in current_roi_names: self.pop_one_button_dialog('[Warning] ROI name {} is used before. The previous ROI ' 'will be overwritten by the new defined.'.format(roi_name)) # get current ROI ll_corner, ur_corner = self.ui.graphicsView_detector2dPlot.get_roi() # set ROI self._myControl.set_roi(roi_name, ll_corner, ur_corner) # set it to combo-box self._roiComboBoxMutex = True self.ui.comboBox_maskNames1.addItem(roi_name) self.ui.comboBox_maskNames2.addItem(roi_name) self.ui.comboBox_maskNamesSurvey.addItem(roi_name) self.ui.comboBox_viewRawDataMasks.addItem(roi_name) self.ui.comboBox_viewRawDataMasks.setCurrentIndex(self.ui.comboBox_viewRawDataMasks.count()-1) self._roiComboBoxMutex = False # get experiment, scan status, ret_obj = gutil.parse_integers_editors([self.ui.lineEdit_exp, self.ui.lineEdit_run, self.ui.lineEdit_rawDataPtNo], allow_blank=False) if status: exp, scan, pt = ret_obj else: self.pop_one_button_dialog(ret_obj) return # previously saved ROI if self._myControl.has_roi_generated(roi_name) is False: roi_start, roi_end = self._myControl.get_region_of_interest(roi_name) status, mask_ws_name = self._myControl.generate_mask_workspace(exp, scan, roi_start=roi_start, roi_end=roi_end, mask_tag=roi_name) if status: self._myControl.set_roi_workspace(roi_name, mask_ws_name) # END-IF # plot self.load_plot_raw_data(exp, scan, pt, roi_name=roi_name) # switch ROI edit mode self.do_switch_roi_mode()
[ "def", "do_mask_pt_2d", "(", "self", ")", ":", "# # get the experiment and scan value", "# status, par_val_list = gutil.parse_integers_editors([self.ui.lineEdit_exp, self.ui.lineEdit_run])", "# if not status:", "# raise RuntimeError('Experiment number and Scan number must be given!')", "# exp_number = par_val_list[0]", "# scan_number = par_val_list[1]", "# get the user specified name from ...", "roi_name", ",", "ok", "=", "QInputDialog", ".", "getText", "(", "self", ",", "'Input Mask Name'", ",", "'Enter mask name:'", ")", "# return if cancelled", "if", "not", "ok", ":", "return", "roi_name", "=", "str", "(", "roi_name", ")", "# check whether this ROI name is used or not. If it is, warn user if the given ROI is used already", "current_roi_names", "=", "[", "str", "(", "self", ".", "ui", ".", "comboBox_maskNames1", ".", "itemText", "(", "i", ")", ")", "for", "i", "in", "range", "(", "self", ".", "ui", ".", "comboBox_maskNames1", ".", "count", "(", ")", ")", "]", "if", "roi_name", "in", "current_roi_names", ":", "self", ".", "pop_one_button_dialog", "(", "'[Warning] ROI name {} is used before. The previous ROI '", "'will be overwritten by the new defined.'", ".", "format", "(", "roi_name", ")", ")", "# get current ROI", "ll_corner", ",", "ur_corner", "=", "self", ".", "ui", ".", "graphicsView_detector2dPlot", ".", "get_roi", "(", ")", "# set ROI", "self", ".", "_myControl", ".", "set_roi", "(", "roi_name", ",", "ll_corner", ",", "ur_corner", ")", "# set it to combo-box", "self", ".", "_roiComboBoxMutex", "=", "True", "self", ".", "ui", ".", "comboBox_maskNames1", ".", "addItem", "(", "roi_name", ")", "self", ".", "ui", ".", "comboBox_maskNames2", ".", "addItem", "(", "roi_name", ")", "self", ".", "ui", ".", "comboBox_maskNamesSurvey", ".", "addItem", "(", "roi_name", ")", "self", ".", "ui", ".", "comboBox_viewRawDataMasks", ".", "addItem", "(", "roi_name", ")", "self", ".", "ui", ".", "comboBox_viewRawDataMasks", ".", "setCurrentIndex", "(", "self", ".", "ui", ".", "comboBox_viewRawDataMasks", ".", "count", "(", ")", "-", "1", ")", "self", ".", "_roiComboBoxMutex", "=", "False", "# get experiment, scan", "status", ",", "ret_obj", "=", "gutil", ".", "parse_integers_editors", "(", "[", "self", ".", "ui", ".", "lineEdit_exp", ",", "self", ".", "ui", ".", "lineEdit_run", ",", "self", ".", "ui", ".", "lineEdit_rawDataPtNo", "]", ",", "allow_blank", "=", "False", ")", "if", "status", ":", "exp", ",", "scan", ",", "pt", "=", "ret_obj", "else", ":", "self", ".", "pop_one_button_dialog", "(", "ret_obj", ")", "return", "# previously saved ROI", "if", "self", ".", "_myControl", ".", "has_roi_generated", "(", "roi_name", ")", "is", "False", ":", "roi_start", ",", "roi_end", "=", "self", ".", "_myControl", ".", "get_region_of_interest", "(", "roi_name", ")", "status", ",", "mask_ws_name", "=", "self", ".", "_myControl", ".", "generate_mask_workspace", "(", "exp", ",", "scan", ",", "roi_start", "=", "roi_start", ",", "roi_end", "=", "roi_end", ",", "mask_tag", "=", "roi_name", ")", "if", "status", ":", "self", ".", "_myControl", ".", "set_roi_workspace", "(", "roi_name", ",", "mask_ws_name", ")", "# END-IF", "# plot", "self", ".", "load_plot_raw_data", "(", "exp", ",", "scan", ",", "pt", ",", "roi_name", "=", "roi_name", ")", "# switch ROI edit mode", "self", ".", "do_switch_roi_mode", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py#L1843-L1908
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListItemAttr.GetBackgroundColour
(*args, **kwargs)
return _controls_.ListItemAttr_GetBackgroundColour(*args, **kwargs)
GetBackgroundColour(self) -> Colour
GetBackgroundColour(self) -> Colour
[ "GetBackgroundColour", "(", "self", ")", "-", ">", "Colour" ]
def GetBackgroundColour(*args, **kwargs): """GetBackgroundColour(self) -> Colour""" return _controls_.ListItemAttr_GetBackgroundColour(*args, **kwargs)
[ "def", "GetBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItemAttr_GetBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4118-L4120
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py
python
Metrowerks_Shell_Suite_Events.Remove_Binaries
(self, _no_object=None, _attributes={}, **_arguments)
Remove Binaries: Remove the binary object code from the current project Keyword argument _attributes: AppleEvent attribute dictionary
Remove Binaries: Remove the binary object code from the current project Keyword argument _attributes: AppleEvent attribute dictionary
[ "Remove", "Binaries", ":", "Remove", "the", "binary", "object", "code", "from", "the", "current", "project", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def Remove_Binaries(self, _no_object=None, _attributes={}, **_arguments): """Remove Binaries: Remove the binary object code from the current project Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'MMPR' _subcode = 'RemB' if _arguments: raise TypeError, 'No optional args expected' if _no_object is not None: raise TypeError, 'No direct arg expected' _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", "Remove_Binaries", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'MMPR'", "_subcode", "=", "'RemB'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "if", "_no_object", "is", "not", "None", ":", "raise", "TypeError", ",", "'No direct arg expected'", "_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/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py#L498-L515
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetBundleContentsFolderPath
(self)
Returns the qualified path to the bundle's contents folder. E.g. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.
Returns the qualified path to the bundle's contents folder. E.g. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.
[ "Returns", "the", "qualified", "path", "to", "the", "bundle", "s", "contents", "folder", ".", "E", ".", "g", ".", "Chromium", ".", "app", "/", "Contents", "or", "Foo", ".", "bundle", "/", "Versions", "/", "A", ".", "Only", "valid", "for", "bundles", "." ]
def GetBundleContentsFolderPath(self): """Returns the qualified path to the bundle's contents folder. E.g. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.""" if self.isIOS: return self.GetWrapperName() assert self._IsBundle() if self.spec['type'] == 'shared_library': return os.path.join( self.GetWrapperName(), 'Versions', self.GetFrameworkVersion()) else: # loadable_modules have a 'Contents' folder like executables. return os.path.join(self.GetWrapperName(), 'Contents')
[ "def", "GetBundleContentsFolderPath", "(", "self", ")", ":", "if", "self", ".", "isIOS", ":", "return", "self", ".", "GetWrapperName", "(", ")", "assert", "self", ".", "_IsBundle", "(", ")", "if", "self", ".", "spec", "[", "'type'", "]", "==", "'shared_library'", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetWrapperName", "(", ")", ",", "'Versions'", ",", "self", ".", "GetFrameworkVersion", "(", ")", ")", "else", ":", "# loadable_modules have a 'Contents' folder like executables.", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetWrapperName", "(", ")", ",", "'Contents'", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcode_emulation.py#L294-L305
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_pages.py
python
EdPages.LoadSessionFile
(self, session)
return None
Load files from saved session data in profile @param session: session filename @return: tuple (error desc, error msg), or None if no error
Load files from saved session data in profile @param session: session filename @return: tuple (error desc, error msg), or None if no error
[ "Load", "files", "from", "saved", "session", "data", "in", "profile", "@param", "session", ":", "session", "filename", "@return", ":", "tuple", "(", "error", "desc", "error", "msg", ")", "or", "None", "if", "no", "error" ]
def LoadSessionFile(self, session): """Load files from saved session data in profile @param session: session filename @return: tuple (error desc, error msg), or None if no error """ self._ses_load = True mgr = ed_session.EdSessionMgr() flist = list() try: flist = mgr.LoadSession(session) except Exception, msg: self._ses_load = False errdict = dict(sessionname=session, error=msg) return (_("Session Load Error"), _("Failed to load the session: %(sessionname)s\n\nError: %(error)s") % errdict) if not len(flist): self._ses_load = False return (_("Empty File"), _("Session file is empty.")) # Close current files self.CloseAllPages() missingfns = [] for loadfn in flist: if os.path.exists(loadfn) and os.access(loadfn, os.R_OK): if not ebmlib.IsUnicode(loadfn): try: loadfn = loadfn.decode(sys.getfilesystemencoding()) except UnicodeDecodeError: self.LOG("[ed_pages][err] LoadSessionFile: Failed to decode file name") self.OpenPage(os.path.dirname(loadfn), os.path.basename(loadfn)) else: missingfns.append(loadfn) if missingfns: rmsg = (_("Missing session files"), _("Some files in saved session could not be found on disk:\n")+ u'\n'.join(missingfns)) self._ses_load = False return rmsg self._ses_load = False if self.GetPageCount() == 0: self.NewPage() self.Refresh() return None
[ "def", "LoadSessionFile", "(", "self", ",", "session", ")", ":", "self", ".", "_ses_load", "=", "True", "mgr", "=", "ed_session", ".", "EdSessionMgr", "(", ")", "flist", "=", "list", "(", ")", "try", ":", "flist", "=", "mgr", ".", "LoadSession", "(", "session", ")", "except", "Exception", ",", "msg", ":", "self", ".", "_ses_load", "=", "False", "errdict", "=", "dict", "(", "sessionname", "=", "session", ",", "error", "=", "msg", ")", "return", "(", "_", "(", "\"Session Load Error\"", ")", ",", "_", "(", "\"Failed to load the session: %(sessionname)s\\n\\nError: %(error)s\"", ")", "%", "errdict", ")", "if", "not", "len", "(", "flist", ")", ":", "self", ".", "_ses_load", "=", "False", "return", "(", "_", "(", "\"Empty File\"", ")", ",", "_", "(", "\"Session file is empty.\"", ")", ")", "# Close current files", "self", ".", "CloseAllPages", "(", ")", "missingfns", "=", "[", "]", "for", "loadfn", "in", "flist", ":", "if", "os", ".", "path", ".", "exists", "(", "loadfn", ")", "and", "os", ".", "access", "(", "loadfn", ",", "os", ".", "R_OK", ")", ":", "if", "not", "ebmlib", ".", "IsUnicode", "(", "loadfn", ")", ":", "try", ":", "loadfn", "=", "loadfn", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ")", "except", "UnicodeDecodeError", ":", "self", ".", "LOG", "(", "\"[ed_pages][err] LoadSessionFile: Failed to decode file name\"", ")", "self", ".", "OpenPage", "(", "os", ".", "path", ".", "dirname", "(", "loadfn", ")", ",", "os", ".", "path", ".", "basename", "(", "loadfn", ")", ")", "else", ":", "missingfns", ".", "append", "(", "loadfn", ")", "if", "missingfns", ":", "rmsg", "=", "(", "_", "(", "\"Missing session files\"", ")", ",", "_", "(", "\"Some files in saved session could not be found on disk:\\n\"", ")", "+", "u'\\n'", ".", "join", "(", "missingfns", ")", ")", "self", ".", "_ses_load", "=", "False", "return", "rmsg", "self", ".", "_ses_load", "=", "False", "if", "self", ".", "GetPageCount", "(", ")", "==", "0", ":", "self", ".", "NewPage", "(", ")", "self", ".", "Refresh", "(", ")", "return", "None" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_pages.py#L354-L405