code
stringlengths
1
18.2k
chemical_name=chemical_name, chemical_definition=chemical_definition) q = self._join_disease(q, disease_definition=disease_definition, disease_id=disease_id, disease_name=disease_name) return self._limit_and_df(q, limit, as_df)
def get_gene_pathways(self, gene_name=None, gene_symbol=None, gene_id=None, pathway_id=None, pathway_name=None, limit=None, as_df=False): """Get gene pathway link :param bool as_df: if set to True result returns as `pandas.DataFrame` :param str gene_name: gene name :param str gene_symbol: gene symbol :param int gene_id...
def get_validate_upload_form_kwargs(self): """ Return the keyword arguments for instantiating the form for validating the upload. """ kwargs = { 'storage': self.get_storage(), 'upload_to': self.get_upload_to(), 'content_type_prefix': self.get_content_type_prefix(), 'process_to': self.get_process_to(), 'processed_key_ge...
def play(state): """ Play sound for a given state. :param state: a State value. """ filename = None if state == SoundService.State.welcome: filename = "pad_glow_welcome1.wav" elif state == SoundService.State.goodbye: filename = "pad_glow_power_off.wav" elif state == SoundService.State.hotword_detected: filename = "pad_...
def get_readme(): """Generate long description""" pandoc = None for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') pandoc = os.path.join(path, 'pandoc') if os.path.isfile(pandoc) and os.access(pandoc, os.X_OK): break else: pandoc = None try: if pandoc: cmd = [pandoc, '-t', 'rst', 'README.md'] long...
def main(): """Main""" lic = ( 'License :: OSI Approved :: GNU Affero ' 'General Public License v3 or later (AGPLv3+)') version = load_source("version", os.path.join("spamc", "version.py")) opts = dict( name="spamc", version=version.__version__, description="Python spamassassin spamc client library", long_description=g...
def _casual_timedelta_string(meeting): """ Return a casual timedelta string. If a meeting starts in 2 hours, 15 minutes, and 32 seconds from now, then return just "in 2 hours". If a meeting starts in 7 minutes and 40 seconds from now, return just "in 7 minutes". If a meeting starts 56 seconds from now, just return "rig...
"right now"
def repo_name(msg): """ Compat util to get the repo name from a message. """ try: # git messages look like this now path = msg['msg']['commit']['path'] project = path.split('.git')[0][9:] except KeyError: # they used to look like this, though project = msg['msg']['commit']['repo'] return project
def usage(self, period=None, start=None, end=None): """ Get account usage information :param period: Period is one of either hourly, daily or monthly :type period: str :param start: Determines time period of the usage :type start: int :param end: Determines time period of the usage :type end: int :return: dict of REST ...
def standard_db_name(file_column_name): """return a standard name by following rules: 1. find all regular expression partners ((IDs)|(ID)|([A-Z][a-z]+)|([A-Z]{2,})) 2. lower very part and join again with _ This method is only used if values in table[model]['columns'] are str :param str file_column_name: name of column ...
def transform_text(input_txt): """Transforms text into :py:class:`~collections.deque`, pre-processes multiline strings. :param str or bytes input_txt: Input text. :return: Double-ended queue of single characters and multiline strings. :rtype: :py:class:`~collections.deque` """ if isinstance(input_txt, str): text = u"{}...
for character in line[1:]: outputq.append(character) else: for character in line: outputq.append(character) outputq.append(u"\n") outputq.extend([u"\n", u""]) # end of file signal return outputq
def bmrblex(text): """A lexical analyzer for the BMRB NMR-STAR format syntax. :param text: Input text. :type text: :py:class:`str` or :py:class:`bytes` :return: Current token. :rtype: :py:class:`str` """ stream = transform_text(text) wordchars = (u"abcdfeghijklmnopqrstuvwxyz" u"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" u"...
# past end of file break elif state == u" ": if not nextchar: state = None break elif nextchar in whitespace: if token: state = u" " break # emit current token else: continue elif nextchar in wordchars: token = nextchar state = u"a" elif nextchar == u"'" or nextchar == u'"': token = nextchar state = nextchar else: toke...
+= nextchar if nextchar == u"\n": state = u" " break # Process regular (unquoted) token elif state == u"a": if not nextchar: state = None break elif nextchar in whitespace: state = u" " if token: break # emit current token else: continue else: token += nextchar if nextnextchar: stream.appendleft(nextnextchar) yield tok...
def check_dependencies(): """Check external dependecies Return a tuple with the available generators. """ available = [] try: shell('ebook-convert') available.append('calibre') except OSError: pass try: shell('pandoc --help') available.append('pandoc') except OSError: pass if not available: sys.exit(error('No generator...
def lock(self, key, owner, timeout=None, expire=None): """Lock given `key` to `owner`. :Parameters: - `key` - lock name - `owner` - name of application/component/whatever which asks for lock - `timeout` (optional) - how long to wait if `key` is locked - `expire` (optional) - when given, lock will be released after that...
def release(self, key, owner): """Release lock with given name. `key` - lock name `owner` - name of application/component/whatever which held a lock Raises `MongoLockException` if no such a lock. """ status = self.collection.find_and_modify( {'_id': key, 'owner': owner}, {'locked': False, 'owner': None, 'created': None...
def touch(self, key, owner, expire=None): """Renew lock to avoid expiration. """ lock = self.collection.find_one({'_id': key, 'owner': owner}) if not lock: raise MongoLockException(u'Can\'t find lock for {key}: {owner}'.format(key=key, owner=owner)) if not lock['expire']: return if not expire: raise MongoLockException(...
def _get_archive_listing(self, archive_name): ''' Return full document for ``{_id:'archive_name'}`` .. note:: MongoDB specific results - do not expose to user ''' res = self.collection.find_one({'_id': archive_name}) if res is None: raise KeyError return res
def _batch_get_archive_listing(self, archive_names): ''' Batched version of :py:meth:`~MongoDBManager._get_archive_listing` Returns a list of full archive listings from an iterable of archive names .. note :: Invalid archive names will simply not be returned, so the response may not be the same length as the supplied `...
def build_response(self, response, path=None, parser=json_decode_wrapper, async=False): """ Builds a List or Dict response object. Wrapper for a response from the DataSift REST API, can be accessed as a list. :param response: HTTP response to wrap :type response: :class:`~datasift.requests.DictResponse` :param parser: ...
isinstance(data, dict): r = DictResponse(response, data) elif isinstance(data, (list, map)): r = ListResponse(response, data) self.outputmapper.outputmap(r) return r else: # empty dict return DictResponse(response, {})
def ratelimits(self): """ :returns: Rate Limit headers :rtype: dict """ # can't use a dict comprehension because we want python2.6 support r = {} keys = filter(lambda x: x.startswith("x-ratelimit-"), self.headers.keys()) for key in keys: r[key.replace("x-ratelimit-", "")] = int(self.headers[key]) return r
def compile_instance_masks(cls): """ Compiles instance masks into a master mask that is usable by the IO expander. Also determines whether or not the pump should be on. Method is generalized to support multiple IO expanders for possible future expansion. """ # Compute required # of IO expanders needed, clear mask varia...
def update(self): """ This method exposes a more simple interface to the IO module Regardless of what the control instance contains, this method will transmit the queued IO commands to the IO expander Usage: plant1Control.update(bus) """ ControlCluster.compile_instance_masks() IO_expander_output( ControlCluster.bus, se...
def form_GPIO_map(self): """ This method creates a dictionary to map plant IDs to GPIO pins are associated in triples. Each ID gets a light, a fan, and a mist nozzle. """ # Compute bank/pins/IOexpander address based on ID if self.ID == 1: self.IOexpander = 0x20 self.bank = 0 self.fan = 2 self.light = 3 self.valve = 4 e...
make sure reserved pins are not requested if (self.bank == 0) and (min(self.fan, self.light, self.valve) < 2): raise InvalidIOMap( "Pins A0 and A1 are reserved for other functions") self.GPIO_dict = [{'ID': self.ID, 'bank': self.bank, 'fan': self.fan, 'valve': self.valve, 'light': self.light}] # Append dictionary to cl...
def manage_pump(self, operation): """ Updates control module knowledge of pump requests. If any sensor module requests water, the pump will turn on. """ if operation == "on": self.controls["pump"] = "on" elif operation == "off": self.controls["pump"] = "off" return True
def control(self, on=[], off=[]): """ This method serves as the primary interaction point to the controls interface. - The 'on' and 'off' arguments can either be a list or a single string. This allows for both individual device control and batch controls. Note: Both the onlist and offlist are optional. If only one item...
return set(arg) & controls # User has requested individual controls. for item in cast_arg(on): self.manage(item, "on") for item in cast_arg(off): self.manage(item, "off") sleep(.01) # Force delay to throttle requests return self.update()
def restore_state(self): """ Method should be called on obj. initialization When called, the method will attempt to restore IO expander and RPi coherence and restore local knowledge across a possible power failure """ current_mask = get_IO_reg(ControlCluster.bus, self.IOexpander, self.bank) if current_mask & (1 << Cont...
def _key(key=''): ''' Returns a Datastore key object, prefixed with the NAMESPACE. ''' if not isinstance(key, datastore.Key): # Switchboard uses ':' to denote one thing (parent-child) and datastore # uses it for another, so replace ':' in the datastore version of the # key. safe_key = key.replace(':', '|') key = datast...
def get_or_create(cls, key, defaults={}): ''' A port of functionality from the Django ORM. Defaults can be passed in if creating a new document is necessary. Keyword args are used to lookup the document. Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean speci...
def update(cls, spec, updates, upsert=False): ''' The spec is used to search for the data to update, updates contains the values to be updated, and upsert specifies whether to do an insert if the original data is not found. ''' if 'key' in spec: previous = cls.get(spec['key']) else: previous = None if previous: # Updat...
def _queryless_all(cls): ''' This is a hack because some datastore implementations don't support querying. Right now the solution is to drop down to the underlying native client and query all, which means that this section is ugly. If it were architected properly, you might be able to do something like inject an implem...
def remove_condition(self, manager, condition_set, field_name, condition, commit=True): """ Removes a condition and updates the global ``operator`` switch manager. If ``commit`` is ``False``, the data will not be written to the database. >>> switch = operator['my_switch'] #doctest: +SKIP >>> cs_id = condition_set.get_i...
def get_active_conditions(self, manager): ''' Returns a generator which yields groups of lists of conditions. >>> conditions = switch.get_active_conditions() >>> for label, set_id, field, value, exc in conditions: #doctest: +SKIP >>> print ("%(label)s: %(field)s = %(value)s (exclude: %(exc)s)" >>> % (label, field.label...
def main(): """Main loop.""" parser = optparse.OptionParser() parser.add_option( '-s', '--server', help='Index Server Name', metavar='SERVER') parser.add_option( '-r', '--repository', help='Repository URL', metavar='URL') parser.add_option( '-u', '--username', help='User Name', metavar='USERNAME') parser.add_option( '-...
def validate(self, output_type, output_params): """ Check that a subscription is defined correctly. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushvalidate :param output_type: One of DataSift's supported output types, e.g. s3 :type output_type: str :param output_params: The set of parame...
def create_from_hash(self, stream, name, output_type, output_params, initial_status=None, start=None, end=None): """ Create a new push subscription using a live stream. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param stream: The hash of a DataSift stream. :type stream: str :...
self._create(True, stream, name, output_type, output_params, initial_status, start, end)
def create_from_historics(self, historics_id, name, output_type, output_params, initial_status=None, start=None, end=None): """ Create a new push subscription using the given Historic ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param historics_id: The ID of a Historics que...
""" return self._create(False, historics_id, name, output_type, output_params, initial_status, start, end)
def pause(self, subscription_id): """ Pause a Subscription and buffer the data for up to one hour. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushpause :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :returns: dict with extra response data :rtype: ...
def resume(self, subscription_id): """ Resume a previously paused Subscription. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushresume :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :returns: dict with extra response data :rtype: :class:`~datasift....
def update(self, subscription_id, output_params, name=None): """ Update the name or output parameters for an existing Subscription. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushupdate :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :param output_...
def stop(self, subscription_id): """ Stop the given subscription from running. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushstop :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :returns: dict with extra response data :rtype: :class:`~datasift.req...
def delete(self, subscription_id): """ Delete the subscription for the given ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushdelete :param subscription_id: id of an existing Push Subscription. :type subscription_id: str :returns: dict with extra response data :rtype: :class:`~datasift...
def log(self, subscription_id=None, page=None, per_page=None, order_by=None, order_dir=None): """ Retrieve any messages that have been logged for your subscriptions. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushlog :param subscription_id: optional id of an existing Push Subscription, r...
params['order_dir'] = order_dir return self.request.get('log', params=params)
def get(self, subscription_id=None, stream=None, historics_id=None, page=None, per_page=None, order_by=None, order_dir=None, include_finished=None): """ Show details of the Subscriptions belonging to this user. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushget :param subscription_id: op...
data :rtype: :class:`~datasift.request.DictResponse` :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` """ params = {} if subscription_id: params['id'] = subscription_id if stream: params['hash'] = stream if historics_id: params['historics_id'] = historics_id if page: p...
def _get_project(msg, key='project'): ''' Return the project as `foo` or `user/foo` if the project is a fork. ''' project = msg[key]['name'] ns = msg[key].get('namespace') if ns: project = '/'.join([ns, project]) if msg[key]['parent']: user = msg[key]['user']['name'] project = '/'.join(['fork', user, project]) return p...
def _git_receive_v1(msg, tmpl, **config): ''' Return the subtitle for the first version of pagure git.receive messages. ''' repo = _get_project(msg['msg']['commit'], key='repo') email = msg['msg']['commit']['email'] user = email2fas(email, **config) summ = msg['msg']['commit']['summary'] whole = msg['msg']['commit']['m...
def _git_receive_v2(msg, tmpl): ''' Return the subtitle for the second version of pagure git.receive messages. ''' repo = _get_project(msg['msg'], key='repo') user = msg['msg']['agent'] n_commits = msg['msg']['total_commits'] commit_lbl = 'commit' if str(n_commits) == '1' else 'commits' branch = msg['msg']['branch'] if...
def update(self, archive_name, version_metadata): ''' Register a new version for archive ``archive_name`` .. note :: need to implement hash checking to prevent duplicate writes ''' version_metadata['updated'] = self.create_timestamp() version_metadata['version'] = str( version_metadata.get('version', None)) if version_...
def update_metadata(self, archive_name, archive_metadata): ''' Update metadata for archive ``archive_name`` ''' required_metadata_keys = self.required_archive_metadata.keys() for key, val in archive_metadata.items(): if key in required_metadata_keys and val is None: raise ValueError( 'Cannot remove required metadata at...
def create_archive( self, archive_name, authority_name, archive_path, versioned, raise_on_err=True, metadata=None, user_config=None, tags=None, helper=False): ''' Create a new data archive Returns ------- archive : object new :py:class:`~datafs.core.data_archive.DataArchive` object ''' archive_metadata = self._create_a...
def get_archive(self, archive_name): ''' Get a data archive given an archive name Returns ------- archive_specification : dict archive_name: name of the archive to be retrieved authority: name of the archive's authority archive_path: service path of archive ''' try: spec = self._get_archive_spec(archive_name) return sp...
def add_tags(self, archive_name, tags): ''' Add tags to an archive Parameters ---------- archive_name:s tr Name of archive tags: list or tuple of strings tags to add to the archive ''' updated_tag_list = list(self._get_tags(archive_name)) for tag in tags: if tag not in updated_tag_list: updated_tag_list.append(tag) sel...
def delete_tags(self, archive_name, tags): ''' Delete tags from an archive Parameters ---------- archive_name:s tr Name of archive tags: list or tuple of strings tags to delete from the archive ''' updated_tag_list = list(self._get_tags(archive_name)) for tag in tags: if tag in updated_tag_list: updated_tag_list.remove...
def _normalize_tags(self, tags): ''' Coerces tags to lowercase strings Parameters ---------- tags: list or tuple of strings ''' lowered_str_tags = [] for tag in tags: lowered_str_tags.append(str(tag).lower()) return lowered_str_tags
def start(self): "Start the project on the directory" bookname = self.args.get('--bookname', None) if not bookname: bookname = 'book.md' project_dir = self.args.get('<name>', None) if not project_dir: project_dir = join(self.cwd, 'Book') project_dir = abspath(project_dir) # create the working dir? if not exists(project...
fd: data = { 'files': ['%s' % bookname], 'author': "%s" % ask("What is your name? "), 'title': '%s' % ask("E-book title, please? "), } data['fileroot'] = unidecode(data['title']).lower() \ .replace(' ', '-') # pick a generator if len(self.generators) == 1: data['generator'] = self.generators[0] else: picked_generator =...
def build(self): "Build your book" config = self.load_config() html_generator = HTMLGenerator(self.cwd, config) html_generator.build() if self.args.get('--generator', None): generator = self.args.get('--generator') else: generator = config.get('generator') if generator == 'calibre': EPUBClass = CalibreEPUBGenerator PDF...
def check(self): "Checks EPUB integrity" config = self.load_config() if not check_dependency_epubcheck(): sys.exit(error('Unavailable command.')) epub_file = u"%s.epub" % config['fileroot'] epub_path = join(CWD, 'build', epub_file) print success("Starting to check %s..." % epub_file) epubcheck = u'epubcheck %s' % epub_...
def create(self, sql=None): """CREATE this DATABASE. @param sql: (Optional) A string of psql (such as might be generated by pg_dump); it will be executed by psql(1) after creating the database. @type sql: str @rtype: None """ create_sql = 'CREATE DATABASE {self.db_name} WITH OWNER {self.user}' create_sql = create_sql.f...
def psql_string(self, sql): """ Evaluate the sql file (possibly multiple statements) using psql. """ argv = [ PostgresFinder.find_root() / 'psql', '--quiet', '-U', self.user, '-h', self.host, '-p', self.port, '-f', '-', self.db_name, ] popen = subprocess.Popen(argv, stdin=subprocess.PIPE) popen.communicate(input=sql.en...
def psql(self, args): r"""Invoke psql, passing the given command-line arguments. Typical <args> values: ['-c', <sql_string>] or ['-f', <pathname>]. Connection parameters are taken from self. STDIN, STDOUT, and STDERR are inherited from the parent. WARNING: This method uses the psql(1) program, which ignores SQL errors ...
def sql(self, input_string, *args): """Execute a SQL command using the Python DBI directly. Connection parameters are taken from self. Autocommit is in effect. Example: .sql('SELECT %s FROM %s WHERE age > %s', 'name', 'table1', '45') @param input_string: A string of SQL. May contain %s or %(name)s format specifiers; th...
try: # sqlalchemy 0.6.7 offers a result.returns_rows attribute, but # no prior version offers anything comparable. A tacky # workaround... try: return result.fetchall() except psycopg2.ProgrammingError: return None finally: result.close() connection.close() """ psycopg2 = importlib.import_module('psycopg2') importlib.i...
def super_psql(self, args): """Just like .psql(), except that we connect as the database superuser (and we connect to the superuser's database, not the user's database). """ argv = [ PostgresFinder.find_root() / 'psql', '--quiet', '-U', self.superuser, '-h', self.host, '-p', self.port, ] + args subprocess.check_call(ar...
def destroy(self): """Undo the effects of initdb. Destroy all evidence of this DBMS, including its backing files. """ self.stop() if self.base_pathname is not None: self._robust_remove(self.base_pathname)
def _robust_remove(path): """ Remove the directory specified by `path`. Because we can't determine directly if the path is in use, and on Windows, it's not possible to remove a path if it is in use, retry a few times until the call succeeds. """ tries = itertools.count() max_tries = 50 while os.path.isdir(path): try: s...
def initdb(self, quiet=True, locale='en_US.UTF-8'): """Bootstrap this DBMS from nothing. If you're running in an environment where the DBMS is provided as part of the basic infrastructure, you probably don't want to call this method! @param quiet: Should we operate quietly, emitting nothing if things go well? """ # Def...
PostgreSQL with command: {}'.format( ' '.join(cmd) )) subprocess.check_call(cmd, stdout=stdout)
def _is_running(self, tries=10): """ Return if the server is running according to pg_ctl. """ # We can't possibly be running if our base_pathname isn't defined. if not self.base_pathname: return False if tries < 1: raise ValueError('tries must be > 0') cmd = [ PostgresFinder.find_root() / 'pg_ctl', 'status', '-D', self...
def ready(self): """ Assumes postgres now talks to pg_ctl, but might not yet be listening or connections from psql. Test that psql is able to connect, as it occasionally takes 5-10 seconds for postgresql to start listening. """ cmd = self._psql_cmd() for i in range(50, -1, -1): res = subprocess.call( cmd, stdin=DEV_NUL...
def pid(self): """The server's PID (None if not running). """ # We can't possibly be running if our base_pathname isn't defined. if not self.base_pathname: return None try: pidfile = os.path.join(self.base_pathname, 'postmaster.pid') return int(open(pidfile).readline()) except (IOError, OSError): return None
def get_version(): """Returns the Postgres version in tuple form, e.g: (9, 1)""" cmd = [PostgresFinder.find_root() / 'pg_ctl', '--version'] results = subprocess.check_output(cmd).decode('utf-8') match = re.search(r'(\d+\.\d+(\.\d+)?)', results) if match: ver_string = match.group(0) return tuple(int(x) for x in ver_stri...
def start(self): """Launch this postgres server. If it's already running, do nothing. If the backing storage directory isn't configured, raise NotInitializedError. This method is optional. If you're running in an environment where the DBMS is provided as part of the basic infrastructure, you probably want to skip this ...
postgres might try to put files # where they're not writable (see # https://paste.yougov.net/YKdgi). So set the socket_dir. '-c', '{}={}'.format(socketop, self.base_pathname), '-h', self.host, '-i', # enable TCP/IP connections '-p', self.port, ] subprocess.check_call([ PostgresFinder.find_root() / 'pg_ctl', 'start', '-...
def stop(self): """Stop this DMBS daemon. If it's not currently running, do nothing. Don't return until it's terminated. """ log.info('Stopping PostgreSQL at %s:%s', self.host, self.port) if self._is_running(): cmd = [ PostgresFinder.find_root() / 'pg_ctl', 'stop', '-D', self.base_pathname, '-m', 'fast', ] subprocess.c...
def create(self, db_name, **kwargs): """ Construct a PostgresDatabase and create it on self """ db = PostgresDatabase( db_name, host=self.host, port=self.port, superuser=self.superuser, **kwargs) db.ensure_user() db.create() return db
def _search(self, search_terms, begins_with=None): """ Returns a list of Archive id's in the table on Dynamo """ kwargs = dict( ProjectionExpression='#id', ExpressionAttributeNames={"#id": "_id"}) if len(search_terms) > 0: kwargs['FilterExpression'] = reduce( lambda x, y: x & y, [Attr('tags').contains(arg) for arg in s...
def _update(self, archive_name, version_metadata): ''' Updates the version specific metadata attribute in DynamoDB In DynamoDB this is simply a list append on this attribute value Parameters ---------- archive_name: str unique '_id' primary key version_metadata: dict dictionary of version metadata values Returns ------...
def _create_archive_table(self, table_name): ''' Dynamo implementation of BaseDataManager create_archive_table waiter object is implemented to ensure table creation before moving on this will slow down table creation. However, since we are only creating table once this should no impact users. Parameters ---------- tabl...
def _create_spec_config(self, table_name, spec_documents): ''' Dynamo implementation of spec config creation Called by `create_archive_table()` in :py:class:`manager.BaseDataManager` Simply adds two rows to the spec table Parameters ---------- table_name : base table name (not including .spec suffix) spec_documents : l...
def _update_spec_config(self, document_name, spec): ''' Dynamo implementation of project specific metadata spec ''' # add the updated archive_metadata object to Dynamo self._spec_table.update_item( Key={'_id': '{}'.format(document_name)}, UpdateExpression="SET config = :v", ExpressionAttributeValues={':v': spec}, Retur...
def _update_metadata(self, archive_name, archive_metadata): """ Appends the updated_metada dict to the Metadata Attribute list Parameters ---------- archive_name: str ID of archive to update updated_metadata: dict dictionary of metadata keys and values to update. If the value for a particular key is `None`, the key is ...
def _create_archive( self, archive_name, metadata): ''' This adds an item in a DynamoDB table corresponding to a S3 object Args ---- arhive_name: str corresponds to the name of the Archive (e.g. ) Returns ------- Dictionary with confirmation of upload ''' archive_exists = False try: self.get_archive(archive_name) archi...
def _batch_get_archive_listing(self, archive_names): ''' Batched version of :py:meth:`~DynamoDBManager._get_archive_listing` Returns a list of full archive listings from an iterable of archive names .. note :: Invalid archive names will simply not be returned, so the response may not be the same length as the supplied ...
+= 1 return archives
def load_backend(backend_name): """ load pool backend.""" try: if len(backend_name.split(".")) > 1: mod = import_module(backend_name) else: mod = import_module("spamc.backend_%s" % backend_name) return mod except ImportError: error_msg = "%s isn't a spamc backend" % backend_name raise ImportError(error_msg)
def Voevent(stream, stream_id, role): """Create a new VOEvent element tree, with specified IVORN and role. Args: stream (str): used to construct the IVORN like so:: ivorn = 'ivo://' + stream + '#' + stream_id (N.B. ``stream_id`` is converted to string if required.) So, e.g. we might set:: stream='voevent.soton.ac.uk/su...
= ( 'VOEvent created with voevent-parse, version {}. ' 'See https://github.com/timstaley/voevent-parse for details.').format( __version__ ) return v
def loads(s, check_version=True): """ Load VOEvent from bytes. This parses a VOEvent XML packet string, taking care of some subtleties. For Python 3 users, ``s`` should be a bytes object - see also http://lxml.de/FAQ.html, "Why can't lxml parse my XML from unicode strings?" (Python 2 users can stick with old-school ``s...
note:: # # The namespace is removed from the root element tag to make # objectify access work as expected, # (see :py:func:`._remove_root_tag_prefix`) # so we must re-insert it when we want to conform to schema. v = objectify.fromstring(s) _remove_root_tag_prefix(v) if check_version: version = v.attrib['version'] if no...