Search is not available for this dataset
text stringlengths 75 104k |
|---|
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.
... |
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... |
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 |
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:
... |
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... |
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())
... |
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... |
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... |
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... |
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.... |
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,
:... |
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... |
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:
... |
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... |
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... |
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
... |
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:
... |
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... |
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... |
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... |
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... |
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:
... |
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... |
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')
... |
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) |
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... |
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_... |
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... |
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,
... |
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.
"""
... |
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... |
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)
"""
... |
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(),
... |
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 = ... |
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... |
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) |
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... |
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],... |
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... |
def set_interface(self, interface):
"""Add update toolbar callback to the interface"""
self.interface = interface
self.interface.callbacks.update_toolbar = self._update
self._update() |
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... |
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... |
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-... |
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... |
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:
... |
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() |
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.
"""
... |
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())) |
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 ) |
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... |
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... |
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 |
def validate( self ):
"""Validate all the fields on this Block instance."""
klass = self.__class__
for name in klass._fields:
self.validate_field( name )
return |
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... |
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... |
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... |
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... |
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... |
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... |
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... |
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 ... |
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(
... |
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_... |
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,
... |
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',... |
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... |
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... |
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... |
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... |
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... |
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)
... |
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
... |
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() |
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.... |
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... |
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... |
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 =... |
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:
... |
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... |
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://... |
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... |
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... |
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... |
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 ... |
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... |
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... |
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... |
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... |
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... |
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]):
... |
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... |
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
'''
... |
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
... |
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... |
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... |
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", ... |
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.
... |
def get_vowel(syll):
'''Return the firstmost vowel in 'syll'.'''
return re.search(r'([ieaouäöy]{1})', syll, flags=FLAGS).group(1).upper() |
def is_light(syll):
'''Return True if 'syll' is light.'''
return re.match(r'(^|[^ieaouäöy]+)[ieaouäöy]{1}$', syll, flags=FLAGS) |
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):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.