nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
renpy/pygame_sdl2
c8c732109c38da2453b85270882115a24b71b238
src/pygame_sdl2/sprite.py
python
Sprite.alive
(self)
return truth(self.__g)
does the sprite belong to any groups Sprite.alive(): return bool Returns True when the Sprite belongs to one or more Groups.
does the sprite belong to any groups
[ "does", "the", "sprite", "belong", "to", "any", "groups" ]
def alive(self): """does the sprite belong to any groups Sprite.alive(): return bool Returns True when the Sprite belongs to one or more Groups. """ return truth(self.__g)
[ "def", "alive", "(", "self", ")", ":", "return", "truth", "(", "self", ".", "__g", ")" ]
https://github.com/renpy/pygame_sdl2/blob/c8c732109c38da2453b85270882115a24b71b238/src/pygame_sdl2/sprite.py#L208-L215
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/core/virtual_network_client.py
python
VirtualNetworkClient.bulk_add_virtual_circuit_public_prefixes
(self, virtual_circuit_id, bulk_add_virtual_circuit_public_prefixes_details, **kwargs)
Adds one or more customer public IP prefixes to the specified public virtual circuit. Use this operation (and not :func:`update_virtual_circuit`) to add prefixes to the virtual circuit. Oracle must verify the customer's ownership of each prefix before traffic for that prefix will flow across the virtual circuit. :param str virtual_circuit_id: (required) The `OCID`__ of the virtual circuit. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param oci.core.models.BulkAddVirtualCircuitPublicPrefixesDetails bulk_add_virtual_circuit_public_prefixes_details: (required) Request with publix prefixes to be added to the virtual circuit :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/core/bulk_add_virtual_circuit_public_prefixes.py.html>`__ to see an example of how to use bulk_add_virtual_circuit_public_prefixes API.
Adds one or more customer public IP prefixes to the specified public virtual circuit. Use this operation (and not :func:`update_virtual_circuit`) to add prefixes to the virtual circuit. Oracle must verify the customer's ownership of each prefix before traffic for that prefix will flow across the virtual circuit.
[ "Adds", "one", "or", "more", "customer", "public", "IP", "prefixes", "to", "the", "specified", "public", "virtual", "circuit", ".", "Use", "this", "operation", "(", "and", "not", ":", "func", ":", "update_virtual_circuit", ")", "to", "add", "prefixes", "to",...
def bulk_add_virtual_circuit_public_prefixes(self, virtual_circuit_id, bulk_add_virtual_circuit_public_prefixes_details, **kwargs): """ Adds one or more customer public IP prefixes to the specified public virtual circuit. Use this operation (and not :func:`update_virtual_circuit`) to add prefixes to the virtual circuit. Oracle must verify the customer's ownership of each prefix before traffic for that prefix will flow across the virtual circuit. :param str virtual_circuit_id: (required) The `OCID`__ of the virtual circuit. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param oci.core.models.BulkAddVirtualCircuitPublicPrefixesDetails bulk_add_virtual_circuit_public_prefixes_details: (required) Request with publix prefixes to be added to the virtual circuit :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/core/bulk_add_virtual_circuit_public_prefixes.py.html>`__ to see an example of how to use bulk_add_virtual_circuit_public_prefixes API. """ resource_path = "/virtualCircuits/{virtualCircuitId}/actions/bulkAddPublicPrefixes" method = "POST" expected_kwargs = ["retry_strategy"] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "bulk_add_virtual_circuit_public_prefixes got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "virtualCircuitId": virtual_circuit_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json" } retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=bulk_add_virtual_circuit_public_prefixes_details) else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=bulk_add_virtual_circuit_public_prefixes_details)
[ "def", "bulk_add_virtual_circuit_public_prefixes", "(", "self", ",", "virtual_circuit_id", ",", "bulk_add_virtual_circuit_public_prefixes_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/virtualCircuits/{virtualCircuitId}/actions/bulkAddPublicPrefixes\"", "met...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/core/virtual_network_client.py#L835-L911
yuzhoujr/leetcode
6a2ad1fc11225db18f68bfadd21a7419d2cb52a4
dp/70.py
python
Solution.climbStairs
(self, n)
return res[-1]
:type n: int :rtype: int
:type n: int :rtype: int
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int" ]
def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 res = [1,2] for i in xrange(2, n): res.append(res[i-1] + res[i-2]) return res[-1]
[ "def", "climbStairs", "(", "self", ",", "n", ")", ":", "if", "n", "==", "1", ":", "return", "1", "res", "=", "[", "1", ",", "2", "]", "for", "i", "in", "xrange", "(", "2", ",", "n", ")", ":", "res", ".", "append", "(", "res", "[", "i", "-...
https://github.com/yuzhoujr/leetcode/blob/6a2ad1fc11225db18f68bfadd21a7419d2cb52a4/dp/70.py#L37-L48
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
NLP/ACL2020-GraphSum/src/networks/graphsum/graphsum_reader.py
python
GraphSumReader._pad_tgt_batch_data
(self, insts)
return return_list
Pad the instances to the max sequence length in batch, and generate the corresponding position data and attention bias.
Pad the instances to the max sequence length in batch, and generate the corresponding position data and attention bias.
[ "Pad", "the", "instances", "to", "the", "max", "sequence", "length", "in", "batch", "and", "generate", "the", "corresponding", "position", "data", "and", "attention", "bias", "." ]
def _pad_tgt_batch_data(self, insts): """ Pad the instances to the max sequence length in batch, and generate the corresponding position data and attention bias. """ return_list = [] # (batch_size, max_tgt_len) inst_data = np.array([inst + [self.pad_idx] * (self.max_tgt_len - len(inst)) for inst in insts], dtype="int64") return_list += [inst_data] # (batch_size, max_tgt_len) inst_pos = np.array([list(range(0, len(inst))) + [0] * (self.max_tgt_len - len(inst)) for inst in insts], dtype="int64") return_list += [inst_pos] # This is used to avoid attention on subsequent words. slf_attn_bias_data = np.ones((len(insts), self.max_tgt_len, self.max_tgt_len), dtype="float32") slf_attn_bias_data = np.triu(slf_attn_bias_data, 1) * -1e18 return_list += [slf_attn_bias_data] return return_list
[ "def", "_pad_tgt_batch_data", "(", "self", ",", "insts", ")", ":", "return_list", "=", "[", "]", "# (batch_size, max_tgt_len)", "inst_data", "=", "np", ".", "array", "(", "[", "inst", "+", "[", "self", ".", "pad_idx", "]", "*", "(", "self", ".", "max_tgt...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/NLP/ACL2020-GraphSum/src/networks/graphsum/graphsum_reader.py#L412-L434
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/output/text_file.py
python
text_file.vulnerability
(self, message, new_line=True, severity=severity.MEDIUM)
This method is called from the output object. The output object was called from a plugin or from the framework. This method should take an action when a vulnerability is found.
This method is called from the output object. The output object was called from a plugin or from the framework. This method should take an action when a vulnerability is found.
[ "This", "method", "is", "called", "from", "the", "output", "object", ".", "The", "output", "object", "was", "called", "from", "a", "plugin", "or", "from", "the", "framework", ".", "This", "method", "should", "take", "an", "action", "when", "a", "vulnerabil...
def vulnerability(self, message, new_line=True, severity=severity.MEDIUM): """ This method is called from the output object. The output object was called from a plugin or from the framework. This method should take an action when a vulnerability is found. """ self.write(message, 'vulnerability', new_line)
[ "def", "vulnerability", "(", "self", ",", "message", ",", "new_line", "=", "True", ",", "severity", "=", "severity", ".", "MEDIUM", ")", ":", "self", ".", "write", "(", "message", ",", "'vulnerability'", ",", "new_line", ")" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/output/text_file.py#L223-L229
awslabs/gluon-ts
066ec3b7f47aa4ee4c061a28f35db7edbad05a98
src/gluonts/model/gp_forecaster/gaussian_process.py
python
GaussianProcess.__init__
( self, sigma: Tensor, kernel: Kernel, prediction_length: Optional[int] = None, context_length: Optional[int] = None, num_samples: Optional[int] = None, float_type: Type = np.float64, jitter_method: str = "iter", max_iter_jitter: int = 10, neg_tol: float = -1e-8, diag_weight: float = 1e-6, increase_jitter: int = 10, sample_noise: bool = True, F=None, )
r""" Parameters ---------- sigma Noise parameter of shape (batch_size, num_data_points, 1), where num_data_points is the number of rows in the Cholesky matrix. kernel Kernel object. prediction_length Prediction length. context_length Training length. num_samples The number of samples to be drawn. float_type Determines whether to use single or double precision. jitter_method Iteratively jitter method or use eigenvalue decomposition depending on problem size. max_iter_jitter Maximum number of iterations for jitter to iteratively make the matrix positive definite. neg_tol Parameter in the jitter methods to eliminate eliminate matrices with diagonal elements smaller than this when checking if a matrix is positive definite. diag_weight Multiple of mean of diagonal entries to initialize the jitter. increase_jitter Each iteration multiply by jitter by this amount sample_noise Boolean to determine whether to add :math:`\sigma^2I` to the predictive covariance matrix. F A module that can either refer to the Symbol API or the NDArray API in MXNet.
r""" Parameters ---------- sigma Noise parameter of shape (batch_size, num_data_points, 1), where num_data_points is the number of rows in the Cholesky matrix. kernel Kernel object. prediction_length Prediction length. context_length Training length. num_samples The number of samples to be drawn. float_type Determines whether to use single or double precision. jitter_method Iteratively jitter method or use eigenvalue decomposition depending on problem size. max_iter_jitter Maximum number of iterations for jitter to iteratively make the matrix positive definite. neg_tol Parameter in the jitter methods to eliminate eliminate matrices with diagonal elements smaller than this when checking if a matrix is positive definite. diag_weight Multiple of mean of diagonal entries to initialize the jitter. increase_jitter Each iteration multiply by jitter by this amount sample_noise Boolean to determine whether to add :math:`\sigma^2I` to the predictive covariance matrix. F A module that can either refer to the Symbol API or the NDArray API in MXNet.
[ "r", "Parameters", "----------", "sigma", "Noise", "parameter", "of", "shape", "(", "batch_size", "num_data_points", "1", ")", "where", "num_data_points", "is", "the", "number", "of", "rows", "in", "the", "Cholesky", "matrix", ".", "kernel", "Kernel", "object", ...
def __init__( self, sigma: Tensor, kernel: Kernel, prediction_length: Optional[int] = None, context_length: Optional[int] = None, num_samples: Optional[int] = None, float_type: Type = np.float64, jitter_method: str = "iter", max_iter_jitter: int = 10, neg_tol: float = -1e-8, diag_weight: float = 1e-6, increase_jitter: int = 10, sample_noise: bool = True, F=None, ) -> None: r""" Parameters ---------- sigma Noise parameter of shape (batch_size, num_data_points, 1), where num_data_points is the number of rows in the Cholesky matrix. kernel Kernel object. prediction_length Prediction length. context_length Training length. num_samples The number of samples to be drawn. float_type Determines whether to use single or double precision. jitter_method Iteratively jitter method or use eigenvalue decomposition depending on problem size. max_iter_jitter Maximum number of iterations for jitter to iteratively make the matrix positive definite. neg_tol Parameter in the jitter methods to eliminate eliminate matrices with diagonal elements smaller than this when checking if a matrix is positive definite. diag_weight Multiple of mean of diagonal entries to initialize the jitter. increase_jitter Each iteration multiply by jitter by this amount sample_noise Boolean to determine whether to add :math:`\sigma^2I` to the predictive covariance matrix. F A module that can either refer to the Symbol API or the NDArray API in MXNet. """ assert ( prediction_length is None or prediction_length > 0 ), "The value of `prediction_length` should be > 0" assert ( context_length is None or context_length > 0 ), "The value of `context_length` should be > 0" assert ( num_samples is None or num_samples > 0 ), "The value of `num_samples` should be > 0" self.sigma = sigma self.kernel = kernel self.prediction_length = prediction_length self.context_length = ( context_length if context_length is not None else prediction_length ) self.num_samples = num_samples self.F = F if F else getF(sigma) self.float_type = float_type self.jitter_method = jitter_method self.max_iter_jitter = max_iter_jitter self.neg_tol = neg_tol self.diag_weight = diag_weight self.increase_jitter = increase_jitter self.sample_noise = sample_noise
[ "def", "__init__", "(", "self", ",", "sigma", ":", "Tensor", ",", "kernel", ":", "Kernel", ",", "prediction_length", ":", "Optional", "[", "int", "]", "=", "None", ",", "context_length", ":", "Optional", "[", "int", "]", "=", "None", ",", "num_samples", ...
https://github.com/awslabs/gluon-ts/blob/066ec3b7f47aa4ee4c061a28f35db7edbad05a98/src/gluonts/model/gp_forecaster/gaussian_process.py#L32-L104
bwohlberg/sporco
df67462abcf83af6ab1961bcb0d51b87a66483fa
sporco/admm/cbpdn.py
python
ConvMinL1InL2Ball.eval_objfn
(self)
return (g1v, g0v)
Compute components of regularisation function as well as total contribution to objective function.
Compute components of regularisation function as well as total contribution to objective function.
[ "Compute", "components", "of", "regularisation", "function", "as", "well", "as", "total", "contribution", "to", "objective", "function", "." ]
def eval_objfn(self): """Compute components of regularisation function as well as total contribution to objective function. """ g0v = self.obfn_g0(self.obfn_g0var()) g1v = self.obfn_g1(self.obfn_g1var()) return (g1v, g0v)
[ "def", "eval_objfn", "(", "self", ")", ":", "g0v", "=", "self", ".", "obfn_g0", "(", "self", ".", "obfn_g0var", "(", ")", ")", "g1v", "=", "self", ".", "obfn_g1", "(", "self", ".", "obfn_g1var", "(", ")", ")", "return", "(", "g1v", ",", "g0v", ")...
https://github.com/bwohlberg/sporco/blob/df67462abcf83af6ab1961bcb0d51b87a66483fa/sporco/admm/cbpdn.py#L2053-L2060
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/path.py
python
Path.read_hexhash
(self, hash_name)
return self._hash(hash_name).hexdigest()
Calculate given hash for this file, returning hexdigest. List of supported hashes can be obtained from :mod:`hashlib` package. This reads the entire file. .. seealso:: :meth:`hashlib.hash.hexdigest`
Calculate given hash for this file, returning hexdigest.
[ "Calculate", "given", "hash", "for", "this", "file", "returning", "hexdigest", "." ]
def read_hexhash(self, hash_name): """ Calculate given hash for this file, returning hexdigest. List of supported hashes can be obtained from :mod:`hashlib` package. This reads the entire file. .. seealso:: :meth:`hashlib.hash.hexdigest` """ return self._hash(hash_name).hexdigest()
[ "def", "read_hexhash", "(", "self", ",", "hash_name", ")", ":", "return", "self", ".", "_hash", "(", "hash_name", ")", ".", "hexdigest", "(", ")" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/path.py#L969-L977
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_pvc.py
python
OCPVC.delete
(self)
return self._delete(self.kind, self.config.name)
delete the object
delete the object
[ "delete", "the", "object" ]
def delete(self): '''delete the object''' return self._delete(self.kind, self.config.name)
[ "def", "delete", "(", "self", ")", ":", "return", "self", ".", "_delete", "(", "self", ".", "kind", ",", "self", ".", "config", ".", "name", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_pvc.py#L1750-L1752
fake-name/ChromeController
6c70d855e33e06463516b263bf9e6f34c48e29e8
ChromeController/Generator/Generated.py
python
ChromeRemoteDebugInterface.DOMStorage_enable
(self)
return subdom_funcs
Function path: DOMStorage.enable Domain: DOMStorage Method name: enable No return value. Description: Enables storage tracking, storage events will now be delivered to the client.
Function path: DOMStorage.enable Domain: DOMStorage Method name: enable No return value. Description: Enables storage tracking, storage events will now be delivered to the client.
[ "Function", "path", ":", "DOMStorage", ".", "enable", "Domain", ":", "DOMStorage", "Method", "name", ":", "enable", "No", "return", "value", ".", "Description", ":", "Enables", "storage", "tracking", "storage", "events", "will", "now", "be", "delivered", "to",...
def DOMStorage_enable(self): """ Function path: DOMStorage.enable Domain: DOMStorage Method name: enable No return value. Description: Enables storage tracking, storage events will now be delivered to the client. """ subdom_funcs = self.synchronous_command('DOMStorage.enable') return subdom_funcs
[ "def", "DOMStorage_enable", "(", "self", ")", ":", "subdom_funcs", "=", "self", ".", "synchronous_command", "(", "'DOMStorage.enable'", ")", "return", "subdom_funcs" ]
https://github.com/fake-name/ChromeController/blob/6c70d855e33e06463516b263bf9e6f34c48e29e8/ChromeController/Generator/Generated.py#L3259-L3270
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distro.py
python
LinuxDistribution._get_lsb_release_info
(self)
Get the information items from the lsb_release command output. Returns: A dictionary containing all information items.
Get the information items from the lsb_release command output.
[ "Get", "the", "information", "items", "from", "the", "lsb_release", "command", "output", "." ]
def _get_lsb_release_info(self): """ Get the information items from the lsb_release command output. Returns: A dictionary containing all information items. """ cmd = 'lsb_release -a' process = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8') code = process.returncode if code == 0: content = stdout.splitlines() return self._parse_lsb_release_content(content) elif code == 127: # Command not found return {} else: if sys.version_info[:2] >= (3, 5): raise subprocess.CalledProcessError(code, cmd, stdout, stderr) elif sys.version_info[:2] >= (2, 7): raise subprocess.CalledProcessError(code, cmd, stdout) elif sys.version_info[:2] == (2, 6): raise subprocess.CalledProcessError(code, cmd)
[ "def", "_get_lsb_release_info", "(", "self", ")", ":", "cmd", "=", "'lsb_release -a'", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", ...
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distro.py#L908-L935
rohitgirdhar/AttentionalPoolingAction
9ab0acd9360fc9763b27073a7da057f996c01c58
models/slim/nets/inception_v2_tsn.py
python
_reduced_kernel_size_for_small_input
(input_tensor, kernel_size)
return kernel_size_out
Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough. Args: input_tensor: input tensor of size [batch_size, height, width, channels]. kernel_size: desired kernel size of length 2: [kernel_height, kernel_width] Returns: a tensor with the kernel size. TODO(jrru): Make this function work with unknown shapes. Theoretically, this can be done with the code below. Problems are two-fold: (1) If the shape was known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot handle tensors that define the kernel size. shape = tf.shape(input_tensor) return = tf.pack([tf.minimum(shape[1], kernel_size[0]), tf.minimum(shape[2], kernel_size[1])])
Define kernel size which is automatically reduced for small input.
[ "Define", "kernel", "size", "which", "is", "automatically", "reduced", "for", "small", "input", "." ]
def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough. Args: input_tensor: input tensor of size [batch_size, height, width, channels]. kernel_size: desired kernel size of length 2: [kernel_height, kernel_width] Returns: a tensor with the kernel size. TODO(jrru): Make this function work with unknown shapes. Theoretically, this can be done with the code below. Problems are two-fold: (1) If the shape was known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot handle tensors that define the kernel size. shape = tf.shape(input_tensor) return = tf.pack([tf.minimum(shape[1], kernel_size[0]), tf.minimum(shape[2], kernel_size[1])]) """ shape = input_tensor.get_shape().as_list() if shape[1] is None or shape[2] is None: kernel_size_out = kernel_size else: kernel_size_out = [min(shape[1], kernel_size[0]), min(shape[2], kernel_size[1])] return kernel_size_out
[ "def", "_reduced_kernel_size_for_small_input", "(", "input_tensor", ",", "kernel_size", ")", ":", "shape", "=", "input_tensor", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "shape", "[", "1", "]", "is", "None", "or", "shape", "[", "2", "]", ...
https://github.com/rohitgirdhar/AttentionalPoolingAction/blob/9ab0acd9360fc9763b27073a7da057f996c01c58/models/slim/nets/inception_v2_tsn.py#L268-L296
marcwebbie/passpie
421c40a57ad5f55e3f14b323c929a2c41dfb5527
passpie/cli.py
python
list_database
(db)
Print credential as a table
Print credential as a table
[ "Print", "credential", "as", "a", "table" ]
def list_database(db): """Print credential as a table""" credentials = db.credentials() if credentials: table = Table( db.config['headers'], table_format=db.config['table_format'], colors=db.config['colors'], hidden=db.config['hidden'], hidden_string=db.config['hidden_string'], ) click.echo(table.render(credentials))
[ "def", "list_database", "(", "db", ")", ":", "credentials", "=", "db", ".", "credentials", "(", ")", "if", "credentials", ":", "table", "=", "Table", "(", "db", ".", "config", "[", "'headers'", "]", ",", "table_format", "=", "db", ".", "config", "[", ...
https://github.com/marcwebbie/passpie/blob/421c40a57ad5f55e3f14b323c929a2c41dfb5527/passpie/cli.py#L127-L138
zachwill/flask-engine
7c8ad4bfe36382a8c9286d873ec7b785715832a4
libs/werkzeug/formparser.py
python
default_stream_factory
(total_content_length, filename, content_type, content_length=None)
return StringIO()
The stream factory that is used per default.
The stream factory that is used per default.
[ "The", "stream", "factory", "that", "is", "used", "per", "default", "." ]
def default_stream_factory(total_content_length, filename, content_type, content_length=None): """The stream factory that is used per default.""" if total_content_length > 1024 * 500: return TemporaryFile('wb+') return StringIO()
[ "def", "default_stream_factory", "(", "total_content_length", ",", "filename", ",", "content_type", ",", "content_length", "=", "None", ")", ":", "if", "total_content_length", ">", "1024", "*", "500", ":", "return", "TemporaryFile", "(", "'wb+'", ")", "return", ...
https://github.com/zachwill/flask-engine/blob/7c8ad4bfe36382a8c9286d873ec7b785715832a4/libs/werkzeug/formparser.py#L31-L36
hvac/hvac
ec048ded30d21c13c21cfa950d148c8bfc1467b0
hvac/adapters.py
python
Adapter.urljoin
(*args)
return "/".join(map(lambda x: str(x).strip("/"), args))
Joins given arguments into a url. Trailing and leading slashes are stripped for each argument. :param args: Multiple parts of a URL to be combined into one string. :type args: str | unicode :return: Full URL combining all provided arguments :rtype: str | unicode
Joins given arguments into a url. Trailing and leading slashes are stripped for each argument.
[ "Joins", "given", "arguments", "into", "a", "url", ".", "Trailing", "and", "leading", "slashes", "are", "stripped", "for", "each", "argument", "." ]
def urljoin(*args): """Joins given arguments into a url. Trailing and leading slashes are stripped for each argument. :param args: Multiple parts of a URL to be combined into one string. :type args: str | unicode :return: Full URL combining all provided arguments :rtype: str | unicode """ return "/".join(map(lambda x: str(x).strip("/"), args))
[ "def", "urljoin", "(", "*", "args", ")", ":", "return", "\"/\"", ".", "join", "(", "map", "(", "lambda", "x", ":", "str", "(", "x", ")", ".", "strip", "(", "\"/\"", ")", ",", "args", ")", ")" ]
https://github.com/hvac/hvac/blob/ec048ded30d21c13c21cfa950d148c8bfc1467b0/hvac/adapters.py#L87-L96
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/pickle.py
python
Pickler.dump
(self, obj)
Write a pickled representation of obj to the open file.
Write a pickled representation of obj to the open file.
[ "Write", "a", "pickled", "representation", "of", "obj", "to", "the", "open", "file", "." ]
def dump(self, obj): """Write a pickled representation of obj to the open file.""" if self.proto >= 2: self.write(PROTO + chr(self.proto)) self.save(obj) self.write(STOP)
[ "def", "dump", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "proto", ">=", "2", ":", "self", ".", "write", "(", "PROTO", "+", "chr", "(", "self", ".", "proto", ")", ")", "self", ".", "save", "(", "obj", ")", "self", ".", "write", "("...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/pickle.py#L221-L226
pillone/usntssearch
24b5e5bc4b6af2589d95121c4d523dc58cb34273
NZBmegasearch/mechanize/_beautifulsoup.py
python
Tag.__iter__
(self)
return iter(self.contents)
Iterating over a tag iterates over its contents.
Iterating over a tag iterates over its contents.
[ "Iterating", "over", "a", "tag", "iterates", "over", "its", "contents", "." ]
def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "contents", ")" ]
https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/mechanize/_beautifulsoup.py#L300-L302
kozec/sc-controller
ce92c773b8b26f6404882e9209aff212c4053170
scc/lib/usb1.py
python
USBTransfer.__init__
(self, handle, iso_packets, before_submit, after_completion)
You should not instanciate this class directly. Call "getTransfer" method on an USBDeviceHandle instance to get instances of this class.
You should not instanciate this class directly. Call "getTransfer" method on an USBDeviceHandle instance to get instances of this class.
[ "You", "should", "not", "instanciate", "this", "class", "directly", ".", "Call", "getTransfer", "method", "on", "an", "USBDeviceHandle", "instance", "to", "get", "instances", "of", "this", "class", "." ]
def __init__(self, handle, iso_packets, before_submit, after_completion): """ You should not instanciate this class directly. Call "getTransfer" method on an USBDeviceHandle instance to get instances of this class. """ if iso_packets < 0: raise ValueError( 'Cannot request a negative number of iso packets.' ) self.__handle = handle self.__before_submit = before_submit self.__after_completion = after_completion self.__num_iso_packets = iso_packets result = libusb1.libusb_alloc_transfer(iso_packets) if not result: # pylint: disable=undefined-variable raise USBErrorNoMem # pylint: enable=undefined-variable self.__transfer = result self.__ctypesCallbackWrapper = libusb1.libusb_transfer_cb_fn_p( self.__callbackWrapper)
[ "def", "__init__", "(", "self", ",", "handle", ",", "iso_packets", ",", "before_submit", ",", "after_completion", ")", ":", "if", "iso_packets", "<", "0", ":", "raise", "ValueError", "(", "'Cannot request a negative number of iso packets.'", ")", "self", ".", "__h...
https://github.com/kozec/sc-controller/blob/ce92c773b8b26f6404882e9209aff212c4053170/scc/lib/usb1.py#L239-L260
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/set/src/core/setcore.py
python
meta_database
()
[]
def meta_database(): # DEFINE METASPLOIT PATH meta_path = file("%s/config/set_config" % (definepath),"r").readlines() for line in meta_path: line = line.rstrip() match = re.search("METASPLOIT_DATABASE=", line) if match: line = line.replace("METASPLOIT_DATABASE=","") msf_database = line.rstrip() return msf_database
[ "def", "meta_database", "(", ")", ":", "# DEFINE METASPLOIT PATH", "meta_path", "=", "file", "(", "\"%s/config/set_config\"", "%", "(", "definepath", ")", ",", "\"r\"", ")", ".", "readlines", "(", ")", "for", "line", "in", "meta_path", ":", "line", "=", "lin...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/set/src/core/setcore.py#L296-L305
ayoolaolafenwa/PixelLib
ae56003c416a98780141a1170c9d888fe9a31317
pixellib/torchbackend/instance/data/transforms/augmentation.py
python
_get_aug_input_args
(aug, aug_input)
return args
Get the arguments to be passed to ``aug.get_transform`` from the input ``aug_input``.
Get the arguments to be passed to ``aug.get_transform`` from the input ``aug_input``.
[ "Get", "the", "arguments", "to", "be", "passed", "to", "aug", ".", "get_transform", "from", "the", "input", "aug_input", "." ]
def _get_aug_input_args(aug, aug_input) -> List[Any]: """ Get the arguments to be passed to ``aug.get_transform`` from the input ``aug_input``. """ if aug.input_args is None: # Decide what attributes are needed automatically prms = list(inspect.signature(aug.get_transform).parameters.items()) # The default behavior is: if there is one parameter, then its "image" # (work automatically for majority of use cases, and also avoid BC breaking), # Otherwise, use the argument names. if len(prms) == 1: names = ("image",) else: names = [] for name, prm in prms: if prm.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD): raise TypeError( f""" \ The default implementation of `{type(aug)}.__call__` does not allow \ `{type(aug)}.get_transform` to use variable-length arguments (*args, **kwargs)! \ If arguments are unknown, reimplement `__call__` instead. \ """ ) names.append(name) aug.input_args = tuple(names) args = [] for f in aug.input_args: try: args.append(getattr(aug_input, f)) except AttributeError as e: raise AttributeError( f"{type(aug)}.get_transform needs input attribute '{f}', " f"but it is not an attribute of {type(aug_input)}!" ) from e return args
[ "def", "_get_aug_input_args", "(", "aug", ",", "aug_input", ")", "->", "List", "[", "Any", "]", ":", "if", "aug", ".", "input_args", "is", "None", ":", "# Decide what attributes are needed automatically", "prms", "=", "list", "(", "inspect", ".", "signature", ...
https://github.com/ayoolaolafenwa/PixelLib/blob/ae56003c416a98780141a1170c9d888fe9a31317/pixellib/torchbackend/instance/data/transforms/augmentation.py#L39-L74
ChenRocks/fast_abs_rl
a3cd65016082ab842be4e42b0b26b7bc046f4ad5
model/rl.py
python
PtrExtractorRL.forward
(self, attn_mem, n_step)
return outputs
atten_mem: Tensor of size [num_sents, input_dim]
atten_mem: Tensor of size [num_sents, input_dim]
[ "atten_mem", ":", "Tensor", "of", "size", "[", "num_sents", "input_dim", "]" ]
def forward(self, attn_mem, n_step): """atten_mem: Tensor of size [num_sents, input_dim]""" attn_feat = torch.mm(attn_mem, self._attn_wm) hop_feat = torch.mm(attn_mem, self._hop_wm) outputs = [] lstm_in = self._init_i.unsqueeze(0) lstm_states = (self._init_h.unsqueeze(1), self._init_c.unsqueeze(1)) for _ in range(n_step): h, c = self._lstm_cell(lstm_in, lstm_states) query = h[:, -1, :] for _ in range(self._n_hop): query = PtrExtractorRL.attention(hop_feat, query, self._hop_v, self._hop_wq) score = PtrExtractorRL.attention_score( attn_feat, query, self._attn_v, self._attn_wq) if self.training: prob = F.softmax(score, dim=-1) out = torch.distributions.Categorical(prob) else: for o in outputs: score[0, o[0, 0].item()][0] = -1e18 out = score.max(dim=1, keepdim=True)[1] outputs.append(out) lstm_in = attn_mem[out[0, 0].item()].unsqueeze(0) lstm_states = (h, c) return outputs
[ "def", "forward", "(", "self", ",", "attn_mem", ",", "n_step", ")", ":", "attn_feat", "=", "torch", ".", "mm", "(", "attn_mem", ",", "self", ".", "_attn_wm", ")", "hop_feat", "=", "torch", ".", "mm", "(", "attn_mem", ",", "self", ".", "_hop_wm", ")",...
https://github.com/ChenRocks/fast_abs_rl/blob/a3cd65016082ab842be4e42b0b26b7bc046f4ad5/model/rl.py#L35-L60
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/readers/sar_c_safe.py
python
SAFEXMLCalibration.get_dataset
(self, key, info, chunks=None)
return self.get_calibration(key["name"], chunks=chunks or CHUNK_SIZE)
Load a dataset.
Load a dataset.
[ "Load", "a", "dataset", "." ]
def get_dataset(self, key, info, chunks=None): """Load a dataset.""" if self._polarization != key["polarization"]: return if key["name"] == "calibration_constant": return self.get_calibration_constant() return self.get_calibration(key["name"], chunks=chunks or CHUNK_SIZE)
[ "def", "get_dataset", "(", "self", ",", "key", ",", "info", ",", "chunks", "=", "None", ")", ":", "if", "self", ".", "_polarization", "!=", "key", "[", "\"polarization\"", "]", ":", "return", "if", "key", "[", "\"name\"", "]", "==", "\"calibration_consta...
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/sar_c_safe.py#L147-L153
stanfordnlp/stanza-old
920c55d8eaa1e7105971059c66eb448a74c100d6
stanza/text/vocab.py
python
FrozenVocab.__init__
(self, vocab)
[]
def __init__(self, vocab): self._word2index = dict(vocab) # make a copy self._index2word = copy(vocab._index2word)
[ "def", "__init__", "(", "self", ",", "vocab", ")", ":", "self", ".", "_word2index", "=", "dict", "(", "vocab", ")", "# make a copy", "self", ".", "_index2word", "=", "copy", "(", "vocab", ".", "_index2word", ")" ]
https://github.com/stanfordnlp/stanza-old/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L284-L286
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/huizuo.py
python
HuizuoLampFan.set_natural_fan_mode
(self)
Set fan mode to 'Natural wind' (only for models with fan)
Set fan mode to 'Natural wind' (only for models with fan)
[ "Set", "fan", "mode", "to", "Natural", "wind", "(", "only", "for", "models", "with", "fan", ")" ]
def set_natural_fan_mode(self): """Set fan mode to 'Natural wind' (only for models with fan)""" if self.model in MODELS_WITH_FAN_WY or self.model in MODELS_WITH_FAN_WY2: return self.set_property("fan_mode", 1) raise HuizuoException("Your device doesn't support a fan management")
[ "def", "set_natural_fan_mode", "(", "self", ")", ":", "if", "self", ".", "model", "in", "MODELS_WITH_FAN_WY", "or", "self", ".", "model", "in", "MODELS_WITH_FAN_WY2", ":", "return", "self", ".", "set_property", "(", "\"fan_mode\"", ",", "1", ")", "raise", "H...
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/huizuo.py#L362-L367
thanethomson/statik
ea422b8fccd1430f60e3d8b62d9221365ec4e31f
statik/templating.py
python
StatikJinjaTemplate.__init__
(self, provider, template, **kwargs)
Constructor. Args: provider: The provider that created this template. template: The Jinja2 template to wrap.
Constructor.
[ "Constructor", "." ]
def __init__(self, provider, template, **kwargs): """Constructor. Args: provider: The provider that created this template. template: The Jinja2 template to wrap. """ super(StatikJinjaTemplate, self).__init__(template.filename, **kwargs) self.provider = provider self.template = template
[ "def", "__init__", "(", "self", ",", "provider", ",", "template", ",", "*", "*", "kwargs", ")", ":", "super", "(", "StatikJinjaTemplate", ",", "self", ")", ".", "__init__", "(", "template", ".", "filename", ",", "*", "*", "kwargs", ")", "self", ".", ...
https://github.com/thanethomson/statik/blob/ea422b8fccd1430f60e3d8b62d9221365ec4e31f/statik/templating.py#L325-L334
munificent/magpie
f5138e3d316ec1a664b5eadba1bcc8573d3faca3
dep/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.HasExplicitIdlRules
(self, spec)
return self._HasExplicitRuleForExtension(spec, 'idl')
Determine if there's an explicit rule for idl files. When there isn't we need to generate implicit rules to build MIDL .idl files.
Determine if there's an explicit rule for idl files. When there isn't we need to generate implicit rules to build MIDL .idl files.
[ "Determine", "if", "there", "s", "an", "explicit", "rule", "for", "idl", "files", ".", "When", "there", "isn", "t", "we", "need", "to", "generate", "implicit", "rules", "to", "build", "MIDL", ".", "idl", "files", "." ]
def HasExplicitIdlRules(self, spec): """Determine if there's an explicit rule for idl files. When there isn't we need to generate implicit rules to build MIDL .idl files.""" return self._HasExplicitRuleForExtension(spec, 'idl')
[ "def", "HasExplicitIdlRules", "(", "self", ",", "spec", ")", ":", "return", "self", ".", "_HasExplicitRuleForExtension", "(", "spec", ",", "'idl'", ")" ]
https://github.com/munificent/magpie/blob/f5138e3d316ec1a664b5eadba1bcc8573d3faca3/dep/gyp/pylib/gyp/msvs_emulation.py#L560-L563
pculture/miro
d8e4594441939514dd2ac29812bf37087bb3aea5
tv/lib/frontends/widgets/cellpack.py
python
Layout.add
(self, x, y, width, height, drawing_function=None, hotspot=None)
return self.add_rect(LayoutRect(x, y, width, height), drawing_function, hotspot)
Add a new element to this Layout :param x: x coordinate :param y: y coordinate :param width: width :param height: height :param drawing_function: if set, call this function to render the element on a DrawingContext :param hotspot: if set, the hotspot for this element :returns: LayoutRect of the added element
Add a new element to this Layout
[ "Add", "a", "new", "element", "to", "this", "Layout" ]
def add(self, x, y, width, height, drawing_function=None, hotspot=None): """Add a new element to this Layout :param x: x coordinate :param y: y coordinate :param width: width :param height: height :param drawing_function: if set, call this function to render the element on a DrawingContext :param hotspot: if set, the hotspot for this element :returns: LayoutRect of the added element """ return self.add_rect(LayoutRect(x, y, width, height), drawing_function, hotspot)
[ "def", "add", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "drawing_function", "=", "None", ",", "hotspot", "=", "None", ")", ":", "return", "self", ".", "add_rect", "(", "LayoutRect", "(", "x", ",", "y", ",", "width", ",", ...
https://github.com/pculture/miro/blob/d8e4594441939514dd2ac29812bf37087bb3aea5/tv/lib/frontends/widgets/cellpack.py#L737-L752
ntoll/drogulus
d74b78d0bf0220b91f075dbd3f9a06c2663b474e
drogulus/dht/validators.py
python
validate_string
(val)
return isinstance(val, str)
Returns a boolean to indicate that a field is a string of some sort.
Returns a boolean to indicate that a field is a string of some sort.
[ "Returns", "a", "boolean", "to", "indicate", "that", "a", "field", "is", "a", "string", "of", "some", "sort", "." ]
def validate_string(val): """ Returns a boolean to indicate that a field is a string of some sort. """ return isinstance(val, str)
[ "def", "validate_string", "(", "val", ")", ":", "return", "isinstance", "(", "val", ",", "str", ")" ]
https://github.com/ntoll/drogulus/blob/d74b78d0bf0220b91f075dbd3f9a06c2663b474e/drogulus/dht/validators.py#L24-L28
dbrgn/RPLCD
e651d9cfc0e24e1ad47fe63cf50d3fec0d751c61
RPLCD/contextmanagers.py
python
cleared
(lcd)
Context manager to clear display before writing. DEPRECATED.
Context manager to clear display before writing. DEPRECATED.
[ "Context", "manager", "to", "clear", "display", "before", "writing", ".", "DEPRECATED", "." ]
def cleared(lcd): """ Context manager to clear display before writing. DEPRECATED. """ warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning) lcd.clear() yield
[ "def", "cleared", "(", "lcd", ")", ":", "warnings", ".", "warn", "(", "'The `cursor` context manager is deprecated'", ",", "DeprecationWarning", ")", "lcd", ".", "clear", "(", ")", "yield" ]
https://github.com/dbrgn/RPLCD/blob/e651d9cfc0e24e1ad47fe63cf50d3fec0d751c61/RPLCD/contextmanagers.py#L19-L25
flennerhag/mlens
6cbc11354b5f9500a33d9cefb700a1bba9d3199a
mlens/externals/joblib/_parallel_backends.py
python
SequentialBackend.effective_n_jobs
(self, n_jobs)
return 1
Determine the number of jobs which are going to run in parallel
Determine the number of jobs which are going to run in parallel
[ "Determine", "the", "number", "of", "jobs", "which", "are", "going", "to", "run", "in", "parallel" ]
def effective_n_jobs(self, n_jobs): """Determine the number of jobs which are going to run in parallel""" if n_jobs == 0: raise ValueError('n_jobs == 0 in Parallel has no meaning') return 1
[ "def", "effective_n_jobs", "(", "self", ",", "n_jobs", ")", ":", "if", "n_jobs", "==", "0", ":", "raise", "ValueError", "(", "'n_jobs == 0 in Parallel has no meaning'", ")", "return", "1" ]
https://github.com/flennerhag/mlens/blob/6cbc11354b5f9500a33d9cefb700a1bba9d3199a/mlens/externals/joblib/_parallel_backends.py#L103-L107
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/queue.py
python
_PySimpleQueue.get_nowait
(self)
return self.get(block=False)
Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception.
Remove and return an item from the queue without blocking.
[ "Remove", "and", "return", "an", "item", "from", "the", "queue", "without", "blocking", "." ]
def get_nowait(self): '''Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. ''' return self.get(block=False)
[ "def", "get_nowait", "(", "self", ")", ":", "return", "self", ".", "get", "(", "block", "=", "False", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/queue.py#L303-L309
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/externaldrive/mac_dev.py
python
ExternalDriveManager.getRemovableDrives
(self)
return self.getDirContents('%s/*' % self.ROOT_MOUNT_POINT, 'usb')
[]
def getRemovableDrives(self): return self.getDirContents('%s/*' % self.ROOT_MOUNT_POINT, 'usb')
[ "def", "getRemovableDrives", "(", "self", ")", ":", "return", "self", ".", "getDirContents", "(", "'%s/*'", "%", "self", ".", "ROOT_MOUNT_POINT", ",", "'usb'", ")" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/externaldrive/mac_dev.py#L31-L32
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/recommendation_service/client.py
python
RecommendationServiceClient.ad_group_path
(customer_id: str, ad_group_id: str,)
return "customers/{customer_id}/adGroups/{ad_group_id}".format( customer_id=customer_id, ad_group_id=ad_group_id, )
Return a fully-qualified ad_group string.
Return a fully-qualified ad_group string.
[ "Return", "a", "fully", "-", "qualified", "ad_group", "string", "." ]
def ad_group_path(customer_id: str, ad_group_id: str,) -> str: """Return a fully-qualified ad_group string.""" return "customers/{customer_id}/adGroups/{ad_group_id}".format( customer_id=customer_id, ad_group_id=ad_group_id, )
[ "def", "ad_group_path", "(", "customer_id", ":", "str", ",", "ad_group_id", ":", "str", ",", ")", "->", "str", ":", "return", "\"customers/{customer_id}/adGroups/{ad_group_id}\"", ".", "format", "(", "customer_id", "=", "customer_id", ",", "ad_group_id", "=", "ad_...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/recommendation_service/client.py#L175-L179
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/core/program.py
python
SimpleProgramSchedule.Params
(cls)
return p
Params for a SimpleProgramSchedule.
Params for a SimpleProgramSchedule.
[ "Params", "for", "a", "SimpleProgramSchedule", "." ]
def Params(cls): """Params for a SimpleProgramSchedule.""" p = hyperparams.InstantiableParams(cls) p.Define('task_dict', None, 'dataset_name -> task params') p.Define('task_name', None, 'High level task name') p.Define('logdir', None, 'Log directory') p.Define('train_program', None, 'Train program params') p.Define('train_executions_per_eval', 1, '') p.Define('eval_programs', [], 'List of eval program params.') p.Define('num_splits_per_client', None, '') p.Define('dataset_names', [], 'List of all dataset names.') p.Define('async_postprocess', True, 'whether to CPU postprocess asynchronously with TPU train') # TODO(blee): Clean these up. p.Define('ml_perf', hyperparams.Params(), 'MlPerf configuration.') mlp = p.ml_perf mlp.Define('submission_metadata', None, 'A dictionary of static submission metadata') mlp.Define('benchmark_name', None, 'Benchmark name for compliance log.') mlp.Define('steps_per_epoch', None, 'Number of training steps per epoch.') mlp.Define('decoder_metric_name', None, 'Name of the decoder metric to report for compliance log.') mlp.Define('decoder_metric_success_threshold', None, 'Benchmark run must exceed this value to succeed.') mlp.Define('max_steps_to_train', None, 'Maximum number of steps to reach target accuracy') return p
[ "def", "Params", "(", "cls", ")", ":", "p", "=", "hyperparams", ".", "InstantiableParams", "(", "cls", ")", "p", ".", "Define", "(", "'task_dict'", ",", "None", ",", "'dataset_name -> task params'", ")", "p", ".", "Define", "(", "'task_name'", ",", "None",...
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/core/program.py#L1649-L1676
rst2pdf/rst2pdf
dac0653f8eb894aa5b83cf0877ca3420cdfaf4b2
rst2pdf/sphinxnodes.py
python
SphinxHandler.__init__
(self)
This is where the magic happens. Make a copy of the elements in the non-sphinx dispatch dictionary, setting sphinxmode on every element, and then overwrite that dictionary with any sphinx-specific handlers.
This is where the magic happens. Make a copy of the elements in the non-sphinx dispatch dictionary, setting sphinxmode on every element, and then overwrite that dictionary with any sphinx-specific handlers.
[ "This", "is", "where", "the", "magic", "happens", ".", "Make", "a", "copy", "of", "the", "elements", "in", "the", "non", "-", "sphinx", "dispatch", "dictionary", "setting", "sphinxmode", "on", "every", "element", "and", "then", "overwrite", "that", "dictiona...
def __init__(self): """This is where the magic happens. Make a copy of the elements in the non-sphinx dispatch dictionary, setting sphinxmode on every element, and then overwrite that dictionary with any sphinx-specific handlers. """ mydict = {} for key, value in self._baseclass.dispatchdict.items(): value = copy(value) value.sphinxmode = True mydict[key] = value mydict.update(self.dispatchdict) self.dispatchdict = mydict
[ "def", "__init__", "(", "self", ")", ":", "mydict", "=", "{", "}", "for", "key", ",", "value", "in", "self", ".", "_baseclass", ".", "dispatchdict", ".", "items", "(", ")", ":", "value", "=", "copy", "(", "value", ")", "value", ".", "sphinxmode", "...
https://github.com/rst2pdf/rst2pdf/blob/dac0653f8eb894aa5b83cf0877ca3420cdfaf4b2/rst2pdf/sphinxnodes.py#L38-L50
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
crio/datadog_checks/crio/config_models/__init__.py
python
ConfigMixin.shared_config
(self)
return self._config_model_shared
[]
def shared_config(self) -> SharedConfig: return self._config_model_shared
[ "def", "shared_config", "(", "self", ")", "->", "SharedConfig", ":", "return", "self", ".", "_config_model_shared" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/crio/datadog_checks/crio/config_models/__init__.py#L23-L24
django/django-localflavor
5d9c3bdc4a6b5e114da2b7226b9b0bcf32757a66
localflavor/fr/forms.py
python
FRNationalIdentificationNumber._check_corsica
(self, commune_of_origin, current_year, department_of_origin, year_of_birth)
Departments number 20, 2A and 2B represent Corsica
Departments number 20, 2A and 2B represent Corsica
[ "Departments", "number", "20", "2A", "and", "2B", "represent", "Corsica" ]
def _check_corsica(self, commune_of_origin, current_year, department_of_origin, year_of_birth): """Departments number 20, 2A and 2B represent Corsica""" # For people born before 1976, Corsica number was 20 if current_year < int(year_of_birth) < 76 and department_of_origin != '20': raise ValidationError(self.error_messages['invalid'], code='invalid') # For people born from 1976, Corsica dep number is either 2A or 2B if (int(year_of_birth) > 75 and department_of_origin not in ['2A', '2B']): raise ValidationError(self.error_messages['invalid'], code='invalid')
[ "def", "_check_corsica", "(", "self", ",", "commune_of_origin", ",", "current_year", ",", "department_of_origin", ",", "year_of_birth", ")", ":", "# For people born before 1976, Corsica number was 20", "if", "current_year", "<", "int", "(", "year_of_birth", ")", "<", "7...
https://github.com/django/django-localflavor/blob/5d9c3bdc4a6b5e114da2b7226b9b0bcf32757a66/localflavor/fr/forms.py#L158-L165
google/deepvariant
9cf1c7b0e2342d013180aa153cba3c9331c9aef7
third_party/nucleus/util/variant_utils.py
python
variant_type
(variant)
Gets the VariantType of variant. Args: variant: nucleus.genomics.v1.Variant. Returns: VariantType indicating the type of this variant.
Gets the VariantType of variant.
[ "Gets", "the", "VariantType", "of", "variant", "." ]
def variant_type(variant): """Gets the VariantType of variant. Args: variant: nucleus.genomics.v1.Variant. Returns: VariantType indicating the type of this variant. """ if is_ref(variant): return VariantType.ref elif is_snp(variant): return VariantType.snp else: return VariantType.indel
[ "def", "variant_type", "(", "variant", ")", ":", "if", "is_ref", "(", "variant", ")", ":", "return", "VariantType", ".", "ref", "elif", "is_snp", "(", "variant", ")", ":", "return", "VariantType", ".", "snp", "else", ":", "return", "VariantType", ".", "i...
https://github.com/google/deepvariant/blob/9cf1c7b0e2342d013180aa153cba3c9331c9aef7/third_party/nucleus/util/variant_utils.py#L332-L346
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/urllib3/contrib/securetransport.py
python
WrappedSocket._set_ciphers
(self)
Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare.
Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare.
[ "Sets", "up", "the", "allowed", "ciphers", ".", "By", "default", "this", "matches", "the", "set", "in", "util", ".", "ssl_", ".", "DEFAULT_CIPHERS", "at", "least", "as", "supported", "by", "macOS", ".", "This", "is", "done", "custom", "and", "doesn", "t"...
def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result)
[ "def", "_set_ciphers", "(", "self", ")", ":", "ciphers", "=", "(", "Security", ".", "SSLCipherSuite", "*", "len", "(", "CIPHER_SUITES", ")", ")", "(", "*", "CIPHER_SUITES", ")", "result", "=", "Security", ".", "SSLSetEnabledCiphers", "(", "self", ".", "con...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/urllib3/contrib/securetransport.py#L335-L346
styxit/HTPC-Manager
490697460b4fa1797106aece27d873bc256b2ff1
libs/cherrypy/_cptools.py
python
SessionTool.regenerate
(self)
Drop the current session and make a new one (with a new id).
Drop the current session and make a new one (with a new id).
[ "Drop", "the", "current", "session", "and", "make", "a", "new", "one", "(", "with", "a", "new", "id", ")", "." ]
def regenerate(self): """Drop the current session and make a new one (with a new id).""" sess = cherrypy.serving.session sess.regenerate() # Grab cookie-relevant tool args conf = dict([(k, v) for k, v in self._merged_args().items() if k in ('path', 'path_header', 'name', 'timeout', 'domain', 'secure')]) _sessions.set_response_cookie(**conf)
[ "def", "regenerate", "(", "self", ")", ":", "sess", "=", "cherrypy", ".", "serving", ".", "session", "sess", ".", "regenerate", "(", ")", "# Grab cookie-relevant tool args", "conf", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", ...
https://github.com/styxit/HTPC-Manager/blob/490697460b4fa1797106aece27d873bc256b2ff1/libs/cherrypy/_cptools.py#L305-L314
tgalal/python-axolotl
b8d1a2e04bda38575dc5c0c6daf1b545283e31d7
axolotl/groups/groupsessionbuilder.py
python
GroupSessionBuilder.create
(self, senderKeyName)
:type senderKeyName: SenderKeyName
:type senderKeyName: SenderKeyName
[ ":", "type", "senderKeyName", ":", "SenderKeyName" ]
def create(self, senderKeyName): """ :type senderKeyName: SenderKeyName """ try: senderKeyRecord = self.senderKeyStore.loadSenderKey(senderKeyName); if senderKeyRecord.isEmpty() : senderKeyRecord.setSenderKeyState(KeyHelper.generateSenderKeyId(), 0, KeyHelper.generateSenderKey(), KeyHelper.generateSenderSigningKey()); self.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord); state = senderKeyRecord.getSenderKeyState(); return SenderKeyDistributionMessage(state.getKeyId(), state.getSenderChainKey().getIteration(), state.getSenderChainKey().getSeed(), state.getSigningKeyPublic()); except (InvalidKeyException, InvalidKeyIdException) as e: raise AssertionError(e)
[ "def", "create", "(", "self", ",", "senderKeyName", ")", ":", "try", ":", "senderKeyRecord", "=", "self", ".", "senderKeyStore", ".", "loadSenderKey", "(", "senderKeyName", ")", "if", "senderKeyRecord", ".", "isEmpty", "(", ")", ":", "senderKeyRecord", ".", ...
https://github.com/tgalal/python-axolotl/blob/b8d1a2e04bda38575dc5c0c6daf1b545283e31d7/axolotl/groups/groupsessionbuilder.py#L23-L44
wrye-bash/wrye-bash
d495c47cfdb44475befa523438a40c4419cb386f
Mopy/bash/bolt.py
python
Path.psize
(self)
Size of file or directory.
Size of file or directory.
[ "Size", "of", "file", "or", "directory", "." ]
def psize(self): """Size of file or directory.""" if self.is_dir(): join = os.path.join op_size = os.path.getsize try: return sum(sum(op_size(join(x, f)) for f in files) for x, _y, files in os.walk(self._s)) except ValueError: return 0 else: return os.path.getsize(self._s)
[ "def", "psize", "(", "self", ")", ":", "if", "self", ".", "is_dir", "(", ")", ":", "join", "=", "os", ".", "path", ".", "join", "op_size", "=", "os", ".", "path", ".", "getsize", "try", ":", "return", "sum", "(", "sum", "(", "op_size", "(", "jo...
https://github.com/wrye-bash/wrye-bash/blob/d495c47cfdb44475befa523438a40c4419cb386f/Mopy/bash/bolt.py#L676-L687
janrueth/SiriServerCore
dcc028c1fdddcc362e484b9ad655420ce953c8d2
biplist/__init__.py
python
PlistWriter.writeObjectReference
(self, obj, output)
Tries to write an object reference, adding it to the references table. Does not write the actual object bytes or set the reference position. Returns a tuple of whether the object was a new reference (True if it was, False if it already was in the reference table) and the new output.
Tries to write an object reference, adding it to the references table. Does not write the actual object bytes or set the reference position. Returns a tuple of whether the object was a new reference (True if it was, False if it already was in the reference table) and the new output.
[ "Tries", "to", "write", "an", "object", "reference", "adding", "it", "to", "the", "references", "table", ".", "Does", "not", "write", "the", "actual", "object", "bytes", "or", "set", "the", "reference", "position", ".", "Returns", "a", "tuple", "of", "whet...
def writeObjectReference(self, obj, output): """Tries to write an object reference, adding it to the references table. Does not write the actual object bytes or set the reference position. Returns a tuple of whether the object was a new reference (True if it was, False if it already was in the reference table) and the new output. """ position = self.positionOfObjectReference(obj) if position is None: self.writtenReferences[obj] = len(self.writtenReferences) output += self.binaryInt(len(self.writtenReferences) - 1, bytes=self.trailer.objectRefSize) return (True, output) else: output += self.binaryInt(position, bytes=self.trailer.objectRefSize) return (False, output)
[ "def", "writeObjectReference", "(", "self", ",", "obj", ",", "output", ")", ":", "position", "=", "self", ".", "positionOfObjectReference", "(", "obj", ")", "if", "position", "is", "None", ":", "self", ".", "writtenReferences", "[", "obj", "]", "=", "len",...
https://github.com/janrueth/SiriServerCore/blob/dcc028c1fdddcc362e484b9ad655420ce953c8d2/biplist/__init__.py#L535-L549
bmuller/twistar
1eb46ff2577473e0a26932ee57473e26203a3db2
twistar/dbobject.py
python
DBObject.beforeDelete
(self)
Method called before a L{DBObject} is deleted. Classes can overwrite this method. If False is returned, then the L{DBObject} is not deleted from database. This method may return a C{Deferred}.
Method called before a L{DBObject} is deleted. Classes can overwrite this method. If False is returned, then the L{DBObject} is not deleted from database. This method may return a C{Deferred}.
[ "Method", "called", "before", "a", "L", "{", "DBObject", "}", "is", "deleted", ".", "Classes", "can", "overwrite", "this", "method", ".", "If", "False", "is", "returned", "then", "the", "L", "{", "DBObject", "}", "is", "not", "deleted", "from", "database...
def beforeDelete(self): """ Method called before a L{DBObject} is deleted. Classes can overwrite this method. If False is returned, then the L{DBObject} is not deleted from database. This method may return a C{Deferred}. """
[ "def", "beforeDelete", "(", "self", ")", ":" ]
https://github.com/bmuller/twistar/blob/1eb46ff2577473e0a26932ee57473e26203a3db2/twistar/dbobject.py#L169-L174
pyglet/pyglet
2833c1df902ca81aeeffa786c12e7e87d402434b
pyglet/shapes.py
python
Triangle.x2
(self)
return self._x2
Second X coordinate of the shape. :type: int or float
Second X coordinate of the shape.
[ "Second", "X", "coordinate", "of", "the", "shape", "." ]
def x2(self): """Second X coordinate of the shape. :type: int or float """ return self._x2
[ "def", "x2", "(", "self", ")", ":", "return", "self", ".", "_x2" ]
https://github.com/pyglet/pyglet/blob/2833c1df902ca81aeeffa786c12e7e87d402434b/pyglet/shapes.py#L1248-L1253
gxcuizy/Python
72167d12439a615a8fd4b935eae1fb6516ed4e69
从零学Python-掘金活动/day07/juejin_poins.py
python
save_avatar
(object_id, pictures)
下载用户头像
下载用户头像
[ "下载用户头像" ]
def save_avatar(object_id, pictures): """下载用户头像""" # 拼接图片路径 path = os.path.join('.', object_id) # 图片名称 img_name = 'avatar.jpg' img_path = os.path.join(path, img_name) print('开始下载图片:' + img_path) with open(img_path, 'wb') as img: # 下载图片 img_re = requests.get(pictures) img.write(img_re.content) print('下载图片完毕!')
[ "def", "save_avatar", "(", "object_id", ",", "pictures", ")", ":", "# 拼接图片路径", "path", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "object_id", ")", "# 图片名称", "img_name", "=", "'avatar.jpg'", "img_path", "=", "os", ".", "path", ".", "join", "...
https://github.com/gxcuizy/Python/blob/72167d12439a615a8fd4b935eae1fb6516ed4e69/从零学Python-掘金活动/day07/juejin_poins.py#L69-L81
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/xml/sax/saxutils.py
python
escape
(data, entities={})
return data
Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value.
Escape &, <, and > in a string of data.
[ "Escape", "&", "<", "and", ">", "in", "a", "string", "of", "data", "." ]
def escape(data, entities={}): """Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ # must do ampersand first data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") if entities: data = __dict_replace(data, entities) return data
[ "def", "escape", "(", "data", ",", "entities", "=", "{", "}", ")", ":", "# must do ampersand first", "data", "=", "data", ".", "replace", "(", "\"&\"", ",", "\"&amp;\"", ")", "data", "=", "data", ".", "replace", "(", "\">\"", ",", "\"&gt;\"", ")", "dat...
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/xml/sax/saxutils.py#L23-L37
craigmacartney/Wave-U-Net-For-Speech-Enhancement
c8ccbd286cbe73d7539e5703e4407762304e3068
Models/UnetAudioSeparator.py
python
UnetAudioSeparator.get_padding
(self, shape)
Calculates the required amounts of padding along each axis of the input and output, so that the Unet works and has the given shape as output shape :param shape: Desired output shape :return: Input_shape, output_shape, where each is a list [batch_size, time_steps, channels]
Calculates the required amounts of padding along each axis of the input and output, so that the Unet works and has the given shape as output shape :param shape: Desired output shape :return: Input_shape, output_shape, where each is a list [batch_size, time_steps, channels]
[ "Calculates", "the", "required", "amounts", "of", "padding", "along", "each", "axis", "of", "the", "input", "and", "output", "so", "that", "the", "Unet", "works", "and", "has", "the", "given", "shape", "as", "output", "shape", ":", "param", "shape", ":", ...
def get_padding(self, shape): ''' Calculates the required amounts of padding along each axis of the input and output, so that the Unet works and has the given shape as output shape :param shape: Desired output shape :return: Input_shape, output_shape, where each is a list [batch_size, time_steps, channels] ''' if self.context: # Check if desired shape is possible as output shape - go from output shape towards lowest-res feature map rem = float(shape[1]) # Cut off batch size number and channel #rem = rem + self.filter_size - 1 for i in range(self.num_layers): rem = rem + self.merge_filter_size - 1 rem = (rem + 1.) / 2.# out = in + in - 1 <=> in = (out+1)/ # Round resulting feature map dimensions up to nearest integer x = np.asarray(np.ceil(rem),dtype=np.int64) assert(x >= 2) # Compute input and output shapes based on lowest-res feature map output_shape = x input_shape = x # Extra conv input_shape = input_shape + self.filter_size - 1 # Go from centre feature map through up- and downsampling blocks for i in range(self.num_layers): output_shape = 2*output_shape - 1 #Upsampling output_shape = output_shape - self.merge_filter_size + 1 # Conv input_shape = 2*input_shape - 1 # Decimation input_shape = input_shape + self.filter_size - 1 # Conv input_shape = np.concatenate([[shape[0]], [input_shape], [self.num_channels]]) output_shape = np.concatenate([[shape[0]], [output_shape], [self.num_channels]]) return input_shape, output_shape else: return [shape[0], shape[1], self.num_channels], [shape[0], shape[1], self.num_channels]
[ "def", "get_padding", "(", "self", ",", "shape", ")", ":", "if", "self", ".", "context", ":", "# Check if desired shape is possible as output shape - go from output shape towards lowest-res feature map", "rem", "=", "float", "(", "shape", "[", "1", "]", ")", "# Cut off ...
https://github.com/craigmacartney/Wave-U-Net-For-Speech-Enhancement/blob/c8ccbd286cbe73d7539e5703e4407762304e3068/Models/UnetAudioSeparator.py#L30-L70
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/musicxml/m21ToXml.py
python
ScoreExporter.setScoreLayouts
(self)
sets `self.scoreLayouts` and `self.firstScoreLayout` >>> b = corpus.parse('schoenberg/opus19', 2) >>> SX = musicxml.m21ToXml.ScoreExporter(b) >>> SX.setScoreLayouts() >>> SX.scoreLayouts <music21.stream.Score 0x...> >>> len(SX.scoreLayouts) 1 >>> SX.firstScoreLayout <music21.layout.ScoreLayout>
sets `self.scoreLayouts` and `self.firstScoreLayout`
[ "sets", "self", ".", "scoreLayouts", "and", "self", ".", "firstScoreLayout" ]
def setScoreLayouts(self): ''' sets `self.scoreLayouts` and `self.firstScoreLayout` >>> b = corpus.parse('schoenberg/opus19', 2) >>> SX = musicxml.m21ToXml.ScoreExporter(b) >>> SX.setScoreLayouts() >>> SX.scoreLayouts <music21.stream.Score 0x...> >>> len(SX.scoreLayouts) 1 >>> SX.firstScoreLayout <music21.layout.ScoreLayout> ''' s = self.stream scoreLayouts = s.getElementsByClass('ScoreLayout').stream() if scoreLayouts: scoreLayout = scoreLayouts[0] else: scoreLayout = None self.scoreLayouts = scoreLayouts self.firstScoreLayout = scoreLayout
[ "def", "setScoreLayouts", "(", "self", ")", ":", "s", "=", "self", ".", "stream", "scoreLayouts", "=", "s", ".", "getElementsByClass", "(", "'ScoreLayout'", ")", ".", "stream", "(", ")", "if", "scoreLayouts", ":", "scoreLayout", "=", "scoreLayouts", "[", "...
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/musicxml/m21ToXml.py#L1599-L1620
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/contrib/admin/options.py
python
ModelAdmin.get_fieldsets
(self, request, obj=None)
return [(None, {'fields': fields})]
Hook for specifying fieldsets for the add form.
Hook for specifying fieldsets for the add form.
[ "Hook", "for", "specifying", "fieldsets", "for", "the", "add", "form", "." ]
def get_fieldsets(self, request, obj=None): "Hook for specifying fieldsets for the add form." if self.declared_fieldsets: return self.declared_fieldsets form = self.get_form(request, obj) fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj)) return [(None, {'fields': fields})]
[ "def", "get_fieldsets", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "if", "self", ".", "declared_fieldsets", ":", "return", "self", ".", "declared_fieldsets", "form", "=", "self", ".", "get_form", "(", "request", ",", "obj", ")", "fie...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/admin/options.py#L399-L405
pySTEPS/pysteps
bd9478538249e1d64036a721ceb934085d6e1da9
pysteps/io/exporters.py
python
export_forecast_dataset
(field, exporter)
Write a forecast array into a file. If the exporter was initialized with n_ens_members>1, the written dataset has dimensions (n_ens_members,num_timesteps,shape[0],shape[1]), where shape refers to the shape of the two-dimensional forecast grids. Otherwise, the dimensions are (num_timesteps,shape[0],shape[1]). If the exporter was initialized with incremental!=None, the array is appended to the existing dataset either along the ensemble member or time axis. Parameters ---------- exporter: dict An exporter object created with any initialization method implemented in :py:mod:`pysteps.io.exporters`. field: array_like The array to write. The required shape depends on the choice of the 'incremental' parameter the exporter was initialized with: +-----------------+---------------------------------------------------+ | incremental | required shape | +=================+===================================================+ | None | (num_ens_members,num_timesteps,shape[0],shape[1]) | +-----------------+---------------------------------------------------+ | 'timestep' | (num_ens_members,shape[0],shape[1]) | +-----------------+---------------------------------------------------+ | 'member' | (num_timesteps,shape[0],shape[1]) | +-----------------+---------------------------------------------------+ If the exporter was initialized with num_ens_members=1, the num_ens_members dimension is dropped.
Write a forecast array into a file.
[ "Write", "a", "forecast", "array", "into", "a", "file", "." ]
def export_forecast_dataset(field, exporter): """Write a forecast array into a file. If the exporter was initialized with n_ens_members>1, the written dataset has dimensions (n_ens_members,num_timesteps,shape[0],shape[1]), where shape refers to the shape of the two-dimensional forecast grids. Otherwise, the dimensions are (num_timesteps,shape[0],shape[1]). If the exporter was initialized with incremental!=None, the array is appended to the existing dataset either along the ensemble member or time axis. Parameters ---------- exporter: dict An exporter object created with any initialization method implemented in :py:mod:`pysteps.io.exporters`. field: array_like The array to write. The required shape depends on the choice of the 'incremental' parameter the exporter was initialized with: +-----------------+---------------------------------------------------+ | incremental | required shape | +=================+===================================================+ | None | (num_ens_members,num_timesteps,shape[0],shape[1]) | +-----------------+---------------------------------------------------+ | 'timestep' | (num_ens_members,shape[0],shape[1]) | +-----------------+---------------------------------------------------+ | 'member' | (num_timesteps,shape[0],shape[1]) | +-----------------+---------------------------------------------------+ If the exporter was initialized with num_ens_members=1, the num_ens_members dimension is dropped. """ if exporter["method"] == "netcdf" and not NETCDF4_IMPORTED: raise MissingOptionalDependency( "netCDF4 package is required for netcdf " "exporters but it is not installed" ) if exporter["incremental"] is None: if exporter["num_ens_members"] > 1: shp = ( exporter["num_ens_members"], exporter["num_timesteps"], exporter["shape"][0], exporter["shape"][1], ) else: shp = ( exporter["num_timesteps"], exporter["shape"][0], exporter["shape"][1], ) if field.shape != shp: raise ValueError( "field has invalid shape: %s != %s" % (str(field.shape), str(shp)) ) elif exporter["incremental"] == "timestep": if exporter["num_ens_members"] > 1: shp = ( exporter["num_ens_members"], exporter["shape"][0], exporter["shape"][1], ) else: shp = exporter["shape"] if field.shape != shp: raise ValueError( "field has invalid shape: %s != %s" % (str(field.shape), str(shp)) ) elif exporter["incremental"] == "member": shp = (exporter["num_timesteps"], exporter["shape"][0], exporter["shape"][1]) if field.shape != shp: raise ValueError( "field has invalid shape: %s != %s" % (str(field.shape), str(shp)) ) if exporter["method"] == "geotiff": _export_geotiff(field, exporter) elif exporter["method"] == "netcdf": _export_netcdf(field, exporter) elif exporter["method"] == "kineros": _export_kineros(field, exporter) else: raise ValueError("unknown exporter method %s" % exporter["method"])
[ "def", "export_forecast_dataset", "(", "field", ",", "exporter", ")", ":", "if", "exporter", "[", "\"method\"", "]", "==", "\"netcdf\"", "and", "not", "NETCDF4_IMPORTED", ":", "raise", "MissingOptionalDependency", "(", "\"netCDF4 package is required for netcdf \"", "\"e...
https://github.com/pySTEPS/pysteps/blob/bd9478538249e1d64036a721ceb934085d6e1da9/pysteps/io/exporters.py#L595-L679
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/docutils/utils/math/math2html.py
python
Position.next
(self)
return self.current()
Advance the position and return the next character.
Advance the position and return the next character.
[ "Advance", "the", "position", "and", "return", "the", "next", "character", "." ]
def next(self): "Advance the position and return the next character." self.skipcurrent() return self.current()
[ "def", "next", "(", "self", ")", ":", "self", ".", "skipcurrent", "(", ")", "return", "self", ".", "current", "(", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/docutils/utils/math/math2html.py#L1962-L1965
simpeg/simpeg
d93145d768b5512621cdd75566b4a8175fee9ed3
SimPEG/electromagnetics/utils/analytic_utils.py
python
MagneticLoopVectorPotential
( srcLoc, obsLoc, component, radius, orientation="Z", mu=mu_0 )
This code has been deprecated after SimPEG 0.11.5. Please use geoana instead. " .. code:: >> pip install geoana >> from geoana.electromagnetics.static import MagneticDipoleWholeSpace
This code has been deprecated after SimPEG 0.11.5. Please use geoana instead. "
[ "This", "code", "has", "been", "deprecated", "after", "SimPEG", "0", ".", "11", ".", "5", ".", "Please", "use", "geoana", "instead", "." ]
def MagneticLoopVectorPotential( srcLoc, obsLoc, component, radius, orientation="Z", mu=mu_0 ): """ This code has been deprecated after SimPEG 0.11.5. Please use geoana instead. " .. code:: >> pip install geoana >> from geoana.electromagnetics.static import MagneticDipoleWholeSpace """ raise Exception( "This code has been deprecated after SimPEG 0.11.5. " "Please use geoana instead. " "\n >> pip install geoana " "\n >> from geoana.electromagnetics.static import CircularLoopWholeSpace" )
[ "def", "MagneticLoopVectorPotential", "(", "srcLoc", ",", "obsLoc", ",", "component", ",", "radius", ",", "orientation", "=", "\"Z\"", ",", "mu", "=", "mu_0", ")", ":", "raise", "Exception", "(", "\"This code has been deprecated after SimPEG 0.11.5. \"", "\"Please use...
https://github.com/simpeg/simpeg/blob/d93145d768b5512621cdd75566b4a8175fee9ed3/SimPEG/electromagnetics/utils/analytic_utils.py#L53-L70
Wramberg/TerminalView
b0856fa62c1fdd3ad968bf6b8aaa344962b65adf
pyte/screens.py
python
Screen.carriage_return
(self)
Move the cursor to the beginning of the current line.
Move the cursor to the beginning of the current line.
[ "Move", "the", "cursor", "to", "the", "beginning", "of", "the", "current", "line", "." ]
def carriage_return(self): """Move the cursor to the beginning of the current line.""" self.cursor.x = 0
[ "def", "carriage_return", "(", "self", ")", ":", "self", ".", "cursor", ".", "x", "=", "0" ]
https://github.com/Wramberg/TerminalView/blob/b0856fa62c1fdd3ad968bf6b8aaa344962b65adf/pyte/screens.py#L454-L456
freedombox/FreedomBox
335a7f92cc08f27981f838a7cddfc67740598e54
plinth/modules/upgrades/__init__.py
python
can_activate_backports
()
return True
Return whether backports can be activated.
Return whether backports can be activated.
[ "Return", "whether", "backports", "can", "be", "activated", "." ]
def can_activate_backports(): """Return whether backports can be activated.""" release, _ = get_current_release() if release == 'unstable' or (release == 'testing' and not cfg.develop): return False return True
[ "def", "can_activate_backports", "(", ")", ":", "release", ",", "_", "=", "get_current_release", "(", ")", "if", "release", "==", "'unstable'", "or", "(", "release", "==", "'testing'", "and", "not", "cfg", ".", "develop", ")", ":", "return", "False", "retu...
https://github.com/freedombox/FreedomBox/blob/335a7f92cc08f27981f838a7cddfc67740598e54/plinth/modules/upgrades/__init__.py#L296-L302
fab-jul/imgcomp-cvpr
f03ce0bfa846f7ba1bf9b7ba415b082efe5c192c
code/train.py
python
Distortions.get_ms_ssim
(inp, otp)
[]
def get_ms_ssim(inp, otp): with tf.name_scope('mean_MS_SSIM'): return ms_ssim.MultiScaleSSIM(inp, otp, data_format='NCHW', name='MS-SSIM')
[ "def", "get_ms_ssim", "(", "inp", ",", "otp", ")", ":", "with", "tf", ".", "name_scope", "(", "'mean_MS_SSIM'", ")", ":", "return", "ms_ssim", ".", "MultiScaleSSIM", "(", "inp", ",", "otp", ",", "data_format", "=", "'NCHW'", ",", "name", "=", "'MS-SSIM'"...
https://github.com/fab-jul/imgcomp-cvpr/blob/f03ce0bfa846f7ba1bf9b7ba415b082efe5c192c/code/train.py#L429-L431
PINTO0309/PINTO_model_zoo
2924acda7a7d541d8712efd7cc4fd1c61ef5bddd
105_MobileStyleGAN/saved_model_to_tflite.py
python
convert
(saved_model_dir_path, signature_def, input_shapes, model_output_dir_path, output_no_quant_float32_tflite, output_weight_quant_tflite, output_float16_quant_tflite, output_integer_quant_tflite, output_full_integer_quant_tflite, output_integer_quant_type, string_formulas_for_normalization, calib_ds_type, ds_name_for_tfds_for_calibration, split_name_for_tfds_for_calibration, download_dest_folder_path_for_the_calib_tfds, tfds_download_flg, npy_load_default_path, load_dest_file_path_for_the_calib_npy, output_tfjs, output_tftrt, output_coreml, output_edgetpu, output_onnx, onnx_opset)
[]
def convert(saved_model_dir_path, signature_def, input_shapes, model_output_dir_path, output_no_quant_float32_tflite, output_weight_quant_tflite, output_float16_quant_tflite, output_integer_quant_tflite, output_full_integer_quant_tflite, output_integer_quant_type, string_formulas_for_normalization, calib_ds_type, ds_name_for_tfds_for_calibration, split_name_for_tfds_for_calibration, download_dest_folder_path_for_the_calib_tfds, tfds_download_flg, npy_load_default_path, load_dest_file_path_for_the_calib_npy, output_tfjs, output_tftrt, output_coreml, output_edgetpu, output_onnx, onnx_opset): print(f'{Color.REVERCE}Start conversion process from saved_model to tflite{Color.RESET}', '=' * 38) import subprocess import tensorflow as tf tf.get_logger().setLevel('INFO') tf.autograph.set_verbosity(0) tf.get_logger().setLevel(logging.ERROR) import tensorflow_datasets as tfds from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph # Load saved_model and change input shape # https://github.com/tensorflow/tensorflow/issues/30180#issuecomment-505959220 model = tf.saved_model.load(saved_model_dir_path) if signature_def: concrete_func = model.signatures[signature_def] else: concrete_func = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY] if input_shapes: concrete_func_input_tensors = [tensor for tensor in concrete_func.inputs if tensor.dtype != tf.resource and not 'unknown' in tensor.name] for conc_input, def_input in zip(concrete_func_input_tensors, input_shapes): print('Before changing the input shape', conc_input) conc_input.set_shape(def_input) print('After changing the input shape', conc_input) else: concrete_func_input_tensors = [tensor for tensor in concrete_func.inputs if tensor.dtype != tf.resource and not 'unknown' in tensor.name] for conc_input in concrete_func_input_tensors: input_shapes.append(conc_input.shape.as_list()) # No Quantization - Input/Output=float32 if output_no_quant_float32_tflite: try: print(f'{Color.REVERCE}tflite Float32 convertion started{Color.RESET}', '=' * 51) converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func]) converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] tflite_model = converter.convert() with open(f'{model_output_dir_path}/model_float32.tflite', 'wb') as w: w.write(tflite_model) print(f'{Color.GREEN}tflite Float32 convertion complete!{Color.RESET} - {model_output_dir_path}/model_float32.tflite') except Exception as e: print(f'{Color.RED}ERROR:{Color.RESET}', e) import traceback traceback.print_exc() # Weight Quantization - Input/Output=float32 if output_weight_quant_tflite: try: print(f'{Color.REVERCE}Weight Quantization started{Color.RESET}', '=' * 57) converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func]) converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] tflite_model = converter.convert() with open(f'{model_output_dir_path}/model_weight_quant.tflite', 'wb') as w: w.write(tflite_model) print(f'{Color.GREEN}Weight Quantization complete!{Color.RESET} - {model_output_dir_path}/model_weight_quant.tflite') except Exception as e: print(f'{Color.RED}ERROR:{Color.RESET}', e) import traceback traceback.print_exc() # Float16 Quantization - Input/Output=float32 if output_float16_quant_tflite: try: print(f'{Color.REVERCE}Float16 Quantization started{Color.RESET}', '=' * 56) converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func]) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_types = [tf.float16] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] tflite_quant_model = converter.convert() with open(f'{model_output_dir_path}/model_float16_quant.tflite', 'wb') as w: w.write(tflite_quant_model) print(f'{Color.GREEN}Float16 Quantization complete!{Color.RESET} - {model_output_dir_path}/model_float16_quant.tflite') except Exception as e: print(f'{Color.RED}ERROR:{Color.RESET}', e) import traceback traceback.print_exc() # Downloading datasets for calibration raw_test_data = None if output_integer_quant_tflite or output_full_integer_quant_tflite: if calib_ds_type == 'tfds': print(f'{Color.REVERCE}TFDS download started{Color.RESET}', '=' * 63) raw_test_data = tfds.load(name=ds_name_for_tfds_for_calibration, with_info=False, split=split_name_for_tfds_for_calibration, data_dir=download_dest_folder_path_for_the_calib_tfds, download=tfds_download_flg) print(f'{Color.GREEN}TFDS download complete!{Color.RESET}') elif calib_ds_type == 'numpy': print(f'{Color.REVERCE}numpy dataset load started{Color.RESET}', '=' * 58) try: if load_dest_file_path_for_the_calib_npy == npy_load_default_path and not os.path.exists(npy_load_default_path): os.makedirs(os.path.dirname(npy_load_default_path), exist_ok=True) import gdown import subprocess try: result = subprocess.check_output(['gdown', '--id', '1z-K0KZCK3JBH9hXFuBTmIM4jaMPOubGN', '-O', load_dest_file_path_for_the_calib_npy], stderr=subprocess.PIPE).decode('utf-8') except: result = subprocess.check_output(['sudo', 'gdown', '--id', '1z-K0KZCK3JBH9hXFuBTmIM4jaMPOubGN', '-O', load_dest_file_path_for_the_calib_npy], stderr=subprocess.PIPE).decode('utf-8') raw_test_data = np.load(load_dest_file_path_for_the_calib_npy) print(f'{Color.GREEN}numpy dataset load complete!{Color.RESET}') except subprocess.CalledProcessError as e: print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8')) import traceback traceback.print_exc() else: pass def representative_dataset_gen(): if calib_ds_type == 'tfds': for data in raw_test_data.take(10): image = data['image'].numpy() images = [] for shape in input_shapes: data = tf.image.resize(image, (shape[1], shape[2])) tmp_image = eval(string_formulas_for_normalization) # Default: (data - [127.5,127.5,127.5]) / [127.5,127.5,127.5] tmp_image = tmp_image[np.newaxis,:,:,:] images.append(tmp_image) yield images elif calib_ds_type == 'numpy': # for idx in range(raw_test_data.shape[0]): # image = raw_test_data[idx] # images = [] # for shape in input_shapes: # data = tf.image.resize(image, (shape[1], shape[2])) # tmp_image = eval(string_formulas_for_normalization) # Default: (data - [127.5,127.5,127.5]) / [127.5,127.5,127.5] # tmp_image = tmp_image[np.newaxis,:,:,:] # images.append(tmp_image) # yield images for idx in range(10): data = tf.random.uniform([1,512]) yield [data] # Integer Quantization if output_integer_quant_tflite: try: print(f'{Color.REVERCE}Integer Quantization started{Color.RESET}', '=' * 56) converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func]) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS] converter.representative_dataset = representative_dataset_gen tflite_model = converter.convert() with open(f'{model_output_dir_path}/model_integer_quant.tflite', 'wb') as w: w.write(tflite_model) print(f'{Color.GREEN}Integer Quantization complete!{Color.RESET} - {model_output_dir_path}/model_integer_quant.tflite') except Exception as e: print(f'{Color.RED}ERROR:{Color.RESET}', e) import traceback traceback.print_exc() # Full Integer Quantization if output_full_integer_quant_tflite: try: print(f'{Color.REVERCE}Full Integer Quantization started{Color.RESET}', '=' * 51) converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func]) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS] inf_type = None if output_integer_quant_type == 'int8': inf_type = tf.int8 elif output_integer_quant_type == 'uint8': inf_type = tf.uint8 else: inf_type = tf.int8 converter.inference_input_type = inf_type converter.inference_output_type = inf_type converter.representative_dataset = representative_dataset_gen tflite_model = converter.convert() with open(f'{model_output_dir_path}/model_full_integer_quant.tflite', 'wb') as w: w.write(tflite_model) print(f'{Color.GREEN}Full Integer Quantization complete!{Color.RESET} - {model_output_dir_path}/model_full_integer_quant.tflite') except Exception as e: print(f'{Color.RED}ERROR:{Color.RESET}', e) import traceback traceback.print_exc() # EdgeTPU convert if output_edgetpu: try: print(f'{Color.REVERCE}EdgeTPU convertion started{Color.RESET}', '=' * 58) result = subprocess.check_output(['edgetpu_compiler', '-o', model_output_dir_path, '-s', f'{model_output_dir_path}/model_full_integer_quant.tflite'], stderr=subprocess.PIPE).decode('utf-8') print(result) print(f'{Color.GREEN}EdgeTPU convert complete!{Color.RESET} - {model_output_dir_path}/model_full_integer_quant_edgetpu.tflite') except subprocess.CalledProcessError as e: print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8')) import traceback traceback.print_exc() print("-" * 80) print('Please install edgetpu_compiler according to the following website.') print('https://coral.ai/docs/edgetpu/compiler/#system-requirements') # TensorFlow.js convert if output_tfjs: import subprocess try: print(f'{Color.REVERCE}TensorFlow.js Float32 convertion started{Color.RESET}', '=' * 44) result = subprocess.check_output(['tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', '--signature_name', 'serving_default', '--saved_model_tags', 'serve', saved_model_dir_path, f'{model_output_dir_path}/tfjs_model_float32'], stderr=subprocess.PIPE).decode('utf-8') print(result) print(f'{Color.GREEN}TensorFlow.js convertion complete!{Color.RESET} - {model_output_dir_path}/tfjs_model_float32') except subprocess.CalledProcessError as e: print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8')) import traceback traceback.print_exc() try: print(f'{Color.REVERCE}TensorFlow.js Float16 convertion started{Color.RESET}', '=' * 44) result = subprocess.check_output(['tensorflowjs_converter', '--quantize_float16', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', '--signature_name', 'serving_default', '--saved_model_tags', 'serve', saved_model_dir_path, f'{model_output_dir_path}/tfjs_model_float16'], stderr=subprocess.PIPE).decode('utf-8') print(result) print(f'{Color.GREEN}TensorFlow.js convertion complete!{Color.RESET} - {model_output_dir_path}/tfjs_model_float16') except subprocess.CalledProcessError as e: print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8')) import traceback traceback.print_exc() # TF-TRT (TensorRT) convert if output_tftrt: try: def input_fn(): input_shapes_tmp = [] for tf_input in input_shapes: input_shapes_tmp.append(np.zeros(tf_input).astype(np.float32)) yield input_shapes_tmp print(f'{Color.REVERCE}TF-TRT (TensorRT) Float32 convertion started{Color.RESET}', '=' * 40) params = tf.experimental.tensorrt.ConversionParams(precision_mode='FP32', maximum_cached_engines=10000) converter = tf.experimental.tensorrt.Converter(input_saved_model_dir=saved_model_dir_path, conversion_params=params) converter.convert() converter.build(input_fn=input_fn) converter.save(f'{model_output_dir_path}/tensorrt_saved_model_float32') print(f'{Color.GREEN}TF-TRT (TensorRT) convertion complete!{Color.RESET} - {model_output_dir_path}/tensorrt_saved_model_float32') print(f'{Color.REVERCE}TF-TRT (TensorRT) Float16 convertion started{Color.RESET}', '=' * 40) params = tf.experimental.tensorrt.ConversionParams(precision_mode='FP16', maximum_cached_engines=10000) converter = tf.experimental.tensorrt.Converter(input_saved_model_dir=saved_model_dir_path, conversion_params=params) converter.convert() converter.build(input_fn=input_fn) converter.save(f'{model_output_dir_path}/tensorrt_saved_model_float16') print(f'{Color.GREEN}TF-TRT (TensorRT) convertion complete!{Color.RESET} - {model_output_dir_path}/tensorrt_saved_model_float16') except Exception as e: print(f'{Color.RED}ERROR:{Color.RESET}', e) import traceback traceback.print_exc() print(f'{Color.RED}The binary versions of TensorFlow and TensorRT may not be compatible. Please check the version compatibility of each package.{Color.RESET}') # CoreML convert if output_coreml: try: import coremltools as ct print(f'{Color.REVERCE}CoreML convertion started{Color.RESET}', '=' * 59) mlmodel = ct.convert(saved_model_dir_path, source='tensorflow') mlmodel.save(f'{model_output_dir_path}/model_coreml_float32.mlmodel') print(f'{Color.GREEN}CoreML convertion complete!{Color.RESET} - {model_output_dir_path}/model_coreml_float32.mlmodel') except Exception as e: print(f'{Color.RED}ERROR:{Color.RESET}', e) import traceback traceback.print_exc() # ONNX convert if output_onnx: import subprocess try: print(f'{Color.REVERCE}ONNX convertion started{Color.RESET}', '=' * 61) result = subprocess.check_output(['python3', '-m', 'tf2onnx.convert', '--saved-model', model_output_dir_path, '--opset', str(onnx_opset), '--output', f'{model_output_dir_path}/model_float32.onnx'], stderr=subprocess.PIPE).decode('utf-8') print(result) print(f'{Color.GREEN}ONNX convertion complete!{Color.RESET} - {model_output_dir_path}/model_float32.onnx') except subprocess.CalledProcessError as e: print(f'{Color.RED}ERROR:{Color.RESET}', e.stderr.decode('utf-8')) import traceback traceback.print_exc()
[ "def", "convert", "(", "saved_model_dir_path", ",", "signature_def", ",", "input_shapes", ",", "model_output_dir_path", ",", "output_no_quant_float32_tflite", ",", "output_weight_quant_tflite", ",", "output_float16_quant_tflite", ",", "output_integer_quant_tflite", ",", "output...
https://github.com/PINTO0309/PINTO_model_zoo/blob/2924acda7a7d541d8712efd7cc4fd1c61ef5bddd/105_MobileStyleGAN/saved_model_to_tflite.py#L40-L358
p/redis-dump-load
d5affcb9c140e55da738de4f18b360282fb0f9e0
redisdl.py
python
load_streaming
(fp, host='localhost', port=6379, password=None, db=0, empty=False, unix_socket_path=None, encoding='utf-8', use_expireat=False, streaming_backend=None, )
[]
def load_streaming(fp, host='localhost', port=6379, password=None, db=0, empty=False, unix_socket_path=None, encoding='utf-8', use_expireat=False, streaming_backend=None, ): loader = create_loader(fp, streaming_backend) r = client(host=host, port=port, password=password, db=db, unix_socket_path=unix_socket_path, encoding=encoding) counter = 0 for key, item in loader(): # Create pipeline: if not counter: p = r.pipeline(transaction=False) type = item['type'] value = item['value'] ttl = item.get('ttl') expireat = item.get('expireat') _writer(r, p, key, type, value, ttl, expireat, use_expireat=use_expireat) # Increase counter until 10 000... counter = (counter + 1) % 10000 # ... then execute: if not counter: p.execute() if counter: # Finally, execute again: p.execute()
[ "def", "load_streaming", "(", "fp", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ",", "password", "=", "None", ",", "db", "=", "0", ",", "empty", "=", "False", ",", "unix_socket_path", "=", "None", ",", "encoding", "=", "'utf-8'", ",", ...
https://github.com/p/redis-dump-load/blob/d5affcb9c140e55da738de4f18b360282fb0f9e0/redisdl.py#L429-L455
dustin/py-github
1b2f55e7b73ede3b16062b2a1195fb47153bae42
github/github.py
python
RepositoryEndpoint.watchers
(self, user, repo)
return self._parsed('repos/show/%s/%s/watchers' % (user, repo))
Find all of the watchers of one of your repositories.
Find all of the watchers of one of your repositories.
[ "Find", "all", "of", "the", "watchers", "of", "one", "of", "your", "repositories", "." ]
def watchers(self, user, repo): """Find all of the watchers of one of your repositories.""" return self._parsed('repos/show/%s/%s/watchers' % (user, repo))
[ "def", "watchers", "(", "self", ",", "user", ",", "repo", ")", ":", "return", "self", ".", "_parsed", "(", "'repos/show/%s/%s/watchers'", "%", "(", "user", ",", "repo", ")", ")" ]
https://github.com/dustin/py-github/blob/1b2f55e7b73ede3b16062b2a1195fb47153bae42/github/github.py#L462-L464
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/flask_lib/jinja2/runtime.py
python
Context.get_all
(self)
return dict(self.parent, **self.vars)
Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.
Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.
[ "Return", "the", "complete", "context", "as", "dict", "including", "the", "exported", "variables", ".", "For", "optimizations", "reasons", "this", "might", "not", "return", "an", "actual", "copy", "so", "be", "careful", "with", "using", "it", "." ]
def get_all(self): """Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it. """ if not self.vars: return self.parent if not self.parent: return self.vars return dict(self.parent, **self.vars)
[ "def", "get_all", "(", "self", ")", ":", "if", "not", "self", ".", "vars", ":", "return", "self", ".", "parent", "if", "not", "self", ".", "parent", ":", "return", "self", ".", "vars", "return", "dict", "(", "self", ".", "parent", ",", "*", "*", ...
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/flask_lib/jinja2/runtime.py#L223-L232
PaloAltoNetworks/pan-os-python
30f6cd9e29d0e3c2549d46c722f6dcb507acd437
panos/userid.py
python
UserId.logout
(self, user, ip)
Logout a single user Removes a mapping of a user to an IP address This method can be batched with batch_start() and batch_end(). Args: user (str): a username ip (str): an ip address
Logout a single user
[ "Logout", "a", "single", "user" ]
def logout(self, user, ip): """Logout a single user Removes a mapping of a user to an IP address This method can be batched with batch_start() and batch_end(). Args: user (str): a username ip (str): an ip address """ root, payload = self._create_uidmessage() logout = payload.find("logout") if logout is None: logout = ET.SubElement(payload, "logout") ET.SubElement(logout, "entry", {"name": user, "ip": ip}) self.send(root)
[ "def", "logout", "(", "self", ",", "user", ",", "ip", ")", ":", "root", ",", "payload", "=", "self", ".", "_create_uidmessage", "(", ")", "logout", "=", "payload", ".", "find", "(", "\"logout\"", ")", "if", "logout", "is", "None", ":", "logout", "=",...
https://github.com/PaloAltoNetworks/pan-os-python/blob/30f6cd9e29d0e3c2549d46c722f6dcb507acd437/panos/userid.py#L187-L204
openstack/nova
b49b7663e1c3073917d5844b81d38db8e86d05c4
nova/virt/libvirt/migration.py
python
update_downtime
(guest, instance, olddowntime, downtime_steps, elapsed)
return thisstep[1]
Update max downtime if needed :param guest: a nova.virt.libvirt.guest.Guest to set downtime for :param instance: a nova.objects.Instance :param olddowntime: current set downtime, or None :param downtime_steps: list of downtime steps :param elapsed: total time of migration in secs Determine if the maximum downtime needs to be increased based on the downtime steps. Each element in the downtime steps list should be a 2 element tuple. The first element contains a time marker and the second element contains the downtime value to set when the marker is hit. The guest object will be used to change the current downtime value on the instance. Any errors hit when updating downtime will be ignored :returns: the new downtime value
Update max downtime if needed
[ "Update", "max", "downtime", "if", "needed" ]
def update_downtime(guest, instance, olddowntime, downtime_steps, elapsed): """Update max downtime if needed :param guest: a nova.virt.libvirt.guest.Guest to set downtime for :param instance: a nova.objects.Instance :param olddowntime: current set downtime, or None :param downtime_steps: list of downtime steps :param elapsed: total time of migration in secs Determine if the maximum downtime needs to be increased based on the downtime steps. Each element in the downtime steps list should be a 2 element tuple. The first element contains a time marker and the second element contains the downtime value to set when the marker is hit. The guest object will be used to change the current downtime value on the instance. Any errors hit when updating downtime will be ignored :returns: the new downtime value """ LOG.debug("Current %(dt)s elapsed %(elapsed)d steps %(steps)s", {"dt": olddowntime, "elapsed": elapsed, "steps": downtime_steps}, instance=instance) thisstep = None for step in downtime_steps: if elapsed > step[0]: thisstep = step if thisstep is None: LOG.debug("No current step", instance=instance) return olddowntime if thisstep[1] == olddowntime: LOG.debug("Downtime does not need to change", instance=instance) return olddowntime LOG.info("Increasing downtime to %(downtime)d ms " "after %(waittime)d sec elapsed time", {"downtime": thisstep[1], "waittime": thisstep[0]}, instance=instance) try: guest.migrate_configure_max_downtime(thisstep[1]) except libvirt.libvirtError as e: LOG.warning("Unable to increase max downtime to %(time)d ms: %(e)s", {"time": thisstep[1], "e": e}, instance=instance) return thisstep[1]
[ "def", "update_downtime", "(", "guest", ",", "instance", ",", "olddowntime", ",", "downtime_steps", ",", "elapsed", ")", ":", "LOG", ".", "debug", "(", "\"Current %(dt)s elapsed %(elapsed)d steps %(steps)s\"", ",", "{", "\"dt\"", ":", "olddowntime", ",", "\"elapsed\...
https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/virt/libvirt/migration.py#L475-L527
Ultimaker/Cura
a1622c77ea7259ecb956acd6de07b7d34b7ac52b
plugins/UM3NetworkPrinting/src/Network/LocalClusterOutputDeviceManager.py
python
LocalClusterOutputDeviceManager._connectToOutputDevice
(self, device: UltimakerNetworkedPrinterOutputDevice, machine: GlobalStack)
Add a device to the current active machine.
Add a device to the current active machine.
[ "Add", "a", "device", "to", "the", "current", "active", "machine", "." ]
def _connectToOutputDevice(self, device: UltimakerNetworkedPrinterOutputDevice, machine: GlobalStack) -> None: """Add a device to the current active machine.""" # Make sure users know that we no longer support legacy devices. if Version(device.firmwareVersion) < self.MIN_SUPPORTED_CLUSTER_VERSION: LegacyDeviceNoLongerSupportedMessage().show() return machine.setName(device.name) machine.setMetaDataEntry(self.META_NETWORK_KEY, device.key) machine.setMetaDataEntry("group_name", device.name) machine.addConfiguredConnectionType(device.connectionType.value) if not device.isConnected(): device.connect() output_device_manager = CuraApplication.getInstance().getOutputDeviceManager() if device.key not in output_device_manager.getOutputDeviceIds(): output_device_manager.addOutputDevice(device)
[ "def", "_connectToOutputDevice", "(", "self", ",", "device", ":", "UltimakerNetworkedPrinterOutputDevice", ",", "machine", ":", "GlobalStack", ")", "->", "None", ":", "# Make sure users know that we no longer support legacy devices.", "if", "Version", "(", "device", ".", ...
https://github.com/Ultimaker/Cura/blob/a1622c77ea7259ecb956acd6de07b7d34b7ac52b/plugins/UM3NetworkPrinting/src/Network/LocalClusterOutputDeviceManager.py#L264-L282
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/internet/interfaces.py
python
IResolver.lookupMailGroup
(name, timeout = 10)
Lookup the MG records associated with C{name}.
Lookup the MG records associated with C{name}.
[ "Lookup", "the", "MG", "records", "associated", "with", "C", "{", "name", "}", "." ]
def lookupMailGroup(name, timeout = 10): """ Lookup the MG records associated with C{name}. """
[ "def", "lookupMailGroup", "(", "name", ",", "timeout", "=", "10", ")", ":" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/internet/interfaces.py#L126-L129
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/Bastion.py
python
BastionClass.__init__
(self, get, name)
Constructor. Arguments: get - a function that gets the attribute value (by name) name - a human-readable name for the original object (suggestion: use repr(object))
Constructor.
[ "Constructor", "." ]
def __init__(self, get, name): """Constructor. Arguments: get - a function that gets the attribute value (by name) name - a human-readable name for the original object (suggestion: use repr(object)) """ self._get_ = get self._name_ = name
[ "def", "__init__", "(", "self", ",", "get", ",", "name", ")", ":", "self", ".", "_get_", "=", "get", "self", ".", "_name_", "=", "name" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/Bastion.py#L47-L58
mediacloud/backend
d36b489e4fbe6e44950916a04d9543a1d6cd5df0
apps/topics-map/src/python/topics_map/map.py
python
draw_labels
(graph: nx.Graph)
Draw labels, sizing by cohorts.
Draw labels, sizing by cohorts.
[ "Draw", "labels", "sizing", "by", "cohorts", "." ]
def draw_labels(graph: nx.Graph) -> None: """Draw labels, sizing by cohorts.""" positions = nx.get_node_attributes(graph, 'position') cohort_size = 35 num_cohorts = math.ceil(len(positions) / cohort_size) num_cohorts = min(30, num_cohorts) for i in range(num_cohorts): labels = get_labels_by_attribute( graph=graph, label_attribute='name', rank_attribute='size', iteration=i, num_labels=cohort_size, ) weight = 'bold' if i == 0 else 'normal' alpha = 1.0 if i == 0 else 0.5 font_size = 8 if i == 0 else 2 nx.draw_networkx_labels( G=graph, pos=positions, labels=labels, font_size=font_size, font_weight=weight, alpha=alpha )
[ "def", "draw_labels", "(", "graph", ":", "nx", ".", "Graph", ")", "->", "None", ":", "positions", "=", "nx", ".", "get_node_attributes", "(", "graph", ",", "'position'", ")", "cohort_size", "=", "35", "num_cohorts", "=", "math", ".", "ceil", "(", "len", ...
https://github.com/mediacloud/backend/blob/d36b489e4fbe6e44950916a04d9543a1d6cd5df0/apps/topics-map/src/python/topics_map/map.py#L533-L558
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/system/system.py
python
System.tasks
(self)
return PersistedTaskCollection()
nidaqmx.system._collections.PersistedTaskCollection: Indicates the collection of saved tasks for this DAQmx system.
nidaqmx.system._collections.PersistedTaskCollection: Indicates the collection of saved tasks for this DAQmx system.
[ "nidaqmx", ".", "system", ".", "_collections", ".", "PersistedTaskCollection", ":", "Indicates", "the", "collection", "of", "saved", "tasks", "for", "this", "DAQmx", "system", "." ]
def tasks(self): """ nidaqmx.system._collections.PersistedTaskCollection: Indicates the collection of saved tasks for this DAQmx system. """ return PersistedTaskCollection()
[ "def", "tasks", "(", "self", ")", ":", "return", "PersistedTaskCollection", "(", ")" ]
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/system/system.py#L93-L98
pycontribs/confluence
e21dc44f61229ca767f4183134ba5887d071babe
confluence/confluence.py
python
Confluence.getPage
(self, page, space)
return page
Returns a page object as a dictionary. :param page: The page name :type page: ``str`` :param space: The space name :type space: ``str`` :return: dictionary. result['content'] contains the body of the page.
Returns a page object as a dictionary.
[ "Returns", "a", "page", "object", "as", "a", "dictionary", "." ]
def getPage(self, page, space): """ Returns a page object as a dictionary. :param page: The page name :type page: ``str`` :param space: The space name :type space: ``str`` :return: dictionary. result['content'] contains the body of the page. """ if self._token2: page = self._server.confluence2.getPage(self._token2, space, page) else: page = self._server.confluence1.getPage(self._token, space, page) return page
[ "def", "getPage", "(", "self", ",", "page", ",", "space", ")", ":", "if", "self", ".", "_token2", ":", "page", "=", "self", ".", "_server", ".", "confluence2", ".", "getPage", "(", "self", ".", "_token2", ",", "space", ",", "page", ")", "else", ":"...
https://github.com/pycontribs/confluence/blob/e21dc44f61229ca767f4183134ba5887d071babe/confluence/confluence.py#L202-L218
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/nlp/v20190408/models.py
python
EntityRelationObject.__init__
(self)
r""" :param Popular: object对应popular值 注意:此字段可能返回 null,表示取不到有效值。 :type Popular: list of int :param Id: object对应id 注意:此字段可能返回 null,表示取不到有效值。 :type Id: list of str :param Name: object对应name 注意:此字段可能返回 null,表示取不到有效值。 :type Name: list of str
r""" :param Popular: object对应popular值 注意:此字段可能返回 null,表示取不到有效值。 :type Popular: list of int :param Id: object对应id 注意:此字段可能返回 null,表示取不到有效值。 :type Id: list of str :param Name: object对应name 注意:此字段可能返回 null,表示取不到有效值。 :type Name: list of str
[ "r", ":", "param", "Popular", ":", "object对应popular值", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "Popular", ":", "list", "of", "int", ":", "param", "Id", ":", "object对应id", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "Id", ":", "list", "of", "str", ":", ...
def __init__(self): r""" :param Popular: object对应popular值 注意:此字段可能返回 null,表示取不到有效值。 :type Popular: list of int :param Id: object对应id 注意:此字段可能返回 null,表示取不到有效值。 :type Id: list of str :param Name: object对应name 注意:此字段可能返回 null,表示取不到有效值。 :type Name: list of str """ self.Popular = None self.Id = None self.Name = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Popular", "=", "None", "self", ".", "Id", "=", "None", "self", ".", "Name", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/nlp/v20190408/models.py#L947-L961
ilastik/ilastik
6acd2c554bc517e9c8ddad3623a7aaa2e6970c28
lazyflow/utility/pipeline.py
python
Pipeline.close
(self)
Cleanup all operators in this pipeline in the LIFO order.
Cleanup all operators in this pipeline in the LIFO order.
[ "Cleanup", "all", "operators", "in", "this", "pipeline", "in", "the", "LIFO", "order", "." ]
def close(self) -> None: """Cleanup all operators in this pipeline in the LIFO order.""" for op in reversed(self): op.cleanUp()
[ "def", "close", "(", "self", ")", "->", "None", ":", "for", "op", "in", "reversed", "(", "self", ")", ":", "op", ".", "cleanUp", "(", ")" ]
https://github.com/ilastik/ilastik/blob/6acd2c554bc517e9c8ddad3623a7aaa2e6970c28/lazyflow/utility/pipeline.py#L97-L100
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/repackage/setuptools/pkg_resources/_vendor/pyparsing.py
python
ParserElement.setDebugActions
( self, startAction, successAction, exceptionAction )
return self
Enable display of debugging messages while doing pattern matching.
Enable display of debugging messages while doing pattern matching.
[ "Enable", "display", "of", "debugging", "messages", "while", "doing", "pattern", "matching", "." ]
def setDebugActions( self, startAction, successAction, exceptionAction ): """ Enable display of debugging messages while doing pattern matching. """ self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self
[ "def", "setDebugActions", "(", "self", ",", "startAction", ",", "successAction", ",", "exceptionAction", ")", ":", "self", ".", "debugActions", "=", "(", "startAction", "or", "_defaultStartDebugAction", ",", "successAction", "or", "_defaultSuccessDebugAction", ",", ...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/repackage/setuptools/pkg_resources/_vendor/pyparsing.py#L2102-L2110
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/sms/api.py
python
load_and_call
(sms_handler_names, phone_number, text, sms)
return handled
[]
def load_and_call(sms_handler_names, phone_number, text, sms): handled = False for sms_handler_name in sms_handler_names: try: handler = to_function(sms_handler_name) except: notify_exception(None, message=('error loading sms handler: %s' % sms_handler_name)) continue try: handled = handler(phone_number, text, sms) except Exception: log_sms_exception(sms) if handled: break return handled
[ "def", "load_and_call", "(", "sms_handler_names", ",", "phone_number", ",", "text", ",", "sms", ")", ":", "handled", "=", "False", "for", "sms_handler_name", "in", "sms_handler_names", ":", "try", ":", "handler", "=", "to_function", "(", "sms_handler_name", ")",...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/sms/api.py#L617-L635
ros/ros
93d8da32091b8b43702eab5d3202f4511dfeb7dc
core/roslib/src/roslib/manifestlib.py
python
Depend.__init__
(self, package)
Create new depend instance. @param package: package name. must be non-empty @type package: str
Create new depend instance.
[ "Create", "new", "depend", "instance", "." ]
def __init__(self, package): """ Create new depend instance. @param package: package name. must be non-empty @type package: str """ if not package: raise ValueError("bad 'package' attribute") self.package = package
[ "def", "__init__", "(", "self", ",", "package", ")", ":", "if", "not", "package", ":", "raise", "ValueError", "(", "\"bad 'package' attribute\"", ")", "self", ".", "package", "=", "package" ]
https://github.com/ros/ros/blob/93d8da32091b8b43702eab5d3202f4511dfeb7dc/core/roslib/src/roslib/manifestlib.py#L311-L319
MultiChain/multichain-explorer
9e850fa79d0759b7348647ccf73a31d387c945a5
Mce/DataStore.py
python
DataStore.get_sent
(store, chain_id, pubkey_hash, block_height = None)
return store.get_sent_and_last_block_id( chain_id, pubkey_hash, block_height)[0]
[]
def get_sent(store, chain_id, pubkey_hash, block_height = None): return store.get_sent_and_last_block_id( chain_id, pubkey_hash, block_height)[0]
[ "def", "get_sent", "(", "store", ",", "chain_id", ",", "pubkey_hash", ",", "block_height", "=", "None", ")", ":", "return", "store", ".", "get_sent_and_last_block_id", "(", "chain_id", ",", "pubkey_hash", ",", "block_height", ")", "[", "0", "]" ]
https://github.com/MultiChain/multichain-explorer/blob/9e850fa79d0759b7348647ccf73a31d387c945a5/Mce/DataStore.py#L3479-L3481
zhirongw/lemniscate.pytorch
f7cfe298357cb2b169cd59eb540aca24bed1f9b8
models/resnet.py
python
Bottleneck.__init__
(self, inplanes, planes, stride=1, downsample=None)
[]
def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride
[ "def", "__init__", "(", "self", ",", "inplanes", ",", "planes", ",", "stride", "=", "1", ",", "downsample", "=", "None", ")", ":", "super", "(", "Bottleneck", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "conv1", "=", "nn", ".", "Conv2...
https://github.com/zhirongw/lemniscate.pytorch/blob/f7cfe298357cb2b169cd59eb540aca24bed1f9b8/models/resnet.py#L59-L70
dropbox/stone
b7b64320631b3a4d2f10681dca64e0718ebe68ee
stone/ir/data_types.py
python
Struct._filter_fields
(self, filter_function)
return fields
Utility to iterate through all fields (super types first) of a type. :param filter: A function that takes in a Field object. If it returns True, the field is part of the generated output. If False, it is omitted.
Utility to iterate through all fields (super types first) of a type.
[ "Utility", "to", "iterate", "through", "all", "fields", "(", "super", "types", "first", ")", "of", "a", "type", "." ]
def _filter_fields(self, filter_function): """ Utility to iterate through all fields (super types first) of a type. :param filter: A function that takes in a Field object. If it returns True, the field is part of the generated output. If False, it is omitted. """ fields = [] if self.parent_type: fields.extend(self.parent_type._filter_fields(filter_function)) fields.extend(filter(filter_function, self.fields)) return fields
[ "def", "_filter_fields", "(", "self", ",", "filter_function", ")", ":", "fields", "=", "[", "]", "if", "self", ".", "parent_type", ":", "fields", ".", "extend", "(", "self", ".", "parent_type", ".", "_filter_fields", "(", "filter_function", ")", ")", "fiel...
https://github.com/dropbox/stone/blob/b7b64320631b3a4d2f10681dca64e0718ebe68ee/stone/ir/data_types.py#L972-L984
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py
python
Forward.__lshift__
( self, other )
return self
[]
def __lshift__( self, other ): if isinstance( other, basestring ): other = ParserElement._literalStringClass(other) self.expr = other self.strRepr = None self.mayIndexError = self.expr.mayIndexError self.mayReturnEmpty = self.expr.mayReturnEmpty self.setWhitespaceChars( self.expr.whiteChars ) self.skipWhitespace = self.expr.skipWhitespace self.saveAsList = self.expr.saveAsList self.ignoreExprs.extend(self.expr.ignoreExprs) return self
[ "def", "__lshift__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "self", ".", "expr", "=", "other", "self", ".", "strRep...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L4141-L4152
tonyfischetti/sake
818f1b1ad97a0d7bcf2c9e0082affb2865b25f26
sakelib/build.py
python
merge_from_store_and_in_mems
(from_store, in_mem_shas, dont_update_shas_of)
return in_mem_shas
If we don't merge the shas from the sha store and if we build a subgraph, the .shastore will only contain the shas of the files from the subgraph and the rest of the graph will have to be rebuilt
If we don't merge the shas from the sha store and if we build a subgraph, the .shastore will only contain the shas of the files from the subgraph and the rest of the graph will have to be rebuilt
[ "If", "we", "don", "t", "merge", "the", "shas", "from", "the", "sha", "store", "and", "if", "we", "build", "a", "subgraph", "the", ".", "shastore", "will", "only", "contain", "the", "shas", "of", "the", "files", "from", "the", "subgraph", "and", "the",...
def merge_from_store_and_in_mems(from_store, in_mem_shas, dont_update_shas_of): """ If we don't merge the shas from the sha store and if we build a subgraph, the .shastore will only contain the shas of the files from the subgraph and the rest of the graph will have to be rebuilt """ if not from_store: for item in dont_update_shas_of: if item in in_mem_shas['files']: del in_mem_shas['files'][item] return in_mem_shas for key in from_store['files']: if key not in in_mem_shas['files'] and key not in dont_update_shas_of: in_mem_shas['files'][key] = from_store['files'][key] for item in dont_update_shas_of: if item in in_mem_shas['files']: del in_mem_shas['files'][item] return in_mem_shas
[ "def", "merge_from_store_and_in_mems", "(", "from_store", ",", "in_mem_shas", ",", "dont_update_shas_of", ")", ":", "if", "not", "from_store", ":", "for", "item", "in", "dont_update_shas_of", ":", "if", "item", "in", "in_mem_shas", "[", "'files'", "]", ":", "del...
https://github.com/tonyfischetti/sake/blob/818f1b1ad97a0d7bcf2c9e0082affb2865b25f26/sakelib/build.py#L481-L499
ronreiter/interactive-tutorials
d026d1ae58941863d60eb30a8a94a8650d2bd4bf
suds/xsd/sxbase.py
python
NodeFinder.find
(self, node, list)
return self
Traverse the tree looking for matches. @param node: A node to match on. @type node: L{SchemaObject} @param list: A list to fill. @type list: list
Traverse the tree looking for matches.
[ "Traverse", "the", "tree", "looking", "for", "matches", "." ]
def find(self, node, list): """ Traverse the tree looking for matches. @param node: A node to match on. @type node: L{SchemaObject} @param list: A list to fill. @type list: list """ if self.matcher.match(node): list.append(node) self.limit -= 1 if self.limit == 0: return for c in node.rawchildren: self.find(c, list) return self
[ "def", "find", "(", "self", ",", "node", ",", "list", ")", ":", "if", "self", ".", "matcher", ".", "match", "(", "node", ")", ":", "list", ".", "append", "(", "node", ")", "self", ".", "limit", "-=", "1", "if", "self", ".", "limit", "==", "0", ...
https://github.com/ronreiter/interactive-tutorials/blob/d026d1ae58941863d60eb30a8a94a8650d2bd4bf/suds/xsd/sxbase.py#L657-L672
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_openshift_3.2/library/oc_env.py
python
DeploymentConfig.__init__
(self, content=None)
Constructor for OpenshiftOC
Constructor for OpenshiftOC
[ "Constructor", "for", "OpenshiftOC" ]
def __init__(self, content=None): ''' Constructor for OpenshiftOC ''' if not content: content = DeploymentConfig.default_deployment_config super(DeploymentConfig, self).__init__(content=content)
[ "def", "__init__", "(", "self", ",", "content", "=", "None", ")", ":", "if", "not", "content", ":", "content", "=", "DeploymentConfig", ".", "default_deployment_config", "super", "(", "DeploymentConfig", ",", "self", ")", ".", "__init__", "(", "content", "="...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/library/oc_env.py#L962-L967
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
cmk/base/plugins/agent_based/netscaler_sslcertificates.py
python
parse_netscaler_sslcertificates
(string_table: List[StringTable])
return {certname: int(daysleft) for certname, daysleft in string_table[0]}
>>> parse_netscaler_sslcertificates([[['cert1', '3'], ['cert2', '100']]]) {'cert1': 3, 'cert2': 100}
>>> parse_netscaler_sslcertificates([[['cert1', '3'], ['cert2', '100']]]) {'cert1': 3, 'cert2': 100}
[ ">>>", "parse_netscaler_sslcertificates", "(", "[[[", "cert1", "3", "]", "[", "cert2", "100", "]]]", ")", "{", "cert1", ":", "3", "cert2", ":", "100", "}" ]
def parse_netscaler_sslcertificates(string_table: List[StringTable]) -> Section: """ >>> parse_netscaler_sslcertificates([[['cert1', '3'], ['cert2', '100']]]) {'cert1': 3, 'cert2': 100} """ return {certname: int(daysleft) for certname, daysleft in string_table[0]}
[ "def", "parse_netscaler_sslcertificates", "(", "string_table", ":", "List", "[", "StringTable", "]", ")", "->", "Section", ":", "return", "{", "certname", ":", "int", "(", "daysleft", ")", "for", "certname", ",", "daysleft", "in", "string_table", "[", "0", "...
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/base/plugins/agent_based/netscaler_sslcertificates.py#L25-L30
AlexYangLi/ABSA_Keras
8de8f6a3d8861c68e3f552a4b77bf60d75ee05f6
models.py
python
SentimentModel.atae_lstm
(self)
return Model([input_text, input_aspect], final_output)
[]
def atae_lstm(self): input_text = Input(shape=(self.max_len,)) input_aspect = Input(shape=(1,), ) if self.use_elmo: elmo_embedding = ELMoEmbedding(output_mode=self.config.elmo_output_mode, idx2word=self.config.idx2token, mask_zero=True, hub_url=self.config.elmo_hub_url, elmo_trainable=self.config.elmo_trainable) if self.config.use_elmo_alone: text_embed = SpatialDropout1D(0.2)(elmo_embedding(input_text)) else: word_embedding = Embedding(input_dim=self.text_embeddings.shape[0], output_dim=self.config.word_embed_dim, weights=[self.text_embeddings], trainable=self.config.word_embed_trainable, mask_zero=True) text_embed = SpatialDropout1D(0.2)(concatenate([word_embedding(input_text), elmo_embedding(input_text)])) else: word_embedding = Embedding(input_dim=self.text_embeddings.shape[0], output_dim=self.config.word_embed_dim, weights=[self.text_embeddings], trainable=self.config.word_embed_trainable, mask_zero=True) text_embed = SpatialDropout1D(0.2)(word_embedding(input_text)) if self.config.aspect_embed_type == 'random': asp_embedding = Embedding(input_dim=self.n_aspect, output_dim=self.config.aspect_embed_dim) else: asp_embedding = Embedding(input_dim=self.aspect_embeddings.shape[0], output_dim=self.config.aspect_embed_dim, trainable=self.config.aspect_embed_trainable) aspect_embed = asp_embedding(input_aspect) aspect_embed = Flatten()(aspect_embed) # reshape to 2d repeat_aspect = RepeatVector(self.max_len)(aspect_embed) # repeat aspect for every word in sequence input_concat = concatenate([text_embed, repeat_aspect], axis=-1) hidden_vecs, state_h, _ = LSTM(self.config.lstm_units, return_sequences=True, return_state=True)(input_concat) concat = concatenate([hidden_vecs, repeat_aspect], axis=-1) # apply attention mechanism attend_weight = Attention()(concat) attend_weight_expand = Lambda(lambda x: K.expand_dims(x))(attend_weight) attend_hidden = multiply([hidden_vecs, attend_weight_expand]) attend_hidden = Lambda(lambda x: K.sum(x, axis=1))(attend_hidden) attend_hidden_dense = Dense(self.config.lstm_units)(attend_hidden) last_hidden_dense = Dense(self.config.lstm_units)(state_h) final_output = Activation('tanh')(add([attend_hidden_dense, last_hidden_dense])) return Model([input_text, input_aspect], final_output)
[ "def", "atae_lstm", "(", "self", ")", ":", "input_text", "=", "Input", "(", "shape", "=", "(", "self", ".", "max_len", ",", ")", ")", "input_aspect", "=", "Input", "(", "shape", "=", "(", "1", ",", ")", ",", ")", "if", "self", ".", "use_elmo", ":...
https://github.com/AlexYangLi/ABSA_Keras/blob/8de8f6a3d8861c68e3f552a4b77bf60d75ee05f6/models.py#L454-L500
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/asset_service/transports/grpc.py
python
AssetServiceGrpcTransport.get_asset
( self, )
return self._stubs["get_asset"]
r"""Return a callable for the get asset method over gRPC. Returns the requested asset in full detail. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: Callable[[~.GetAssetRequest], ~.Asset]: A function that, when called, will call the underlying RPC on the server.
r"""Return a callable for the get asset method over gRPC.
[ "r", "Return", "a", "callable", "for", "the", "get", "asset", "method", "over", "gRPC", "." ]
def get_asset( self, ) -> Callable[[asset_service.GetAssetRequest], asset.Asset]: r"""Return a callable for the get asset method over gRPC. Returns the requested asset in full detail. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: Callable[[~.GetAssetRequest], ~.Asset]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_asset" not in self._stubs: self._stubs["get_asset"] = self.grpc_channel.unary_unary( "/google.ads.googleads.v8.services.AssetService/GetAsset", request_serializer=asset_service.GetAssetRequest.serialize, response_deserializer=asset.Asset.deserialize, ) return self._stubs["get_asset"]
[ "def", "get_asset", "(", "self", ",", ")", "->", "Callable", "[", "[", "asset_service", ".", "GetAssetRequest", "]", ",", "asset", ".", "Asset", "]", ":", "# Generate a \"stub function\" on-the-fly which will actually make", "# the request.", "# gRPC handles serialization...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/asset_service/transports/grpc.py#L215-L242
sqlmapproject/sqlmap
3b07b70864624dff4c29dcaa8a61c78e7f9189f7
thirdparty/bottle/bottle.py
python
BaseRequest.is_xhr
(self)
return requested_with.lower() == 'xmlhttprequest'
True if the request was triggered by a XMLHttpRequest. This only works with JavaScript libraries that support the `X-Requested-With` header (most of the popular libraries do).
True if the request was triggered by a XMLHttpRequest. This only works with JavaScript libraries that support the `X-Requested-With` header (most of the popular libraries do).
[ "True", "if", "the", "request", "was", "triggered", "by", "a", "XMLHttpRequest", ".", "This", "only", "works", "with", "JavaScript", "libraries", "that", "support", "the", "X", "-", "Requested", "-", "With", "header", "(", "most", "of", "the", "popular", "...
def is_xhr(self): """ True if the request was triggered by a XMLHttpRequest. This only works with JavaScript libraries that support the `X-Requested-With` header (most of the popular libraries do). """ requested_with = self.environ.get('HTTP_X_REQUESTED_WITH', '') return requested_with.lower() == 'xmlhttprequest'
[ "def", "is_xhr", "(", "self", ")", ":", "requested_with", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_X_REQUESTED_WITH'", ",", "''", ")", "return", "requested_with", ".", "lower", "(", ")", "==", "'xmlhttprequest'" ]
https://github.com/sqlmapproject/sqlmap/blob/3b07b70864624dff4c29dcaa8a61c78e7f9189f7/thirdparty/bottle/bottle.py#L1497-L1502
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
chap19/monitor/monitor/build/lib.linux-x86_64-2.7/monitor/openstack/common/rpc/impl_qpid.py
python
DirectConsumer.__init__
(self, conf, session, msg_id, callback)
Init a 'direct' queue. 'session' is the amqp session to use 'msg_id' is the msg_id to listen on 'callback' is the callback to call when messages are received
Init a 'direct' queue.
[ "Init", "a", "direct", "queue", "." ]
def __init__(self, conf, session, msg_id, callback): """Init a 'direct' queue. 'session' is the amqp session to use 'msg_id' is the msg_id to listen on 'callback' is the callback to call when messages are received """ super(DirectConsumer, self).__init__(session, callback, "%s/%s" % (msg_id, msg_id), {"type": "direct"}, msg_id, {"exclusive": True})
[ "def", "__init__", "(", "self", ",", "conf", ",", "session", ",", "msg_id", ",", "callback", ")", ":", "super", "(", "DirectConsumer", ",", "self", ")", ".", "__init__", "(", "session", ",", "callback", ",", "\"%s/%s\"", "%", "(", "msg_id", ",", "msg_i...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/monitor/build/lib.linux-x86_64-2.7/monitor/openstack/common/rpc/impl_qpid.py#L144-L156
hubblestack/hubble
763142474edcecdec5fd25591dc29c3536e8f969
hubblestack/utils/json.py
python
loads
(s, **kwargs)
.. versionadded:: 2018.3.0 Wraps json.loads and prevents a traceback in the event that a bytestring is passed to the function. (Python < 3.6 cannot load bytestrings) You can pass an alternate json module (loaded via import_json() above) using the _json_module argument)
.. versionadded:: 2018.3.0
[ "..", "versionadded", "::", "2018", ".", "3", ".", "0" ]
def loads(s, **kwargs): """ .. versionadded:: 2018.3.0 Wraps json.loads and prevents a traceback in the event that a bytestring is passed to the function. (Python < 3.6 cannot load bytestrings) You can pass an alternate json module (loaded via import_json() above) using the _json_module argument) """ json_module = kwargs.pop("_json_module", json) try: return json_module.loads(s, **kwargs) except TypeError as exc: # json.loads cannot load bytestrings in Python < 3.6 if isinstance(s, bytes): return json_module.loads(hubblestack.utils.stringutils.to_unicode(s), **kwargs) else: raise exc
[ "def", "loads", "(", "s", ",", "*", "*", "kwargs", ")", ":", "json_module", "=", "kwargs", ".", "pop", "(", "\"_json_module\"", ",", "json", ")", "try", ":", "return", "json_module", ".", "loads", "(", "s", ",", "*", "*", "kwargs", ")", "except", "...
https://github.com/hubblestack/hubble/blob/763142474edcecdec5fd25591dc29c3536e8f969/hubblestack/utils/json.py#L31-L49
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/trusthub/v1/trust_products/__init__.py
python
TrustProductsContext.trust_products_entity_assignments
(self)
return self._trust_products_entity_assignments
Access the trust_products_entity_assignments :returns: twilio.rest.trusthub.v1.trust_products.trust_products_entity_assignments.TrustProductsEntityAssignmentsList :rtype: twilio.rest.trusthub.v1.trust_products.trust_products_entity_assignments.TrustProductsEntityAssignmentsList
Access the trust_products_entity_assignments
[ "Access", "the", "trust_products_entity_assignments" ]
def trust_products_entity_assignments(self): """ Access the trust_products_entity_assignments :returns: twilio.rest.trusthub.v1.trust_products.trust_products_entity_assignments.TrustProductsEntityAssignmentsList :rtype: twilio.rest.trusthub.v1.trust_products.trust_products_entity_assignments.TrustProductsEntityAssignmentsList """ if self._trust_products_entity_assignments is None: self._trust_products_entity_assignments = TrustProductsEntityAssignmentsList( self._version, trust_product_sid=self._solution['sid'], ) return self._trust_products_entity_assignments
[ "def", "trust_products_entity_assignments", "(", "self", ")", ":", "if", "self", ".", "_trust_products_entity_assignments", "is", "None", ":", "self", ".", "_trust_products_entity_assignments", "=", "TrustProductsEntityAssignmentsList", "(", "self", ".", "_version", ",", ...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/trusthub/v1/trust_products/__init__.py#L306-L318
fooof-tools/fooof
14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac
fooof/plts/style.py
python
apply_axis_style
(ax, style_args=AXIS_STYLE_ARGS, **kwargs)
Apply axis plot style. Parameters ---------- ax : matplotlib.Axes Figure axes to apply style to. style_args : list of str A list of arguments to be sub-selected from `kwargs` and applied as axis styling. **kwargs Keyword arguments that define plot style to apply.
Apply axis plot style.
[ "Apply", "axis", "plot", "style", "." ]
def apply_axis_style(ax, style_args=AXIS_STYLE_ARGS, **kwargs): """Apply axis plot style. Parameters ---------- ax : matplotlib.Axes Figure axes to apply style to. style_args : list of str A list of arguments to be sub-selected from `kwargs` and applied as axis styling. **kwargs Keyword arguments that define plot style to apply. """ # Apply any provided axis style arguments plot_kwargs = {key : val for key, val in kwargs.items() if key in style_args} ax.set(**plot_kwargs)
[ "def", "apply_axis_style", "(", "ax", ",", "style_args", "=", "AXIS_STYLE_ARGS", ",", "*", "*", "kwargs", ")", ":", "# Apply any provided axis style arguments", "plot_kwargs", "=", "{", "key", ":", "val", "for", "key", ",", "val", "in", "kwargs", ".", "items",...
https://github.com/fooof-tools/fooof/blob/14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac/fooof/plts/style.py#L74-L89
jgyates/genmon
2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e
genmonlib/generac_HPanel.py
python
GPanelReg.hexsort
(self, e)
[]
def hexsort(self, e): try: return int(e[REGISTER],16) except: return 0
[ "def", "hexsort", "(", "self", ",", "e", ")", ":", "try", ":", "return", "int", "(", "e", "[", "REGISTER", "]", ",", "16", ")", "except", ":", "return", "0" ]
https://github.com/jgyates/genmon/blob/2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e/genmonlib/generac_HPanel.py#L394-L398
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pymongo/mongo_client.py
python
MongoClient.min_pool_size
(self)
return self.__options.pool_options.min_pool_size
The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0.
The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0.
[ "The", "minimum", "required", "number", "of", "concurrent", "connections", "that", "the", "pool", "will", "maintain", "to", "each", "connected", "server", ".", "Default", "is", "0", "." ]
def min_pool_size(self): """The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0. """ return self.__options.pool_options.min_pool_size
[ "def", "min_pool_size", "(", "self", ")", ":", "return", "self", ".", "__options", ".", "pool_options", ".", "min_pool_size" ]
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pymongo/mongo_client.py#L1032-L1036
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_benchmarks/aws_dynamodb_ycsb_benchmark.py
python
Run
(benchmark_spec)
return samples
Run YCSB on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects.
Run YCSB on the target vm.
[ "Run", "YCSB", "on", "the", "target", "vm", "." ]
def Run(benchmark_spec): """Run YCSB on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ vms = benchmark_spec.vms run_kwargs = { 'dynamodb.awsCredentialsFile': GetRemoteVMCredentialsFullPath(vms[0]), 'dynamodb.primaryKey': FLAGS.aws_dynamodb_primarykey, 'dynamodb.endpoint': benchmark_spec.dynamodb_instance.GetEndPoint(), 'table': 'pkb-{0}'.format(FLAGS.run_uri), } if FLAGS.aws_dynamodb_use_sort: run_kwargs.update({'dynamodb.primaryKeyType': 'HASH_AND_RANGE', 'aws_dynamodb_connectMax': FLAGS.aws_dynamodb_connectMax, 'dynamodb.hashKeyName': FLAGS.aws_dynamodb_primarykey, 'dynamodb.primaryKey': FLAGS.aws_dynamodb_sortkey}) if FLAGS.aws_dynamodb_ycsb_consistentReads: run_kwargs.update({'dynamodb.consistentReads': 'true'}) load_kwargs = run_kwargs.copy() if FLAGS['ycsb_preload_threads'].present: load_kwargs['threads'] = FLAGS.ycsb_preload_threads # More WCU results in a faster load stage. benchmark_spec.dynamodb_instance.SetThroughput(wcu=_INITIAL_WRITES.value) samples = list(benchmark_spec.executor.Load(vms, load_kwargs=load_kwargs)) # Reset the WCU to the initial level. benchmark_spec.dynamodb_instance.SetThroughput() samples += list(benchmark_spec.executor.Run(vms, run_kwargs=run_kwargs)) benchmark_metadata = { 'ycsb_client_vms': len(vms), } for sample in samples: sample.metadata.update( benchmark_spec.dynamodb_instance.GetResourceMetadata()) sample.metadata.update(benchmark_metadata) return samples
[ "def", "Run", "(", "benchmark_spec", ")", ":", "vms", "=", "benchmark_spec", ".", "vms", "run_kwargs", "=", "{", "'dynamodb.awsCredentialsFile'", ":", "GetRemoteVMCredentialsFullPath", "(", "vms", "[", "0", "]", ")", ",", "'dynamodb.primaryKey'", ":", "FLAGS", "...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_benchmarks/aws_dynamodb_ycsb_benchmark.py#L88-L128
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/scapy/utils.py
python
do_graph
(graph,prog=None,format=None,target=None,type=None,string=None,options=None)
do_graph(graph, prog=conf.prog.dot, format="svg", target="| conf.prog.display", options=None, [string=1]): string: if not None, simply return the graph string graph: GraphViz graph description format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option target: filename or redirect. Defaults pipe to Imagemagick's display program prog: which graphviz program to use options: options to be passed to prog
do_graph(graph, prog=conf.prog.dot, format="svg", target="| conf.prog.display", options=None, [string=1]): string: if not None, simply return the graph string graph: GraphViz graph description format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option target: filename or redirect. Defaults pipe to Imagemagick's display program prog: which graphviz program to use options: options to be passed to prog
[ "do_graph", "(", "graph", "prog", "=", "conf", ".", "prog", ".", "dot", "format", "=", "svg", "target", "=", "|", "conf", ".", "prog", ".", "display", "options", "=", "None", "[", "string", "=", "1", "]", ")", ":", "string", ":", "if", "not", "No...
def do_graph(graph,prog=None,format=None,target=None,type=None,string=None,options=None): """do_graph(graph, prog=conf.prog.dot, format="svg", target="| conf.prog.display", options=None, [string=1]): string: if not None, simply return the graph string graph: GraphViz graph description format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option target: filename or redirect. Defaults pipe to Imagemagick's display program prog: which graphviz program to use options: options to be passed to prog""" if format is None: if WINDOWS: format = "png" # use common format to make sure a viewer is installed else: format = "svg" if string: return graph if type is not None: format=type if prog is None: prog = conf.prog.dot start_viewer=False if target is None: if WINDOWS: tempfile = os.tempnam("", "scapy") + "." + format target = "> %s" % tempfile start_viewer = True else: target = "| %s" % conf.prog.display if format is not None: format = "-T %s" % format w,r = os.popen2("%s %s %s %s" % (prog,options or "", format or "", target)) w.write(graph) w.close() if start_viewer: # Workaround for file not found error: We wait until tempfile is written. waiting_start = time.time() while not os.path.exists(tempfile): time.sleep(0.1) if time.time() - waiting_start > 3: warning("Temporary file '%s' could not be written. Graphic will not be displayed." % tempfile) break else: if conf.prog.display == conf.prog._default: os.startfile(tempfile) else: subprocess.Popen([conf.prog.display, tempfile])
[ "def", "do_graph", "(", "graph", ",", "prog", "=", "None", ",", "format", "=", "None", ",", "target", "=", "None", ",", "type", "=", "None", ",", "string", "=", "None", ",", "options", "=", "None", ")", ":", "if", "format", "is", "None", ":", "if...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/utils.py#L281-L327
tensorflow/tensorboard
61d11d99ef034c30ba20b6a7840c8eededb9031c
tensorboard/data/grpc_provider.py
python
make_stub
(channel)
return data_provider_pb2_grpc.TensorBoardDataProviderStub(channel)
Wraps a gRPC channel with a service stub.
Wraps a gRPC channel with a service stub.
[ "Wraps", "a", "gRPC", "channel", "with", "a", "service", "stub", "." ]
def make_stub(channel): """Wraps a gRPC channel with a service stub.""" return data_provider_pb2_grpc.TensorBoardDataProviderStub(channel)
[ "def", "make_stub", "(", "channel", ")", ":", "return", "data_provider_pb2_grpc", ".", "TensorBoardDataProviderStub", "(", "channel", ")" ]
https://github.com/tensorflow/tensorboard/blob/61d11d99ef034c30ba20b6a7840c8eededb9031c/tensorboard/data/grpc_provider.py#L29-L31
iiau-tracker/SPLT
a196e603798e9be969d9d985c087c11cad1cda43
lib/object_detection/core/losses.py
python
HardExampleMiner._subsample_selection_to_desired_neg_pos_ratio
(self, indices, match, max_negatives_per_positive, min_negatives_per_image=0)
return (tf.reshape(tf.gather(indices, subsampled_selection_indices), [-1]), num_positives, num_negatives)
Subsample a collection of selected indices to a desired neg:pos ratio. This function takes a subset of M indices (indexing into a large anchor collection of N anchors where M<N) which are labeled as positive/negative via a Match object (matched indices are positive, unmatched indices are negative). It returns a subset of the provided indices retaining all positives as well as up to the first K negatives, where: K=floor(num_negative_per_positive * num_positives). For example, if indices=[2, 4, 5, 7, 9, 10] (indexing into 12 anchors), with positives=[2, 5] and negatives=[4, 7, 9, 10] and num_negatives_per_positive=1, then the returned subset of indices is [2, 4, 5, 7]. Args: indices: An integer tensor of shape [M] representing a collection of selected anchor indices match: A matcher.Match object encoding the match between anchors and groundtruth boxes for a given image, with rows of the Match objects corresponding to groundtruth boxes and columns corresponding to anchors. max_negatives_per_positive: (float) maximum number of negatives for each positive anchor. min_negatives_per_image: minimum number of negative anchors for a given image. Allow sampling negatives in image without any positive anchors. Returns: selected_indices: An integer tensor of shape [M'] representing a collection of selected anchor indices with M' <= M. num_positives: An integer tensor representing the number of positive examples in selected set of indices. num_negatives: An integer tensor representing the number of negative examples in selected set of indices.
Subsample a collection of selected indices to a desired neg:pos ratio.
[ "Subsample", "a", "collection", "of", "selected", "indices", "to", "a", "desired", "neg", ":", "pos", "ratio", "." ]
def _subsample_selection_to_desired_neg_pos_ratio(self, indices, match, max_negatives_per_positive, min_negatives_per_image=0): """Subsample a collection of selected indices to a desired neg:pos ratio. This function takes a subset of M indices (indexing into a large anchor collection of N anchors where M<N) which are labeled as positive/negative via a Match object (matched indices are positive, unmatched indices are negative). It returns a subset of the provided indices retaining all positives as well as up to the first K negatives, where: K=floor(num_negative_per_positive * num_positives). For example, if indices=[2, 4, 5, 7, 9, 10] (indexing into 12 anchors), with positives=[2, 5] and negatives=[4, 7, 9, 10] and num_negatives_per_positive=1, then the returned subset of indices is [2, 4, 5, 7]. Args: indices: An integer tensor of shape [M] representing a collection of selected anchor indices match: A matcher.Match object encoding the match between anchors and groundtruth boxes for a given image, with rows of the Match objects corresponding to groundtruth boxes and columns corresponding to anchors. max_negatives_per_positive: (float) maximum number of negatives for each positive anchor. min_negatives_per_image: minimum number of negative anchors for a given image. Allow sampling negatives in image without any positive anchors. Returns: selected_indices: An integer tensor of shape [M'] representing a collection of selected anchor indices with M' <= M. num_positives: An integer tensor representing the number of positive examples in selected set of indices. num_negatives: An integer tensor representing the number of negative examples in selected set of indices. """ positives_indicator = tf.gather(match.matched_column_indicator(), indices) negatives_indicator = tf.gather(match.unmatched_column_indicator(), indices) num_positives = tf.reduce_sum(tf.to_int32(positives_indicator)) max_negatives = tf.maximum(min_negatives_per_image, tf.to_int32(max_negatives_per_positive * tf.to_float(num_positives))) topk_negatives_indicator = tf.less_equal( tf.cumsum(tf.to_int32(negatives_indicator)), max_negatives) subsampled_selection_indices = tf.where( tf.logical_or(positives_indicator, topk_negatives_indicator)) num_negatives = tf.size(subsampled_selection_indices) - num_positives return (tf.reshape(tf.gather(indices, subsampled_selection_indices), [-1]), num_positives, num_negatives)
[ "def", "_subsample_selection_to_desired_neg_pos_ratio", "(", "self", ",", "indices", ",", "match", ",", "max_negatives_per_positive", ",", "min_negatives_per_image", "=", "0", ")", ":", "positives_indicator", "=", "tf", ".", "gather", "(", "match", ".", "matched_colum...
https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/lib/object_detection/core/losses.py#L500-L550
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/core/management/commands/inspectdb.py
python
Command.get_meta
(self, table_name)
return [" class Meta:", " db_table = '%s'" % table_name, ""]
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
[ "Return", "a", "sequence", "comprising", "the", "lines", "of", "code", "necessary", "to", "construct", "the", "inner", "Meta", "class", "for", "the", "model", "corresponding", "to", "the", "given", "database", "table", "name", "." ]
def get_meta(self, table_name): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ return [" class Meta:", " db_table = '%s'" % table_name, ""]
[ "def", "get_meta", "(", "self", ",", "table_name", ")", ":", "return", "[", "\" class Meta:\"", ",", "\" db_table = '%s'\"", "%", "table_name", ",", "\"\"", "]" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/core/management/commands/inspectdb.py#L216-L224
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
datadog_checks_dev/datadog_checks/dev/tooling/utils.py
python
check_root
()
return False
Check if root has already been set.
Check if root has already been set.
[ "Check", "if", "root", "has", "already", "been", "set", "." ]
def check_root(): """Check if root has already been set.""" existing_root = get_root() if existing_root: return True root = os.getenv('DDEV_ROOT', '') if root and os.path.isdir(root): set_root(root) return True return False
[ "def", "check_root", "(", ")", ":", "existing_root", "=", "get_root", "(", ")", "if", "existing_root", ":", "return", "True", "root", "=", "os", ".", "getenv", "(", "'DDEV_ROOT'", ",", "''", ")", "if", "root", "and", "os", ".", "path", ".", "isdir", ...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/datadog_checks_dev/datadog_checks/dev/tooling/utils.py#L118-L128
ahkab/ahkab
1e8939194b689909b8184ce7eba478b485ff9e3a
ahkab/results.py
python
ac_solution.get
(self, name, default=None)
return data
Get a solution by variable name.
Get a solution by variable name.
[ "Get", "a", "solution", "by", "variable", "name", "." ]
def get(self, name, default=None): """Get a solution by variable name.""" try: data = self.__getitem__(name) except KeyError: return default return data
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "try", ":", "data", "=", "self", ".", "__getitem__", "(", "name", ")", "except", "KeyError", ":", "return", "default", "return", "data" ]
https://github.com/ahkab/ahkab/blob/1e8939194b689909b8184ce7eba478b485ff9e3a/ahkab/results.py#L687-L693
openembedded/bitbake
98407efc8c670abd71d3fa88ec3776ee9b5c38f3
lib/pyinotify.py
python
Notifier.read_events
(self)
Read events from device, build _RawEvents, and enqueue them.
Read events from device, build _RawEvents, and enqueue them.
[ "Read", "events", "from", "device", "build", "_RawEvents", "and", "enqueue", "them", "." ]
def read_events(self): """ Read events from device, build _RawEvents, and enqueue them. """ buf_ = array.array('i', [0]) # get event queue size if fcntl.ioctl(self._fd, termios.FIONREAD, buf_, 1) == -1: return queue_size = buf_[0] if queue_size < self._threshold: log.debug('(fd: %d) %d bytes available to read but threshold is ' 'fixed to %d bytes', self._fd, queue_size, self._threshold) return try: # Read content from file r = os.read(self._fd, queue_size) except Exception as msg: raise NotifierError(msg) log.debug('Event queue size: %d', queue_size) rsum = 0 # counter while rsum < queue_size: s_size = 16 # Retrieve wd, mask, cookie and fname_len wd, mask, cookie, fname_len = struct.unpack('iIII', r[rsum:rsum+s_size]) # Retrieve name bname, = struct.unpack('%ds' % fname_len, r[rsum + s_size:rsum + s_size + fname_len]) # FIXME: should we explictly call sys.getdefaultencoding() here ?? uname = bname.decode() rawevent = _RawEvent(wd, mask, cookie, uname) if self._coalesce: # Only enqueue new (unique) events. raweventstr = str(rawevent) if raweventstr not in self._eventset: self._eventset.add(raweventstr) self._eventq.append(rawevent) else: self._eventq.append(rawevent) rsum += s_size + fname_len
[ "def", "read_events", "(", "self", ")", ":", "buf_", "=", "array", ".", "array", "(", "'i'", ",", "[", "0", "]", ")", "# get event queue size", "if", "fcntl", ".", "ioctl", "(", "self", ".", "_fd", ",", "termios", ".", "FIONREAD", ",", "buf_", ",", ...
https://github.com/openembedded/bitbake/blob/98407efc8c670abd71d3fa88ec3776ee9b5c38f3/lib/pyinotify.py#L1191-L1232
cirosantilli/linux-kernel-module-cheat
97773a4e3cde9604c4ecec7f25fb60fe21058b29
lkmc/import_path.py
python
import_path_main
(basename)
return import_path_relative_root(basename).Main()
Import an object of the Main class of a given file. By convention, we call the main object of all our CLI scripts as Main.
Import an object of the Main class of a given file.
[ "Import", "an", "object", "of", "the", "Main", "class", "of", "a", "given", "file", "." ]
def import_path_main(basename): ''' Import an object of the Main class of a given file. By convention, we call the main object of all our CLI scripts as Main. ''' return import_path_relative_root(basename).Main()
[ "def", "import_path_main", "(", "basename", ")", ":", "return", "import_path_relative_root", "(", "basename", ")", ".", "Main", "(", ")" ]
https://github.com/cirosantilli/linux-kernel-module-cheat/blob/97773a4e3cde9604c4ecec7f25fb60fe21058b29/lkmc/import_path.py#L28-L34
deanishe/alfred-stackexchange
b2047b76165900d55f0c7d18fd7c40131bee94ed
src/workflow/workflow3.py
python
Variables.__init__
(self, arg=None, **variables)
Create a new `Variables` object.
Create a new `Variables` object.
[ "Create", "a", "new", "Variables", "object", "." ]
def __init__(self, arg=None, **variables): """Create a new `Variables` object.""" self.arg = arg self.config = {} super(Variables, self).__init__(**variables)
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "*", "*", "variables", ")", ":", "self", ".", "arg", "=", "arg", "self", ".", "config", "=", "{", "}", "super", "(", "Variables", ",", "self", ")", ".", "__init__", "(", "*", "*", "v...
https://github.com/deanishe/alfred-stackexchange/blob/b2047b76165900d55f0c7d18fd7c40131bee94ed/src/workflow/workflow3.py#L63-L67