code stringlengths 1 18.2k |
|---|
def load(file, check_version=True): """Load VOEvent from file object. A simple wrapper to read a file before passing the contents to :py:func:`.loads`. Use with an open file object, e.g.:: with open('/path/to/voevent.xml', 'rb') as f: v = vp.load(f) Args: file (io.IOBase): An open file object (binary mode preferred), s... |
def dumps(voevent, pretty_print=False, xml_declaration=True, encoding='UTF-8'): """Converts voevent to string. .. note:: Default encoding is UTF-8, in line with VOE2.0 schema. Declaring the encoding can cause diffs with the original loaded VOEvent, but I think it's probably the right thing to do (and lxml doesn't reall... |
def dump(voevent, file, pretty_print=True, xml_declaration=True): """Writes the voevent to the file object. e.g.:: with open('/tmp/myvoevent.xml','wb') as f: voeventparse.dump(v, f) Args: voevent(:class:`Voevent`): Root node of the VOevent etree. file (io.IOBase): An open (binary mode) file object for writing. pretty_p... |
def valid_as_v2_0(voevent): """Tests if a voevent conforms to the schema. Args: voevent(:class:`Voevent`): Root node of a VOEvent etree. Returns: bool: Whether VOEvent is valid """ _return_to_standard_xml(voevent) valid_bool = voevent_v2_0_schema.validate(voevent) _remove_root_tag_prefix(voevent) return valid_bool |
def set_who(voevent, date=None, author_ivorn=None): """Sets the minimal 'Who' attributes: date of authoring, AuthorIVORN. Args: voevent(:class:`Voevent`): Root node of a VOEvent etree. date(datetime.datetime): Date of authoring. NB Microseconds are ignored, as per the VOEvent spec. author_ivorn(str): Short author ident... |
def set_author(voevent, title=None, shortName=None, logoURL=None, contactName=None, contactEmail=None, contactPhone=None, contributor=None): """For setting fields in the detailed author description. This can optionally be neglected if a well defined AuthorIVORN is supplied. .. note:: Unusually for this library, the arg... |
def add_where_when(voevent, coords, obs_time, observatory_location, allow_tz_naive_datetime=False): """ Add details of an observation to the WhereWhen section. We Args: voevent(:class:`Voevent`): Root node of a VOEvent etree. coords(:class:`.Position2D`): Sky co-ordinates of event. obs_time(datetime.datetime): Nominal ... |
as appropriate", ) else: utc_naive_obs_time = obs_time obs_data = etree.SubElement(voevent.WhereWhen, 'ObsDataLocation') etree.SubElement(obs_data, 'ObservatoryLocation', id=observatory_location) ol = etree.SubElement(obs_data, 'ObservationLocation') etree.SubElement(ol, 'AstroCoordSystem', id=coords.system) ac = etree... |
def add_how(voevent, descriptions=None, references=None): """Add descriptions or references to the How section. Args: voevent(:class:`Voevent`): Root node of a VOEvent etree. descriptions(str): Description string, or list of description strings. references(:py:class:`voeventparse.misc.Reference`): A reference element (... |
def add_why(voevent, importance=None, expires=None, inferences=None): """Add Inferences, or set importance / expires attributes of the Why section. .. note:: ``importance`` / ``expires`` are 'Why' attributes, therefore setting them will overwrite previous values. ``inferences``, on the other hand, are appended to the l... |
def add_citations(voevent, event_ivorns): """Add citations to other voevents. The schema mandates that the 'Citations' section must either be entirely absent, or non-empty - hence we require this wrapper function for its creation prior to listing the first citation. Args: voevent(:class:`Voevent`): Root node of a VOEve... |
def _remove_root_tag_prefix(v): """ Removes 'voe' namespace prefix from root tag. When we load in a VOEvent, the root element has a tag prefixed by the VOE namespace, e.g. {http://www.ivoa.net/xml/VOEvent/v2.0}VOEvent Because objectify expects child elements to have the same namespace as their parent, this breaks the p... |
# LXML syntax is a minefield! v['{}original_prefix'][0] = v.prefix v.tag = v.tag.replace(''.join(('{', v.nsmap[v.prefix], '}')), '') # Now v.tag = '{}VOEvent', v.prefix = None return |
def _reinsert_root_tag_prefix(v): """ Returns namespace prefix to root tag, if it had one. """ if hasattr(v, 'original_prefix'): original_prefix = v.original_prefix del v.original_prefix v.tag = ''.join(('{', v.nsmap[original_prefix], '}VOEvent')) return |
def _listify(x): """Ensure x is iterable; if not then enclose it in a list and return it.""" if isinstance(x, string_types): return [x] elif isinstance(x, collections.Iterable): return x else: return [x] |
def list(self, label=None, per_page=20, page=1): """ Get a list of identities that have been created :param per_page: The number of results per page returned :type per_page: int :param page: The page number of the results :type page: int :return: dict of REST API output with headers attached :rtype: :class:`~datasift.r... |
def create(self, label, status=None, master=None): """ Create an Identity :param label: The label to give this new identity :param status: The status of this identity. Default: 'active' :param master: Represents whether this identity is a master. Default: False :return: dict of REST API output with headers attached :rt... |
def update(self, id, label=None, status=None, master=None): """ Update an Identity :param label: The label to give this new identity :param status: The status of this identity. Default: 'active' :param master: Represents whether this identity is a master. Default: False :return: dict of REST API output with headers att... |
def get(self, id, service='facebook', type='analysis'): """ Get a given Pylon task :param id: The ID of the task :type id: str :param service: The PYLON service (facebook) :type service: str :return: dict of REST API output with headers attached :rtype: :class:`~datasift.request.DictResponse` :raises: :class:`~datasift... |
def list(self, per_page=None, page=None, status=None, service='facebook'): """ Get a list of Pylon tasks :param per_page: How many tasks to display per page :type per_page: int :param page: Which page of tasks to display :type page: int :param status: The status of the tasks to list :type page: string :param service: T... |
def create(self, subscription_id, name, parameters, type='analysis', service='facebook'): """ Create a PYLON task :param subscription_id: The ID of the recording to create the task for :type subscription_id: str :param name: The name of the new task :type name: str :param parameters: The parameters for this task :type ... |
def value_from_datadict(self, data, files, name): """Returns uploaded file from serialized value.""" upload = super(StickyUploadWidget, self).value_from_datadict(data, files, name) if upload is not None: # File was posted or cleared as normal return upload else: # Try the hidden input hidden_name = self.get_hidden_name... |
def render(self, name, value, attrs=None, renderer=None): """Include a hidden input to store the serialized upload value.""" location = getattr(value, '_seralized_location', '') if location and not hasattr(value, 'url'): value.url = '#' if hasattr(self, 'get_template_substitution_values'): # Django 1.8-1.10 self.templa... |
def configure(config={}, datastore=None, nested=False): """ Useful for when you need to control Switchboard's setup """ if nested: config = nested_config(config) # Re-read settings to make sure we have everything. # XXX It would be really nice if we didn't need to do this. Settings.init(**config) if datastore: Switch.d... |
def with_result_cache(func): """ Decorator specifically for is_active. If self.result_cache is set to a {} the is_active results will be cached for each set of params. """ def inner(self, *args, **kwargs): dic = self.result_cache cache_key = None if dic is not None: cache_key = (args, tuple(kwargs.items())) try: result... |
def is_active(self, key, *instances, **kwargs): """ Returns ``True`` if any of ``instances`` match an active switch. Otherwise returns ``False``. >>> operator.is_active('my_feature', request) #doctest: +SKIP """ try: default = kwargs.pop('default', False) # Check all parents for a disabled state parts = key.split(':') ... |
instances.extend(self.context.values()) # check each switch to see if it can execute return_value = False for namespace, condition in conditions.iteritems(): condition_set = registry_by_namespace.get(namespace) if not condition_set: continue result = condition_set.has_active_condition(condition, instances) if result is... |
def register(self, condition_set): """ Registers a condition set with the manager. >>> condition_set = MyConditionSet() #doctest: +SKIP >>> operator.register(condition_set) #doctest: +SKIP """ if callable(condition_set): condition_set = condition_set() registry[condition_set.get_id()] = condition_set registry_by_namesp... |
def unregister(self, condition_set): """ Unregisters a condition set with the manager. >>> operator.unregister(condition_set) #doctest: +SKIP """ if callable(condition_set): condition_set = condition_set() registry.pop(condition_set.get_id(), None) registry_by_namespace.pop(condition_set.get_namespace(), None) |
def get_dupe_prob(self, url): """ A probability of given url being a duplicate of some content that has already been seem. """ path, query = _parse_url(url) dupestats = [] extend_ds = lambda x: dupestats.extend(filter(None, ( ds_dict.get(key) for ds_dict, key in x))) if self.urls_by_path.get(path): extend_ds([(self.pat... |
this could be a long list of param values, # it's better to somehow store only high-probability values? for value in self.param_values.get((path, param), set()): extend_ds(self._param_value_dupstats(path, param, value)) return max(ds.get_prob() for ds in dupestats) if dupestats else 0. |
def update_model(self, url, text): """ Update prediction model with a page by given url and text content. Return a list of item duplicates (for testing purposes). """ min_hash = get_min_hash(text, self.too_common_shingles, self.num_perm) item_url = canonicalize_url(url) item_path, item_query = _parse_url(item_url) all_... |
set())) # Update indexes for param, value in item_query.items(): self.urls_by_path_q[item_path, _q_key(item_query)].add(item_url) item_qwp_key = _q_key(_without_key(item_query, param)) self.urls_by_path_qwp[item_path, param, item_qwp_key].add(item_url) self.params_by_path[item_path].add(param) self.param_values[item_pa... |
def _nodup_filter(self, min_hash, all_urls, max_sample=200): """ This filters results that are considered not duplicates. But we really need to check that, because lsh.query does not always return ALL duplicates, esp. when there are a lot of them, so here we double-check and return only urls that are NOT duplicates. Re... |
def get_queryset(self, request): """ Remove ``show_rendered`` from the context, if it's there. """ qs = super(UnrenderedAdmin, self).get_queryset(request) if 'show_rendered' in qs.query.context: del qs.query.context['show_rendered'] return qs |
def get_one(self, cls=None, **kwargs): """Returns a one case.""" case = cls() if cls else self._CasesClass() for attr, value in kwargs.iteritems(): setattr(case, attr, value) return case |
def get_each_choice(self, cls=None, **kwargs): """Returns a generator that generates positive cases by "each choice" algorithm. """ defaults = {attr: kwargs[attr][0] for attr in kwargs} for set_of_values in izip_longest(*kwargs.values()): case = cls() if cls else self._CasesClass() for attr, value in izip(kwargs.keys()... |
def get_pairwise(self, cls=None, **kwargs): """Returns a generator that generates positive cases by "pairwise" algorithm. """ for set_of_values in allpairs(kwargs.values()): case = cls() if cls else self._CasesClass() for attr, value in izip(kwargs.keys(), set_of_values): setattr(case, attr, value) yield case |
def get_negative(self, cls=None, **kwargs): """Returns a generator that generates negative cases by "each negative value in separate case" algorithm. """ for attr, set_of_values in kwargs.iteritems(): defaults = {key: kwargs[key][-1]["default"] for key in kwargs} defaults.pop(attr) for value in set_of_values[:-1]: case... |
def get_mix_gen(self, sample): """Returns function that returns sequence of characters of a given length from a given sample """ def mix(length): result = "".join(random.choice(sample) for _ in xrange(length)).strip() if len(result) == length: return result return mix(length) return mix |
def update(connection=None, urls=None, force_download=False): """Updates CTD database :param iter[str] urls: list of urls to download :param str connection: custom database connection string :param bool force_download: force method to download """ db = DbManager(connection) db.db_import(urls=urls, force_download=force_... |
def set_mysql_connection(host='localhost', user='pyctd_user', password='pyctd_passwd', db='pyctd', charset='utf8'): """Sets the connection using MySQL Parameters""" set_connection('mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}'.format( host=host, user=user, passwd=password, db=db, charset=charset) ) |
def set_connection(connection=defaults.sqlalchemy_connection_string_default): """Set the connection string for SQLAlchemy :param str connection: SQLAlchemy connection string """ cfp = defaults.config_file_path config = RawConfigParser() if not os.path.exists(cfp): with open(cfp, 'w') as config_file: config['database'] ... |
def set_connection_string_by_user_input(self): """Prompts the user to input a connection string""" user_connection = input( bcolors.WARNING + "\nFor any reason connection to " + bcolors.ENDC + bcolors.FAIL + "{}".format(self.connection) + bcolors.ENDC + bcolors.WARNING + " is not possible.\n\n" + bcolors.ENDC + "For mo... |
connection {}:\n".format(defaults.sqlalchemy_connection_string_default) ) if not (user_connection or user_connection.strip()): user_connection = defaults.sqlalchemy_connection_string_default set_connection(user_connection.strip()) |
def create_all(self, checkfirst=True): """Creates all tables from models in the database :param bool checkfirst: Check if tables already exists """ log.info('creating tables in %s', self.engine.url) models.Base.metadata.create_all(self.engine, checkfirst=checkfirst) |
def drop_all(self): """Drops all tables in the database""" log.info('dropping tables in %s', self.engine.url) self.session.commit() models.Base.metadata.drop_all(self.engine) self.session.commit() |
def db_import(self, urls=None, force_download=False): """Updates the CTD database 1. downloads all files from CTD 2. drops all tables in database 3. creates all tables in database 4. import all data from CTD files :param iter[str] urls: An iterable of URL strings :param bool force_download: force method to download """... |
def mapper(self): """returns a dictionary with keys of pyctd.manager.table_con.domains_to_map and pandas.DataFrame as values. DataFrames column names: - domain_id (represents the domain identifier of e.g. chemical) - domain__id (represents the primary key in domain table) :return: dict of pandas DataFrames (keys:domain... |
def import_tables(self, only_tables=None, exclude_tables=None): """Imports all data in database tables :param set[str] only_tables: names of tables to be imported :param set[str] exclude_tables: names of tables to be excluded """ for table in self.tables: if only_tables is not None and table.name not in only_tables: co... |
def get_index_of_column(cls, column, file_path): """Get index of a specific column name in a CTD file :param column: :param file_path: :return: Optional[int] """ columns = cls.get_column_names_from_file(file_path) if column in columns: return columns.index(column) |
def get_index_and_columns_order(cls, columns_in_file_expected, columns_dict, file_path): """ :param columns_in_file_expected: :param columns_dict: :param file_path: :rtype: tuple[list,list] """ use_columns_with_index = [] column_names_in_db = [] column_names_from_file = cls.get_column_names_from_file(file_path) if not ... |
def import_table(self, table): """import table by Table object :param `manager.table_conf.Table` table: Table object """ file_path = os.path.join(self.pyctd_data_dir, table.file_name) log.info('importing %s data into table %s', file_path, table.name) table_import_timer = time.time() use_columns_with_index, column_names... |
def import_one_to_many(self, file_path, column_index, parent_table, column_in_one2many_table): """ :param file_path: :param column_index: :param parent_table: :param column_in_one2many_table: """ chunks = pd.read_table( file_path, usecols=[column_index], header=None, comment='#', index_col=False, chunksize=1000000, dty... |
def import_table_in_db(self, file_path, use_columns_with_index, column_names_in_db, table): """Imports data from CTD file into database :param str file_path: path to file :param list[int] use_columns_with_index: list of column indices in file :param list[str] column_names_in_db: list of column names (have to fit to mod... |
= defaults.TABLE_PREFIX + table.name chunk.to_sql(name=table_with_prefix, if_exists='append', con=self.engine) del chunks |
def get_column_names_from_file(file_path): """returns column names from CTD download file :param str file_path: path to CTD download file """ if file_path.endswith('.gz'): file_handler = io.TextIOWrapper(io.BufferedReader(gzip.open(file_path))) else: file_handler = open(file_path, 'r') fields_line = False with file_han... |
def download_urls(cls, urls, force_download=False): """Downloads all CTD URLs that don't exist :param iter[str] urls: iterable of URL of CTD :param bool force_download: force method to download """ for url in urls: file_path = cls.get_path_to_file_from_url(url) if os.path.exists(file_path) and not force_download: log.i... |
def comma_join(fields, oxford=True): """ Join together words. """ def fmt(field): return "'%s'" % field if not fields: return "nothing" elif len(fields) == 1: return fmt(fields[0]) elif len(fields) == 2: return " and ".join([fmt(f) for f in fields]) else: result = ", ".join([fmt(f) for f in fields[:-1]]) if oxford: res... |
def avatar_url_from_openid(openid, size=64, default='retro', dns=False): """ Our own implementation since fas doesn't support this nicely yet. """ if dns: # This makes an extra DNS SRV query, which can slow down our webapps. # It is necessary for libravatar federation, though. import libravatar return libravatar.librav... |
def avatar_url_from_email(email, size=64, default='retro', dns=False): """ Our own implementation since fas doesn't support this nicely yet. """ if dns: # This makes an extra DNS SRV query, which can slow down our webapps. # It is necessary for libravatar federation, though. import libravatar return libravatar.libravat... |
def run(self, target, args=()): """ Run a function in a separate thread. :param target: the function to run. :param args: the parameters to pass to the function. """ run_event = threading.Event() run_event.set() thread = threading.Thread(target=target, args=args + (run_event, )) self.thread_pool.append(thread) self.run... |
def stop(self): """ Stop all functions running in the thread handler.""" for run_event in self.run_events: run_event.clear() for thread in self.thread_pool: thread.join() |
def generate(self, labels, split_idx): """Generate peak-specific noise abstract method, must be reimplemented in a subclass. :param tuple labels: Dimension labels of a peak. :param int split_idx: Index specifying which peak list split parameters to use. :return: List of noise values for dimensions ordered as they appea... |
def load_cover(self): """Load the cover out of the config, options and conventions. Priority goes this way: 1. if a --cover option is set, use it. 2. if there's a "cover" key in the config file, use it. 3. if a cover.(png|jpg|jpeg|svg) exists in the directory, use it. Once the choice is set, the program will check if t... |
print error('The designated cover (%s) does not exists.' ' Please check your settings.' % filename) filename = None if not filename: print warning('No cover is set, will use the default (ugly) one.') return False return abspath(filename) |
def parse_python(classifiers): """Parse out the versions of python supported a/c classifiers.""" prefix = 'Programming Language :: Python ::' python_classifiers = [c.split('::')[2].strip() for c in classifiers if c.startswith(prefix)] return ', '.join([c for c in python_classifiers if parse_version(c)]) |
def parse_django(classifiers): """Parse out the versions of django supported a/c classifiers.""" prefix = 'Framework :: Django ::' django_classifiers = [c.split('::')[2].strip() for c in classifiers if c.startswith(prefix)] return ', '.join([c for c in django_classifiers if parse_version(c)]) |
def version_diff(version1, version2): """Return string representing the diff between package versions. We're interested in whether this is a major, minor, patch or 'other' update. This method will compare the two versions and return None if they are the same, else it will return a string value indicating the type of di... |
def data(self): """Fetch latest data from PyPI, and cache for 30s.""" key = cache_key(self.name) data = cache.get(key) if data is None: logger.debug("Updating package info for %s from PyPI.", self.name) data = requests.get(self.url).json() cache.set(key, data, PYPI_CACHE_EXPIRY) return data |
def _query_wrap(fun, *args, **kwargs): """Wait until at least QUERY_WAIT_TIME seconds have passed since the last invocation of this function, then call the given function with the given arguments. """ with _query_lock: global _last_query_time since_last_query = time.time() - _last_query_time if since_last_query < QUERY... |
def formdata_encode(fields): """Encode fields (a dict) as a multipart/form-data HTTP request payload. Returns a (content type, request body) pair. """ BOUNDARY = '----form-data-boundary-ZmRkNzJkMjUtMjkyMC00' out = [] for (key, value) in fields.items(): out.append('--' + BOUNDARY) out.append('Content-Disposition: form-d... |
def formdata_post(url, fields): """Send an HTTP request with a multipart/form-data body for the given URL and return the data returned by the server. """ content_type, data = formdata_encode(fields) req = urllib2.Request(url, data) req.add_header('Content-Type', content_type) return urllib2.urlopen(req).read() |
def fpid_query(duration, fpdata, metadata=None): """Send fingerprint data to Last.fm to get the corresponding fingerprint ID, which can then be used to fetch metadata. duration is the length of the track in (integral) seconds. If metadata is provided, it is a dictionary with three optional fields reflecting the current... |
failed') try: fpid, status = res.split()[:2] fpid = int(fpid) except ValueError: raise BadResponseError('malformed response: ' + res) if status == 'NEW': raise NotFoundError() elif status == 'FOUND': return fpid else: raise BadResponseError('unknown status: ' + res) |
def metadata_query(fpid, apikey): """Queries the Last.fm servers for metadata about a given fingerprint ID (an integer). Returns the XML response (a string). """ params = { 'method': 'track.getFingerprintMetadata', 'fingerprintid': fpid, 'api_key': apikey, } url = '%s?%s' % (URL_METADATA, urllib.urlencode(params)) try:... |
def extract(pcmiter, samplerate, channels, duration = -1): """Given a PCM data stream, extract fingerprint data from the audio. Returns a byte string of fingerprint data. Raises an ExtractionError if fingerprinting fails. """ extractor = _fplib.Extractor(samplerate, channels, duration) # Get first block. try: next_bloc... |
out is None: raise ExtractionError() # Free extractor memory. extractor.free() return out |
def match(apikey, pcmiter, samplerate, duration, channels=2, metadata=None): """Given a PCM data stream, perform fingerprinting and look up the metadata for the audio. pcmiter must be an iterable of blocks of PCM data (buffers). duration is the total length of the track in seconds (an integer). metadata may be a dictio... |
def parse_metadata(xml): """Given an XML document (string) returned from metadata_query(), parse the response into a list of track info dicts. May raise an APIError if the lookup fails. """ try: root = etree.fromstring(xml) except (ExpatError, etree.ParseError): # The Last.fm API occasionally generates malformed XML wh... |
def match_file(apikey, path, metadata=None): """Uses the audioread library to decode an audio file and match it. """ import audioread with audioread.audio_open(path) as f: return match(apikey, iter(f), f.samplerate, int(f.duration), f.channels, metadata) |
def update_constants(nmrstar2cfg="", nmrstar3cfg="", resonance_classes_cfg="", spectrum_descriptions_cfg=""): """Update constant variables. :return: None :rtype: :py:obj:`None` """ nmrstar_constants = {} resonance_classes = {} spectrum_descriptions = {} this_directory = os.path.dirname(__file__) nmrstar2_config_filepat... |
def list_spectrum_descriptions(*args): """List all available spectrum descriptions that can be used for peak list simulation. :param str args: Spectrum name(s), e.g. list_spectrum_descriptions("HNCO", "HNcoCACB"), leave empty to list everything. :return: None :rtype: :py:obj:`None` """ if args: for spectrum_name in arg... |
def read(filehandle, source): """Read data into a :class:`~nmrstarlib.nmrstarlib.StarFile` instance. :param filehandle: file-like object. :type filehandle: :py:class:`io.TextIOWrapper`, :py:class:`gzip.GzipFile`, :py:class:`bz2.BZ2File`, :py:class:`zipfile.ZipFile` :param str source: String indicating where file is com... |
def write(self, filehandle, file_format): """Write :class:`~nmrstarlib.nmrstarlib.StarFile` data into file. :param filehandle: file-like object. :type filehandle: :py:class:`io.TextIOWrapper` :param str file_format: Format to use to write data: `nmrstar`, `cif`, or `json`. :return: None :rtype: :py:obj:`None` """ try: ... |
def _to_star(self): """Save :class:`~nmrstarlib.nmrstarlib.StarFile` into NMR-STAR or CIF formatted string. :return: NMR-STAR string. :rtype: :py:class:`str` """ star_str = io.StringIO() self.print_file(star_str) return star_str.getvalue() |
def _is_nmrstar(string): """Test if input string is in NMR-STAR format. :param string: Input string. :type string: :py:class:`str` or :py:class:`bytes` :return: Input string if in NMR-STAR format or False otherwise. :rtype: :py:class:`str` or :py:obj:`False` """ if (string[0:5] == u"data_" and u"save_" in string) or (s... |
def _is_cif(string): """Test if input string is in CIF format. :param string: Input string. :type string: :py:class:`str` or :py:class:`bytes` :return: Input string if in CIF format or False otherwise. :rtype: :py:class:`str` or :py:obj:`False` """ if (string[0:5] == u"data_" and u"_entry.id" in string) or (string[0:5]... |
def _is_json(string): """Test if input string is in JSON format. :param string: Input string. :type string: :py:class:`str` or :py:class:`bytes` :return: Input string if in JSON format or False otherwise. :rtype: :py:class:`str` or :py:obj:`False` """ try: if isinstance(string, bytes): string = string.decode("utf-8") j... |
def _build_file(self, nmrstar_str): """Build :class:`~nmrstarlib.nmrstarlib.NMRStarFile` object. :param nmrstar_str: NMR-STAR-formatted string. :type nmrstar_str: :py:class:`str` or :py:class:`bytes` :return: instance of :class:`~nmrstarlib.nmrstarlib.NMRStarFile`. :rtype: :class:`~nmrstarlib.nmrstarlib.NMRStarFile` ""... |
def _build_saveframe(self, lexer): """Build NMR-STAR file saveframe. :param lexer: instance of the lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Saveframe dictionary. :rtype: :py:class:`collections.OrderedDict` """ odict = OrderedDict() loop_count = 0 token = next(lexer) while token != u"s... |
odict is None: token = u"save_" else: token = next(lexer) return odict |
def _build_loop(self, lexer): """Build saveframe loop. :param lexer: instance of lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Fields and values of the loop. :rtype: :py:class:`tuple` """ fields = [] values = [] token = next(lexer) while token[0] == u"_": fields.append(token[1:]) token = n... |
def _skip_saveframe(self, lexer): """Skip entire saveframe - keep emitting tokens until the end of saveframe. :param lexer: instance of the lexical analyzer class. :type lexer: :class:`~nmrstarlib.bmrblex.bmrblex` :return: None :rtype: :py:obj:`None` """ token = u"" while token != u"save_": token = next(lexer) |
def print_file(self, f=sys.stdout, file_format="nmrstar", tw=3): """Print :class:`~nmrstarlib.nmrstarlib.NMRStarFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `nmrstar` or `json`. :param int tw: Tab width. :return: None :rtype: :py:obj:`None` """ if ... |
def print_saveframe(self, sf, f=sys.stdout, file_format="nmrstar", tw=3): """Print saveframe into a file or stdout. We need to keep track of how far over everything is tabbed. The "tab width" variable tw does this for us. :param str sf: Saveframe name. :param io.StringIO f: writable file-like stream. :param str file_fo... |
of two or more words print(u"{}_{}\t {}".format(tw * u" ", sftag, u"'{}'".format(self[sf][sftag])), file=f) else: print(u"{}_{}\t {}".format(tw * u" ", sftag, self[sf][sftag]), file=f) elif file_format == "json": print(json.dumps(self[sf], sort_keys=False, indent=4), file=f) |
def print_loop(self, sf, sftag, f=sys.stdout, file_format="nmrstar", tw=3): """Print loop into a file or stdout. :param str sf: Saveframe name. :param str sftag: Saveframe tag, i.e. field name. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `nmrstar` or `json`. :param int tw: Ta... |
sort_keys=False, indent=4), file=f) |
def chem_shifts_by_residue(self, amino_acids=None, atoms=None, amino_acids_and_atoms=None, nmrstar_version="3"): """Organize chemical shifts by amino acid residue. :param list amino_acids: List of amino acids three-letter codes. :param list atoms: List of BMRB atom type codes. :param dict amino_acids_and_atoms: Amino a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.