code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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 in self.groups.values(): if dim not in subgroup._h5group: ...
def _detach_dim_scale(self, name)
Detach the dimension scale corresponding to a dimension name.
4.773755
4.551906
1.048737
if self.dimensions[dimension] is not None: raise ValueError("Dimension '%s' is not unlimited and thus " "cannot be resized." % dimension) # Resize the dimension. self._current_dim_sizes[dimension] = size for var in self.variables.values...
def resize_dimension(self, dimension, size)
Resize a dimension to a certain size. It will pad with the underlying HDF5 data sets' fill values (usually zero) where necessary.
3.789677
3.432199
1.104154
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], q1[1]*q2[2] - q2[1]*q1[2] + q1[0]*q2[3] + q2[0]*q1[3]])
def multiplyQuats(q1, q2)
q1, q2 must be [scalar, x, y, z] but those may be arrays or scalars
1.308399
1.307145
1.000959
qConj = -q qConj[0] = -qConj[0] normSqr = multiplyQuats(q, qConj)[0] return qConj/normSqr
def quatInv(q)
Returns QBar such that Q*QBar = 1
4.708818
5.046292
0.933124
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*(gamma - alpha)), sb*np.cos(0.5*(gamma - alpha)), ...
def alignVec_quat(vec)
Returns a unit quaternion that will align vec with the z-axis
2.319339
2.320387
0.999548
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), qInv))[1:]
def transformTimeDependentVector(quat, vec, inverse=0)
Given (for example) a minimal rotation frame quat, transforms vec from the minimal rotation frame to the inertial frame. With inverse=1, transforms from the inertial frame to the minimal rotation frame.
5.230852
5.767856
0.906897
v = chi.T sp = np.sin(phase) cp = np.cos(phase) res = 1.*v res[0] = v[0]*cp + v[1]*sp res[1] = v[1]*cp - v[0]*sp return res.T
def rotate_in_plane(chi, phase)
For transforming spins between the coprecessing and coorbital frames
2.749116
2.803828
0.980487
# Transform to coprecessing frame vec_copr = rotate_in_plane(vec_coorb, -orbPhase) # Transform to inertial frame vec = transformTimeDependentVector(np.array([quat_copr]).T, np.array([vec_copr]).T).T[0] return np.array(vec)
def transform_vector_coorb_to_inertial(vec_coorb, orbPhase, quat_copr)
Given a vector (of size 3) in coorbital frame, orbital phase in coprecessing frame and a minimal rotation frame quat, transforms the vector from the coorbital to the inertial frame.
4.790807
4.328659
1.106765
# for reproducibility np.random.seed(0) # Get distribution in coorbital frame dist_coorb = np.array([np.random.normal(m, s, 1000) for m,s in zip(vec_coorb, vec_err_coorb)]).T # Transform distribution to coprecessing frame dist_copr = rotate_in_plane(dist_coorb, -orbPhase) # ...
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 returns 1-simga widths in the inertial frame.
3.456278
2.963145
1.166422
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) return fits
def _load_fits(self, h5file)
Loads fits from h5file and returns a dictionary of fits.
4.691084
4.427013
1.05965
# larger than default sometimes needed when extrapolating omega_switch_test = 0.019 extra_args = [] extra_args.append({ 'omega0': 5e-3, 'PN_approximant': 'SpinTaylorT4', 'PN_dt': 0.1, 'PN_spin_order': 7, 'PN_phase_ord...
def _extra_regression_kwargs(self)
List of additional kwargs to use in regression tests.
2.930598
2.887976
1.014758
q, chiAz, chiBz = x[0], x[3], x[6] eta = q/(1.+q)**2 chi_wtAvg = (q*chiAz+chiBz)/(1.+q) chiHat = (chi_wtAvg - 38.*eta/113.*(chiAz + chiBz))/(1. - 76.*eta/113.) chi_a = (chiAz - chiBz)/2. fit_params = x fit_params[0] = np.log(q) fit_params[3] = ch...
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 with chiAz and chiBz instead of chiA and chiB....
5.261687
3.632421
1.448535
if omega0 < omega0_nrsur: # If omega0 is below the NRSur7dq2 start frequency, we use PN # to evolve the spins until orbital frequency = omega0_nrsur. # Note that we update omega0_nrsur here with the PN # frequency that was closest to the input omega0_nr...
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 spins until orbital frequency = omega0. Then evolves further with the NRSur7dq2 waveform model until t=-100M from the...
3.340267
2.857323
1.16902
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) omega0 = kwargs.pop('omega0', None) PN_approximant = kwargs.pop('PN_approxima...
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs)
Evaluates the surfinBH7dq2 model.
2.779106
2.774267
1.001744
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)): DownloadData(name) fit = fits_collection[name].fit_class(name...
def LoadFits(name)
Loads data for a fit. If data is not available, downloads it before loading.
5.930563
5.571562
1.064435
if name == 'all': for tmp_name in fits_collection.keys(): DownloadData(name=tmp_name, data_dir=data_dir) return if name not in fits_collection.keys(): raise Exception('Invalid fit name : %s'%name) print('Downloading %s data'%name) data_url = fits_collection[nam...
def DownloadData(name='all', data_dir=DataPath())
Downloads fit data to DataPath() diretory. If name='all', gets all fit data.
2.247849
2.302146
0.976415
fits = {} for key in ['mf', 'chifz', 'vfx', 'vfy']: fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file) return fits
def _load_fits(self, h5file)
Loads fits from h5file and returns a dictionary of fits.
8.751637
8.075635
1.083709
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) self._check_unused_kwargs(kwargs) x = [q, chiA[2], chiB[2]] if fit_k...
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs)
Evaluates the surfinBH3dq8 model.
2.132817
2.149694
0.992149
omega, phi, chiA, chiB, lNhat, e1 = lal_spin_evloution_wrapper(approximant, q, omega0, chiA0, chiB0, dt, spinO, phaseO) # Compute omega, inertial spins, angular momentum direction and orbital # phase when omega = omegaTimesM_final end_idx = np.argmin(np.abs(omega - omegaTimesM_final)) ...
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 spin of BhA at initial freq. chiB0: Dimless spin of BhB at initial freq. omega0: Initial orbital freque...
3.783738
3.16295
1.196269
if type(value) in (tuple, list): for v in value: if v is None: return True return False else: return value is None
def is_null(value)
Check if the scalar value or tuple/list value is NULL. :param value: Value to check. :type value: a scalar or tuple or list :return: Returns ``True`` if and only if the value is NULL (scalar value is None or _any_ tuple/list elements are None). :rtype: bool
2.518008
2.712021
0.928462
return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__)
def qual(obj)
Return fully qualified name of a class.
5.015184
3.926693
1.277203
assert type(return_keys) == bool assert type(return_values) == bool assert type(reverse) == bool assert limit is None or (type(limit) == int and limit > 0 and limit < 10000000) return PersistentMapIterator(txn, self, ...
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` :param from_key: Return records starting from (and including) this key. :type from_key: object :param to_key: ...
1.952073
2.286962
0.853566
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_from) while has_more: _key = cursor.key() ...
def count(self, txn, prefix=None)
Count number of records in the persistent map. When no prefix is given, the total number of records is returned. When a prefix is given, only the number of records with keys that have this prefix are counted. :param txn: The transaction in which to run. :type txn: :class:`zlmdb....
3.633453
3.998526
0.908698
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.cursor() has_more = cursor.set_range(key_from) while has_more: if cursor.key() >= ...
def count_range(self, txn, from_key, to_key)
Counter number of records in the perstistent map with keys within the given range. :param txn: The transaction in which to run. :type txn: :class:`zlmdb.Transaction` :param from_key: Count records starting and including from this key. :type from_key: object :param to_k...
2.853572
3.047471
0.936374
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_GROUP))) else: return token_value
def _random_string()
Generate a globally unique serial / product code of the form ``u'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'``. The generated value is cryptographically strong and has (at least) 114 bits of entropy. :return: new random string key
3.780056
3.962365
0.95399
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 type(v) == str and v == "NONE": d[k] = None elif...
def _read_dict(self, f)
Converts h5 groups to dictionaries
2.427604
2.282336
1.063649
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)): raise ValueError("Specify exactly one of fit_key and fit_data.") if fit_data is N...
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None)
Loads a single fit
3.219804
3.221387
0.999509
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_data)) return vector_fit
def _load_vector_fit(self, fit_key, h5file)
Loads a vector of fits
3.239037
3.128265
1.03541
fit = self.fits[fit_key] fit_params = self._get_fit_params(np.copy(x), fit_key) if type(fit) == list: res = [] for i in range(len(fit)): res.append(fit[i](fit_params)) return np.array(res) else: return fit(fit_param...
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.
2.328681
2.113578
1.101772
if len(kwargs.keys()) != 0: unused = "" for k in kwargs.keys(): unused += "'%s', "%k if unused[-2:] == ", ": # get rid of trailing comma unused = unused[:-2] raise Exception('Unused keys in kwargs: %s'%unused)
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.
3.977343
3.796614
1.047603
if q < 1: raise ValueError('Mass ratio should be >= 1.') chiAmag = np.sqrt(np.sum(chiA**2)) chiBmag = np.sqrt(np.sum(chiB**2)) if chiAmag > 1 + 1e-14: raise ValueError('Spin magnitude of BhA > 1.') if chiBmag > 1 + 1e-14: raise Value...
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.
2.048388
1.94329
1.054082
def decorate(o): assert isinstance(o, PersistentMap) name = o.__class__.__name__ assert slot_index not in self._index_to_slot assert name not in self._name_to_slot o._zlmdb_slot = slot_index o._zlmdb_marshal = marshal ...
def slot(self, slot_index, marshal=None, unmarshal=None, build=None, cast=None, compress=False)
Decorator for use on classes derived from zlmdb.PersistentMap. The decorator define slots in a LMDB database schema based on persistent maps, and slot configuration. :param slot_index: :param marshal: :param unmarshal: :param build: :param cast: :param compress: ...
2.53001
2.221075
1.139092
return os.path.abspath('%s/data'%(os.path.dirname( \ os.path.realpath(__file__))))
def DataPath()
Return the default path for fit data h5 files
4.061231
4.276274
0.949713
try: encalg = kwargs["request_object_encryption_alg"] except KeyError: try: encalg = service_context.behaviour["request_object_encryption_alg"] except KeyError: return msg if not encalg: return msg try: encenc = kwargs["request_objec...
def request_object_encryption(msg, service_context, **kwargs)
Created an encrypted JSON Web token with *msg* as body. :param msg: The mesaqg :param service_context: :param kwargs: :return:
2.26869
2.340202
0.969442
_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) while os.path.exists(filename): _name = rndstr(10) filename = os.path.join(_filedir, _name) _webna...
def construct_request_uri(local_dir, base_path, **kwargs)
Constructs a special redirect_uri to be used when communicating with one OP. Each OP should get their own redirect_uris. :param local_dir: Local directory in which to place the file :param base_path: Base URL to start with :param kwargs: :return: 2-tuple with (filename, url)
2.907377
2.687207
1.081933
service = {} for service_name, service_configuration in service_definitions.items(): try: kwargs = service_configuration['kwargs'] except KeyError: kwargs = {} kwargs.update({'service_context': service_context, 'state_db': state_db, ...
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 reference to the service context, this is the same for all service instances. :param state_db: A reference to the state database. Shared by all the services. :par...
2.263986
2.355318
0.961223
ar_args = kwargs.copy() # Go through the list of claims defined for the message class # there are a couple of places where informtation can be found # access them in the order of priority # 1. A keyword argument # 2. configured set of default attribute values ...
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 augmented set of attributes
5.078773
4.81261
1.055305
try: _args = self.conf[context].copy() except KeyError: _args = kwargs else: _args.update(kwargs) return _args
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
4.528187
5.058547
0.895156
_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_args.update(_post_args) return request_args, post_args
def do_pre_construct(self, request_args, **kwargs)
Will run the pre_construct methods one by one in the order given. :param request_args: Request arguments :param kwargs: Extra key word arguments :return: A tuple of request_args and post_args. post_args are to be used by the post_construct methods.
3.884093
3.311571
1.172885
_args = self.method_args('post_construct', **kwargs) for meth in self.post_construct: request_args = meth(request_args, service=self, **_args) return request_args
def do_post_construct(self, request_args, **kwargs)
Will run the post_construct methods one at the time in order. :param request_args: Request arguments :param kwargs: Arguments used by the post_construct method :return: Possible modified set of request arguments.
5.082613
5.419499
0.937838
if request_args is None: request_args = {} # run the pre_construct methods. Will return a possibly new # set of request arguments but also a set of arguments to # be used by the post_construct methods. request_args, post_args = self.do_pre_construct(request_...
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 :return: message class instance
4.891737
4.758821
1.027931
if http_args is None: http_args = {} if authn_method: logger.debug('Client authn method: {}'.format(authn_method)) return self.client_authn_factory(authn_method).construct( request, self, http_args=http_args, **kwargs) else: ...
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 place. A method may modify the request. :param request: The request, a Message class instance :param authn_method: Client authentication method :param http_ar...
3.114008
3.134629
0.993422
if request_args is None: request_args = {} # remove arguments that should not be included in the request # _args = dict( # [(k, v) for k, v in kwargs.items() if v and k not in SPECIAL_ARGS]) return self.construct(request_args, **kwargs)
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 kwargs: Extra keyword arguments :return: A dictionary with the keys 'u...
4.114796
4.56827
0.900734
if self.endpoint: return self.endpoint else: return self.service_context.provider_info[self.endpoint_name]
def get_endpoint(self)
Find the service endpoint :return: The service endpoint (a URL)
5.725232
6.388963
0.896113
headers = {} # If I should deal with client authentication if authn_method: h_arg = self.init_authentication_method(request, authn_method, **kwargs) try: headers = h_arg['headers'] ex...
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 arguments :return: A set of keyword arguments to be sent in the HTTP hea...
6.101291
6.884531
0.886232
if not method: method = self.http_method if not authn_method: authn_method = self.get_authn_method() if not request_body_type: request_body_type = self.request_body_type request = self.construct_request(request_args=request_args, **kwargs) ...
def get_request_parameters(self, request_body_type="", method="", authn_method='', request_args=None, http_args=None, **kwargs)
Builds the request message and constructs the HTTP headers. This is the starting point for a pipeline that will: - construct the request message - add/remove information to/from the request message in the way a specific client authentication method requires. - gather a set ...
3.081563
3.074028
1.002451
# 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 query of fragment if query: info = query ...
def get_urlinfo(info)
Pick out the fragment or query part from a URL. :param info: A URL possibly containing a query or a fragment part :return: the query/fragment part
4.851365
4.176294
1.161643
kwargs = {'client_id': self.service_context.client_id, 'iss': self.service_context.issuer, 'keyjar': self.service_context.keyjar, 'verify': True} return kwargs
def gather_verify_arguments(self)
Need to add some information before running verify() :return: dictionary with arguments to the verify call
4.151449
3.857609
1.076172
if not sformat: sformat = self.response_body_type logger.debug('response format: {}'.format(sformat)) if sformat in ['jose', 'jws', 'jwe']: resp = self.post_parse_response(info, state=state) if not resp: logger.error('Missing or fa...
def parse_response(self, info, sformat="", state="", **kwargs)
This the start of a pipeline that will: 1 Deserializes a response into it's response message class. Or :py:class:`oidcmsg.oauth2.ErrorResponse` if it's an error message 2 verifies the correctness of the response by running the verify method belonging to...
3.672009
3.476795
1.056148
if attr in self.conf: return self.conf[attr] else: return default
def get_conf_attr(self, attr, default=None)
Get the value of a attribute in the configuration :param attr: The attribute :param default: If the attribute doesn't appear in the configuration return this value :return: The value of attribute in the configuration or the default value
2.791916
4.290189
0.650768
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_verifier = unreserved(cv_len) _cv = code_verifier.encode() try: _method = service.service_context.conf...
def add_code_challenge(request_args, service, **kwargs)
PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :param kwargs: Extra set of keyword arguments :return: Updated set of ...
4.336512
4.291357
1.010522
_item = service.get_item(Message, 'pkce', kwargs['state']) request_args.update({'code_verifier': _item['code_verifier']}) return request_args
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: updated set of request arguments
9.302922
8.08823
1.15018
_ctx = self.service_context kwargs = { 'client_id': _ctx.client_id, 'iss': _ctx.issuer, 'keyjar': _ctx.keyjar, 'verify': True, 'skew': _ctx.clock_skew } for attr, param in IDT2REG.items(): try: kwargs[attr] = _ctx....
def gather_verify_arguments(self)
Need to add some information before running verify() :return: dictionary with arguments to the verify call
4.273291
4.372301
0.977355
if "scope" not in response: try: _key = kwargs['state'] except KeyError: pass else: if _key: item = self.get_item(oauth2.AuthorizationRequest, 'auth_request'...
def post_parse_response(self, response, **kwargs)
Add scope claim to response, from the request, if not present in the response :param response: The response :param kwargs: Extra Keyword arguments :return: A possibly augmented response
5.375845
4.793016
1.1216
request_args = self.multiple_extend_request_args( request_args, kwargs['state'], ['id_token'], ['auth_response', 'token_response', 'refresh_token_response'], orig=True ) try: request_args['id_token_hint'] = request_args['id_token'] ...
def get_id_token_hint(self, request_args=None, **kwargs)
Add id_token_hint to request :param request_args: :param kwargs: :return:
4.125981
4.226713
0.976168
_data = self.state_db.get(key) if not _data: raise KeyError(key) else: return State().from_json(_data)
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
4.555143
4.306129
1.057828
try: _state = self.get_state(key) except KeyError: _state = State() try: _state[item_type] = item.to_json() except AttributeError: _state[item_type] = item self.state_db.set(key, _state.to_json())
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 information should be stored in the state database
2.758956
2.558462
1.078365
_state = self.get_state(key) if not _state: raise KeyError(key) return _state['iss']
def get_iss(self, key)
Get the Issuer ID :param key: Key to the information in the state database :return: The issuer ID
4.233634
4.998006
0.847065
_state = self.get_state(key) try: return item_cls(**_state[item_type]) except TypeError: return item_cls().from_json(_state[item_type])
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 wanted :param key: The key to the information in the stat...
3.679937
4.323036
0.851239
try: item = self.get_item(item_cls, item_type, key) except KeyError: pass else: for parameter in parameters: if orig: try: args[parameter] = item[parameter] except KeyErro...
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 that describes the item :param item_type: The type of item, this is one of the parameter names in the :py:cl...
2.444379
2.191537
1.115372
_state = self.get_state(key) for typ in item_types: try: _item = Message(**_state[typ]) except KeyError: continue for parameter in parameters: if orig: try: args[par...
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 different items then the value in the later one will be the one used. :param args: Initial set of arguments :param key: Key ...
3.195659
2.785017
1.147447
self.state_db.set(KEY_PATTERN[xtyp].format(x), state) try: _val = self.state_db.get("ref{}ref".format(state)) except KeyError: _val = None if _val is None: refs = {xtyp:x} else: refs = json.loads(_val) refs[xty...
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. nonce, ...)
3.571324
3.531453
1.01129
_state = self.state_db.get(KEY_PATTERN[xtyp].format(x)) if _state: return _state else: raise KeyError('Unknown {}: "{}"'.format(xtyp, x))
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
4.764398
4.874802
0.977352
if not webname.startswith(self.base_url): raise ValueError("Webname doesn't match base_url") _name = webname[len(self.base_url):] if _name.startswith('/'): return _name[1:] else: return _name
def filename_from_webname(self, webname)
A 1<->1 map is maintained between a URL pointing to a file and the name of the file in the file system. As an example if the base_url is 'https://example.com' and a jwks_uri is 'https://example.com/jwks_uri.json' then the filename of the corresponding file on the local filesystem would ...
2.724868
2.862839
0.951806
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)) if not path.startswith('/'): return ['{}/{}/{}'.format(self.base_url, path, m...
def generate_request_uris(self, path)
Need to generate a redirect_uri path that is unique for a OP/RP combo This is to counter the mix-up attack. :param path: Leading path :return: A list of one unique URL
2.599536
2.53088
1.027127
for where, spec in keyspec.items(): if where == 'file': for typ, files in spec.items(): if typ == 'rsa': for fil in files: _key = RSAKey( key=import_private_rsa_key_from_f...
def import_keys(self, keyspec)
The client needs it's own set of keys. It can either dynamically create them or load them from local storage. This method can also fetch other entities keys provided the URL points to a JWKS. :param keyspec:
3.856556
4.060597
0.949751
_now = utc_time_sans_frac() at = AuthnToken(iss=client_id, sub=client_id, aud=audience, jti=rndstr(32), exp=_now + lifetime, iat=_now) logger.debug('AuthnToken: {}'.format(at.to_dict())) return at.to_jwt(key=keys, algorithm=algorithm)
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 :param lifetime: The lifetime of the signed Json Web Token :return: A Signed Json We...
3.682144
4.214959
0.87359
if request is not None: try: _token = request[token_type] except KeyError: pass else: del request[token_type] # Required under certain circumstances :-) not under other request.c_param[token_type] = SINGLE_OPTIONAL_STRING ...
def find_token(request, token_type, service, **kwargs)
The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run service. :param request: :param token_type: :param service: ...
10.025249
9.721509
1.031244
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
def valid_service_context(service_context, when=0)
Check if the client_secret has expired :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :param when: A time stamp against which the expiration time is to be checked :return: True if the client_secret is still valid
4.978267
4.168716
1.194197
if http_args is None: http_args = {} if "headers" not in http_args: http_args["headers"] = {} # get the username (client_id) and the password (client_secret) try: passwd = kwargs["password"] except KeyError: try: ...
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 :return: dictionary of HTTP arguments
3.236281
3.19641
1.012474
if service.service_name == 'refresh_token': _acc_token = find_token(request, 'refresh_token', service, **kwargs) else: _acc_token = find_token(request, 'access_token', service, **kwargs) if not _acc_token: raise KeyError('No access or refresh token ...
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 http_args: HTTP header arguments :param kwargs: extra keyword arguments :return:
3.119604
3.011832
1.035783
_acc_token = '' for _token_type in ['access_token', 'refresh_token']: _acc_token = find_token(request, _token_type, service, **kwargs) if _acc_token: break if not _acc_token: raise KeyError('No access or refresh token available') ...
def construct(self, request, service=None, http_args=None, **kwargs)
Will add a token to the request if not present :param request: The request :param service_context: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: extra keyword arguments :return: A possibly modified dictionary with ...
3.818583
3.69623
1.033102
try: algorithm = kwargs["algorithm"] except KeyError: # different contexts uses different signing algorithms algorithm = DEF_SIGN_ALG[context] if not algorithm: raise AuthnFailure("Missing algorithm specification") return algorithm
def choose_algorithm(self, context, **kwargs)
Pick signing algorithm :param context: Signing context :param kwargs: extra keyword arguments :return: Name of a signing algorithm
9.300856
8.635293
1.077075
return service_context.keyjar.get_signing_key( alg2keytype(algorithm), alg=algorithm)
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
6.858477
8.263348
0.829988
_key = service_context.keyjar.get_key_by_kid(kid) if _key: ktype = alg2keytype(algorithm) if _key.kty != ktype: raise NoMatchingKey("Wrong key type") else: return _key else: raise NoMatchingKey("No key with ...
def get_key_by_kid(self, kid, algorithm, service_context)
Pick a key that matches a given key ID and signing algorithm. :param kid: Key ID :param algorithm: Signing algorithm :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :return: A matching key
3.148735
3.304528
0.952855
if 'client_assertion' in kwargs: request["client_assertion"] = kwargs['client_assertion'] if 'client_assertion_type' in kwargs: request[ 'client_assertion_type'] = kwargs['client_assertion_type'] else: request["cli...
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 :param http_args: HTTP arguments :param kwargs: Extra arguments :return: Constr...
3.20893
3.101934
1.034493
try: _iss = self.service_context.issuer except AttributeError: _iss = self.endpoint if _iss.endswith('/'): return OIDCONF_PATTERN.format(_iss[:-1]) else: return OIDCONF_PATTERN.format(_iss)
def get_endpoint(self)
Find the issuer ID and from it construct the service endpoint :return: Service endpoint
4.993871
5.06818
0.985338
issuer = self.service_context.issuer # Verify that the issuer value received is the same as the # url that was used as service endpoint (without the .well-known part) if "issuer" in resp: _pcr_issuer = resp["issuer"] if resp["issuer"].endswith("/"): ...
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 services
4.571503
4.547676
1.005239
if resource[0] in ['=', '@', '!']: # Have no process for handling these raise ValueError('Not allowed resource identifier') try: part = urlsplit(resource) except Exception: raise ValueError('Unparsable resource') else: if not par...
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:
3.276919
3.148183
1.040892
if method in ["GET", "DELETE"]: if req.keys(): _req = req.copy() comp = urlsplit(str(url)) if comp.query: _req.update(parse_qs(comp.query)) _query = str(_req.to_urlencoded()) return urlunsplit((comp.scheme, comp.netloc, comp.p...
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 method: The HTTP method :return: A possibly modified...
3.202357
3.098773
1.033428
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 packaged else: raise UnSupported( "Unsupported content type: '%s'" % content_type)
def get_http_body(req, content_type=URL_ENCODED)
Get the message into the format that should be places in the body part of a HTTP request. :param req: The service request as a :py:class:`oidcmsg.message.Message` instance :param content_type: The format of the body part. :return: The correctly formatet service request.
3.913191
3.79304
1.031677
if ':' in s: c = s.split(':') if len(c) != 2: raise ValueError("Syntax error: {s}") return c[0], c[1] else: c = s.split('.') if len(c) < 2: raise ValueError("Syntax error: {s}") return '.'.join(c[:-1]), c[-1]
def modsplit(s)
Split importable
2.297835
2.292334
1.0024
c1, c2 = modsplit(name) module = importlib.import_module(c1) return getattr(module, c2)
def importer(name)
Import by name
4.874366
4.673959
1.042877
_basech = string.ascii_letters + string.digits return "".join([rnd.choice(_basech) for _ in range(size)])
def rndstr(size=16)
Returns a string of random ascii characters or digits :param size: The length of the string :return: string
4.645634
4.926266
0.943033
_context = service.service_context if "redirect_uris" not in request_args: # Callbacks is a dictionary with callback type 'code', 'implicit', # 'form_post' as keys. try: _cbs = _context.callbacks except AttributeError: request_args['redirect_uris'] = ...
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 arguments.
5.03683
5.326821
0.94556
if not pcr: pcr = self.service_context.provider_info regreq = oidc.RegistrationRequest for _pref, _prov in PREFERENCE2PROVIDER.items(): try: vals = self.service_context.client_preferences[_pref] except KeyError: cont...
def match_preferences(self, pcr=None, issuer=None)
Match the clients preferences against what the provider can do. This is to prepare for later client registration and or what functionality the client actually will use. In the client configuration the client preferences are expressed. These are then compared with the Provider Configurati...
3.034323
2.89505
1.048107
'''Return the soundex code for given character :param char: Character whose soundex code is needed :return: Returns soundex code if character is found in charmap else returns 0 ''' lang = get_language(char) try: ...
def soundexCode(self, char)
Return the soundex code for given character :param char: Character whose soundex code is needed :return: Returns soundex code if character is found in charmap else returns 0
4.733743
3.100207
1.526912
'''Calculate soundex of given string This function calculates soundex for Indian language string as well as English string. This function is exposed as service method for JSONRPC in SILPA framework. :param name: String whose Soundex value to be calculate...
def soundex(self, name, length=8)
Calculate soundex of given string This function calculates soundex for Indian language string as well as English string. This function is exposed as service method for JSONRPC in SILPA framework. :param name: String whose Soundex value to be calculated ...
5.577073
2.759491
2.021051
'''Compare soundex of given strings This function checks if 2 given strings are phonetically sounds same by doing soundex code comparison :param string1: First string for comparison :param string2: Second string for comparison :return: Returns 0 if both ...
def compare(self, string1, string2)
Compare soundex of given strings This function checks if 2 given strings are phonetically sounds same by doing soundex code comparison :param string1: First string for comparison :param string2: Second string for comparison :return: Returns 0 if both strings are...
4.220844
1.909323
2.21065
if not url or "//" not in url: raise ValueError("Missing or invalid url: %s" % url) render_url = self.BASE_URL + url headers = { 'X-Prerender-Token': self.token, } r = self.session.get(render_url, headers=headers, allow_redirects=False) ...
def get_response_for_url(self, url)
Accepts a fully-qualified url. Returns an HttpResponse, passing through all headers and the status code.
3.942206
3.860346
1.021205
if not url and not regex: raise ValueError("Neither a url or regex was provided to update_url.") headers = { 'X-Prerender-Token': self.token, 'Content-Type': 'application/json', } data = { 'prerenderToken': settings.PRERENDER_TOK...
def update_url(self, url=None, regex=None)
Accepts a fully-qualified url, or regex. Returns True if successful, False if not successful.
2.826424
2.701713
1.04616
if not url: raise ValueError("Neither a url or regex was provided to update_url.") post_url = "%s%s" % (self.BASE_URL, url) r = self.session.post(post_url) return int(r.status_code) < 500
def update_url(self, url=None)
Accepts a fully-qualified url. Returns True if successful, False if not successful.
4.27196
3.995692
1.069141
if 'user' not in validated_data: validated_data['user'] = self.context['request'].user return super(RefreshTokenSerializer, self).create(validated_data)
def create(self, validated_data)
Override ``create`` to provide a user via request.user by default. This is required since the read_only ``user`` field is not included by default anymore since https://github.com/encode/django-rest-framework/pull/5886.
2.641312
2.343156
1.127246
user = request.user if not user.is_authenticated: return False elif user.is_staff or user.is_superuser: return True return user == obj.user
def has_object_permission(self, request, view, obj)
Allow staff or superusers, and the owner of the object itself.
2.748476
2.198565
1.250122
with self._cond: to_notify = self._initial - self._value self._value = self._initial self._cond.notify(to_notify)
def clear(self)
Release the semaphore of all of its bounds, setting the internal counter back to its original bind limit. Notify an equivalent amount of threads that they can run.
6.684828
5.475365
1.220892
def _convert(value): if isinstance(value, _datetime.date): return value.strftime('%s') return value @_six.wraps(fn) def _fn(self, command, **params): # sanitize the params by removing the None values with self.startup_lock: if self.timer.ident i...
def _api_wrapper(fn)
API function decorator that performs rate limiting and error checking.
4.923499
4.867276
1.011551
params['command'] = command response = self.session.get(self._public_url, params=params) return response
def _public(self, command, **params)
Invoke the 'command' public API with optional params.
3.974399
3.855561
1.030823
return self._public('returnOrderBook', currencyPair=currencyPair, depth=depth)
def returnOrderBook(self, currencyPair='all', depth='50')
Returns the order book for a given market, as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen. You may set currencyPair to "all" to get the order books of all markets.
4.822388
4.995569
0.965333
return self._public('returnTradeHistory', currencyPair=currencyPair, start=start, end=end)
def returnTradeHistory(self, currencyPair, start=None, end=None)
Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.
3.964014
4.588697
0.863865
return self._public('returnChartData', currencyPair=currencyPair, period=period, start=start, end=end)
def returnChartData(self, currencyPair, period, start=0, end=2**32-1)
Returns candlestick chart data. Required GET parameters are "currencyPair", "period" (candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end". "Start" and "end" are given in UNIX timestamp format and used to specify the date range for t...
3.571379
3.601826
0.991547