output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def from_xml_node(cls, node):
"""Construct a Signal instance from an XML node exported from a Vector
CANoe .dbc file."""
return cls(name=node.find("Name").text,
bit_position=int(node.find("Bitposition").text),
bit_size=int(node.find("Bitsize").text),
... | Implement a Python 3 function for
constructing a Signal instance from an XML node exported from a Vector CANoe.dbc file. | As a python code expert, you are capable of creating scripts from specifications. |
Continuously read data from the source and attempt to parse a valid
message from the buffer of bytes. | How would you explain what the following Python 3 function does
def run(self):
message_buffer = b""
while self.running:
try:
message_buffer += self.source.read_logs()
except DataSourceError as e:
if self.running:
LOG.warn("Can't... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function will compare two strings of X. Y. Z and returns a boolean indicating if the two strings are the same. | How would you explain what the following Python 3 function does
def compare_versions(x, y):
def version_to_tuple(version):
# Trim off the leading v
version_list = version[1:].split('.', 2)
if len(version_list) <= 3:
[version_list.append(0) for _ in range(3 - len(version_list))]
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the extended form of the covariance matrix and factorize the uncertainties of the data points at the specified coordinates. | Make a summary of the following Python 3 code
def compute(self, t, yerr=1.123e-12, check_sorted=True,
A=None, U=None, V=None):
"""
Compute the extended form of the covariance matrix and factorize
Args:
x (array[n]): The independent coordinates of the data points.
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def log_likelihood(self, y, _const=math.log(2.0*math.pi), quiet=False):
"""
Compute the marginalized likelihood of the GP model
The factorized matrix from the previous call to :func:`GP.compute` is
used so ``compute`` must be called first.
Args:
y (array[n]): The ob... | How would you code a function in Python 3 to
compute the marginalized likelihood of the GP model. | As a python code expert, you are capable of creating scripts from specifications. |
def grad_log_likelihood(self, y, quiet=False):
"""
Compute the gradient of the marginalized likelihood
The factorized matrix from the previous call to :func:`GP.compute` is
used so ``compute`` must be called first. The gradient is taken with
respect to the parameters returned by... | Write a Python 3 script to
compute the gradient of the marginalized likelihood of the log likelihood. | You are a Python code generator, capable of creating scripts from specifications. |
Applies the inverse of the covariance matrix to a vector or matrix y | Given the following Python 3 function, write the documentation
def apply_inverse(self, y):
self._recompute()
return self.solver.solve(self._process_input(y)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def dot(self, y, t=None, A=None, U=None, V=None, kernel=None,
check_sorted=True):
"""
Dot the covariance matrix into a vector or matrix
Compute ``K.y`` where ``K`` is the covariance matrix of the GP without
the white noise or ``yerr`` values on the diagonal.
Args:
... | Implement a function in Python 3 to
dot product of the covariance matrix into a vector or matrix. | You are a Python code generator, capable of creating scripts from specifications. |
Compute the conditional predictive distribution of the model at the specified observations at the specified coordinates. | Explain what the following Python 3 code does
def predict(self, y, t=None, return_cov=True, return_var=False):
y = self._process_input(y)
if len(y.shape) > 1:
raise ValueError("dimension mismatch")
if t is None:
xs = self._t
else:
xs = np.ascontiguous... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the covariance matrix at given independent coordinates. | Can you generate the documentation for the following Python 3 function
def get_matrix(self, x1=None, x2=None, include_diagonal=None,
include_general=None):
"""
Get the covariance matrix at given independent coordinates
Args:
x1 (Optional[array[n1]]): The first set... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a random sample from the prior distribution over datasets
. | Given the following Python 3 function, write the documentation
def sample(self, size=None):
self._recompute()
if size is None:
n = np.random.randn(len(self._t))
else:
n = np.random.randn(len(self._t), size)
n = self.solver.dot_L(n)
if size is None:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Sample from the conditional distribution. | How would you explain what the following Python 3 function does
def sample_conditional(self, y, t=None, size=None):
mu, cov = self.predict(y, t, return_cov=True)
return np.random.multivariate_normal(mu, cov, size=size) | As a Python code analyst, you investigate and solve complex coding mysteries |
Compute the value of the term for an array of lags | Can you generate the documentation for the following Python 3 function
def get_value(self, tau):
tau = np.asarray(tau)
(alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,
beta_complex_real, beta_complex_imag) = self.coefficients
k = get_kernel_value(
alpha_real, ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_psd(self, omega):
"""
Compute the PSD of the term for an array of angular frequencies
Args:
omega (array[...]): An array of frequencies where the PSD should
be evaluated.
Returns:
The value of the PSD for each ``omega``. This will have th... | Write a Python 3 function that can
compute the PSD of the term for an array of angular frequencies . | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_complex_coefficients(self, params):
"""
Get the arrays ``alpha_complex_*`` and ``beta_complex_*``
This method should be overloaded by subclasses to return the arrays
``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
and ``beta_complex_imag`` given th... | Create a Python 3 function for
getting the arrays alpha_complex_real alpha_complex_imag beta_complex_real and beta_complex_imag. | You are a Python code generator, capable of creating scripts from specifications. |
def coefficients(self):
"""
All of the coefficient arrays
This property is the concatenation of the results from
:func:`terms.Term.get_real_coefficients` and
:func:`terms.Term.get_complex_coefficients` but it will always return
a tuple of length 6, even if ``alpha_comple... | Can you implement a function in Python 3 that
returns the coefficients of the current term as a tuple of length 6. | You are a Python code architect, reviewing and designing scalable and efficient code |
def pop(self, key, *args):
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
try:
return self.maps[0].pop(key, *args)
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key)) | Write a Python 3 script for
removing *key* from maps [ 0 ] and return its value. Raise KeyError. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create all necessary HDF5 dimension scales. | How would you explain what the following Python 3 function does
def _create_dim_scales(self):
dim_order = self._dim_order.maps[0]
for dim in sorted(dim_order, key=lambda d: dim_order[d]):
if dim not in self._h5group:
size = self._current_dim_sizes[dim]
kwargs ... | As a Python code composer, you craft elegant and concise scripts. |
def _attach_dim_scales(self):
"""Attach dimension scales to all variables."""
for name, var in self.variables.items():
if name not in self.dimensions:
for n, dim in enumerate(var.dimensions):
var._h5ds.dims[n].attach_scale(self._all_h5groups[dim])
... | Write a Python 3 script for
attaching dimension scales to all variables and groups. | You are a Python code architect, reviewing and designing scalable and efficient code |
Detach the dimension scale corresponding to a dimension name. | Can you tell what is the following Python 3 function doing
def _detach_dim_scale(self, name):
for var in self.variables.values():
for n, dim in enumerate(var.dimensions):
if dim == name:
var._h5ds.dims[n].detach_scale(self._all_h5groups[dim])
for subgroup... | As a python code expert, you are capable of creating scripts from specifications. |
multiplies q1 and q2 by q1 and q2 | Here you have a function in Python 3, explain what it does
def multiplyQuats(q1, q2):
return np.array([
q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3],
q1[2]*q2[3] - q2[2]*q1[3] + q1[0]*q2[1] + q2[0]*q1[1],
q1[3]*q2[1] - q2[3]*q1[1] + q1[0]*q2[2] + q2[0]*q1[2],
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def quatInv(q):
"""Returns QBar such that Q*QBar = 1"""
qConj = -q
qConj[0] = -qConj[0]
normSqr = multiplyQuats(q, qConj)[0]
return qConj/normSqr | Write a Python 3 function for
returning QBar such that Q = 1 | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a unit quaternion that will align vec with the z - axis | Can you tell what is the following Python 3 function doing
def alignVec_quat(vec):
alpha = np.arctan2(vec[1], vec[0])
beta = np.arccos(vec[2])
gamma = -alpha*vec[2]
cb = np.cos(0.5*beta)
sb = np.sin(0.5*beta)
return np.array([cb*np.cos(0.5*(alpha + gamma)),
sb*np.sin(0.5*(ga... | You are a Python code architect, reviewing and designing scalable and efficient code |
Given a minimal rotation frame quat transforms vec from the inertial frame to the minimal rotation frame. | Explain what the following Python 3 code does
def transformTimeDependentVector(quat, vec, inverse=0):
qInv = quatInv(quat)
if inverse:
return transformTimeDependentVector(qInv, vec, inverse=0)
return multiplyQuats(quat, multiplyQuats(np.append(np.array([
np.zeros(len(vec[0]))]), vec, 0)... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Transform a vector from the coorbital frame to the inertial frame. | Can you generate the documentation for the following Python 3 function
def transform_vector_coorb_to_inertial(vec_coorb, orbPhase, quat_copr):
# Transform to coprecessing frame
vec_copr = rotate_in_plane(vec_coorb, -orbPhase)
# Transform to inertial frame
vec = transformTimeDependentVector(np.array([q... | As a python code expert, you are capable of creating scripts from specifications. |
Transform error in a vector from the coorbital frame to the inertial frame. Generates distributions in the coorbital frame and transforms them to 1 - simga widths in the inertial frame. | Make a summary of the following Python 3 code
def transform_error_coorb_to_inertial(vec_coorb, vec_err_coorb, orbPhase,
quat_copr):
""" Transform error in a vector from the coorbital frame to the inertial
frame. Generates distributions in the coorbital frame, transforms them
to inertial frame and re... | As a Python code analyst, you investigate and solve complex coding mysteries |
Loads fits from h5file and returns a dictionary of fits. | Can you generate a brief explanation for the following Python 3 code
def _load_fits(self, h5file):
fits = {}
for key in ['mf']:
fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file)
for key in ['chif', 'vf']:
fits[key] = self._load_vector_fit(key, h5file)
... | You are a Python code generator, capable of creating scripts from specifications. |
def _extra_regression_kwargs(self):
""" List of additional kwargs to use in regression tests.
"""
# larger than default sometimes needed when extrapolating
omega_switch_test = 0.019
extra_args = []
extra_args.append({
'omega0': 5e-3,
'PN_approxim... | Create a Python 3 function for
returning a list of additional kwargs to use in regression tests. | You are a Python code generator, capable of creating scripts from specifications. |
def _get_fit_params(self, x, fit_key):
""" Transforms the input parameter to fit parameters for the 7dq2 model.
That is, maps from
x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz]
fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a]
chiHat is defined in Eq.(3) of 1508.07253, but... | Write a Python 3 function for
transforming the input parameter to fit parameters for the 7dq2 model. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _evolve_spins(self, q, chiA0, chiB0, omega0, PN_approximant,
PN_dt, PN_spin0, PN_phase0, omega0_nrsur):
""" Evolves spins of the component BHs from an initial orbital
frequency = omega0 until t=-100 M from the peak of the waveform.
If omega0 < omega0_nrsur, use PN to evolve the s... | Create a Python 3 function for
evolving the spins of the component BHs in the coorbital frame until omega0_nrsur. | You are a Python code generator, capable of creating scripts from specifications. |
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs):
"""Evaluates the surfinBH7dq2 model.
"""
chiA = np.array(chiA)
chiB = np.array(chiB)
# Warn/Exit if extrapolating
allow_extrap = kwargs.pop('allow_extrap', False)
self._check_param_limits(q, chiA, chiB, a... | Create a Python 3 function for
evaluating the surfinBH7dq2 model. | As a Python code analyst, you investigate and solve complex coding mysteries |
Loads data for a fit. | Here you have a function in Python 3, explain what it does
def LoadFits(name):
if name not in fits_collection.keys():
raise Exception('Invalid fit name : %s'%name)
else:
testPath = DataPath() + '/' + fits_collection[name].data_url.split('/')[-1]
if (not os.path.isfile(testPath)):
... | You are a Python code generator, capable of creating scripts from specifications. |
def DownloadData(name='all', data_dir=DataPath()):
""" Downloads fit data to DataPath() diretory.
If name='all', gets all fit data.
"""
if name == 'all':
for tmp_name in fits_collection.keys():
DownloadData(name=tmp_name, data_dir=data_dir)
return
if name not in fits... | Create a Python 3 function to
download fit data to DataPath | You are a Python code generator, capable of creating scripts from specifications. |
Loads the FITS from a given HDF5 file and returns a dictionary of FITS. | Here you have a function in Python 3, explain what it does
def _load_fits(self, h5file):
fits = {}
for key in ['mf', 'chifz', 'vfx', 'vfy']:
fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file)
return fits | You are a Python code generator, capable of creating scripts from specifications. |
Evaluates the surfinBH3dq8 model. | Explain what the following Python 3 code does
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs):
chiA = np.array(chiA)
chiB = np.array(chiB)
# Warn/Exit if extrapolating
allow_extrap = kwargs.pop('allow_extrap', False)
self._check_param_limits(q, chiA, chiB, allow_extrap... | As a Python code composer, you craft elegant and concise scripts. |
Wrapper function for the lal spin evloution function. | Here you have a function in Python 3, explain what it does
def lal_spin_evloution_wrapper(approximant, q, omega0, chiA0, chiB0,
dt, spinO, phaseO):
"""
Inputs:
approximant: 'SpinTaylorT1/T2/T4'
q: Mass ratio (q>=1)
omega0: Initial orbital frequency in diml... | As a python code expert, you are capable of creating scripts from specifications. |
def evolve_pn_spins(q, chiA0, chiB0, omega0, omegaTimesM_final,
approximant='SpinTaylorT4', dt=0.1, spinO=7, phaseO=7):
""" Evolves PN spins from a starting orbital frequency and spins to a final
frequency.
Inputs:
q: Mass ratio (q>=1)
chiA0: Dimless sp... | Can you create a Python 3 function that
evolves PN spins from a starting orbital frequency and spins to a final orbital frequency. | You are a Python code generator, capable of creating scripts from specifications. |
Checks if the scalar value or tuple or list value is NULL. | Explain what the following Python 3 code does
def is_null(value):
if type(value) in (tuple, list):
for v in value:
if v is None:
return True
return False
else:
return value is None | You are a Python code analyst, evaluating scripts for potential improvements. |
def qual(obj):
"""
Return fully qualified name of a class.
"""
return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__) | Create a Python 3 function to
return fully qualified name of a class. | You are a Python code generator, capable of creating scripts from specifications. |
def select(self, txn, from_key=None, to_key=None, return_keys=True, return_values=True, reverse=False, limit=None):
"""
Select all records (key-value pairs) in table, optionally within a given key range.
:param txn: The transaction in which to run.
:type txn: :class:`zlmdb.Transaction`
... | Write a Python 3 script for
returning an iterator over the records in the current table optionally within a given key range. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Count the number of records in the persistent map. | Explain what the following Python 3 code does
def count(self, txn, prefix=None):
key_from = struct.pack('>H', self._slot)
if prefix:
key_from += self._serialize_key(prefix)
kfl = len(key_from)
cnt = 0
cursor = txn._txn.cursor()
has_more = cursor.set_range(key... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Count the number of records in the perstistent map with keys
within the given range. | Can you generate the documentation for the following Python 3 function
def count_range(self, txn, from_key, to_key):
key_from = struct.pack('>H', self._slot) + self._serialize_key(from_key)
to_key = struct.pack('>H', self._slot) + self._serialize_key(to_key)
cnt = 0
cursor = txn._txn.cu... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate a randomly generated string of the form uYRAC - EXQE - AW4T - WWNUV - VN6T. | Can you tell what is the following Python 3 function doing
def _random_string():
rng = random.SystemRandom()
token_value = u''.join(rng.choice(CHARSET) for _ in range(CHAR_GROUPS * CHARS_PER_GROUP))
if CHARS_PER_GROUP > 1:
return GROUP_SEP.join(map(u''.join, zip(*[iter(token_value)] * CHARS_PER_GROU... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a dictionary of h5 groups to dictionaries | Can you generate a brief explanation for the following Python 3 code
def _read_dict(self, f):
d = {}
for k, item in f.items():
if type(item) == h5py._hl.dataset.Dataset:
v = item.value
if type(v) == np.string_:
v = str(v)
if... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None):
""" Loads a single fit
"""
if (fit_key is None) ^ (h5file is None):
raise ValueError("Either specify both fit_key and h5file, or"
" neither")
if not ((fit_key is None) ^ (fit_data is None))... | Write a Python 3 script to
load a single fit from a given hdf5 file. | As a Python code composer, you craft elegant and concise scripts. |
Loads a vector of fits from a hdf5 file | Given the following Python 3 function, write the documentation
def _load_vector_fit(self, fit_key, h5file):
vector_fit = []
for i in range(len(h5file[fit_key].keys())):
fit_data = self._read_dict(h5file[fit_key]['comp_%d'%i])
vector_fit.append(self._load_scalar_fit(fit_data=fit_d... | You are a Python code generator, capable of creating scripts from specifications. |
def _evaluate_fits(self, x, fit_key):
""" Evaluates a particular fit by passing fit_key to self.fits.
Assumes self._get_fit_params() has been overriden.
"""
fit = self.fits[fit_key]
fit_params = self._get_fit_params(np.copy(x), fit_key)
if type(fit) == list:
... | Implement a function in Python 3 to
evaluate a particular fit by passing fit_key to self. fits. | You are a Python code generator, capable of creating scripts from specifications. |
def _check_unused_kwargs(self, kwargs):
""" Call this at the end of call module to check if all the kwargs have
been used. Assumes kwargs were extracted using pop.
"""
if len(kwargs.keys()) != 0:
unused = ""
for k in kwargs.keys():
unused += "'%s',... | Can you implement a function in Python 3 that
checks if all the kwargs have been used. | As a Python code composer, you craft elegant and concise scripts. |
def _check_param_limits(self, q, chiA, chiB, allow_extrap):
""" Checks that params are within allowed range of paramters.
Raises a warning if outside self.soft_param_lims limits and
raises an error if outside self.hard_param_lims.
If allow_extrap=True, skips these checks.
"""
... | Implement a Python 3 function for
checking that the parameters of the current class are within the allowed range of paramters. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the default path for fit data h5 files | Can you generate a brief explanation for the following Python 3 code
def DataPath():
return os.path.abspath('%s/data'%(os.path.dirname( \
os.path.realpath(__file__)))) | As a Python code analyst, you investigate and solve complex coding mysteries |
This function returns a JSON Web token with the message as body. | How would you explain what the following Python 3 function does
def request_object_encryption(msg, service_context, **kwargs):
try:
encalg = kwargs["request_object_encryption_alg"]
except KeyError:
try:
encalg = service_context.behaviour["request_object_encryption_alg"]
excep... | You are a Python code generator, capable of creating scripts from specifications. |
Construct a special redirect_uri to be used when communicating with a single OP. | How would you explain what the following Python 3 function does
def construct_request_uri(local_dir, base_path, **kwargs):
_filedir = local_dir
if not os.path.isdir(_filedir):
os.makedirs(_filedir)
_webpath = base_path
_name = rndstr(10) + ".jwt"
filename = os.path.join(_filedir, _name)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Initializes a set of services with the given service_definitions. | Can you tell what is the following Python 3 function doing
def init_services(service_definitions, service_context, state_db,
client_authn_factory=None):
"""
Initiates a set of services
:param service_definitions: A dictionary cotaining service definitions
:param service_context: A ref... | As a Python code composer, you craft elegant and concise scripts. |
def gather_request_args(self, **kwargs):
"""
Go through the attributes that the message class can contain and
add values if they are missing but exists in the client info or
when there are default values.
:param kwargs: Initial set of attributes.
:return: Possibly augmen... | Implement a function in Python 3 to
gather the arguments that are passed to the request method. | As a Python code composer, you craft elegant and concise scripts. |
def method_args(self, context, **kwargs):
"""
Collect the set of arguments that should be used by a set of methods
:param context: Which service we're working for
:param kwargs: A set of keyword arguments that are added at run-time.
:return: A set of keyword arguments
""... | Create a Python 3 function for
collecting the set of arguments that should be used by a set of methods | As a Python code composer, you craft elegant and concise scripts. |
This method will run the pre_construct methods one by one in the order given. | Explain what the following Python 3 code does
def do_pre_construct(self, request_args, **kwargs):
_args = self.method_args('pre_construct', **kwargs)
post_args = {}
for meth in self.pre_construct:
request_args, _post_args = meth(request_args, service=self, **_args)
post_... | As a Python code analyst, you investigate and solve complex coding mysteries |
def construct(self, request_args=None, **kwargs):
"""
Instantiate the request as a message class instance with
attribute values gathered in a pre_construct method or in the
gather_request_args method.
:param request_args:
:param kwargs: extra keyword arguments
:r... | Write a Python 3 function for
constructing a new message class instance for the specified request. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Initializes the client authentication method. | Explain what the following Python 3 code does
def init_authentication_method(self, request, authn_method,
http_args=None, **kwargs):
"""
Will run the proper client authentication method.
Each such method will place the necessary information in the necessary
... | You are a Python code generator, capable of creating scripts from specifications. |
def construct_request(self, request_args=None, **kwargs):
"""
The method where everything is setup for sending the request.
The request information is gathered and the where and how of sending the
request is decided.
:param request_args: Initial request arguments
:param ... | Create a Python 3 function for
constructing the request for the current locale. | As a Python code composer, you craft elegant and concise scripts. |
Find the service endpoint | How would you explain what the following Python 3 function does
def get_endpoint(self):
if self.endpoint:
return self.endpoint
else:
return self.service_context.provider_info[self.endpoint_name] | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_authn_header(self, request, authn_method, **kwargs):
"""
Construct an authorization specification to be sent in the
HTTP header.
:param request: The service request
:param authn_method: Which authentication/authorization method to use
:param kwargs: Extra keyword... | Can you create a Python 3 function that
constructs an authorization specification to be sent in the HTTP header. | As a Python code analyst, you investigate and solve complex coding mysteries |
Builds the request message and returns the dictionary with the necessary information for the HTTP request. | Can you generate a brief explanation for the following Python 3 code
def get_request_parameters(self, request_body_type="", method="",
authn_method='', request_args=None,
http_args=None, **kwargs):
"""
Builds the request message and construct... | You are a Python code analyst, evaluating scripts for potential improvements. |
Pick out the fragment or query part from a URL. | Here you have a function in Python 3, explain what it does
def get_urlinfo(info):
# If info is a whole URL pick out the query or fragment part
if '?' in info or '#' in info:
parts = urlparse(info)
scheme, netloc, path, params, query, fragment = parts[:6]
# either quer... | As a python code expert, you are capable of creating scripts from specifications. |
def gather_verify_arguments(self):
"""
Need to add some information before running verify()
:return: dictionary with arguments to the verify call
"""
kwargs = {'client_id': self.service_context.client_id,
'iss': self.service_context.issuer,
'... | Write a Python 3 function for
gathering the arguments to pass to verify | As a Python code analyst, you investigate and solve complex coding mysteries |
Parses a response into a message class. | How would you explain what the following Python 3 function does
def parse_response(self, info, sformat="", state="", **kwargs):
if not sformat:
sformat = self.response_body_type
logger.debug('response format: {}'.format(sformat))
if sformat in ['jose', 'jws', 'jwe']:
r... | As a python code expert, you are capable of creating scripts from specifications. |
Get the value of a attribute in the configuration | Can you tell what is the following Python 3 function doing
def get_conf_attr(self, attr, default=None):
if attr in self.conf:
return self.conf[attr]
else:
return default | You are a Python code analyst, evaluating scripts for potential improvements. |
Add code_challenge to an existing set of request arguments. | Given the following Python 3 function, write the documentation
def add_code_challenge(request_args, service, **kwargs):
try:
cv_len = service.service_context.config['code_challenge']['length']
except KeyError:
cv_len = 64 # Use default
# code_verifier: string of length cv_len
code_veri... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_code_verifier(request_args, service, **kwargs):
"""
PKCE RFC 7636 support
To be added as a post_construct method to an
:py:class:`oidcservice.oidc.service.AccessToken` instance
:param service: The service that uses this function
:param request_args: Set of request arguments
:return:... | Write a Python 3 function for
adding code_verifier to the request arguments. | You are a Python code architect, reviewing and designing scalable and efficient code |
def gather_verify_arguments(self):
"""
Need to add some information before running verify()
:return: dictionary with arguments to the verify call
"""
_ctx = self.service_context
kwargs = {
'client_id': _ctx.client_id, 'iss': _ctx.issuer,
'keyjar':... | Write a Python 3 script for
gathering the arguments to pass to verify | As a python code expert, you are capable of creating scripts from specifications. |
Add scope claim to response from the request if not present in the response | Make a summary of the following Python 3 code
def post_parse_response(self, response, **kwargs):
if "scope" not in response:
try:
_key = kwargs['state']
except KeyError:
pass
else:
if _key:
item = self.get_i... | As a python code expert, you are capable of creating scripts from specifications. |
def get_id_token_hint(self, request_args=None, **kwargs):
"""
Add id_token_hint to request
:param request_args:
:param kwargs:
:return:
"""
request_args = self.multiple_extend_request_args(
request_args, kwargs['state'], ['id_token'],
['au... | Can you write a function in Python 3 where it
adds id_token_hint to request_args | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_state(self, key):
"""
Get the state connected to a given key.
:param key: Key into the state database
:return: A :py:class:´oidcservice.state_interface.State` instance
"""
_data = self.state_db.get(key)
if not _data:
raise KeyError(key)
... | Create a Python 3 function for
getting the state connected to a given key. | You are a Python code generator, capable of creating scripts from specifications. |
def store_item(self, item, item_type, key):
"""
Store a service response.
:param item: The item as a :py:class:`oidcmsg.message.Message`
subclass instance or a JSON document.
:param item_type: The type of request or response
:param key: The key under which the inform... | Create a Python 3 function to
store a service response. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_iss(self, key):
"""
Get the Issuer ID
:param key: Key to the information in the state database
:return: The issuer ID
"""
_state = self.get_state(key)
if not _state:
raise KeyError(key)
return _state['iss'] | Implement a function in Python 3 to
get the Issuer ID of the key | As a Python code composer, you craft elegant and concise scripts. |
def get_item(self, item_cls, item_type, key):
"""
Get a piece of information (a request or a response) from the state
database.
:param item_cls: The :py:class:`oidcmsg.message.Message` subclass
that described the item.
:param item_type: Which request/response that is... | Write a Python 3 function that can
get a piece of information from the state database. | As a Python code composer, you craft elegant and concise scripts. |
def extend_request_args(self, args, item_cls, item_type, key,
parameters, orig=False):
"""
Add a set of parameters and their value to a set of request arguments.
:param args: A dictionary
:param item_cls: The :py:class:`oidcmsg.message.Message` subclass
... | How would you code a function in Python 3 to
add a set of parameters and their values to a set of request arguments. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def multiple_extend_request_args(self, args, key, parameters, item_types,
orig=False):
"""
Go through a set of items (by their type) and add the attribute-value
that match the list of parameters to the arguments
If the same parameter occurs in 2 diffe... | Create a Python 3 function for
going through a set of items (by their type) and add the attribute-value that match the list of parameters to the arguments If the same parameter occurs in 2 different items then the value in the later one will be the one used. :param args: Initial set of arguments :param key: Key to the ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def store_X2state(self, x, state, xtyp):
"""
Store the connection between some value (x) and a state value.
This allows us later in the game to find the state if we have x.
:param x: The value of x
:param state: The state value
:param xtyp: The type of value x is (e.g. n... | Create a Python 3 function to
store the connection between some value x and a state value. | You are a Python code generator, capable of creating scripts from specifications. |
def get_state_by_X(self, x, xtyp):
"""
Find the state value by providing the x value.
Will raise an exception if the x value is absent from the state
data base.
:param x: The x value
:return: The state value
"""
_state = self.state_db.get(KEY_PATTERN[xtyp... | How would you code a function in Python 3 to
find the state value by providing the x value. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the local filename of the file that is published from the given webname. | Can you generate a brief explanation for the following Python 3 code
def filename_from_webname(self, webname):
if not webname.startswith(self.base_url):
raise ValueError("Webname doesn't match base_url")
_name = webname[len(self.base_url):]
if _name.startswith('/'):
retu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate a list of request uris that can be used to redirect to a specific path. | Can you tell what is the following Python 3 function doing
def generate_request_uris(self, path):
m = hashlib.sha256()
try:
m.update(as_bytes(self.provider_info['issuer']))
except KeyError:
m.update(as_bytes(self.issuer))
m.update(as_bytes(self.base_url))
... | As a Python code analyst, you investigate and solve complex coding mysteries |
This method creates a set of keys from a JWKS file or RSA key. | Can you generate a brief explanation for the following Python 3 code
def import_keys(self, keyspec):
for where, spec in keyspec.items():
if where == 'file':
for typ, files in spec.items():
if typ == 'rsa':
for fil in files:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def assertion_jwt(client_id, keys, audience, algorithm, lifetime=600):
"""
Create a signed Json Web Token containing some information.
:param client_id: The Client ID
:param keys: Signing keys
:param audience: Who is the receivers for this assertion
:param algorithm: Signing algorithm
:para... | How would you implement a function in Python 3 that
creates a signed Json Web Token containing some information. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find an access token in a number of places. | Here you have a function in Python 3, explain what it does
def find_token(request, token_type, service, **kwargs):
if request is not None:
try:
_token = request[token_type]
except KeyError:
pass
else:
del request[token_type]
# Required under ce... | As a Python code composer, you craft elegant and concise scripts. |
Checks if the client_secret is still valid | Can you generate a brief explanation for the following Python 3 code
def valid_service_context(service_context, when=0):
eta = getattr(service_context, 'client_secret_expires_at', 0)
now = when or utc_time_sans_frac()
if eta != 0 and eta < now:
return False
return True | You are a Python code generator, capable of creating scripts from specifications. |
def construct(self, request, service=None, http_args=None, **kwargs):
"""
Construct a dictionary to be added to the HTTP request headers
:param request: The request
:param service: A
:py:class:`oidcservice.service.Service` instance
:param http_args: HTTP arguments
... | Implement a function in Python 3 to
construct a dictionary of HTTP arguments that can be passed to the HTTP request. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def construct(self, request=None, service=None, http_args=None,
**kwargs):
"""
Constructing the Authorization header. The value of
the Authorization header is "Bearer <access_token>".
:param request: Request class instance
:param service: Service
:param... | Can you implement a function in Python 3 that
constructs the Authorization header. The value of the Authorization header is Bearer <access_token >. | You are a Python code architect, reviewing and designing scalable and efficient code |
Construct a dictionary with HTTP arguments for the A
. | Given the following Python 3 function, write the documentation
def construct(self, request, service=None, http_args=None, **kwargs):
_acc_token = ''
for _token_type in ['access_token', 'refresh_token']:
_acc_token = find_token(request, _token_type, service, **kwargs)
if _acc_tok... | You are a Python code architect, reviewing and designing scalable and efficient code |
def choose_algorithm(self, context, **kwargs):
"""
Pick signing algorithm
:param context: Signing context
:param kwargs: extra keyword arguments
:return: Name of a signing algorithm
"""
try:
algorithm = kwargs["algorithm"]
except KeyError:
... | How would you code a function in Python 3 to
choose a signing algorithm based on the context and keyword arguments. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_signing_key(self, algorithm, service_context):
"""
Pick signing key based on signing algorithm to be used
:param algorithm: Signing algorithm
:param service_context: A
:py:class:`oidcservice.service_context.ServiceContext` instance
:return: A key
"""
... | Create a Python 3 function for
picking signing key based on signing algorithm | As a Python code translator, you convert algorithms and pseudocode into Python. |
Pick a key that matches a given key ID and signing algorithm. | Can you generate a brief explanation for the following Python 3 code
def get_key_by_kid(self, kid, algorithm, service_context):
_key = service_context.keyjar.get_key_by_kid(kid)
if _key:
ktype = alg2keytype(algorithm)
if _key.kty != ktype:
raise NoMatchingKey("Wro... | You are a Python code architect, reviewing and designing scalable and efficient code |
def construct(self, request, service=None, http_args=None, **kwargs):
"""
Constructs a client assertion and signs it with a key.
The request is modified as a side effect.
:param request: The request
:param service: A :py:class:`oidcservice.service.Service` instance
:para... | Write a Python 3 script for
constructing a client assertion and signs it with a key. | You are a Python code architect, reviewing and designing scalable and efficient code |
Find the issuer ID and from it construct the service endpoint | Here you have a function in Python 3, explain what it does
def get_endpoint(self):
try:
_iss = self.service_context.issuer
except AttributeError:
_iss = self.endpoint
if _iss.endswith('/'):
return OIDCONF_PATTERN.format(_iss[:-1])
else:
re... | As a Python code composer, you craft elegant and concise scripts. |
def _update_service_context(self, resp, **kwargs):
"""
Deal with Provider Config Response. Based on the provider info
response a set of parameters in different places needs to be set.
:param resp: The provider info response
:param service_context: Information collected/used by s... | Write a Python 3 function that can
deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. | You are a Python code generator, capable of creating scripts from specifications. |
def query(self, resource):
"""
Given a resource identifier find the domain specifier and then
construct the webfinger request. Implements
http://openid.net/specs/openid-connect-discovery-1_0.html#NormalizationSteps
:param resource:
"""
if resource[0] in ['=', '@'... | Create a Python 3 function for
giving a resource identifier find the domain specifier and then construct the webfinger request. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_http_url(url, req, method='GET'):
"""
Add a query part representing the request to a url that may already contain
a query part. Only done if the HTTP method used is 'GET' or 'DELETE'.
:param url: The URL
:param req: The request as a :py:class:`oidcmsg.message.Message` instance
:param me... | How would you implement a function in Python 3 that
returns the url that may already contain a query part. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the HTTP body part of a service request. | Given the following Python 3 function, write the documentation
def get_http_body(req, content_type=URL_ENCODED):
if URL_ENCODED in content_type:
return req.to_urlencoded()
elif JSON_ENCODED in content_type:
return req.to_json()
elif JOSE_ENCODED in content_type:
return req # already... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a random ascii character or digits of the given length. | How would you explain what the following Python 3 function does
def rndstr(size=16):
_basech = string.ascii_letters + string.digits
return "".join([rnd.choice(_basech) for _ in range(size)]) | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_redirect_uris(request_args, service=None, **kwargs):
"""
Add redirect_uris to the request arguments.
:param request_args: Incomming request arguments
:param service: A link to the service
:param kwargs: Possible extra keyword arguments
:return: A possibly augmented set of request argume... | Write a Python 3 script to
add redirect_uris to the request arguments. | You are a Python code analyst, evaluating scripts for potential improvements. |
Match the client preferences against what the provider can do. | How would you explain what the following Python 3 function does
def match_preferences(self, pcr=None, issuer=None):
if not pcr:
pcr = self.service_context.provider_info
regreq = oidc.RegistrationRequest
for _pref, _prov in PREFERENCE2PROVIDER.items():
try:
... | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.