_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275300 | Autoencoder._find_output | test | def _find_output(self, layer):
'''Find a layer output name for the given layer specifier.
Parameters
----------
layer : None, int, str, or :class:`theanets.layers.Layer`
A layer specification. If this is None, the "middle" layer in the
network will be used (i.e.,... | python | {
"resource": ""
} |
q275301 | Autoencoder.score | test | def score(self, x, w=None, **kwargs):
'''Compute R^2 coefficient of determination for a given input.
Parameters
----------
x : ndarray (num-examples, num-inputs)
An array containing data to be fed into the network. Multiple
examples are arranged as rows in this a... | python | {
"resource": ""
} |
q275302 | Classifier.predict | test | def predict(self, x, **kwargs):
'''Compute a greedy classification for the given set of data.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to classify. Examples are given as the
rows in this array.
Returns
... | python | {
"resource": ""
} |
q275303 | Classifier.predict_proba | test | def predict_proba(self, x, **kwargs):
'''Compute class posterior probabilities for the given set of data.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to predict. Examples are given as the
rows in this array.
... | python | {
"resource": ""
} |
q275304 | Classifier.predict_logit | test | def predict_logit(self, x, **kwargs):
'''Compute the logit values that underlie the softmax output.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to classify. Examples are given as the
rows in this array.
Re... | python | {
"resource": ""
} |
q275305 | Classifier.score | test | def score(self, x, y, w=None, **kwargs):
'''Compute the mean accuracy on a set of labeled data.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to classify. Examples are given as the
rows in this array.
y : nda... | python | {
"resource": ""
} |
q275306 | batch_at | test | def batch_at(features, labels, seq_begins, seq_lengths):
'''Extract a single batch of data to pass to the model being trained.
Parameters
----------
features, labels : ndarray
Arrays of the input features and target labels.
seq_begins : ndarray
Array of the start offsets of the spee... | python | {
"resource": ""
} |
q275307 | batches | test | def batches(dataset):
'''Returns a callable that chooses sequences from netcdf data.'''
seq_lengths = dataset.variables['seqLengths'].data
seq_begins = np.concatenate(([0], np.cumsum(seq_lengths)[:-1]))
def sample():
chosen = np.random.choice(
list(range(len(seq_lengths))), BATCH_SI... | python | {
"resource": ""
} |
q275308 | Experiment.load | test | def load(self, path):
'''Load a saved network from a pickle file on disk.
This method sets the ``network`` attribute of the experiment to the
loaded network model.
Parameters
----------
filename : str
Load the keyword arguments and parameters of a network fr... | python | {
"resource": ""
} |
q275309 | random_matrix | test | def random_matrix(rows, cols, mean=0, std=1, sparsity=0, radius=0, diagonal=0, rng=None):
'''Create a matrix of randomly-initialized weights.
Parameters
----------
rows : int
Number of rows of the weight matrix -- equivalently, the number of
"input" units that the weight matrix connects... | python | {
"resource": ""
} |
q275310 | random_vector | test | def random_vector(size, mean=0, std=1, rng=None):
'''Create a vector of randomly-initialized values.
Parameters
----------
size : int
Length of vecctor to create.
mean : float, optional
Mean value for initial vector values. Defaults to 0.
std : float, optional
Standard d... | python | {
"resource": ""
} |
q275311 | outputs_matching | test | def outputs_matching(outputs, patterns):
'''Get the outputs from a network that match a pattern.
Parameters
----------
outputs : dict or sequence of (str, theano expression)
Output expressions to filter for matches. If this is a dictionary, its
``items()`` will be processed for matches.... | python | {
"resource": ""
} |
q275312 | params_matching | test | def params_matching(layers, patterns):
'''Get the parameters from a network that match a pattern.
Parameters
----------
layers : list of :class:`theanets.layers.Layer`
A list of network layers to retrieve parameters from.
patterns : sequence of str
A sequence of glob-style patterns ... | python | {
"resource": ""
} |
q275313 | from_kwargs | test | def from_kwargs(graph, **kwargs):
'''Construct common regularizers from a set of keyword arguments.
Keyword arguments not listed below will be passed to
:func:`Regularizer.build` if they specify the name of a registered
:class:`Regularizer`.
Parameters
----------
graph : :class:`theanets.g... | python | {
"resource": ""
} |
q275314 | Loss.variables | test | def variables(self):
'''A list of Theano variables used in this loss.'''
result = [self._target]
if self._weights is not None:
result.append(self._weights)
return result | python | {
"resource": ""
} |
q275315 | CrossEntropy.accuracy | test | def accuracy(self, outputs):
'''Build a Theano expression for computing the accuracy of graph output.
Parameters
----------
outputs : dict of Theano expressions
A dictionary mapping network output names to Theano expressions
representing the outputs of a computat... | python | {
"resource": ""
} |
q275316 | Recurrent._scan | test | def _scan(self, inputs, outputs, name='scan', step=None, constants=None):
'''Helper method for defining a basic loop in theano.
Parameters
----------
inputs : sequence of theano expressions
Inputs to the scan operation.
outputs : sequence of output specifiers
... | python | {
"resource": ""
} |
q275317 | build | test | def build(name, layer, **kwargs):
'''Construct an activation function by name.
Parameters
----------
name : str or :class:`Activation`
The name of the type of activation function to build, or an
already-created instance of an activation function.
layer : :class:`theanets.layers.Laye... | python | {
"resource": ""
} |
q275318 | SampleTrainer.reservoir | test | def reservoir(xs, n, rng):
'''Select a random sample of n items from xs.'''
pool = []
for i, x in enumerate(xs):
if len(pool) < n:
pool.append(x / np.linalg.norm(x))
continue
j = rng.randint(i + 1)
if j < n:
pool... | python | {
"resource": ""
} |
q275319 | Network.set_loss | test | def set_loss(self, *args, **kwargs):
'''Clear the current loss functions from the network and add a new one.
All parameters and keyword arguments are passed to :func:`add_loss`
after clearing the current losses.
'''
self.losses = []
self.add_loss(*args, **kwargs) | python | {
"resource": ""
} |
q275320 | Network.itertrain | test | def itertrain(self, train, valid=None, algo='rmsprop', subalgo='rmsprop',
save_every=0, save_progress=None, **kwargs):
'''Train our network, one batch at a time.
This method yields a series of ``(train, valid)`` monitor pairs. The
``train`` value is a dictionary mapping names ... | python | {
"resource": ""
} |
q275321 | Network.train | test | def train(self, *args, **kwargs):
'''Train the network until the trainer converges.
All arguments are passed to :func:`itertrain`.
Returns
-------
training : dict
A dictionary of monitor values computed using the training dataset,
at the conclusion of tr... | python | {
"resource": ""
} |
q275322 | Network._hash | test | def _hash(self, regularizers=()):
'''Construct a string key for representing a computation graph.
This key will be unique for a given (a) network topology, (b) set of
losses, and (c) set of regularizers.
Returns
-------
key : str
A hash representing the comp... | python | {
"resource": ""
} |
q275323 | Network.build_graph | test | def build_graph(self, regularizers=()):
'''Connect the layers in this network to form a computation graph.
Parameters
----------
regularizers : list of :class:`theanets.regularizers.Regularizer`
A list of the regularizers to apply while building the computation
g... | python | {
"resource": ""
} |
q275324 | Network.inputs | test | def inputs(self):
'''A list of Theano variables for feedforward computations.'''
return [l.input for l in self.layers if isinstance(l, layers.Input)] | python | {
"resource": ""
} |
q275325 | Network.variables | test | def variables(self):
'''A list of Theano variables for loss computations.'''
result = self.inputs
seen = set(i.name for i in result)
for loss in self.losses:
for v in loss.variables:
if v.name not in seen:
result.append(v)
... | python | {
"resource": ""
} |
q275326 | Network.find | test | def find(self, which, param):
'''Get a parameter from a layer in the network.
Parameters
----------
which : int or str
The layer that owns the parameter to return.
If this is an integer, then 0 refers to the input layer, 1 refers
to the first hidden ... | python | {
"resource": ""
} |
q275327 | Network.feed_forward | test | def feed_forward(self, x, **kwargs):
'''Compute a forward pass of all layers from the given input.
All keyword arguments are passed directly to :func:`build_graph`.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing data to be fed in... | python | {
"resource": ""
} |
q275328 | Network.predict | test | def predict(self, x, **kwargs):
'''Compute a forward pass of the inputs, returning the network output.
All keyword arguments end up being passed to :func:`build_graph`.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing data to be fe... | python | {
"resource": ""
} |
q275329 | Network.score | test | def score(self, x, y, w=None, **kwargs):
'''Compute R^2 coefficient of determination for a given labeled input.
Parameters
----------
x : ndarray (num-examples, num-inputs)
An array containing data to be fed into the network. Multiple
examples are arranged as row... | python | {
"resource": ""
} |
q275330 | Network.save | test | def save(self, filename_or_handle):
'''Save the state of this network to a pickle file on disk.
Parameters
----------
filename_or_handle : str or file handle
Save the state of this network to a pickle file. If this parameter
is a string, it names the file where t... | python | {
"resource": ""
} |
q275331 | Network.load | test | def load(cls, filename_or_handle):
'''Load a saved network from disk.
Parameters
----------
filename_or_handle : str or file handle
Load the state of this network from a pickle file. If this parameter
is a string, it names the file where the pickle will be saved.... | python | {
"resource": ""
} |
q275332 | Network.loss | test | def loss(self, **kwargs):
'''Return a variable representing the regularized loss for this network.
The regularized loss includes both the :ref:`loss computation <losses>`
for the network as well as any :ref:`regularizers <regularizers>` that
are in place.
Keyword arguments are ... | python | {
"resource": ""
} |
q275333 | Network.updates | test | def updates(self, **kwargs):
'''Return expressions to run as updates during network training.
Returns
-------
updates : list of (parameter, expression) pairs
A list of named parameter update expressions for this network.
'''
regs = regularizers.from_kwargs(se... | python | {
"resource": ""
} |
q275334 | Layer.output_size | test | def output_size(self):
'''Number of "neurons" in this layer's default output.'''
shape = self.output_shape
if shape is None:
raise util.ConfigurationError(
'undefined output size for layer "{}"'.format(self.name))
return shape[-1] | python | {
"resource": ""
} |
q275335 | Layer.connect | test | def connect(self, inputs):
'''Create Theano variables representing the outputs of this layer.
Parameters
----------
inputs : dict of Theano expressions
Symbolic inputs to this layer, given as a dictionary mapping string
names to Theano expressions. Each string ke... | python | {
"resource": ""
} |
q275336 | Layer.bind | test | def bind(self, graph, reset=True, initialize=True):
'''Bind this layer into a computation graph.
This method is a wrapper for performing common initialization tasks. It
calls :func:`resolve`, :func:`setup`, and :func:`log`.
Parameters
----------
graph : :class:`Network ... | python | {
"resource": ""
} |
q275337 | Layer.resolve_inputs | test | def resolve_inputs(self, layers):
'''Resolve the names of inputs for this layer into shape tuples.
Parameters
----------
layers : list of :class:`Layer`
A list of the layers that are available for resolving inputs.
Raises
------
theanets.util.Configu... | python | {
"resource": ""
} |
q275338 | Layer.resolve_outputs | test | def resolve_outputs(self):
'''Resolve the names of outputs for this layer into shape tuples.'''
input_shape = None
for i, shape in enumerate(self._input_shapes.values()):
if i == 0:
input_shape = shape
if len(input_shape) != len(shape) or any(
... | python | {
"resource": ""
} |
q275339 | Layer.log | test | def log(self):
'''Log some information about this layer.'''
inputs = ', '.join('"{0}" {1}'.format(*ns) for ns in self._input_shapes.items())
util.log('layer {0.__class__.__name__} "{0.name}" {0.output_shape} {1} from {2}',
self, getattr(self.activate, 'name', self.activate), inp... | python | {
"resource": ""
} |
q275340 | Layer.log_params | test | def log_params(self):
'''Log information about this layer's parameters.'''
total = 0
for p in self.params:
shape = p.get_value().shape
util.log('parameter "{}" {}', p.name, shape)
total += np.prod(shape)
return total | python | {
"resource": ""
} |
q275341 | Layer._fmt | test | def _fmt(self, string):
'''Helper method to format our name into a string.'''
if '{' not in string:
string = '{}.' + string
return string.format(self.name) | python | {
"resource": ""
} |
q275342 | Layer._resolve_shape | test | def _resolve_shape(self, name, layers):
'''Given a list of layers, find the layer output with the given name.
Parameters
----------
name : str
Name of a layer to resolve.
layers : list of :class:`theanets.layers.base.Layer`
A list of layers to search in.
... | python | {
"resource": ""
} |
q275343 | Layer.find | test | def find(self, key):
'''Get a shared variable for a parameter by name.
Parameters
----------
key : str or int
The name of the parameter to look up, or the index of the parameter
in our parameter list. These are both dependent on the
implementation of ... | python | {
"resource": ""
} |
q275344 | Layer.add_bias | test | def add_bias(self, name, size, mean=0, std=1):
'''Helper method to create a new bias vector.
Parameters
----------
name : str
Name of the parameter to add.
size : int
Size of the bias vector.
mean : float, optional
Mean value for rando... | python | {
"resource": ""
} |
q275345 | Layer.to_spec | test | def to_spec(self):
'''Create a specification dictionary for this layer.
Returns
-------
spec : dict
A dictionary specifying the configuration of this layer.
'''
spec = dict(**self.kwargs)
spec.update(
form=self.__class__.__name__.lower(),
... | python | {
"resource": ""
} |
q275346 | LogGabor.loggabor | test | def loggabor(self, x_pos, y_pos, sf_0, B_sf, theta, B_theta, preprocess=True):
"""
Returns the envelope of a LogGabor
Note that the convention for coordinates follows that of matrices:
the origin is at the top left of the image, and coordinates are first
the rows (vertical axis,... | python | {
"resource": ""
} |
q275347 | LogGabor.loggabor_image | test | def loggabor_image(self, x_pos, y_pos, theta, sf_0, phase, B_sf, B_theta):
"""
Returns the image of a LogGabor
Note that the convention for coordinates follows that of matrices:
the origin is at the top left of the image, and coordinates are first
the rows (vertical axis, going ... | python | {
"resource": ""
} |
q275348 | TextGrid.add_tier | test | def add_tier(self, name, tier_type='IntervalTier', number=None):
"""Add an IntervalTier or a TextTier on the specified location.
:param str name: Name of the tier, duplicate names is allowed.
:param str tier_type: Type of the tier.
:param int number: Place to insert the tier, when ``Non... | python | {
"resource": ""
} |
q275349 | TextGrid.remove_tier | test | def remove_tier(self, name_num):
"""Remove a tier, when multiple tiers exist with that name only the
first is removed.
:param name_num: Name or number of the tier to remove.
:type name_num: int or str
:raises IndexError: If there is no tier with that number.
"""
... | python | {
"resource": ""
} |
q275350 | TextGrid.get_tier | test | def get_tier(self, name_num):
"""Gives a tier, when multiple tiers exist with that name only the
first is returned.
:param name_num: Name or number of the tier to return.
:type name_num: int or str
:returns: The tier.
:raises IndexError: If the tier doesn't exist.
... | python | {
"resource": ""
} |
q275351 | TextGrid.to_eaf | test | def to_eaf(self, skipempty=True, pointlength=0.1):
"""Convert the object to an pympi.Elan.Eaf object
:param int pointlength: Length of respective interval from points in
seconds
:param bool skipempty: Skip the empty annotations
:returns: :class:`pympi.Ela... | python | {
"resource": ""
} |
q275352 | Tier.add_point | test | def add_point(self, point, value, check=True):
"""Add a point to the TextTier
:param int point: Time of the point.
:param str value: Text of the point.
:param bool check: Flag to check for overlap.
:raises Exception: If overlap or wrong tiertype.
"""
if self.tier... | python | {
"resource": ""
} |
q275353 | Tier.add_interval | test | def add_interval(self, begin, end, value, check=True):
"""Add an interval to the IntervalTier.
:param float begin: Start time of the interval.
:param float end: End time of the interval.
:param str value: Text of the interval.
:param bool check: Flag to check for overlap.
... | python | {
"resource": ""
} |
q275354 | Tier.remove_interval | test | def remove_interval(self, time):
"""Remove an interval, if no interval is found nothing happens.
:param int time: Time of the interval.
:raises TierTypeException: If the tier is not a IntervalTier.
"""
if self.tier_type != 'IntervalTier':
raise Exception('Tiertype mu... | python | {
"resource": ""
} |
q275355 | Tier.remove_point | test | def remove_point(self, time):
"""Remove a point, if no point is found nothing happens.
:param int time: Time of the point.
:raises TierTypeException: If the tier is not a TextTier.
"""
if self.tier_type != 'TextTier':
raise Exception('Tiertype must be TextTier.')
... | python | {
"resource": ""
} |
q275356 | Tier.get_intervals | test | def get_intervals(self, sort=False):
"""Give all the intervals or points.
:param bool sort: Flag for yielding the intervals or points sorted.
:yields: All the intervals
"""
for i in sorted(self.intervals) if sort else self.intervals:
yield i | python | {
"resource": ""
} |
q275357 | Tier.get_all_intervals | test | def get_all_intervals(self):
"""Returns the true list of intervals including the empty intervals."""
ints = sorted(self.get_intervals(True))
if self.tier_type == 'IntervalTier':
if not ints:
ints.append((self.xmin, self.xmax, ''))
else:
if ... | python | {
"resource": ""
} |
q275358 | indent | test | def indent(el, level=0):
"""Function to pretty print the xml, meaning adding tabs and newlines.
:param ElementTree.Element el: Current element.
:param int level: Current level.
"""
i = '\n' + level * '\t'
if len(el):
if not el.text or not el.text.strip():
el.text = i+'\t'
... | python | {
"resource": ""
} |
q275359 | Eaf.add_annotation | test | def add_annotation(self, id_tier, start, end, value='', svg_ref=None):
"""Add an annotation.
:param str id_tier: Name of the tier.
:param int start: Start time of the annotation.
:param int end: End time of the annotation.
:param str value: Value of the annotation.
:para... | python | {
"resource": ""
} |
q275360 | Eaf.add_cv_entry | test | def add_cv_entry(self, cv_id, cve_id, values, ext_ref=None):
"""Add an entry to a controlled vocabulary.
:param str cv_id: Name of the controlled vocabulary to add an entry.
:param str cve_id: Name of the entry.
:param list values: List of values of the form:
``(value, lang_... | python | {
"resource": ""
} |
q275361 | Eaf.add_cv_description | test | def add_cv_description(self, cv_id, lang_ref, description=None):
"""Add a description to a controlled vocabulary.
:param str cv_id: Name of the controlled vocabulary to add the
description.
:param str lang_ref: Language reference.
:param str description: Description, this ca... | python | {
"resource": ""
} |
q275362 | Eaf.add_external_ref | test | def add_external_ref(self, eid, etype, value):
"""Add an external reference.
:param str eid: Name of the external reference.
:param str etype: Type of the external reference, has to be in
``['iso12620', 'ecv', 'cve_id', 'lexen_id', 'resource_url']``.
:param str value: Value ... | python | {
"resource": ""
} |
q275363 | Eaf.add_language | test | def add_language(self, lang_id, lang_def=None, lang_label=None):
"""Add a language.
:param str lang_id: ID of the language.
:param str lang_def: Definition of the language(preferably ISO-639-3).
:param str lang_label: Label of the language.
"""
self.languages[lang_id] = ... | python | {
"resource": ""
} |
q275364 | Eaf.add_lexicon_ref | test | def add_lexicon_ref(self, lrid, name, lrtype, url, lexicon_id,
lexicon_name, datcat_id=None, datcat_name=None):
"""Add lexicon reference.
:param str lrid: Lexicon reference internal ID.
:param str name: Lexicon reference display name.
:param str lrtype: Lexicon r... | python | {
"resource": ""
} |
q275365 | Eaf.add_linguistic_type | test | def add_linguistic_type(self, lingtype, constraints=None,
timealignable=True, graphicreferences=False,
extref=None, param_dict=None):
"""Add a linguistic type.
:param str lingtype: Name of the linguistic type.
:param str constraints: Const... | python | {
"resource": ""
} |
q275366 | Eaf.add_linked_file | test | def add_linked_file(self, file_path, relpath=None, mimetype=None,
time_origin=None, ex_from=None):
"""Add a linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: Mimetype of the file, if ``None`` ... | python | {
"resource": ""
} |
q275367 | Eaf.add_locale | test | def add_locale(self, language_code, country_code=None, variant=None):
"""Add a locale.
:param str language_code: The language code of the locale.
:param str country_code: The country code of the locale.
:param str variant: The variant of the locale.
"""
self.locales[lang... | python | {
"resource": ""
} |
q275368 | Eaf.add_secondary_linked_file | test | def add_secondary_linked_file(self, file_path, relpath=None, mimetype=None,
time_origin=None, assoc_with=None):
"""Add a secondary linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: M... | python | {
"resource": ""
} |
q275369 | Eaf.add_tier | test | def add_tier(self, tier_id, ling='default-lt', parent=None, locale=None,
part=None, ann=None, language=None, tier_dict=None):
"""Add a tier. When no linguistic type is given and the default
linguistic type is unavailable then the assigned linguistic type will
be the first in the... | python | {
"resource": ""
} |
q275370 | Eaf.clean_time_slots | test | def clean_time_slots(self):
"""Clean up all unused timeslots.
.. warning:: This can and will take time for larger tiers.
When you want to do a lot of operations on a lot of tiers please unset
the flags for cleaning in the functions so that the cleaning is only
performed afterwa... | python | {
"resource": ""
} |
q275371 | Eaf.extract | test | def extract(self, start, end):
"""Extracts the selected time frame as a new object.
:param int start: Start time.
:param int end: End time.
:returns: class:`pympi.Elan.Eaf` object containing the extracted frame.
"""
from copy import deepcopy
eaf_out = deepcopy(se... | python | {
"resource": ""
} |
q275372 | Eaf.generate_annotation_id | test | def generate_annotation_id(self):
"""Generate the next annotation id, this function is mainly used
internally.
"""
if not self.maxaid:
valid_anns = [int(''.join(filter(str.isdigit, a)))
for a in self.timeslots]
self.maxaid = max(valid_ann... | python | {
"resource": ""
} |
q275373 | Eaf.generate_ts_id | test | def generate_ts_id(self, time=None):
"""Generate the next timeslot id, this function is mainly used
internally
:param int time: Initial time to assign to the timeslot.
:raises ValueError: If the time is negative.
"""
if time and time < 0:
raise ValueError('Ti... | python | {
"resource": ""
} |
q275374 | Eaf.get_child_tiers_for | test | def get_child_tiers_for(self, id_tier):
"""Give all child tiers for a tier.
:param str id_tier: Name of the tier.
:returns: List of all children
:raises KeyError: If the tier is non existent.
"""
self.tiers[id_tier]
return [m for m in self.tiers if 'PARENT_REF' i... | python | {
"resource": ""
} |
q275375 | Eaf.get_full_time_interval | test | def get_full_time_interval(self):
"""Give the full time interval of the file. Note that the real interval
can be longer because the sound file attached can be longer.
:returns: Tuple of the form: ``(min_time, max_time)``.
"""
return (0, 0) if not self.timeslots else\
... | python | {
"resource": ""
} |
q275376 | Eaf.get_ref_annotation_data_after_time | test | def get_ref_annotation_data_after_time(self, id_tier, time):
"""Give the ref annotation after a time. If an annotation overlaps
with `ktime`` that annotation will be returned.
:param str id_tier: Name of the tier.
:param int time: Time to get the annotation after.
:returns: Anno... | python | {
"resource": ""
} |
q275377 | Eaf.get_ref_annotation_data_before_time | test | def get_ref_annotation_data_before_time(self, id_tier, time):
"""Give the ref annotation before a time. If an annotation overlaps
with ``time`` that annotation will be returned.
:param str id_tier: Name of the tier.
:param int time: Time to get the annotation before.
:returns: A... | python | {
"resource": ""
} |
q275378 | Eaf.get_tier_ids_for_linguistic_type | test | def get_tier_ids_for_linguistic_type(self, ling_type, parent=None):
"""Give a list of all tiers matching a linguistic type.
:param str ling_type: Name of the linguistic type.
:param str parent: Only match tiers from this parent, when ``None``
this option will be ignor... | python | {
"resource": ""
} |
q275379 | Eaf.merge_tiers | test | def merge_tiers(self, tiers, tiernew=None, gapt=0, sep='_', safe=False):
"""Merge tiers into a new tier and when the gap is lower then the
threshhold glue the annotations together.
:param list tiers: List of tier names.
:param str tiernew: Name for the new tier, if ``None`` the name wil... | python | {
"resource": ""
} |
q275380 | Eaf.remove_all_annotations_from_tier | test | def remove_all_annotations_from_tier(self, id_tier, clean=True):
"""remove all annotations from a tier
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
for aid in self.tiers[id_tier][0]:
del(self.annotations[aid])
for a... | python | {
"resource": ""
} |
q275381 | Eaf.remove_cv_description | test | def remove_cv_description(self, cv_id, lang_ref):
"""Remove a controlled vocabulary description.
:param str cv_id: Name of the controlled vocabulary.
:paarm str cve_id: Name of the entry.
:throws KeyError: If there is no controlled vocabulary with that name.
"""
for i, (... | python | {
"resource": ""
} |
q275382 | Eaf.remove_license | test | def remove_license(self, name=None, url=None):
"""Remove all licenses matching both key and value.
:param str name: Name of the license.
:param str url: URL of the license.
"""
for k, v in self.licenses[:]:
if (name is None or name == k) and (url is None or url == v)... | python | {
"resource": ""
} |
q275383 | Eaf.remove_linked_files | test | def remove_linked_files(self, file_path=None, relpath=None, mimetype=None,
time_origin=None, ex_from=None):
"""Remove all linked files that match all the criteria, criterias that
are ``None`` are ignored.
:param str file_path: Path of the file.
:param str rel... | python | {
"resource": ""
} |
q275384 | Eaf.remove_property | test | def remove_property(self, key=None, value=None):
"""Remove all properties matching both key and value.
:param str key: Key of the property.
:param str value: Value of the property.
"""
for k, v in self.properties[:]:
if (key is None or key == k) and (value is None or... | python | {
"resource": ""
} |
q275385 | Eaf.remove_ref_annotation | test | def remove_ref_annotation(self, id_tier, time):
"""Remove a reference annotation.
:param str id_tier: Name of tier.
:param int time: Time of the referenced annotation
:raises KeyError: If the tier is non existent.
:returns: Number of removed annotations.
"""
remo... | python | {
"resource": ""
} |
q275386 | Eaf.remove_secondary_linked_files | test | def remove_secondary_linked_files(self, file_path=None, relpath=None,
mimetype=None, time_origin=None,
assoc_with=None):
"""Remove all secondary linked files that match all the criteria,
criterias that are ``None`` are ignored.
... | python | {
"resource": ""
} |
q275387 | Eaf.remove_tier | test | def remove_tier(self, id_tier, clean=True):
"""Remove a tier.
:param str id_tier: Name of the tier.
:param bool clean: Flag to also clean the timeslots.
:raises KeyError: If tier is non existent.
"""
del(self.tiers[id_tier])
if clean:
self.clean_time_... | python | {
"resource": ""
} |
q275388 | Eaf.remove_tiers | test | def remove_tiers(self, tiers):
"""Remove multiple tiers, note that this is a lot faster then removing
them individually because of the delayed cleaning of timeslots.
:param list tiers: Names of the tier to remove.
:raises KeyError: If a tier is non existent.
"""
for a in... | python | {
"resource": ""
} |
q275389 | Eaf.rename_tier | test | def rename_tier(self, id_from, id_to):
"""Rename a tier. Note that this renames also the child tiers that have
the tier as a parent.
:param str id_from: Original name of the tier.
:param str id_to: Target name of the tier.
:throws KeyError: If the tier doesnt' exist.
"""... | python | {
"resource": ""
} |
q275390 | Eaf.shift_annotations | test | def shift_annotations(self, time):
"""Shift all annotations in time. Annotations that are in the beginning
and a left shift is applied can be squashed or discarded.
:param int time: Time shift width, negative numbers make a left shift.
:returns: Tuple of a list of squashed annotations a... | python | {
"resource": ""
} |
q275391 | main | test | def main():
"""Will be used to create the console script"""
import optparse
import sys
import codecs
import locale
import six
from .algorithm import get_display
parser = optparse.OptionParser()
parser.add_option('-e', '--encoding',
dest='encoding',
... | python | {
"resource": ""
} |
q275392 | debug_storage | test | def debug_storage(storage, base_info=False, chars=True, runs=False):
"Display debug information for the storage"
import codecs
import locale
import sys
if six.PY2:
stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr)
else:
stderr = sys.stderr
caller = inspe... | python | {
"resource": ""
} |
q275393 | get_base_level | test | def get_base_level(text, upper_is_rtl=False):
"""Get the paragraph base embedding level. Returns 0 for LTR,
1 for RTL.
`text` a unicode object.
Set `upper_is_rtl` to True to treat upper case chars as strong 'R'
for debugging (default: False).
"""
base_level = None
prev_surrogate = F... | python | {
"resource": ""
} |
q275394 | get_embedding_levels | test | def get_embedding_levels(text, storage, upper_is_rtl=False, debug=False):
"""Get the paragraph base embedding level and direction,
set the storage to the array of chars"""
prev_surrogate = False
base_level = storage['base_level']
# preset the storage's chars
for _ch in text:
if _IS_UCS... | python | {
"resource": ""
} |
q275395 | explicit_embed_and_overrides | test | def explicit_embed_and_overrides(storage, debug=False):
"""Apply X1 to X9 rules of the unicode algorithm.
See http://unicode.org/reports/tr9/#Explicit_Levels_and_Directions
"""
overflow_counter = almost_overflow_counter = 0
directional_override = 'N'
levels = deque()
# X1
embedding_le... | python | {
"resource": ""
} |
q275396 | calc_level_runs | test | def calc_level_runs(storage):
"""Split the storage to run of char types at the same level.
Applies X10. See http://unicode.org/reports/tr9/#X10
"""
# run level depends on the higher of the two levels on either side of
# the boundary If the higher level is odd, the type is R; otherwise,
# it is ... | python | {
"resource": ""
} |
q275397 | resolve_weak_types | test | def resolve_weak_types(storage, debug=False):
"""Reslove weak type rules W1 - W3.
See: http://unicode.org/reports/tr9/#Resolving_Weak_Types
"""
for run in storage['runs']:
prev_strong = prev_type = run['sor']
start, length = run['start'], run['length']
chars = storage['chars']... | python | {
"resource": ""
} |
q275398 | resolve_neutral_types | test | def resolve_neutral_types(storage, debug):
"""Resolving neutral types. Implements N1 and N2
See: http://unicode.org/reports/tr9/#Resolving_Neutral_Types
"""
for run in storage['runs']:
start, length = run['start'], run['length']
# use sor and eor
chars = [{'type': run['sor']}]... | python | {
"resource": ""
} |
q275399 | reverse_contiguous_sequence | test | def reverse_contiguous_sequence(chars, line_start, line_end, highest_level,
lowest_odd_level):
"""L2. From the highest level found in the text to the lowest odd
level on each line, including intermediate levels not actually
present in the text, reverse any contiguous sequence... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.