text
stringlengths
81
112k
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 def authz_part2(self, user, authn_event, reques...
The AuthorizationRequest endpoint :param request_info: The authorization request as a dictionary :return: dictionary def process_request(self, request_info=None, **kwargs): """ The AuthorizationRequest endpoint :param request_info: The authorization request as a dictionary :re...
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: def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt', authn_event=...
Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False 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 """ ...
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 def mint_sub(client_salt, sector_id...
Add attribute value assertion to a special session :param sid: Session ID :param kwargs: def update(self, sid, **kwargs): """ Add attribute value assertion to a special session :param sid: Session ID :param kwargs: """ item = self[sid] for attri...
Updated the session info. Any type of known token can be used :param token: code/access token/refresh token/... :param kwargs: Key word arguements def update_by_token(self, token, **kwargs): """ Updated the session info. Any type of known token can be used :param token: code/a...
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 def replace_token(self, sid, sinfo, token_type): """ Replace an old refresh_token with a...
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 ...
Checks validity of a given token :param token: Access or refresh token def is_token_valid(self, token): """ Checks validity of a given token :param token: Access or refresh token """ try: _tinfo = self.handler.info(token) except KeyError: ...
Revokes access token :param token: access token def revoke_token(self, token, token_type=''): """ Revokes access token :param token: access token """ if token_type: self.handler[token_type].black_list(token) else: self.handler.black_list...
Mark session as revoked but also explicitly revoke all issued tokens :param token: any token connected to the session :param sid: Session identifier def revoke_session(self, sid='', token=''): """ Mark session as revoked but also explicitly revoke all issued tokens :param toke...
Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration corresponding to a longslit observation. geometry : TBD debugplo...
Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary with the authentication method and its authn class ref def pick_auth(endpoint_context, areq, all=False): """ Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary ...
Generator that returns all registered authenticators based on a specific authentication class. :param acr: Authentication Class :return: generator def get_method(self, cls_name): """ Generator that returns all registered authenticators based on a specific authentication...
Given the authentication context find zero or more authn methods that could be used. :param acr: The authentication class reference requested :return: An URL def pick(self, acr=None): """ Given the authentication context find zero or more authn methods that could be use...
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. def setup(self, path=None): """ Look for SExtractor program ('sextractor', or 'sex'). ...
Update the configuration files according to the current in-memory SExtractor configuration. def update_config(self): """ Update the configuration files according to the current in-memory SExtractor configuration. """ # -- Write filter configuration file # First...
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. def run(self, file, updateconfig=True, clean=False, path=N...
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, ...}. def catalog(self): """ Read the output catalog produced by the last SExtractor run. Output is a list of dictio...
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. def clean(self, config=True, catalog=False, check=False): """ Remove the generated...
Refine RectWaveCoeff object using a catalogue of lines One and only one among refine_with_oh_lines_mode and refine_with_arc_lines must be different from zero. Parameters ---------- input_image : HDUList object Input 2D image. rectwv_coeff : RectWaveCoeff instance Rectification ...
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...
Evaluate rect.+wavecal. coefficients from arc image Parameters ---------- reduced_image : HDUList object Image with preliminary basic reduction: bpm, bias, dark and flatfield. bound_param : RefinedBoundaryModelParam instance Refined boundary model. lines_catalog : Numpy arra...
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...
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...
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...
Perform user logout :param request: :param cookie: :param kwargs: :return: def process_request(self, request=None, cookie=None, **kwargs): """ Perform user logout :param request: :param cookie: :param kwargs: :return: """ ...
Evaluate rect.+wavecal. coefficients from MOS library Parameters ---------- reduced_image : HDUList object Image with preliminary basic reduction: bpm, bias, dark and flatfield. master_rectwv : MasterRectWave instance Rectification and Wavelength Calibrartion Library product. ...
Compute median spectrum for each slitlet. Parameters ---------- input_image : HDUList object Input 2D image. mode : int Indicate desired result: 0 : image with the same size as the input image, with the median spectrum of each slitlet spanning all the spectra ...
This is borrowed from execo. def _check_deployed_nodes(nodes): """This is borrowed from execo.""" deployed = [] undeployed = [] cmd = "! (mount | grep -E '^/dev/[[:alpha:]]+2 on / ')" deployed_check = get_execo_remote( cmd, nodes, DEFAULT_CONN_PARAMS) for p in deployed...
Get the networks assoiated with the resource description. Returns list of tuple roles, network def get_networks(self): """Get the networks assoiated with the resource description. Returns list of tuple roles, network """ networks = self.c_resources["net...
Get the roles associated with the hosts. Returns dict of role -> [host] def get_roles(self): """Get the roles associated with the hosts. Returns dict of role -> [host] """ machines = self.c_resources["machines"] result = {} for desc in ...
Start a client WS connection on this socket. Returns: the AcceptConnection message. async def start_client(self, sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, ...
Start a server WS connection on this socket. Filter: an async callable that gets passed the initial Request. It may return an AcceptConnection message, a bool, or a string (the subprotocol to use). Returns: the Request message. async def start_server(self, sock: anyio.abc.SocketStream,...
Gets the next event. async def _next_event(self): """ Gets the next event. """ while True: for event in self._connection.events(): if isinstance(event, Message): # check if we need to buffer if event.message_finished: ...
Closes the websocket. async def close(self, code: int = 1006, reason: str = "Connection closed"): """ Closes the websocket. """ if self._closed: return self._closed = True if self._scope is not None: await self._scope.cancel() # canc...
Sends some data down the connection. async def send(self, data: Union[bytes, str], final: bool = True): """ Sends some data down the connection. """ MsgType = TextMessage if isinstance(data, str) else BytesMessage data = MsgType(data=data, message_finished=final) data = ...
Buffers an event, if applicable. def _buffer(self, event: Message): """ Buffers an event, if applicable. """ if isinstance(event, BytesMessage): self._byte_buffer.write(event.data) elif isinstance(event, TextMessage): self._string_buffer.write(event.data)
Gathers all the data from a buffer. def _gather_buffers(self, event: Message): """ Gathers all the data from a buffer. """ if isinstance(event, BytesMessage): buf = self._byte_buffer else: buf = self._string_buffer # yay for code shortening ...
Wraps data into the right event. def _wrap_data(data: Union[str, bytes]): """ Wraps data into the right event. """ MsgType = TextMessage if isinstance(data, str) else BytesMessage return MsgType(data=data, frame_finished=True, message_finished=True)
returns the SQL for a given field with full type information http://www.sqlite.org/datatype3.html field_name -- string -- the field's name field -- Field() -- the set options for the field return -- string -- the field type (eg, foo BOOL NOT NULL) def get_field_SQL(self, field_name, ...
http://sqlite.org/lang_createtable.html def _set_table(self, schema, **kwargs): """ http://sqlite.org/lang_createtable.html """ query_str = [] query_str.append("CREATE TABLE {} (".format(self._normalize_table_name(schema))) query_fields = [] for field_name, fiel...
https://www.sqlite.org/lang_createindex.html def _set_index(self, schema, name, fields, **index_options): """ https://www.sqlite.org/lang_createindex.html """ query_str = "CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})".format( 'UNIQUE ' if index_options.get('unique', False...
return all the indexes for the given schema def _get_indexes(self, schema, **kwargs): """return all the indexes for the given schema""" # http://www.sqlite.org/pragma.html#schema # http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html # http://stackoverflow.com/questions/604...
return all the fields for the given table def _get_fields(self, table_name, **kwargs): """return all the fields for the given table""" ret = {} query_str = 'PRAGMA table_info({})'.format(self._normalize_table_name(table_name)) fields = self._query(query_str, **kwargs) #pout.v([d...
allow extracting information from date http://www.sqlite.org/lang_datefunc.html def _normalize_date_SQL(self, field_name, field_kwargs, symbol): """ allow extracting information from date http://www.sqlite.org/lang_datefunc.html """ fstrs = [] k_opts = { ...
allow sorting by a set of values http://stackoverflow.com/questions/3303851/sqlite-and-custom-order-by def _normalize_sort_SQL(self, field_name, field_vals, sort_dir_str): """ allow sorting by a set of values http://stackoverflow.com/questions/3303851/sqlite-and-custom-order-by ...
Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time :param new_calc: register new calculation def register(se...
Transform fiber traces to ds9-region format. Parameters ---------- ds9reg : BinaryIO Handle to output file name in ds9-region format. def slits_to_ds9_reg(ds9reg, slits): """Transform fiber traces to ds9-region format. Parameters ---------- ds9reg : BinaryIO Handle to outp...
Makes an ID from the object's class name and the datetime now in ISO format. :param obj: the class from which to make the ID :return: ID def id_maker(obj): """ Makes an ID from the object's class name and the datetime now in ISO format. :param obj: the class from which to make the ID :return:...
topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`_ def topological_sort(dag): """ ...
register simulation and metadata. * ``commands`` - list of methods to callable from model :param sim: new simulation def register(self, sim, *args, **kwargs): """ register simulation and metadata. * ``commands`` - list of methods to callable from model :param sim: ne...
Check if data loaded for all sources in data layer. :param data: data layer from model :type data: :class:`~simkit.core.layer.Data` :return: dictionary of data sources and objects or `None` if not loaded def check_data(self, data): """ Check if data loaded for all sources in da...
Initialize the simulation. Organize calculations by dependency. :param calc_reg: Calculation registry. :type calc_reg: :class:`~simkit.core.calculation.CalcRegistry` def initialize(self, calc_reg): """ Initialize the simulation. Organize calculations by dependency. ...
Generator that resumes from same index, or restarts from sent index. def index_iterator(self): """ Generator that resumes from same index, or restarts from sent index. """ idx = 0 # index while idx < self.number_intervals: new_idx = yield idx idx += 1 ...
Start the simulation from time zero. :param model: Model with layers and registries containing parameters :type: :class:`~simkit.core.models.Model` :param progress_hook: A function that receives either a string or a list containing the index followed by tuples of the data or outputs...
Pause the simulation. How is this different from stopping it? Maintain info sufficient to restart simulation. Sets ``is_paused`` to True. Will this state allow analysis? changing parameters? What can you do with a paused simulation? Should be capable of saving paused simulation for loadi...
Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name. def save_ds9(output, filename): """Save ds9 region output info filename. Parameters ----...
Save the 4 possible ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level for messages and plots. For details see '...
Generate ds9 region output with requested slitlet limits Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. limits : str Region to be saved: the only two possibilities are 'bound...
Save expected location of arc and OH airglow to ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level for messages and plots. F...
Generate ds9 region output with requested spectral lines Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. spectral_lines : str Spectral lines to be saved: the only two possibil...
Dynamically create the provider info response :param capabilities: :return: def create_providerinfo(self, capabilities): """ Dynamically create the provider info response :param capabilities: :return: """ _pinfo = self.package_capabilities() no...
Writes a length-prefixed UTF-8 string. def _write_utf8(write, value): """Writes a length-prefixed UTF-8 string.""" write('h', len(value)) write.io.write(value.encode('utf-8'))
Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name. def read(cls, read, has_name=True): """ Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name. """ name = cls._read_utf8(read) if has_name els...
Pretty-print a tag in the same general style as Markus's example output. def pretty(self, indent=0, indent_str=' '): """ Pretty-print a tag in the same general style as Markus's example output. """ return '{0}{1}({2!r}): {3!r}'.format( indent_str * indent, ...
See `__setitem__`. def update(self, *args, **kwargs): """See `__setitem__`.""" super(TAG_Compound, self).update(*args, **kwargs) for key, item in self.items(): if item.name is None: item.name = key
Saves the `NBTFile()` to `io`, which can be any file-like object providing `write()`. def save(self, io, little_endian=False): """ Saves the `NBTFile()` to `io`, which can be any file-like object providing `write()`. """ if little_endian: write = lambda fmt, ...
Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance def factory(ec, code=None, token=None, refresh=None, **kwargs): """ Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance """ TT...
Return a key (the session id) :param user: User id :param areq: The authorization request :return: An ID def key(self, user="", areq=None): """ Return a key (the session id) :param user: User id :param areq: The authorization request :return: An ID ...
Return token information. :param token: A token :return: dictionary with info about the token def info(self, token): """ Return token information. :param token: A token :return: dictionary with info about the token """ _res = dict(zip(['_id', 'type', 's...
Processes element with a wildcard ``?`` weight fraction and returns composition balanced to 1.0. def process_wildcard(fractions): """ Processes element with a wildcard ``?`` weight fraction and returns composition balanced to 1.0. """ wildcard_zs = set() total_fraction = 0.0 for z, frac...
Converts a mass fraction :class:`dict` to an atomic fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values weight fractions. No wildcard are accepted. def...
Converts an atomic fraction :class:`dict` to a mass fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values atomic fractions. No wildcard are accepted. ...
Converts a chemical formula to an atomic fraction :class:`dict`. Args: formula (str): chemical formula, like Al2O3. No wildcard are accepted. def convert_formula_to_atomic_fractions(formula): """ Converts a chemical formula to an atomic fraction :class:`dict`. Args: formula (str): che...
Generates a name from the composition. The name is generated on the basis of a classical chemical formula. def generate_name(atomic_fractions): """ Generates a name from the composition. The name is generated on the basis of a classical chemical formula. """ if not atomic_fractions: ret...
Creates a pure composition. Args: z (int): atomic number def from_pure(cls, z): """ Creates a pure composition. Args: z (int): atomic number """ return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))
Creates a composition from a mass fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The keys are atomic numbers and the values weight fractions. Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron will get a m...
Creates a composition from an atomic fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The keys are atomic numbers and the values atomic fractions. Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron will ...
Sample collection is meant to be very tolerant to generic failures as failing to obtain the sample has important consequences on the results. - Multiple retries with longer delays - Larger than usual timeout async def _collect_sample(self, url, url_pattern): """ Sample collecti...
Return the path part of the URL with the last element replaced with its pattern in a regex-like format: \l -> lowercase letters, same as [a-z]+ \L -> uppercase letters, same as [A-Z]+ \i -> letters ignoring case, same as [a-zA-Z]+ \d -> digits, same as \d+ \w -> word characters (...
Read the bounddict json file and return the polynomial boundaries. Parameters ---------- bounddict_file : file handler File containing the bounddict JSON data. slitlet_number : int Number of slitlet. Returns ------- pol_lower_boundary : numpy polynomial Polynomial d...
Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` def _to_enos_roles(roles): """Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:fun...
Transform the networks returned by deploy5k. Args: networks (dict): networks returned by :py:func:`enoslib.infra.provider.Provider.init` def _to_enos_networks(networks): """Transform the networks returned by deploy5k. Args: networks (dict): networks returned by :py...
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
Destroys the jobs. def destroy(self): """Destroys the jobs.""" r = api.Resources(self.provider_conf.to_dict()) # insert force_deploy r.destroy()
Finds all Wikipedia pages referring to the specified name in English and returns a dictionary where the keys are the language code and the values are the titles of the corresponding pages. def _find_wikipedia_names(self, name_en): """ Finds all Wikipedia pages referring to the specified...
Append the response to the stack of responses. :param tornado.httpclient.HTTPResponse response: The HTTP response def append_response(self, response): """Append the response to the stack of responses. :param tornado.httpclient.HTTPResponse response: The HTTP response """ self...
Returns the HTTP response body, deserialized if possible. :rtype: mixed def body(self): """Returns the HTTP response body, deserialized if possible. :rtype: mixed """ if not self._responses: return None if self._responses[-1].code >= 400: retur...
Return the parsed link header if it was set, returning a list of the links as a dict. :rtype: list(dict()) or None def links(self): """Return the parsed link header if it was set, returning a list of the links as a dict. :rtype: list(dict()) or None """ if not...
Decode bytes to UTF-8 strings as a singe value, list, or dict. :param mixed value: The value to decode :rtype: mixed def _decode(self, value): """Decode bytes to UTF-8 strings as a singe value, list, or dict. :param mixed value: The value to decode :rtype: mixed """ ...
Try and deserialize a response body based upon the specified content type. :rtype: mixed def _deserialize(self): """Try and deserialize a response body based upon the specified content type. :rtype: mixed """ if not self._responses or not self._responses[-1].b...
Try and extract the error message from a HTTP error response. :rtype: str def _error_message(self): """Try and extract the error message from a HTTP error response. :rtype: str """ body = self._deserialize() return body.get('message', body) if isinstance(body, dict) e...
Perform a HTTP request Will retry up to ``self.MAX_HTTP_RETRIES`` times. :param str url: The URL for the request :param str method: The HTTP request method, defaults to ``GET`` :param dict request_headers: Headers to include in the HTTP request :param mixed body: The HTTP reque...
Set default values for common HTTP request headers :param dict request_headers: The HTTP request headers :param content_type: The mime-type used in the request/response :type content_type: :py:class:`ietfparse.datastructures.ContentType` or str :param mixed body: The request...
Conditionally serialize the request body value if mime_type is set and it's serializable. :param mixed body: The request body :param str content_type: The content type for the request body :raises: ValueError def _http_req_body_serialize(self, body, content_type): """Conditiona...
Return the User-Agent value to specify in HTTP requests, defaulting to ``service/version`` if configured in the application settings, or if used in a consumer, it will attempt to obtain a user-agent from the consumer's process. If it can not auto-set the User-Agent, it defaults to ``spro...
Extract the ``Retry-After`` header value if the request was rate limited and return a future to sleep for the specified duration. :param tornado.httpclient.HTTPResponse response: The response :rtype: tornado.concurrent.Future def _http_resp_rate_limited(response): """Extract the ``Retr...
Decorator to ensure function only runs when it is unique holder of the resource. Any invocations of the functions before the first is done will raise RuntimeError. Locks are stored in redis with prefix: `lock:acquires_lock` Arguments: expires(timedelta|int): Expiry time of lock, way more than...