sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def __normalize(self):
"""
Adjusts the values of the filters to be correct.
For example, if you set grade 'B' to True, then 'All'
should be set to False
"""
# Don't normalize if we're already normalizing or intializing
if self.__normalizing is True or self.__init... | Adjusts the values of the filters to be correct.
For example, if you set grade 'B' to True, then 'All'
should be set to False | entailment |
def validate_one(self, loan):
"""
Validate a single loan result record against the filters
Parameters
----------
loan : dict
A single loan note record
Returns
-------
boolean
True or raises FilterValidationError
Raises
... | Validate a single loan result record against the filters
Parameters
----------
loan : dict
A single loan note record
Returns
-------
boolean
True or raises FilterValidationError
Raises
------
FilterValidationError
... | entailment |
def search_string(self):
""""
Returns the JSON string that LendingClub expects for it's search
"""
self.__normalize()
# Get the template
tmpl_source = unicode(open(self.tmpl_file).read())
# Process template
compiler = Compiler()
template = compil... | Returns the JSON string that LendingClub expects for it's search | entailment |
def all_filters(lc):
"""
Get a list of all your saved filters
Parameters
----------
lc : :py:class:`lendingclub.LendingClub`
An instance of the authenticated LendingClub class
Returns
-------
list
A list of lendingclub.filters.Sav... | Get a list of all your saved filters
Parameters
----------
lc : :py:class:`lendingclub.LendingClub`
An instance of the authenticated LendingClub class
Returns
-------
list
A list of lendingclub.filters.SavedFilter objects | entailment |
def load(self):
"""
Load the filter from the server
"""
# Attempt to load the saved filter
payload = {
'id': self.id
}
response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload)
self.response = response
json_respo... | Load the filter from the server | entailment |
def __analyze(self):
"""
Analyze the filter JSON and attempt to parse out the individual filters.
"""
filter_values = {}
# ID to filter name mapping
name_map = {
10: 'grades',
11: 'loan_purpose',
13: 'approved',
15: 'fundin... | Analyze the filter JSON and attempt to parse out the individual filters. | entailment |
def _float_copy_to_out(out, origin):
"""
Copy origin to out and return it.
If ``out`` is None, a new copy (casted to floating point) is used. If
``out`` and ``origin`` are the same, we simply return it. Otherwise we
copy the values.
"""
if out is None:
out = origin / 1 # The divis... | Copy origin to out and return it.
If ``out`` is None, a new copy (casted to floating point) is used. If
``out`` and ``origin`` are the same, we simply return it. Otherwise we
copy the values. | entailment |
def _double_centered_imp(a, out=None):
"""
Real implementation of :func:`double_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2.
"""
out = _float_copy_to_out(out, a)
dim = np.size(a, 0)
mu = np.sum(a) / (dim * dim)
sum_cols = np.sum(a, 0, keepd... | Real implementation of :func:`double_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2. | entailment |
def _u_centered_imp(a, out=None):
"""
Real implementation of :func:`u_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2.
"""
out = _float_copy_to_out(out, a)
dim = np.size(a, 0)
u_mu = np.sum(a) / ((dim - 1) * (dim - 2))
sum_cols = np.sum(a, 0, k... | Real implementation of :func:`u_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2. | entailment |
def u_product(a, b):
r"""
Inner product in the Hilbert space of :math:`U`-centered distance matrices.
This inner product is defined as
.. math::
\frac{1}{n(n-3)} \sum_{i,j=1}^n a_{i, j} b_{i, j}
Parameters
----------
a: array_like
First input array to be multiplied.
b:... | r"""
Inner product in the Hilbert space of :math:`U`-centered distance matrices.
This inner product is defined as
.. math::
\frac{1}{n(n-3)} \sum_{i,j=1}^n a_{i, j} b_{i, j}
Parameters
----------
a: array_like
First input array to be multiplied.
b: array_like
Secon... | entailment |
def u_projection(a):
r"""
Return the orthogonal projection function over :math:`a`.
The function returned computes the orthogonal projection over
:math:`a` in the Hilbert space of :math:`U`-centered distance
matrices.
The projection of a matrix :math:`B` over a matrix :math:`A`
is defined ... | r"""
Return the orthogonal projection function over :math:`a`.
The function returned computes the orthogonal projection over
:math:`a` in the Hilbert space of :math:`U`-centered distance
matrices.
The projection of a matrix :math:`B` over a matrix :math:`A`
is defined as
.. math::
... | entailment |
def u_complementary_projection(a):
r"""
Return the orthogonal projection function over :math:`a^{\perp}`.
The function returned computes the orthogonal projection over
:math:`a^{\perp}` (the complementary projection over a)
in the Hilbert space of :math:`U`-centered distance matrices.
The proj... | r"""
Return the orthogonal projection function over :math:`a^{\perp}`.
The function returned computes the orthogonal projection over
:math:`a^{\perp}` (the complementary projection over a)
in the Hilbert space of :math:`U`-centered distance matrices.
The projection of a matrix :math:`B` over a mat... | entailment |
def _distance_matrix_generic(x, centering, exponent=1):
"""Compute a centered distance matrix given a matrix."""
_check_valid_dcov_exponent(exponent)
x = _transform_to_2d(x)
# Calculate distance matrices
a = distances.pairwise_distances(x, exponent=exponent)
# Double centering
a = centeri... | Compute a centered distance matrix given a matrix. | entailment |
def _af_inv_scaled(x):
"""Scale a random vector for using the affinely invariant measures"""
x = _transform_to_2d(x)
cov_matrix = np.atleast_2d(np.cov(x, rowvar=False))
cov_matrix_power = _mat_sqrt_inv(cov_matrix)
return x.dot(cov_matrix_power) | Scale a random vector for using the affinely invariant measures | entailment |
def partial_distance_covariance(x, y, z):
"""
Partial distance covariance estimator.
Compute the estimator for the partial distance covariance of the
random vectors corresponding to :math:`x` and :math:`y` with respect
to the random variable corresponding to :math:`z`.
Parameters
---------... | Partial distance covariance estimator.
Compute the estimator for the partial distance covariance of the
random vectors corresponding to :math:`x` and :math:`y` with respect
to the random variable corresponding to :math:`z`.
Parameters
----------
x: array_like
First random vector. The c... | entailment |
def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals
"""
Partial distance correlation estimator.
Compute the estimator for the partial distance correlation of the
random vectors corresponding to :math:`x` and :math:`y` with respect
to the random variable corresponding to :ma... | Partial distance correlation estimator.
Compute the estimator for the partial distance correlation of the
random vectors corresponding to :math:`x` and :math:`y` with respect
to the random variable corresponding to :math:`z`.
Parameters
----------
x: array_like
First random vector. The... | entailment |
def _energy_distance_from_distance_matrices(
distance_xx, distance_yy, distance_xy):
"""Compute energy distance with precalculated distance matrices."""
return (2 * np.mean(distance_xy) - np.mean(distance_xx) -
np.mean(distance_yy)) | Compute energy distance with precalculated distance matrices. | entailment |
def _energy_distance_imp(x, y, exponent=1):
"""
Real implementation of :func:`energy_distance`.
This function is used to make parameter ``exponent`` keyword-only in
Python 2.
"""
x = _transform_to_2d(x)
y = _transform_to_2d(y)
_check_valid_energy_exponent(exponent)
distance_xx = ... | Real implementation of :func:`energy_distance`.
This function is used to make parameter ``exponent`` keyword-only in
Python 2. | entailment |
def _distance_covariance_sqr_naive(x, y, exponent=1):
"""
Naive biased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm.
"""
a = _distance_matrix(x, exponent=exponent)
b = _distance_matrix(y, e... | Naive biased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm. | entailment |
def _u_distance_covariance_sqr_naive(x, y, exponent=1):
"""
Naive unbiased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm.
"""
a = _u_distance_matrix(x, exponent=exponent)
b = _u_distance_mat... | Naive unbiased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm. | entailment |
def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product,
exponent=1):
"""Compute generic squared stats."""
a = matrix_centered(x, exponent=exponent)
b = matrix_centered(y, exponent=exponent)
covariance_xy_sqr = product(a, b)
variance_x_sqr = produc... | Compute generic squared stats. | entailment |
def _distance_correlation_sqr_naive(x, y, exponent=1):
"""Biased distance correlation estimator between two matrices."""
return _distance_sqr_stats_naive_generic(
x, y,
matrix_centered=_distance_matrix,
product=mean_product,
exponent=exponent).correlation_xy | Biased distance correlation estimator between two matrices. | entailment |
def _u_distance_correlation_sqr_naive(x, y, exponent=1):
"""Bias-corrected distance correlation estimator between two matrices."""
return _distance_sqr_stats_naive_generic(
x, y,
matrix_centered=_u_distance_matrix,
product=u_product,
exponent=exponent).correlation_xy | Bias-corrected distance correlation estimator between two matrices. | entailment |
def _can_use_fast_algorithm(x, y, exponent=1):
"""
Check if the fast algorithm for distance stats can be used.
The fast algorithm has complexity :math:`O(NlogN)`, better than the
complexity of the naive algorithm (:math:`O(N^2)`).
The algorithm can only be used for random variables (not vectors) w... | Check if the fast algorithm for distance stats can be used.
The fast algorithm has complexity :math:`O(NlogN)`, better than the
complexity of the naive algorithm (:math:`O(N^2)`).
The algorithm can only be used for random variables (not vectors) where
the number of instances is greater than 3. Also, t... | entailment |
def _dyad_update(y, c): # pylint:disable=too-many-locals
# This function has many locals so it can be compared
# with the original algorithm.
"""
Inner function of the fast distance covariance.
This function is compiled because otherwise it would become
a bottleneck.
"""
n = y.shape[0... | Inner function of the fast distance covariance.
This function is compiled because otherwise it would become
a bottleneck. | entailment |
def _distance_covariance_sqr_fast_generic(
x, y, unbiased=False): # pylint:disable=too-many-locals
# This function has many locals so it can be compared
# with the original algorithm.
"""Fast algorithm for the squared distance covariance."""
x = np.asarray(x)
y = np.asarray(y)
x = np.r... | Fast algorithm for the squared distance covariance. | entailment |
def _distance_stats_sqr_fast_generic(x, y, dcov_function):
"""Compute the distance stats using the fast algorithm."""
covariance_xy_sqr = dcov_function(x, y)
variance_x_sqr = dcov_function(x, x)
variance_y_sqr = dcov_function(y, y)
denominator_sqr_signed = variance_x_sqr * variance_y_sqr
denomin... | Compute the distance stats using the fast algorithm. | entailment |
def distance_covariance_sqr(x, y, **kwargs):
"""
distance_covariance_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimator for the squared distance covariance
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond with t... | distance_covariance_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimator for the squared distance covariance
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond with the individual random
variables while the rows are... | entailment |
def u_distance_covariance_sqr(x, y, **kwargs):
"""
u_distance_covariance_sqr(x, y, *, exponent=1)
Computes the unbiased estimator for the squared distance covariance
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond with the... | u_distance_covariance_sqr(x, y, *, exponent=1)
Computes the unbiased estimator for the squared distance covariance
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond with the individual random
variables while the rows are ind... | entailment |
def distance_stats_sqr(x, y, **kwargs):
"""
distance_stats_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimators for the squared distance covariance
and squared distance correlation between two random vectors, and the
individual squared distance variances.
Parameters
----------
... | distance_stats_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimators for the squared distance covariance
and squared distance correlation between two random vectors, and the
individual squared distance variances.
Parameters
----------
x: array_like
First random vector. The co... | entailment |
def u_distance_stats_sqr(x, y, **kwargs):
"""
u_distance_stats_sqr(x, y, *, exponent=1)
Computes the unbiased estimators for the squared distance covariance
and squared distance correlation between two random vectors, and the
individual squared distance variances.
Parameters
----------
... | u_distance_stats_sqr(x, y, *, exponent=1)
Computes the unbiased estimators for the squared distance covariance
and squared distance correlation between two random vectors, and the
individual squared distance variances.
Parameters
----------
x: array_like
First random vector. The column... | entailment |
def distance_stats(x, y, **kwargs):
"""
distance_stats(x, y, *, exponent=1)
Computes the usual (biased) estimators for the distance covariance
and distance correlation between two random vectors, and the
individual distance variances.
Parameters
----------
x: array_like
First r... | distance_stats(x, y, *, exponent=1)
Computes the usual (biased) estimators for the distance covariance
and distance correlation between two random vectors, and the
individual distance variances.
Parameters
----------
x: array_like
First random vector. The columns correspond with the in... | entailment |
def distance_correlation_sqr(x, y, **kwargs):
"""
distance_correlation_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimator for the squared distance correlation
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond wit... | distance_correlation_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimator for the squared distance correlation
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond with the individual random
variables while the rows a... | entailment |
def u_distance_correlation_sqr(x, y, **kwargs):
"""
u_distance_correlation_sqr(x, y, *, exponent=1)
Computes the bias-corrected estimator for the squared distance correlation
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond... | u_distance_correlation_sqr(x, y, *, exponent=1)
Computes the bias-corrected estimator for the squared distance correlation
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond with the individual random
variables while the rows... | entailment |
def distance_correlation_af_inv_sqr(x, y):
"""
Square of the affinely invariant distance correlation.
Computes the estimator for the square of the affinely invariant distance
correlation between two random vectors.
.. warning:: The return value of this function is undefined when the
... | Square of the affinely invariant distance correlation.
Computes the estimator for the square of the affinely invariant distance
correlation between two random vectors.
.. warning:: The return value of this function is undefined when the
covariance matrix of :math:`x` or :math:`y` is singu... | entailment |
def pairwise(function, x, y=None, **kwargs):
"""
pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs)
Computes a dependency measure between each pair of elements.
Parameters
----------
function: Dependency measure function.
x: iterable of array_like
First list o... | pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs)
Computes a dependency measure between each pair of elements.
Parameters
----------
function: Dependency measure function.
x: iterable of array_like
First list of random vectors. The columns of each vector correspond
... | entailment |
def _pairwise_imp(function, x, y=None, pool=None, is_symmetric=None, **kwargs):
"""
Real implementation of :func:`pairwise`.
This function is used to make several parameters keyword-only in
Python 2.
"""
map_function = pool.map if pool else map
if is_symmetric is None:
is_symmetri... | Real implementation of :func:`pairwise`.
This function is used to make several parameters keyword-only in
Python 2. | entailment |
def _jit(function):
"""
Compile a function using a jit compiler.
The function is always compiled to check errors, but is only used outside
tests, so that code coverage analysis can be performed in jitted functions.
The tests set sys._called_from_test in conftest.py.
"""
import sys
co... | Compile a function using a jit compiler.
The function is always compiled to check errors, but is only used outside
tests, so that code coverage analysis can be performed in jitted functions.
The tests set sys._called_from_test in conftest.py. | entailment |
def _sqrt(x):
"""
Return square root of an ndarray.
This sqrt function for ndarrays tries to use the exponentiation operator
if the objects stored do not supply a sqrt method.
"""
x = np.clip(x, a_min=0, a_max=None)
try:
return np.sqrt(x)
except AttributeError:
exponen... | Return square root of an ndarray.
This sqrt function for ndarrays tries to use the exponentiation operator
if the objects stored do not supply a sqrt method. | entailment |
def _transform_to_2d(t):
"""Convert vectors to column matrices, to always have a 2d shape."""
t = np.asarray(t)
dim = len(t.shape)
assert dim <= 2
if dim < 2:
t = np.atleast_2d(t).T
return t | Convert vectors to column matrices, to always have a 2d shape. | entailment |
def _can_be_double(x):
"""
Return if the array can be safely converted to double.
That happens when the dtype is a float with the same size of
a double or narrower, or when is an integer that can be safely
converted to double (if the roundtrip conversion works).
"""
return ((np.issubdtype(... | Return if the array can be safely converted to double.
That happens when the dtype is a float with the same size of
a double or narrower, or when is an integer that can be safely
converted to double (if the roundtrip conversion works). | entailment |
def _cdist_naive(x, y, exponent=1):
"""Pairwise distance, custom implementation."""
squared_norms = ((x[_np.newaxis, :, :] - y[:, _np.newaxis, :]) ** 2).sum(2)
exponent = exponent / 2
try:
exponent = squared_norms.take(0).from_float(exponent)
except AttributeError:
pass
return ... | Pairwise distance, custom implementation. | entailment |
def _pdist_scipy(x, exponent=1):
"""Pairwise distance between points in a set."""
metric = 'euclidean'
if exponent != 1:
metric = 'sqeuclidean'
distances = _spatial.distance.pdist(x, metric=metric)
distances = _spatial.distance.squareform(distances)
if exponent != 1:
distances... | Pairwise distance between points in a set. | entailment |
def _cdist_scipy(x, y, exponent=1):
"""Pairwise distance between the points in two sets."""
metric = 'euclidean'
if exponent != 1:
metric = 'sqeuclidean'
distances = _spatial.distance.cdist(x, y, metric=metric)
if exponent != 1:
distances **= exponent / 2
return distances | Pairwise distance between the points in two sets. | entailment |
def _pdist(x, exponent=1):
"""
Pairwise distance between points in a set.
As Scipy converts every value to double, this wrapper uses
a less efficient implementation if the original dtype
can not be converted to double.
"""
if _can_be_double(x):
return _pdist_scipy(x, exponent)
... | Pairwise distance between points in a set.
As Scipy converts every value to double, this wrapper uses
a less efficient implementation if the original dtype
can not be converted to double. | entailment |
def _cdist(x, y, exponent=1):
"""
Pairwise distance between points in two sets.
As Scipy converts every value to double, this wrapper uses
a less efficient implementation if the original dtype
can not be converted to double.
"""
if _can_be_double(x) and _can_be_double(y):
return _c... | Pairwise distance between points in two sets.
As Scipy converts every value to double, this wrapper uses
a less efficient implementation if the original dtype
can not be converted to double. | entailment |
def pairwise_distances(x, y=None, **kwargs):
r"""
pairwise_distances(x, y=None, *, exponent=1)
Pairwise distance between points.
Return the pairwise distance between points in two sets, or
in the same set if only one set is passed.
Parameters
----------
x: array_like
An :math:... | r"""
pairwise_distances(x, y=None, *, exponent=1)
Pairwise distance between points.
Return the pairwise distance between points in two sets, or
in the same set if only one set is passed.
Parameters
----------
x: array_like
An :math:`n \times m` array of :math:`n` observations in
... | entailment |
def respond(self,
content=EmptyValue,
content_type=EmptyValue,
always_hash_content=True,
ext=None):
"""
Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=E... | Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=EmptyValue: Byte string of response body that will be sent.
:type content=EmptyValue: str
:param content_type=EmptyValue: content-type header value for response.
... | entailment |
def calculate_payload_hash(payload, algorithm, content_type):
"""Calculates a hash for a given payload."""
p_hash = hashlib.new(algorithm)
parts = []
parts.append('hawk.' + str(HAWK_VER) + '.payload\n')
parts.append(parse_content_type(content_type) + '\n')
parts.append(payload or '')
parts.... | Calculates a hash for a given payload. | entailment |
def calculate_mac(mac_type, resource, content_hash):
"""Calculates a message authorization code (MAC)."""
normalized = normalize_string(mac_type, resource, content_hash)
log.debug(u'normalized resource for mac calc: {norm}'
.format(norm=normalized))
digestmod = getattr(hashlib, resource.cr... | Calculates a message authorization code (MAC). | entailment |
def calculate_ts_mac(ts, credentials):
"""Calculates a message authorization code (MAC) for a timestamp."""
normalized = ('hawk.{hawk_ver}.ts\n{ts}\n'
.format(hawk_ver=HAWK_VER, ts=ts))
log.debug(u'normalized resource for ts mac calc: {norm}'
.format(norm=normalized))
dig... | Calculates a message authorization code (MAC) for a timestamp. | entailment |
def normalize_string(mac_type, resource, content_hash):
"""Serializes mac_type and resource into a HAWK string."""
normalized = [
'hawk.' + str(HAWK_VER) + '.' + mac_type,
normalize_header_attr(resource.timestamp),
normalize_header_attr(resource.nonce),
normalize_header_attr(res... | Serializes mac_type and resource into a HAWK string. | entailment |
def parse_authorization_header(auth_header):
"""
Example Authorization header:
'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and
welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="'
"""
if len(auth_header) > MAX_LENGTH:
raise BadHeaderValue('Header exc... | Example Authorization header:
'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and
welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="' | entailment |
def get_bewit(resource):
"""
Returns a bewit identifier for the resource as a string.
:param resource:
Resource to generate a bewit for
:type resource: `mohawk.base.Resource`
"""
if resource.method != 'GET':
raise ValueError('bewits can only be generated for GET requests')
i... | Returns a bewit identifier for the resource as a string.
:param resource:
Resource to generate a bewit for
:type resource: `mohawk.base.Resource` | entailment |
def parse_bewit(bewit):
"""
Returns a `bewittuple` representing the parts of an encoded bewit string.
This has the following named attributes:
(id, expiration, mac, ext)
:param bewit:
A base64 encoded bewit string
:type bewit: str
"""
decoded_bewit = b64decode(bewit).decode(... | Returns a `bewittuple` representing the parts of an encoded bewit string.
This has the following named attributes:
(id, expiration, mac, ext)
:param bewit:
A base64 encoded bewit string
:type bewit: str | entailment |
def strip_bewit(url):
"""
Strips the bewit parameter out of a url.
Returns (encoded_bewit, stripped_url)
Raises InvalidBewit if no bewit found.
:param url:
The url containing a bewit parameter
:type url: str
"""
m = re.search('[?&]bewit=([^&]+)', url)
if not m:
rai... | Strips the bewit parameter out of a url.
Returns (encoded_bewit, stripped_url)
Raises InvalidBewit if no bewit found.
:param url:
The url containing a bewit parameter
:type url: str | entailment |
def check_bewit(url, credential_lookup, now=None):
"""
Validates the given bewit.
Returns True if the resource has a valid bewit parameter attached,
or raises a subclass of HawkFail otherwise.
:param credential_lookup:
Callable to look up the credentials dict by sender ID.
The cred... | Validates the given bewit.
Returns True if the resource has a valid bewit parameter attached,
or raises a subclass of HawkFail otherwise.
:param credential_lookup:
Callable to look up the credentials dict by sender ID.
The credentials dict must have the keys:
``id``, ``key``, and `... | entailment |
def accept_response(self,
response_header,
content=EmptyValue,
content_type=EmptyValue,
accept_untrusted_content=False,
localtime_offset_in_seconds=0,
timestamp_skew_in_seconds... | Accept a response to this request.
:param response_header:
A `Hawk`_ ``Server-Authorization`` header
such as one created by :class:`mohawk.Receiver`.
:type response_header: str
:param content=EmptyValue: Byte string of the response body received.
:type content=E... | entailment |
def current_state(self):
"""
Returns a ``field -> value`` dict of the current state of the instance.
"""
field_names = set()
[field_names.add(f.name) for f in self._meta.local_fields]
[field_names.add(f.attname) for f in self._meta.local_fields]
return dict([(fiel... | Returns a ``field -> value`` dict of the current state of the instance. | entailment |
def was_persisted(self):
"""
Returns true if the instance was persisted (saved) in its old
state.
Examples::
>>> user = User()
>>> user.save()
>>> user.was_persisted()
False
>>> user = User.objects.get(pk=1)
>>> u... | Returns true if the instance was persisted (saved) in its old
state.
Examples::
>>> user = User()
>>> user.save()
>>> user.was_persisted()
False
>>> user = User.objects.get(pk=1)
>>> user.delete()
>>> user.was_persist... | entailment |
def _trim(cls, s):
"""
Remove trailing colons from the URI back to the first non-colon.
:param string s: input URI string
:returns: URI string with trailing colons removed
:rtype: string
TEST: trailing colons necessary
>>> s = '1:2::::'
>>> CPE._trim(s)... | Remove trailing colons from the URI back to the first non-colon.
:param string s: input URI string
:returns: URI string with trailing colons removed
:rtype: string
TEST: trailing colons necessary
>>> s = '1:2::::'
>>> CPE._trim(s)
'1:2'
TEST: trailing ... | entailment |
def _create_cpe_parts(self, system, components):
"""
Create the structure to store the input type of system associated
with components of CPE Name (hardware, operating system and software).
:param string system: type of system associated with CPE Name
:param dict components: CPE... | Create the structure to store the input type of system associated
with components of CPE Name (hardware, operating system and software).
:param string system: type of system associated with CPE Name
:param dict components: CPE Name components to store
:returns: None
:exception: ... | entailment |
def _get_attribute_components(self, att):
"""
Returns the component list of input attribute.
:param string att: Attribute name to get
:returns: List of Component objects of the attribute in CPE Name
:rtype: list
:exception: ValueError - invalid attribute name
"""... | Returns the component list of input attribute.
:param string att: Attribute name to get
:returns: List of Component objects of the attribute in CPE Name
:rtype: list
:exception: ValueError - invalid attribute name | entailment |
def _pack_edition(self):
"""
Pack the values of the five arguments into the simple edition
component. If all the values are blank, just return a blank.
:returns: "edition", "sw_edition", "target_sw", "target_hw" and "other"
attributes packed in a only value
:rtype: s... | Pack the values of the five arguments into the simple edition
component. If all the values are blank, just return a blank.
:returns: "edition", "sw_edition", "target_sw", "target_hw" and "other"
attributes packed in a only value
:rtype: string
:exception: TypeError - incompa... | entailment |
def as_uri_2_3(self):
"""
Returns the CPE Name as URI string of version 2.3.
:returns: CPE Name as URI string of version 2.3
:rtype: string
:exception: TypeError - incompatible version
"""
uri = []
uri.append("cpe:/")
ordered_comp_parts = {
... | Returns the CPE Name as URI string of version 2.3.
:returns: CPE Name as URI string of version 2.3
:rtype: string
:exception: TypeError - incompatible version | entailment |
def as_wfn(self):
"""
Returns the CPE Name as Well-Formed Name string of version 2.3.
:return: CPE Name as WFN string
:rtype: string
:exception: TypeError - incompatible version
"""
from .cpe2_3_wfn import CPE2_3_WFN
wfn = []
wfn.append(CPE2_3_W... | Returns the CPE Name as Well-Formed Name string of version 2.3.
:return: CPE Name as WFN string
:rtype: string
:exception: TypeError - incompatible version | entailment |
def as_fs(self):
"""
Returns the CPE Name as formatted string of version 2.3.
:returns: CPE Name as formatted string
:rtype: string
:exception: TypeError - incompatible version
"""
fs = []
fs.append("cpe:2.3:")
for i in range(0, len(CPEComponent... | Returns the CPE Name as formatted string of version 2.3.
:returns: CPE Name as formatted string
:rtype: string
:exception: TypeError - incompatible version | entailment |
def _is_alphanum(cls, c):
"""
Returns True if c is an uppercase letter, a lowercase letter,
a digit or an underscore, otherwise False.
:param string c: Character to check
:returns: True if char is alphanumeric or an underscore,
False otherwise
:rtype: boolean... | Returns True if c is an uppercase letter, a lowercase letter,
a digit or an underscore, otherwise False.
:param string c: Character to check
:returns: True if char is alphanumeric or an underscore,
False otherwise
:rtype: boolean
TEST: a wrong character
>>> ... | entailment |
def _pct_encode_uri(cls, c):
"""
Return the appropriate percent-encoding of character c (URI string).
Certain characters are returned without encoding.
:param string c: Character to check
:returns: Encoded character as URI
:rtype: string
TEST:
>>> c = '... | Return the appropriate percent-encoding of character c (URI string).
Certain characters are returned without encoding.
:param string c: Character to check
:returns: Encoded character as URI
:rtype: string
TEST:
>>> c = '.'
>>> CPEComponentSimple._pct_encode_uri... | entailment |
def _is_valid_language(self):
"""
Return True if the value of component in attribute "language" is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean
"""
comp_str = self._encoded_value.lower()
lang_rxc = re.comp... | Return True if the value of component in attribute "language" is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean | entailment |
def _is_valid_part(self):
"""
Return True if the value of component in attribute "part" is valid,
and otherwise False.
:returns: True if value of component is valid, False otherwise
:rtype: boolean
"""
comp_str = self._encoded_value.lower()
part_rxc = re... | Return True if the value of component in attribute "part" is valid,
and otherwise False.
:returns: True if value of component is valid, False otherwise
:rtype: boolean | entailment |
def _parse(self, comp_att):
"""
Check if the value of component is correct in the attribute "comp_att".
:param string comp_att: attribute associated with value of component
:returns: None
:exception: ValueError - incorrect value of component
"""
errmsg = "Invali... | Check if the value of component is correct in the attribute "comp_att".
:param string comp_att: attribute associated with value of component
:returns: None
:exception: ValueError - incorrect value of component | entailment |
def as_fs(self):
"""
Returns the value of component encoded as formatted string.
Inspect each character in value of component.
Certain nonalpha characters pass thru without escaping
into the result, but most retain escaping.
:returns: Formatted string associated with co... | Returns the value of component encoded as formatted string.
Inspect each character in value of component.
Certain nonalpha characters pass thru without escaping
into the result, but most retain escaping.
:returns: Formatted string associated with component
:rtype: string | entailment |
def as_uri_2_3(self):
"""
Returns the value of component encoded as URI string.
Scans an input string s and applies the following transformations:
- Pass alphanumeric characters thru untouched
- Percent-encode quoted non-alphanumerics as needed
- Unquoted special charac... | Returns the value of component encoded as URI string.
Scans an input string s and applies the following transformations:
- Pass alphanumeric characters thru untouched
- Percent-encode quoted non-alphanumerics as needed
- Unquoted special characters are mapped to their special forms.
... | entailment |
def set_value(self, comp_str, comp_att):
"""
Set the value of component. By default, the component has a simple
value.
:param string comp_str: new value of component
:param string comp_att: attribute associated with value of component
:returns: None
:exception: V... | Set the value of component. By default, the component has a simple
value.
:param string comp_str: new value of component
:param string comp_att: attribute associated with value of component
:returns: None
:exception: ValueError - incorrect value of component | entailment |
def _decode(self):
"""
Convert the characters of string s to standard value (WFN value).
Inspect each character in value of component. Copy quoted characters,
with their escaping, into the result. Look for unquoted non
alphanumerics and if not "*" or "?", add escaping.
:... | Convert the characters of string s to standard value (WFN value).
Inspect each character in value of component. Copy quoted characters,
with their escaping, into the result. Look for unquoted non
alphanumerics and if not "*" or "?", add escaping.
:exception: ValueError - invalid charact... | entailment |
def _parse(self):
"""
Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name
"""
# CPE Name must not have whitespaces
if (self.cpe_str.find(" ") != -1):
errmsg = "Bad-formed CPE Name: it must not have whitespaces... | Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name | entailment |
def get_attribute_values(self, att_name):
"""
Returns the values of attribute "att_name" of CPE Name.
By default a only element in each part.
:param string att_name: Attribute name to get
:returns: List of attribute values
:rtype: list
:exception: ValueError - in... | Returns the values of attribute "att_name" of CPE Name.
By default a only element in each part.
:param string att_name: Attribute name to get
:returns: List of attribute values
:rtype: list
:exception: ValueError - invalid attribute name | entailment |
def set_value(self, comp_str):
"""
Set the value of component.
:param string comp_str: value of component
:returns: None
:exception: ValueError - incorrect value of component
"""
self._is_negated = False
self._encoded_value = comp_str
self._stand... | Set the value of component.
:param string comp_str: value of component
:returns: None
:exception: ValueError - incorrect value of component | entailment |
def _decode(self):
"""
Convert the encoded value of component to standard value (WFN value).
"""
s = self._encoded_value
elements = s.replace('~', '').split('!')
dec_elements = []
for elem in elements:
result = []
idx = 0
whil... | Convert the encoded value of component to standard value (WFN value). | entailment |
def _is_valid_value(self):
"""
Return True if the value of component in generic attribute is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean
"""
comp_str = self._encoded_value
value_pattern = []
valu... | Return True if the value of component in generic attribute is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean | entailment |
def as_wfn(self):
r"""
Returns the value of compoment encoded as Well-Formed Name (WFN)
string.
:returns: WFN string
:rtype: string
TEST:
>>> val = 'xp!vista'
>>> comp1 = CPEComponent1_1(val, CPEComponentSimple.ATT_VERSION)
>>> comp1.as_wfn()
... | r"""
Returns the value of compoment encoded as Well-Formed Name (WFN)
string.
:returns: WFN string
:rtype: string
TEST:
>>> val = 'xp!vista'
>>> comp1 = CPEComponent1_1(val, CPEComponentSimple.ATT_VERSION)
>>> comp1.as_wfn()
'xp\\!vista' | entailment |
def set_value(self, comp_str, comp_att):
"""
Set the value of component. By default, the component has a simple
value.
:param string comp_att: attribute associated with value of component
:returns: None
:exception: ValueError - incorrect value of component
TEST:... | Set the value of component. By default, the component has a simple
value.
:param string comp_att: attribute associated with value of component
:returns: None
:exception: ValueError - incorrect value of component
TEST:
>>> val = 'xp!vista'
>>> val2 = 'sp2'
... | entailment |
def _create_component(cls, att, value):
"""
Returns a component with value "value".
:param string att: Attribute name
:param string value: Attribute value
:returns: Component object created
:rtype: CPEComponent
:exception: ValueError - invalid value of attribute
... | Returns a component with value "value".
:param string att: Attribute name
:param string value: Attribute value
:returns: Component object created
:rtype: CPEComponent
:exception: ValueError - invalid value of attribute | entailment |
def _unpack_edition(cls, value):
"""
Unpack its elements and set the attributes in wfn accordingly.
Parse out the five elements:
~ edition ~ software edition ~ target sw ~ target hw ~ other
:param string value: Value of edition attribute
:returns: Dictionary with parts ... | Unpack its elements and set the attributes in wfn accordingly.
Parse out the five elements:
~ edition ~ software edition ~ target sw ~ target hw ~ other
:param string value: Value of edition attribute
:returns: Dictionary with parts of edition attribute
:exception: ValueError -... | entailment |
def _parse(self):
"""
Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name
"""
# CPE Name must not have whitespaces
if (self._str.find(" ") != -1):
msg = "Bad-formed CPE Name: it must not have whitespaces"
... | Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name | entailment |
def as_wfn(self):
"""
Returns the CPE Name as Well-Formed Name string of version 2.3.
If edition component is not packed, only shows the first seven
components, otherwise shows all.
:return: CPE Name as WFN string
:rtype: string
:exception: TypeError - incompatib... | Returns the CPE Name as Well-Formed Name string of version 2.3.
If edition component is not packed, only shows the first seven
components, otherwise shows all.
:return: CPE Name as WFN string
:rtype: string
:exception: TypeError - incompatible version | entailment |
def _decode(self):
"""
Convert the characters of character in value of component to standard
value (WFN value).
This function scans the value of component and returns a copy
with all percent-encoded characters decoded.
:exception: ValueError - invalid character in value ... | Convert the characters of character in value of component to standard
value (WFN value).
This function scans the value of component and returns a copy
with all percent-encoded characters decoded.
:exception: ValueError - invalid character in value of component | entailment |
def _is_valid_edition(self):
"""
Return True if the input value of attribute "edition" is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean
"""
comp_str = self._standard_value[0]
packed = []
packed.app... | Return True if the input value of attribute "edition" is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean | entailment |
def _is_valid_language(self):
"""
Return True if the value of component in attribute "language" is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean
CASE 1: Language part with/without region part
CASE 2: Language part ... | Return True if the value of component in attribute "language" is valid,
and otherwise False.
:returns: True if value is valid, False otherwise
:rtype: boolean
CASE 1: Language part with/without region part
CASE 2: Language part without region part
CASE 3: Region part wi... | entailment |
def _is_valid_part(self):
"""
Return True if the value of component in attribute "part" is valid,
and otherwise False.
:returns: True if value of component is valid, False otherwise
:rtype: boolean
"""
comp_str = self._encoded_value
# Check if value of ... | Return True if the value of component in attribute "part" is valid,
and otherwise False.
:returns: True if value of component is valid, False otherwise
:rtype: boolean | entailment |
def _compare(cls, source, target):
"""
Compares two values associated with a attribute of two WFNs,
which may be logical values (ANY or NA) or string values.
:param string source: First attribute value
:param string target: Second attribute value
:returns: The attribute ... | Compares two values associated with a attribute of two WFNs,
which may be logical values (ANY or NA) or string values.
:param string source: First attribute value
:param string target: Second attribute value
:returns: The attribute comparison relation.
:rtype: int
This ... | entailment |
def _compare_strings(cls, source, target):
"""
Compares a source string to a target string,
and addresses the condition in which the source string
includes unquoted special characters.
It performs a simple regular expression match,
with the assumption that (as required) ... | Compares a source string to a target string,
and addresses the condition in which the source string
includes unquoted special characters.
It performs a simple regular expression match,
with the assumption that (as required) unquoted special characters
appear only at the beginnin... | entailment |
def _contains_wildcards(cls, s):
"""
Return True if the string contains any unquoted special characters
(question-mark or asterisk), otherwise False.
Ex: _contains_wildcards("foo") => FALSE
Ex: _contains_wildcards("foo\?") => FALSE
Ex: _contains_wildcards("foo?") => TRUE... | Return True if the string contains any unquoted special characters
(question-mark or asterisk), otherwise False.
Ex: _contains_wildcards("foo") => FALSE
Ex: _contains_wildcards("foo\?") => FALSE
Ex: _contains_wildcards("foo?") => TRUE
Ex: _contains_wildcards("\*bar") => FALSE
... | entailment |
def _is_even_wildcards(cls, str, idx):
"""
Returns True if an even number of escape (backslash) characters
precede the character at index idx in string str.
:param string str: string to check
:returns: True if an even number of escape characters precede
the character... | Returns True if an even number of escape (backslash) characters
precede the character at index idx in string str.
:param string str: string to check
:returns: True if an even number of escape characters precede
the character at index idx in string str, False otherwise.
:rtyp... | entailment |
def _is_string(cls, arg):
"""
Return True if arg is a string value,
and False if arg is a logical value (ANY or NA).
:param string arg: string to check
:returns: True if value is a string, False if it is a logical value.
:rtype: boolean
This function is a suppor... | Return True if arg is a string value,
and False if arg is a logical value (ANY or NA).
:param string arg: string to check
:returns: True if value is a string, False if it is a logical value.
:rtype: boolean
This function is a support function for _compare(). | entailment |
def compare_wfns(cls, source, target):
"""
Compares two WFNs and returns a generator of pairwise attribute-value
comparison results. It provides full access to the individual
comparison results to enable use-case specific implementations
of novel name-comparison algorithms.
... | Compares two WFNs and returns a generator of pairwise attribute-value
comparison results. It provides full access to the individual
comparison results to enable use-case specific implementations
of novel name-comparison algorithms.
Compare each attribute of the Source WFN to the Target ... | entailment |
def cpe_disjoint(cls, source, target):
"""
Compares two WFNs and returns True if the set-theoretic relation
between the names is DISJOINT.
:param CPE2_3_WFN source: first WFN CPE Name
:param CPE2_3_WFN target: seconds WFN CPE Name
:returns: True if the set relation betwe... | Compares two WFNs and returns True if the set-theoretic relation
between the names is DISJOINT.
:param CPE2_3_WFN source: first WFN CPE Name
:param CPE2_3_WFN target: seconds WFN CPE Name
:returns: True if the set relation between source and target
is DISJOINT, otherwise Fal... | entailment |
def cpe_equal(cls, source, target):
"""
Compares two WFNs and returns True if the set-theoretic relation
between the names is EQUAL.
:param CPE2_3_WFN source: first WFN CPE Name
:param CPE2_3_WFN target: seconds WFN CPE Name
:returns: True if the set relation between sou... | Compares two WFNs and returns True if the set-theoretic relation
between the names is EQUAL.
:param CPE2_3_WFN source: first WFN CPE Name
:param CPE2_3_WFN target: seconds WFN CPE Name
:returns: True if the set relation between source and target
is EQUAL, otherwise False.
... | entailment |
def cpe_subset(cls, source, target):
"""
Compares two WFNs and returns True if the set-theoretic relation
between the names is (non-proper) SUBSET.
:param CPE2_3_WFN source: first WFN CPE Name
:param CPE2_3_WFN target: seconds WFN CPE Name
:returns: True if the set relat... | Compares two WFNs and returns True if the set-theoretic relation
between the names is (non-proper) SUBSET.
:param CPE2_3_WFN source: first WFN CPE Name
:param CPE2_3_WFN target: seconds WFN CPE Name
:returns: True if the set relation between source and target
is SUBSET, othe... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.