text
stringlengths
81
112k
Escapes a value so that it can be used in a mime header def escape_header(val): """Escapes a value so that it can be used in a mime header""" if val is None: return None try: return quote(val, encoding="ascii", safe="/ ") except ValueError: return "utf-8''" + quote(val, encodin...
Generates one or more streams for each name, value pair def make_streams(name, value, boundary, encoding): """Generates one or more streams for each name, value pair""" filename = None mime = None # user passed in a special dict. if isinstance(value, collections.Mapping) and "name" in value and "...
Length of the data stream def len(self): """Length of the data stream""" # The len property is needed for requests. # requests checks __len__, then len # Since we cannot implement __len__ because python 32-bit uses 32-bit # sizes, we implement this instead. def stream_le...
All headers needed to make a request def headers(self): """All headers needed to make a request""" return { "Content-Type": ("multipart/form-data; boundary={}".format(self.boundary)), "Content-Length": str(self.len), "Content-Encoding": self.encoding, }
Indexes a thing by the keyfnc to construct pools of things. def mk_pools(things, keyfnc=lambda x: x): "Indexes a thing by the keyfnc to construct pools of things." pools = {} sthings = sorted(things, key=keyfnc) for key, thingz in groupby(sthings, key=keyfnc): pools.setdefault(key, []).extend(l...
Picks a maximum of n things in a dict of indexed pool of things. def pick_things(pools, key, n): "Picks a maximum of n things in a dict of indexed pool of things." pool = pools.get(key) if not pool: return [] things = pool[:n] del pool[:n] return things
Open a volafile room and start listening to it def listen(room): """Open a volafile room and start listening to it""" def onmessage(m): """Print the new message and respond to it.""" print(m) if m.admin or m.nick == r.user.name: return if "parrot" in m.msg.lower(): ...
Compute valid scan range for provided y0_frontier values. Parameters ---------- y0_frontier_lower : float Ordinate of the lower frontier. y0_frontier_upper : float Ordinate of the upper frontier. resize : bool If True, when the limits are beyond the expected values [1...
Return DtuConfiguration instance with averaged values. Parameters ---------- list_of_objects : python list List of DtuConfiguration instances to be averaged. Returns ------- result : DtuConfiguration instance Object with averaged values. def average_dtu_configurations(list_of_...
Return DtuConfiguration instance with maximum differences. Parameters ---------- list_of_objects : python list List of DtuConfiguration instances to be averaged. Returns ------- result : DtuConfiguration instance Object with averaged values. def maxdiff_dtu_configurations(list...
Define class object from header information in FITS file. Parameters ---------- fitsobj: file object FITS file whose header contains the DTU information needed to initialise the members of this class. extnum : int Extension number (first extension is ...
Define class object from dictionary. Parameters ---------- inputdict : dictionary like object Dictionary like object defining each member of the class. def define_from_dictionary(cls, inputdict): """Define class object from dictionary. Parameters ----------...
Define class object from from provided values. Parameters ---------- xdtu : float XDTU fits keyword value. ydtu : float YDTU fits keyword value. zdtu : float ZDTU fits keyword value. xdtu_0 : float XDTU_0 fits keyword value...
Check that all the members are equal within provided absolute error. Parameters ---------- other : DtuConfiguration object DTU configuration instance to be compared with self. abserror : float Absolute maximum allowed error. Returns ------- ...
Return dictionary structure rounded to a given precision. def outdict(self, ndigits=3): """Return dictionary structure rounded to a given precision.""" output = self.__dict__.copy() for item in output: output[item] = round(output[item], ndigits) return output
conf typically contains:: 'provider_config': { 'path': '.well-known/openid-configuration', 'class': ProviderConfiguration, 'kwargs': {} }, :param conf: :param endpoint_context: :param client_authn_method: :param issuer: :return: def build_endpoi...
Serializes using length:value format :param args: values :return: string def lv_pack(*args): """ Serializes using length:value format :param args: values :return: string """ s = [] for a in args: s.append('{}:{}'.format(len(a), a)) return ''.join(s)
Deserializes a string of the length:value format :param txt: The input string :return: a list og values def lv_unpack(txt): """ Deserializes a string of the length:value format :param txt: The input string :return: a list og values """ txt = txt.strip() res = [] while txt: ...
Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started def init(self, force_deploy=False): """Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started """ ...
Destroy all vagrant box involved in the deployment. def destroy(self): """Destroy all vagrant box involved in the deployment.""" v = vagrant.Vagrant(root=os.getcwd(), quiet_stdout=False, quiet_stderr=True) v.destroy()
Mark the passage of time and decay the current rate accordingly. def tick(self): """Mark the passage of time and decay the current rate accordingly.""" instant_rate = self.count / float(self.tick_interval_s) self.count = 0 if self.initialized: self.rate += (self.alpha * (ins...
Merge CSU configuration using odd- and even-numbered values. The CSU returned CSU configuration include the odd-numbered values from 'conf_odd' and the even-numbered values from 'conf_even'. Parameters ---------- conf_odd : CsuConfiguration instance CSU configuration corresponding to odd-n...
Define class members directly from FITS header. Parameters ---------- image_header : instance of hdulist.header Header content from a FITS file. def define_from_header(cls, image_header): """Define class members directly from FITS header. Parameters -------...
Return dictionary structure rounded to a given precision. def outdict(self, ndigits=3): """Return dictionary structure rounded to a given precision.""" outdict = {} for i in range(EMIR_NBARS): ibar = i + 1 cbar = 'slitlet' + str(ibar).zfill(2) outdict[cbar] ...
Return list of slitlets which width is within given range Parameters ---------- minwidth : float Minimum slit width (mm). maxwidth : float Maximum slit width (mm). Returns ------- list_ok : list List of booleans indicating whe...
Encloses function backported from old photutils def encloses_annulus(x_min, x_max, y_min, y_max, nx, ny, r_in, r_out): '''Encloses function backported from old photutils''' gout = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_out, 1, 1) gin = circular_overlap_grid(x_min, x_max, y_min, y_max,...
center: [x,y], center of first pixel is [0,0] def comp_back_with_annulus(img, xc, yc, r_in, r_out, frac=0.1): ''' center: [x,y], center of first pixel is [0,0] ''' x_min = -0.5 - xc x_max = img.shape[1] - 0.5 - xc y_min = -0.5 - yc y_max = img.shape[1] - 0.5 - yc mm = encloses_annulus(...
with open(args.out_MOSlibrary.name + '_old', 'w') as fstream: json.dump(outdict, fstream, indent=2, sort_keys=True) print('>>> Saving file ' + args.out_MOSlibrary.name + '_old') def main(args=None): # parse command-line options parser = argparse.ArgumentParser(prog='rect_wpoly_for_mos') # ...
Display slitlet arrangment from CSUP keywords in FITS header. Parameters ---------- fileobj : file object FITS or TXT file object. grism : str Grism. grism : str Filter. bbox : tuple of 4 floats If not None, values for xmin, xmax, ymin and ymax. adjust : bool...
Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy array Image corresponding to the slitlet reg...
Rectify slitlet using computed transformation. Parameters ---------- slitlet2d : numpy array Image containing the 2d slitlet image. resampling : int 1: nearest neighbour, 2: flux preserving interpolation. inverse : bool If true, the inverse re...
Display unrectified image with spectrails and frontiers. Parameters ---------- slitlet2d : numpy array Array containing the unrectified slitlet image. def ximshow_unrectified(self, slitlet2d): """Display unrectified image with spectrails and frontiers. Parameters ...
Display rectified image with spectrails and frontiers. Parameters ---------- slitlet2d_rect : numpy array Array containing the rectified slitlet image def ximshow_rectified(self, slitlet2d_rect): """Display rectified image with spectrails and frontiers. Parameters ...
Return type of Token (A=Access code, T=Token, R=Refresh token) and the session id. :param token: A token :return: tuple of token type and session id def info(self, token): """ Return type of Token (A=Access code, T=Token, R=Refresh token) and the session id. :p...
Evaluate whether the token has expired or not :param token: The token :param when: The time against which to check the expiration 0 means now. :return: True/False def is_expired(self, token, when=0): """ Evaluate whether the token has expired or not :param ...
Opens a websocket. async def open_websocket(url: str, headers: Optional[list] = None, subprotocols: Optional[list] = None): """ Opens a websocket. """ ws = await create_websocket( url, headers=headers, subprotocols=subprotocols) try: ...
A more low-level form of open_websocket. You are responsible for closing this websocket. async def create_websocket(url: str, ssl: Optional[SSLContext] = None, headers: Optional[list] = None, subprotocols: Optional[list] = None): ...
Create a websocket on top of a socket. async def open_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[list] = None, subprotocols: Optional[list] = None): ...
A more low-level form of create_websocket_client. You are responsible for closing this websocket. async def create_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, ...
Iterate over mac addresses (given as string). def range_mac(mac_start, mac_end, step=1): """Iterate over mac addresses (given as string).""" start = int(EUI(mac_start)) end = int(EUI(mac_end)) for i_mac in range(start, end, step): mac = EUI(int(EUI(i_mac)) + 1) ip = ['10'] + [str(int(i,...
Gets one row from the query. Raises NotFoundError if there isn't a row or if there are multiple rows def _one(self, query): """Gets one row from the query. Raises NotFoundError if there isn't a row or if there are multiple rows""" try: result = query.one() if result.has_expired(...
Gets the first row of the query. Raises NotFoundError if there isn't a row def _first(self, query): """Gets the first row of the query. Raises NotFoundError if there isn't a row""" result = query.first() if result is None: raise NotFoundError else: if result.has_...
Gets all rows of the query. Raises a NotFoundError if there are 0 rows def _all(self, query): """Gets all rows of the query. Raises a NotFoundError if there are 0 rows""" if query.count() > 0: results = query.all() for result in results: if result.has_expired(sel...
Puts a item into the database. Updates lastUpdate column def _put(self, item: SQLBaseObject): """Puts a item into the database. Updates lastUpdate column""" if item._dto_type in self._expirations and self._expirations[item._dto_type] == 0: # The expiration time has been set to 0 -> shoud no...
Puts many items into the database. Updates lastUpdate column for each of them def _put_many(self, items: Iterable[DtoObject], cls): """Puts many items into the database. Updates lastUpdate column for each of them""" if cls._dto_type in self._expirations and self._expirations[cls._dto_type] == 0: ...
Return only those claims that are asked for. It's a best effort task; if essential claims are not present no error is flagged. :param userinfo: A dictionary containing the available info for one user :param user_info_claims: A dictionary specifying the asked for claims :return: ...
Construct a ChatMessage instance from raw protocol data def from_data(room, conn, data): """Construct a ChatMessage instance from raw protocol data""" files = list() rooms = dict() msg = str() for part in data["message"]: ptype = part["type"] if ptype ==...
Create 2D rotation matrix def create_rot2d(angle): """Create 2D rotation matrix""" ca = math.cos(angle) sa = math.sin(angle) return np.array([[ca, -sa], [sa, ca]])
Detect objects in a region and return the centroid of the brightest one def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None): """Detect objects in a region and return the centroid of the brightest one""" from matplotlib.patches import Ellipse if logger is None: ...
Signed and or encrypt a IDToken :param session_info: Session information :param client_id: Client ID :param code: Access grant :param access_token: Access Token :param user_info: User information :param sign: If the JWT should be signed :param encrypt: If the JWT...
Add layer class to model. This method may be overloaded by layer. :param src_cls: layer class to add, should not start with underscores :type src_cls: str :param module: Python module that contains layer class :type module: str :param package: optional package containing module ...
Add data_source to model. Tries to import module, then looks for data source class definition. :param data_source: Name of data source to add. :type data_source: str :param module: Module in which data source resides. Can be absolute or relative. See :func:`importlib.import_...
Open filename to get data for data_source. :param data_source: Data source for which the file contains data. :type data_source: str Positional and keyword arguments can contain either the data to use for the data source or the full path of the file which contains data for the d...
Add data_sources to layer and open files with data for the data_source. def load(self, rel_path=None): """ Add data_sources to layer and open files with data for the data_source. """ for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package')) f...
Edit data layer. :param data_src: Name of :class:`DataSource` to edit. :type data_src: str :param value: Values to edit. :type value: dict def edit(self, data_src, value): """ Edit data layer. :param data_src: Name of :class:`DataSource` to edit. :type ...
Delete data sources. def delete(self, data_src): """ Delete data sources. """ items = self.objects[data_src].data.keys() # items to edit self.reg.unregister(items) # remove items from Registry self.layer.pop(data_src) # remove data source from layer self.objec...
Import module (from package) with formulas, import formulas and add them to formula registry. :param formula: Name of the formula source to add/open. :param module: Module containing formula source. :param package: [Optional] Package of formula source module. .. seealso:: ...
Add formulas to layer. def load(self, _=None): """ Add formulas to layer. """ for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package'))
Add calc to layer. def add(self, calc, module, package=None): """ Add calc to layer. """ super(Calculations, self).add(calc, module, package) # only update layer info if it is missing! if calc not in self.layer: # copy calc source parameters to :attr:`Layer.l...
Add output to def add(self, output, module, package=None): """ Add output to """ super(Outputs, self).add(output, module, package) # only update layer info if it is missing! if output not in self.layer: # copy output source parameters to :attr:`Layer.layer` ...
Add simulation to layer. def add(self, sim, module, package=None): """ Add simulation to layer. """ super(Simulations, self).add(sim, module, package) # only update layer info if it is missing! if sim not in self.layer: # copy simulation source parameters to ...
Add sim_src to layer. def load(self, rel_path=None): """ Add sim_src to layer. """ for k, v in self.layer.iteritems(): self.add(k, v['module'], v.get('package')) filename = v.get('filename') path = v.get('path') if filename: ...
Calculate solar position for lat/long at times. :param times: Python :class:`datetime.datetime` object. :type times: list :param latitude: latitude [degrees] :type latitude: float :param longitude: longitude [degrees] :type longitude: float :returns: apparent zenith, azimuth def f_solpos(t...
Calculate total irradiance :param times: timestamps :param surface_tilt: panel tilt from horizontal [deg] :param surface_azimuth: panel azimuth from north [deg] :param solar_zenith: refracted solar zenith angle [deg] :param solar_azimuth: solar azimuth [deg] :param dni: direct normal irradiance...
Rescale the values in a numpy array to the [z1,z2] interval. The transformation is carried out following the relation array_rs = b_flux * array - c_flux as explained in Appendix B1 of Cardiel (2009, MNRAS, 396, 680) Parameters ---------- array : numpy array Numpy array to be rescaled. ...
Restore the values in a numpy array rescaled to the [z1,z2] interval. The transformation is carried out following the relation array = (array_rs + c_flux)/b_flux as explained in Appendix B1 of Cardiel (2009, MNRAS, 396, 680) Parameters ---------- array_rs : numpy array Numpy array prev...
Class decorator to enable a class (and it's sub-classes) to have a 'Meta' class attribute. :type class_to_decorate: class :param bool add_init_kwargs: Pass Meta class members to constructor :rtype: class def with_meta(class_to_decorate=None, add_init_kwargs=True): """ Class decora...
Collect all members of any contained :code:`Meta` class declarations from the given class or any of its base classes. (Sub class values take precedence.) :type cls: class :rtype: Struct def get_meta(cls): """ Collect all members of any contained :code:`Meta` class declarations from...
Class decorator that ensures that instances will be ordered after creation order when sorted. :type class_to_decorate: class :rtype: class def creation_ordered(class_to_decorate): """ Class decorator that ensures that instances will be ordered after creation order when sorted. :ty...
Collect all class level attributes matching the given criteria. :param class member_class: Class(es) to collect :param is_member: Function to determine if an object should be collected :param sort_key: Function to invoke on members to obtain ordering (Default is to use ordering from `creation_o...
Class decorator to enable classes to be defined in the style of django models. That is, @declarative classes will get an additional argument to constructor, containing an OrderedDict with all class members matching the specified type. :param class member_class: Class(es) to collect :par...
:type func: Callable :rtype: str def get_signature(func): """ :type func: Callable :rtype: str """ try: return object.__getattribute__(func, '__tri_declarative_signature') except AttributeError: pass try: if sys.version_info[0] < 3: # pragma: no mut...
Gather mappings with keys of the shape '<base_key>__<sub_key>' as new dicts under '<base_key>', indexed by '<sub_key>'. >>> foo = dict( ... foo__foo=1, ... foo__bar=2, ... bar__foo=3, ... bar__bar=4, ... foo_baz=5, ... baz=6 ... ) >>> assert collect_namespac...
Extract mappings of the shape '<base_key>__<sub_key>' to new mappings under '<sub_key>'. >>> foo = { ... 'foo__foo': 1, ... 'foo__bar': 2, ... 'baz': 3, ... } >>> assert extract_subkeys(foo, 'foo', defaults={'quux': 4}) == { ... 'foo': 1, ... 'bar': 2, ... 'q...
:type d: dict :type d2: dict :rtype: dict def setdefaults(d, d2): """ :type d: dict :type d2: dict :rtype: dict """ for k, v in d2.items(): d.setdefault(k, v) return d
Get an attribute path, as defined by a string separated by '__'. getattr_path(foo, 'a__b__c') is roughly equivalent to foo.a.b.c but will short circuit to return None if something on the path is None. def getattr_path(obj, path): """ Get an attribute path, as defined by a string separated by '__'. ...
Set an attribute path, as defined by a string separated by '__'. setattr_path(foo, 'a__b__c', value) is equivalent to "foo.a.b.c = value". def setattr_path(obj, path, value): """ Set an attribute path, as defined by a string separated by '__'. setattr_path(foo, 'a__b__c', value) is equivalent to "foo.a...
Generate documentation for tri.declarative APIs :param directory: directory to write the .rst files into :param classes: list of classes to generate documentation for :param missing_objects: tuple of objects to count as missing markers, if applicable def generate_rst_docs(directory, classes, missing_objec...
Make a copy of a subset of a registry. :param reg: source registry :param keys: keys of registry items to copy :return: copied registry subset def reg_copy(reg, keys=None): """ Make a copy of a subset of a registry. :param reg: source registry :param keys: keys of registry items to copy ...
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 def get_covariance(datargs, outargs, vargs, ...
Calculate looping over specified repeat arguments. :param calc: Calculation to loop over. :param formula_reg: Formula registry :param data_reg: Data registry :param out_reg: Outputs registry :param timestep: timestep used for dynamic calcs :param idx: index used in dynam...
Listen for changes in all registered listeners in all specified rooms def listen_many(*rooms): """Listen for changes in all registered listeners in all specified rooms""" rooms = set(r.conn for r in rooms) for room in rooms: room.validate_listeners() with ARBITRATOR.condition: while an...
Connect to websocket through asyncio http interface def connect(self, username, checksum, password=None, key=None): """Connect to websocket through asyncio http interface""" ws_url = ( f"{BASE_WS_URL}?room={self.room.room_id}&cs={checksum}&nick={username}" f"&rn={random_id(6)}&...
Send an ack message def send_ack(self): """Send an ack message""" if self.last_ack == self.proto.max_id: return LOGGER.debug("ack (%d)", self.proto.max_id) self.last_ack = self.proto.max_id self.send_message(f"4{to_json([self.proto.max_id])}")
Makes a regular API call def make_call(self, fun, *args): """Makes a regular API call""" obj = {"fn": fun, "args": list(args)} obj = [self.proto.max_id, [[0, ["call", obj]], self.proto.send_count]] self.send_message(f"4{to_json(obj)}") self.proto.send_count += 1
Makes an API call with a callback to wait for def make_call_with_cb(self, fun, *args): """Makes an API call with a callback to wait for""" cid, event = self.handler.register_callback() argscp = list(args) argscp.append(cid) self.make_call(fun, *argscp) return event
Make a REST API call def make_api_call(self, call, params): """Make a REST API call""" if not isinstance(params, dict): raise ValueError("params argument must be a dictionary") kw = dict( params=params, headers={"Origin": BASE_URL, "Referer": f"{BASE_URL}/r/...
Reraise an exception passed by the event thread def reraise(self, ex): """Reraise an exception passed by the event thread""" self.exception = ex self.process_queues(forced=True)
Closes connection pair def close(self): """Closes connection pair""" if self.connected: obj = [self.proto.max_id, [[2], self.proto.send_count]] ARBITRATOR.send_sync_message(self.proto, f"4{to_json(obj)}") self.proto.send_count += 1 ARBITRATOR.close(self....
DingDongmaster the connection is open async def on_open(self): """DingDongmaster the connection is open""" self.__ensure_barrier() while self.connected: try: if self.__lastping > self.__lastpong: raise IOError("Last ping remained unanswered") ...
Processes incoming messages according to engine-io rules def on_message(self, new_data): """Processes incoming messages according to engine-io rules""" # https://github.com/socketio/engine.io-protocol LOGGER.debug("new frame [%r]", new_data) try: what = int(new_data[0]) ...
Add a listener for specific event type. You'll need to actually listen for changes using the listen method def add_listener(self, event_type, callback): """Add a listener for specific event type. You'll need to actually listen for changes using the listen method""" if not self.connecte...
Enqueue a data item for specific event type def enqueue_data(self, event_type, data): """Enqueue a data item for specific event type""" with self.lock: listeners = self.listeners.values() for listener in listeners: listener.enqueue(event_type, data) ...
Process queues if any have data queued def process_queues(self, forced=False): """Process queues if any have data queued""" with self.lock: if (not forced and not self.must_process) or not self.queues_enabled: return self.must_process = False ARBITRATOR....
All Listeners for the current thread def __listeners_for_thread(self): """All Listeners for the current thread""" thread = get_thread_ident() with self.lock: return [l for tid, l in self.listeners.items() if tid == thread]
Validates that some listeners are actually registered def validate_listeners(self): """Validates that some listeners are actually registered""" if self.exception: # pylint: disable=raising-bad-type raise self.exception listeners = self.__listeners_for_thread if...
Listen for changes in all registered listeners. def listen(self): """Listen for changes in all registered listeners.""" self.validate_listeners() with ARBITRATOR.condition: while self.connected: ARBITRATOR.condition.wait() if not self.run_queues(): ...
Run all queues that have data queued def run_queues(self): """Run all queues that have data queued""" if self.exception: # pylint: disable=raising-bad-type raise self.exception listeners = self.__listeners_for_thread return sum(l.process() for l in listeners) > ...
Add gettable and settable room config property during runtime def __add_prop(self, key, admin=False): """Add gettable and settable room config property during runtime""" def getter(self): return self.config[key] def setter(self, val): if admin and not self.admin: ...
Sets a value for a room config def __set_config_value(self, key, value): """Sets a value for a room config""" self.check_owner() params = {"room": self.room_id, "config": to_json({key: value})} resp = self.conn.make_api_call("setRoomConfig", params) if "error" in resp: ...