code stringlengths 1 18.2k |
|---|
def rootChild_resetPassword(self, req, webViewer): """ Return a page which will allow the user to re-set their password. """ from xmantissa.signup import PasswordResetResource return PasswordResetResource(self.store) |
def indirect(self, interface): """ Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}. """ if interface == IWebViewer: return _AnonymousWebViewer(self.store) return super(AnonymousSite, self).indirect(interface) |
def get_configurable_by_name(self, name): """ Returns the registered configurable with the specified name or ``None`` if no such configurator exists. """ l = [c for c in self.configurables if c.name == name] if l: return l[0] |
def results(self, trial_ids): """ Accepts a sequence of trial ids and returns a pandas dataframe with the schema trial_id, iteration?, *metric_schema_union where iteration is an optional column that specifies the iteration when a user logged a metric, if the user supplied one. The iteration column is added if any metri... |
TODO constants should just contain the recipes for filename # construction instead of this multi-file implicit constraint result_file = os.path.join( metadata_folder, trial_id + "_" + constants.RESULT_SUFFIX) assert os.path.isfile(result_file), result_file dfs.append(pd.read_json(result_file, typ='frame', lines=True)) ... |
def fetch_artifact(self, trial_id, prefix): """ Verifies that all children of the artifact prefix path are available locally. Fetches them if not. Returns the local path to the given trial's artifacts at the specified prefix, which is always just {log_dir}/{trial_id}/{prefix} """ # TODO: general windows concern: local ... |
def scan_temperature(self, measure, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep r... |
60. t_last = t_now if abs(temperature - Tset) < abs(dT): self.target_temperature = temperature break else: self.target_temperature = Tset = Tset + dT time.sleep(delay) |
def scan_temperature_old(self, measure, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The swe... |
def set_temperature(self, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kel... |
def set_temperature_old(self, temperature, rate, wait_for_stability=True, delay=1): """Sets the temperature. .. note:: For complex sweep sequences, checkout :attr:`ITC503.sweep_table`. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param wait_for_stability: If w... |
def _load(self): """ Load provenance info from the main store. """ graph = self.context.parent.graph.get_context(self.context.identifier) data = {} for (_, p, o) in graph.triples((self.context.identifier, None, None)): if not p.startswith(META): continue name = p[len(META):] data[name] = o.toPython() return data |
def generate(self): """ Add provenance info to the context graph. """ t = (self.context.identifier, RDF.type, META.Provenance) if t not in self.context.graph: self.context.graph.add(t) for name, value in self.data.items(): pat = (self.context.identifier, META[name], None) if pat in self.context.graph: self.context.grap... |
def jsonresolver_loader(url_map): """Jsonresolver hook for funders resolving.""" def endpoint(doi_code): pid_value = "10.13039/{0}".format(doi_code) _, record = Resolver(pid_type='frdoi', object_type='rec', getter=Record.get_record).resolve(pid_value) return record pattern = '/10.13039/<doi_code>' url_map.add(Rule(patt... |
def snap(self, *args): """Records up to 6 parameters at a time. :param args: Specifies the values to record. Valid ones are 'X', 'Y', 'R', 'theta', 'AuxIn1', 'AuxIn2', 'AuxIn3', 'AuxIn4', 'Ref', 'CH1' and 'CH2'. If none are given 'X' and 'Y' are used. """ # TODO: Do not use transport directly. params = {'X': 1, 'Y': 2,... |
def trace(self, buffer, start, length=1): """Reads the points stored in the channel buffer. :param buffer: Selects the channel buffer (either 1 or 2). :param start: Selects the bin where the reading starts. :param length: The number of bins to read. .. todo:: Use binary command TRCB to speed up data transmission. """ #... |
def isAppStore(s): """ Return whether the given store is an application store or not. @param s: A Store. """ if s.parent is None: return False substore = s.parent.getItemByID(s.idInParent) return s.parent.query(InstalledOffering, InstalledOffering.application == substore ).count() > 0 |
def getInstalledOfferings(self): """ Return a mapping from the name of each L{InstalledOffering} in C{self._siteStore} to the corresponding L{IOffering} plugins. """ d = {} installed = self._siteStore.query(InstalledOffering) for installation in installed: offering = installation.getOffering() if offering is not None: ... |
def installOffering(self, offering): """ Install the given offering:: - Create and install the powerups in its I{siteRequirements} list. - Create an application L{Store} and a L{LoginAccount} referring to it. Install the I{appPowerups} on the application store. - Create an L{InstalledOffering. Perform all of these task... |
requiredPowerup is None: raise NotImplementedError( 'Interface %r required by %r but not provided by %r' % (requiredInterface, offering, self._siteStore)) self._siteStore.findOrCreate( requiredPowerup, lambda p: installOn(p, self._siteStore)) ls = self._siteStore.findOrCreate(userbase.LoginSystem) substoreItem = substo... |
def installOffering(self, offering, configuration): """ Create an app store for an L{Offering} and install its dependencies. Also create an L{InstalledOffering} in the site store, and return it. """ s = self.store.parent self.installedOfferingCount += 1 return installOffering(s, offering, configuration) |
def send_file(self, file): """ Send a file to the client, it is a convenient method to avoid duplicated code """ if self.logger: self.logger.debug("[ioc.extra.tornado.RouterHandler] send file %s" % file) self.send_file_header(file) fp = open(file, 'rb') self.write(fp.read()) fp.close() |
def triplify_object(binding): """ Create bi-directional bindings for object relationships. """ triples = [] if binding.uri: triples.append((binding.subject, RDF.type, binding.uri)) if binding.parent is not None: parent = binding.parent.subject if binding.parent.is_array: parent = binding.parent.parent.subject triples.a... |
def triplify(binding): """ Recursively generate RDF statement triples from the data and schema supplied to the application. """ triples = [] if binding.data is None: return None, triples if binding.is_object: return triplify_object(binding) elif binding.is_array: for item in binding.items: _, item_triples = triplify(it... |
def _candidate_type_names(python_type_representation): """Generator which yields possible type names to look up in the conversion dictionary. Parameters ---------- python_type_representation : object Any Python object which represents a type, such as `int`, `dtype('int8')`, `np.int8`, or `"int8"`. """ # if we get a sin... |
yield str(python_type_representation) |
def db_type(python_type_representation): """ Converts from any of: (1) Python type (2) NumPy/Pandas dtypes (3) string names of types ...to a sqlite3 type name """ for type_name in _candidate_type_names(python_type_representation): db_type_name = _lookup_type_name(type_name) if db_type_name: return db_type_name raise Va... |
def ip_address(self): """ The IP address of the first interface listed in the droplet's ``networks`` field (ordering IPv4 before IPv6), or `None` if there are no interfaces """ networks = self.get("networks", {}) v4nets = networks.get("v4", []) v6nets = networks.get("v6", []) try: return (v4nets + v6nets)[0].ip_address... |
def fetch(self): """ Fetch & return a new `Droplet` object representing the droplet's current state :rtype: Droplet :raises DOAPIError: if the API endpoint replies with an error (e.g., if the droplet no longer exists) """ api = self.doapi_manager return api._droplet(api.request(self.url)["droplet"]) |
def fetch_all_neighbors(self): r""" Returns a generator that yields all of the droplets running on the same physical server as the droplet :rtype: generator of `Droplet`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager return map(api._droplet, api.paginate(self.url + '/neigh... |
def fetch_all_snapshots(self): r""" Returns a generator that yields all of the snapshot images created from the droplet :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for obj in api.paginate(self.url + '/snapshots', 'snapshots'): yield Image(ob... |
def fetch_all_backups(self): r""" Returns a generator that yields all of the backup images created from the droplet :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for obj in api.paginate(self.url + '/backups', 'backups'): yield Image(obj, doapi... |
def fetch_all_kernels(self): r""" Returns a generator that yields all of the kernels available to the droplet :rtype: generator of `Kernel`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for kern in api.paginate(self.url + '/kernels', 'kernels'): yield Kernel(kern, doapi_m... |
def restore(self, image): """ Restore the droplet to the specified backup image A Droplet restoration will rebuild an image using a backup image. The image ID that is passed in must be a backup of the current Droplet instance. The operation will leave any embedded SSH keys intact. [APIDocs]_ :param image: an image ID, ... |
def resize(self, size, disk=None): """ Resize the droplet :param size: a size slug or a `Size` object representing the size to resize to :type size: string or `Size` :param bool disk: Set to `True` for a permanent resize, including disk changes :return: an `Action` representing the in-progress operation on the droplet ... |
def rebuild(self, image): """ Rebuild the droplet with the specified image A rebuild action functions just like a new create. [APIDocs]_ :param image: an image ID, an image slug, or an `Image` object representing the image the droplet should use as a base :type image: integer, string, or `Image` :return: an `Action` re... |
def change_kernel(self, kernel): """ Change the droplet's kernel :param kernel: a kernel ID or `Kernel` object representing the new kernel :type kernel: integer or `Kernel` :return: an `Action` representing the in-progress operation on the droplet :rtype: Action :raises DOAPIError: if the API endpoint replies with an e... |
def wait(self, status=None, locked=None, wait_interval=None, wait_time=None): """ Poll the server periodically until the droplet has reached some final state. If ``status`` is non-`None`, ``wait`` will wait for the droplet's ``status`` field to equal the given value. If ``locked`` is non-`None`, `wait` will wait for th... |
desired value for the ``status`` field of the droplet, which should be one of `Droplet.STATUS_ACTIVE`, `Droplet.STATUS_ARCHIVE`, `Droplet.STATUS_NEW`, and `Droplet.STATUS_OFF`. (For the sake of forwards-compatibility, any other value is accepted as well.) :type status: string or `None` :param locked: When non-`None`, t... |
or neither of ``status`` & ``locked`` are defined :raises DOAPIError: if the API endpoint replies with an error :raises WaitTimeoutError: if ``wait_time`` is exceeded """ return next(self.doapi_manager.wait_droplets([self], status, locked, wait_interval, wait_time)) |
def minter(record_uuid, data, pid_type, key): """Mint PIDs for a record.""" pid = PersistentIdentifier.create( pid_type, data[key], object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED ) for scheme, identifier in data['identifiers'].items(): if identifier: PersistentIdentifier.create( scheme, identif... |
def date_range(start_date, end_date, increment, period): """ Generate `date` objects between `start_date` and `end_date` in `increment` `period` intervals. """ next = start_date delta = relativedelta.relativedelta(**{period:increment}) while next <= end_date: yield next next += delta |
def GaP_Eg_Gamma(self, **kwargs): ''' Returns the Gamma-valley bandgap, Eg_Gamma, in electron Volts at a given temperature, T, in Kelvin (default: 300 K). GaP has a unique Gamma-gap temperature dependence. ''' T = kwargs.get('T', 300.) if T < 1e-4: return self.Eg_Gamma_0() return self.Eg_Gamma_0() + 0.1081 * (1 - 1. / ... |
def send_message(frm=None, to=None, text=None): """Shortcut to send a sms using libnexmo api. :param frm: The originator of the message :param to: The message's recipient :param text: The text message body Example usage: >>> send_message(to='+33123456789', text='My sms message body') """ assert to is not None assert te... |
def filtered(f): ''' Decorator function that wraps functions returning pandas dataframes, such that the dataframe is filtered according to left and right bounds set. ''' def _filter(f, self, *args, **kwargs): frame = f(self, *args, **kwargs) ret = type(self)(frame) ret._lbound = self._lbound ret._rbound = self._rbound ... |
def to_datetime(self, column): ''' This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime ''' if column in self: if self[column].dtype in NUMPY_NUMERICAL: self[column] = pd.to_datetime(self[column], unit='s') else: self[column] = pd.to_datetime(self[column]... |
def set_date_bounds(self, date): ''' Pass in the date used in the original query. :param date: Date (date range) that was queried: date -> 'd', '~d', 'd~', 'd~d' d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d' ''' if date is not None: split = date.split('~') if len(split) == 1: self._lbound = ts2dt(date) s... |
def check_in_bounds(self, date): '''Check that left and right bounds are sane :param date: date to validate left/right bounds for ''' dt = Timestamp(date) return ((self._lbound is None or dt >= self._lbound) and (self._rbound is None or dt <= self._rbound)) |
def on_date(self, date, only_count=False): ''' Filters out only the rows that match the spectified date. Works only on a Result that has _start and _end columns. :param date: date can be anything Pandas.Timestamp supports parsing :param only_count: return back only the match count ''' if not self.check_in_bounds(date):... |
def history(self, dates=None, linreg_since=None, lin_reg_days=20): ''' Works only on a Result that has _start and _end columns. :param dates: list of dates to query :param linreg_since: estimate future values using linear regression. :param lin_reg_days: number of past days to use as prediction basis ''' dates = dates ... |
def _linreg_future(self, series, since, days=20): ''' Predicts future using linear regression. :param series: A series in which the values will be places. The index will not be touched. Only the values on dates > `since` will be predicted. :param since: The starting date from which the future will be predicted. :param ... |
def get_dates_range(self, scale='auto', start=None, end=None, date_max='2010-01-01'): ''' Returns a list of dates sampled according to the specified parameters. :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'} Scale specifies the sampling intervals. 'auto' will heuristically choose... |
start if self.check_in_bounds(start) else self._lbound end = end if self.check_in_bounds(end) else self._rbound if scale == 'auto': scale = self._auto_select_scale(start, end) if scale == 'maximum': start_dts = list(self._start.dropna().values) end_dts = list(self._end.dropna().values) dts = map(Timestamp, set(start_dt... |
> ret[-1] else ret ret = filter(lambda ts: self.check_in_bounds(ts), ret) return ret |
def _auto_select_scale(self, start=None, end=None, ideal=300): ''' Guess what a good timeseries scale might be, given a particular data set, attempting to make the total number of x values as close to `ideal` as possible This is a helper for plotting ''' start = start or self._start.min() end = end or max(self._end.max... |
def filter_oids(self, oids): ''' Leaves only objects with specified oids. :param oids: list of oids to include ''' oids = set(oids) return self[self['_oid'].map(lambda x: x in oids)] |
def unfinished_objects(self): ''' Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`. ''' mask = self._end_isnull if self._rbound is not None: mask = mask | (self._end > self._rbound) oids = set(self[mask]._oid.tolist()) return self[self._oid.apply(lambda oid: ... |
def persistent_oid_counts(self, dates): ''' Counts how many objects (identified by their oids) existed before or on a given date. :param dates: list of the dates the count should be computed. ''' total = pd.Series([self.on_date(d)._oid for d in dates], index=dates) for i in range(1, total.size): a1 = total[total.index[... |
def last_versions_with_age(self, col_name='age'): ''' Leaves only the latest version for each object. Adds a new column which represents age. The age is computed by subtracting _start of the oldest version from one of these possibilities:: # psuedo-code if self._rbound is None: if latest_version._end is pd.NaT: current... |
= row vals = max_start_ser_map.values() cut_ts = datetime.utcnow() ages = [] for row in vals: end = row[i_end] end = cut_ts if end is pd.NaT else min(cut_ts, end) age = end - min_start_map[row[i_oid]] age = age - timedelta(microseconds=age.microseconds) ages.append(age) res = pd.DataFrame(max_start_ser_map.values(), co... |
def last_chain(self): ''' Leaves only the last chain for each object. Chain is a series of consecutive versions where `_end` of one is `_start` of another. ''' cols = self.columns.tolist() i_oid = cols.index('_oid') i_start = cols.index('_start') i_end = cols.index('_end') start_map = {} end_map = {} for row in self.va... |
def one_version(self, index=0): ''' Leaves only one version for each object. :param index: List-like index of the version. 0 == first; -1 == last ''' def prep(df): start = sorted(df._start.tolist())[index] return df[df._start == start] return pd.concat([prep(df) for _, df in self.groupby(self._oid)]) |
def started_after(self, date): ''' Leaves only those objects whose first version started after the specified date. :param date: date string to use in calculation ''' dt = Timestamp(date) starts = self.groupby(self._oid).apply(lambda df: df._start.min()) oids = set(starts[starts > dt].index.tolist()) return self[self._o... |
def object_apply(self, function): ''' Groups by _oid, then applies the function to each group and finally concatenates the results. :param function: func that takes a DataFrame and returns a DataFrame ''' return pd.concat([function(df) for _, df in self.groupby(self._oid)]) |
def _has_x(self, kwargs): '''Returns True if x is explicitly defined in kwargs''' return (('x' in kwargs) or (self._element_x in kwargs) or (self._type == 3 and self._element_1mx in kwargs)) |
def _get_x(self, kwargs): ''' Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if 'x' in kwargs: return round(float(kwargs['x']), 6) elif self._element_x in kwargs: return round(float(kwargs[self._element_x]), 6) elif self._type == 3 and self._element_1mx in kwargs: return round(1. - fl... |
def _has_y(self, kwargs): '''Returns True if y is explicitly defined in kwargs''' return (('y' in kwargs) or (self._element_y in kwargs) or (self._type == 3 and self._element_1my in kwargs)) |
def _get_y(self, kwargs): ''' Returns y if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if 'y' in kwargs: return round(float(kwargs['y']), 6) elif self._element_y in kwargs: return round(float(kwargs[self._element_y]), 6) elif self._type == 3 and self._element_1my in kwargs: return round(1. - fl... |
def _has_z(self, kwargs): ''' Returns True if type is 1 or 2 and z is explicitly defined in kwargs. ''' return ((self._type == 1 or self._type ==2) and (('z' in kwargs) or (self._element_z in kwargs))) |
def _get_z(self, kwargs): ''' Returns z if type is 1 or 2 and z is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if self._type == 1 or self._type == 2: if 'z' in kwargs: return round(float(kwargs['z']), 6) elif self._element_z in kwargs: return round(float(kwargs[self._element_z]), 6) raise TypeError() |
def exists(cls, query=None, path=None, **kwargs): """ Like __init__ but simply returns a boolean as to whether or not the object exists, rather than returning the whole object. NOTE: if you pass in a single argument to exists, this will match against ID_KEY. @param query: a dictionary specifying key-value pairs that th... |
query = kwargs if query is None: return False return cls.db(path).find_one(query) is not None |
def create(cls, data, path=None, defaults=None, overwrite=False, random_id=False, **kwargs): """ Creates a new database object and stores it in the database NOTE: The path and defaults parameters to this function are to allow use of the DatabaseObject class directly. However, this class is intended for subclassing and ... |
database with the same ID_KEY; if set to false will raise an exception if there is another object with the same ID_KEY @param random_id: stores the new object with a random value for ID_KEY; overwrites data[ID_KEY] @param **kwargs: ignored @raise Exception: if path and self.PATH are None; the database path must be defi... |
in self: dict.__delitem__(self, ID_KEY) if not random_id and ID_KEY not in self: raise MalformedObjectError("No " + ID_KEY + " key in item") if not random_id and not overwrite and self._collection.find_one({ID_KEY: data[ID_KEY]}): raise DatabaseConflictError('ID_KEY "%s" already exists in collection %s' % (data[ID_KEY]... |
def create_from_json(cls, json_str, ignore_non_defaults=True): """ Creates a database object from a json object. The intent of this method is to allow creating a database object directly from json. Mongolia will also automatically convert any json values that are formatted using the MongoliaJSONEncoder (for ObjectIds a... |
that do not appear in DEFAULTS will also be excluded in creation """ create_dict = json.loads(json_str, cls=MongoliaJSONDecoder, encoding="utf-8") # Remove all keys not in DEFAULTS if ignore_non_defaults is True if cls.DEFAULTS and ignore_non_defaults: for key in frozenset(create_dict).difference(frozenset(cls.DEFAULTS... |
def db(cls, path=None): """ Returns a pymongo Collection object from the current database connection. If the database connection is in test mode, collection will be in the test database. @param path: if is None, the PATH attribute of the current class is used; if is not None, this is used instead @raise Exception: if n... |
def save(self): """ Saves the current state of the DatabaseObject to the database. Fills in missing values from defaults before saving. NOTE: The actual operation here is to overwrite the entry in the database with the same ID_KEY. WARNING: While the save operation itself is atomic, it is not atomic with loads and modi... |
def rename(self, new_id): """ Renames the DatabaseObject to have ID_KEY new_id. This is the only way allowed by DatabaseObject to change the ID_KEY of an object. Trying to modify ID_KEY in the dictionary will raise an exception. @param new_id: the new value for ID_KEY NOTE: This is actually a create and delete. WARNING... |
def remove(self): """ Deletes the object from the database WARNING: This cannot be undone. Be really careful when deleting programatically. It is recommended to backup your database before applying specific deletes. If your application uses deletes regularly, it is strongly recommended that you have a recurring backup ... |
def copy(self, new_id=None, attribute_overrides={}): """ Copies the DatabaseObject under the ID_KEY new_id. @param new_id: the value for ID_KEY of the copy; if this is none, creates the new object with a random ID_KEY @param attribute_overrides: dictionary of attribute names -> values that you would like to override wi... |
def update(self, update_dict=None, raw=False, **kwargs): """ Applies updates both to the database object and to the database via the mongo update method with the $set argument. Use the `raw` keyword to perform an arbitrary mongo update query. WARNING: Raw updates do not perform type checking. WARNING: While the update ... |
@param update_dict: dictionary of updates to apply @param raw: if set to True, uses the contents of update_dict directly to perform the update rather than wrapping them in $set. @param **kwargs: used as update_dict if no update_dict is None """ if update_dict is None: update_dict = kwargs if raw: self._collection.updat... |
def json_update(self, json_str, exclude=[], ignore_non_defaults=True): """ Updates a database object based on a json object. The intent of this method is to allow passing json to an interface which then subsequently manipulates the object and then sends back an update. Mongolia will also automatically convert any json ... |
need not be included in this list; it is automatically deleted since it can't be part of a mongo update operation) @param ignore_non_defaults: if this is True and the database object has non-empty DEFAULTS, then any top-level keys in the update json that do not appear in DEFAULTS will also be excluded from the update "... |
def json_update_fields(self, json_str, fields_to_update): """ Updates the specified fields of a database object based on a json object. The intent of this method is to allow passing json to an interface which then subsequently manipulates the object and then sends back an update for specific fields of the object. Mongo... |
of the top-level keys to update; only keys included in this list will be update. Do not include ID_KEY in this list since it can't be part of a mongo update operation """ update_dict = json.loads(json_str, cls=MongoliaJSONDecoder, encoding="utf-8") update_dict = dict((k, v) for k, v in update_dict.items() if k in field... |
def raxml_alignment(align_obj, raxml_model="GTRCAT", params={}, SuppressStderr=True, SuppressStdout=True): """Run raxml on alignment object align_obj: Alignment object params: you can set any params except -w and -n returns: tuple (phylonode, parsimonyphylonode, log likelihood, total exec time) """ # generate temp file... |
parsimony_tree_node, log_likelihood, total_exec_time |
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={}): """Returns a tree from Alignment object aln. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: best_tree suppport is currently not implemented params: dict of parameters... |
aln.toPhylip() # generate temp filename for output params["-w"] = "/tmp/" params["-n"] = get_tmp_filename().split("/")[-1] params["-k"] = True params["-p"] = randint(1,100000) params["-x"] = randint(1,100000) ih = '_input_as_multiline_string' raxml_app = Raxml(params=params, InputHandler=ih, WorkingDir=None, SuppressSt... |
def insert_sequences_into_tree(seqs, moltype, params={}, write_log=True): """Insert sequences into Tree. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object params: dict of parameters to pass in to the RAxML app controller. The result will be a tree. """ ih =... |
def _format_output(self, outfile_name, out_type): """ Prepend proper output prefix to output filename """ outfile_name = self._absolute(outfile_name) outparts = outfile_name.split("/") outparts[-1] = self._out_format % (out_type, outparts[-1] ) return '/'.join(outparts) |
def _checkpoint_out_filenames(self): """ RAxML generates a crapload of checkpoint files so need to walk directory to collect names of all of them. """ out_filenames = [] if self.Parameters['-n'].isOn(): out_name = str(self.Parameters['-n'].Value) walk_root = self.WorkingDir if self.Parameters['-w'].isOn(): walk_root = ... |
def _handle_app_result_build_failure(self,out,err,exit_status,result_paths): """ Catch the error when files are not produced """ try: raise ApplicationError, \ 'RAxML failed to produce an output file due to the following error: \n\n%s ' \ % err.read() except: raise ApplicationError,\ 'RAxML failed to run properly.' |
def names(self): """ Returns a list of queues available, ``None`` if no such queues found. Remember this will only shows queues with at least one item enqueued. """ data = None if not self.connected: raise ConnectionError('Queue is not connected') try: data = self.rdb.keys("retaskqueue-*") except redis.exceptions.Conne... |
def length(self): """ Gives the length of the queue. Returns ``None`` if the queue is not connected. If the queue is not connected then it will raise :class:`retask.ConnectionError`. """ if not self.connected: raise ConnectionError('Queue is not connected') try: length = self.rdb.llen(self._name) except redis.exception... |
def connect(self): """ Creates the connection with the redis server. Return ``True`` if the connection works, else returns ``False``. It does not take any arguments. :return: ``Boolean`` value .. note:: After creating the ``Queue`` object the user should call the ``connect`` method to create the connection. .. doctest:... |
def wait(self, wait_time=0): """ Returns a :class:`~retask.task.Task` object from the queue. Returns ``False`` if it timeouts. :arg wait_time: Time in seconds to wait, default is infinite. :return: :class:`~retask.task.Task` object from the queue or False if it timeouts. .. doctest:: >>> from retask import Queue >>> q ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.