text
stringlengths
81
112k
Updates the mode/owner/group for the remote file at the given location. def file_attribs(location, mode=None, owner=None, group=None, use_sudo=False, recursive=True): """Updates the mode/owner/group for the remote file at the ...
returns /etc/os-release in a dictionary def os_release(): """ returns /etc/os-release in a dictionary """ with settings(hide('warnings', 'running', 'stderr'), warn_only=True, capture=True): release = {} data = run('cat /etc/os-release') for line in data.split('\n'): ...
returns the linux distribution in lower case def linux_distribution(): """ returns the linux distribution in lower case """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): data = os_release() return(data['ID'])
returns /etc/lsb-release in a dictionary def lsb_release(): """ returns /etc/lsb-release in a dictionary """ with settings(hide('warnings', 'running'), capture=True): _lsb_release = {} data = sudo('cat /etc/lsb-release') for line in data.split('\n'): if not line: ...
restarts a service def restart_service(service, log=False): """ restarts a service """ with settings(): if log: bookshelf2.logging_helpers.log_yellow( 'stoping service %s' % service) sudo('service %s stop' % service) if log: bookshelf2.logging_he...
manipulates systemd services def systemd(service, start=True, enabled=True, unmask=False, restart=False): """ manipulates systemd services """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): if restart: sudo('systemctl restar...
installs OS updates def install_os_updates(distribution, force=False): """ installs OS updates """ if ('centos' in distribution or 'rhel' in distribution or 'redhat' in distribution): bookshelf2.logging_helpers.log_green('installing OS updates') sudo("yum -y --quiet clea...
Return a human readable ANSI-terminal printout of the stats. width Custom width for the graph (in characters). height Custom height for the graph (in characters). def ansi_format( self, width=64, height=12 ): """Return a human readable ANSI-terminal printout of the sta...
Updates this task whitelist on the saltant server. Returns: :class:`saltant.models.task_whitelist.TaskWhitelist`: A task whitelist model instance representing the task whitelist just updated. def put(self): """Updates this task whitelist on the saltant serve...
Create a task whitelist. Args: name (str): The name of the task whitelist. description (str, optional): A description of the task whitelist. whitelisted_container_task_types (list, optional): A list of whitelisted container task type IDs. whitelis...
Partially updates a task whitelist on the saltant server. Args: id (int): The ID of the task whitelist. name (str, optional): The name of the task whitelist. description (str, optional): A description of the task whitelist. whitelisted_container_task_types (list,...
Enable sending logs to stderr. Useful for shell sessions. level Logging threshold, as defined in the logging module of the Python standard library. Defaults to 'WARNING'. def enable_logging( level='WARNING' ): """Enable sending logs to stderr. Useful for shell sessions. level Logg...
Iterate through every location a substring can be found in a source string. source The source string to search. start Start offset to read from (default: start) end End offset to stop reading at (default: end) overlap Whether to return overlapping matches (default: fa...
Return every location a substring can be found in a source string. source The source string to search. start Start offset to read from (default: start) end End offset to stop reading at (default: end) overlap Whether to return overlapping matches (default: false) def...
Perform a basic diff between two equal-sized binary strings and return a list of (offset, size) tuples denoting the differences. source1 The first byte string source. source2 The second byte string source. start Start offset to read from (default: start) end End o...
Return the contents of a byte string in tabular hexadecimal/ASCII format. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) ...
Print the contents of a byte string in tabular hexadecimal/ASCII format. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) ...
Returns the differences between two byte strings in tabular hexadecimal/ASCII format. source1 The first byte string source. source2 The second byte string source. start Start offset to read from (default: start) end End offset to stop reading at (default: end) le...
Returns the differences between two byte strings in tabular hexadecimal/ASCII format. source1 The first byte string source. source2 The second byte string source. start Start offset to read from (default: start) end End offset to stop reading at (default: end) le...
Expand a bitfield into a 64-bit int (8 bool bytes). def unpack_bits( byte ): """Expand a bitfield into a 64-bit int (8 bool bytes).""" longbits = byte & (0x00000000000000ff) longbits = (longbits | (longbits<<28)) & (0x0000000f0000000f) longbits = (longbits | (longbits<<14)) & (0x0003000300030003) l...
Crunch a 64-bit int (8 bool bytes) into a bitfield. def pack_bits( longbits ): """Crunch a 64-bit int (8 bool bytes) into a bitfield.""" byte = longbits & (0x0101010101010101) byte = (byte | (byte>>7)) & (0x0003000300030003) byte = (byte | (byte>>14)) & (0x0000000f0000000f) byte = (byte | (byte>>28...
Return the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) width Wi...
Print the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) width Wid...
Set the current read offset (in bytes) for the instance. def set_offset( self, offset ): """Set the current read offset (in bytes) for the instance.""" assert offset in range( len( self.buffer ) ) self.pos = offset self._fill_buffer()
Get an integer containing the next [count] bits from the source. def get_bits( self, count ): """Get an integer containing the next [count] bits from the source.""" result = 0 for i in range( count ): if self.bits_remaining <= 0: self._fill_buffer() if se...
Push bits into the target. value Integer containing bits to push, ordered from least-significant bit to most-significant bit. count Number of bits to push to the target. def put_bits( self, value, count ): """Push bits into the target. value ...
Return a byte string containing the target as currently written. def get_buffer( self ): """Return a byte string containing the target as currently written.""" last_byte = self.current_bits if (self.bits_remaining < 8) else None result = self.output if last_byte is not None: ...
http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=update#sqlalchemy.orm.query.Query.with_for_update # noqa def get_for_update(self, connection_name='DEFAULT', **kwargs): """ http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=update#sqlalchemy.orm.query.Query.with_for_update # ...
Syllabify the given word, whether simplex or complex. def syllabify(word, compound=None): '''Syllabify the given word, whether simplex or complex.''' if compound is None: compound = bool(re.search(r'(-| |=)', word)) syllabify = _syllabify_compound if compound else _syllabify syll, rules = syll...
Converts name from CamelCase to snake_case def convert_case(name): """Converts name from CamelCase to snake_case""" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Pluralises the class_name using utterly simple algo and returns as table_name def table_name(self): """Pluralises the class_name using utterly simple algo and returns as table_name""" if not self.class_name: raise ValueError else: tbl_name = ModelCompiler.convert_case(se...
All the unique types found in user supplied model def types(self): """All the unique types found in user supplied model""" res = [] for column in self.column_definitions: tmp = column.get('type', None) res.append(ModelCompiler.get_column_type(tmp)) if tmp else False ...
Returns non-postgres types referenced in user supplied model def basic_types(self): """Returns non-postgres types referenced in user supplied model """ if not self.foreign_key_definitions: return self.standard_types else: tmp = self.standard_types tmp.append(...
Returns the primary keys referenced in user supplied model def primary_keys(self): """Returns the primary keys referenced in user supplied model""" res = [] for column in self.column_definitions: if 'primary_key' in column.keys(): tmp = column.get('primary_key', None...
Returns compiled named imports required for the model def compiled_named_imports(self): """Returns compiled named imports required for the model""" res = [] if self.postgres_types: res.append( ALCHEMY_TEMPLATES.named_import.safe_substitute( module...
Returns compiled named imports required for the model def compiled_orm_imports(self): """Returns compiled named imports required for the model""" module = 'sqlalchemy.orm' labels = [] if self.relationship_definitions: labels.append("relationship") return ALCHEMY_TEMP...
Returns compiled column definitions def compiled_columns(self): """Returns compiled column definitions""" def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type'): if arg_name in ('ser...
Returns compiled foreign key definitions def compiled_foreign_keys(self): """Returns compiled foreign key definitions""" def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type', 'reference'): ...
Returns compiled relationship definitions def compiled_relationships(self): """Returns compiled relationship definitions""" def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type', 'reference', 'class'): ...
Return names of all the addressable columns (including foreign keys) referenced in user supplied model def columns(self): """Return names of all the addressable columns (including foreign keys) referenced in user supplied model""" res = [col['name'] for col in self.column_definitions] res.exten...
Returns compiled init function def compiled_init_func(self): """Returns compiled init function""" def get_column_assignment(column_name): return ALCHEMY_TEMPLATES.col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): return ALCHEMY_TEMPL...
Returns compiled update function def compiled_update_func(self): """Returns compiled update function""" def get_not_none_col_assignment(column_name): return ALCHEMY_TEMPLATES.not_none_col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): ...
Returns compiled hash function based on hash of stringified primary_keys. This isn't the most efficient way def compiled_hash_func(self): """Returns compiled hash function based on hash of stringified primary_keys. This isn't the most efficient way""" def get_primary_key_str(pkey_name)...
Generic function can be used to compile __repr__ or __unicode__ or __str__ def representation_function_compiler(self, func_name): """Generic function can be used to compile __repr__ or __unicode__ or __str__""" def get_col_accessor(col): return ALCHEMY_TEMPLATES.col_accessor.safe_substitut...
Returns compile ORM class for the user supplied model def compiled_model(self): """Returns compile ORM class for the user supplied model""" return ALCHEMY_TEMPLATES.model.safe_substitute(class_name=self.class_name, table_name=self.table_name, ...
Updates this task queue on the saltant server. Returns: :class:`saltant.models.task_queue.TaskQueue`: A task queue model instance representing the task queue just updated. def put(self): """Updates this task queue on the saltant server. Returns: ...
Get a task queue. Either the id xor the name of the task type must be specified. Args: id (int, optional): The id of the task type to get. name (str, optional): The name of the task type to get. Returns: :class:`saltant.models.task_queue.TaskQueue`: ...
Create a task queue. Args: name (str): The name of the task queue. description (str, optional): A description of the task queue. private (bool, optional): A boolean specifying whether the queue is exclusive to its creator. Defaults to False. runs_...
Partially updates a task queue on the saltant server. Args: id (int): The ID of the task queue. name (str, optional): The name of the task queue. description (str, optional): The description of the task queue. private (bool, optional): A Booleon s...
Updates a task queue on the saltant server. Args: id (int): The ID of the task queue. name (str): The name of the task queue. description (str): The description of the task queue. private (bool): A Booleon signalling whether the queue can only be ...
Run the required methods in the appropriate order def main(self): """ Run the required methods in the appropriate order """ self.targets() self.bait(k=49) self.reversebait(maskmiddle='t', k=19) self.subsample_reads()
Create the GenObject for the analysis type, create the hash file for baiting (if necessary) def targets(self): """ Create the GenObject for the analysis type, create the hash file for baiting (if necessary) """ for sample in self.runmetadata: if sample.general.bestassemblyfi...
Using the data from the BLAST analyses, set the targets folder, and create the 'mapping file'. This is the genera-specific FASTA file that will be used for all the reference mapping; it replaces the 'bait file' in the code def targets(self): """ Using the data from the BLAST analyses, s...
Run the necessary methods in the correct order def runner(self): """ Run the necessary methods in the correct order """ logging.info('Starting {} analysis pipeline'.format(self.analysistype)) if not self.pipeline: # If the metadata has been passed from the method scr...
Subsample 1000 reads from the baited files def subsample(self): """ Subsample 1000 reads from the baited files """ # Create the threads for the analysis logging.info('Subsampling FASTQ reads') for _ in range(self.cpus): threads = Thread(target=self.subsamplet...
Convert the subsampled reads to FASTA format using reformat.sh def fasta(self): """ Convert the subsampled reads to FASTA format using reformat.sh """ logging.info('Converting FASTQ files to FASTA format') # Create the threads for the analysis for _ in range(self.cpus): ...
Makes blast database files from targets as necessary def makeblastdb(self): """ Makes blast database files from targets as necessary """ # Iterate through the samples to set the bait file. for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != ...
Run BLAST analyses of the subsampled FASTQ reads against the NCBI 16S reference database def blast(self): """ Run BLAST analyses of the subsampled FASTQ reads against the NCBI 16S reference database """ logging.info('BLASTing FASTA files against {} database'.format(self.analysistype)) ...
Parse the blast results, and store necessary data in dictionaries in sample object def blastparse(self): """ Parse the blast results, and store necessary data in dictionaries in sample object """ logging.info('Parsing BLAST results') # Load the NCBI 16S reference database as a d...
Creates a report of the results def reporter(self): """ Creates a report of the results """ # Create the path in which the reports are stored make_path(self.reportpath) logging.info('Creating {} report'.format(self.analysistype)) # Initialise the header and data ...
添加观察者函数。 :params evt_name: 事件名称 :params fn: 要注册的触发函数函数 .. note:: 允许一个函数多次注册,多次注册意味着一次 :func:`fire_event` 多次调用。 def add_listener(self, evt_name, fn): """添加观察者函数。 :params evt_name: 事件名称 :params fn: 要注册的触发函数函数 .. note:: 允许一个函数多次注册,多次注册意味着一次...
删除观察者函数。 :params evt_name: 事件名称 :params fn: 要注册的触发函数函数 :params remove_all: 是否删除fn在evt_name中的所有注册\n 如果为 `True`,则删除所有\n 如果为 `False`,则按注册先后顺序删除第一个\n .. note:: 允许一个函数多次注册,多次注册意味着一次时间多次调用。 def remove_listener(self, evt_name...
指定listener是否存在 :params evt_name: 事件名称 :params fn: 要注册的触发函数函数 def has_listener(self, evt_name, fn): """指定listener是否存在 :params evt_name: 事件名称 :params fn: 要注册的触发函数函数 """ listeners = self.__get_listeners(evt_name) return fn in listeners
触发事件 :params evt_name: 事件名称 :params args: 给事件接受者的参数 :params kwargs: 给事件接受者的参数 def fire_event(self, evt_name, *args, **kwargs): """触发事件 :params evt_name: 事件名称 :params args: 给事件接受者的参数 :params kwargs: 给事件接受者的参数 """ listeners = self.__get_listeners(...
Creates EC2 Instance def create_server_ec2(connection, region, disk_name, disk_size, ami, key_pair, instance_type, tags={}, security_groups=Non...
destroys an ebs volume def destroy_ebs_volume(connection, region, volume_id, log=False): """ destroys an ebs volume """ if ebs_volume_exists(connection, region, volume_id): if log: log_yellow('destroying EBS volume ...') try: connection.delete_volume(volume_id) ...
terminates the instance def destroy_ec2(connection, region, instance_id, log=False): """ terminates the instance """ data = get_ec2_info(connection=connection, instance_id=instance_id, region=region) instance = connection.terminate_instances(instance_ids=[d...
shutdown of an existing EC2 instance def down_ec2(connection, instance_id, region, log=False): """ shutdown of an existing EC2 instance """ # get the instance_id from the state file, and stop the instance instance = connection.stop_instances(instance_ids=instance_id)[0] while instance.state != "stopped...
finds out if a ebs volume exists def ebs_volume_exists(connection, region, volume_id): """ finds out if a ebs volume exists """ for vol in connection.get_all_volumes(): if vol.id == volume_id: return True return False
queries EC2 for details about a particular instance_id def get_ec2_info(connection, instance_id, region, username=None): """ queries EC2 for details about a particular instance_id """ instance = connection.get_only_instances( filters={'instance_id'...
boots an existing ec2_instance def up_ec2(connection, region, instance_id, wait_for_ssh_available=True, log=False, timeout=600): """ boots an existing ec2_instance """ # boot the ec2 instance instance = connection.start_instances(instance_ids=instance...
An agglutination diphthong that ends in /u, y/ usually contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa]. def apply_T4(word): '''An agglutination diphthong that ends in /u, y/ usually contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va....
Extract sequences from a file Name: seqs_from_file Author(s): Martin C F Thomsen Date: 18 Jul 2013 Description: Iterator which extract sequence data from the input file Args: filename: string which contain a path to the input file Supported Formats: fasta, fastq...
Switch for both open() and gzip.open(). Determines if the file is normal or gzipped by looking at the file extension. The filename argument is required; mode defaults to 'rb' for gzip and 'r' for normal and compresslevel defaults to 9 for gzip. >>> import gzip >>> from contextlib import cl...
Load json from file or file name def load_json(json_object): ''' Load json from file or file name ''' content = None if isinstance(json_object, str) and os.path.exists(json_object): with open_(json_object) as f: try: content = json.load(f) except Exception as e: ...
Sort an array of strings to groups by patterns def sort2groups(array, gpat=['_R1','_R2']): """ Sort an array of strings to groups by patterns """ groups = [REGroup(gp) for gp in gpat] unmatched = [] for item in array: matched = False for m in groups: if m.match(item): match...
Sort an array of strings to groups by alphabetically continuous distribution def sort_and_distribute(array, splits=2): """ Sort an array of strings to groups by alphabetically continuous distribution """ if not isinstance(array, (list,tuple)): raise TypeError("array must be a list") if not is...
This function executes a mkdir command for filepath and with permissions (octal number with leading 0 or string only) # eg. mkpath("path/to/file", "0o775") def mkpath(filepath, permissions=0o777): """ This function executes a mkdir command for filepath and with permissions (octal number with leading 0 or s...
This function creates a zipfile located in zipFilePath with the files in the file list # fileList can be both a comma separated list or an array def create_zip_dir(zipfile_path, *file_list): """ This function creates a zipfile located in zipFilePath with the files in the file list # fileList can be both...
This function will zip the files created in the runroot directory and subdirectories def file_zipper(root_dir): """ This function will zip the files created in the runroot directory and subdirectories """ # FINDING AND ZIPPING UNZIPPED FILES for root, dirs, files in os.walk(root_dir, topdown=False): ...
This function will unzip all files in the runroot directory and subdirectories def file_unzipper(directory): """ This function will unzip all files in the runroot directory and subdirectories """ debug.log("Unzipping directory (%s)..."%directory) #FINDING AND UNZIPPING ZIPPED FILES for root, dirs,...
this function will simply move the file from the source path to the dest path given as input def move_file(src, dst): """ this function will simply move the file from the source path to the dest path given as input """ # Sanity checkpoint src = re.sub('[^\w/\-\.\*]', '', src) dst = re.sub('[^\w/\-...
this function will simply copy the file from the source path to the dest path given as input def copy_file(src, dst, ignore=None): """ this function will simply copy the file from the source path to the dest path given as input """ # Sanity checkpoint src = re.sub('[^\w/\-\.\*]', '', src) dst = re...
this function will simply copy the file from the source path to the dest path given as input def copy_dir(src, dst): """ this function will simply copy the file from the source path to the dest path given as input """ try: debug.log("copy dir from "+ src, "to "+ dst) shutil.copytree(src, dst...
Print list of strings to the predefined stdout. def print_out(self, *lst): """ Print list of strings to the predefined stdout. """ self.print2file(self.stdout, True, True, *lst)
Print list of strings to the predefined stdout. def print_err(self, *lst): """ Print list of strings to the predefined stdout. """ self.print2file(self.stderr, False, True, *lst)
This function prints to the screen and logs to a file, all the strings given. # print2screen eg. True, *lst is a commaseparated list of strings def print2file(self, logfile, print2screen, addLineFeed, *lst): """ This function prints to the screen and logs to a file, all the strings given. ...
Print list of strings to the predefined logfile if debug is set. and sets the caught_error message if an error is found def log(self, *lst): """ Print list of strings to the predefined logfile if debug is set. and sets the caught_error message if an error is found """ self.print2file(self...
print the message to the predefined log file without newline def log_no_newline(self, msg): """ print the message to the predefined log file without newline """ self.print2file(self.logfile, False, False, msg)
This function Tries to update the MSQL database before exiting. def graceful_exit(self, msg): """ This function Tries to update the MSQL database before exiting. """ # Print stored errors to stderr if self.caught_error: self.print2file(self.stderr, False, False, self.caught_error) # Ki...
gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1', 'key2'] USAGE >>> # Access the value for key2 within the nested dictionary >>> adv_dict({'key1': {'key2': 'value'}}).gettree(['key1', 'key2']) 'value' def get_tree(self, list_...
Return inverse mapping of dictionary with sorted values. USAGE >>> # Switch the keys and values >>> adv_dict({ ... 'A': [1, 2, 3], ... 'B': [4, 2], ... 'C': [1, 4], ... }).invert() {1: ['A', 'C'], 2: ['A', 'B'], 3: ['A'], 4: ['B', 'C']} d...
returns new string where the matching cases (limited by the count) in the string is replaced. def sub(self, replace, string, count=0): """ returns new string where the matching cases (limited by the count) in the string is replaced. """ return self.re.sub(replace, string, count)
Matches the string to the stored regular expression, and stores all groups in mathches. Returns False on negative match. def match(self, s): """ Matches the string to the stored regular expression, and stores all groups in mathches. Returns False on negative match. """ self.matches = self.re.se...
Matching the pattern to the input string, returns True/False and saves the matched string in the internal list def match(self, s): """ Matching the pattern to the input string, returns True/False and saves the matched string in the internal list """ if self.re.match(s): s...
Create the MASH report def reporter(self): """ Create the MASH report """ logging.info('Creating {} report'.format(self.analysistype)) make_path(self.reportpath) header = 'Strain,ReferenceGenus,ReferenceFile,ReferenceGenomeMashDistance,Pvalue,NumMatchingHashes\n' ...
Take a full path to a python method or class, for example mypkg.subpkg.method and return the method or class (after importing the required packages) def get_function(pkgpath): """Take a full path to a python method or class, for example mypkg.subpkg.method and return the method or class (after importin...
Run the necessary methods in the correct order def runner(self): """ Run the necessary methods in the correct order """ printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime) # Create the objects to be used in the analyses objects = Objectpr...
Syllabify the given word, whether simplex or complex. def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' word = split(word) # detect any non-delimited compounds compound = True if re.search(r'-| |\.', word) else False syllabify = _syllabify_compound if compound else _syll...
Return the edge characters of this node. def edges(self): """ Return the edge characters of this node. """ edge_str = ctypes.create_string_buffer(MAX_CHARS) cgaddag.gdg_edges(self.gdg, self.node, edge_str) return [char for char in edge_str.value.decode("ascii")]