sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def property_set( prop, instance, value, **kwargs ): """Wrapper for property writes which auto-deferences Refs. prop A Ref (which gets dereferenced and the target value set). instance The context object used to dereference the Ref. value The value to set the property to. ...
Wrapper for property writes which auto-deferences Refs. prop A Ref (which gets dereferenced and the target value set). instance The context object used to dereference the Ref. value The value to set the property to. Throws AttributeError if prop is not a Ref.
entailment
def view_property( prop ): """Wrapper for attributes of a View class which auto-dereferences Refs. Equivalent to setting a property on the class with the getter wrapped with property_get(), and the setter wrapped with property_set(). prop A string containing the name of the class attribute...
Wrapper for attributes of a View class which auto-dereferences Refs. Equivalent to setting a property on the class with the getter wrapped with property_get(), and the setter wrapped with property_set(). prop A string containing the name of the class attribute to wrap.
entailment
def get( self, instance, **kwargs ): """Return an attribute from an object using the Ref path. instance The object instance to traverse. """ target = instance for attr in self._path: target = getattr( target, attr ) return target
Return an attribute from an object using the Ref path. instance The object instance to traverse.
entailment
def set( self, instance, value, **kwargs ): """Set an attribute on an object using the Ref path. instance The object instance to traverse. value The value to set. Throws AttributeError if allow_write is False. """ if not self._allow_write: ...
Set an attribute on an object using the Ref path. instance The object instance to traverse. value The value to set. Throws AttributeError if allow_write is False.
entailment
def traverse_until_fixpoint(predicate, tree): """Traverses the tree again and again until it is not modified.""" old_tree = None tree = simplify(tree) while tree and old_tree != tree: old_tree = tree tree = tree.traverse(predicate) if not tree: return None tre...
Traverses the tree again and again until it is not modified.
entailment
def runner(self): """ Run the necessary methods in the correct order """ logging.info('Starting {} analysis pipeline'.format(self.analysistype)) # Initialise the GenObject for sample in self.runmetadata.samples: setattr(sample, self.analysistype, GenObject()) ...
Run the necessary methods in the correct order
entailment
def fasta(self): """ Create FASTA files of the PointFinder results to be fed into PointFinder """ logging.info('Extracting FASTA sequences matching PointFinder database') for sample in self.runmetadata.samples: # Ensure that there are sequence data to extract from the...
Create FASTA files of the PointFinder results to be fed into PointFinder
entailment
def run_pointfinder(self): """ Run PointFinder on the FASTA sequences extracted from the raw reads """ logging.info('Running PointFinder on FASTA files') for i in range(len(self.runmetadata.samples)): # Start threads threads = Thread(target=self.pointfinde...
Run PointFinder on the FASTA sequences extracted from the raw reads
entailment
def populate_summary_dict(self, genus=str(), key=str()): """ :param genus: Non-supported genus to be added to the dictionary :param key: section of dictionary to be populated. Supported keys are: prediction, table, and results Populate self.summary_dict as required. If the genus is not p...
:param genus: Non-supported genus to be added to the dictionary :param key: section of dictionary to be populated. Supported keys are: prediction, table, and results Populate self.summary_dict as required. If the genus is not provided, populate the dictionary for Salmonella Escherichia and Campy...
entailment
def parse_pointfinder(self): """ Create summary reports for the PointFinder outputs """ # Create the nested dictionary that stores the necessary values for creating summary reports self.populate_summary_dict() # Clear out any previous reports for organism in self....
Create summary reports for the PointFinder outputs
entailment
def write_report(summary_dict, seqid, genus, key): """ Parse the PointFinder outputs, and write the summary report for the current analysis type :param summary_dict: nested dictionary containing data such as header strings, and paths to reports :param seqid: name of the strain, :...
Parse the PointFinder outputs, and write the summary report for the current analysis type :param summary_dict: nested dictionary containing data such as header strings, and paths to reports :param seqid: name of the strain, :param genus: MASH-calculated genus of current isolate :param ke...
entailment
def write_table_report(summary_dict, seqid, genus): """ Parse the PointFinder table output, and write a summary report :param summary_dict: nested dictionary containing data such as header strings, and paths to reports :param seqid: name of the strain, :param genus: MASH-calculat...
Parse the PointFinder table output, and write a summary report :param summary_dict: nested dictionary containing data such as header strings, and paths to reports :param seqid: name of the strain, :param genus: MASH-calculated genus of current isolate
entailment
def targets(self): """ Search the targets folder for FASTA files, create the multi-FASTA file of all targets if necessary, and populate objects """ logging.info('Performing analysis with {} targets folder'.format(self.analysistype)) for sample in self.runmetadata: ...
Search the targets folder for FASTA files, create the multi-FASTA file of all targets if necessary, and populate objects
entailment
def strains(self): """ Create a dictionary of SEQID: OLNID from the supplied """ with open(os.path.join(self.path, 'strains.csv')) as strains: next(strains) for line in strains: oln, seqid = line.split(',') self.straindict[oln] = se...
Create a dictionary of SEQID: OLNID from the supplied
entailment
def sequence_prep(self): """ Create metadata objects for all PacBio assembly FASTA files in the sequencepath. Create individual subdirectories for each sample. Relative symlink the original FASTA file to the appropriate subdirectory """ # Create a sorted list of all the...
Create metadata objects for all PacBio assembly FASTA files in the sequencepath. Create individual subdirectories for each sample. Relative symlink the original FASTA file to the appropriate subdirectory
entailment
def write_json(metadata): """ Write the metadata object to file :param metadata: Metadata object """ # Open the metadata file to write with open(metadata.jsonfile, 'w') as metadatafile: # Write the json dump of the object dump to the metadata file ...
Write the metadata object to file :param metadata: Metadata object
entailment
def read_json(json_metadata): """ Read the metadata object from file :param json_metadata: Path and file name of JSON-formatted metadata object file :return: metadata object """ # Load the metadata object from the file with open(json_metadata) as metadatareport: ...
Read the metadata object from file :param json_metadata: Path and file name of JSON-formatted metadata object file :return: metadata object
entailment
def assembly_length(self): """ Use SeqIO.parse to extract the total number of bases in each assembly file """ for sample in self.metadata: # Only determine the assembly length if is has not been previously calculated if not GenObject.isattr(sample, 'assembly_lengt...
Use SeqIO.parse to extract the total number of bases in each assembly file
entailment
def simulate_reads(self): """ Use the PacBio assembly FASTA files to generate simulated reads of appropriate forward and reverse lengths at different depths of sequencing using randomreads.sh from the bbtools suite """ logging.info('Read simulation') for sample in self.me...
Use the PacBio assembly FASTA files to generate simulated reads of appropriate forward and reverse lengths at different depths of sequencing using randomreads.sh from the bbtools suite
entailment
def read_length_adjust(self, analysistype): """ Trim the reads to the correct length using reformat.sh :param analysistype: current analysis type. Will be either 'simulated' or 'sampled' """ logging.info('Trimming {at} reads'.format(at=analysistype)) for sample in self.me...
Trim the reads to the correct length using reformat.sh :param analysistype: current analysis type. Will be either 'simulated' or 'sampled'
entailment
def read_quality_trim(self): """ Perform quality trim, and toss reads below appropriate thresholds """ logging.info('Quality trim') for sample in self.metadata: sample.sampled_reads = GenObject() sample.sampled_reads.outputdir = os.path.join(sample.outputd...
Perform quality trim, and toss reads below appropriate thresholds
entailment
def sample_reads(self): """ For each PacBio assembly, sample reads from corresponding FASTQ files for appropriate forward and reverse lengths and sequencing depths using reformat.sh from the bbtools suite """ logging.info('Read sampling') for sample in self.metadata: ...
For each PacBio assembly, sample reads from corresponding FASTQ files for appropriate forward and reverse lengths and sequencing depths using reformat.sh from the bbtools suite
entailment
def link_reads(self, analysistype): """ Create folders with relative symlinks to the desired simulated/sampled reads. These folders will contain all the reads created for each sample, and will be processed with GeneSippr and COWBAT pipelines :param analysistype: Current analysis type. Wi...
Create folders with relative symlinks to the desired simulated/sampled reads. These folders will contain all the reads created for each sample, and will be processed with GeneSippr and COWBAT pipelines :param analysistype: Current analysis type. Will either be 'simulated' or 'sampled'
entailment
def run_genesippr(self): """ Run GeneSippr on each of the samples """ from pathlib import Path home = str(Path.home()) logging.info('GeneSippr') # These unfortunate hard coded paths appear to be necessary miniconda_path = os.path.join(home, 'miniconda3') ...
Run GeneSippr on each of the samples
entailment
def set_level(self, level): """ Set the logging level of this logger. :param level: must be an int or a str. """ for handler in self.__coloredlogs_handlers: handler.setLevel(level=level) self.logger.setLevel(level=level)
Set the logging level of this logger. :param level: must be an int or a str.
entailment
def disable_logger(self, disabled=True): """ Disable all logging calls. """ # Disable standard IO streams if disabled: sys.stdout = _original_stdout sys.stderr = _original_stderr else: sys.stdout = self.__stdout_stream sys.s...
Disable all logging calls.
entailment
def redirect_stdout(self, enabled=True, log_level=logging.INFO): """ Redirect sys.stdout to file-like object. """ if enabled: if self.__stdout_wrapper: self.__stdout_wrapper.update_log_level(log_level=log_level) else: self.__stdout_...
Redirect sys.stdout to file-like object.
entailment
def redirect_stderr(self, enabled=True, log_level=logging.ERROR): """ Redirect sys.stderr to file-like object. """ if enabled: if self.__stderr_wrapper: self.__stderr_wrapper.update_log_level(log_level=log_level) else: self.__stderr...
Redirect sys.stderr to file-like object.
entailment
def use_file(self, enabled=True, file_name=None, level=logging.WARNING, when='d', interval=1, backup_count=30, delay=False, utc=False, at_time=None, log_format=None, ...
Handler for logging to a file, rotating the log file at certain timed intervals.
entailment
def use_loggly(self, enabled=True, loggly_token=None, loggly_tag=None, level=logging.WARNING, log_format=None, date_format=None): """ Enable handler for sending the record to Loggly service. """ ...
Enable handler for sending the record to Loggly service.
entailment
def __find_caller(stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ frame = logging.currentframe() # On some versions of IronPython, currentframe() returns None if # IronPython is...
Find the stack frame of the caller so that we can note the source file name, line number and function name.
entailment
def _log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ ...
Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
entailment
def flush(self): """ Flush the buffer, if applicable. """ if self.__buffer.tell() > 0: # Write the buffer to log # noinspection PyProtectedMember self.__logger._log(level=self.__log_level, msg=self.__buffer.getvalue().strip(), ...
Flush the buffer, if applicable.
entailment
def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' compound = bool(re.search(r'(-| |=)', word)) syllabify = _syllabify_compound if compound else _syllabify syllabifications = list(syllabify(word)) for syll, rules in syllabifications: yield syll, rules n = ...
Syllabify the given word, whether simplex or complex.
entailment
def apply_T4(word): '''An agglutination diphthong that ends in /u, y/ optionally contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa].''' WORD = word.split('.') PARTS = [[] for part in range(len(WORD))] for i, v in enumerate(WORD): # i % 2 != 0 preven...
An agglutination diphthong that ends in /u, y/ optionally contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa].
entailment
def setup(product_name): """Setup logging.""" if CONF.log_config: _load_log_config(CONF.log_config) else: _setup_logging_from_conf() sys.excepthook = _create_logging_excepthook(product_name)
Setup logging.
entailment
def format(self, record): """Uses contextstring if request_id is set, otherwise default.""" # NOTE(sdague): default the fancier formating params # to an empty string so we don't throw an exception if # they get used for key in ('instance', 'color'): if key not in reco...
Uses contextstring if request_id is set, otherwise default.
entailment
def formatException(self, exc_info, record=None): """Format exception output with CONF.logging_exception_prefix.""" if not record: return logging.Formatter.formatException(self, exc_info) stringbuffer = cStringIO.StringIO() traceback.print_exception(exc_info[0], exc_info[1],...
Format exception output with CONF.logging_exception_prefix.
entailment
def _set_boutons_interface(self, buttons): """Display buttons given by the list of tuples (id,function,description,is_active)""" for id_action, f, d, is_active in buttons: icon = self.get_icon(id_action) action = self.addAction(QIcon(icon), d) action.setEnabled(is_act...
Display buttons given by the list of tuples (id,function,description,is_active)
entailment
def set_interface(self, interface): """Add update toolbar callback to the interface""" self.interface = interface self.interface.callbacks.update_toolbar = self._update self._update()
Add update toolbar callback to the interface
entailment
def _update(self): """Update the display of button after querying data from interface""" self.clear() self._set_boutons_communs() if self.interface: self.addSeparator() l_actions = self.interface.get_actions_toolbar() self._set_boutons_interface(l_acti...
Update the display of button after querying data from interface
entailment
def init_login(self, from_local=False): """Display login screen. May ask for local data loading if from_local is True.""" if self.toolbar: self.removeToolBar(self.toolbar) widget_login = login.Loading(self.statusBar(), self.theory_main) self.centralWidget().addWidget(widget_l...
Display login screen. May ask for local data loading if from_local is True.
entailment
def make_response(self, status, content_type, response): """Shortcut for making a response to the client's request.""" headers = [('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'), ('Access-Control-Allow-Headers', 'Content-...
Shortcut for making a response to the client's request.
entailment
def process_request(self, request): """Processes a request.""" try: request = Request.from_json(request.read().decode()) except ValueError: raise ClientError('Data is not valid JSON.') except KeyError: raise ClientError('Missing mandatory field in requ...
Processes a request.
entailment
def on_post(self): """Extracts the request, feeds the module, and returns the response.""" request = self.environ['wsgi.input'] try: return self.process_request(request) except ClientError as exc: return self.on_client_error(exc) except BadGateway as exc: ...
Extracts the request, feeds the module, and returns the response.
entailment
def dispatch(self): """Handles dispatching of the request.""" method_name = 'on_' + self.environ['REQUEST_METHOD'].lower() method = getattr(self, method_name, None) if method: return method() else: return self.on_bad_method()
Handles dispatching of the request.
entailment
def sync(self): """Sync this model with latest data on the saltant server. Note that in addition to returning the updated object, it also updates the existing object. Returns: :class:`saltant.models.user.User`: This user instance after syncing. """ ...
Sync this model with latest data on the saltant server. Note that in addition to returning the updated object, it also updates the existing object. Returns: :class:`saltant.models.user.User`: This user instance after syncing.
entailment
def serialised( self ): """Tuple containing the contents of the Block.""" klass = self.__class__ return ((klass.__module__, klass.__name__), tuple( (name, field.serialise( self._field_data[name], parent=self ) ) for name, field in klass._fields.items()))
Tuple containing the contents of the Block.
entailment
def clone_data( self, source ): """Clone data from another Block. source Block instance to copy from. """ klass = self.__class__ assert isinstance( source, klass ) for name in klass._fields: self._field_data[name] = getattr( source, name )
Clone data from another Block. source Block instance to copy from.
entailment
def import_data( self, raw_buffer ): """Import data from a byte array. raw_buffer Byte array to import from. """ klass = self.__class__ if raw_buffer: assert common.is_bytes( raw_buffer ) # raw_buffer = memoryview( raw_buffer ) self._f...
Import data from a byte array. raw_buffer Byte array to import from.
entailment
def export_data( self ): """Export data to a byte array.""" klass = self.__class__ output = bytearray( b'\x00'*self.get_size() ) # prevalidate all data before export. # this is important to ensure that any dependent fields # are updated beforehand, e.g. a count referenc...
Export data to a byte array.
entailment
def update_deps( self ): """Update dependencies on all the fields on this Block instance.""" klass = self.__class__ for name in klass._fields: self.update_deps_on_field( name ) return
Update dependencies on all the fields on this Block instance.
entailment
def validate( self ): """Validate all the fields on this Block instance.""" klass = self.__class__ for name in klass._fields: self.validate_field( name ) return
Validate all the fields on this Block instance.
entailment
def get_size( self ): """Get the projected size (in bytes) of the exported data from this Block instance.""" klass = self.__class__ size = 0 for name in klass._fields: size = max( size, klass._fields[name].get_end_offset( self._field_data[name], parent=self ) ) for ch...
Get the projected size (in bytes) of the exported data from this Block instance.
entailment
def save(self, path, compressed=True, exist_ok=False): """ Save the GADDAG to file. Args: path: path to save the GADDAG to. compressed: compress the saved GADDAG using gzip. exist_ok: overwrite existing file at `path`. """ path = os.path.expan...
Save the GADDAG to file. Args: path: path to save the GADDAG to. compressed: compress the saved GADDAG using gzip. exist_ok: overwrite existing file at `path`.
entailment
def load(self, path): """ Load a GADDAG from file, replacing the words currently in this GADDAG. Args: path: path to saved GADDAG to be loaded. """ path = os.path.expandvars(os.path.expanduser(path)) gdg = cgaddag.gdg_load(path.encode("ascii")) if no...
Load a GADDAG from file, replacing the words currently in this GADDAG. Args: path: path to saved GADDAG to be loaded.
entailment
def starts_with(self, prefix): """ Find all words starting with a prefix. Args: prefix: A prefix to be searched for. Returns: A list of all words found. """ prefix = prefix.lower() found_words = [] res = cgaddag.gdg_starts_with(s...
Find all words starting with a prefix. Args: prefix: A prefix to be searched for. Returns: A list of all words found.
entailment
def contains(self, sub): """ Find all words containing a substring. Args: sub: A substring to be searched for. Returns: A list of all words found. """ sub = sub.lower() found_words = set() res = cgaddag.gdg_contains(self.gdg, sub...
Find all words containing a substring. Args: sub: A substring to be searched for. Returns: A list of all words found.
entailment
def ends_with(self, suffix): """ Find all words ending with a suffix. Args: suffix: A suffix to be searched for. Returns: A list of all words found. """ suffix = suffix.lower() found_words = [] res = cgaddag.gdg_ends_with(self.gd...
Find all words ending with a suffix. Args: suffix: A suffix to be searched for. Returns: A list of all words found.
entailment
def add_word(self, word): """ Add a word to the GADDAG. Args: word: A word to be added to the GADDAG. """ word = word.lower() if not (word.isascii() and word.isalpha()): raise ValueError("Invalid character in word '{}'".format(word)) wor...
Add a word to the GADDAG. Args: word: A word to be added to the GADDAG.
entailment
def formatLog(source="", level="", title="", data={}): """ Similar to format, but takes additional reserved params to promote logging best-practices :param level - severity of message - how bad is it? :param source - application context - where did it come from? :param title - brief description - what kind of ...
Similar to format, but takes additional reserved params to promote logging best-practices :param level - severity of message - how bad is it? :param source - application context - where did it come from? :param title - brief description - what kind of event happened? :param data - additional information - what...
entailment
def put(self): """Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ContainerTaskType`: A task type model instance representing the task type just updated. """ return self.manager.put( ...
Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ContainerTaskType`: A task type model instance representing the task type just updated.
entailment
def create( self, name, command_to_run, container_image, container_type, description="", logs_path="", results_path="", environment_variables=None, required_arguments=None, required_arguments_default_values=None, extra_data_...
Create a container task type. Args: name (str): The name of the task. command_to_run (str): The command to run to execute the task. container_image (str): The container name and tag. For example, ubuntu:14.04 for Docker; and docker://ubuntu:14:04 ...
entailment
def put( self, id, name, description, command_to_run, environment_variables, required_arguments, required_arguments_default_values, logs_path, results_path, container_image, container_type, extra_data_to_put=None, ...
Updates a task type on the saltant server. Args: id (int): The ID of the task type. name (str): The name of the task type. description (str): The description of the task type. command_to_run (str): The command to run to execute the task. environment_v...
entailment
def _strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', '0' and ''. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ('y',...
Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', '0' and ''. Raises ValueError if 'val' is anything else.
entailment
def _str_to_list(value, separator): """Convert a string to a list with sanitization.""" value_list = [item.strip() for item in value.split(separator)] value_list_sanitized = builtins.list(filter(None, value_list)) if len(value_list_sanitized) > 0: return value_list_sanitized else: ra...
Convert a string to a list with sanitization.
entailment
def write(name, value): """Write a raw env value. A ``None`` value clears the environment variable. Args: name: The environment variable name value: The value to write """ if value is not None: environ[name] = builtins.str(value) elif environ.get(name): del envi...
Write a raw env value. A ``None`` value clears the environment variable. Args: name: The environment variable name value: The value to write
entailment
def read(name, default=None, allow_none=False, fallback=None): """Read the raw env value. Read the raw environment variable or use the default. If the value is not found and no default is set throw an exception. Args: name: The environment variable name default: The default value to us...
Read the raw env value. Read the raw environment variable or use the default. If the value is not found and no default is set throw an exception. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the retur...
entailment
def str(name, default=None, allow_none=False, fallback=None): """Get a string based environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optio...
Get a string based environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional)
entailment
def bool(name, default=None, allow_none=False, fallback=None): """Get a boolean based environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. opt...
Get a boolean based environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional)
entailment
def int(name, default=None, allow_none=False, fallback=None): """Get a string environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) ...
Get a string environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional)
entailment
def list(name, default=None, allow_none=False, fallback=None, separator=','): """Get a list of strings or the default. The individual list elements are whitespace-stripped. Args: name: The environment variable name default: The default value to use if no environment variable is found ...
Get a list of strings or the default. The individual list elements are whitespace-stripped. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) separator: T...
entailment
def includeme(config): """this function adds some configuration for the application""" config.add_route('references', '/references') _add_referencer(config.registry) config.add_view_deriver(protected_resources.protected_view) config.add_renderer('json_item', json_renderer) config.scan()
this function adds some configuration for the application
entailment
def _add_referencer(registry): """ Gets the Referencer from config and adds it to the registry. """ referencer = registry.queryUtility(IReferencer) if referencer is not None: return referencer ref = registry.settings['urireferencer.referencer'] url = registry.settings['urireferencer....
Gets the Referencer from config and adds it to the registry.
entailment
def get_referencer(registry): """ Get the referencer class :rtype: pyramid_urireferencer.referencer.AbstractReferencer """ # Argument might be a config or request regis = getattr(registry, 'registry', None) if regis is None: regis = registry return regis.queryUtility(IReferencer...
Get the referencer class :rtype: pyramid_urireferencer.referencer.AbstractReferencer
entailment
def _connect_to_ec2(region, credentials): """ :param region: The region of AWS to connect to. :param EC2Credentials credentials: The credentials to use to authenticate with EC2. :return: a connection object to AWS EC2 """ conn = boto.ec2.connect_to_region( region, aws_ac...
:param region: The region of AWS to connect to. :param EC2Credentials credentials: The credentials to use to authenticate with EC2. :return: a connection object to AWS EC2
entailment
def write(self, *args, **kwargs): """ :param args: tuple(value, style), tuple(value, style) :param kwargs: header=tuple(value, style), header=tuple(value, style) :param args: value, value :param kwargs: header=value, header=value """ if args: kwargs =...
:param args: tuple(value, style), tuple(value, style) :param kwargs: header=tuple(value, style), header=tuple(value, style) :param args: value, value :param kwargs: header=value, header=value
entailment
def clear_layout(layout: QLayout) -> None: """Clear the layout off all its components""" if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: widget.deleteLater() else: ...
Clear the layout off all its components
entailment
def _load_hangul_syllable_types(): """ Helper function for parsing the contents of "HangulSyllableType.txt" from the Unicode Character Database (UCD) and generating a lookup table for determining whether or not a given Hangul syllable is of type "L", "V", "T", "LV" or "LVT". For more info on the UCD, s...
Helper function for parsing the contents of "HangulSyllableType.txt" from the Unicode Character Database (UCD) and generating a lookup table for determining whether or not a given Hangul syllable is of type "L", "V", "T", "LV" or "LVT". For more info on the UCD, see the following website: https://www.unicode.o...
entailment
def _load_jamo_short_names(): """ Function for parsing the Jamo short names from the Unicode Character Database (UCD) and generating a lookup table For more info on how this is used, see the Unicode Standard, ch. 03, section 3.12, "Conjoining Jamo Behavior" and ch. 04, section 4.8, "Name". https://...
Function for parsing the Jamo short names from the Unicode Character Database (UCD) and generating a lookup table For more info on how this is used, see the Unicode Standard, ch. 03, section 3.12, "Conjoining Jamo Behavior" and ch. 04, section 4.8, "Name". https://www.unicode.org/versions/latest/ch03.pdf ...
entailment
def _get_hangul_syllable_type(hangul_syllable): """ Function for taking a Unicode scalar value representing a Hangul syllable and determining the correct value for its Hangul_Syllable_Type property. For more information on the Hangul_Syllable_Type property see the Unicode Standard, ch. 03, section 3.12...
Function for taking a Unicode scalar value representing a Hangul syllable and determining the correct value for its Hangul_Syllable_Type property. For more information on the Hangul_Syllable_Type property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. https://www.unicode.org/ver...
entailment
def _get_jamo_short_name(jamo): """ Function for taking a Unicode scalar value representing a Jamo and determining the correct value for its Jamo_Short_Name property. For more information on the Jamo_Short_Name property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. http...
Function for taking a Unicode scalar value representing a Jamo and determining the correct value for its Jamo_Short_Name property. For more information on the Jamo_Short_Name property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. https://www.unicode.org/versions/latest/ch03.pdf...
entailment
def compose_hangul_syllable(jamo): """ Function for taking a tuple or list of Unicode scalar values representing Jamo and composing it into a Hangul syllable. If the values in the list or tuple passed in are not in the ranges of Jamo, a ValueError will be raised. The algorithm for doing the compositio...
Function for taking a tuple or list of Unicode scalar values representing Jamo and composing it into a Hangul syllable. If the values in the list or tuple passed in are not in the ranges of Jamo, a ValueError will be raised. The algorithm for doing the composition is described in the Unicode Standard, ch. 03,...
entailment
def decompose_hangul_syllable(hangul_syllable, fully_decompose=False): """ Function for taking a Unicode scalar value representing a Hangul syllable and decomposing it into a tuple representing the scalar values of the decomposed (canonical decomposition) Jamo. If the Unicode scalar value passed in is ...
Function for taking a Unicode scalar value representing a Hangul syllable and decomposing it into a tuple representing the scalar values of the decomposed (canonical decomposition) Jamo. If the Unicode scalar value passed in is not in the range of Hangul syllable values (as defined in UnicodeData.txt), a Value...
entailment
def _get_hangul_syllable_name(hangul_syllable): """ Function for taking a Unicode scalar value representing a Hangul syllable and converting it to its syllable name as defined by the Unicode naming rule NR1. See the Unicode Standard, ch. 04, section 4.8, Names, for more information. :param hangul_syll...
Function for taking a Unicode scalar value representing a Hangul syllable and converting it to its syllable name as defined by the Unicode naming rule NR1. See the Unicode Standard, ch. 04, section 4.8, Names, for more information. :param hangul_syllable: Unicode scalar value representing the Hangul syllable ...
entailment
def generate_client_callers(spec, timeout, error_callback, local, app): """Return a dict mapping method names to anonymous functions that will call the server's endpoint of the corresponding name as described in the api defined by the swagger dict and bravado spec""" callers_dict = {} def mycallba...
Return a dict mapping method names to anonymous functions that will call the server's endpoint of the corresponding name as described in the api defined by the swagger dict and bravado spec
entailment
def _call_retry(self, force_retry): """Call request and retry up to max_attempts times (or none if self.max_attempts=1)""" last_exception = None for i in range(self.max_attempts): try: log.info("Calling %s %s" % (self.method, self.url)) response = self...
Call request and retry up to max_attempts times (or none if self.max_attempts=1)
entailment
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 _syllabify syll, rules = syllabify(word) yield syll...
Syllabify the given word, whether simplex or complex.
entailment
def _syllabify(word, T4=True): '''Syllabify the given word.''' word = replace_umlauts(word) word, rules = apply_T1(word) if re.search(r'[^ieAyOauo]*([ieAyOauo]{2})[^ieAyOauo]*', word): word, T2 = apply_T2(word) word, T8 = apply_T8(word) word, T9 = apply_T9(word) word, T4...
Syllabify the given word.
entailment
def apply_T1(word): '''There is a syllable boundary in front of every CV-sequence.''' # split consonants and vowels: 'balloon' -> ['b', 'a', 'll', 'oo', 'n'] WORD = [w for w in re.split('([ieAyOauo]+)', word) if w] count = 0 for i, v in enumerate(WORD): if i == 0 and is_consonant(v[0]): ...
There is a syllable boundary in front of every CV-sequence.
entailment
def extended_cigar(aligned_template, aligned_query): ''' Convert mutation annotations to extended cigar format https://github.com/lh3/minimap2#the-cs-optional-tag USAGE: >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA' >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA' >>> extended_cigar(tem...
Convert mutation annotations to extended cigar format https://github.com/lh3/minimap2#the-cs-optional-tag USAGE: >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA' >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA' >>> extended_cigar(template, query) == ':6-ata:10+gtc:4*at:3' True
entailment
def cigar2query(template, cigar): ''' Generate query sequence from the template and extended cigar annotation USAGE: >>> template = 'CGATCGATAAATAGAGTAGGAATAGCA' >>> cigar = ':6-ata:10+gtc:4*at:3' >>> cigar2query(template, cigar) == 'CGATCGAATAGAGTAGGTCGAATtGCA'.upper() True ''' ...
Generate query sequence from the template and extended cigar annotation USAGE: >>> template = 'CGATCGATAAATAGAGTAGGAATAGCA' >>> cigar = ':6-ata:10+gtc:4*at:3' >>> cigar2query(template, cigar) == 'CGATCGAATAGAGTAGGTCGAATtGCA'.upper() True
entailment
def Blaster(inputfile, databases, db_path, out_path='.', min_cov=0.6, threshold=0.9, blast='blastn', cut_off=True): ''' BLAST wrapper method, that takes a simple input and produces a overview list of the hits to templates, and their alignments Usage >>> import os, subprocess, collections ...
BLAST wrapper method, that takes a simple input and produces a overview list of the hits to templates, and their alignments Usage >>> import os, subprocess, collections >>> from Bio.Blast import NCBIXML >>> from Bio import SeqIO >>> from string import maketrans >>> inputfile = 't...
entailment
def compare_results(save, best_hsp, tmp_results, tmp_gene_split): ''' Function for comparing hits and saving only the best hit ''' # Get data for comparison hit_id = best_hsp['hit_id'] new_start_query = best_hsp['query_start'] new_end_query = best_hsp['query_end'] new_start_sbjct = int(best_hsp['sbjct...
Function for comparing hits and saving only the best hit
entailment
def calculate_new_length(gene_split, gene_results, hit): ''' Function for calcualting new length if the gene is split on several contigs ''' # Looping over splitted hits and calculate new length first = 1 for split in gene_split[hit['sbjct_header']]: new_start = int(gene_results[split]['sbjct_st...
Function for calcualting new length if the gene is split on several contigs
entailment
def stream_to_packet(data): """ Chop a stream of data into MODBUS packets. :param data: stream of data :returns: a tuple of the data that is a packet with the remaining data, or ``None`` """ if len(data) < 6: return None # unpack the length pktlen = struct.unpack(">H", ...
Chop a stream of data into MODBUS packets. :param data: stream of data :returns: a tuple of the data that is a packet with the remaining data, or ``None``
entailment
def to_primitive(value, convert_instances=False, convert_datetime=True, level=0, max_depth=3): """Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. ...
Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. To handle cyclical data structures we could track the actual objects visited in a set, but not all objects are...
entailment
def get_vowel(syll): '''Return the firstmost vowel in 'syll'.''' return re.search(r'([ieaouäöy]{1})', syll, flags=FLAGS).group(1).upper()
Return the firstmost vowel in 'syll'.
entailment
def is_light(syll): '''Return True if 'syll' is light.''' return re.match(r'(^|[^ieaouäöy]+)[ieaouäöy]{1}$', syll, flags=FLAGS)
Return True if 'syll' is light.
entailment
def stress(syllabified_simplex_word): '''Assign primary and secondary stress to 'syllabified_simplex_word'.''' syllables = syllabified_simplex_word.split('.') stressed = '\'' + syllables[0] # primary stress try: n = 0 medial = syllables[1:-1] for i, syll in enumerate(medial): ...
Assign primary and secondary stress to 'syllabified_simplex_word'.
entailment