_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q247600
MBAR._selfConsistentIteration
train
def _selfConsistentIteration(self, relative_tolerance=1.0e-6, maximum_iterations=1000, verbose=True, print_warning=False): """ Determine free energies by self-consistent iteration. OPTIONAL ARGUMENTS relative_tolerance (float between 0 and 1) - relative tolerance for convergence (def...
python
{ "resource": "" }
q247601
MBAR._pseudoinverse
train
def _pseudoinverse(self, A, tol=1.0e-10): """Compute the Moore-Penrose pseudoinverse, wraps np.linalg.pinv REQUIRED ARGUMENTS A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed RETURN VALUES Ainv (np KxK matrix) - the pseudoinverse OPTIONAL...
python
{ "resource": "" }
q247602
validate_inputs
train
def validate_inputs(u_kn, N_k, f_k): """Check types and return inputs for MBAR calculations. Parameters ---------- u_kn or q_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies or unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='in...
python
{ "resource": "" }
q247603
self_consistent_update
train
def self_consistent_update(u_kn, N_k, f_k): """Return an improved guess for the dimensionless free energies Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_sta...
python
{ "resource": "" }
q247604
mbar_gradient
train
def mbar_gradient(u_kn, N_k, f_k): """Gradient of MBAR objective function. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The num...
python
{ "resource": "" }
q247605
mbar_objective_and_gradient
train
def mbar_objective_and_gradient(u_kn, N_k, f_k): """Calculates both objective function and gradient for MBAR. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_s...
python
{ "resource": "" }
q247606
mbar_hessian
train
def mbar_hessian(u_kn, N_k, f_k): """Hessian of MBAR objective function. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The numbe...
python
{ "resource": "" }
q247607
mbar_log_W_nk
train
def mbar_log_W_nk(u_kn, N_k, f_k): """Calculate the log weight matrix. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number ...
python
{ "resource": "" }
q247608
mbar_W_nk
train
def mbar_W_nk(u_kn, N_k, f_k): """Calculate the weight matrix. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of sampl...
python
{ "resource": "" }
q247609
precondition_u_kn
train
def precondition_u_kn(u_kn, N_k, f_k): """Subtract a sample-dependent constant from u_kn to improve precision Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_s...
python
{ "resource": "" }
q247610
solve_mbar_once
train
def solve_mbar_once(u_kn_nonzero, N_k_nonzero, f_k_nonzero, method="hybr", tol=1E-12, options=None): """Solve MBAR self-consistent equations using some form of equation solver. Parameters ---------- u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential ener...
python
{ "resource": "" }
q247611
solve_mbar
train
def solve_mbar(u_kn_nonzero, N_k_nonzero, f_k_nonzero, solver_protocol=None): """Solve MBAR self-consistent equations using some sequence of equation solvers. Parameters ---------- u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log un...
python
{ "resource": "" }
q247612
solve_mbar_for_all_states
train
def solve_mbar_for_all_states(u_kn, N_k, f_k, solver_protocol): """Solve for free energies of states with samples, then calculate for empty states. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized prob...
python
{ "resource": "" }
q247613
construct_nonuniform_bins
train
def construct_nonuniform_bins(x_n, nbins): """Construct histogram using bins of unequal size to ensure approximately equal population in each bin. ARGUMENTS x_n (1D numpy array of floats) - x_n[n] is data point n RETURN VALUES bin_left_boundary_i (1D numpy array of floats) - data in bin i will...
python
{ "resource": "" }
q247614
integratedAutocorrelationTime
train
def integratedAutocorrelationTime(A_n, B_n=None, fast=False, mintime=3): """Estimate the integrated autocorrelation time.
python
{ "resource": "" }
q247615
integratedAutocorrelationTimeMultiple
train
def integratedAutocorrelationTimeMultiple(A_kn, fast=False): """Estimate the integrated autocorrelation time from multiple timeseries. See Also -------- statisticalInefficiencyMultiple
python
{ "resource": "" }
q247616
subsampleCorrelatedData
train
def subsampleCorrelatedData(A_t, g=None, fast=False, conservative=False, verbose=False): """Determine the indices of an uncorrelated subsample of the data. Parameters ---------- A_t : np.ndarray A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector. g : float, optional...
python
{ "resource": "" }
q247617
BARzero
train
def BARzero(w_F, w_R, DeltaF): """A function that when zeroed is equivalent to the solution of the Bennett acceptance ratio. from http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.91.140601 D_F = M + w_F - Delta F D_R = M + w_R - Delta F we want: \sum_N_F (1+exp(D_F))^-1 = \sum N_R N_R <...
python
{ "resource": "" }
q247618
kln_to_kn
train
def kln_to_kn(kln, N_k = None, cleanup = False): """ Convert KxKxN_max array to KxN max array if self.N is not initialized, it will be here. Parameters ---------- u_kln : np.ndarray, float, shape=(KxLxN_max) N_k (optional) : np.array the N_k matrix from the previous formatting form ...
python
{ "resource": "" }
q247619
kn_to_n
train
def kn_to_n(kn, N_k = None, cleanup = False): """ Convert KxN_max array to N array Parameters ---------- u_kn: np.ndarray, float, shape=(KxN_max) N_k (optional) : np.array the N_k matrix from the previous formatting form cleanup (optional) : bool optional command to clean up, s...
python
{ "resource": "" }
q247620
ensure_type
train
def ensure_type(val, dtype, ndim, name, length=None, can_be_none=False, shape=None, warn_on_cast=True, add_newaxis_on_deficient_ndim=False): """Typecheck the size, shape and dtype of a numpy array, with optional casting. Parameters ---------- val : {np.ndaraay, None} The arr...
python
{ "resource": "" }
q247621
logsumexp
train
def logsumexp(a, axis=None, b=None, use_numexpr=True): """Compute the log of the sum of exponentials of input elements. Parameters ---------- a : array_like Input array. axis : None or int, optional, default=None Axis or axes over which the sum is taken. By default `axis` is None, ...
python
{ "resource": "" }
q247622
check_w_normalized
train
def check_w_normalized(W, N_k, tolerance = 1.0e-4): """Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1 Parameters ---------- W : np.ndarray, shape=(N, K), dtype='float' The normalized weight matrix for snapshots and states...
python
{ "resource": "" }
q247623
configuration_callback
train
def configuration_callback(cmd_name, option_name, config_file_name, saved_callback, provider, implicit, ctx, param, value): """ Callback for reading the config file. Also takes care of calling user specified custom callback afterwards. cmd_name : s...
python
{ "resource": "" }
q247624
configuration_option
train
def configuration_option(*param_decls, **attrs): """ Adds configuration file support to a click application. This will create an option of type `click.File` expecting the path to a configuration file. When specified, it overwrites the default values for all other click arguments or options with the...
python
{ "resource": "" }
q247625
decode_value
train
def decode_value(stream): """Decode the contents of a value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded value :rtype:
python
{ "resource": "" }
q247626
decode_tag
train
def decode_tag(stream): """Decode a tag value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded tag :rtype: bytes """
python
{ "resource": "" }
q247627
read
train
def read(*args): """Reads complete file contents."""
python
{ "resource": "" }
q247628
sign_item
train
def sign_item(encrypted_item, signing_key, crypto_config): # type: (dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> dynamodb_types.BINARY_ATTRIBUTE """Generate the signature DynamoDB atttribute. :param dict encrypted_item: Encrypted DynamoDB item :param DelegatedKey signing_key: DelegatedKey to use...
python
{ "resource": "" }
q247629
verify_item_signature
train
def verify_item_signature(signature_attribute, encrypted_item, verification_key, crypto_config): # type: (dynamodb_types.BINARY_ATTRIBUTE, dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> None """Verify the item signature. :param dict signature_attribute: Item signature DynamoDB attribute value :par...
python
{ "resource": "" }
q247630
_string_to_sign
train
def _string_to_sign(item, table_name, attribute_actions): # type: (dynamodb_types.ITEM, Text, AttributeActions) -> bytes """Generate the string to sign from an encrypted item and configuration. :param dict item: Encrypted DynamoDB item :param str table_name: Table name to use when generating the string...
python
{ "resource": "" }
q247631
_hash_data
train
def _hash_data(hasher, data): """Generate hash of data using provided hash type. :param hasher: Hasher instance to use as a base for calculating hash :type hasher: cryptography.hazmat.primitives.hashes.Hash :param bytes data: Data to sign
python
{ "resource": "" }
q247632
serialize
train
def serialize(material_description): # type: (Dict[Text, Text]) -> dynamodb_types.BINARY_ATTRIBUTE """Serialize a material description dictionary into a DynamodDB attribute. :param dict material_description: Material description dictionary :returns: Serialized material description as a DynamoDB binary ...
python
{ "resource": "" }
q247633
deserialize
train
def deserialize(serialized_material_description): # type: (dynamodb_types.BINARY_ATTRIBUTE) -> Dict[Text, Text] """Deserialize a serialized material description attribute into a material description dictionary. :param dict serialized_material_description: DynamoDB attribute value containing serialized mate...
python
{ "resource": "" }
q247634
_read_version
train
def _read_version(material_description_bytes): # type: (io.BytesIO) -> None """Read the version from the serialized material description and raise an error if it is unknown. :param material_description_bytes: serializezd material description :type material_description_bytes: io.BytesIO :raises Inva...
python
{ "resource": "" }
q247635
encrypt_dynamodb_item
train
def encrypt_dynamodb_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Encrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item >>> plaintext_item = { ... 'some': {'S': 'data'}, ... 'more': {'N':...
python
{ "resource": "" }
q247636
encrypt_python_item
train
def encrypt_python_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Encrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item >>> plaintext_item = { ... 'some': 'data', ... 'more': 5 ...
python
{ "resource": "" }
q247637
decrypt_dynamodb_item
train
def decrypt_dynamodb_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Decrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': {'B': b'ENCRYPTED_DATA'}, ... 'mor...
python
{ "resource": "" }
q247638
decrypt_python_item
train
def decrypt_python_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Decrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': Binary(b'ENCRYPTED_DATA'), ......
python
{ "resource": "" }
q247639
dict_to_ddb
train
def dict_to_ddb(item): # type: (Dict[str, Any]) -> Dict[str, Any] # TODO: narrow these types down """Converts a native Python dictionary to a
python
{ "resource": "" }
q247640
ddb_to_dict
train
def ddb_to_dict(item): # type: (Dict[str, Any]) -> Dict[str, Any] # TODO: narrow these types down """Converts a raw DynamoDB item to a native Python dictionary.
python
{ "resource": "" }
q247641
dictionary_validator
train
def dictionary_validator(key_type, value_type): """Validator for ``attrs`` that performs deep type checking of dictionaries.""" def _validate_dictionary(instance, attribute, value): # pylint: disable=unused-argument """Validate that a dictionary is structured as expected. :raises TypeE...
python
{ "resource": "" }
q247642
iterable_validator
train
def iterable_validator(iterable_type, member_type): """Validator for ``attrs`` that performs deep type checking of iterables.""" def _validate_tuple(instance, attribute, value): # pylint: disable=unused-argument """Validate that a dictionary is structured as expected. :raises TypeError...
python
{ "resource": "" }
q247643
callable_validator
train
def callable_validator(instance, attribute, value): # pylint: disable=unused-argument """Validate that an attribute value is callable.
python
{ "resource": "" }
q247644
encrypt_attribute
train
def encrypt_attribute(attribute_name, attribute, encryption_key, algorithm): # type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.BINARY_ATTRIBUTE """Encrypt a single DynamoDB attribute. :param str attribute_name: DynamoDB attribute name :param dict attribute: Plaintext Dy...
python
{ "resource": "" }
q247645
decrypt_attribute
train
def decrypt_attribute(attribute_name, attribute, decryption_key, algorithm): # type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.RAW_ATTRIBUTE """Decrypt a single DynamoDB attribute. :param str attribute_name: DynamoDB attribute name :param dict attribute: Encrypted Dynam...
python
{ "resource": "" }
q247646
_generate_rsa_key
train
def _generate_rsa_key(key_length): """Generate a new RSA private key. :param int key_length: Required key length in bits :returns: DER-encoded private key, private key identifier, and DER encoding identifier :rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`) """ private_...
python
{ "resource": "" }
q247647
encode_value
train
def encode_value(value): # type: (bytes) -> bytes """Encodes the value in Length-Value format. :param value: Value to encode :type value: six.string_types or :class:`boto3.dynamodb_encryption_sdk.types.Binary` :returns: Length-Value
python
{ "resource": "" }
q247648
encrypt_item
train
def encrypt_item(table_name, aws_cmk_id): """Demonstrate use of EncryptedClient to transparently encrypt an item.""" index_key = {"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}} plaintext_item = { "example": {"S": "data"}, "some numbers": {"N": "99"}, "and som...
python
{ "resource": "" }
q247649
encrypt_batch_items
train
def encrypt_batch_items(table_name, aws_cmk_id): """Demonstrate use of EncryptedClient to transparently encrypt multiple items in a batch request.""" index_keys = [ {"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}}, {"partition_attribute": {"S": "is this"}, "sort_attribute...
python
{ "resource": "" }
q247650
load_rsa_key
train
def load_rsa_key(key, key_type, key_encoding): # (bytes, EncryptionKeyType, KeyEncodingType) -> Any # TODO: narrow down the output type """Load an RSA key object from the provided raw key bytes. :param bytes key: Raw key bytes to load :param EncryptionKeyType key_type: Type of key to load :para...
python
{ "resource": "" }
q247651
JavaSymmetricEncryptionAlgorithm._disable_encryption
train
def _disable_encryption(self): # () -> None """Enable encryption methods for
python
{ "resource": "" }
q247652
JavaSymmetricEncryptionAlgorithm.wrap
train
def wrap(self, wrapping_key, key_to_wrap): # type: (bytes, bytes) -> bytes """Wrap key using AES keywrap. :param bytes wrapping_key: Loaded key with which to wrap :param bytes key_to_wrap: Raw key to wrap :returns: Wrapped key :rtype: bytes """ if self.ja...
python
{ "resource": "" }
q247653
JavaSymmetricEncryptionAlgorithm.unwrap
train
def unwrap(self, wrapping_key, wrapped_key): # type: (bytes, bytes) -> bytes """Unwrap key using AES keywrap. :param bytes wrapping_key: Loaded key with which to unwrap :param bytes wrapped_key: Wrapped key to unwrap :returns: Unwrapped key :rtype: bytes
python
{ "resource": "" }
q247654
_validate_attribute_values_are_ddb_items
train
def _validate_attribute_values_are_ddb_items(instance, attribute, value): # pylint: disable=unused-argument """Validate that dictionary values in ``value`` match the structure of DynamoDB JSON items. .. note:: We are not trying to validate the full structure of the item with this validator. ...
python
{ "resource": "" }
q247655
validate_get_arguments
train
def validate_get_arguments(kwargs): # type: (Dict[Text, Any]) -> None """Verify that attribute filtering parameters are not found in the request. :raises InvalidArgumentError: if banned parameters are found """ for arg in ("AttributesToGet", "ProjectionExpression"): if arg in kwargs: ...
python
{ "resource": "" }
q247656
crypto_config_from_kwargs
train
def crypto_config_from_kwargs(fallback, **kwargs): """Pull all encryption-specific parameters from the request and use them to build a crypto config. :returns: crypto config and updated kwargs :rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict """ try: crypto_config = kwargs.po...
python
{ "resource": "" }
q247657
crypto_config_from_table_info
train
def crypto_config_from_table_info(materials_provider, attribute_actions, table_info): """Build a crypto config from the provided values and table info. :returns: crypto config and updated kwargs :rtype: tuple(CryptoConfig, dict) """ ec_kwargs = table_info.encryption_context_values
python
{ "resource": "" }
q247658
crypto_config_from_cache
train
def crypto_config_from_cache(materials_provider, attribute_actions, table_info_cache, table_name): """Build a crypto config from the provided values, loading the table info from the provided cache. :returns: crypto config and updated kwargs :rtype: tuple(CryptoConfig, dict) """
python
{ "resource": "" }
q247659
decrypt_multi_get
train
def decrypt_multi_get(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt multiple items after getting them from the table with a scan or query method. :param callable decrypt_method: Metho...
python
{ "resource": "" }
q247660
decrypt_get_item
train
def decrypt_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt an item after getting it from the table. :param callable decrypt_method: Method to use to decrypt item :param ca...
python
{ "resource": "" }
q247661
decrypt_batch_get_item
train
def decrypt_batch_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt multiple items after getting them in a batch request. :param callable decrypt_method: Method to use to decrypt...
python
{ "resource": "" }
q247662
encrypt_put_item
train
def encrypt_put_item(encrypt_method, crypto_config_method, write_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently encrypt an item before putting it to the table. :param callable encrypt_method: Method to use to encrypt items :param c...
python
{ "resource": "" }
q247663
encrypt_batch_write_item
train
def encrypt_batch_write_item(encrypt_method, crypto_config_method, write_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently encrypt multiple items before putting them in a batch request. :param callable encrypt_method: Method to use to enc...
python
{ "resource": "" }
q247664
_process_batch_write_response
train
def _process_batch_write_response(request, response, table_crypto_config): # type: (Dict, Dict, Dict[Text, CryptoConfig]) -> Dict """Handle unprocessed items in the response from a transparently encrypted write. :param dict request: The DynamoDB plaintext request dictionary :param dict response: The Dy...
python
{ "resource": "" }
q247665
_item_attributes_match
train
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item): # type: (CryptoConfig, Dict, Dict) -> Bool """Determines whether the unencrypted values in the plaintext items attributes are the same as those in the encrypted item. Essentially this uses brute force to cover when we don't know the ...
python
{ "resource": "" }
q247666
CommandResult._feed_line
train
def _feed_line(self, line): """Put the given line into the callback machinery, and set the result on a None line.""" if line is None:
python
{ "resource": "" }
q247667
mpd_command_provider
train
def mpd_command_provider(cls): """Decorator hooking up registered MPD commands to concrete client implementation. A class using this decorator must inherit from ``MPDClientBase`` and implement it's ``add_command`` function. """ def collect(cls, callbacks=dict()): """Collect MPD command ...
python
{ "resource": "" }
q247668
_create_callback
train
def _create_callback(self, function, wrap_result): """Create MPD command related response callback. """ if not isinstance(function, Callable): return None def command_callback(): # command result callback expects response from MPD as iterable lines, # thus read available lines fr...
python
{ "resource": "" }
q247669
_create_command
train
def _create_command(wrapper, name, return_value, wrap_result): """Create MPD command related function. """
python
{ "resource": "" }
q247670
i4_bit_hi1
train
def i4_bit_hi1(n): """ i4_bit_hi1 returns the position of the high 1 bit base 2 in an integer. Example: +------+-------------+----- | N | Binary | BIT +------|-------------+----- | 0 | 0 | 0 | 1 | 1 | 1 | 2 | 10 | 2 ...
python
{ "resource": "" }
q247671
i4_bit_lo0
train
def i4_bit_lo0(n): """ I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer. Example: +------+------------+---- | N | Binary | BIT +------+------------+---- | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 10 | 1 | 3...
python
{ "resource": "" }
q247672
i4_sobol_generate
train
def i4_sobol_generate(dim_num, n, skip=1): """ i4_sobol_generate generates a Sobol dataset. Parameters: Input, integer dim_num, the spatial dimension. Input, integer N, the number of points to generate. Input, integer SKIP, the number of initial points to skip. Output, real R(M,N),...
python
{ "resource": "" }
q247673
i4_sobol_generate_std_normal
train
def i4_sobol_generate_std_normal(dim_num, n, skip=1): """ Generates multivariate standard normal quasi-random variables. Parameters: Input, integer dim_num, the spatial dimension. Input, integer n, the number of points to generate. Input, integer SKIP, the number of initial points to skip...
python
{ "resource": "" }
q247674
i4_uniform
train
def i4_uniform(a, b, seed): """ i4_uniform returns a scaled pseudorandom I4. Discussion: The pseudorandom number will be scaled to be uniformly distributed between A and B. Reference: Paul Bratley, Bennett Fox, Linus Schrage, A Guide to Simulation, Springer Verlag, pages ...
python
{ "resource": "" }
q247675
prime_ge
train
def prime_ge(n): """ PRIME_GE returns the smallest prime greater than or equal to N. Example: +-----+--------- | N | PRIME_GE +-----+--------- | -10 | 2 | 1 | 2 | 2 | 2 | 3 | 3 | 4 |
python
{ "resource": "" }
q247676
is_prime
train
def is_prime(n): """ is_prime returns True if N is a prime number, False otherwise Parameters: Input, integer N, the number to be checked. Output, boolean value, True or False """ if n != int(n) or n < 2: return False
python
{ "resource": "" }
q247677
generate_jwt
train
def generate_jwt(claims, priv_key=None, algorithm='PS512', lifetime=None, expires=None, not_before=None, jti_size=16, other_headers=None): """ Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict ...
python
{ "resource": "" }
q247678
verify_jwt
train
def verify_jwt(jwt, pub_key=None, allowed_algs=None, iat_skew=timedelta(), checks_optional=False, ignore_not_implemented=False): """ Verify a JSON Web Token. :param jwt: The JSON Web Token to verify. :type jwt: str or unicode ...
python
{ "resource": "" }
q247679
process_jwt
train
def process_jwt(jwt): """ Process a JSON Web Token without verifying it. Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key. :param jwt:...
python
{ "resource": "" }
q247680
Benchmark.run
train
def run(self, reporter=None): """This should generally not be overloaded. Runs the benchmark functions that are found in the child class. """ if not reporter: reporter = ConsoleReporter() benchmarks = sorted(self._find_benchmarks()) reporter.write_titles(map(self._...
python
{ "resource": "" }
q247681
Benchmark._find_benchmarks
train
def _find_benchmarks(self): """Return a suite of all tests cases contained in testCaseClass""" def is_bench_method(attrname, prefix="bench"):
python
{ "resource": "" }
q247682
TACACSClient.send
train
def send(self, body, req_type, seq_no=1): """ Send a TACACS+ message body :param body: packed bytes, i.e., `struct.pack(...)` :param req_type: TAC_PLUS_AUTHEN, TAC_PLUS_AUTHOR, TAC_PLUS_ACCT :param seq_no: The sequence numb...
python
{ "resource": "" }
q247683
TACACSClient.authenticate
train
def authenticate(self, username, password, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, chap_ppp_id=None, chap_challenge=None, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authenticate to a ...
python
{ "resource": "" }
q247684
TACACSClient.authorize
train
def authorize(self, username, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authorize with a TACACS+ server. :param username: :param arguments...
python
{ "resource": "" }
q247685
TACACSClient.account
train
def account(self, username, flags, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Account with a TACACS+ server. :param username: :param flags: ...
python
{ "resource": "" }
q247686
GPServiceAccount.__get_user_env_vars
train
def __get_user_env_vars(self): """Return the user defined environment variables""" return (os.environ.get(self.GP_URL_ENV_VAR), os.environ.get(self.GP_INSTANCE_ID_ENV_VAR),
python
{ "resource": "" }
q247687
GPServiceAccount.__parse_vcap_services_env_var
train
def __parse_vcap_services_env_var(self, serviceInstanceName=None): """Parse the ``VCAP_SERVICES`` env var and search for the necessary values """ vcapServices = os.environ.get(self.__VCAP_SERVICES_ENV_VAR) if not vcapServices: return (None, None, None, None, N...
python
{ "resource": "" }
q247688
GPClient.__prepare_gprest_call
train
def __prepare_gprest_call(self, requestURL, params=None, headers=None, restType='GET', body=None): """Returns Authorization type and GP headers """ if self.__serviceAccount.is_iam_enabled(): auth = None iam_api_key_header = { self.__AUTHORIZATION_HEA...
python
{ "resource": "" }
q247689
GPClient.__process_gprest_response
train
def __process_gprest_response(self, r=None, restType='GET'): """Returns the processed response for rest calls """ if r is None: logging.info('No response for REST '+restType+' request') return None httpStatus = r.status_code logging.info('HTTP sta...
python
{ "resource": "" }
q247690
GPClient.__perform_rest_call
train
def __perform_rest_call(self, requestURL, params=None, headers=None, restType='GET', body=None): """Returns the JSON representation of the response if the response status was ok, returns ``None`` otherwise. """ auth, headers = self.__prepare_gprest_call(requestURL, params=params, hea...
python
{ "resource": "" }
q247691
GPClient.createReaderUser
train
def createReaderUser(self,accessibleBundles=None): """Creates a new reader user with access to the specified bundle Ids""" url = self.__serviceAccount.get_url() + '/' + \ self.__serviceAccount.get_instance_id()+ '/v2/users/new' headers = {'content-type': 'application/json'}...
python
{ "resource": "" }
q247692
GPClient.__has_language
train
def __has_language(self, bundleId, languageId): """Returns ``True`` if the bundle has the language, ``False`` otherwise
python
{ "resource": "" }
q247693
GPClient.__get_keys_map
train
def __get_keys_map(self, bundleId, languageId, fallback=False): """Returns key-value pairs for the specified language. If fallback is ``True``,
python
{ "resource": "" }
q247694
GPClient.__get_value
train
def __get_value(self, bundleId, languageId, resourceKey, fallback=False): """Returns the value for the key. If fallback is ``True``, source language value is used if translated value is not available. If the key is not found, returns ``None``. """ resourceEntryData = self.__...
python
{ "resource": "" }
q247695
GPClient.get_avaliable_languages
train
def get_avaliable_languages(self, bundleId): """Returns a list of avaliable languages in the bundle""" bundleData = self.__get_bundle_data(bundleId) if not bundleData: return [] sourceLanguage = bundleData.get(self.__RESPONSE_SRC_LANGUAGE_KEY) languages
python
{ "resource": "" }
q247696
GPClient.create_bundle
train
def create_bundle(self, bundleId, data=None): """Creates a bundle using Globalization Pipeline service""" headers={'content-type':'application/json'} url = self.__get_base_bundle_url() + "/" + bundleId if data is None: data = {} data['sourceLanguage'] = 'en'...
python
{ "resource": "" }
q247697
GPClient.update_resource_entry
train
def update_resource_entry(self, bundleId, languageId, resourceKey, data=None): """Updates the resource entry for a particular key in a target language for a specific bundle in the globalization pipeline""" headers={'content-type':'application/json'} url = self.__get_base_bundle_ur...
python
{ "resource": "" }
q247698
GPTranslations.__get_return_value
train
def __get_return_value(self, messageKey, value): """Determines the return value; used to prevent code duplication """ # if value is not None, return it # otherwise, either use the Translations fallback if there is one, # or return the message key back if value:
python
{ "resource": "" }
q247699
_find_library_candidates
train
def _find_library_candidates(library_names, library_file_extensions, library_search_paths): """ Finds and returns filenames which might be the library you are looking for. """ candidates = set() for library_name in library_names: for ...
python
{ "resource": "" }