code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# split orm from module path orm_module, orm_class = get_objects(orm_classpath) # if orm_classpath.startswith("."): # # we handle relative classpaths by using the orm_class and its parents # # to find the relative import # if self.orm_class: # ...
def ref(self, orm_classpath, cls_pk=None)
takes a classpath to allow query-ing from another Orm class the reason why it takes string paths is to avoid infinite recursion import problems because an orm class from module A might have a ref from module B and sometimes it is handy to have module B be able to get the objects from m...
2.784981
2.694461
1.033595
self.fields_set.options["unique"] = True return self.select_field(field_name)
def unique_field(self, field_name)
set a unique field to be selected, this is automatically called when you do unique_FIELDNAME(...)
9.768921
7.647905
1.277333
if fields: if not isinstance(fields[0], basestring): fields = list(fields[0]) + list(fields)[1:] for field_name in fields: field_name = self._normalize_field_name(field_name) self.select_field(field_name) return self
def select_fields(self, *fields)
set multiple fields to be selected
3.261978
3.130008
1.042163
field_name = self._normalize_field_name(field_name) self.fields_set.append(field_name, [field_name, field_val]) return self
def set_field(self, field_name, field_val=None)
set a field into .fields attribute n insert/update queries, these are the fields that will be inserted/updated into the db
4.41409
4.977386
0.886829
if fields_args: fields = [fields] fields.extend(fields_args) for field_name in fields: self.set_field(field_name) elif fields_kwargs: fields = make_dict(fields, fields_kwargs) for field_name, field_val in fields.items(...
def set_fields(self, fields=None, *fields_args, **fields_kwargs)
completely replaces the current .fields with fields and fields_kwargs combined
1.960934
1.888802
1.038189
field_name = self._normalize_field_name(field_name) fv = make_list(field_vals[0]) if field_vals else None if field_kwargs: for k in field_kwargs: if not field_kwargs[k]: raise ValueError("Cannot IN an empty list") field_kw...
def in_field(self, field_name, *field_vals, **field_kwargs)
field_vals -- list -- a list of field_val values
4.509989
4.629849
0.974111
if not field_val: raise ValueError("Cannot NOT LIKE nothing") field_name = self._normalize_field_name(field_name) fv = field_val[0] self.fields_where.append(field_name, ["nlike", field_name, fv, field_kwargs]) return self
def nlike_field(self, field_name, *field_val, **field_kwargs)
Perform a field_name NOT LIKE field_val query :param field_name: string, the field we are filtering on :param field_val: string, the like query: %val, %val%, val% :returns: self, for fluid interface
5.176115
5.477776
0.94493
field_name = self._normalize_field_name(field_name) if direction > 0: direction = 1 elif direction < 0: direction = -1 else: raise ValueError("direction {} is undefined".format(direction)) self.fields_sort.append(field_name, [directio...
def sort_field(self, field_name, direction, field_vals=None)
sort this query by field_name in directrion field_name -- string -- the field to sort on direction -- integer -- negative for DESC, positive for ASC field_vals -- list -- the order the rows should be returned in
3.263965
3.490296
0.935154
has_more = False self.bounds.paginate = True limit_paginate, offset = self.bounds.get(limit, page) self.default_val = [] results = self._query('get') if limit_paginate: self.bounds.paginate = False if len(results) == limit_paginate: ...
def get(self, limit=None, page=None)
get results from the db return -- Iterator()
6.115731
6.110515
1.000854
self.default_val = None o = self.default_val d = self._query('get_one') if d: o = self.orm_class(d, hydrate=True) return o
def get_one(self)
get one row from the db
7.916446
7.609277
1.040368
return self.get(limit=limit, page=page).values()
def values(self, limit=None, page=None)
convenience method to get just the values from the query (same as get().values()) if you want to get all values, you can use: self.all().values()
6.448833
3.548904
1.817134
field_vals = None field_names = self.fields_select.names() fcount = len(field_names) if fcount: d = self._query('get_one') if d: field_vals = [d.get(fn, None) for fn in field_names] if fcount == 1: field...
def value(self)
convenience method to just get one value or tuple of values for the query
4.979589
4.144341
1.201539
self.fields_set.reset() return self.select_pk().values(limit, page)
def pks(self, limit=None, page=None)
convenience method for setting select_pk().values() since this is so common
19.770721
6.657547
2.969671
field_name = self.schema.pk.name return self.in_field(field_name, field_vals).get()
def get_pks(self, field_vals)
convenience method for running in__id([...]).get() since this is so common
8.997567
5.830447
1.543204
field_name = self.schema.pk.name return self.is_field(field_name, field_val).get_one()
def get_pk(self, field_val)
convenience method for running is_pk(_id).get_one() since this is so common
10.165857
4.688977
2.168033
# count queries shouldn't care about sorting fields_sort = self.fields_sort self.fields_sort = self.fields_sort_class() self.default_val = 0 ret = self._query('count') # restore previous values now that count is done self.fields_sort = fields_sort ...
def count(self)
return the count of the criteria
10.286786
9.296179
1.106561
self.default_val = 0 #fields = self.fields #fields = self.orm_class.depart(self.fields, is_update=False) #self.set_fields(fields) return self.interface.insert( self.schema, self.fields ) return self.interface.insert(self.schema, s...
def insert(self)
persist the .fields
7.411556
6.785227
1.092308
self.default_val = 0 #fields = self.fields #fields = self.orm_class.depart(self.fields, is_update=True) #self.set_fields(fields) return self.interface.update( self.schema, self.fields, self )
def update(self)
persist the .fields using .fields_where
9.204509
7.985617
1.152636
i = self.interface return i.query(query_str, *query_args, **query_options)
def raw(self, query_str, *query_args, **query_options)
use the interface.query() method to pass in your own raw query without any processing NOTE -- This will allow you to make any raw query and will usually return raw results, it won't wrap those results in a prom.Orm iterator instance like other methods like .all() and .get() que...
4.798532
4.066269
1.180082
if not threads: threads = multiprocessing.cpu_count() # we subtract one for the main process map_threads = threads - 1 if threads > 1 else 1 q = self.copy() limit = q.bounds.limit offset = q.bounds.offset total_count = limit if limit else q...
def reduce(self, target_map, target_reduce, threads=0)
map/reduce this query among a bunch of processes :param target_map: callable, this function will be called once for each row this query pulls out of the db, if you want something about the row to be seen by the target_reduce function return that value from this function and...
4.855077
4.683324
1.036673
key = "" method = getattr(self, "cache_key_{}".format(method_name), None) if method: key = method() return key
def cache_key(self, method_name)
decides if this query is cacheable, returns a key if it is, otherwise empty
3.992112
3.388718
1.17806
ret = 3600 cn = self.get_process() if "ttl" in cn: ret = cn["ttl"] return ret
def ttl(self)
how long you should cache results for cacheable queries
7.805876
6.845474
1.140297
logger.debug("normalize: {}".format(type(self).__name__)) normalize_headers = self._normalize_headers() return TableData( self.__normalize_table_name(), normalize_headers, self._normalize_rows(normalize_headers), dp_extractor=self._tabl...
def normalize(self)
:return: Sanitized table data. :rtype: tabledata.TableData
6.901493
5.782948
1.193421
# apply header units header_param = parameters.get('header') # default is None # check for headers if header_param: fields = header_param['fields'] # header fields # dictionary of header field parameters header_fields = {field[0]: field[1:] for field in fields} # l...
def _apply_units_to_numpy_data_readers(parameters, data)
Apply units to data originally loaded by :class:`NumPyLoadTxtReader` or :class:`NumPyGenFromTxtReader`. :param parameters: Dictionary of data source parameters read from JSON file. :type parameters: dict :param data: Dictionary of data read
3.647258
3.946665
0.924137
# default delimiter is a comma, can't be None header_delim = str(header_param.get('delimiter', ',')) # don't allow unnamed fields if 'fields' not in header_param: raise UnnamedDataError(f.name) header_fields = {field[0]: field[1:] for field in header_param['fields']} # header_names ...
def _read_header(f, header_param)
Read and parse data from 1st line of a file. :param f: :func:`file` or :class:`~StringIO.StringIO` object from which to read 1st line. :type f: file :param header_param: Parameters used to parse the data from the header. Contains "delimiter" and "fields". :type header_param: dict :r...
4.4124
4.098538
1.076579
data_names = data_data.dtype.names # raise error if NumPy data doesn't have names if not data_names: raise UnnamedDataError(fname) data = dict.fromkeys(data_names) # dictionary of data read by NumPy # iterate over data read by NumPy for data_name in data_names: if data_name...
def _apply_units(data_data, data_units, fname)
Apply units to data. :param data_data: NumPy structured array with data from fname. :type data_data: :class:`numpy.ndarray` :param data_units: Units of fields in data_data. :type data_units: dict :param fname: Name of file from which data_data was read. :type fname: str :returns: Dictionary...
3.114082
3.064473
1.016188
for n, utf8 in enumerate(utf8_list): utf8_list[n][0] = str(utf8[0]) utf8_list[n][1] = str(utf8[1]) utf8_list[n] = tuple(utf8)
def _utf8_list_to_ascii_tuple(utf8_list)
Convert unicode strings in a list of lists to ascii in a list of tuples. :param utf8_list: A nested list of unicode strings. :type utf8_list: list
2.313203
2.395386
0.965691
# append .json extension if needed if not filename.endswith('.json'): filename += '.json' # append "json" to filename # open file and load JSON data with open(filename, 'r') as fid: json_data = json.load(fid) # if JSONReader is the original reade...
def load_data(self, filename, *args, **kwargs)
Load JSON data. :param filename: name of JSON file with data :type filename: str :return: data :rtype: dict
4.014505
4.036736
0.994493
for k, val in self.parameters.iteritems(): if 'units' in val: data[k] = Q_(data[k], val.get('units')) return data
def apply_units_to_cache(self, data)
Apply units to data read using :class:`JSONReader`. :param data: cached data :return: data with units applied :rtype: :class:`~pint.unit.Quantity`
4.133414
4.910757
0.841706
# workbook read from file workbook = open_workbook(filename, verbosity=True) data = {} # an empty dictionary to store data # iterate through sheets in parameters # iterate through the parameters on each sheet for param, pval in self.parameters.iteritems(): ...
def load_data(self, filename, *args, **kwargs)
Load parameters from Excel spreadsheet. :param filename: Name of Excel workbook with data. :type filename: str :returns: Data read from Excel workbook. :rtype: dict
5.744475
5.687009
1.010105
# iterate through sheets in parameters # iterate through the parameters on each sheet for param, pval in self.parameters.iteritems(): # try to apply units try: data[param] *= UREG(str(pval.get('units') or '')) except TypeError: ...
def apply_units_to_cache(self, data)
Apply units to cached data read using :class:`JSONReader`. :param data: Cached data. :type data: dict :return: data with units
9.127247
10.237973
0.891509
# header keys header_param = self.parameters.get('header') # default is None # data keys data_param = self.parameters['data'] # raises KeyError if no 'data' dtype = data_param['dtype'] # raises KeyError if no 'dtype' # convert to tuple and normal ASCII ...
def load_data(self, filename, *args, **kwargs)
load data from text file. :param filename: name of text file to read :type filename: str :returns: data read from file using :func:`numpy.loadtxt` :rtype: dict
3.847079
3.849622
0.999339
# header keys header_param = self.parameters.get('header') # default is None # data keys data_param = self.parameters['data'] # raises KeyError if no 'data' dtype = data_param.get('dtype') # default is None # if not None convert to tuple and normal ASCII ...
def load_data(self, filename, *args, **kwargs)
load data from text file. :param filename: name of file to read :type filename: str :returns: data read from file using :func:`numpy.genfromtxt` :rtype: dict :raises: :exc:`~simkit.core.exceptions.UnnamedDataError`
3.253633
3.091352
1.052495
# load parameterized data data = super(ParameterizedXLS, self).load_data(filename) # add parameter to data parameter_name = self.parameterization['parameter']['name'] parameter_values = self.parameterization['parameter']['values'] parameter_units = str(self.param...
def load_data(self, filename, *args, **kwargs)
Load parameterized data from different sheets.
3.578585
3.345494
1.069673
# parameter parameter_name = self.parameters['parameter']['name'] parameter_units = str(self.parameters['parameter']['units']) data[parameter_name] *= UREG(parameter_units) # data self.parameters.pop('parameter') return super(ParameterizedXLS, self).apply...
def apply_units_to_cache(self, data)
Apply units to :class:`ParameterizedXLS` data reader.
5.596592
3.89891
1.435425
# load text data data = super(MixedTextXLS, self).load_data(filename) # iterate through sheets in parameters for sheet_params in self.parameters.itervalues(): # iterate through the parameters on each sheet for param, pval in sheet_params.iteritems(): ...
def load_data(self, filename, *args, **kwargs)
Load text data from different sheets.
5.054129
4.964832
1.017986
self.tick_if_necessary() self.count += n self.m1_rate.update(n) self.m5_rate.update(n) self.m15_rate.update(n)
def mark(self, n=1)
Mark the occurrence of a given number of events.
4.048339
3.848436
1.051944
# open model file for reading and convert JSON object to dictionary # read and load JSON parameter map file as "parameters" with open(self.param_file, 'r') as param_file: file_params = json.load(param_file) for layer, params in file_params.iteritems(): ...
def _load(self, layer=None)
Load or update all or part of :attr:`model`. :param layer: Optionally load only specified layer. :type layer: str
6.678496
6.442571
1.03662
meta = getattr(self, ModelBase._meta_attr) if not layer: layers = self.layers else: # convert non-sequence to tuple layers = _listify(layer) for layer in layers: # relative path to layer files from model file path = os....
def _update(self, layer=None)
Update layers in model.
6.161669
5.631673
1.09411
meta = getattr(self, ModelBase._meta_attr) # read modelfile, convert JSON and load/update model if self.param_file is not None: self._load() LOGGER.debug('model:\n%r', self.model) # initialize layers # FIXME: move import inside loop for custom layers ...
def _initialize(self)
Initialize model and layers.
4.874628
4.759153
1.024264
# read modelfile, convert JSON and load/update model self.param_file = modelfile self._load(layer) self._update(layer)
def load(self, modelfile, layer=None)
Load or update a model or layers in a model. :param modelfile: The name of the json file to load. :type modelfile: str :param layer: Optionally load only specified layer. :type layer: str
12.898581
13.326539
0.967887
# get layer attribute with model data if hasattr(self, layer): layer_obj = getattr(self, layer) else: raise AttributeError('missing layer: %s', layer) if delete: return layer_obj # iterate over items and edit layer for k, v in ...
def edit(self, layer, item, delete=False)
Edit model. :param layer: Layer of model to edit :type layer: str :param item: Items to edit. :type item: dict :param delete: Flag to return :class:`~simkit.core.layers.Layer` to delete item. :type delete: bool
3.322963
3.229392
1.028975
for k in items.iterkeys(): if k in self.model[layer]: raise Exception('item %s is already in layer %s' % (k, layer)) self.model[layer].update(items) # this should also update Layer.layer, the layer data # same as calling layer constructor # so...
def add(self, layer, items)
Add items in model.
6.763911
6.723133
1.006065
# Use edit to get the layer obj containing item items = _listify(items) # make items a list if it's not layer_obj = self.edit(layer, dict.fromkeys(items), delete=True) for k in items: if k in layer_obj.layer: layer_obj.delete(k) else: ...
def delete(self, layer, items)
Delete items in model.
6.194325
6.007804
1.031046
if layer: obj = {layer: self.model[layer]} else: obj = self.model with open(modelfile, 'w') as fp: json.dump(obj, fp, indent=2, sort_keys=True)
def save(self, modelfile, layer=None)
Save a model file. :param modelfile: The name of the json file to save. :type modelfile: str :param layer: Optionally save only specified layer. :type layer: str
2.595002
2.659818
0.975631
cmds = cmd.split(None, 1) # split commands and simulations sim_names = cmds[1:] # simulations if not sim_names: sim_names = self.cmd_layer.reg.iterkeys() for sim_name in sim_names: sim_cmd = getattr(self.cmd_layer.reg[sim_name], cmd) sim_cmd...
def command(self, cmd, progress_hook=None, *args, **kwargs)
Execute a model command. :param cmd: Name of the command. :param progress_hook: A function to which progress updates are passed.
4.282899
4.416021
0.969855
if self.logged_in: raise RuntimeError("User already logged in!") params = {"name": self.nick, "password": password} resp = self.conn.make_api_call("login", params) if "error" in resp: raise RuntimeError( f"Login failed: {resp['error'].ge...
def login(self, password)
Attempts to log in as the current user with given password
3.283993
3.199203
1.026504
if not other.logged_in: raise ValueError("Other room is not logged in") cookie = other.session if not cookie: raise ValueError("Other room has no cookie") self.conn.cookies.update({"session": cookie}) self.session = cookie self.logged_in ...
def login_transplant(self, other)
Attempts to carry over the login state from another room
4.591897
3.843801
1.194624
if not self.logged_in: raise RuntimeError("User is not logged in") if self.conn.connected: params = {"room": self.conn.room.room_id} resp = self.conn.make_api_call("logout", params) if not resp.get("success", False): raise Runtime...
def logout(self)
Logs your user out
3.979453
3.740162
1.063979
if self.logged_in: raise RuntimeError("User must be logged out") self.__verify_username(new_nick) self.conn.make_call("command", self.nick, "nick", new_nick) self.nick = new_nick
def change_nick(self, new_nick)
Change the name of your user Note: Must be logged out to change nick
5.556997
4.53363
1.225728
if len(password) < 8: raise ValueError("Password must be at least 8 characters.") params = {"name": self.nick, "password": password} resp = self.conn.make_api_call("register", params) if "error" in resp: raise RuntimeError(f"{resp['error'].get('message...
def register(self, password)
Registers the current user with the given password.
3.412304
3.279332
1.040549
if len(username) > self.__max_length or len(username) < 3: raise ValueError( f"Username must be between 3 and {self.__max_length} characters." ) if any(c not in string.ascii_letters + string.digits for c in username): raise ValueError("Userna...
def __verify_username(self, username)
Raises an exception if the given username is not valid.
2.602692
2.359684
1.102983
if timestamp is None: timestamp = self.current_time_in_fractional_seconds() self.rescale_if_needed() priority = self.weight(timestamp - self.start_time) / random.random() self.values[priority] = value if len(self.values) > self.size: self.values....
def update(self, value, timestamp=None)
Add a value to the reservoir. :param value: the value to be added :param timestamp: the epoch timestamp of the value in seconds, defaults to the current timestamp if not specified.
5.525331
5.174513
1.067797
old_start_time = self.start_time self.start_time = self.current_time_in_fractional_seconds() self.next_scale_time = now + RESCALE_THRESHOLD_S new_values = treap.treap() for key in self.values.keys(): new_key = key * math.exp( -self.alpha * (s...
def rescale(self, now)
"A common feature of the above techniques—indeed, the key technique that allows us to track the decayed weights efficiently—is that they maintain counts and other quantities based on g(ti − L), and only scale by g(t − L) at query time. But while g(ti −L)/g(t−L) is guaranteed to lie betwe...
4.069558
3.637672
1.118726
# if classpath.startswith("."): # rel_count = len(re.match("^\.+", classpath).group(0)) # if calling_classpath: # calling_count = calling_classpath.count(".") # if rel_count > calling_count: # raise ValueError( # "Attempting relative i...
def get_objects(classpath, calling_classpath="")
given a classpath like foo.bar.Baz return module foo.bar and class Baz objects .. seealso:: https://docs.python.org/2.5/whatsnew/pep-328.html https://www.python.org/dev/peps/pep-0328/ :param classpath: string, the full python class path (includes modules), a classpath is something ...
2.732302
2.58378
1.057483
ret = {} if fields: ret.update(fields) if fields_kwargs: ret.update(fields_kwargs) return ret
def make_dict(fields, fields_kwargs)
lot's of methods take a dict or kwargs, this combines those Basically, we do a lot of def method(fields, **kwargs) and we want to merge those into one super dict with kwargs taking precedence, this does that fields -- dict -- a passed in dict fields_kwargs -- dict -- usually a **kwargs dict from anoth...
3.054988
3.365208
0.907816
self.write(line) self.write_newlines(count)
def write_line(self, line, count=1)
writes the line and count newlines after the line
6.343057
4.061684
1.561682
if key in self.item_finder: self.remove(key) else: # keep the queue contained if self.full(): raise OverflowError("Queue is full") if priority is None: priority = next(self.counter) item = [priority, key, val] ...
def add(self, key, val, priority=None)
add a value to the queue with priority, using the key to know uniqueness key -- str -- this is used to determine if val already exists in the queue, if key is already in the queue, then the val will be replaced in the queue with the new priority val -- mixed -- the value to add ...
3.830389
3.867438
0.99042
item = self.item_finder.pop(key) item[-1] = None self.removed_count += 1
def remove(self, key)
remove the value found at key from the queue
8.96946
8.709025
1.029904
pq = self.pq while pq: priority, key, val = heapq.heappop(pq) if val is None: self.removed_count -= 1 else: del self.item_finder[key] return key, val, priority raise KeyError("pop from an empty priorit...
def popitem(self)
remove the next prioritized [key, val, priority] and return it
4.597738
3.590708
1.280454
if not self.size: return False return len(self.pq) == (self.size + self.removed_count)
def full(self)
Return True if the queue is full
11.622846
10.140288
1.146205
# extract slitlet region slitlet2d = image_2k2k[(sltlim.bb_ns1_orig - 1):sltlim.bb_ns2_orig, (sltlim.bb_nc1_orig - 1):sltlim.bb_nc2_orig] # transform to float slitlet2d = slitlet2d.astype(np.float) # return slitlet image return slitlet2d
def extract_slitlet2d(image_2k2k, sltlim)
Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : 2d numpy array, float Original image (dimensions NAXIS1 * NAXIS2) sltlim : instance of SlitLimits class Object containing relevant information concerning the slitlet region to b...
3.444373
3.006343
1.145702
# TODO: move this to new Registry method or __getitem__ # TODO: replace idx with datetime object and use timeseries to interpolate # into data, not necessary for outputs since that will conform to idx rargs = dict.fromkeys(args) # make dictionary from arguments # iterate over arguments ...
def index_registry(args, reg, ts=None, idx=None)
Index into a :class:`~simkit.core.Registry` to return arguments from :class:`~simkit.core.data_sources.DataRegistry` and :class:`~simkit.core.outputs.OutputRegistry` based on the calculation parameter file. :param args: Arguments field from the calculation parameter file. :param reg: Registry in wh...
7.67617
7.324328
1.048037
# number of formula arguments that are not constant argn = len(vargs) # number of observations must be the same for all vargs nobs = 1 for m in xrange(argn): a = vargs[m] try: a = datargs[a] except (KeyError, TypeError)...
def get_covariance(datargs, outargs, vargs, datvar, outvar)
Get covariance matrix. :param datargs: data arguments :param outargs: output arguments :param vargs: variable arguments :param datvar: variance of data arguments :param outvar: variance of output arguments :return: covariance
2.474191
2.5105
0.985537
'''Put every point in its category. levels must be sorted.''' x = numpy.asarray(x) y = numpy.asarray(y) ys = y.copy() ys.sort() # Mean of the upper half m = ys[len(ys) // 2:].mean() y /= m m = 1.0 s = ys[len(ys) // 2:].std() result = [] if tags is None: tags...
def check_photometry_categorize(x, y, levels, tags=None)
Put every point in its category. levels must be sorted.
3.418739
2.946029
1.160457
return verify_client(self.endpoint_context, request, auth)
def client_authentication(self, request, auth=None, **kwargs)
Do client authentication :param endpoint_context: A :py:class:`oidcendpoint.endpoint_context.SrvInfo` instance :param request: Parsed request, a self.request_cls class instance :param authn: Authorization info :return: client_id or raise and exception
11.324221
11.033945
1.026308
response_args = self.do_pre_construct(response_args, request, **kwargs) # logger.debug("kwargs: %s" % sanitize(kwargs)) response = self.response_cls(**response_args) return self.do_post_construct(response, request, **kwargs)
def construct(self, response_args, request, **kwargs)
Construct the response :param response_args: response arguments :param request: The parsed request, a self.request_cls class instance :param kwargs: Extra keyword arguments :return: An instance of the self.response_cls class
3.571682
3.838515
0.930485
element = [] for name, value in form_args.items(): element.append( '<input type="hidden" name="{}" value="{}"/>'.format(name, value)) return "\n".join(element)
def inputs(form_args)
Creates list of input elements
2.704693
2.418283
1.118435
try: _cid = request["client_id"] except KeyError: _cid = client_id if not _cid: logger.error('No client id found') raise UnknownClient('No client_id provided') _redirect_uri = unquote(request[uri_type]) part = urlparse(_redirect_uri) if part.fragment: ...
def verify_uri(endpoint_context, request, uri_type, client_id=None)
A redirect URI MUST NOT contain a fragment MAY contain query component :param endpoint_context: :param request: :param uri_type: redirect_uri/post_logout_redirect_uri :return: An error response if the redirect URI is faulty otherwise None
3.08203
2.983926
1.032878
if uri_type in request: verify_uri(endpoint_context, request, uri_type) uri = request[uri_type] else: try: _specs = endpoint_context.cdb[ str(request["client_id"])]["{}s".format(uri_type)] except KeyError: raise ParameterError( ...
def get_uri(endpoint_context, request, uri_type)
verify that the redirect URI is reasonable :param endpoint_context: :param request: The Authorization request :param uri_type: 'redirect_uri' or 'post_logout_redirect_uri' :return: redirect_uri
3.597727
3.722094
0.966587
response_info = {} # Do the authorization try: permission = self.endpoint_context.authz( user, client_id=request['client_id']) except ToOld as err: return self.error_response( response_info, 'access_denied', ...
def post_authentication(self, user, request, sid, **kwargs)
Things that are done after a successful authentication. :param user: :param request: :param sid: :param kwargs: :return: A dictionary with 'response_args'
3.481132
3.551075
0.980304
sid = setup_session(self.endpoint_context, request, user, authn_event=authn_event) try: resp_info = self.post_authentication(user, request, sid, **kwargs) except Exception as err: return self.error_response({}, 'server_error', err) ...
def authz_part2(self, user, authn_event, request, **kwargs)
After the authentication this is where you should end up :param user: :param request: The Authorization Request :param sid: Session key :param kwargs: possible other parameters :return: A redirect to the redirect_uri of the client
3.694633
3.857442
0.957793
if isinstance(request_info, AuthorizationErrorResponse): return request_info _cid = request_info["client_id"] cinfo = self.endpoint_context.cdb[_cid] try: cookie = kwargs['cookie'] except KeyError: cookie = '' else: ...
def process_request(self, request_info=None, **kwargs)
The AuthorizationRequest endpoint :param request_info: The authorization request as a dictionary :return: dictionary
3.783061
3.694658
1.023927
if authn_event is None and acr: authn_event = AuthnEvent(uid=uid, salt=salt, authn_info=acr, authn_time=time.time()) if not client_id: client_id = areq['client_id'] sid = endpoint_context.sdb.create_authz_session(authn_event, areq, ...
def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt', authn_event=None)
Setting up a user session :param endpoint_context: :param areq: :param uid: :param acr: :param client_id: :param salt: :param authn_event: A already made AuthnEvent :return:
3.057417
3.118165
0.980518
res = [] for k, v in a.items(): try: res.append(b[k] == v) except KeyError: pass return all(res)
def dict_match(a, b)
Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False
2.547901
2.732995
0.932274
if subject_type == "public": sub = hashlib.sha256( "{}{}".format(uid, user_salt).encode("utf-8")).hexdigest() else: sub = pairwise_id(uid, sector_id, "{}{}".format(client_salt, user_salt)) return sub
def mint_sub(client_salt, sector_id="", subject_type="public", uid='', user_salt='')
Mint a new sub (subject identifier) :param authn_event: Authentication event information :param client_salt: client specific salt - used in pairwise :param sector_id: Possible sector identifier :param subject_type: 'public'/'pairwise' :return: Subject identifier
3.392271
3.178147
1.067374
item = self[sid] for attribute, value in kwargs.items(): item[attribute] = value self[sid] = item
def update(self, sid, **kwargs)
Add attribute value assertion to a special session :param sid: Session ID :param kwargs:
3.711337
4.728316
0.784917
_sid = self.handler.sid(token) return self.update(_sid, **kwargs)
def update_by_token(self, token, **kwargs)
Updated the session info. Any type of known token can be used :param token: code/access token/refresh token/... :param kwargs: Key word arguements
11.78725
15.212623
0.774833
try: # Mint a new one refresh_token = self.handler[token_type](sid, sinfo=sinfo) except KeyError: pass else: # blacklist the old is there is one try: self.handler[token_type].black_list(sinfo[token_type]) ...
def replace_token(self, sid, sinfo, token_type)
Replace an old refresh_token with a new one :param sid: session ID :param sinfo: session info :param token_type: What type of tokens should be replaced :return: Updated session info
5.371798
4.745223
1.132043
try: _tinfo = self.handler['refresh_token'].info(token) except KeyError: return False if is_expired(int(_tinfo['exp'])) or _tinfo['black_listed']: raise ExpiredToken() _sid = _tinfo['sid'] session_info = self[_sid] session_...
def refresh_token(self, token, new_refresh=False)
Issue a new access token using a valid refresh token :param token: Refresh token :param new_refresh: Whether a new refresh token should be minted or not :return: Dictionary with session info :raises: ExpiredToken for invalid refresh token WrongTokenType for wrong token ...
3.84651
3.675493
1.046529
try: _tinfo = self.handler.info(token) except KeyError: return False if is_expired(int(_tinfo['exp'])) or _tinfo['black_listed']: return False # Dependent on what state the session is in. session_info = self[_tinfo['sid']] ...
def is_token_valid(self, token)
Checks validity of a given token :param token: Access or refresh token
4.949602
4.921435
1.005723
if token_type: self.handler[token_type].black_list(token) else: self.handler.black_list(token)
def revoke_token(self, token, token_type='')
Revokes access token :param token: access token
4.550438
7.050527
0.645404
if not sid: if token: sid = self.handler.sid(token) else: raise ValueError('Need one of "sid" or "token"') for typ in ['access_token', 'refresh_token', 'code']: try: self.revoke_token(self[sid][typ], typ) ...
def revoke_session(self, sid='', token='')
Mark session as revoked but also explicitly revoke all issued tokens :param token: any token connected to the session :param sid: Session identifier
4.597908
4.189981
1.097358
acrs = [] try: if len(endpoint_context.authn_broker) == 1: return endpoint_context.authn_broker.default() if "acr_values" in areq: if not isinstance(areq["acr_values"], list): areq["acr_values"] = [areq["acr_values"]] acrs = areq["acr_va...
def pick_auth(endpoint_context, areq, all=False)
Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary with the authentication method and its authn class ref
2.916057
2.981876
0.977927
for id, spec in self.db.items(): if spec["method"].__class__.__name__ == cls_name: yield spec["method"]
def get_method(self, cls_name)
Generator that returns all registered authenticators based on a specific authentication class. :param acr: Authentication Class :return: generator
6.660643
7.186068
0.926883
if acr is None: # Anything else doesn't make sense return self.db.values() else: return self._pick_by_class_ref(acr)
def pick(self, acr=None)
Given the authentication context find zero or more authn methods that could be used. :param acr: The authentication class reference requested :return: An URL
9.649663
10.85259
0.889158
# -- Finding sextractor program and its version # first look for 'sextractor', then 'sex' candidates = ['sextractor', 'sex'] if (path): candidates = [path] selected = None for candidate in candidates: try: p = subproces...
def setup(self, path=None)
Look for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed.
3.716898
3.237067
1.14823
# -- Write filter configuration file # First check the filter itself filter = self.config['FILTER_MASK'] rows = len(filter) cols = len(filter[0]) # May raise ValueError, OK filter_f = __builtin__.open(self.config['FILTER_NAME'], 'w') filter_f.write(...
def update_config(self)
Update the configuration files according to the current in-memory SExtractor configuration.
3.724504
3.530077
1.055077
if updateconfig: self.update_config() # Try to find SExtractor program # This will raise an exception if it failed self.program, self.version = self.setup(path) commandline = ( self.program + " -c " + self.config['CONFIG_FILE'] + " " + file) ...
def run(self, file, updateconfig=True, clean=False, path=None)
Run SExtractor. If updateconfig is True (default), the configuration files will be updated before running SExtractor. If clean is True (default: False), configuration files (if any) will be deleted after SExtractor terminates.
5.119371
4.860887
1.053176
output_f = SExtractorfile(self.config['CATALOG_NAME'], 'r') c = output_f.read() output_f.close() return c
def catalog(self)
Read the output catalog produced by the last SExtractor run. Output is a list of dictionaries, with a dictionary for each star: {'param1': value, 'param2': value, ...}.
10.359886
6.806627
1.522029
try: if (config): os.unlink(self.config['FILTER_NAME']) os.unlink(self.config['PARAMETERS_NAME']) os.unlink(self.config['STARNNW_NAME']) os.unlink(self.config['CONFIG_FILE']) if (catalog): os.unlink...
def clean(self, config=True, catalog=False, check=False)
Remove the generated SExtractor files (if any). If config is True, remove generated configuration files. If catalog is True, remove the output catalog. If check is True, remove output check image.
2.753214
2.348329
1.172414
# protection if image2d.shape != (EMIR_NAXIS2, EMIR_NAXIS1): raise ValueError("NAXIS1, NAXIS2 unexpected for EMIR detector") # initialize image output image2d_output = np.zeros_like(image2d) # expected slitlet frontiers list_expected_frontiers = expected_distorted_frontiers( ...
def select_unrectified_slitlet(image2d, islitlet, csu_bar_slit_center, params, parmodel, maskonly)
Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : numpy array Initial image from which the slitlet data will be extracted. islitlet : int Slitlet number. csu_bar_slit_center : float CSU bar slit center. params : :class:`~lmfit...
4.316894
4.327594
0.997527
'''Compute offsets between frames using WCS information. :parameter frames: sequence of FITS filenames or file descriptors :parameter pixref: numpy array used as reference pixel The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel...
def offsets_from_wcs(frames, pixref)
Compute offsets between frames using WCS information. :parameter frames: sequence of FITS filenames or file descriptors :parameter pixref: numpy array used as reference pixel The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordi...
4.167577
1.623885
2.566424
result = [] with frames[0].open() as hdulist: wcsh = wcs.WCS(hdulist[0].header) skyref = wcsh.wcs_pix2world([pixref], origin) result.append(pixref) for idx, frame in enumerate(frames[1:]): with frame.open() as hdulist: wcsh = wcs.WCS(hdulist[0].header) ...
def reference_pix_from_wcs(frames, pixref, origin=1)
Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are computed for the rest of the frames. The results is a list with...
2.515399
2.590243
0.971105
result = [] refimg = imgs[0] wcsh = wcs.WCS(refimg[0].header) skyref = wcsh.wcs_pix2world([pixref], origin) result.append(pixref) for idx, img in enumerate(imgs[1:]): wcsh = wcs.WCS(img[0].header) pixval = wcsh.wcs_world2pix(skyref, origin) result.append(tuple(pi...
def reference_pix_from_wcs_imgs(imgs, pixref, origin=1)
Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are computed for the rest of the frames. The results is a list with...
2.904891
2.931251
0.991007
_cntx = self.endpoint_context _sdb = _cntx.sdb if 'post_logout_redirect_uri' in request: if 'id_token_hint' not in request: raise InvalidRequest( "If post_logout_redirect_uri then id_token_hint is a MUST") _cookie_name = self.endp...
def process_request(self, request=None, cookie=None, **kwargs)
Perform user logout :param request: :param cookie: :param kwargs: :return:
3.328531
3.332923
0.998682
deployed = [] undeployed = [] cmd = "! (mount | grep -E '^/dev/[[:alpha:]]+2 on / ')" deployed_check = get_execo_remote( cmd, nodes, DEFAULT_CONN_PARAMS) for p in deployed_check.processes: p.nolog_exit_code = True p.nolog_timeout = True p.nolog_...
def _check_deployed_nodes(nodes)
This is borrowed from execo.
6.70943
6.134002
1.09381
networks = self.c_resources["networks"] result = [] for net in networks: _c_network = net.get("_c_network") if _c_network is None: continue roles = utils.get_roles_as_list(net) result.append((roles, _c_network)) ret...
def get_networks(self)
Get the networks assoiated with the resource description. Returns list of tuple roles, network
5.151273
4.453716
1.156624
machines = self.c_resources["machines"] result = {} for desc in machines: roles = utils.get_roles_as_list(desc) hosts = self._denormalize(desc) for role in roles: result.setdefault(role, []) result[role].extend(hosts) ...
def get_roles(self)
Get the roles associated with the hosts. Returns dict of role -> [host]
6.429939
5.204615
1.23543
self._sock = sock self._connection = WSConnection(ConnectionType.CLIENT) if headers is None: headers = [] if subprotocols is None: subprotocols = [] data = self._connection.send( Request( host=addr[0], t...
async def start_client(self, sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None)
Start a client WS connection on this socket. Returns: the AcceptConnection message.
4.018245
3.810936
1.054398