text
stringlengths
18
773k
def get_templatetype_by_name(template_id, type_name,**kwargs): """ Get a specific resource type by name. """ try: templatetype = db.DBSession.query(TemplateType).filter(TemplateType.id==template_id, TemplateType.name==type_name).one() except NoResultFound: raise HydraError("%s i...
def add_typeattr(typeattr,**kwargs): """ Add an typeattr to an existing type. """ tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id')) ta = _set_typeattr(typeattr) tmpltype.typeattrs.append(ta) db.DBSession.flush() return ta
def delete_typeattr(typeattr,**kwargs): """ Remove an typeattr from an existing type """ tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id')) ta = db.DBSession.query(TypeAttr).filter(TypeAttr.type_id == typeattr.type_id, TypeAtt...
def validate_attr(resource_attr_id, scenario_id, template_id=None): """ Check that a resource attribute satisfies the requirements of all the types of the resource. """ rs = db.DBSession.query(ResourceScenario).\ filter(ResourceScenario.resource_attr_id==resource_attr...
def validate_attrs(resource_attr_ids, scenario_id, template_id=None): """ Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached. """ multi_rs = db.DBSession.query(ResourceScenario).\ filter(Resourc...
def _do_validate_resourcescenario(resourcescenario, template_id=None): """ Perform a check to ensure a resource scenario's datasets are correct given what the definition of that resource (its type) specifies. """ res = resourcescenario.resourceattr.get_resource() types = res.types ...
def validate_network(network_id, template_id, scenario_id=None): """ Given a network, scenario and template, ensure that all the nodes, links & groups in the network have the correct resource attributes as defined by the types in the template. Also ensure valid entries in tresourcetype. ...
def get_network_as_xml_template(network_id,**kwargs): """ Turn an existing network into an xml template using its attributes. If an optional scenario ID is passed in, default values will be populated from that scenario. """ template_xml = etree.Element("template_definition") ...
def _make_attr_element_from_typeattr(parent, type_attr_i): """ General function to add an attribute element to a resource element. resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml """ attr = _make_attr_element(parent, type_attr_i.attr) if type_attr_i.unit...
def _make_attr_element_from_resourceattr(parent, resource_attr_i): """ General function to add an attribute element to a resource element. """ attr = _make_attr_element(parent, resource_attr_i.attr) attr_is_var = etree.SubElement(attr, 'is_var') attr_is_var.text = resource_attr_i.attr_i...
def _make_attr_element(parent, attr_i): """ create an attribute element from an attribute DB object """ attr = etree.SubElement(parent, "attribute") attr_name = etree.SubElement(attr, 'name') attr_name.text = attr_i.name attr_desc = etree.SubElement(attr, 'description') a...
def get_etree_layout_as_dict(layout_tree): """ Convert something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> <item> <name>shapefile</name> <value>blah.shp</value> </item> </layout> ...
def _get_layout_as_etree(layout_dict): """ Convert something that looks like this: { 'color' : ['red'], 'shapefile' : ['blah.shp'] } Into something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> ...
def valueFromDataset(cls, datatype, value, metadata=None, tmap=None): """ Return the value contained by dataset argument, after casting to correct type and performing type-specific validation """ if tmap is None: tmap = typemap obj = cls.fromDataset(dataty...
def fromDataset(datatype, value, metadata=None, tmap=None): """ Return a representation of dataset argument as an instance of the class corresponding to its datatype """ if tmap is None: tmap = typemap return tmap[datatype.upper()].fromDataset(value, meta...
def exists_dimension(dimension_name,**kwargs): """ Given a dimension returns True if it exists, False otherwise """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one() # At this point the dimension exists return True except NoResult...
def _parse_unit(measure_or_unit_abbreviation): """ Helper function that extracts constant factors from unit specifications. This allows to specify units similar to this: 10^6 m^3. Return a couple (unit, factor) """ try: float(measure_or_unit_abbreviation[0]) # The mea...
def convert_units(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation,**kwargs): """ Convert a value from one unit to another one. Example:: >>> cli = PluginLib.connect() >>> cli.service.convert_units(20.0, 'm', 'km') 0.02 Pa...
def convert(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation): """ Convert a value or a list of values from an unit to another one. The two units must represent the same physical dimension. """ source_dimension = get_dimension_by_unit_measure_or_abbreviation(...
def get_empty_dimension(**kwargs): """ Returns a dimension object initialized with empty values """ dimension = JSONObject(Dimension()) dimension.id = None dimension.name = '' dimension.description = '' dimension.project_id = None dimension.units = [] return dimension
def get_dimension(dimension_id, do_accept_dimension_id_none=False,**kwargs): """ Given a dimension id returns all its data """ if do_accept_dimension_id_none == True and dimension_id is None: # In this special case, the method returns a dimension with id None return get_empty_dimensi...
def get_dimensions(**kwargs): """ Returns a list of objects describing all the dimensions with all the units. """ dimensions_list = db.DBSession.query(Dimension).options(load_only("id")).all() return_list = [] for dimension in dimensions_list: return_list.append(get_dimension(dimensi...
def get_dimension_by_name(dimension_name,**kwargs): """ Given a dimension name returns all its data. Used in convert functions """ try: if dimension_name is None: dimension_name = '' dimension = db.DBSession.query(Dimension).filter(func.lower(Dimension.name)==func.lower(d...
def get_unit(unit_id, **kwargs): """ Returns a single unit """ try: unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() return JSONObject(unit) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Unit %s not found"%(unit_id...
def get_units(**kwargs): """ Returns all the units """ units_list = db.DBSession.query(Unit).all() units = [] for unit in units_list: new_unit = JSONObject(unit) units.append(new_unit) return units
def get_dimension_by_unit_measure_or_abbreviation(measure_or_unit_abbreviation,**kwargs): """ Return the physical dimension a given unit abbreviation of a measure, or the measure itself, refers to. The search key is the abbreviation or the full measure """ unit_abbreviation, factor = _parse...
def get_dimension_by_unit_id(unit_id, do_accept_unit_id_none=False, **kwargs): """ Return the physical dimension a given unit id refers to. if do_accept_unit_id_none is False, it raises an exception if unit_id is not valid or None if do_accept_unit_id_none is True, and unit_id is None, the f...
def get_unit_by_abbreviation(unit_abbreviation, **kwargs): """ Returns a single unit by abbreviation. Used as utility function to resolve string to id """ try: if unit_abbreviation is None: unit_abbreviation = '' unit_i = db.DBSession.query(Unit).filter(Unit.abbreviation=...
def add_dimension(dimension,**kwargs): """ Add the dimension defined into the object "dimension" to the DB If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project If the dimension exists emits an exception """ if numpy.isscalar(dim...
def update_dimension(dimension,**kwargs): """ Update a dimension in the DB. Raises and exception if the dimension does not exist. The key is ALWAYS the name and the name itself is not modificable """ db_dimension = None dimension = JSONObject(dimension) try: db_dimens...
def delete_dimension(dimension_id,**kwargs): """ Delete a dimension from the DB. Raises and exception if the dimension does not exist """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension_id).one() db.DBSession.query(Unit).filter(Unit.dimension_id==dimens...
def bulk_add_dimensions(dimension_list, **kwargs): """ Save all the dimensions contained in the passed list. """ added_dimensions = [] for dimension in dimension_list: added_dimensions.append(add_dimension(dimension, **kwargs)) return JSONObject({"dimensions": added_dimensions})
def add_unit(unit,**kwargs): """ Add the unit defined into the object "unit" to the DB If unit["project_id"] is None it means that the unit is global, otherwise is property of a project If the unit exists emits an exception A minimal example: .. code-block:: python ...
def bulk_add_units(unit_list, **kwargs): """ Save all the units contained in the passed list, with the name of their dimension. """ # for unit in unit_list: # add_unit(unit, **kwargs) added_units = [] for unit in unit_list: added_units.append(add_unit(unit, **kwargs)) r...
def delete_unit(unit_id, **kwargs): """ Delete a unit from the DB. Raises and exception if the unit does not exist """ try: db_unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() db.DBSession.delete(db_unit) db.DBSession.flush() return True ex...
def update_unit(unit, **kwargs): """ Update a unit in the DB. Raises and exception if the unit does not exist """ try: db_unit = db.DBSession.query(Unit).join(Dimension).filter(Unit.id==unit["id"]).filter().one() db_unit.name = unit["name"] # Needed to uniform into...
def convert_dataset(dataset_id, target_unit_abbreviation,**kwargs): """ Convert a whole dataset (specified by 'dataset_id') to new unit ('target_unit_abbreviation'). Conversion ALWAYS creates a NEW dataset, so function returns the dataset ID of new dataset. """ ds_i = db.DBSession.query(Dat...
def validate_resource_attributes(resource, attributes, template, check_unit=True, exact_match=False,**kwargs): """ Validate that the resource provided matches the template. Only passes if the resource contains ONLY the attributes specified in the template. The template should take t...
def encode(encoding, data): """ Encodes the given data using the encoding that is specified :param str encoding: encoding to use, should be one of the supported encoding :param data: data to encode :type data: str or bytes :return: multibase encoded data :rtype: bytes :raises ValueError...
def get_codec(data): """ Returns the codec used to encode the given data :param data: multibase encoded data :type data: str or bytes :return: the :py:obj:`multibase.Encoding` object for the data's codec :raises ValueError: if the codec is not supported """ try: key = ensure_byt...
def decode(data): """ Decode the multibase decoded data :param data: multibase encoded data :type data: str or bytes :return: decoded data :rtype: str :raises ValueError: if the data is not multibase encoded """ data = ensure_bytes(data, 'utf8') codec = get_codec(data) return...
def ed25519_generate_key_pair_from_secret(secret): """ Generate a new key pair. Args: secret (:class:`string`): A secret that serves as a seed Returns: A tuple of (private_key, public_key) encoded in base58. """ # if you want to do this correctly, use a key derivation function! ...
def generate_key_pair(secret=None): """Generates a cryptographic key pair. Args: secret (:class:`string`): A secret that serves as a seed Returns: :class:`~bigchaindb.common.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb.common.cry...
def _get_role_arn(): """ Return role arn from X-Role-ARN header, lookup role arn from source IP, or fall back to command line default. """ role_arn = bottle.request.headers.get('X-Role-ARN') if not role_arn: role_arn = _lookup_ip_role_arn(bottle.request.environ.get('REMOTE_ADDR')) ...
def _on_dynamodb_exception(self, error): """Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error: """ if isinstance(error, exceptions.ConditionalCheckFailedException): raise web.HTTPError(409, reason='Cond...
def _chunk_with_padding(self, iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # _chunk_with_padding('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)
def marshall(values): """ Marshall a `dict` into something DynamoDB likes. :param dict values: The values to marshall :rtype: dict :raises ValueError: if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB. ...
def unmarshall(values): """ Transform a response payload from DynamoDB to a native dict :param dict values: The response payload from DynamoDB :rtype: dict :raises ValueError: if an unsupported type code is encountered """ unmarshalled = {} for key in values: unmarshalled[key] ...
def _marshall_value(value): """ Recursively transform `value` into an AttributeValue `dict` :param mixed value: The value to encode :rtype: dict :raises ValueError: for unsupported types Return the value as dict indicating the data type and transform or recursively process the value if req...
def _unmarshall_dict(value): """Unmarshall a single dict value from a row that was returned from DynamoDB, returning the value as a normal Python dict. :param dict value: The value to unmarshall :rtype: mixed :raises ValueError: if an unsupported type code is encountered """ key = list(val...
def _unwrap_result(action, result): """Unwrap a request response and return only the response data. :param str action: The action name :param result: The result of the action :type: result: list or dict :rtype: dict | None """ if not result: return elif action in {'DeleteItem',...
def list_tables(self, exclusive_start_table_name=None, limit=None): """ Invoke the `ListTables`_ function. Returns an array of table names associated with the current account and endpoint. The output from *ListTables* is paginated, with each page returning a maximum of ``100`` t...
def put_item(self, table_name, item, condition_expression=None, expression_attribute_names=None, expression_attribute_values=None, return_consumed_capacity=None, return_item_collection_metrics=None, return_values=None)...
def get_item(self, table_name, key_dict, consistent_read=False, expression_attribute_names=None, projection_expression=None, return_consumed_capacity=None): """ Invoke the `GetItem`_ function. :param str table_name: table to re...
def update_item(self, table_name, key_dict, condition_expression=None, update_expression=None, expression_attribute_names=None, expression_attribute_values=None, return_consumed_capacity=None, return_...
def query(self, table_name, index_name=None, consistent_read=None, key_condition_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, projection_expression=None, ...
def scan(self, table_name, index_name=None, consistent_read=None, projection_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, segment=None, tota...
def execute(self, action, parameters): """ Execute a DynamoDB action with the given parameters. The method will retry requests that failed due to OS level errors or when being throttled by DynamoDB. :param str action: DynamoDB action to invoke :param dict parameters: par...
def set_error_callback(self, callback): """Assign a method to invoke when a request has encountered an unrecoverable error in an action execution. :param method callback: The method to invoke """ self.logger.debug('Setting error callback: %r', callback) self._on_error =...
def set_instrumentation_callback(self, callback): """Assign a method to invoke when a request has completed gathering measurements. :param method callback: The method to invoke """ self.logger.debug('Setting instrumentation callback: %r', callback) self._instrumentation...
def _execute(self, action, parameters, attempt, measurements): """Invoke a DynamoDB action :param str action: DynamoDB action to invoke :param dict parameters: parameters to send into the action :param int attempt: Which attempt number this is :param list measurements: A list fo...
def _on_response(self, action, table, attempt, start, response, future, measurements): """Invoked when the HTTP request to the DynamoDB has returned and is responsible for setting the future result or exception based upon the HTTP response provided. :param str actio...
def _process_response(response): """Process the raw AWS response, returning either the mapped exception or deserialized response. :param tornado.concurrent.Future response: The request future :rtype: dict or list :raises: sprockets_dynamodb.exceptions.DynamoDBException ...
def write(self, obj, resource_id=None): """Write and obj in bdb. :param obj: value to be written in bdb. :param resource_id: id to make possible read and search for an resource. :return: id of the transaction """ if resource_id is not None: if self.read(resou...
def _get(self, tx_id): """Read and obj in bdb using the tx_id. :param resource_id: id of the transaction to be read. :return: value with the data, transaction id and transaction. """ # tx_id=self._find_tx_id(resource_id) value = [ { 'data': tr...
def _update(self, metadata, tx_id, resource_id): """Update and obj in bdb using the tx_id. :param metadata: new metadata for the transaction. :param tx_id: id of the transaction to be updated. :return: id of the transaction. """ try: if not tx_id: ...
def list(self, search_from=None, search_to=None, limit=None): """List all the objects saved in the namespace. :param search_from: TBI :param search_to: TBI :param offset: TBI :param limit: max number of values to be shows. :return: list with transactions. "...
def _list(self): """List all the objects saved in the namespace. :param search_from: TBI :param search_to: TBI :param offset: TBI :param limit: max number of values to be shows. :return: list with transactions. """ all = self.driver.instance.metadata.get(...
def query(self, search_model: QueryModel): """Query to bdb namespace. :param query_string: query in string format. :return: list of transactions that match with the query. """ self.logger.debug('bdb::get::{}'.format(search_model.query)) assets = json.loads(requests.post(...
def _delete(self, tx_id): """Delete a transaction. Read documentation about CRAB model in https://blog.bigchaindb.com/crab-create-retrieve-append-burn-b9f6d111f460. :param tx_id: transaction id :return: """ txs = self.driver.instance.transactions.get(asset_id=self.get_asset_id(t...
def get_asset_id(self, tx_id): """Return the tx_id of the first transaction. :param tx_id: Transaction id to start the recursive search. :return Transaction id parent. """ tx = self.driver.instance.transactions.retrieve(txid=tx_id) assert tx is not None return tx...
def hdr(data, filename): """ write ENVI header files Parameters ---------- data: str or dict the file or dictionary to get the info from filename: str the HDR file to write Returns ------- """ hdrobj = data if isinstance(data, HDRobject) else HDRobject(data) ...
def __hdr2dict(self): """ read a HDR file into a dictionary http://gis.stackexchange.com/questions/48618/how-to-read-write-envi-metadata-using-gdal Returns ------- dict the hdr file metadata attributes """ with open(self.filename, 'r') as infil...
def write(self, filename='same'): """ write object to an ENVI header file """ if filename == 'same': filename = self.filename if not filename.endswith('.hdr'): filename += '.hdr' with open(filename, 'w') as out: out.write(self.__str__()...
def MaxSpeed(self, speed): ' Setup of maximum speed ' spi.SPI_write_byte(self.CS, 0x07) # Max Speed setup spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, speed)
def GoZero(self, speed): ' Go to Zero position ' self.ReleaseSW() spi.SPI_write_byte(self.CS, 0x82 | (self.Dir & 1)) # Go to Zero spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, speed) while self.IsBusy(): pass time.sleep(0.3) ...
def Move(self, units): ' Move some distance units from current position ' steps = units * self.SPU # translate units to steps if steps > 0: # look for direction spi.SPI_write_byte(self.CS, 0x40 | (~self.Dir & 1)) else: ...
def ReadStatusBit(self, bit): ' Report given status bit ' spi.SPI_write_byte(self.CS, 0x39) # Read from address 0x19 (STATUS) spi.SPI_write_byte(self.CS, 0x00) data0 = spi.SPI_read_byte() # 1st byte spi.SPI_write_byte(self.CS, 0x00) data1 = spi.SPI_read_byte()...
def SPI_write_byte(self, chip_select, data): 'Writes a data to a SPI device selected by chipselect bit. ' self.bus.write_byte_data(self.address, chip_select, data)
def SPI_write(self, chip_select, data): 'Writes data to SPI device selected by chipselect bit. ' dat = list(data) dat.insert(0, chip_select) return self.bus.write_i2c_block(self.address, dat);
def SPI_config(self,config): 'Configure SPI interface parameters.' self.bus.write_byte_data(self.address, 0xF0, config) return self.bus.read_byte_data(self.address, 0xF0)
def GPIO_read(self): 'Reads logic state on GPIO enabled slave-selects pins.' self.bus.write_byte_data(self.address, 0xF5, 0x0f) status = self.bus.read_byte(self.address) bits_values = dict([('SS0',status & 0x01 == 0x01),('SS1',status & 0x02 == 0x02),('SS2',status & 0x04 == 0x04),('SS3',s...
def GPIO_config(self, gpio_enable, gpio_config): 'Enable or disable slave-select pins as gpio.' self.bus.write_byte_data(self.address, 0xF6, gpio_enable) self.bus.write_byte_data(self.address, 0xF7, gpio_config) return
def get_address(self): """ Returns sensors I2C address. """ LOGGER.debug("Reading RPS01A sensor's address.",) return self.bus.read_byte_data(self.address, self.address_reg)
def get_zero_position(self): """ Returns programmed zero position in OTP memory. """ LSB = self.bus.read_byte_data(self.address, self.zero_position_MSB) MSB = self.bus.read_byte_data(self.address, self.zero_position_LSB) DATA = (MSB << 6) + LSB return DATA
def get_agc_value(self): """ Returns sensor's Automatic Gain Control actual value. 0 - Represents high magtetic field 0xFF - Represents low magnetic field """ LOGGER.debug("Reading RPS01A sensor's AGC settings",) return self.bus.read_byte_data(self.a...
def get_diagnostics(self): """ Reads diagnostic data from the sensor. OCF (Offset Compensation Finished) - logic high indicates the finished Offset Compensation Algorithm. After power up the flag remains always to logic high. COF (Cordic Overflow) - logic high indicates an out of range ...
def get_angle(self, verify = False): """ Retuns measured angle in degrees in range 0-360. """ LSB = self.bus.read_byte_data(self.address, self.angle_LSB) MSB = self.bus.read_byte_data(self.address, self.angle_MSB) DATA = (MSB << 6) + LSB if not verify: ...
def main(input_bed, output_file, output_features=False, genome=None, only_canonical=False, short=False, extended=False, high_confidence=False, ambiguities_method=False, coding_only=False, collapse_exons=False, work_dir=False, is_debug=False): """ Annotating BED file based on reference features ann...
def StateOfCharge(self): """ % of Full Charge """ return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256)
def Chemistry(self): ''' Get cells chemistry ''' length = self.bus.read_byte_data(self.address, 0x79) chem = [] for n in range(length): chem.append(self.bus.read_byte_data(self.address, 0x7A + n)) return chem
def integrate_2d(uSin, angles, res, nm, lD=0, coords=None, count=None, max_count=None, verbose=0): r"""(slow) 2D reconstruction with the Fourier diffraction theorem Two-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u...
def backpropagate_2d(uSin, angles, res, nm, lD=0, coords=None, weight_angles=True, onlyreal=False, padding=True, padval=0, count=None, max_count=None, verbose=0): r"""2D backpropagation with the Fourier diffraction theorem Two-dimensional diffracti...
def color(x, y): """triangles. Colors: - http://paletton.com/#uid=70l150klllletuehUpNoMgTsdcs shade 2 """ if (x-4) > (y-4) and -(y-4) <= (x-4): # right return "#CDB95B" elif (x-4) > (y-4) and -(y-4) > (x-4): # top return "#CD845B" elif (x-4) <= (y-4) and -(y...
def single_read(self, register): ''' Reads data from desired register only once. ''' comm_reg = (0b00010 << 3) + register if register == self.AD7730_STATUS_REG: bytes_num = 1 elif register == self.AD7730_DATA_REG: bytes_num = 3 e...
def getStatus(self): """ RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet STDY - Steady Bit. This bit is updated w...
def setMode(self ,mode ,polarity ,den ,iovalue ,data_length ,reference ,input_range ,clock_enable ,burn_out ,c...
def downsample(work_dir, sample_name, fastq_left_fpath, fastq_right_fpath, downsample_to, num_pairs=None): """ get N random headers from a fastq file without reading the whole thing into memory modified from: http://www.biostars.org/p/6544/ """ sample_name = sample_name or splitext(''.join(lc if lc ...
def get_hum(self, raw = False): """ The physical value RH given above corresponds to the relative humidity above liquid water according to World Meteorological Organization (WMO) """ self.bus.write_byte(self.address, self.TRIG_RH_noHOLD); # start humidity measurement ...
def _calculate_checksum(value): """4.12 Checksum Calculation from an unsigned short input""" # CRC polynomial = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001 crc = 0xFF # calculates 8-Bit checksum with given polynomial for byteCtr in [ord(x) for x in struct.pack(">H", value)...