code
stringlengths
1
18.2k
conversions was found, so find path through graph. # If profile was plural, add in extra steps. path = self.dgraph.shortest_path(in_str, out_str) path += profile[1:] # Loop through each edge traversal, adding converters and type # string pairs as we go along. This is to ensure conversion # profiles that have arguments ...
def find_path_with_profiles(self, conversion_profiles, in_, out): ''' Like find_path, except forces the conversion profiles to be the given conversion profile setting. Useful for "temporarily overriding" the global conversion profiles with your own. ''' original_profiles = dict(self.conversion_profiles) self._setup_pro...
def get_lines_from_file(filename, lineno, context_lines): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ def get_lines(start, end): return [linecache.getline(filename, l).rstrip() for l in range(start, end)] lower_bound = max(1, li...
def get_frames(tback, is_breakpoint): """Builds a list of ErrorFrame objects from a traceback""" frames = [] while tback is not None: if tback.tb_next is None and is_breakpoint: break filename = tback.tb_frame.f_code.co_filename function = tback.tb_frame.f_code.co_name context = tback.tb_frame.f_locals lineno = tback.t...
def prettify_object(obj): """Makes a pretty string for an object for nice output""" try: return pprint.pformat(str(obj)) except UnicodeDecodeError as e: raise except Exception as e: return "[could not display: <%s: %s>]" % (e.__class__.__name__, str(e))
def clone_git_repo(repo_url): """ input: repo_url output: path of the cloned repository steps: 1. clone the repo 2. parse 'site' into for templating assumptions: repo_url = "git@github.com:littleq0903/django-deployer-template-openshift-experiment.git" repo_local_location = "/tmp/djangodeployer-cache-xxxx" # xxxx here w...
def get_template_filelist(repo_path, ignore_files=[], ignore_folders=[]): """ input: local repo path output: path list of files which need to be rendered """ default_ignore_files = ['.gitignore'] default_ignore_folders = ['.git'] ignore_files += default_ignore_files ignore_folders += default_ignore_folders filelist = [...
def render_from_repo(repo_path, to_path, template_params, settings_dir): """ rendering all files into the target directory """ TEMPLATE_PROJECT_FOLDER_PLACEHOLDER_NAME = 'deployer_project' repo_path = repo_path.rstrip('/') to_path = to_path.rstrip('/') files_to_render = get_template_filelist(repo_path, ignore_folders=[...
def gen_logger(name: str, log_level: int=logging.INFO) -> logging.Logger: """Create a logger to be used between processes. :returns: Logging instance. """ logger = logging.getLogger(name) logger.setLevel(log_level) shandler: logging.StreamHandler = logging.StreamHandler(sys.stdout) fmt: str = '\033[1;32m%(levelname)-5s...
def gen_headers() -> Dict[str, str]: """Generate a header pairing.""" ua_list: List[str] = ['Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'] headers: Dict[str, str] = {'User-Agent': ua_list[random.randint(0, len(ua_list) - 1)]} return headers
def extract_emails(results: str, domain: str, fuzzy: bool) -> List[str]: """Grab email addresses from raw text data.""" pattern: Pattern = re.compile(r'([\w.-]+@[\w.-]+)') hits: List[str] = pattern.findall(results) if fuzzy: seed = domain.split('.')[0] emails: List[str] = [x.lower() for x in hits if x.split('@')[1].__c...
def seqs_to_stream(seqs, ih): """Converts seqs into stream of FASTA records, depending on input handler. Each FASTA record will be a list of lines. """ if ih == '_input_as_multiline_string': recs = FastaFinder(seqs.split('\n')) elif ih == '_input_as_string': recs = FastaFinder(open(seqs)) elif ih == '_input_as_seqs': r...
def blast_seqs(seqs, blast_constructor, blast_db=None, blast_mat_root=None, params={}, add_seq_names=True, out_filename=None, WorkingDir=None, SuppressStderr=None, SuppressStdout=None, input_handler=None, HALT_EXEC=False ): """Blast list of sequences. seqs: either file name or list of sequence objects or list of string...
sequence names are inserted in the list of sequences. if False, it assumes seqs is a list of lines of some proper format that the program can handle """ # set num keep if blast_db: params["-d"] = blast_db if out_filename: params["-o"] = out_filename ih = input_handler or guess_input_handler(seqs, add_seq_names) blast_a...
def fasta_cmd_get_seqs(acc_list, blast_db=None, is_protein=None, out_filename=None, params={}, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None): """Retrieve sequences for list of accessions """ if is_protein is None: params["-p"] = 'G' elif is_protein: params["-p"] = 'T' else: params["-p"] = ...
def seqs_from_fastacmd(acc_list, blast_db,is_protein=True): """Get dict of description:seq from fastacmd.""" fasta_cmd_res = fasta_cmd_get_seqs(acc_list, blast_db=blast_db, \ is_protein=is_protein) recs = FastaCmdFinder(fasta_cmd_res['StdOut']) result = {} for rec in recs: try: result[rec[0][1:].strip()] = ''.join(map(...
def psiblast_n_neighbors(seqs, n=100, blast_db=None, core_threshold=1e-50, extra_threshold=1e-10, lower_threshold=1e-6, step=100, method="two-step", blast_mat_root=None, params={}, add_seq_names=False, WorkingDir=None, SuppressStderr=None, SuppressStdout=None, input_handler=None, scorer=3, #shotgun with 3 hits needed t...
blast_db: params["-d"] = blast_db ih = input_handler or guess_input_handler(seqs, add_seq_names) recs = seqs_to_stream(seqs, ih) #checkpointing can only handle one seq... #set up the parameters for the core and additional runs max_iterations = params['-j'] params['-j'] = 2 #won't checkpoint with single iteration app = ...
def ids_from_seq_two_step(seq, n, max_iterations, app, core_threshold, \ extra_threshold, lower_threshold, second_db=None): """Returns ids that match a seq, using a 2-tiered strategy. Optionally uses a second database for the second search. """ #first time through: reset 'h' and 'e' to core #-h is the e-value threshold...
break if num_ids == last_num_ids: break last_num_ids = num_ids #if we didn't write any checkpoints, second run won't work, so return ids if not checkpoints: return ids #if we got too many ids and don't have a second database, return the ids we got if (not second_db) and num_ids >= n: return ids #second time through: re...
= len(ids) if num_ids >= n: break if num_ids == last_num_ids: break last_num_ids = num_ids #return the ids we got. may not be as many as we wanted. for c in checkpoints: remove(c) return ids
def ids_from_seq_lower_threshold(seq, n, max_iterations, app, core_threshold, \ lower_threshold, step=100): """Returns ids that match a seq, decreasing the sensitivity.""" last_num_ids = None checkpoints = [] cp_name_base = make_unique_str() # cache ides for each iteration # store { iteration_num:(core_threshold, [list...
= list(output.get('BlastOut', output['StdOut'])) ids = LastProteinIds9(result,keep_values=True,filter_identity=False) output.cleanUp() all_ids[i + 1] = (core_threshold, copy(ids)) if not access(curr_check, F_OK): raise ThresholdFound checkpoints.append(curr_check) num_ids = len(ids) if num_ids >= n: raise ThresholdFoun...
def make_unique_str(num_chars=20): """make a random string of characters for a temp filename""" chars = 'abcdefghigklmnopqrstuvwxyz' all_chars = chars + chars.upper() + '01234567890' picks = list(all_chars) return ''.join([choice(picks) for i in range(num_chars)])
def keep_everything_scorer(checked_ids): """Returns every query and every match in checked_ids, with best score.""" result = checked_ids.keys() for i in checked_ids.values(): result.extend(i.keys()) return dict.fromkeys(result).keys()
def ids_from_seqs_iterative(seqs, app, query_parser, \ scorer=keep_everything_scorer, max_iterations=None, blast_db=None,\ max_seqs=None, ): """Gets the ids from each seq, then does each additional id until all done. If scorer is passed in as an int, uses shotgun scorer with that # hits. """ if isinstance(scorer, int):...
we've reached it curr_iteration += 1 if max_iterations and (curr_iteration >= max_iterations): break if max_seqs: curr = scorer(checked_ids) if len(curr) >= max_seqs: return curr return scorer(checked_ids)
def blastp(seqs, blast_db="nr", e_value="1e-20", max_hits=200, working_dir=tempfile.gettempdir(), blast_mat_root=None, extra_params={}): """ Returns BlastResult from input seqs, using blastp. Need to add doc string """ # set up params to use with blastp params = { # matrix "-M":"BLOSUM62", # max procs "-a":"1", # expec...
def set_lock(fname): """ Try to lock file and write PID. Return the status of operation. """ global fh fh = open(fname, 'w') if os.name == 'nt': # Code for NT systems got from: http://code.activestate.com/recipes/65203/ import win32con import win32file import pywintypes LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK LOCK_S...
fh.flush() return True
def assert_lock(fname): """ If file is locked then terminate program else lock file. """ if not set_lock(fname): logger.error('File {} is already locked. Terminating.'.format(fname)) sys.exit()
def build_blast_db_from_fasta_path(fasta_path, is_protein=False, output_dir=None, HALT_EXEC=False): """Build blast db from fasta_path; return db name and list of files created **If using to create temporary blast databases, you can call cogent.util.misc.remove_files(db_filepaths) to clean up all the files created by fo...
if not output_dir.endswith('/'): db_name = output_dir + '/' + fasta_filename else: db_name = output_dir + fasta_filename # instantiate the object fdb = FormatDb(WorkingDir=output_dir, HALT_EXEC=HALT_EXEC) if is_protein: fdb.Parameters['-p'].on('T') else: fdb.Parameters['-p'].on('F') app_result = fdb(fasta_path) db_file...
def build_blast_db_from_fasta_file(fasta_file, is_protein=False, output_dir=None, HALT_EXEC=False): """Build blast db from fasta_path; return db name and list of files created **If using to create temporary blast databases, you can call cogent.util.misc.remove_files(db_filepaths) to clean up all the files created by fo...
def build_blast_db_from_seqs(seqs, is_protein=False, output_dir='./', HALT_EXEC=False): """Build blast db from seqs; return db name and list of files created **If using to create temporary blast databases, you can call cogent.util.misc.remove_files(db_filepaths) to clean up all the files created by formatdb when you're...
the temporary file remove(tmp_fasta_filepath) # return the results return db_name, db_filepaths
def parse_command_line_parameters(): """ Parses command line arguments """ usage = 'usage: %prog [options] fasta_filepath' version = 'Version: %prog 0.1' parser = OptionParser(usage=usage, version=version) # A binary 'verbose' flag parser.add_option('-p', '--is_protein', action='store_true', dest='is_protein', default=...
def _input_as_parameter(self, data): """ Set the input path and log path based on data (a fasta filepath) """ self.Parameters['-i'].on(data) # access data through self.Parameters so we know it's been cast # to a FilePath input_filepath = self.Parameters['-i'].Value input_file_dir, input_filename = split(input_filepath)...
def _get_result_paths(self, data): """ Build the dict of result filepaths """ # access data through self.Parameters so we know it's been cast # to a FilePath wd = self.WorkingDir db_name = self.Parameters['-n'].Value log_name = self.Parameters['-l'].Value result = {} result['log'] = ResultPath(Path=wd + log_name, IsWri...
def _session_key(self): """Gets the redis key for a session""" if not hasattr(self, "_cached_session_key"): session_id_bytes = self.get_secure_cookie("session_id") session_id = None if session_id_bytes: try: session_id = session_id_bytes.decode('utf-8') except: pass if not session_id: session_id = oz.redis_sessions.ran...
def _update_session_expiration(self): """ Updates a redis item to expire later since it has been interacted with recently """ session_time = oz.settings["session_time"] if session_time: self.redis().expire(self._session_key, session_time)
def get_session_value(self, name, default=None): """Gets a session value""" value = self.redis().hget(self._session_key, name) or default self._update_session_expiration() return value
def set_session_value(self, name, value): """Sets a session value""" self.redis().hset(self._session_key, name, value) self._update_session_expiration()
def clear_session_value(self, name): """Removes a session value""" self.redis().hdel(self._session_key, name) self._update_session_expiration()
async def rewrite_middleware(server, request): ''' Sanic middleware that utilizes a security class's "rewrite" method to check ''' if singletons.settings.SECURITY is not None: security_class = singletons.settings.load('SECURITY') else: security_class = DummySecurity security = security_class() try: new_path = await sec...
def answer(self, c, details): """Answer will provide all necessary feedback for the caller Args: c (int): HTTP Code details (dict): Response payload Returns: dict: Response payload Raises: ErrAtlasBadRequest ErrAtlasUnauthorized ErrAtlasForbidden ErrAtlasNotFound ErrAtlasMethodNotAllowed ErrAtlasConflict ErrAtlasServer...
def get(self, uri): """Get request Args: uri (str): URI Returns: Json: API response Raises: Exception: Network issue """ r = None try: r = requests.get(uri, allow_redirects=True, timeout=Settings.requests_timeout, headers={}, auth=HTTPDigestAuth(self.user, self.password)) return self.answer(r.status_code, r.json()) exc...
def get_objects(self, uri, pull=True, **kwargs): ''' Walk through repo commits to generate a list of repo commit objects. Each object has the following properties: * repo uri * general commit info * files added, removed fnames * lines added, removed * acked_by * signed_off_by * resolves * related ''' self.repo = repo =...
true, always is true... objs = [] for c_log in c_logs: sha, s, all_changes = c_log.partition('\n') #try: c = repo.get_object(sha) # FIXME: not normalizing to UTC _start = ts2dt(c.commit_time) #except Exception as e: # _start = now # obj = dict(_oid=sha, _start=_start, _end=_end, # repo_uri=uri, _e={sha: to_encoding(e)}...
# file +/- totals obj['added'] = sum( [v.get('added', 0) for v in obj['files'].itervalues()]) obj['removed'] = sum( [v.get('removed', 0) for v in obj['files'].itervalues()]) # extract interesting bits from the message obj['acked_by'] = acked_by_re.findall(c.message) obj['signed_off_by'] = signed_off_by_re.findall(c.mes...
def _dict_values_sorted_by_key(dictionary): # This should be a yield from instead. """Internal helper to return the values of a dictionary, sorted by key. """ for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)): yield value
def _ondemand(f): """Decorator to only request information if not in cache already. """ name = f.__name__ def func(self, *args, **kwargs): if not args and not kwargs: if hasattr(self, '_%s' % name): return getattr(self, '_%s' % name) a = f(self, *args, **kwargs) setattr(self, '_%s' % name, a) return a else: return f(se...
def get_memory(self, start, size): """Retrieve an area of memory from IDA. Returns a sparse dictionary of address -> value. """ LOG.debug('get_memory: %d bytes from %x', size, start) return get_memory(self.ida.idaapi, start, size, default_byte=self.default_byte)
def get_objects(self, **kwargs): ''' Run `rpm -q` command on a {local, remote} system to get back details of installed RPMs. Default rpm details extracted are as follows: * name * version * release * arch * nvra * license * os * packager * platform * sourcepackage * sourcerpm * summary ''' fmt = ':::'.join('%%{%s}' % f...
super(Rpm, self).get_objects(**kwargs)
def handle_404(request, exception): '''Handle 404 Not Found This handler should be used to handle error http 404 not found for all endpoints or if resource not available. ''' error = format_error(title='Resource not found', detail=str(exception)) return json(return_an_error(error), status=HTTPStatus.NOT_FOUND)
def _add_to_dict(t, container, name, value): """ Adds an item to a dictionary, or raises an exception if an item with the specified key already exists in the dictionary. """ if name in container: raise Exception("%s '%s' already exists" % (t, name)) else: container[name] = value
def initialize(config=None): """Initializes oz""" # Load the config file if config == None: config = {} config_source = None try: with open(os.environ.get("OZ_CONFIG", "config.py")) as f: config_source = f.read() except Exception: tornado.log.gen_log.info("Could not read config.py", exc_info=True) if config_source != N...
def trigger(self, name, *args, **kwargs): """ Triggers an event to run through middleware. This method will execute a chain of relevant trigger callbacks, until one of the callbacks returns the `break_trigger`. """ # Relevant middleware is cached so we don't have to rediscover it # every time. Fetch the cached value if...
def cache_makedirs(self, subdir=None): ''' Make necessary directories to hold cache value ''' if subdir is not None: dirname = self.cache_path if subdir: dirname = os.path.join(dirname, subdir) else: dirname = os.path.dirname(self.cache_path) os.makedirs(dirname, exist_ok=True)
def session(connection_string=None): """Gets a SQLAlchemy session""" global _session_makers connection_string = connection_string or oz.settings["db"] if not connection_string in _session_makers: _session_makers[connection_string] = sessionmaker(bind=engine(connection_string=connection_string)) return _session_makers[c...
def assign_reads_to_database(query_fasta_fp, database_fasta_fp, output_fp, params=None): """Assign a set of query sequences to a reference database query_fasta_fp : absolute file path to query sequences database_fasta_fp : absolute file path to the reference database output_fp : absolute file path of the output file to...
def assign_dna_reads_to_dna_database(query_fasta_fp, database_fasta_fp, output_fp, params=None): """Assign DNA reads to a database fasta of DNA sequences. Wraps assign_reads_to_database, setting database and query types. All parameters are set to default unless params is passed. query_fasta_fp: absolute path to the que...
the user specified parameters other than default, then use them. # However, if they try to change the database or query types, raise an # applciation error. if '-t' in params or '-q' in params: raise ApplicationError("Cannot change database or query types when " + "using assign_dna_reads_to_dna_database. " + "Use assig...
def assign_dna_reads_to_protein_database(query_fasta_fp, database_fasta_fp, output_fp, temp_dir="/tmp", params=None): """Assign DNA reads to a database fasta of protein sequences. Wraps assign_reads_to_database, setting database and query types. All parameters are set to default unless params is passed. A temporary fil...
from protein and dna, respectively. This method returns an open file object. The output format defaults to blast9 and should be parsable by the PyCogent BLAST parsers. """ if params is None: params = {} my_params = {'-t': 'prot', '-q': 'prot'} # make sure temp_dir specifies an absolute path if not isabs(temp_dir): rais...
translation of the input DNA sequences and write them to # temporary file. _, tmp = mkstemp(dir=temp_dir) tmp_out = open(tmp, 'w') for label, sequence in parse_fasta(open(query_fasta_fp)): seq_id = label.split()[0] s = DNA.makeSequence(sequence) translations = my_genetic_code.sixframes(s) frames = [1, 2, 3, -1, -2, -3]...
def _get_base_command(self): """Gets the command that will be run when the app controller is called. """ command_parts = [] cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) if self._command is None: raise ApplicationError('_command has not been set.') command = self._command parameters = sorted([str(x) for x in...
def _input_as_list(self, data): '''Takes the positional arguments as input in a list. The list input here should be [query_file_path, database_file_path, output_file_path]''' query, database, output = data if (not isabs(database)) \ or (not isabs(query)) \ or (not isabs(output)): raise ApplicationError("Only absolute p...
self._database_types: error_message = "Invalid database type %s\n" % \ self.Parameters['-t'].Value error_message += "Allowed values: %s\n" % \ ', '.join(self._database_types) raise ApplicationError(error_message) # check query type if self.Parameters['-q'].isOn() and \ self.Parameters['-q'].Value not in self._query_typ...
self._mask_types: error_message = "Invalid repeat type %s\n" % \ self.Parameters['-repeat'].Value error_message += "Allowed values: %s\n" % \ ', '.join(self._mask_types) raise ApplicationError(error_message) # check output format if self.Parameters['-out'].isOn() and \ self.Parameters['-out'].Value not in self._out_typ...
def woa_profile_from_dap(var, d, lat, lon, depth, cfg): """ Monthly Climatologic Mean and Standard Deviation from WOA, used either for temperature or salinity. INPUTS time: [day of the year] lat: [-90<lat<90] lon: [-180<lon<180] depth: [meters] Reads the WOA Monthly Climatology NetCDF file and returns the corresponding...
# dd = ma.masked_values(dataset.t_dd.t_dd[dn, :, yn, xn].reshape( # dataset['depth'].shape[0]), dataset.t_dd.attributes['_FillValue']) elif re.match("salinity\d?$", var): mn = ma.masked_values(dataset.s_mn.s_mn[dn, :, yn, xn].reshape( dataset['depth'].shape[0]), dataset.s_mn.attributes['_FillValue']) sd = ma.masked_val...
def woa_track_from_file(d, lat, lon, filename, varnames=None): """ Temporary solution: WOA for surface track """ d = np.asanyarray(d) lat = np.asanyarray(lat) lon = np.asanyarray(lon) lon[lon < 0] += 360 doy = np.array([int(dd.strftime('%j')) for dd in d]) nc = netCDF4.Dataset(expanduser(filename), 'r') if varnames is ...
def crop(self, doy, depth, lat, lon, var): """ Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the international date line. Accepts 0 to 360 and -1...
subset, dims
def interpolate(self, doy, depth, lat, lon, var): """ Interpolate each var on the coordinates requested """ subset, dims = self.crop(doy, depth, lat, lon, var) # Subset contains everything requested. No need to interpolate. if np.all([d in dims['time'] for d in doy]) & \ np.all([z in dims['depth'] for z in depth]) & \ ...
output[v] = subset[v][:, :, :, xn][:, :, yn][:, zn][dn] return output output = {} for v in var: output[v] = ma.masked_all( (doy.size, depth.size, lat.size, lon.size), dtype=subset[v].dtype) # These interpolators don't understand Masked Arrays, but do NaN if subset[v].dtype in ['int32']: subset[v] = subset[v].astype('f'...
(doy.size, dims['depth'].size, lat.size, lon.size), dtype=subset[v].dtype) for nt in range(doy.size): for nz in range(dims['depth'].size): data = subset[v][nt, nz] # The valid data idx = np.nonzero(~np.isnan(data)) if idx[0].size > 0: points = np.array([ dims['lat'][idx[0]], dims['lon'][idx[1]]]).T values = data[idx] #...
= out subset[v] = tmp # Interpolate on z same_depth = (np.shape(depth) == dims['depth'].shape) and \ np.allclose(depth, dims['depth']) if not same_depth: for v in list(subset.keys()): try: f = interp1d(dims['depth'], subset[v], axis=1, bounds_error=False) # interp1d does not handle Masked Arrays subset[v] = f(np.array(...
def count(cls, path=None, objtype=None, query=None, **kwargs): """ Like __init__, but simply returns the number of objects that match the query rather than returning the objects NOTE: The path and objtype parameters to this function are to allow use of the DatabaseCollection class directly. However, this class is inten...
dictionary specifying key-value pairs that the result must match. If query is None, use kwargs in it's place @param **kwargs: used as query parameters if query is None @raise Exception: if path, PATH, and OBJTYPE.PATH are all None; the database path must be defined in at least one of these """ if not objtype: objtype =...
def iterator(cls, path=None, objtype=None, query=None, page_size=1000, **kwargs): """" Linear time, constant memory, iterator for a mongo collection. @param path: the path of the database to query, in the form "database.colletion"; pass None to use the value of the PATH property of the object or, if that is none, the P...
cls.PATH db = objtype.db(path) if not query: query = kwargs results = list(db.find(query).sort(ID_KEY, ASCENDING).limit(page_size)) while results: page = [objtype(path=path, _new_object=result) for result in results] for obj in page: yield obj query[ID_KEY] = {GT: results[-1][ID_KEY]} results = list(db.find(query).sort...
def insert(self, data, **kwargs): """ Calls the create method of OBJTYPE NOTE: this function is only properly usable on children classes that have overridden either OBJTYPE or PATH. @param data: the data of the new object to be created @param **kwargs: forwarded to create @raise DatabaseConflictError: if there is alrea...
def _move(self, new_path): """ Moves the collection to a different database path NOTE: this function is intended for command prompt use only. WARNING: if execution is interrupted halfway through, the collection will be split into multiple pieces. Furthermore, there is a possible duplication of the database object being...
def pair_hmm_align_unaligned_seqs(seqs, moltype=DNA_cogent, params={}): """ Checks parameters for pairwise alignment, returns alignment. Code from Greg Caporaso. """ seqs = LoadSeqs(data=seqs, moltype=moltype, aligned=False) try: s1, s2 = seqs.values() except ValueError: raise ValueError( "Pairwise aligning of seqs req...
async def viewers_js(request): ''' Viewers determines the viewers installed based on settings, then uses the conversion infrastructure to convert all these JS files into a single JS bundle, that is then served. As with media, it will simply serve a cached version if necessary. ''' # Generates single bundle as such: # B...
process if not viewers_resource.cache_exists(): viewers_resource.save() # Queue up a single function that will in turn queue up conversion process await singletons.workers.async_enqueue_sync( enqueue_conversion_path, url_string, str(target_ts), singletons.workers.enqueue_convert ) return response.text(NOT_LOADED_JS, he...
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None): """Returns a tree from alignment Will check MolType of aln object """ if params is None: params = {} if moltype == DNA or moltype == RNA: params['-nt'] = True elif moltype == PROTEIN: params['-nt'] = False else: raise ValueError, \ "FastTree...
def get_objects(self, uri, _oid=None, _start=None, _end=None, load_kwargs=None, **kwargs): ''' Load and transform csv data into a list of dictionaries. Each row in the csv will result in one dictionary in the list. :param uri: uri (file://, http(s)://) of csv file to load :param _oid: column or func to apply to map _oi...
_oid for each object generated. If either is a function, the function will be applied per each row and the result of the function will be assigned to the _start or _oid, respectively. ''' load_kwargs = load_kwargs or {} objects = load(path=uri, filetype='csv', **load_kwargs) k = itertools.count(1) now = utcnow() __oid ...
def getSpecs(self): """Get specs Returns: dict: Representation of the object """ content = { "databaseName" : self.databaseName, "roles" : self.roles, "username" : self.username, "password" : self.password } return content
def add_roles(self, databaseName, roleNames, collectionName=None): """Add multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection Raises: ErrRoleException: role not compatible with the databaseName and/or collectionName """ for roleName ...
def add_role(self, databaseName, roleName, collectionName=None): """Add one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection Raises: ErrRole: role not compatible with the databaseName and/or collectionName """ role = {"databaseName" : databaseName, "...
def remove_roles(self, databaseName, roleNames, collectionName=None): """Remove multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection """ for roleName in roleNames: self.remove_role(databaseName, roleName, collectionName)
def remove_role(self, databaseName, roleName, collectionName=None): """Remove one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection """ role = {"databaseName" : databaseName, "roleName" : roleName} if collectionName: role["collectionName"] = collectio...
def getSpecs(self): """Get specs Returns: dict: Representation of the object """ content = {} if len(self.roles) != 0: content["roles"] = self.roles if self.password: content["password"] = self.password return content
def sumaclust_denovo_cluster(seq_path=None, result_path=None, shortest_len=True, similarity=0.97, threads=1, exact=False, HALT_EXEC=False ): """ Function : launch SumaClust de novo OTU picker Parameters: seq_path, filepath to reads; result_path, filepath to output OTU map; shortest_len, boolean; similarity, the similar...
clustering (default: False) if exact: sumaclust.Parameters['-e'].on() # Turn off option for reference sequence length to be the shortest if not shortest_len: sumaclust.Parameters['-l'].off() # Set the number of threads if threads > 0: sumaclust.Parameters['-p'].on(threads) else: raise ValueError("Number of threads must...