text
stringlengths
81
112k
Read the file until EOF and return a list of dictionaries. def read(self): """ Read the file until EOF and return a list of dictionaries. """ __result = [] __ll = self.readline() while __ll: __result.append(__ll) __ll = self.readline() r...
Close the SExtractor file. def close(self): """ Close the SExtractor file. """ if self._file: if not(self._file.closed): self._file.close() self.closed = True
Build an instance of the driver to interact with G5K def get_driver(configuration): """Build an instance of the driver to interact with G5K """ resources = configuration["resources"] machines = resources["machines"] networks = resources["networks"] oargrid_jobids = configuration.get("oargrid_jo...
Verifies the value of a cookie :param parts: The parts of the payload :param sign_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance :param enc_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance :param sign_alg: Which signing algorithm to was used :return: A tuple with basic information and a...
Create and return a cookies content If you only provide a `seed`, a HMAC gets added to the cookies value and this is checked, when the cookie is parsed again. If you provide both `seed` and `enc_key`, the cookie gets protected by using AEAD encryption. This provides both a MAC over the whole cookie ...
Give me the parts of the cookie payload :param name: A name of a cookie object :param kaka: The cookie :return: A list of parts or None if there is no cookie object with the given name def cookie_parts(name, kaka): """ Give me the parts of the cookie payload :param name: A name of a c...
Parses and verifies a cookie value Parses a cookie created by `make_cookie` and verifies it has not been tampered with. You need to provide the same `sign_key` and `enc_key` used when creating the cookie, otherwise the verification fails. See `make_cookie` for details about the verification. ...
Create a cookie that will immediately expire when it hits the other side. :param cookie_name: Name of the cookie :return: A tuple to be added to headers def delete_cookie(self, cookie_name=None): """ Create a cookie that will immediately expire when it hits the other si...
Return information stored in a Cookie :param cookie: A cookie instance :param cookie_name: The name of the cookie I'm looking for :return: tuple (value, timestamp, type) def get_cookie_value(self, cookie=None, cookie_name=None): """ Return information stored in a Cookie ...
Adds a cookie to a SimpleCookie instance :param cookie: :param name: :param payload: :param typ: :param domain: :param path: :param timestamp: :param max_age: :return: def append_cookie(self, cookie, name, payload, typ, domain=None, path=None, ...
Calculate AC power :param inverter: :param v_mp: :param p_mp: :return: AC power [W] def f_ac_power(inverter, v_mp, p_mp): """ Calculate AC power :param inverter: :param v_mp: :param p_mp: :return: AC power [W] """ return pvlib.pvsystem.snlinverter(v_mp, p_mp, inverter)...
Calculate DC power using Sandia Performance model :param effective_irradiance: effective irradiance [suns] :param cell_temp: PV cell temperature [degC] :param module: PV module dictionary or pandas data frame :returns: i_sc, i_mp, v_oc, v_mp, p_mp def f_dc_power(effective_irradiance, cell_temp, module...
Calculate effective irradiance for Sandia Performance model :param poa_direct: plane of array direct irradiance [W/m**2] :param poa_diffuse: plane of array diffuse irradiance [W/m**2] :param am_abs: absolute air mass [dimensionless] :param aoi: angle of incidence [degrees] :param module: PV module ...
Calculate cell temperature. :param poa_global: plane of array global irradiance [W/m**2] :param wind_speed: wind speed [m/s] :param air_temp: ambient dry bulb air temperature [degC] :return: cell temperature [degC] def f_cell_temp(poa_global, wind_speed, air_temp): """ Calculate cell temperatu...
Calculate angle of incidence :param surface_tilt: :param surface_azimuth: :param solar_zenith: :param solar_azimuth: :return: angle of incidence [deg] def f_aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth): """ Calculate angle of incidence :param surface_tilt: :para...
Search for assignment of __version__ string in given file and return what it is assigned to. def find_version(filename): """ Search for assignment of __version__ string in given file and return what it is assigned to. """ with open(filename, "r") as filep: version_file = filep.read() ...
Save numpy array(s) into a FITS file with the provided filename. Parameters ---------- array : numpy array or list of numpy arrays Array(s) to be exported as the FITS file. If the input is a list, a multi-extension FITS file is generated assuming that the list contains a list of arr...
Find a EMIR CSU bar position in a edge image. Parameters ========== edges; ndarray, a 2d image with 1 where is a border, 0 otherwise prow: int, reference 'row' of the bars bstart: int, minimum 'x' position of a bar (0-based) bend: int maximum 'x' position of a ba...
Compute the FWHM in the direction given by axis def calc_fwhm(img, region, fexpand=3, axis=0): """Compute the FWHM in the direction given by axis""" # We compute know the FWHM of the slit # Given the computed position of the slit # Expand 'fexpand' pixels around # and cut an slice in the median fi...
Find the first peak to the right of start def simple_prot(x, start): """Find the first peak to the right of start""" # start must b >= 1 for i in range(start,len(x)-1): a,b,c = x[i-1], x[i], x[i+1] if b - a > 0 and b -c >= 0: return i else: return None
Find the position where the value is half of the peak def position_half_h(pslit, cpix, backw=4): """Find the position where the value is half of the peak""" # Find the first peak to the right of cpix next_peak = simple_prot(pslit, cpix) if next_peak is None: raise ValueError dis_peak = n...
Fine position of the left CSU bar def locate_bar_l(icut, epos): """Fine position of the left CSU bar""" def swap_coor(x): return x def swap_line(tab): return tab return _locate_bar_gen(icut, epos, transform1=swap_coor, transform2=s...
Fine position of the right CSU bar def locate_bar_r(icut, epos): """Fine position of the right CSU bar""" sm = len(icut) def swap_coor(x): return sm - 1 - x def swap_line(tab): return tab[::-1] return _locate_bar_gen(icut, epos, transform1=swap_coor, tr...
Generic function for the fine position of the CSU def _locate_bar_gen(icut, epos, transform1, transform2): """Generic function for the fine position of the CSU""" epos_pix = coor_to_pix_1d(epos) # transform -> epos_pix_s = transform1(epos_pix) icut2 = transform2(icut) # try: res ...
Overlaping of two intervals def overlap(intv1, intv2): """Overlaping of two intervals""" return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
Integrity check of 'bounddict' content. Parameters ---------- bounddict : JSON structure Structure employed to store bounddict information. max_dtu_offset : float Maximum allowed difference in DTU location (mm) for each parameter def integrity_check(bounddict, max_dtu_offset): ...
Convert virtual pixel to real pixel. Parameters ---------- x : array-like of floats X coordinate (pixel). y : array-like of floats Y coordinate (pixel). x0 : float X coordinate of reference pixel, in units of 1E3. y0 : float Y coordinate of reference pixel, in un...
Convert virtual pixel(s) to real pixel(s). This function makes use of exvp_scalar(), which performs the conversion for a single point (x, y), over an array of X and Y values. Parameters ---------- x : array-like X coordinate (pixel). y : array-like Y coordinate (pixel). ...
Return individual model parameters from object of type Parameters. Parameters ---------- islitlet : int Number of slitlet. csu_bar_slit_center : float CSU bar slit center, in mm. params : :class:`~lmfit.parameter.Parameters` Parameters to be employed in the prediction of the...
Return expected SpectrumTrail instances associated to a given slitlet. Several SpectrumTrail objects can be computed for the considered slitlet. The parameter borderlist is a list of floats, ranging from 0 to 1, indicating the spatial location of the spectrum trail within the slitlet: 0 means the lower...
Function to be minimised. Parameters ---------- params : :class:`~lmfit.parameter.Parameters` Parameters to be employed in the prediction of the distorted boundaries. parmodel : str Model to be assumed. Allowed values are 'longslit' and 'multislit'. bounddict : JSON ...
Overplot boundaries on current plot. Parameters ---------- ax : matplotlib axes Current plot axes. bounddict : JSON structure Structure employed to store bounddict information. micolors : list of char List with two characters corresponding to alternating colors for o...
Overplot boundaries computed from fitted parameters. Parameters ---------- ax : matplotlib axes Current plot axes. params : :class:`~lmfit.parameter.Parameters` Parameters to be employed in the prediction of the distorted boundaries. parmodel : str Model to be assume...
Export to ds9 region file the boundaries in bounddict. Parameters ---------- bounddict : JSON structure Structure employed to store bounddict information. ds9_filename : str Output file name for the ds9 region file. numpix : int Number of points in which the X-range interval...
Export to ds9 region file the boundaries parametrised with params. Parameters ---------- params : :class:`~lmfit.parameter.Parameters` Parameters to be employed in the prediction of the distorted boundaries. parmodel : str Model to be assumed. Allowed values are 'longslit' and ...
Define `~lmfit.parameter.Parameters` object from dictionary. Parameters ---------- bound_param_dict : dictionary Dictionary containing the JSON contents of a boundary parameter file. Returns ------- params : :class:`~lmfit.parameter.Parameters` Parameters object. def b...
Set metadata in FITS headers. def set_base_headers(self, hdr): """Set metadata in FITS headers.""" hdr = super(StareImageRecipe2, self).set_base_headers(hdr) # Set EXP to 0 hdr['EXP'] = 0 return hdr
Set metadata in FITS headers. def set_base_headers(self, hdr): """Set metadata in FITS headers.""" hdr = super(StareImageBaseRecipe, self).set_base_headers(hdr) # Update EXP to 0 hdr['EXP'] = 0 return hdr
Compute rectification and wavelength calibration coefficients. Parameters ---------- reduced_image : HDUList object Image with preliminary basic reduction: bpm, bias, dark and flatfield. rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients ...
start a transaction this will increment transaction semaphore and pass it to _transaction_start() def transaction_start(self, name): """ start a transaction this will increment transaction semaphore and pass it to _transaction_start() """ if not name: raise...
stop/commit a transaction if ready def transaction_stop(self): """stop/commit a transaction if ready""" if self.transaction_count > 0: logger.debug("{}. Stop transaction".format(self.transaction_count)) if self.transaction_count == 1: self._transaction_stop() ...
rollback a transaction if currently in one e -- Exception() -- if passed in, bubble up the exception by re-raising it def transaction_fail(self, name): """ rollback a transaction if currently in one e -- Exception() -- if passed in, bubble up the exception by re-raising it """...
connect to the interface this will set the raw db connection to self.connection *args -- anything you want that will help the db connect **kwargs -- anything you want that the backend db connection will need to actually connect def connect(self, connection_config=None, *args, **kwargs): ...
close an open connection def close(self): """close an open connection""" if not self.connected: return True self._close() self.connected = False self.log("Closed Connection {}", self.connection_config.interface_name) return True
run a raw query on the db query_str -- string -- the query to run *query_args -- if the query_str is a formatting string, pass the values in this **query_options -- any query options can be passed in by using key=val syntax def query(self, query_str, *query_args, **query_options): """ ...
a simple context manager useful for when you want to wrap a bunch of db calls in a transaction http://docs.python.org/2/library/contextlib.html http://docs.python.org/release/2.5/whatsnew/pep-343.html example -- with self.transaction() # do a bunch of calls ...
add the table to the db schema -- Schema() -- contains all the information about the table def set_table(self, schema, **kwargs): """ add the table to the db schema -- Schema() -- contains all the information about the table """ with self.connection(**kwargs) as connec...
check to see if a table is in the db table_name -- string -- the table to check return -- boolean -- True if the table exists, false otherwise def has_table(self, table_name, **kwargs): """ check to see if a table is in the db table_name -- string -- the table to check ...
get all the tables of the currently connected db table_name -- string -- if you would like to filter the tables list to only include matches with this name return -- list -- a list of table names def get_tables(self, table_name="", **kwargs): """ get all the tables of the currently con...
remove a table matching schema from the db schema -- Schema() def delete_table(self, schema, **kwargs): """ remove a table matching schema from the db schema -- Schema() """ with self.connection(**kwargs) as connection: kwargs['connection'] = connection ...
removes all the tables from the db this is, obviously, very bad if you didn't mean to call this, because of that, you have to pass in disable_protection=True, if it doesn't get that passed in, it won't run this method def delete_tables(self, **kwargs): """ removes all the table...
get all the indexes schema -- Schema() return -- dict -- the indexes in {indexname: fields} format def get_indexes(self, schema, **kwargs): """ get all the indexes schema -- Schema() return -- dict -- the indexes in {indexname: fields} format """ with...
add an index to the table schema -- Schema() name -- string -- the name of the index fields -- array -- the fields the index should be on **index_options -- dict -- any index options that might be useful to create the index def set_index(self, schema, name, fields, **index_options): ...
Persist d into the db schema -- Schema() fields -- dict -- the values to persist return -- int -- the primary key of the row just inserted def insert(self, schema, fields, **kwargs): """ Persist d into the db schema -- Schema() fields -- dict -- the values to ...
Persist the query.fields into the db that match query.fields_where schema -- Schema() fields -- dict -- the values to persist query -- Query() -- will be used to create the where clause return -- int -- how many rows where updated def update(self, schema, fields, query, **kwargs): ...
this is just a common wrapper around all the get queries since they are all really similar in how they execute def _get_query(self, callback, schema, query=None, *args, **kwargs): """this is just a common wrapper around all the get queries since they are all really similar in how they execute""...
get one row from the db matching filters set in query schema -- Schema() query -- Query() return -- dict -- the matching row def get_one(self, schema, query=None, **kwargs): """ get one row from the db matching filters set in query schema -- Schema() query -- ...
get matching rows from the db matching filters set in query schema -- Schema() query -- Query() return -- list -- a list of matching dicts def get(self, schema, query=None, **kwargs): """ get matching rows from the db matching filters set in query schema -- Schema() ...
wrapper around the module's logger format_str -- string -- the message to log *format_args -- list -- if format_str is a string containing {}, then format_str.format(*format_args) is ran **log_options -- level -- something like logging.DEBUG def log(self, format_str, *format_args,...
this is just a wrapper to make the passed in exception an InterfaceError def raise_error(self, e, exc_info=None): """this is just a wrapper to make the passed in exception an InterfaceError""" if not exc_info: exc_info = sys.exc_info() if not isinstance(e, InterfaceError): ...
**query_options -- dict ignore_result -- boolean -- true to not attempt to fetch results fetchone -- boolean -- true to only fetch one result count_result -- boolean -- true to return the int count of rows affected def _query(self, query_str, query_args=None, **query_options): ...
convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- true if this is a count query SELECT only_where_clause -- ...
You can run into a problem when you are trying to set a table and it has a foreign key to a table that doesn't exist, so this method will go through all fk refs and make sure the tables exist def _set_all_tables(self, schema, **kwargs): """ You can run into a problem when you are tryi...
this will add fields that don't exist in the table if they can be set to NULL, the reason they have to be NULL is adding fields to Postgres that can be NULL is really light, but if they have a default value, then it can be costly def _set_all_fields(self, schema, **kwargs): """ this wil...
Random path generator for uploads, specify this for upload_to= argument of FileFields def random_path(instance, filename): """ Random path generator for uploads, specify this for upload_to= argument of FileFields """ # Split the uuid into two parts so that we won't run into subdirectory count limits. First...
Initialize metrics, must be invoked at least once prior to invoking any other method. def initialize(signal_number=DEFAULT_TIMER_SIGNAL_NUMBER, update_period_s=DEFAULT_UPDATE_PERIOD_S): """Initialize metrics, must be invoked at least once prior to invoking any other method.""" global ini...
Serialize metrics to the memory mapped buffer. def emit(_): """Serialize metrics to the memory mapped buffer.""" if not initialized: raise NotInitialized view = { 'version': __version__, 'counters': {}, 'gauges': {}, 'histograms': {}, 'meters': {}, '...
Get a dictionary representation of current metrics. def view(): """Get a dictionary representation of current metrics.""" if not initialized: raise NotInitialized marshalled_metrics_mmap.seek(0) try: uwsgi.lock() marshalled_view = marshalled_metrics_mmap.read( MAX_M...
Context manager to time a section of code:: with timing(__name__, 'my_timer'): do_some_operation() def timing(module, name): """ Context manager to time a section of code:: with timing(__name__, 'my_timer'): do_some_operation() """ start_time_s = time.time() ...
Record a timing delta: :: start_time_s = time.time() do_some_operation() end_time_s = time.time() delta_s = end_time_s - start_time_s delta_ms = delta_s * 1000 timer(__name__, 'my_timer', delta_ms) def timer(module, name, delta, duration_units='milliseconds'): "...
Record a value in a histogram: :: histogram(__name__, 'my_histogram', len(queue)) def histogram(module, name, value): """ Record a value in a histogram: :: histogram(__name__, 'my_histogram', len(queue)) """ histogram = get_metric('histograms', module, name, Histogram()) h...
Record an event's occurence in a counter: :: counter(__name__, 'my_counter') def counter(module, name, count=1): """ Record an event's occurence in a counter: :: counter(__name__, 'my_counter') """ counter = get_metric('counters', module, name, Counter()) counter.inc(count)
Record an event rate: :: meter(__name__, 'my_meter', 'event_type') def meter(module, name, count=1): """ Record an event rate: :: meter(__name__, 'my_meter', 'event_type') """ meter = get_metric('meters', module, name, Meter()) meter.mark(count)
Execute a command on a node (id or hostname) or on a set of nodes. :param nodes: list of targets of the command cmd. Each must be an execo.Host. :param cmd: string representing the command to run on the remote nodes. :param label: string f...
Write EMIRUUID header on reduction def convert_out(self, obj): """Write EMIRUUID header on reduction""" newobj = super(ProcessedImageProduct, self).convert_out(obj) if newobj: hdulist = newobj.open() hdr = hdulist[0].header if 'EMIRUUID' not in hdr: ...
Initiated Guessing ! :param endpoint_context: SrvInfo instance :param request: The request :param authorization_info: Client authentication information :return: dictionary containing client id, client authentication method and possibly access token. def verify_client(endpoint_context, request,...
This is where clients come to refresh their access tokens :param request: The request :param authn: Authentication info, comes from HTTP header :returns: def _post_parse_request(self, request, client_id='', **kwargs): """ This is where clients come to refresh their access token...
Generates a random ID of given length def random_id(length): """Generates a random ID of given length""" def char(): """Generate single random char""" return random.choice(string.ascii_letters + string.digits) return "".join(char() for _ in range(length))
Delay close until this contextmanager dies def delayed_close(closable): """Delay close until this contextmanager dies""" close = getattr(closable, "close", None) if close: # we do not want the library to close file in case we need to # resume, hence make close a no-op # pylint: dis...
Store the connection between a Session ID and a User ID :param sid: Session ID :param uid: User ID def map_sid2uid(self, sid, uid): """ Store the connection between a Session ID and a User ID :param sid: Session ID :param uid: User ID """ self.set('sid2...
Store the connection between a Session ID and a subject ID. :param sid: Session ID :param sub: subject ID def map_sid2sub(self, sid, sub): """ Store the connection between a Session ID and a subject ID. :param sid: Session ID :param sub: subject ID """ ...
Find all subject identifiers that is connected to a User ID. :param uid: A User ID :return: A set of subject identifiers def get_subs_by_uid(self, uid): """ Find all subject identifiers that is connected to a User ID. :param uid: A User ID :return: A set of subject ide...
Remove the connection between a session ID and a Subject :param sid: Session ID :param sub: Subject identifier ´ def remove_sid2sub(self, sid, sub): """ Remove the connection between a session ID and a Subject :param sid: Session ID :param sub: Subject identifier ´ ...
Remove the connection between a session ID and a Subject :param sid: Session ID :param uid: User identifier ´ def remove_sid2uid(self, sid, uid): """ Remove the connection between a session ID and a Subject :param sid: Session ID :param uid: User identifier ´ """...
Remove all references to a specific Session ID :param sid: A Session ID def remove_session_id(self, sid): """ Remove all references to a specific Session ID :param sid: A Session ID """ for uid in self.get('sid2uid', sid): self.remove('uid2sid', uid, sid) ...
Remove all references to a specific User ID :param uid: A User ID def remove_uid(self, uid): """ Remove all references to a specific User ID :param uid: A User ID """ for sid in self.get('uid2sid', uid): self.remove('sid2uid', sid, uid) self.delete(...
Remove all references to a specific Subject ID :param sub: A Subject ID def remove_sub(self, sub): """ Remove all references to a specific Subject ID :param sub: A Subject ID """ for _sid in self.get('sub2sid', sub): self.remove('sid2sub', _sid, sub) ...
Starts a new experiment def up(force=True, env=None, **kwargs): "Starts a new experiment" inventory = os.path.join(os.getcwd(), "hosts") conf = Configuration.from_dictionnary(provider_conf) provider = Enos_vagrant(conf) roles, networks = provider.init() check_networks(roles, networks) env["...
Decorator to be using in formulas to convert ``test_args`` depending on the ``test_fcn``. :param test_fcn: A test function that converts arguments. :type test_fcn: function :param test_args: Names of args to convert using ``test_fcn``. :type test_args: str The following test functions are avai...
Return class attributes that are neither private nor magic. :param cls: class :param as_list: [True] set to False to return generator :return: only public attributes of class def get_public_attributes(cls, as_list=True): """ Return class attributes that are neither private nor magic. :param c...
Register newitems in registry. :param newitems: New items to add to registry. When registering new items, keys are not allowed to override existing keys in the registry. :type newitems: mapping :param args: Positional arguments with meta data corresponding to order ...
Remove items from registry. :param items: def unregister(self, items): """ Remove items from registry. :param items: """ items = _listify(items) # get all members of Registry except private, special or class meta_names = (m for m in vars(self).iterkeys(...
JSONEncoder default method that converts NumPy arrays and quantities objects to lists. def default(self, o): """ JSONEncoder default method that converts NumPy arrays and quantities objects to lists. """ if isinstance(o, Q_): return o.magnitude elif i...
Get all of the ``Meta`` classes from bases and combine them with this class. Pops or creates ``Meta`` from attributes, combines all bases, adds ``_meta`` to attributes with all meta :param bases: bases of this class :param attr: class attributes :return: attributes with...
Set parameters from class attributes that are instances of :class:`~simkit.core.Parameter` or from a parameter file. Any class attributes that are instances of :class:`~simkit.core.Parameter` are popped from the class and added to a the ``parameters`` attribute, which is a dictionary of...
Factory method that can be used to easily instantiate a class instance :param cls: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class. def factory(cls, **kwargs): """ Factory method that can be used to ...
Register formula and meta data. * ``islinear`` - ``True`` if formula is linear, ``False`` if non-linear. * ``args`` - position of arguments * ``units`` - units of returns and arguments as pair of tuples * ``isconstant`` - constant arguments not included in covariance :param new...
Import formulas specified in :attr:`parameters`. :returns: formulas :rtype: dict def import_formulas(self): """ Import formulas specified in :attr:`parameters`. :returns: formulas :rtype: dict """ # TODO: unit tests! # TODO: move this to somewhe...
Check the reservation, creates a new one if nescessary. def create_blazar_client(config, session): """Check the reservation, creates a new one if nescessary.""" return blazar_client.Client(session=session, service_type="reservation", region_name=o...
this is a very specific decorator meant to be used on Interface classes. It will attempt to reconnect if the connection is closed and run the same method again. TODO -- I think this will have issues with transactions using passed in connections, ie, you pass in a transacting connection to the insert()...