repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ynop/audiomate | audiomate/processing/pipeline/base.py | Step._create_buffers | def _create_buffers(self):
"""
Create a buffer for every step in the pipeline.
"""
self.buffers = {}
for step in self.graph.nodes():
num_buffers = 1
if isinstance(step, Reduction):
num_buffers = len(step.parents)
self.buffers[step] = Buffer(step.min_frames, step.left_context, step.right_context, num_buffers)
return self.buffers | python | def _create_buffers(self):
"""
Create a buffer for every step in the pipeline.
"""
self.buffers = {}
for step in self.graph.nodes():
num_buffers = 1
if isinstance(step, Reduction):
num_buffers = len(step.parents)
self.buffers[step] = Buffer(step.min_frames, step.left_context, step.right_context, num_buffers)
return self.buffers | [
"def",
"_create_buffers",
"(",
"self",
")",
":",
"self",
".",
"buffers",
"=",
"{",
"}",
"for",
"step",
"in",
"self",
".",
"graph",
".",
"nodes",
"(",
")",
":",
"num_buffers",
"=",
"1",
"if",
"isinstance",
"(",
"step",
",",
"Reduction",
")",
":",
"n... | Create a buffer for every step in the pipeline. | [
"Create",
"a",
"buffer",
"for",
"every",
"step",
"in",
"the",
"pipeline",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L372-L387 | train | 32,700 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.save | def save(self, writer=None):
"""
If self.path is defined, it tries to save the corpus at the given path.
"""
if self.path is None:
raise ValueError('No path given to save the data set.')
self.save_at(self.path, writer) | python | def save(self, writer=None):
"""
If self.path is defined, it tries to save the corpus at the given path.
"""
if self.path is None:
raise ValueError('No path given to save the data set.')
self.save_at(self.path, writer) | [
"def",
"save",
"(",
"self",
",",
"writer",
"=",
"None",
")",
":",
"if",
"self",
".",
"path",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No path given to save the data set.'",
")",
"self",
".",
"save_at",
"(",
"self",
".",
"path",
",",
"writer",
")"... | If self.path is defined, it tries to save the corpus at the given path. | [
"If",
"self",
".",
"path",
"is",
"defined",
"it",
"tries",
"to",
"save",
"the",
"corpus",
"at",
"the",
"given",
"path",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L69-L77 | train | 32,701 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.save_at | def save_at(self, path, writer=None):
"""
Save this corpus at the given path. If the path differs from the current path set, the path
gets updated.
Parameters:
path (str): Path to save the data set to.
writer (str, CorpusWriter): The writer or the name of the reader to use.
"""
if writer is None:
from . import io
writer = io.DefaultWriter()
elif type(writer) == str:
# If a loader is given as string, try to create such a loader.
from . import io
writer = io.create_writer_of_type(writer)
writer.save(self, path)
self.path = path | python | def save_at(self, path, writer=None):
"""
Save this corpus at the given path. If the path differs from the current path set, the path
gets updated.
Parameters:
path (str): Path to save the data set to.
writer (str, CorpusWriter): The writer or the name of the reader to use.
"""
if writer is None:
from . import io
writer = io.DefaultWriter()
elif type(writer) == str:
# If a loader is given as string, try to create such a loader.
from . import io
writer = io.create_writer_of_type(writer)
writer.save(self, path)
self.path = path | [
"def",
"save_at",
"(",
"self",
",",
"path",
",",
"writer",
"=",
"None",
")",
":",
"if",
"writer",
"is",
"None",
":",
"from",
".",
"import",
"io",
"writer",
"=",
"io",
".",
"DefaultWriter",
"(",
")",
"elif",
"type",
"(",
"writer",
")",
"==",
"str",
... | Save this corpus at the given path. If the path differs from the current path set, the path
gets updated.
Parameters:
path (str): Path to save the data set to.
writer (str, CorpusWriter): The writer or the name of the reader to use. | [
"Save",
"this",
"corpus",
"at",
"the",
"given",
"path",
".",
"If",
"the",
"path",
"differs",
"from",
"the",
"current",
"path",
"set",
"the",
"path",
"gets",
"updated",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L79-L99 | train | 32,702 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.new_file | def new_file(self, path, track_idx, copy_file=False):
"""
Adds a new audio file to the corpus with the given data.
Parameters:
path (str): Path of the file to add.
track_idx (str): The id to associate the file-track with.
copy_file (bool): If True the file is copied to the data set folder, otherwise the given
path is used directly.
Returns:
FileTrack: The newly added file.
"""
new_file_idx = track_idx
new_file_path = os.path.abspath(path)
# Add index to idx if already existing
if new_file_idx in self._tracks.keys():
new_file_idx = naming.index_name_if_in_list(new_file_idx, self._tracks.keys())
# Copy file to default file dir
if copy_file:
if not os.path.isdir(self.path):
raise ValueError('To copy file the dataset needs to have a path.')
__, ext = os.path.splitext(path)
new_file_folder = os.path.join(self.path, DEFAULT_FILE_SUBDIR)
new_file_path = os.path.join(new_file_folder, '{}{}'.format(new_file_idx, ext))
os.makedirs(new_file_folder, exist_ok=True)
shutil.copy(path, new_file_path)
# Create file obj
new_file = tracks.FileTrack(new_file_idx, new_file_path)
self._tracks[new_file_idx] = new_file
return new_file | python | def new_file(self, path, track_idx, copy_file=False):
"""
Adds a new audio file to the corpus with the given data.
Parameters:
path (str): Path of the file to add.
track_idx (str): The id to associate the file-track with.
copy_file (bool): If True the file is copied to the data set folder, otherwise the given
path is used directly.
Returns:
FileTrack: The newly added file.
"""
new_file_idx = track_idx
new_file_path = os.path.abspath(path)
# Add index to idx if already existing
if new_file_idx in self._tracks.keys():
new_file_idx = naming.index_name_if_in_list(new_file_idx, self._tracks.keys())
# Copy file to default file dir
if copy_file:
if not os.path.isdir(self.path):
raise ValueError('To copy file the dataset needs to have a path.')
__, ext = os.path.splitext(path)
new_file_folder = os.path.join(self.path, DEFAULT_FILE_SUBDIR)
new_file_path = os.path.join(new_file_folder, '{}{}'.format(new_file_idx, ext))
os.makedirs(new_file_folder, exist_ok=True)
shutil.copy(path, new_file_path)
# Create file obj
new_file = tracks.FileTrack(new_file_idx, new_file_path)
self._tracks[new_file_idx] = new_file
return new_file | [
"def",
"new_file",
"(",
"self",
",",
"path",
",",
"track_idx",
",",
"copy_file",
"=",
"False",
")",
":",
"new_file_idx",
"=",
"track_idx",
"new_file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"# Add index to idx if already existing",
"if"... | Adds a new audio file to the corpus with the given data.
Parameters:
path (str): Path of the file to add.
track_idx (str): The id to associate the file-track with.
copy_file (bool): If True the file is copied to the data set folder, otherwise the given
path is used directly.
Returns:
FileTrack: The newly added file. | [
"Adds",
"a",
"new",
"audio",
"file",
"to",
"the",
"corpus",
"with",
"the",
"given",
"data",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L129-L166 | train | 32,703 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.new_utterance | def new_utterance(self, utterance_idx, track_idx, issuer_idx=None, start=0, end=float('inf')):
"""
Add a new utterance to the corpus with the given data.
Parameters:
track_idx (str): The track id the utterance is in.
utterance_idx (str): The id to associate with the utterance.
If None or already exists, one is generated.
issuer_idx (str): The issuer id to associate with the utterance.
start (float): Start of the utterance within the track [seconds].
end (float): End of the utterance within the track [seconds].
``inf`` equals the end of the track.
Returns:
Utterance: The newly added utterance.
"""
new_utt_idx = utterance_idx
# Check if there is a track with the given idx
if track_idx not in self._tracks.keys():
raise ValueError('Track with id {} does not exist!'.format(track_idx))
# Check if issuer exists
issuer = None
if issuer_idx is not None:
if issuer_idx not in self._issuers.keys():
raise ValueError('Issuer with id {} does not exist!'.format(issuer_idx))
else:
issuer = self._issuers[issuer_idx]
# Add index to idx if already existing
if new_utt_idx in self._utterances.keys():
new_utt_idx = naming.index_name_if_in_list(new_utt_idx, self._utterances.keys())
new_utt = tracks.Utterance(new_utt_idx,
self.tracks[track_idx],
issuer=issuer,
start=start,
end=end)
self._utterances[new_utt_idx] = new_utt
return new_utt | python | def new_utterance(self, utterance_idx, track_idx, issuer_idx=None, start=0, end=float('inf')):
"""
Add a new utterance to the corpus with the given data.
Parameters:
track_idx (str): The track id the utterance is in.
utterance_idx (str): The id to associate with the utterance.
If None or already exists, one is generated.
issuer_idx (str): The issuer id to associate with the utterance.
start (float): Start of the utterance within the track [seconds].
end (float): End of the utterance within the track [seconds].
``inf`` equals the end of the track.
Returns:
Utterance: The newly added utterance.
"""
new_utt_idx = utterance_idx
# Check if there is a track with the given idx
if track_idx not in self._tracks.keys():
raise ValueError('Track with id {} does not exist!'.format(track_idx))
# Check if issuer exists
issuer = None
if issuer_idx is not None:
if issuer_idx not in self._issuers.keys():
raise ValueError('Issuer with id {} does not exist!'.format(issuer_idx))
else:
issuer = self._issuers[issuer_idx]
# Add index to idx if already existing
if new_utt_idx in self._utterances.keys():
new_utt_idx = naming.index_name_if_in_list(new_utt_idx, self._utterances.keys())
new_utt = tracks.Utterance(new_utt_idx,
self.tracks[track_idx],
issuer=issuer,
start=start,
end=end)
self._utterances[new_utt_idx] = new_utt
return new_utt | [
"def",
"new_utterance",
"(",
"self",
",",
"utterance_idx",
",",
"track_idx",
",",
"issuer_idx",
"=",
"None",
",",
"start",
"=",
"0",
",",
"end",
"=",
"float",
"(",
"'inf'",
")",
")",
":",
"new_utt_idx",
"=",
"utterance_idx",
"# Check if there is a track with t... | Add a new utterance to the corpus with the given data.
Parameters:
track_idx (str): The track id the utterance is in.
utterance_idx (str): The id to associate with the utterance.
If None or already exists, one is generated.
issuer_idx (str): The issuer id to associate with the utterance.
start (float): Start of the utterance within the track [seconds].
end (float): End of the utterance within the track [seconds].
``inf`` equals the end of the track.
Returns:
Utterance: The newly added utterance. | [
"Add",
"a",
"new",
"utterance",
"to",
"the",
"corpus",
"with",
"the",
"given",
"data",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L202-L246 | train | 32,704 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.new_issuer | def new_issuer(self, issuer_idx, info=None):
"""
Add a new issuer to the dataset with the given data.
Parameters:
issuer_idx (str): The id to associate the issuer with. If None or already exists, one is
generated.
info (dict, list): Additional info of the issuer.
Returns:
Issuer: The newly added issuer.
"""
new_issuer_idx = issuer_idx
# Add index to idx if already existing
if new_issuer_idx in self._issuers.keys():
new_issuer_idx = naming.index_name_if_in_list(new_issuer_idx, self._issuers.keys())
new_issuer = issuers.Issuer(new_issuer_idx, info=info)
self._issuers[new_issuer_idx] = new_issuer
return new_issuer | python | def new_issuer(self, issuer_idx, info=None):
"""
Add a new issuer to the dataset with the given data.
Parameters:
issuer_idx (str): The id to associate the issuer with. If None or already exists, one is
generated.
info (dict, list): Additional info of the issuer.
Returns:
Issuer: The newly added issuer.
"""
new_issuer_idx = issuer_idx
# Add index to idx if already existing
if new_issuer_idx in self._issuers.keys():
new_issuer_idx = naming.index_name_if_in_list(new_issuer_idx, self._issuers.keys())
new_issuer = issuers.Issuer(new_issuer_idx, info=info)
self._issuers[new_issuer_idx] = new_issuer
return new_issuer | [
"def",
"new_issuer",
"(",
"self",
",",
"issuer_idx",
",",
"info",
"=",
"None",
")",
":",
"new_issuer_idx",
"=",
"issuer_idx",
"# Add index to idx if already existing",
"if",
"new_issuer_idx",
"in",
"self",
".",
"_issuers",
".",
"keys",
"(",
")",
":",
"new_issuer... | Add a new issuer to the dataset with the given data.
Parameters:
issuer_idx (str): The id to associate the issuer with. If None or already exists, one is
generated.
info (dict, list): Additional info of the issuer.
Returns:
Issuer: The newly added issuer. | [
"Add",
"a",
"new",
"issuer",
"to",
"the",
"dataset",
"with",
"the",
"given",
"data",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L291-L313 | train | 32,705 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.new_feature_container | def new_feature_container(self, idx, path=None):
"""
Add a new feature container with the given data.
Parameters:
idx (str): An unique identifier within the dataset.
path (str): The path to store the feature file. If None a default path is used.
Returns:
FeatureContainer: The newly added feature-container.
"""
new_feature_idx = idx
new_feature_path = path
# Add index to idx if already existing
if new_feature_idx in self._feature_containers.keys():
new_feature_idx = naming.index_name_if_in_list(new_feature_idx,
self._feature_containers.keys())
# Set default path if none given
if new_feature_path is None:
if not os.path.isdir(self.path):
raise ValueError('To copy file the dataset needs to have a path.')
new_feature_path = os.path.join(self.path, DEFAULT_FEAT_SUBDIR, new_feature_idx)
else:
new_feature_path = os.path.abspath(new_feature_path)
feat_container = containers.FeatureContainer(new_feature_path)
self._feature_containers[new_feature_idx] = feat_container
return feat_container | python | def new_feature_container(self, idx, path=None):
"""
Add a new feature container with the given data.
Parameters:
idx (str): An unique identifier within the dataset.
path (str): The path to store the feature file. If None a default path is used.
Returns:
FeatureContainer: The newly added feature-container.
"""
new_feature_idx = idx
new_feature_path = path
# Add index to idx if already existing
if new_feature_idx in self._feature_containers.keys():
new_feature_idx = naming.index_name_if_in_list(new_feature_idx,
self._feature_containers.keys())
# Set default path if none given
if new_feature_path is None:
if not os.path.isdir(self.path):
raise ValueError('To copy file the dataset needs to have a path.')
new_feature_path = os.path.join(self.path, DEFAULT_FEAT_SUBDIR, new_feature_idx)
else:
new_feature_path = os.path.abspath(new_feature_path)
feat_container = containers.FeatureContainer(new_feature_path)
self._feature_containers[new_feature_idx] = feat_container
return feat_container | [
"def",
"new_feature_container",
"(",
"self",
",",
"idx",
",",
"path",
"=",
"None",
")",
":",
"new_feature_idx",
"=",
"idx",
"new_feature_path",
"=",
"path",
"# Add index to idx if already existing",
"if",
"new_feature_idx",
"in",
"self",
".",
"_feature_containers",
... | Add a new feature container with the given data.
Parameters:
idx (str): An unique identifier within the dataset.
path (str): The path to store the feature file. If None a default path is used.
Returns:
FeatureContainer: The newly added feature-container. | [
"Add",
"a",
"new",
"feature",
"container",
"with",
"the",
"given",
"data",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L349-L381 | train | 32,706 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.import_subview | def import_subview(self, idx, subview):
"""
Add the given subview to the corpus.
Args:
idx (str): An idx that is unique in the corpus for identifying the subview.
If already a subview exists with the given id it will be overridden.
subview (Subview): The subview to add.
"""
subview.corpus = self
self._subviews[idx] = subview | python | def import_subview(self, idx, subview):
"""
Add the given subview to the corpus.
Args:
idx (str): An idx that is unique in the corpus for identifying the subview.
If already a subview exists with the given id it will be overridden.
subview (Subview): The subview to add.
"""
subview.corpus = self
self._subviews[idx] = subview | [
"def",
"import_subview",
"(",
"self",
",",
"idx",
",",
"subview",
")",
":",
"subview",
".",
"corpus",
"=",
"self",
"self",
".",
"_subviews",
"[",
"idx",
"]",
"=",
"subview"
] | Add the given subview to the corpus.
Args:
idx (str): An idx that is unique in the corpus for identifying the subview.
If already a subview exists with the given id it will be overridden.
subview (Subview): The subview to add. | [
"Add",
"the",
"given",
"subview",
"to",
"the",
"corpus",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L387-L398 | train | 32,707 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.relocate_audio_to_single_container | def relocate_audio_to_single_container(self, target_path):
"""
Copies every track to a single container.
Afterwards all tracks in the container are linked against
this single container.
"""
cont = containers.AudioContainer(target_path)
cont.open()
new_tracks = {}
# First create a new container track for all existing tracks
for track in self.tracks.values():
sr = track.sampling_rate
samples = track.read_samples()
cont.set(track.idx, samples, sr)
new_track = tracks.ContainerTrack(track.idx, cont)
new_tracks[track.idx] = new_track
# Update track list of corpus
self._tracks = new_tracks
# Update utterances to point to new tracks
for utterance in self.utterances.values():
new_track = self.tracks[utterance.track.idx]
utterance.track = new_track
cont.close() | python | def relocate_audio_to_single_container(self, target_path):
"""
Copies every track to a single container.
Afterwards all tracks in the container are linked against
this single container.
"""
cont = containers.AudioContainer(target_path)
cont.open()
new_tracks = {}
# First create a new container track for all existing tracks
for track in self.tracks.values():
sr = track.sampling_rate
samples = track.read_samples()
cont.set(track.idx, samples, sr)
new_track = tracks.ContainerTrack(track.idx, cont)
new_tracks[track.idx] = new_track
# Update track list of corpus
self._tracks = new_tracks
# Update utterances to point to new tracks
for utterance in self.utterances.values():
new_track = self.tracks[utterance.track.idx]
utterance.track = new_track
cont.close() | [
"def",
"relocate_audio_to_single_container",
"(",
"self",
",",
"target_path",
")",
":",
"cont",
"=",
"containers",
".",
"AudioContainer",
"(",
"target_path",
")",
"cont",
".",
"open",
"(",
")",
"new_tracks",
"=",
"{",
"}",
"# First create a new container track for a... | Copies every track to a single container.
Afterwards all tracks in the container are linked against
this single container. | [
"Copies",
"every",
"track",
"to",
"a",
"single",
"container",
".",
"Afterwards",
"all",
"tracks",
"in",
"the",
"container",
"are",
"linked",
"against",
"this",
"single",
"container",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L439-L469 | train | 32,708 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.from_corpus | def from_corpus(cls, corpus):
"""
Create a new modifiable corpus from any other CorpusView.
This for example can be used to create a independent modifiable corpus from a subview.
Args:
corpus (CorpusView): The corpus to create a copy from.
Returns:
Corpus: A new corpus with the same data as the given one.
"""
ds = Corpus()
# Tracks
tracks = copy.deepcopy(list(corpus.tracks.values()))
track_mapping = ds.import_tracks(tracks)
# Issuers
issuers = copy.deepcopy(list(corpus.issuers.values()))
issuer_mapping = ds.import_issuers(issuers)
# Utterances, with replacing changed track- and issuer-ids
utterances = copy.deepcopy(list(corpus.utterances.values()))
for utterance in utterances:
utterance.track = track_mapping[utterance.track.idx]
if utterance.issuer is not None:
utterance.issuer = issuer_mapping[utterance.issuer.idx]
ds.import_utterances(utterances)
# Subviews
subviews = copy.deepcopy(corpus.subviews)
for subview_idx, subview in subviews.items():
ds.import_subview(subview_idx, subview)
# Feat-Containers
for feat_container_idx, feature_container in corpus.feature_containers.items():
ds.new_feature_container(feat_container_idx, feature_container.path)
return ds | python | def from_corpus(cls, corpus):
"""
Create a new modifiable corpus from any other CorpusView.
This for example can be used to create a independent modifiable corpus from a subview.
Args:
corpus (CorpusView): The corpus to create a copy from.
Returns:
Corpus: A new corpus with the same data as the given one.
"""
ds = Corpus()
# Tracks
tracks = copy.deepcopy(list(corpus.tracks.values()))
track_mapping = ds.import_tracks(tracks)
# Issuers
issuers = copy.deepcopy(list(corpus.issuers.values()))
issuer_mapping = ds.import_issuers(issuers)
# Utterances, with replacing changed track- and issuer-ids
utterances = copy.deepcopy(list(corpus.utterances.values()))
for utterance in utterances:
utterance.track = track_mapping[utterance.track.idx]
if utterance.issuer is not None:
utterance.issuer = issuer_mapping[utterance.issuer.idx]
ds.import_utterances(utterances)
# Subviews
subviews = copy.deepcopy(corpus.subviews)
for subview_idx, subview in subviews.items():
ds.import_subview(subview_idx, subview)
# Feat-Containers
for feat_container_idx, feature_container in corpus.feature_containers.items():
ds.new_feature_container(feat_container_idx, feature_container.path)
return ds | [
"def",
"from_corpus",
"(",
"cls",
",",
"corpus",
")",
":",
"ds",
"=",
"Corpus",
"(",
")",
"# Tracks",
"tracks",
"=",
"copy",
".",
"deepcopy",
"(",
"list",
"(",
"corpus",
".",
"tracks",
".",
"values",
"(",
")",
")",
")",
"track_mapping",
"=",
"ds",
... | Create a new modifiable corpus from any other CorpusView.
This for example can be used to create a independent modifiable corpus from a subview.
Args:
corpus (CorpusView): The corpus to create a copy from.
Returns:
Corpus: A new corpus with the same data as the given one. | [
"Create",
"a",
"new",
"modifiable",
"corpus",
"from",
"any",
"other",
"CorpusView",
".",
"This",
"for",
"example",
"can",
"be",
"used",
"to",
"create",
"a",
"independent",
"modifiable",
"corpus",
"from",
"a",
"subview",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L506-L547 | train | 32,709 |
ynop/audiomate | audiomate/corpus/corpus.py | Corpus.merge_corpora | def merge_corpora(cls, corpora):
"""
Merge a list of corpora into one.
Args:
corpora (Iterable): An iterable of :py:class:`audiomate.corpus.CorpusView`.
Returns:
Corpus: A corpus with the data from all given corpora merged into one.
"""
ds = Corpus()
for merging_corpus in corpora:
ds.merge_corpus(merging_corpus)
return ds | python | def merge_corpora(cls, corpora):
"""
Merge a list of corpora into one.
Args:
corpora (Iterable): An iterable of :py:class:`audiomate.corpus.CorpusView`.
Returns:
Corpus: A corpus with the data from all given corpora merged into one.
"""
ds = Corpus()
for merging_corpus in corpora:
ds.merge_corpus(merging_corpus)
return ds | [
"def",
"merge_corpora",
"(",
"cls",
",",
"corpora",
")",
":",
"ds",
"=",
"Corpus",
"(",
")",
"for",
"merging_corpus",
"in",
"corpora",
":",
"ds",
".",
"merge_corpus",
"(",
"merging_corpus",
")",
"return",
"ds"
] | Merge a list of corpora into one.
Args:
corpora (Iterable): An iterable of :py:class:`audiomate.corpus.CorpusView`.
Returns:
Corpus: A corpus with the data from all given corpora merged into one. | [
"Merge",
"a",
"list",
"of",
"corpora",
"into",
"one",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L550-L566 | train | 32,710 |
ynop/audiomate | audiomate/corpus/io/common_voice.py | CommonVoiceReader.load_subset | def load_subset(corpus, path, subset_idx):
""" Load subset into corpus. """
csv_file = os.path.join(path, '{}.tsv'.format(subset_idx))
subset_utt_ids = []
entries = textfile.read_separated_lines_generator(
csv_file,
separator='\t',
max_columns=8,
ignore_lines_starting_with=['client_id'],
keep_empty=True
)
for entry in entries:
file_idx = CommonVoiceReader.create_assets_if_needed(
corpus,
path,
entry
)
subset_utt_ids.append(file_idx)
filter = subset.MatchingUtteranceIdxFilter(utterance_idxs=set(subset_utt_ids))
subview = subset.Subview(corpus, filter_criteria=[filter])
corpus.import_subview(subset_idx, subview) | python | def load_subset(corpus, path, subset_idx):
""" Load subset into corpus. """
csv_file = os.path.join(path, '{}.tsv'.format(subset_idx))
subset_utt_ids = []
entries = textfile.read_separated_lines_generator(
csv_file,
separator='\t',
max_columns=8,
ignore_lines_starting_with=['client_id'],
keep_empty=True
)
for entry in entries:
file_idx = CommonVoiceReader.create_assets_if_needed(
corpus,
path,
entry
)
subset_utt_ids.append(file_idx)
filter = subset.MatchingUtteranceIdxFilter(utterance_idxs=set(subset_utt_ids))
subview = subset.Subview(corpus, filter_criteria=[filter])
corpus.import_subview(subset_idx, subview) | [
"def",
"load_subset",
"(",
"corpus",
",",
"path",
",",
"subset_idx",
")",
":",
"csv_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'{}.tsv'",
".",
"format",
"(",
"subset_idx",
")",
")",
"subset_utt_ids",
"=",
"[",
"]",
"entries",
"=",
... | Load subset into corpus. | [
"Load",
"subset",
"into",
"corpus",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/common_voice.py#L51-L75 | train | 32,711 |
ynop/audiomate | audiomate/corpus/io/common_voice.py | CommonVoiceReader.map_age | def map_age(age):
""" Map age to correct age-group. """
if age in [None, '']:
return issuers.AgeGroup.UNKNOWN
elif age == 'teens':
return issuers.AgeGroup.YOUTH
elif age in ['sixties', 'seventies', 'eighties', 'nineties']:
return issuers.AgeGroup.SENIOR
else:
return issuers.AgeGroup.ADULT | python | def map_age(age):
""" Map age to correct age-group. """
if age in [None, '']:
return issuers.AgeGroup.UNKNOWN
elif age == 'teens':
return issuers.AgeGroup.YOUTH
elif age in ['sixties', 'seventies', 'eighties', 'nineties']:
return issuers.AgeGroup.SENIOR
else:
return issuers.AgeGroup.ADULT | [
"def",
"map_age",
"(",
"age",
")",
":",
"if",
"age",
"in",
"[",
"None",
",",
"''",
"]",
":",
"return",
"issuers",
".",
"AgeGroup",
".",
"UNKNOWN",
"elif",
"age",
"==",
"'teens'",
":",
"return",
"issuers",
".",
"AgeGroup",
".",
"YOUTH",
"elif",
"age",... | Map age to correct age-group. | [
"Map",
"age",
"to",
"correct",
"age",
"-",
"group",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/common_voice.py#L110-L120 | train | 32,712 |
ynop/audiomate | audiomate/corpus/io/common_voice.py | CommonVoiceReader.map_gender | def map_gender(gender):
""" Map gender to correct value. """
if gender == 'male':
return issuers.Gender.MALE
elif gender == 'female':
return issuers.Gender.FEMALE
else:
return issuers.Gender.UNKNOWN | python | def map_gender(gender):
""" Map gender to correct value. """
if gender == 'male':
return issuers.Gender.MALE
elif gender == 'female':
return issuers.Gender.FEMALE
else:
return issuers.Gender.UNKNOWN | [
"def",
"map_gender",
"(",
"gender",
")",
":",
"if",
"gender",
"==",
"'male'",
":",
"return",
"issuers",
".",
"Gender",
".",
"MALE",
"elif",
"gender",
"==",
"'female'",
":",
"return",
"issuers",
".",
"Gender",
".",
"FEMALE",
"else",
":",
"return",
"issuer... | Map gender to correct value. | [
"Map",
"gender",
"to",
"correct",
"value",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/common_voice.py#L123-L131 | train | 32,713 |
ynop/audiomate | audiomate/utils/units.py | FrameSettings.num_frames | def num_frames(self, num_samples):
"""
Return the number of frames that will be used for a signal with the length of ``num_samples``.
"""
return math.ceil(float(max(num_samples - self.frame_size, 0)) / float(self.hop_size)) + 1 | python | def num_frames(self, num_samples):
"""
Return the number of frames that will be used for a signal with the length of ``num_samples``.
"""
return math.ceil(float(max(num_samples - self.frame_size, 0)) / float(self.hop_size)) + 1 | [
"def",
"num_frames",
"(",
"self",
",",
"num_samples",
")",
":",
"return",
"math",
".",
"ceil",
"(",
"float",
"(",
"max",
"(",
"num_samples",
"-",
"self",
".",
"frame_size",
",",
"0",
")",
")",
"/",
"float",
"(",
"self",
".",
"hop_size",
")",
")",
"... | Return the number of frames that will be used for a signal with the length of ``num_samples``. | [
"Return",
"the",
"number",
"of",
"frames",
"that",
"will",
"be",
"used",
"for",
"a",
"signal",
"with",
"the",
"length",
"of",
"num_samples",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/units.py#L102-L106 | train | 32,714 |
ynop/audiomate | audiomate/utils/units.py | FrameSettings.frame_to_seconds | def frame_to_seconds(self, frame_index, sr):
"""
Return a tuple containing the start and end of the frame in seconds.
"""
start_sample, end_sample = self.frame_to_sample(frame_index)
return sample_to_seconds(start_sample, sampling_rate=sr), sample_to_seconds(end_sample, sampling_rate=sr) | python | def frame_to_seconds(self, frame_index, sr):
"""
Return a tuple containing the start and end of the frame in seconds.
"""
start_sample, end_sample = self.frame_to_sample(frame_index)
return sample_to_seconds(start_sample, sampling_rate=sr), sample_to_seconds(end_sample, sampling_rate=sr) | [
"def",
"frame_to_seconds",
"(",
"self",
",",
"frame_index",
",",
"sr",
")",
":",
"start_sample",
",",
"end_sample",
"=",
"self",
".",
"frame_to_sample",
"(",
"frame_index",
")",
"return",
"sample_to_seconds",
"(",
"start_sample",
",",
"sampling_rate",
"=",
"sr",... | Return a tuple containing the start and end of the frame in seconds. | [
"Return",
"a",
"tuple",
"containing",
"the",
"start",
"and",
"end",
"of",
"the",
"frame",
"in",
"seconds",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/units.py#L126-L131 | train | 32,715 |
ynop/audiomate | audiomate/utils/units.py | FrameSettings.time_range_to_frame_range | def time_range_to_frame_range(self, start, end, sr):
"""
Calculate the frames containing samples from the given time range in seconds.
Args:
start (float): Start time in seconds.
end (float): End time in seconds.
sr (int): The sampling rate to use for time-to-sample conversion.
Returns:
tuple: A tuple containing the start and end (exclusive) frame indices.
"""
start_sample = seconds_to_sample(start, sr)
end_sample = seconds_to_sample(end, sr)
return self.sample_to_frame_range(start_sample)[0], self.sample_to_frame_range(end_sample - 1)[1] | python | def time_range_to_frame_range(self, start, end, sr):
"""
Calculate the frames containing samples from the given time range in seconds.
Args:
start (float): Start time in seconds.
end (float): End time in seconds.
sr (int): The sampling rate to use for time-to-sample conversion.
Returns:
tuple: A tuple containing the start and end (exclusive) frame indices.
"""
start_sample = seconds_to_sample(start, sr)
end_sample = seconds_to_sample(end, sr)
return self.sample_to_frame_range(start_sample)[0], self.sample_to_frame_range(end_sample - 1)[1] | [
"def",
"time_range_to_frame_range",
"(",
"self",
",",
"start",
",",
"end",
",",
"sr",
")",
":",
"start_sample",
"=",
"seconds_to_sample",
"(",
"start",
",",
"sr",
")",
"end_sample",
"=",
"seconds_to_sample",
"(",
"end",
",",
"sr",
")",
"return",
"self",
".... | Calculate the frames containing samples from the given time range in seconds.
Args:
start (float): Start time in seconds.
end (float): End time in seconds.
sr (int): The sampling rate to use for time-to-sample conversion.
Returns:
tuple: A tuple containing the start and end (exclusive) frame indices. | [
"Calculate",
"the",
"frames",
"containing",
"samples",
"from",
"the",
"given",
"time",
"range",
"in",
"seconds",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/units.py#L133-L149 | train | 32,716 |
ynop/audiomate | audiomate/processing/base.py | Processor._process_corpus | def _process_corpus(self, corpus, output_path, processing_func, frame_size=400, hop_size=160, sr=None):
""" Utility function for processing a corpus with a separate processing function. """
feat_container = containers.FeatureContainer(output_path)
feat_container.open()
sampling_rate = -1
for utterance in corpus.utterances.values():
utt_sampling_rate = utterance.sampling_rate
if sr is None:
if sampling_rate > 0 and sampling_rate != utt_sampling_rate:
raise ValueError(
'File {} has a different sampling-rate than the previous ones!'.format(utterance.track.idx))
sampling_rate = utt_sampling_rate
processing_func(utterance, feat_container, frame_size, hop_size, sr, corpus)
tf_frame_size, tf_hop_size = self.frame_transform(frame_size, hop_size)
feat_container.frame_size = tf_frame_size
feat_container.hop_size = tf_hop_size
feat_container.sampling_rate = sr or sampling_rate
feat_container.close()
return feat_container | python | def _process_corpus(self, corpus, output_path, processing_func, frame_size=400, hop_size=160, sr=None):
""" Utility function for processing a corpus with a separate processing function. """
feat_container = containers.FeatureContainer(output_path)
feat_container.open()
sampling_rate = -1
for utterance in corpus.utterances.values():
utt_sampling_rate = utterance.sampling_rate
if sr is None:
if sampling_rate > 0 and sampling_rate != utt_sampling_rate:
raise ValueError(
'File {} has a different sampling-rate than the previous ones!'.format(utterance.track.idx))
sampling_rate = utt_sampling_rate
processing_func(utterance, feat_container, frame_size, hop_size, sr, corpus)
tf_frame_size, tf_hop_size = self.frame_transform(frame_size, hop_size)
feat_container.frame_size = tf_frame_size
feat_container.hop_size = tf_hop_size
feat_container.sampling_rate = sr or sampling_rate
feat_container.close()
return feat_container | [
"def",
"_process_corpus",
"(",
"self",
",",
"corpus",
",",
"output_path",
",",
"processing_func",
",",
"frame_size",
"=",
"400",
",",
"hop_size",
"=",
"160",
",",
"sr",
"=",
"None",
")",
":",
"feat_container",
"=",
"containers",
".",
"FeatureContainer",
"(",... | Utility function for processing a corpus with a separate processing function. | [
"Utility",
"function",
"for",
"processing",
"a",
"corpus",
"with",
"a",
"separate",
"processing",
"function",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/base.py#L358-L384 | train | 32,717 |
ynop/audiomate | audiomate/utils/audio.py | process_buffer | def process_buffer(buffer, n_channels):
"""
Merge the read blocks and resample if necessary.
Args:
buffer (list): A list of blocks of samples.
n_channels (int): The number of channels of the input data.
Returns:
np.array: The samples
"""
samples = np.concatenate(buffer)
if n_channels > 1:
samples = samples.reshape((-1, n_channels)).T
samples = librosa.to_mono(samples)
return samples | python | def process_buffer(buffer, n_channels):
"""
Merge the read blocks and resample if necessary.
Args:
buffer (list): A list of blocks of samples.
n_channels (int): The number of channels of the input data.
Returns:
np.array: The samples
"""
samples = np.concatenate(buffer)
if n_channels > 1:
samples = samples.reshape((-1, n_channels)).T
samples = librosa.to_mono(samples)
return samples | [
"def",
"process_buffer",
"(",
"buffer",
",",
"n_channels",
")",
":",
"samples",
"=",
"np",
".",
"concatenate",
"(",
"buffer",
")",
"if",
"n_channels",
">",
"1",
":",
"samples",
"=",
"samples",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"n_channels",
")",... | Merge the read blocks and resample if necessary.
Args:
buffer (list): A list of blocks of samples.
n_channels (int): The number of channels of the input data.
Returns:
np.array: The samples | [
"Merge",
"the",
"read",
"blocks",
"and",
"resample",
"if",
"necessary",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/audio.py#L7-L24 | train | 32,718 |
ynop/audiomate | audiomate/utils/audio.py | read_blocks | def read_blocks(file_path, start=0.0, end=float('inf'), buffer_size=5760000):
"""
Read an audio file block after block. The blocks are yielded one by one.
Args:
file_path (str): Path to the file to read.
start (float): Start in seconds to read from.
end (float): End in seconds to read to.
``inf`` means to the end of the file.
buffer_size (int): Number of samples to load into memory at once and
return as a single block. The exact number of loaded
samples depends on the block-size of the
audioread library. So it can be of x higher,
where the x is typically 1024 or 4096.
Returns:
Generator: A generator yielding the samples for every block.
"""
buffer = []
n_buffer = 0
n_samples = 0
with audioread.audio_open(file_path) as input_file:
n_channels = input_file.channels
sr_native = input_file.samplerate
start_sample = int(np.round(sr_native * start)) * n_channels
end_sample = end
if end_sample != np.inf:
end_sample = int(np.round(sr_native * end)) * n_channels
for block in input_file:
block = librosa.util.buf_to_float(block)
n_prev = n_samples
n_samples += len(block)
if n_samples < start_sample:
continue
if n_prev > end_sample:
break
if n_samples > end_sample:
block = block[:end_sample - n_prev]
if n_prev <= start_sample <= n_samples:
block = block[start_sample - n_prev:]
n_buffer += len(block)
buffer.append(block)
if n_buffer >= buffer_size:
yield process_buffer(buffer, n_channels)
buffer = []
n_buffer = 0
if len(buffer) > 0:
yield process_buffer(buffer, n_channels) | python | def read_blocks(file_path, start=0.0, end=float('inf'), buffer_size=5760000):
"""
Read an audio file block after block. The blocks are yielded one by one.
Args:
file_path (str): Path to the file to read.
start (float): Start in seconds to read from.
end (float): End in seconds to read to.
``inf`` means to the end of the file.
buffer_size (int): Number of samples to load into memory at once and
return as a single block. The exact number of loaded
samples depends on the block-size of the
audioread library. So it can be of x higher,
where the x is typically 1024 or 4096.
Returns:
Generator: A generator yielding the samples for every block.
"""
buffer = []
n_buffer = 0
n_samples = 0
with audioread.audio_open(file_path) as input_file:
n_channels = input_file.channels
sr_native = input_file.samplerate
start_sample = int(np.round(sr_native * start)) * n_channels
end_sample = end
if end_sample != np.inf:
end_sample = int(np.round(sr_native * end)) * n_channels
for block in input_file:
block = librosa.util.buf_to_float(block)
n_prev = n_samples
n_samples += len(block)
if n_samples < start_sample:
continue
if n_prev > end_sample:
break
if n_samples > end_sample:
block = block[:end_sample - n_prev]
if n_prev <= start_sample <= n_samples:
block = block[start_sample - n_prev:]
n_buffer += len(block)
buffer.append(block)
if n_buffer >= buffer_size:
yield process_buffer(buffer, n_channels)
buffer = []
n_buffer = 0
if len(buffer) > 0:
yield process_buffer(buffer, n_channels) | [
"def",
"read_blocks",
"(",
"file_path",
",",
"start",
"=",
"0.0",
",",
"end",
"=",
"float",
"(",
"'inf'",
")",
",",
"buffer_size",
"=",
"5760000",
")",
":",
"buffer",
"=",
"[",
"]",
"n_buffer",
"=",
"0",
"n_samples",
"=",
"0",
"with",
"audioread",
".... | Read an audio file block after block. The blocks are yielded one by one.
Args:
file_path (str): Path to the file to read.
start (float): Start in seconds to read from.
end (float): End in seconds to read to.
``inf`` means to the end of the file.
buffer_size (int): Number of samples to load into memory at once and
return as a single block. The exact number of loaded
samples depends on the block-size of the
audioread library. So it can be of x higher,
where the x is typically 1024 or 4096.
Returns:
Generator: A generator yielding the samples for every block. | [
"Read",
"an",
"audio",
"file",
"block",
"after",
"block",
".",
"The",
"blocks",
"are",
"yielded",
"one",
"by",
"one",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/audio.py#L27-L86 | train | 32,719 |
ynop/audiomate | audiomate/utils/audio.py | read_frames | def read_frames(file_path, frame_size, hop_size, start=0.0,
end=float('inf'), buffer_size=5760000):
"""
Read an audio file frame by frame. The frames are yielded one after another.
Args:
file_path (str): Path to the file to read.
frame_size (int): The number of samples per frame.
hop_size (int): The number of samples between two frames.
start (float): Start in seconds to read from.
end (float): End in seconds to read to.
``inf`` means to the end of the file.
buffer_size (int): Number of samples to load into memory at once
and return as a single block.
The exact number of loaded samples depends on the
block-size of the audioread library. So it can be
of x higher, where the x is typically 1024 or 4096.
Returns:
Generator: A generator yielding a tuple for every frame.
The first item is the frame and
the second a boolean indicating if it is the last frame.
"""
rest_samples = np.array([], dtype=np.float32)
for block in read_blocks(file_path, start=start, end=end, buffer_size=buffer_size):
# Prepend rest samples from previous block
block = np.concatenate([rest_samples, block])
current_sample = 0
# Get frames that are fully contained in the block
while current_sample + frame_size < block.size:
frame = block[current_sample:current_sample + frame_size]
yield frame, False
current_sample += hop_size
# Store rest samples for next block
rest_samples = block[current_sample:]
if rest_samples.size > 0:
rest_samples = np.pad(
rest_samples,
(0, frame_size - rest_samples.size),
mode='constant',
constant_values=0
)
yield rest_samples, True | python | def read_frames(file_path, frame_size, hop_size, start=0.0,
end=float('inf'), buffer_size=5760000):
"""
Read an audio file frame by frame. The frames are yielded one after another.
Args:
file_path (str): Path to the file to read.
frame_size (int): The number of samples per frame.
hop_size (int): The number of samples between two frames.
start (float): Start in seconds to read from.
end (float): End in seconds to read to.
``inf`` means to the end of the file.
buffer_size (int): Number of samples to load into memory at once
and return as a single block.
The exact number of loaded samples depends on the
block-size of the audioread library. So it can be
of x higher, where the x is typically 1024 or 4096.
Returns:
Generator: A generator yielding a tuple for every frame.
The first item is the frame and
the second a boolean indicating if it is the last frame.
"""
rest_samples = np.array([], dtype=np.float32)
for block in read_blocks(file_path, start=start, end=end, buffer_size=buffer_size):
# Prepend rest samples from previous block
block = np.concatenate([rest_samples, block])
current_sample = 0
# Get frames that are fully contained in the block
while current_sample + frame_size < block.size:
frame = block[current_sample:current_sample + frame_size]
yield frame, False
current_sample += hop_size
# Store rest samples for next block
rest_samples = block[current_sample:]
if rest_samples.size > 0:
rest_samples = np.pad(
rest_samples,
(0, frame_size - rest_samples.size),
mode='constant',
constant_values=0
)
yield rest_samples, True | [
"def",
"read_frames",
"(",
"file_path",
",",
"frame_size",
",",
"hop_size",
",",
"start",
"=",
"0.0",
",",
"end",
"=",
"float",
"(",
"'inf'",
")",
",",
"buffer_size",
"=",
"5760000",
")",
":",
"rest_samples",
"=",
"np",
".",
"array",
"(",
"[",
"]",
"... | Read an audio file frame by frame. The frames are yielded one after another.
Args:
file_path (str): Path to the file to read.
frame_size (int): The number of samples per frame.
hop_size (int): The number of samples between two frames.
start (float): Start in seconds to read from.
end (float): End in seconds to read to.
``inf`` means to the end of the file.
buffer_size (int): Number of samples to load into memory at once
and return as a single block.
The exact number of loaded samples depends on the
block-size of the audioread library. So it can be
of x higher, where the x is typically 1024 or 4096.
Returns:
Generator: A generator yielding a tuple for every frame.
The first item is the frame and
the second a boolean indicating if it is the last frame. | [
"Read",
"an",
"audio",
"file",
"frame",
"by",
"frame",
".",
"The",
"frames",
"are",
"yielded",
"one",
"after",
"another",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/audio.py#L89-L137 | train | 32,720 |
ynop/audiomate | audiomate/utils/audio.py | write_wav | def write_wav(path, samples, sr=16000):
"""
Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rate.
"""
max_value = np.abs(np.iinfo(np.int16).min)
data = (samples * max_value).astype(np.int16)
scipy.io.wavfile.write(path, sr, data) | python | def write_wav(path, samples, sr=16000):
"""
Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rate.
"""
max_value = np.abs(np.iinfo(np.int16).min)
data = (samples * max_value).astype(np.int16)
scipy.io.wavfile.write(path, sr, data) | [
"def",
"write_wav",
"(",
"path",
",",
"samples",
",",
"sr",
"=",
"16000",
")",
":",
"max_value",
"=",
"np",
".",
"abs",
"(",
"np",
".",
"iinfo",
"(",
"np",
".",
"int16",
")",
".",
"min",
")",
"data",
"=",
"(",
"samples",
"*",
"max_value",
")",
... | Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rate. | [
"Write",
"to",
"given",
"samples",
"to",
"a",
"wav",
"file",
".",
"The",
"samples",
"are",
"expected",
"to",
"be",
"floating",
"point",
"numbers",
"in",
"the",
"range",
"of",
"-",
"1",
".",
"0",
"to",
"1",
".",
"0",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/audio.py#L140-L153 | train | 32,721 |
ynop/audiomate | audiomate/utils/stats.py | DataStats.to_dict | def to_dict(self):
"""
Return the stats as a dictionary.
"""
return {
'mean': self.mean,
'var': self.var,
'min': self.min,
'max': self.max,
'num': self.num
} | python | def to_dict(self):
"""
Return the stats as a dictionary.
"""
return {
'mean': self.mean,
'var': self.var,
'min': self.min,
'max': self.max,
'num': self.num
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'mean'",
":",
"self",
".",
"mean",
",",
"'var'",
":",
"self",
".",
"var",
",",
"'min'",
":",
"self",
".",
"min",
",",
"'max'",
":",
"self",
".",
"max",
",",
"'num'",
":",
"self",
".",
"nu... | Return the stats as a dictionary. | [
"Return",
"the",
"stats",
"as",
"a",
"dictionary",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/stats.py#L32-L42 | train | 32,722 |
ynop/audiomate | audiomate/utils/stats.py | DataStats.concatenate | def concatenate(cls, list_of_stats):
"""
Take a list of stats from different sets of data points and
merge the stats for getting stats overall data points.
Args:
list_of_stats (iterable): A list containing stats for different sets of data points.
Returns:
DataStats: Stats calculated overall sets of data points.
"""
all_stats = np.stack([stats.values for stats in list_of_stats])
all_counts = all_stats[:, 4]
all_counts_relative = all_counts / np.sum(all_counts)
min_value = float(np.min(all_stats[:, 2]))
max_value = float(np.max(all_stats[:, 3]))
mean_value = float(np.sum(all_counts_relative * all_stats[:, 0]))
var_value = float(np.sum(all_counts_relative * (all_stats[:, 1] + np.power(all_stats[:, 0] - mean_value, 2))))
num_value = int(np.sum(all_counts))
return cls(mean_value, var_value, min_value, max_value, num_value) | python | def concatenate(cls, list_of_stats):
"""
Take a list of stats from different sets of data points and
merge the stats for getting stats overall data points.
Args:
list_of_stats (iterable): A list containing stats for different sets of data points.
Returns:
DataStats: Stats calculated overall sets of data points.
"""
all_stats = np.stack([stats.values for stats in list_of_stats])
all_counts = all_stats[:, 4]
all_counts_relative = all_counts / np.sum(all_counts)
min_value = float(np.min(all_stats[:, 2]))
max_value = float(np.max(all_stats[:, 3]))
mean_value = float(np.sum(all_counts_relative * all_stats[:, 0]))
var_value = float(np.sum(all_counts_relative * (all_stats[:, 1] + np.power(all_stats[:, 0] - mean_value, 2))))
num_value = int(np.sum(all_counts))
return cls(mean_value, var_value, min_value, max_value, num_value) | [
"def",
"concatenate",
"(",
"cls",
",",
"list_of_stats",
")",
":",
"all_stats",
"=",
"np",
".",
"stack",
"(",
"[",
"stats",
".",
"values",
"for",
"stats",
"in",
"list_of_stats",
"]",
")",
"all_counts",
"=",
"all_stats",
"[",
":",
",",
"4",
"]",
"all_cou... | Take a list of stats from different sets of data points and
merge the stats for getting stats overall data points.
Args:
list_of_stats (iterable): A list containing stats for different sets of data points.
Returns:
DataStats: Stats calculated overall sets of data points. | [
"Take",
"a",
"list",
"of",
"stats",
"from",
"different",
"sets",
"of",
"data",
"points",
"and",
"merge",
"the",
"stats",
"for",
"getting",
"stats",
"overall",
"data",
"points",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/stats.py#L63-L85 | train | 32,723 |
ynop/audiomate | bench/resources/__init__.py | generate_corpus | def generate_corpus(n_issuers,
n_tracks_per_issuer,
n_utts_per_track,
n_ll_per_utt,
n_label_per_ll,
rand=None):
"""
Generate a corpus with mock data.
"""
corpus = audiomate.Corpus()
for issuer in generate_issuers(n_issuers, rand):
corpus.import_issuers(issuer)
n_tracks = rand.randint(*n_tracks_per_issuer)
tracks = generate_tracks(n_tracks, rand)
corpus.import_tracks(tracks)
n_utts = rand.randint(*n_utts_per_track)
for track in tracks:
utts = generate_utterances(
track,
issuer,
n_utts,
n_ll_per_utt,
n_label_per_ll,
rand
)
corpus.import_utterances(utts)
return corpus | python | def generate_corpus(n_issuers,
n_tracks_per_issuer,
n_utts_per_track,
n_ll_per_utt,
n_label_per_ll,
rand=None):
"""
Generate a corpus with mock data.
"""
corpus = audiomate.Corpus()
for issuer in generate_issuers(n_issuers, rand):
corpus.import_issuers(issuer)
n_tracks = rand.randint(*n_tracks_per_issuer)
tracks = generate_tracks(n_tracks, rand)
corpus.import_tracks(tracks)
n_utts = rand.randint(*n_utts_per_track)
for track in tracks:
utts = generate_utterances(
track,
issuer,
n_utts,
n_ll_per_utt,
n_label_per_ll,
rand
)
corpus.import_utterances(utts)
return corpus | [
"def",
"generate_corpus",
"(",
"n_issuers",
",",
"n_tracks_per_issuer",
",",
"n_utts_per_track",
",",
"n_ll_per_utt",
",",
"n_label_per_ll",
",",
"rand",
"=",
"None",
")",
":",
"corpus",
"=",
"audiomate",
".",
"Corpus",
"(",
")",
"for",
"issuer",
"in",
"genera... | Generate a corpus with mock data. | [
"Generate",
"a",
"corpus",
"with",
"mock",
"data",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/bench/resources/__init__.py#L9-L40 | train | 32,724 |
ynop/audiomate | audiomate/corpus/io/speech_commands.py | SpeechCommandsReader._create_subviews | def _create_subviews(path, corpus):
""" Load the subviews based on testing_list.txt and validation_list.txt """
test_list_path = os.path.join(path, 'testing_list.txt')
dev_list_path = os.path.join(path, 'validation_list.txt')
test_list = textfile.read_separated_lines(test_list_path, separator='/', max_columns=2)
dev_list = textfile.read_separated_lines(dev_list_path, separator='/', max_columns=2)
test_set = set(['{}_{}'.format(os.path.splitext(x[1])[0], x[0]) for x in test_list])
dev_set = set(['{}_{}'.format(os.path.splitext(x[1])[0], x[0]) for x in dev_list])
inv_train_set = test_set.union(dev_set)
train_filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=inv_train_set, inverse=True)
train_view = subview.Subview(corpus, filter_criteria=train_filter)
corpus.import_subview('train', train_view)
dev_filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=dev_set, inverse=False)
dev_view = subview.Subview(corpus, filter_criteria=dev_filter)
corpus.import_subview('dev', dev_view)
test_filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=test_set, inverse=False)
test_view = subview.Subview(corpus, filter_criteria=test_filter)
corpus.import_subview('test', test_view) | python | def _create_subviews(path, corpus):
""" Load the subviews based on testing_list.txt and validation_list.txt """
test_list_path = os.path.join(path, 'testing_list.txt')
dev_list_path = os.path.join(path, 'validation_list.txt')
test_list = textfile.read_separated_lines(test_list_path, separator='/', max_columns=2)
dev_list = textfile.read_separated_lines(dev_list_path, separator='/', max_columns=2)
test_set = set(['{}_{}'.format(os.path.splitext(x[1])[0], x[0]) for x in test_list])
dev_set = set(['{}_{}'.format(os.path.splitext(x[1])[0], x[0]) for x in dev_list])
inv_train_set = test_set.union(dev_set)
train_filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=inv_train_set, inverse=True)
train_view = subview.Subview(corpus, filter_criteria=train_filter)
corpus.import_subview('train', train_view)
dev_filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=dev_set, inverse=False)
dev_view = subview.Subview(corpus, filter_criteria=dev_filter)
corpus.import_subview('dev', dev_view)
test_filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=test_set, inverse=False)
test_view = subview.Subview(corpus, filter_criteria=test_filter)
corpus.import_subview('test', test_view) | [
"def",
"_create_subviews",
"(",
"path",
",",
"corpus",
")",
":",
"test_list_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'testing_list.txt'",
")",
"dev_list_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'validation_list.t... | Load the subviews based on testing_list.txt and validation_list.txt | [
"Load",
"the",
"subviews",
"based",
"on",
"testing_list",
".",
"txt",
"and",
"validation_list",
".",
"txt"
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/speech_commands.py#L64-L86 | train | 32,725 |
ynop/audiomate | audiomate/formats/audacity.py | write_label_list | def write_label_list(path, label_list):
"""
Writes the given `label_list` to an audacity label file.
Args:
path (str): Path to write the file to.
label_list (audiomate.annotations.LabelList): Label list
"""
entries = []
for label in label_list:
entries.append([label.start, label.end, label.value])
textfile.write_separated_lines(path, entries, separator='\t') | python | def write_label_list(path, label_list):
"""
Writes the given `label_list` to an audacity label file.
Args:
path (str): Path to write the file to.
label_list (audiomate.annotations.LabelList): Label list
"""
entries = []
for label in label_list:
entries.append([label.start, label.end, label.value])
textfile.write_separated_lines(path, entries, separator='\t') | [
"def",
"write_label_list",
"(",
"path",
",",
"label_list",
")",
":",
"entries",
"=",
"[",
"]",
"for",
"label",
"in",
"label_list",
":",
"entries",
".",
"append",
"(",
"[",
"label",
".",
"start",
",",
"label",
".",
"end",
",",
"label",
".",
"value",
"... | Writes the given `label_list` to an audacity label file.
Args:
path (str): Path to write the file to.
label_list (audiomate.annotations.LabelList): Label list | [
"Writes",
"the",
"given",
"label_list",
"to",
"an",
"audacity",
"label",
"file",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/formats/audacity.py#L30-L42 | train | 32,726 |
ynop/audiomate | audiomate/formats/audacity.py | read_label_file | def read_label_file(path):
"""
Read the labels from an audacity label file.
Args:
path (str): Path to the label file.
Returns:
list: List of labels (start [sec], end [sec], label)
Example::
>>> read_label_file('/path/to/label/file.txt')
[
[0.0, 0.2, 'sie'],
[0.2, 2.2, 'hallo']
]
"""
labels = []
for record in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3):
value = ''
if len(record) > 2:
value = str(record[2])
labels.append([float(_clean_time(record[0])), float(_clean_time(record[1])), value])
return labels | python | def read_label_file(path):
"""
Read the labels from an audacity label file.
Args:
path (str): Path to the label file.
Returns:
list: List of labels (start [sec], end [sec], label)
Example::
>>> read_label_file('/path/to/label/file.txt')
[
[0.0, 0.2, 'sie'],
[0.2, 2.2, 'hallo']
]
"""
labels = []
for record in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3):
value = ''
if len(record) > 2:
value = str(record[2])
labels.append([float(_clean_time(record[0])), float(_clean_time(record[1])), value])
return labels | [
"def",
"read_label_file",
"(",
"path",
")",
":",
"labels",
"=",
"[",
"]",
"for",
"record",
"in",
"textfile",
".",
"read_separated_lines_generator",
"(",
"path",
",",
"separator",
"=",
"'\\t'",
",",
"max_columns",
"=",
"3",
")",
":",
"value",
"=",
"''",
"... | Read the labels from an audacity label file.
Args:
path (str): Path to the label file.
Returns:
list: List of labels (start [sec], end [sec], label)
Example::
>>> read_label_file('/path/to/label/file.txt')
[
[0.0, 0.2, 'sie'],
[0.2, 2.2, 'hallo']
] | [
"Read",
"the",
"labels",
"from",
"an",
"audacity",
"label",
"file",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/formats/audacity.py#L45-L73 | train | 32,727 |
ynop/audiomate | audiomate/utils/download.py | extract_zip | def extract_zip(zip_path, target_folder):
"""
Extract the content of the zip-file at `zip_path` into `target_folder`.
"""
with zipfile.ZipFile(zip_path) as archive:
archive.extractall(target_folder) | python | def extract_zip(zip_path, target_folder):
"""
Extract the content of the zip-file at `zip_path` into `target_folder`.
"""
with zipfile.ZipFile(zip_path) as archive:
archive.extractall(target_folder) | [
"def",
"extract_zip",
"(",
"zip_path",
",",
"target_folder",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"zip_path",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
"target_folder",
")"
] | Extract the content of the zip-file at `zip_path` into `target_folder`. | [
"Extract",
"the",
"content",
"of",
"the",
"zip",
"-",
"file",
"at",
"zip_path",
"into",
"target_folder",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/download.py#L23-L28 | train | 32,728 |
ynop/audiomate | audiomate/utils/download.py | extract_tar | def extract_tar(tar_path, target_folder):
"""
Extract the content of the tar-file at `tar_path` into `target_folder`.
"""
with tarfile.open(tar_path, 'r') as archive:
archive.extractall(target_folder) | python | def extract_tar(tar_path, target_folder):
"""
Extract the content of the tar-file at `tar_path` into `target_folder`.
"""
with tarfile.open(tar_path, 'r') as archive:
archive.extractall(target_folder) | [
"def",
"extract_tar",
"(",
"tar_path",
",",
"target_folder",
")",
":",
"with",
"tarfile",
".",
"open",
"(",
"tar_path",
",",
"'r'",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
"target_folder",
")"
] | Extract the content of the tar-file at `tar_path` into `target_folder`. | [
"Extract",
"the",
"content",
"of",
"the",
"tar",
"-",
"file",
"at",
"tar_path",
"into",
"target_folder",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/download.py#L31-L36 | train | 32,729 |
ynop/audiomate | audiomate/utils/textfile.py | read_separated_lines | def read_separated_lines(path, separator=' ', max_columns=-1, keep_empty=False):
"""
Reads a text file where each line represents a record with some separated columns.
Parameters:
path (str): Path to the file to read.
separator (str): Separator that is used to split the columns.
max_columns (int): Number of max columns (if the separator occurs within the last column).
keep_empty (bool): If True empty columns are returned as well.
Returns:
list: A list containing a list for each line read.
"""
gen = read_separated_lines_generator(path, separator, max_columns, keep_empty=keep_empty)
return list(gen) | python | def read_separated_lines(path, separator=' ', max_columns=-1, keep_empty=False):
"""
Reads a text file where each line represents a record with some separated columns.
Parameters:
path (str): Path to the file to read.
separator (str): Separator that is used to split the columns.
max_columns (int): Number of max columns (if the separator occurs within the last column).
keep_empty (bool): If True empty columns are returned as well.
Returns:
list: A list containing a list for each line read.
"""
gen = read_separated_lines_generator(path, separator, max_columns, keep_empty=keep_empty)
return list(gen) | [
"def",
"read_separated_lines",
"(",
"path",
",",
"separator",
"=",
"' '",
",",
"max_columns",
"=",
"-",
"1",
",",
"keep_empty",
"=",
"False",
")",
":",
"gen",
"=",
"read_separated_lines_generator",
"(",
"path",
",",
"separator",
",",
"max_columns",
",",
"kee... | Reads a text file where each line represents a record with some separated columns.
Parameters:
path (str): Path to the file to read.
separator (str): Separator that is used to split the columns.
max_columns (int): Number of max columns (if the separator occurs within the last column).
keep_empty (bool): If True empty columns are returned as well.
Returns:
list: A list containing a list for each line read. | [
"Reads",
"a",
"text",
"file",
"where",
"each",
"line",
"represents",
"a",
"record",
"with",
"some",
"separated",
"columns",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/textfile.py#L10-L25 | train | 32,730 |
ynop/audiomate | audiomate/utils/textfile.py | read_separated_lines_with_first_key | def read_separated_lines_with_first_key(path: str, separator: str = ' ', max_columns: int = -1,
keep_empty: bool = False):
"""
Reads the separated lines of a file and return a dictionary with the first column as keys, value
is a list with the rest of the columns.
Parameters:
path (str): Path to the file to read.
separator (str): Separator that is used to split the columns.
max_columns (str): Number of max columns (if the separator occurs within the last column).
keep_empty (bool): If True empty columns are returned as well.
Returns:
dict: Dictionary with list of column values and first column value as key.
"""
gen = read_separated_lines_generator(path, separator, max_columns, keep_empty=keep_empty)
dic = {}
for record in gen:
if len(record) > 0:
dic[record[0]] = record[1:len(record)]
return dic | python | def read_separated_lines_with_first_key(path: str, separator: str = ' ', max_columns: int = -1,
keep_empty: bool = False):
"""
Reads the separated lines of a file and return a dictionary with the first column as keys, value
is a list with the rest of the columns.
Parameters:
path (str): Path to the file to read.
separator (str): Separator that is used to split the columns.
max_columns (str): Number of max columns (if the separator occurs within the last column).
keep_empty (bool): If True empty columns are returned as well.
Returns:
dict: Dictionary with list of column values and first column value as key.
"""
gen = read_separated_lines_generator(path, separator, max_columns, keep_empty=keep_empty)
dic = {}
for record in gen:
if len(record) > 0:
dic[record[0]] = record[1:len(record)]
return dic | [
"def",
"read_separated_lines_with_first_key",
"(",
"path",
":",
"str",
",",
"separator",
":",
"str",
"=",
"' '",
",",
"max_columns",
":",
"int",
"=",
"-",
"1",
",",
"keep_empty",
":",
"bool",
"=",
"False",
")",
":",
"gen",
"=",
"read_separated_lines_generato... | Reads the separated lines of a file and return a dictionary with the first column as keys, value
is a list with the rest of the columns.
Parameters:
path (str): Path to the file to read.
separator (str): Separator that is used to split the columns.
max_columns (str): Number of max columns (if the separator occurs within the last column).
keep_empty (bool): If True empty columns are returned as well.
Returns:
dict: Dictionary with list of column values and first column value as key. | [
"Reads",
"the",
"separated",
"lines",
"of",
"a",
"file",
"and",
"return",
"a",
"dictionary",
"with",
"the",
"first",
"column",
"as",
"keys",
"value",
"is",
"a",
"list",
"with",
"the",
"rest",
"of",
"the",
"columns",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/textfile.py#L28-L51 | train | 32,731 |
ynop/audiomate | audiomate/utils/textfile.py | write_separated_lines | def write_separated_lines(path, values, separator=' ', sort_by_column=0):
"""
Writes list or dict to file line by line. Dict can have list as value then they written
separated on the line.
Parameters:
path (str): Path to write file to.
values (dict, list): A dictionary or a list to write to the file.
separator (str): Separator to use between columns.
sort_by_column (int): if >= 0, sorts the list by the given index, if its 0 or 1 and its a
dictionary it sorts it by either the key (0) or value (1). By default
0, meaning sorted by the first column or the key.
"""
f = open(path, 'w', encoding='utf-8')
if type(values) is dict:
if sort_by_column in [0, 1]:
items = sorted(values.items(), key=lambda t: t[sort_by_column])
else:
items = values.items()
for key, value in items:
if type(value) in [list, set]:
value = separator.join([str(x) for x in value])
f.write('{}{}{}\n'.format(key, separator, value))
elif type(values) is list or type(values) is set:
if 0 <= sort_by_column < len(values):
items = sorted(values)
else:
items = values
for record in items:
str_values = [str(value) for value in record]
f.write('{}\n'.format(separator.join(str_values)))
f.close() | python | def write_separated_lines(path, values, separator=' ', sort_by_column=0):
"""
Writes list or dict to file line by line. Dict can have list as value then they written
separated on the line.
Parameters:
path (str): Path to write file to.
values (dict, list): A dictionary or a list to write to the file.
separator (str): Separator to use between columns.
sort_by_column (int): if >= 0, sorts the list by the given index, if its 0 or 1 and its a
dictionary it sorts it by either the key (0) or value (1). By default
0, meaning sorted by the first column or the key.
"""
f = open(path, 'w', encoding='utf-8')
if type(values) is dict:
if sort_by_column in [0, 1]:
items = sorted(values.items(), key=lambda t: t[sort_by_column])
else:
items = values.items()
for key, value in items:
if type(value) in [list, set]:
value = separator.join([str(x) for x in value])
f.write('{}{}{}\n'.format(key, separator, value))
elif type(values) is list or type(values) is set:
if 0 <= sort_by_column < len(values):
items = sorted(values)
else:
items = values
for record in items:
str_values = [str(value) for value in record]
f.write('{}\n'.format(separator.join(str_values)))
f.close() | [
"def",
"write_separated_lines",
"(",
"path",
",",
"values",
",",
"separator",
"=",
"' '",
",",
"sort_by_column",
"=",
"0",
")",
":",
"f",
"=",
"open",
"(",
"path",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"type",
"(",
"values",
")",
"i... | Writes list or dict to file line by line. Dict can have list as value then they written
separated on the line.
Parameters:
path (str): Path to write file to.
values (dict, list): A dictionary or a list to write to the file.
separator (str): Separator to use between columns.
sort_by_column (int): if >= 0, sorts the list by the given index, if its 0 or 1 and its a
dictionary it sorts it by either the key (0) or value (1). By default
0, meaning sorted by the first column or the key. | [
"Writes",
"list",
"or",
"dict",
"to",
"file",
"line",
"by",
"line",
".",
"Dict",
"can",
"have",
"list",
"as",
"value",
"then",
"they",
"written",
"separated",
"on",
"the",
"line",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/textfile.py#L79-L116 | train | 32,732 |
ynop/audiomate | audiomate/utils/textfile.py | read_separated_lines_generator | def read_separated_lines_generator(path, separator=' ', max_columns=-1,
ignore_lines_starting_with=[], keep_empty=False):
"""
Creates a generator through all lines of a file and returns the splitted line.
Parameters:
path: Path to the file.
separator: Separator that is used to split the columns.
max_columns: Number of max columns (if the separator occurs within the last column).
ignore_lines_starting_with: Lines starting with a string in this list will be ignored.
keep_empty (bool): If True empty columns are returned as well.
"""
if not os.path.isfile(path):
print('File doesnt exist or is no file: {}'.format(path))
return
f = open(path, 'r', errors='ignore', encoding='utf-8')
if max_columns > -1:
max_splits = max_columns - 1
else:
max_splits = -1
for line in f:
if keep_empty:
stripped_line = line
else:
stripped_line = line.strip()
should_ignore = text.starts_with_prefix_in_list(stripped_line, ignore_lines_starting_with)
if not should_ignore and stripped_line != '':
record = stripped_line.split(sep=separator, maxsplit=max_splits)
record = [field.strip() for field in record]
yield record
f.close() | python | def read_separated_lines_generator(path, separator=' ', max_columns=-1,
ignore_lines_starting_with=[], keep_empty=False):
"""
Creates a generator through all lines of a file and returns the splitted line.
Parameters:
path: Path to the file.
separator: Separator that is used to split the columns.
max_columns: Number of max columns (if the separator occurs within the last column).
ignore_lines_starting_with: Lines starting with a string in this list will be ignored.
keep_empty (bool): If True empty columns are returned as well.
"""
if not os.path.isfile(path):
print('File doesnt exist or is no file: {}'.format(path))
return
f = open(path, 'r', errors='ignore', encoding='utf-8')
if max_columns > -1:
max_splits = max_columns - 1
else:
max_splits = -1
for line in f:
if keep_empty:
stripped_line = line
else:
stripped_line = line.strip()
should_ignore = text.starts_with_prefix_in_list(stripped_line, ignore_lines_starting_with)
if not should_ignore and stripped_line != '':
record = stripped_line.split(sep=separator, maxsplit=max_splits)
record = [field.strip() for field in record]
yield record
f.close() | [
"def",
"read_separated_lines_generator",
"(",
"path",
",",
"separator",
"=",
"' '",
",",
"max_columns",
"=",
"-",
"1",
",",
"ignore_lines_starting_with",
"=",
"[",
"]",
",",
"keep_empty",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile... | Creates a generator through all lines of a file and returns the splitted line.
Parameters:
path: Path to the file.
separator: Separator that is used to split the columns.
max_columns: Number of max columns (if the separator occurs within the last column).
ignore_lines_starting_with: Lines starting with a string in this list will be ignored.
keep_empty (bool): If True empty columns are returned as well. | [
"Creates",
"a",
"generator",
"through",
"all",
"lines",
"of",
"a",
"file",
"and",
"returns",
"the",
"splitted",
"line",
"."
] | 61727920b23a708293c3d526fa3000d4de9c6c21 | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/textfile.py#L119-L155 | train | 32,733 |
MichaelSolati/typeform-python-sdk | typeform/forms.py | Forms.update | def update(self, uid: str, patch=False, data: any = {}) -> typing.Union[str, dict]:
"""
Updates an existing form.
Defaults to `put`.
`put` will return the modified form as a `dict` object.
`patch` will return a `str` based on success of change, `OK` on success, otherwise an error message.
"""
methodType = 'put' if patch is False else 'patch'
return self.__client.request(methodType, '/forms/%s' % uid, data=data) | python | def update(self, uid: str, patch=False, data: any = {}) -> typing.Union[str, dict]:
"""
Updates an existing form.
Defaults to `put`.
`put` will return the modified form as a `dict` object.
`patch` will return a `str` based on success of change, `OK` on success, otherwise an error message.
"""
methodType = 'put' if patch is False else 'patch'
return self.__client.request(methodType, '/forms/%s' % uid, data=data) | [
"def",
"update",
"(",
"self",
",",
"uid",
":",
"str",
",",
"patch",
"=",
"False",
",",
"data",
":",
"any",
"=",
"{",
"}",
")",
"->",
"typing",
".",
"Union",
"[",
"str",
",",
"dict",
"]",
":",
"methodType",
"=",
"'put'",
"if",
"patch",
"is",
"Fa... | Updates an existing form.
Defaults to `put`.
`put` will return the modified form as a `dict` object.
`patch` will return a `str` based on success of change, `OK` on success, otherwise an error message. | [
"Updates",
"an",
"existing",
"form",
".",
"Defaults",
"to",
"put",
".",
"put",
"will",
"return",
"the",
"modified",
"form",
"as",
"a",
"dict",
"object",
".",
"patch",
"will",
"return",
"a",
"str",
"based",
"on",
"success",
"of",
"change",
"OK",
"on",
"... | 04e999be448e3226df73f238fe127385e43b1e98 | https://github.com/MichaelSolati/typeform-python-sdk/blob/04e999be448e3226df73f238fe127385e43b1e98/typeform/forms.py#L43-L51 | train | 32,734 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.configure | def configure(self, app):
'''
Load configuration from application configuration.
For each storage, the configuration is loaded with the following pattern::
FS_{BACKEND_NAME}_{KEY} then
{STORAGE_NAME}_FS_{KEY}
If no configuration is set for a given key, global config is taken as default.
'''
config = Config()
prefix = PREFIX.format(self.name.upper())
backend_key = '{0}BACKEND'.format(prefix)
self.backend_name = app.config.get(backend_key, app.config['FS_BACKEND'])
self.backend_prefix = BACKEND_PREFIX.format(self.backend_name.upper())
backend_excluded_keys = [''.join((self.backend_prefix, k)) for k in BACKEND_EXCLUDED_CONFIG]
# Set default values
for key, value in DEFAULT_CONFIG.items():
config.setdefault(key, value)
# Set backend level values
for key, value in app.config.items():
if key.startswith(self.backend_prefix) and key not in backend_excluded_keys:
config[key.replace(self.backend_prefix, '').lower()] = value
# Set storage level values
for key, value in app.config.items():
if key.startswith(prefix):
config[key.replace(prefix, '').lower()] = value
if self.backend_name not in BACKENDS:
raise ValueError('Unknown backend "{0}"'.format(self.backend_name))
backend_class = BACKENDS[self.backend_name].load()
backend_class.backend_name = self.backend_name
self.backend = backend_class(self.name, config)
self.config = config | python | def configure(self, app):
'''
Load configuration from application configuration.
For each storage, the configuration is loaded with the following pattern::
FS_{BACKEND_NAME}_{KEY} then
{STORAGE_NAME}_FS_{KEY}
If no configuration is set for a given key, global config is taken as default.
'''
config = Config()
prefix = PREFIX.format(self.name.upper())
backend_key = '{0}BACKEND'.format(prefix)
self.backend_name = app.config.get(backend_key, app.config['FS_BACKEND'])
self.backend_prefix = BACKEND_PREFIX.format(self.backend_name.upper())
backend_excluded_keys = [''.join((self.backend_prefix, k)) for k in BACKEND_EXCLUDED_CONFIG]
# Set default values
for key, value in DEFAULT_CONFIG.items():
config.setdefault(key, value)
# Set backend level values
for key, value in app.config.items():
if key.startswith(self.backend_prefix) and key not in backend_excluded_keys:
config[key.replace(self.backend_prefix, '').lower()] = value
# Set storage level values
for key, value in app.config.items():
if key.startswith(prefix):
config[key.replace(prefix, '').lower()] = value
if self.backend_name not in BACKENDS:
raise ValueError('Unknown backend "{0}"'.format(self.backend_name))
backend_class = BACKENDS[self.backend_name].load()
backend_class.backend_name = self.backend_name
self.backend = backend_class(self.name, config)
self.config = config | [
"def",
"configure",
"(",
"self",
",",
"app",
")",
":",
"config",
"=",
"Config",
"(",
")",
"prefix",
"=",
"PREFIX",
".",
"format",
"(",
"self",
".",
"name",
".",
"upper",
"(",
")",
")",
"backend_key",
"=",
"'{0}BACKEND'",
".",
"format",
"(",
"prefix",... | Load configuration from application configuration.
For each storage, the configuration is loaded with the following pattern::
FS_{BACKEND_NAME}_{KEY} then
{STORAGE_NAME}_FS_{KEY}
If no configuration is set for a given key, global config is taken as default. | [
"Load",
"configuration",
"from",
"application",
"configuration",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L87-L125 | train | 32,735 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.base_url | def base_url(self):
'''The public URL for this storage'''
config_value = self.config.get('url')
if config_value:
return self._clean_url(config_value)
default_url = current_app.config.get('FS_URL')
default_url = current_app.config.get('{0}URL'.format(self.backend_prefix), default_url)
if default_url:
url = urljoin(default_url, self.name)
return self._clean_url(url)
return url_for('fs.get_file', fs=self.name, filename='', _external=True) | python | def base_url(self):
'''The public URL for this storage'''
config_value = self.config.get('url')
if config_value:
return self._clean_url(config_value)
default_url = current_app.config.get('FS_URL')
default_url = current_app.config.get('{0}URL'.format(self.backend_prefix), default_url)
if default_url:
url = urljoin(default_url, self.name)
return self._clean_url(url)
return url_for('fs.get_file', fs=self.name, filename='', _external=True) | [
"def",
"base_url",
"(",
"self",
")",
":",
"config_value",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'url'",
")",
"if",
"config_value",
":",
"return",
"self",
".",
"_clean_url",
"(",
"config_value",
")",
"default_url",
"=",
"current_app",
".",
"config",... | The public URL for this storage | [
"The",
"public",
"URL",
"for",
"this",
"storage"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L132-L142 | train | 32,736 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.url | def url(self, filename, external=False):
'''
This function gets the URL a file uploaded to this set would be
accessed at. It doesn't check whether said file exists.
:param string filename: The filename to return the URL for.
:param bool external: If True, returns an absolute URL
'''
if filename.startswith('/'):
filename = filename[1:]
if self.has_url:
return self.base_url + filename
else:
return url_for('fs.get_file', fs=self.name, filename=filename, _external=external) | python | def url(self, filename, external=False):
'''
This function gets the URL a file uploaded to this set would be
accessed at. It doesn't check whether said file exists.
:param string filename: The filename to return the URL for.
:param bool external: If True, returns an absolute URL
'''
if filename.startswith('/'):
filename = filename[1:]
if self.has_url:
return self.base_url + filename
else:
return url_for('fs.get_file', fs=self.name, filename=filename, _external=external) | [
"def",
"url",
"(",
"self",
",",
"filename",
",",
"external",
"=",
"False",
")",
":",
"if",
"filename",
".",
"startswith",
"(",
"'/'",
")",
":",
"filename",
"=",
"filename",
"[",
"1",
":",
"]",
"if",
"self",
".",
"has_url",
":",
"return",
"self",
".... | This function gets the URL a file uploaded to this set would be
accessed at. It doesn't check whether said file exists.
:param string filename: The filename to return the URL for.
:param bool external: If True, returns an absolute URL | [
"This",
"function",
"gets",
"the",
"URL",
"a",
"file",
"uploaded",
"to",
"this",
"set",
"would",
"be",
"accessed",
"at",
".",
"It",
"doesn",
"t",
"check",
"whether",
"said",
"file",
"exists",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L156-L169 | train | 32,737 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.path | def path(self, filename):
'''
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
to save to.
:raises OperationNotSupported: when the backenddoesn't support direct file access
'''
if not self.backend.root:
raise OperationNotSupported(
'Direct file access is not supported by ' +
self.backend.__class__.__name__
)
return os.path.join(self.backend.root, filename) | python | def path(self, filename):
'''
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
to save to.
:raises OperationNotSupported: when the backenddoesn't support direct file access
'''
if not self.backend.root:
raise OperationNotSupported(
'Direct file access is not supported by ' +
self.backend.__class__.__name__
)
return os.path.join(self.backend.root, filename) | [
"def",
"path",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"self",
".",
"backend",
".",
"root",
":",
"raise",
"OperationNotSupported",
"(",
"'Direct file access is not supported by '",
"+",
"self",
".",
"backend",
".",
"__class__",
".",
"__name__",
")... | This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
to save to.
:raises OperationNotSupported: when the backenddoesn't support direct file access | [
"This",
"returns",
"the",
"absolute",
"path",
"of",
"a",
"file",
"uploaded",
"to",
"this",
"set",
".",
"It",
"doesn",
"t",
"actually",
"check",
"whether",
"said",
"file",
"exists",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L171-L187 | train | 32,738 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.read | def read(self, filename):
'''
Read a file content.
:param string filename: The storage root-relative filename
:raises FileNotFound: If the file does not exists
'''
if not self.backend.exists(filename):
raise FileNotFound(filename)
return self.backend.read(filename) | python | def read(self, filename):
'''
Read a file content.
:param string filename: The storage root-relative filename
:raises FileNotFound: If the file does not exists
'''
if not self.backend.exists(filename):
raise FileNotFound(filename)
return self.backend.read(filename) | [
"def",
"read",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"self",
".",
"backend",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"FileNotFound",
"(",
"filename",
")",
"return",
"self",
".",
"backend",
".",
"read",
"(",
"filename",
")"
] | Read a file content.
:param string filename: The storage root-relative filename
:raises FileNotFound: If the file does not exists | [
"Read",
"a",
"file",
"content",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L220-L229 | train | 32,739 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.open | def open(self, filename, mode='r', **kwargs):
'''
Open the file and return a file-like object.
:param str filename: The storage root-relative filename
:param str mode: The open mode (``(r|w)b?``)
:raises FileNotFound: If trying to read a file that does not exists
'''
if 'r' in mode and not self.backend.exists(filename):
raise FileNotFound(filename)
return self.backend.open(filename, mode, **kwargs) | python | def open(self, filename, mode='r', **kwargs):
'''
Open the file and return a file-like object.
:param str filename: The storage root-relative filename
:param str mode: The open mode (``(r|w)b?``)
:raises FileNotFound: If trying to read a file that does not exists
'''
if 'r' in mode and not self.backend.exists(filename):
raise FileNotFound(filename)
return self.backend.open(filename, mode, **kwargs) | [
"def",
"open",
"(",
"self",
",",
"filename",
",",
"mode",
"=",
"'r'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'r'",
"in",
"mode",
"and",
"not",
"self",
".",
"backend",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"FileNotFound",
"(",
"filen... | Open the file and return a file-like object.
:param str filename: The storage root-relative filename
:param str mode: The open mode (``(r|w)b?``)
:raises FileNotFound: If trying to read a file that does not exists | [
"Open",
"the",
"file",
"and",
"return",
"a",
"file",
"-",
"like",
"object",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L231-L241 | train | 32,740 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.write | def write(self, filename, content, overwrite=False):
'''
Write content to a file.
:param str filename: The storage root-relative filename
:param content: The content to write in the file
:param bool overwrite: Whether to wllow overwrite or not
:raises FileExists: If the file exists and `overwrite` is `False`
'''
if not self.overwrite and not overwrite and self.backend.exists(filename):
raise FileExists()
return self.backend.write(filename, content) | python | def write(self, filename, content, overwrite=False):
'''
Write content to a file.
:param str filename: The storage root-relative filename
:param content: The content to write in the file
:param bool overwrite: Whether to wllow overwrite or not
:raises FileExists: If the file exists and `overwrite` is `False`
'''
if not self.overwrite and not overwrite and self.backend.exists(filename):
raise FileExists()
return self.backend.write(filename, content) | [
"def",
"write",
"(",
"self",
",",
"filename",
",",
"content",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"overwrite",
"and",
"not",
"overwrite",
"and",
"self",
".",
"backend",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
... | Write content to a file.
:param str filename: The storage root-relative filename
:param content: The content to write in the file
:param bool overwrite: Whether to wllow overwrite or not
:raises FileExists: If the file exists and `overwrite` is `False` | [
"Write",
"content",
"to",
"a",
"file",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L243-L254 | train | 32,741 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.metadata | def metadata(self, filename):
'''
Get some metadata for a given file.
Can vary from a backend to another but some are always present:
- `filename`: the base filename (without the path/prefix)
- `url`: the file public URL
- `checksum`: a checksum expressed in the form `algo:hash`
- 'mime': the mime type
- `modified`: the last modification date
'''
metadata = self.backend.metadata(filename)
metadata['filename'] = os.path.basename(filename)
metadata['url'] = self.url(filename, external=True)
return metadata | python | def metadata(self, filename):
'''
Get some metadata for a given file.
Can vary from a backend to another but some are always present:
- `filename`: the base filename (without the path/prefix)
- `url`: the file public URL
- `checksum`: a checksum expressed in the form `algo:hash`
- 'mime': the mime type
- `modified`: the last modification date
'''
metadata = self.backend.metadata(filename)
metadata['filename'] = os.path.basename(filename)
metadata['url'] = self.url(filename, external=True)
return metadata | [
"def",
"metadata",
"(",
"self",
",",
"filename",
")",
":",
"metadata",
"=",
"self",
".",
"backend",
".",
"metadata",
"(",
"filename",
")",
"metadata",
"[",
"'filename'",
"]",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"metadata",
"[... | Get some metadata for a given file.
Can vary from a backend to another but some are always present:
- `filename`: the base filename (without the path/prefix)
- `url`: the file public URL
- `checksum`: a checksum expressed in the form `algo:hash`
- 'mime': the mime type
- `modified`: the last modification date | [
"Get",
"some",
"metadata",
"for",
"a",
"given",
"file",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L310-L324 | train | 32,742 |
noirbizarre/flask-fs | flask_fs/storage.py | Storage.serve | def serve(self, filename):
'''Serve a file given its filename'''
if not self.exists(filename):
abort(404)
return self.backend.serve(filename) | python | def serve(self, filename):
'''Serve a file given its filename'''
if not self.exists(filename):
abort(404)
return self.backend.serve(filename) | [
"def",
"serve",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
"filename",
")",
":",
"abort",
"(",
"404",
")",
"return",
"self",
".",
"backend",
".",
"serve",
"(",
"filename",
")"
] | Serve a file given its filename | [
"Serve",
"a",
"file",
"given",
"its",
"filename"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/storage.py#L350-L354 | train | 32,743 |
noirbizarre/flask-fs | flask_fs/images.py | make_thumbnail | def make_thumbnail(file, size, bbox=None):
'''
Generate a thumbnail for a given image file.
:param file file: The source image file to thumbnail
:param int size: The thumbnail size in pixels (Thumbnails are squares)
:param tuple bbox: An optionnal Bounding box definition for the thumbnail
'''
image = Image.open(file)
if bbox:
thumbnail = crop_thumbnail(image, size, bbox)
else:
thumbnail = center_thumbnail(image, size)
return _img_to_file(thumbnail) | python | def make_thumbnail(file, size, bbox=None):
'''
Generate a thumbnail for a given image file.
:param file file: The source image file to thumbnail
:param int size: The thumbnail size in pixels (Thumbnails are squares)
:param tuple bbox: An optionnal Bounding box definition for the thumbnail
'''
image = Image.open(file)
if bbox:
thumbnail = crop_thumbnail(image, size, bbox)
else:
thumbnail = center_thumbnail(image, size)
return _img_to_file(thumbnail) | [
"def",
"make_thumbnail",
"(",
"file",
",",
"size",
",",
"bbox",
"=",
"None",
")",
":",
"image",
"=",
"Image",
".",
"open",
"(",
"file",
")",
"if",
"bbox",
":",
"thumbnail",
"=",
"crop_thumbnail",
"(",
"image",
",",
"size",
",",
"bbox",
")",
"else",
... | Generate a thumbnail for a given image file.
:param file file: The source image file to thumbnail
:param int size: The thumbnail size in pixels (Thumbnails are squares)
:param tuple bbox: An optionnal Bounding box definition for the thumbnail | [
"Generate",
"a",
"thumbnail",
"for",
"a",
"given",
"image",
"file",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/images.py#L16-L29 | train | 32,744 |
noirbizarre/flask-fs | setup.py | pip | def pip(filename):
"""Parse pip reqs file and transform it to setuptools requirements."""
requirements = []
for line in open(join(ROOT, 'requirements', filename)):
line = line.strip()
if not line or '://' in line:
continue
match = RE_REQUIREMENT.match(line)
if match:
requirements.extend(pip(match.group('filename')))
else:
requirements.append(line)
return requirements | python | def pip(filename):
"""Parse pip reqs file and transform it to setuptools requirements."""
requirements = []
for line in open(join(ROOT, 'requirements', filename)):
line = line.strip()
if not line or '://' in line:
continue
match = RE_REQUIREMENT.match(line)
if match:
requirements.extend(pip(match.group('filename')))
else:
requirements.append(line)
return requirements | [
"def",
"pip",
"(",
"filename",
")",
":",
"requirements",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"join",
"(",
"ROOT",
",",
"'requirements'",
",",
"filename",
")",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
... | Parse pip reqs file and transform it to setuptools requirements. | [
"Parse",
"pip",
"reqs",
"file",
"and",
"transform",
"it",
"to",
"setuptools",
"requirements",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/setup.py#L16-L28 | train | 32,745 |
noirbizarre/flask-fs | flask_fs/backends/__init__.py | BaseBackend.move | def move(self, filename, target):
'''
Move a file given its filename to another path in the storage
Default implementation perform a copy then a delete.
Backends should overwrite it if there is a better way.
'''
self.copy(filename, target)
self.delete(filename) | python | def move(self, filename, target):
'''
Move a file given its filename to another path in the storage
Default implementation perform a copy then a delete.
Backends should overwrite it if there is a better way.
'''
self.copy(filename, target)
self.delete(filename) | [
"def",
"move",
"(",
"self",
",",
"filename",
",",
"target",
")",
":",
"self",
".",
"copy",
"(",
"filename",
",",
"target",
")",
"self",
".",
"delete",
"(",
"filename",
")"
] | Move a file given its filename to another path in the storage
Default implementation perform a copy then a delete.
Backends should overwrite it if there is a better way. | [
"Move",
"a",
"file",
"given",
"its",
"filename",
"to",
"another",
"path",
"in",
"the",
"storage"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/backends/__init__.py#L49-L57 | train | 32,746 |
noirbizarre/flask-fs | flask_fs/backends/__init__.py | BaseBackend.save | def save(self, file_or_wfs, filename, overwrite=False):
'''
Save a file-like object or a `werkzeug.FileStorage` with the specified filename.
:param storage: The file or the storage to be saved.
:param filename: The destination in the storage.
:param overwrite: if `False`, raise an exception if file exists in storage
:raises FileExists: when file exists and overwrite is `False`
'''
self.write(filename, file_or_wfs.read())
return filename | python | def save(self, file_or_wfs, filename, overwrite=False):
'''
Save a file-like object or a `werkzeug.FileStorage` with the specified filename.
:param storage: The file or the storage to be saved.
:param filename: The destination in the storage.
:param overwrite: if `False`, raise an exception if file exists in storage
:raises FileExists: when file exists and overwrite is `False`
'''
self.write(filename, file_or_wfs.read())
return filename | [
"def",
"save",
"(",
"self",
",",
"file_or_wfs",
",",
"filename",
",",
"overwrite",
"=",
"False",
")",
":",
"self",
".",
"write",
"(",
"filename",
",",
"file_or_wfs",
".",
"read",
"(",
")",
")",
"return",
"filename"
] | Save a file-like object or a `werkzeug.FileStorage` with the specified filename.
:param storage: The file or the storage to be saved.
:param filename: The destination in the storage.
:param overwrite: if `False`, raise an exception if file exists in storage
:raises FileExists: when file exists and overwrite is `False` | [
"Save",
"a",
"file",
"-",
"like",
"object",
"or",
"a",
"werkzeug",
".",
"FileStorage",
"with",
"the",
"specified",
"filename",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/backends/__init__.py#L59-L70 | train | 32,747 |
noirbizarre/flask-fs | flask_fs/backends/__init__.py | BaseBackend.metadata | def metadata(self, filename):
'''
Fetch all available metadata for a given file
'''
meta = self.get_metadata(filename)
# Fix backend mime misdetection
meta['mime'] = meta.get('mime') or files.mime(filename, self.DEFAULT_MIME)
return meta | python | def metadata(self, filename):
'''
Fetch all available metadata for a given file
'''
meta = self.get_metadata(filename)
# Fix backend mime misdetection
meta['mime'] = meta.get('mime') or files.mime(filename, self.DEFAULT_MIME)
return meta | [
"def",
"metadata",
"(",
"self",
",",
"filename",
")",
":",
"meta",
"=",
"self",
".",
"get_metadata",
"(",
"filename",
")",
"# Fix backend mime misdetection",
"meta",
"[",
"'mime'",
"]",
"=",
"meta",
".",
"get",
"(",
"'mime'",
")",
"or",
"files",
".",
"mi... | Fetch all available metadata for a given file | [
"Fetch",
"all",
"available",
"metadata",
"for",
"a",
"given",
"file"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/backends/__init__.py#L72-L79 | train | 32,748 |
noirbizarre/flask-fs | flask_fs/backends/__init__.py | BaseBackend.as_binary | def as_binary(self, content, encoding='utf8'):
'''Perform content encoding for binary write'''
if hasattr(content, 'read'):
return content.read()
elif isinstance(content, six.text_type):
return content.encode(encoding)
else:
return content | python | def as_binary(self, content, encoding='utf8'):
'''Perform content encoding for binary write'''
if hasattr(content, 'read'):
return content.read()
elif isinstance(content, six.text_type):
return content.encode(encoding)
else:
return content | [
"def",
"as_binary",
"(",
"self",
",",
"content",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"if",
"hasattr",
"(",
"content",
",",
"'read'",
")",
":",
"return",
"content",
".",
"read",
"(",
")",
"elif",
"isinstance",
"(",
"content",
",",
"six",
".",
"t... | Perform content encoding for binary write | [
"Perform",
"content",
"encoding",
"for",
"binary",
"write"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/backends/__init__.py#L91-L98 | train | 32,749 |
noirbizarre/flask-fs | flask_fs/backends/s3.py | S3Backend.get_metadata | def get_metadata(self, filename):
'''Fetch all availabe metadata'''
obj = self.bucket.Object(filename)
checksum = 'md5:{0}'.format(obj.e_tag[1:-1])
mime = obj.content_type.split(';', 1)[0] if obj.content_type else None
return {
'checksum': checksum,
'size': obj.content_length,
'mime': mime,
'modified': obj.last_modified,
} | python | def get_metadata(self, filename):
'''Fetch all availabe metadata'''
obj = self.bucket.Object(filename)
checksum = 'md5:{0}'.format(obj.e_tag[1:-1])
mime = obj.content_type.split(';', 1)[0] if obj.content_type else None
return {
'checksum': checksum,
'size': obj.content_length,
'mime': mime,
'modified': obj.last_modified,
} | [
"def",
"get_metadata",
"(",
"self",
",",
"filename",
")",
":",
"obj",
"=",
"self",
".",
"bucket",
".",
"Object",
"(",
"filename",
")",
"checksum",
"=",
"'md5:{0}'",
".",
"format",
"(",
"obj",
".",
"e_tag",
"[",
"1",
":",
"-",
"1",
"]",
")",
"mime",... | Fetch all availabe metadata | [
"Fetch",
"all",
"availabe",
"metadata"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/backends/s3.py#L89-L99 | train | 32,750 |
noirbizarre/flask-fs | flask_fs/mongo.py | ImageReference.thumbnail | def thumbnail(self, size):
'''Get the thumbnail filename for a given size'''
if size in self.thumbnail_sizes:
return self.thumbnails.get(str(size))
else:
raise ValueError('Unregistered thumbnail size {0}'.format(size)) | python | def thumbnail(self, size):
'''Get the thumbnail filename for a given size'''
if size in self.thumbnail_sizes:
return self.thumbnails.get(str(size))
else:
raise ValueError('Unregistered thumbnail size {0}'.format(size)) | [
"def",
"thumbnail",
"(",
"self",
",",
"size",
")",
":",
"if",
"size",
"in",
"self",
".",
"thumbnail_sizes",
":",
"return",
"self",
".",
"thumbnails",
".",
"get",
"(",
"str",
"(",
"size",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unregistered... | Get the thumbnail filename for a given size | [
"Get",
"the",
"thumbnail",
"filename",
"for",
"a",
"given",
"size"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/mongo.py#L163-L168 | train | 32,751 |
noirbizarre/flask-fs | flask_fs/mongo.py | ImageReference.full | def full(self, external=False):
'''Get the full image URL in respect with ``max_size``'''
return self.fs.url(self.filename, external=external) if self.filename else None | python | def full(self, external=False):
'''Get the full image URL in respect with ``max_size``'''
return self.fs.url(self.filename, external=external) if self.filename else None | [
"def",
"full",
"(",
"self",
",",
"external",
"=",
"False",
")",
":",
"return",
"self",
".",
"fs",
".",
"url",
"(",
"self",
".",
"filename",
",",
"external",
"=",
"external",
")",
"if",
"self",
".",
"filename",
"else",
"None"
] | Get the full image URL in respect with ``max_size`` | [
"Get",
"the",
"full",
"image",
"URL",
"in",
"respect",
"with",
"max_size"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/mongo.py#L170-L172 | train | 32,752 |
noirbizarre/flask-fs | flask_fs/mongo.py | ImageReference.best_url | def best_url(self, size=None, external=False):
'''
Provide the best thumbnail for downscaling.
If there is no match, provide the bigger if exists or the original
'''
if not self.thumbnail_sizes:
return self.url
elif not size:
self.thumbnail_sizes.sort()
best_size = self.thumbnail_sizes[-1]
else:
self.thumbnail_sizes.sort()
index = bisect.bisect_left(self.thumbnail_sizes, size)
if index >= len(self.thumbnail_sizes):
best_size = self.thumbnail_sizes[-1]
else:
best_size = self.thumbnail_sizes[index]
filename = self.thumbnail(best_size)
return self.fs.url(filename, external=external) if filename else None | python | def best_url(self, size=None, external=False):
'''
Provide the best thumbnail for downscaling.
If there is no match, provide the bigger if exists or the original
'''
if not self.thumbnail_sizes:
return self.url
elif not size:
self.thumbnail_sizes.sort()
best_size = self.thumbnail_sizes[-1]
else:
self.thumbnail_sizes.sort()
index = bisect.bisect_left(self.thumbnail_sizes, size)
if index >= len(self.thumbnail_sizes):
best_size = self.thumbnail_sizes[-1]
else:
best_size = self.thumbnail_sizes[index]
filename = self.thumbnail(best_size)
return self.fs.url(filename, external=external) if filename else None | [
"def",
"best_url",
"(",
"self",
",",
"size",
"=",
"None",
",",
"external",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"thumbnail_sizes",
":",
"return",
"self",
".",
"url",
"elif",
"not",
"size",
":",
"self",
".",
"thumbnail_sizes",
".",
"sort",
... | Provide the best thumbnail for downscaling.
If there is no match, provide the bigger if exists or the original | [
"Provide",
"the",
"best",
"thumbnail",
"for",
"downscaling",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/mongo.py#L174-L193 | train | 32,753 |
noirbizarre/flask-fs | flask_fs/mongo.py | ImageReference.rerender | def rerender(self):
'''
Rerender all derived images from the original.
If optmization settings or expected sizes changed,
they will be used for the new rendering.
'''
with self.fs.open(self.original, 'rb') as f_img:
img = io.BytesIO(f_img.read()) # Store the image in memory to avoid overwritting
self.save(img, filename=self.filename, bbox=self.bbox, overwrite=True) | python | def rerender(self):
'''
Rerender all derived images from the original.
If optmization settings or expected sizes changed,
they will be used for the new rendering.
'''
with self.fs.open(self.original, 'rb') as f_img:
img = io.BytesIO(f_img.read()) # Store the image in memory to avoid overwritting
self.save(img, filename=self.filename, bbox=self.bbox, overwrite=True) | [
"def",
"rerender",
"(",
"self",
")",
":",
"with",
"self",
".",
"fs",
".",
"open",
"(",
"self",
".",
"original",
",",
"'rb'",
")",
"as",
"f_img",
":",
"img",
"=",
"io",
".",
"BytesIO",
"(",
"f_img",
".",
"read",
"(",
")",
")",
"# Store the image in ... | Rerender all derived images from the original.
If optmization settings or expected sizes changed,
they will be used for the new rendering. | [
"Rerender",
"all",
"derived",
"images",
"from",
"the",
"original",
".",
"If",
"optmization",
"settings",
"or",
"expected",
"sizes",
"changed",
"they",
"will",
"be",
"used",
"for",
"the",
"new",
"rendering",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/mongo.py#L195-L203 | train | 32,754 |
noirbizarre/flask-fs | flask_fs/views.py | get_file | def get_file(fs, filename):
'''Serve files for storages with direct file access'''
storage = by_name(fs)
if storage is None:
abort(404)
return storage.serve(filename) | python | def get_file(fs, filename):
'''Serve files for storages with direct file access'''
storage = by_name(fs)
if storage is None:
abort(404)
return storage.serve(filename) | [
"def",
"get_file",
"(",
"fs",
",",
"filename",
")",
":",
"storage",
"=",
"by_name",
"(",
"fs",
")",
"if",
"storage",
"is",
"None",
":",
"abort",
"(",
"404",
")",
"return",
"storage",
".",
"serve",
"(",
"filename",
")"
] | Serve files for storages with direct file access | [
"Serve",
"files",
"for",
"storages",
"with",
"direct",
"file",
"access"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/views.py#L12-L17 | train | 32,755 |
noirbizarre/flask-fs | flask_fs/__init__.py | init_app | def init_app(app, *storages):
'''
Initialize Storages configuration
Register blueprint if necessary.
:param app: The `~flask.Flask` instance to get the configuration from.
:param storages: A `Storage` instance list to register and configure.
'''
# Set default configuration
app.config.setdefault('FS_SERVE', app.config.get('DEBUG', False))
app.config.setdefault('FS_ROOT', join(app.instance_path, 'fs'))
app.config.setdefault('FS_PREFIX', None)
app.config.setdefault('FS_URL', None)
app.config.setdefault('FS_BACKEND', DEFAULT_BACKEND)
app.config.setdefault('FS_IMAGES_OPTIMIZE', False)
state = app.extensions['fs'] = app.extensions.get('fs', {})
for storage in storages:
storage.configure(app)
state[storage.name] = storage
from .views import bp
app.register_blueprint(bp, url_prefix=app.config['FS_PREFIX']) | python | def init_app(app, *storages):
'''
Initialize Storages configuration
Register blueprint if necessary.
:param app: The `~flask.Flask` instance to get the configuration from.
:param storages: A `Storage` instance list to register and configure.
'''
# Set default configuration
app.config.setdefault('FS_SERVE', app.config.get('DEBUG', False))
app.config.setdefault('FS_ROOT', join(app.instance_path, 'fs'))
app.config.setdefault('FS_PREFIX', None)
app.config.setdefault('FS_URL', None)
app.config.setdefault('FS_BACKEND', DEFAULT_BACKEND)
app.config.setdefault('FS_IMAGES_OPTIMIZE', False)
state = app.extensions['fs'] = app.extensions.get('fs', {})
for storage in storages:
storage.configure(app)
state[storage.name] = storage
from .views import bp
app.register_blueprint(bp, url_prefix=app.config['FS_PREFIX']) | [
"def",
"init_app",
"(",
"app",
",",
"*",
"storages",
")",
":",
"# Set default configuration",
"app",
".",
"config",
".",
"setdefault",
"(",
"'FS_SERVE'",
",",
"app",
".",
"config",
".",
"get",
"(",
"'DEBUG'",
",",
"False",
")",
")",
"app",
".",
"config",... | Initialize Storages configuration
Register blueprint if necessary.
:param app: The `~flask.Flask` instance to get the configuration from.
:param storages: A `Storage` instance list to register and configure. | [
"Initialize",
"Storages",
"configuration",
"Register",
"blueprint",
"if",
"necessary",
"."
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/__init__.py#L25-L48 | train | 32,756 |
noirbizarre/flask-fs | flask_fs/backends/local.py | LocalBackend.get_metadata | def get_metadata(self, filename):
'''Fetch all available metadata'''
dest = self.path(filename)
with open(dest, 'rb', buffering=0) as f:
checksum = 'sha1:{0}'.format(sha1(f))
return {
'checksum': checksum,
'size': os.path.getsize(dest),
'mime': files.mime(filename),
'modified': datetime.fromtimestamp(os.path.getmtime(dest)),
} | python | def get_metadata(self, filename):
'''Fetch all available metadata'''
dest = self.path(filename)
with open(dest, 'rb', buffering=0) as f:
checksum = 'sha1:{0}'.format(sha1(f))
return {
'checksum': checksum,
'size': os.path.getsize(dest),
'mime': files.mime(filename),
'modified': datetime.fromtimestamp(os.path.getmtime(dest)),
} | [
"def",
"get_metadata",
"(",
"self",
",",
"filename",
")",
":",
"dest",
"=",
"self",
".",
"path",
"(",
"filename",
")",
"with",
"open",
"(",
"dest",
",",
"'rb'",
",",
"buffering",
"=",
"0",
")",
"as",
"f",
":",
"checksum",
"=",
"'sha1:{0}'",
".",
"f... | Fetch all available metadata | [
"Fetch",
"all",
"available",
"metadata"
] | 092e9327384b8411c9bb38ca257ecb558584d201 | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/backends/local.py#L132-L142 | train | 32,757 |
LogicalDash/LiSE | ELiDE/ELiDE/dummy.py | Dummy.on_touch_move | def on_touch_move(self, touch):
"""Follow the touch"""
if touch is not self._touch:
return False
self.pos = (
touch.x + self.x_down,
touch.y + self.y_down
)
return True | python | def on_touch_move(self, touch):
"""Follow the touch"""
if touch is not self._touch:
return False
self.pos = (
touch.x + self.x_down,
touch.y + self.y_down
)
return True | [
"def",
"on_touch_move",
"(",
"self",
",",
"touch",
")",
":",
"if",
"touch",
"is",
"not",
"self",
".",
"_touch",
":",
"return",
"False",
"self",
".",
"pos",
"=",
"(",
"touch",
".",
"x",
"+",
"self",
".",
"x_down",
",",
"touch",
".",
"y",
"+",
"sel... | Follow the touch | [
"Follow",
"the",
"touch"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/dummy.py#L75-L83 | train | 32,758 |
LogicalDash/LiSE | LiSE/LiSE/thing.py | Thing.clear | def clear(self):
"""Unset everything."""
for k in list(self.keys()):
if k not in self.extrakeys:
del self[k] | python | def clear(self):
"""Unset everything."""
for k in list(self.keys()):
if k not in self.extrakeys:
del self[k] | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"k",
"in",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
":",
"if",
"k",
"not",
"in",
"self",
".",
"extrakeys",
":",
"del",
"self",
"[",
"k",
"]"
] | Unset everything. | [
"Unset",
"everything",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/thing.py#L152-L156 | train | 32,759 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | AbstractEngine.loading | def loading(self):
"""Context manager for when you need to instantiate entities upon unpacking"""
if getattr(self, '_initialized', False):
raise ValueError("Already loading")
self._initialized = False
yield
self._initialized = True | python | def loading(self):
"""Context manager for when you need to instantiate entities upon unpacking"""
if getattr(self, '_initialized', False):
raise ValueError("Already loading")
self._initialized = False
yield
self._initialized = True | [
"def",
"loading",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_initialized'",
",",
"False",
")",
":",
"raise",
"ValueError",
"(",
"\"Already loading\"",
")",
"self",
".",
"_initialized",
"=",
"False",
"yield",
"self",
".",
"_initialized",
"... | Context manager for when you need to instantiate entities upon unpacking | [
"Context",
"manager",
"for",
"when",
"you",
"need",
"to",
"instantiate",
"entities",
"upon",
"unpacking"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L164-L170 | train | 32,760 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | AbstractEngine.dice | def dice(self, n, d):
"""Roll ``n`` dice with ``d`` faces, and yield the results.
This is an iterator. You'll get the result of each die in
successon.
"""
for i in range(0, n):
yield self.roll_die(d) | python | def dice(self, n, d):
"""Roll ``n`` dice with ``d`` faces, and yield the results.
This is an iterator. You'll get the result of each die in
successon.
"""
for i in range(0, n):
yield self.roll_die(d) | [
"def",
"dice",
"(",
"self",
",",
"n",
",",
"d",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"n",
")",
":",
"yield",
"self",
".",
"roll_die",
"(",
"d",
")"
] | Roll ``n`` dice with ``d`` faces, and yield the results.
This is an iterator. You'll get the result of each die in
successon. | [
"Roll",
"n",
"dice",
"with",
"d",
"faces",
"and",
"yield",
"the",
"results",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L413-L421 | train | 32,761 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | AbstractEngine.dice_check | def dice_check(self, n, d, target, comparator='<='):
"""Roll ``n`` dice with ``d`` sides, sum them, and return whether they
are <= ``target``.
If ``comparator`` is provided, use it instead of <=. You may
use a string like '<' or '>='.
"""
from operator import gt, lt, ge, le, eq, ne
comps = {
'>': gt,
'<': lt,
'>=': ge,
'<=': le,
'=': eq,
'==': eq,
'!=': ne
}
try:
comparator = comps.get(comparator, comparator)
except TypeError:
pass
return comparator(sum(self.dice(n, d)), target) | python | def dice_check(self, n, d, target, comparator='<='):
"""Roll ``n`` dice with ``d`` sides, sum them, and return whether they
are <= ``target``.
If ``comparator`` is provided, use it instead of <=. You may
use a string like '<' or '>='.
"""
from operator import gt, lt, ge, le, eq, ne
comps = {
'>': gt,
'<': lt,
'>=': ge,
'<=': le,
'=': eq,
'==': eq,
'!=': ne
}
try:
comparator = comps.get(comparator, comparator)
except TypeError:
pass
return comparator(sum(self.dice(n, d)), target) | [
"def",
"dice_check",
"(",
"self",
",",
"n",
",",
"d",
",",
"target",
",",
"comparator",
"=",
"'<='",
")",
":",
"from",
"operator",
"import",
"gt",
",",
"lt",
",",
"ge",
",",
"le",
",",
"eq",
",",
"ne",
"comps",
"=",
"{",
"'>'",
":",
"gt",
",",
... | Roll ``n`` dice with ``d`` sides, sum them, and return whether they
are <= ``target``.
If ``comparator`` is provided, use it instead of <=. You may
use a string like '<' or '>='. | [
"Roll",
"n",
"dice",
"with",
"d",
"sides",
"sum",
"them",
"and",
"return",
"whether",
"they",
"are",
"<",
"=",
"target",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L423-L446 | train | 32,762 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | AbstractEngine.percent_chance | def percent_chance(self, pct):
"""Given a ``pct``% chance of something happening right now, decide at
random whether it actually happens, and return ``True`` or
``False`` as appropriate.
Values not between 0 and 100 are treated as though they
were 0 or 100, whichever is nearer.
"""
if pct <= 0:
return False
if pct >= 100:
return True
return pct / 100 < self.random() | python | def percent_chance(self, pct):
"""Given a ``pct``% chance of something happening right now, decide at
random whether it actually happens, and return ``True`` or
``False`` as appropriate.
Values not between 0 and 100 are treated as though they
were 0 or 100, whichever is nearer.
"""
if pct <= 0:
return False
if pct >= 100:
return True
return pct / 100 < self.random() | [
"def",
"percent_chance",
"(",
"self",
",",
"pct",
")",
":",
"if",
"pct",
"<=",
"0",
":",
"return",
"False",
"if",
"pct",
">=",
"100",
":",
"return",
"True",
"return",
"pct",
"/",
"100",
"<",
"self",
".",
"random",
"(",
")"
] | Given a ``pct``% chance of something happening right now, decide at
random whether it actually happens, and return ``True`` or
``False`` as appropriate.
Values not between 0 and 100 are treated as though they
were 0 or 100, whichever is nearer. | [
"Given",
"a",
"pct",
"%",
"chance",
"of",
"something",
"happening",
"right",
"now",
"decide",
"at",
"random",
"whether",
"it",
"actually",
"happens",
"and",
"return",
"True",
"or",
"False",
"as",
"appropriate",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L448-L461 | train | 32,763 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | Engine._remember_avatarness | def _remember_avatarness(
self, character, graph, node,
is_avatar=True, branch=None, turn=None,
tick=None
):
"""Use this to record a change in avatarness.
Should be called whenever a node that wasn't an avatar of a
character now is, and whenever a node that was an avatar of a
character now isn't.
``character`` is the one using the node as an avatar,
``graph`` is the character the node is in.
"""
branch = branch or self.branch
turn = turn or self.turn
tick = tick or self.tick
self._avatarness_cache.store(
character,
graph,
node,
branch,
turn,
tick,
is_avatar
)
self.query.avatar_set(
character,
graph,
node,
branch,
turn,
tick,
is_avatar
) | python | def _remember_avatarness(
self, character, graph, node,
is_avatar=True, branch=None, turn=None,
tick=None
):
"""Use this to record a change in avatarness.
Should be called whenever a node that wasn't an avatar of a
character now is, and whenever a node that was an avatar of a
character now isn't.
``character`` is the one using the node as an avatar,
``graph`` is the character the node is in.
"""
branch = branch or self.branch
turn = turn or self.turn
tick = tick or self.tick
self._avatarness_cache.store(
character,
graph,
node,
branch,
turn,
tick,
is_avatar
)
self.query.avatar_set(
character,
graph,
node,
branch,
turn,
tick,
is_avatar
) | [
"def",
"_remember_avatarness",
"(",
"self",
",",
"character",
",",
"graph",
",",
"node",
",",
"is_avatar",
"=",
"True",
",",
"branch",
"=",
"None",
",",
"turn",
"=",
"None",
",",
"tick",
"=",
"None",
")",
":",
"branch",
"=",
"branch",
"or",
"self",
"... | Use this to record a change in avatarness.
Should be called whenever a node that wasn't an avatar of a
character now is, and whenever a node that was an avatar of a
character now isn't.
``character`` is the one using the node as an avatar,
``graph`` is the character the node is in. | [
"Use",
"this",
"to",
"record",
"a",
"change",
"in",
"avatarness",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L806-L841 | train | 32,764 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | Engine._init_caches | def _init_caches(self):
from .xcollections import (
StringStore,
FunctionStore,
CharacterMapping,
UniversalMapping
)
from .cache import (
Cache,
NodeContentsCache,
InitializedCache,
EntitylessCache,
InitializedEntitylessCache,
AvatarnessCache,
AvatarRulesHandledCache,
CharacterThingRulesHandledCache,
CharacterPlaceRulesHandledCache,
CharacterPortalRulesHandledCache,
NodeRulesHandledCache,
PortalRulesHandledCache,
CharacterRulesHandledCache,
ThingsCache
)
from .rule import AllRuleBooks, AllRules
super()._init_caches()
self._things_cache = ThingsCache(self)
self._things_cache.setdb = self.query.set_thing_loc
self._node_contents_cache = NodeContentsCache(self)
self.character = self.graph = CharacterMapping(self)
self._universal_cache = EntitylessCache(self)
self._universal_cache.setdb = self.query.universal_set
self._rulebooks_cache = InitializedEntitylessCache(self)
self._rulebooks_cache.setdb = self.query.rulebook_set
self._characters_rulebooks_cache = InitializedEntitylessCache(self)
self._avatars_rulebooks_cache = InitializedEntitylessCache(self)
self._characters_things_rulebooks_cache = InitializedEntitylessCache(self)
self._characters_places_rulebooks_cache = InitializedEntitylessCache(self)
self._characters_portals_rulebooks_cache = InitializedEntitylessCache(self)
self._nodes_rulebooks_cache = InitializedCache(self)
self._portals_rulebooks_cache = InitializedCache(self)
self._triggers_cache = InitializedEntitylessCache(self)
self._prereqs_cache = InitializedEntitylessCache(self)
self._actions_cache = InitializedEntitylessCache(self)
self._node_rules_handled_cache = NodeRulesHandledCache(self)
self._portal_rules_handled_cache = PortalRulesHandledCache(self)
self._character_rules_handled_cache = CharacterRulesHandledCache(self)
self._avatar_rules_handled_cache = AvatarRulesHandledCache(self)
self._character_thing_rules_handled_cache \
= CharacterThingRulesHandledCache(self)
self._character_place_rules_handled_cache \
= CharacterPlaceRulesHandledCache(self)
self._character_portal_rules_handled_cache \
= CharacterPortalRulesHandledCache(self)
self._avatarness_cache = AvatarnessCache(self)
self._turns_completed = defaultdict(lambda: max((0, self.turn - 1)))
"""The last turn when the rules engine ran in each branch"""
self.eternal = self.query.globl
self.universal = UniversalMapping(self)
if hasattr(self, '_action_file'):
self.action = FunctionStore(self._action_file)
if hasattr(self, '_prereq_file'):
self.prereq = FunctionStore(self._prereq_file)
if hasattr(self, '_trigger_file'):
self.trigger = FunctionStore(self._trigger_file)
if hasattr(self, '_function_file'):
self.function = FunctionStore(self._function_file)
if hasattr(self, '_method_file'):
self.method = FunctionStore(self._method_file)
self.rule = AllRules(self)
self.rulebook = AllRuleBooks(self)
if hasattr(self, '_string_file'):
self.string = StringStore(
self.query,
self._string_file,
self.eternal.setdefault('language', 'eng')
) | python | def _init_caches(self):
from .xcollections import (
StringStore,
FunctionStore,
CharacterMapping,
UniversalMapping
)
from .cache import (
Cache,
NodeContentsCache,
InitializedCache,
EntitylessCache,
InitializedEntitylessCache,
AvatarnessCache,
AvatarRulesHandledCache,
CharacterThingRulesHandledCache,
CharacterPlaceRulesHandledCache,
CharacterPortalRulesHandledCache,
NodeRulesHandledCache,
PortalRulesHandledCache,
CharacterRulesHandledCache,
ThingsCache
)
from .rule import AllRuleBooks, AllRules
super()._init_caches()
self._things_cache = ThingsCache(self)
self._things_cache.setdb = self.query.set_thing_loc
self._node_contents_cache = NodeContentsCache(self)
self.character = self.graph = CharacterMapping(self)
self._universal_cache = EntitylessCache(self)
self._universal_cache.setdb = self.query.universal_set
self._rulebooks_cache = InitializedEntitylessCache(self)
self._rulebooks_cache.setdb = self.query.rulebook_set
self._characters_rulebooks_cache = InitializedEntitylessCache(self)
self._avatars_rulebooks_cache = InitializedEntitylessCache(self)
self._characters_things_rulebooks_cache = InitializedEntitylessCache(self)
self._characters_places_rulebooks_cache = InitializedEntitylessCache(self)
self._characters_portals_rulebooks_cache = InitializedEntitylessCache(self)
self._nodes_rulebooks_cache = InitializedCache(self)
self._portals_rulebooks_cache = InitializedCache(self)
self._triggers_cache = InitializedEntitylessCache(self)
self._prereqs_cache = InitializedEntitylessCache(self)
self._actions_cache = InitializedEntitylessCache(self)
self._node_rules_handled_cache = NodeRulesHandledCache(self)
self._portal_rules_handled_cache = PortalRulesHandledCache(self)
self._character_rules_handled_cache = CharacterRulesHandledCache(self)
self._avatar_rules_handled_cache = AvatarRulesHandledCache(self)
self._character_thing_rules_handled_cache \
= CharacterThingRulesHandledCache(self)
self._character_place_rules_handled_cache \
= CharacterPlaceRulesHandledCache(self)
self._character_portal_rules_handled_cache \
= CharacterPortalRulesHandledCache(self)
self._avatarness_cache = AvatarnessCache(self)
self._turns_completed = defaultdict(lambda: max((0, self.turn - 1)))
"""The last turn when the rules engine ran in each branch"""
self.eternal = self.query.globl
self.universal = UniversalMapping(self)
if hasattr(self, '_action_file'):
self.action = FunctionStore(self._action_file)
if hasattr(self, '_prereq_file'):
self.prereq = FunctionStore(self._prereq_file)
if hasattr(self, '_trigger_file'):
self.trigger = FunctionStore(self._trigger_file)
if hasattr(self, '_function_file'):
self.function = FunctionStore(self._function_file)
if hasattr(self, '_method_file'):
self.method = FunctionStore(self._method_file)
self.rule = AllRules(self)
self.rulebook = AllRuleBooks(self)
if hasattr(self, '_string_file'):
self.string = StringStore(
self.query,
self._string_file,
self.eternal.setdefault('language', 'eng')
) | [
"def",
"_init_caches",
"(",
"self",
")",
":",
"from",
".",
"xcollections",
"import",
"(",
"StringStore",
",",
"FunctionStore",
",",
"CharacterMapping",
",",
"UniversalMapping",
")",
"from",
".",
"cache",
"import",
"(",
"Cache",
",",
"NodeContentsCache",
",",
"... | The last turn when the rules engine ran in each branch | [
"The",
"last",
"turn",
"when",
"the",
"rules",
"engine",
"ran",
"in",
"each",
"branch"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L843-L919 | train | 32,765 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | Engine.close | def close(self):
"""Commit changes and close the database."""
import sys, os
for store in self.stores:
if hasattr(store, 'save'):
store.save(reimport=False)
path, filename = os.path.split(store._filename)
modname = filename[:-3]
if modname in sys.modules:
del sys.modules[modname]
super().close() | python | def close(self):
"""Commit changes and close the database."""
import sys, os
for store in self.stores:
if hasattr(store, 'save'):
store.save(reimport=False)
path, filename = os.path.split(store._filename)
modname = filename[:-3]
if modname in sys.modules:
del sys.modules[modname]
super().close() | [
"def",
"close",
"(",
"self",
")",
":",
"import",
"sys",
",",
"os",
"for",
"store",
"in",
"self",
".",
"stores",
":",
"if",
"hasattr",
"(",
"store",
",",
"'save'",
")",
":",
"store",
".",
"save",
"(",
"reimport",
"=",
"False",
")",
"path",
",",
"f... | Commit changes and close the database. | [
"Commit",
"changes",
"and",
"close",
"the",
"database",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L1107-L1117 | train | 32,766 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | Engine.advance | def advance(self):
"""Follow the next rule if available.
If we've run out of rules, reset the rules iterator.
"""
try:
return next(self._rules_iter)
except InnerStopIteration:
self._rules_iter = self._follow_rules()
return StopIteration()
except StopIteration:
self._rules_iter = self._follow_rules()
return final_rule | python | def advance(self):
"""Follow the next rule if available.
If we've run out of rules, reset the rules iterator.
"""
try:
return next(self._rules_iter)
except InnerStopIteration:
self._rules_iter = self._follow_rules()
return StopIteration()
except StopIteration:
self._rules_iter = self._follow_rules()
return final_rule | [
"def",
"advance",
"(",
"self",
")",
":",
"try",
":",
"return",
"next",
"(",
"self",
".",
"_rules_iter",
")",
"except",
"InnerStopIteration",
":",
"self",
".",
"_rules_iter",
"=",
"self",
".",
"_follow_rules",
"(",
")",
"return",
"StopIteration",
"(",
")",
... | Follow the next rule if available.
If we've run out of rules, reset the rules iterator. | [
"Follow",
"the",
"next",
"rule",
"if",
"available",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L1395-L1408 | train | 32,767 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | Engine.del_character | def del_character(self, name):
"""Remove the Character from the database entirely.
This also deletes all its history. You'd better be sure.
"""
self.query.del_character(name)
self.del_graph(name)
del self.character[name] | python | def del_character(self, name):
"""Remove the Character from the database entirely.
This also deletes all its history. You'd better be sure.
"""
self.query.del_character(name)
self.del_graph(name)
del self.character[name] | [
"def",
"del_character",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"query",
".",
"del_character",
"(",
"name",
")",
"self",
".",
"del_graph",
"(",
"name",
")",
"del",
"self",
".",
"character",
"[",
"name",
"]"
] | Remove the Character from the database entirely.
This also deletes all its history. You'd better be sure. | [
"Remove",
"the",
"Character",
"from",
"the",
"database",
"entirely",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L1433-L1441 | train | 32,768 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | Engine.alias | def alias(self, v, stat='dummy'):
"""Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which
happens to contain only the value you've provided here, ``v``.
:arg v: the value to represent
:arg stat: what name to pretend its stat has; usually irrelevant
"""
from .util import EntityStatAccessor
r = DummyEntity(self)
r[stat] = v
return EntityStatAccessor(r, stat, engine=self) | python | def alias(self, v, stat='dummy'):
"""Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which
happens to contain only the value you've provided here, ``v``.
:arg v: the value to represent
:arg stat: what name to pretend its stat has; usually irrelevant
"""
from .util import EntityStatAccessor
r = DummyEntity(self)
r[stat] = v
return EntityStatAccessor(r, stat, engine=self) | [
"def",
"alias",
"(",
"self",
",",
"v",
",",
"stat",
"=",
"'dummy'",
")",
":",
"from",
".",
"util",
"import",
"EntityStatAccessor",
"r",
"=",
"DummyEntity",
"(",
"self",
")",
"r",
"[",
"stat",
"]",
"=",
"v",
"return",
"EntityStatAccessor",
"(",
"r",
"... | Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which
happens to contain only the value you've provided here, ``v``.
:arg v: the value to represent
:arg stat: what name to pretend its stat has; usually irrelevant | [
"Return",
"a",
"representation",
"of",
"a",
"value",
"suitable",
"for",
"use",
"in",
"historical",
"queries",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L1460-L1474 | train | 32,769 |
LogicalDash/LiSE | ELiDE/ELiDE/screen.py | MainScreen.on_play_speed | def on_play_speed(self, *args):
"""Change the interval at which ``self.play`` is called to match my
current ``play_speed``.
"""
Clock.unschedule(self.play)
Clock.schedule_interval(self.play, 1.0 / self.play_speed) | python | def on_play_speed(self, *args):
"""Change the interval at which ``self.play`` is called to match my
current ``play_speed``.
"""
Clock.unschedule(self.play)
Clock.schedule_interval(self.play, 1.0 / self.play_speed) | [
"def",
"on_play_speed",
"(",
"self",
",",
"*",
"args",
")",
":",
"Clock",
".",
"unschedule",
"(",
"self",
".",
"play",
")",
"Clock",
".",
"schedule_interval",
"(",
"self",
".",
"play",
",",
"1.0",
"/",
"self",
".",
"play_speed",
")"
] | Change the interval at which ``self.play`` is called to match my
current ``play_speed``. | [
"Change",
"the",
"interval",
"at",
"which",
"self",
".",
"play",
"is",
"called",
"to",
"match",
"my",
"current",
"play_speed",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/screen.py#L210-L216 | train | 32,770 |
LogicalDash/LiSE | ELiDE/ELiDE/screen.py | MainScreen.remake_display | def remake_display(self, *args):
"""Remake any affected widgets after a change in my ``kv``.
"""
Builder.load_string(self.kv)
if hasattr(self, '_kv_layout'):
self.remove_widget(self._kv_layout)
del self._kv_layout
self._kv_layout = KvLayout()
self.add_widget(self._kv_layout) | python | def remake_display(self, *args):
"""Remake any affected widgets after a change in my ``kv``.
"""
Builder.load_string(self.kv)
if hasattr(self, '_kv_layout'):
self.remove_widget(self._kv_layout)
del self._kv_layout
self._kv_layout = KvLayout()
self.add_widget(self._kv_layout) | [
"def",
"remake_display",
"(",
"self",
",",
"*",
"args",
")",
":",
"Builder",
".",
"load_string",
"(",
"self",
".",
"kv",
")",
"if",
"hasattr",
"(",
"self",
",",
"'_kv_layout'",
")",
":",
"self",
".",
"remove_widget",
"(",
"self",
".",
"_kv_layout",
")"... | Remake any affected widgets after a change in my ``kv``. | [
"Remake",
"any",
"affected",
"widgets",
"after",
"a",
"change",
"in",
"my",
"kv",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/screen.py#L218-L227 | train | 32,771 |
LogicalDash/LiSE | ELiDE/ELiDE/screen.py | MainScreen.next_turn | def next_turn(self, *args):
"""Advance time by one turn, if it's not blocked.
Block time by setting ``engine.universal['block'] = True``"""
if self.tmp_block:
return
eng = self.app.engine
dial = self.dialoglayout
if eng.universal.get('block'):
Logger.info("MainScreen: next_turn blocked, delete universal['block'] to unblock")
return
if dial.idx < len(dial.todo):
Logger.info("MainScreen: not advancing time while there's a dialog")
return
self.tmp_block = True
self.app.unbind(
branch=self.app._push_time,
turn=self.app._push_time,
tick=self.app._push_time
)
eng.next_turn(cb=self._update_from_next_turn) | python | def next_turn(self, *args):
"""Advance time by one turn, if it's not blocked.
Block time by setting ``engine.universal['block'] = True``"""
if self.tmp_block:
return
eng = self.app.engine
dial = self.dialoglayout
if eng.universal.get('block'):
Logger.info("MainScreen: next_turn blocked, delete universal['block'] to unblock")
return
if dial.idx < len(dial.todo):
Logger.info("MainScreen: not advancing time while there's a dialog")
return
self.tmp_block = True
self.app.unbind(
branch=self.app._push_time,
turn=self.app._push_time,
tick=self.app._push_time
)
eng.next_turn(cb=self._update_from_next_turn) | [
"def",
"next_turn",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"tmp_block",
":",
"return",
"eng",
"=",
"self",
".",
"app",
".",
"engine",
"dial",
"=",
"self",
".",
"dialoglayout",
"if",
"eng",
".",
"universal",
".",
"get",
"(",
"'b... | Advance time by one turn, if it's not blocked.
Block time by setting ``engine.universal['block'] = True`` | [
"Advance",
"time",
"by",
"one",
"turn",
"if",
"it",
"s",
"not",
"blocked",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/screen.py#L330-L350 | train | 32,772 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | setgraphval | def setgraphval(delta, graph, key, val):
"""Change a delta to say that a graph stat was set to a certain value"""
delta.setdefault(graph, {})[key] = val | python | def setgraphval(delta, graph, key, val):
"""Change a delta to say that a graph stat was set to a certain value"""
delta.setdefault(graph, {})[key] = val | [
"def",
"setgraphval",
"(",
"delta",
",",
"graph",
",",
"key",
",",
"val",
")",
":",
"delta",
".",
"setdefault",
"(",
"graph",
",",
"{",
"}",
")",
"[",
"key",
"]",
"=",
"val"
] | Change a delta to say that a graph stat was set to a certain value | [
"Change",
"a",
"delta",
"to",
"say",
"that",
"a",
"graph",
"stat",
"was",
"set",
"to",
"a",
"certain",
"value"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L222-L224 | train | 32,773 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | setnode | def setnode(delta, graph, node, exists):
"""Change a delta to say that a node was created or deleted"""
delta.setdefault(graph, {}).setdefault('nodes', {})[node] = bool(exists) | python | def setnode(delta, graph, node, exists):
"""Change a delta to say that a node was created or deleted"""
delta.setdefault(graph, {}).setdefault('nodes', {})[node] = bool(exists) | [
"def",
"setnode",
"(",
"delta",
",",
"graph",
",",
"node",
",",
"exists",
")",
":",
"delta",
".",
"setdefault",
"(",
"graph",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"'nodes'",
",",
"{",
"}",
")",
"[",
"node",
"]",
"=",
"bool",
"(",
"exists",... | Change a delta to say that a node was created or deleted | [
"Change",
"a",
"delta",
"to",
"say",
"that",
"a",
"node",
"was",
"created",
"or",
"deleted"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L227-L229 | train | 32,774 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | setnodeval | def setnodeval(delta, graph, node, key, value):
"""Change a delta to say that a node stat was set to a certain value"""
if (
graph in delta and 'nodes' in delta[graph] and
node in delta[graph]['nodes'] and not delta[graph]['nodes'][node]
):
return
delta.setdefault(graph, {}).setdefault('node_val', {}).setdefault(node, {})[key] = value | python | def setnodeval(delta, graph, node, key, value):
"""Change a delta to say that a node stat was set to a certain value"""
if (
graph in delta and 'nodes' in delta[graph] and
node in delta[graph]['nodes'] and not delta[graph]['nodes'][node]
):
return
delta.setdefault(graph, {}).setdefault('node_val', {}).setdefault(node, {})[key] = value | [
"def",
"setnodeval",
"(",
"delta",
",",
"graph",
",",
"node",
",",
"key",
",",
"value",
")",
":",
"if",
"(",
"graph",
"in",
"delta",
"and",
"'nodes'",
"in",
"delta",
"[",
"graph",
"]",
"and",
"node",
"in",
"delta",
"[",
"graph",
"]",
"[",
"'nodes'"... | Change a delta to say that a node stat was set to a certain value | [
"Change",
"a",
"delta",
"to",
"say",
"that",
"a",
"node",
"stat",
"was",
"set",
"to",
"a",
"certain",
"value"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L232-L239 | train | 32,775 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | setedge | def setedge(delta, is_multigraph, graph, orig, dest, idx, exists):
"""Change a delta to say that an edge was created or deleted"""
if is_multigraph(graph):
delta.setdefault(graph, {}).setdefault('edges', {})\
.setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists)
else:
delta.setdefault(graph, {}).setdefault('edges', {})\
.setdefault(orig, {})[dest] = bool(exists) | python | def setedge(delta, is_multigraph, graph, orig, dest, idx, exists):
"""Change a delta to say that an edge was created or deleted"""
if is_multigraph(graph):
delta.setdefault(graph, {}).setdefault('edges', {})\
.setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists)
else:
delta.setdefault(graph, {}).setdefault('edges', {})\
.setdefault(orig, {})[dest] = bool(exists) | [
"def",
"setedge",
"(",
"delta",
",",
"is_multigraph",
",",
"graph",
",",
"orig",
",",
"dest",
",",
"idx",
",",
"exists",
")",
":",
"if",
"is_multigraph",
"(",
"graph",
")",
":",
"delta",
".",
"setdefault",
"(",
"graph",
",",
"{",
"}",
")",
".",
"se... | Change a delta to say that an edge was created or deleted | [
"Change",
"a",
"delta",
"to",
"say",
"that",
"an",
"edge",
"was",
"created",
"or",
"deleted"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L242-L249 | train | 32,776 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | setedgeval | def setedgeval(delta, is_multigraph, graph, orig, dest, idx, key, value):
"""Change a delta to say that an edge stat was set to a certain value"""
if is_multigraph(graph):
if (
graph in delta and 'edges' in delta[graph] and
orig in delta[graph]['edges'] and dest in delta[graph]['edges'][orig]
and idx in delta[graph]['edges'][orig][dest]
and not delta[graph]['edges'][orig][dest][idx]
):
return
delta.setdefault(graph, {}).setdefault('edge_val', {})\
.setdefault(orig, {}).setdefault(dest, {})\
.setdefault(idx, {})[key] = value
else:
if (
graph in delta and 'edges' in delta[graph] and
orig in delta[graph]['edges'] and dest in delta[graph]['edges'][orig]
and not delta[graph]['edges'][orig][dest]
):
return
delta.setdefault(graph, {}).setdefault('edge_val', {})\
.setdefault(orig, {}).setdefault(dest, {})[key] = value | python | def setedgeval(delta, is_multigraph, graph, orig, dest, idx, key, value):
"""Change a delta to say that an edge stat was set to a certain value"""
if is_multigraph(graph):
if (
graph in delta and 'edges' in delta[graph] and
orig in delta[graph]['edges'] and dest in delta[graph]['edges'][orig]
and idx in delta[graph]['edges'][orig][dest]
and not delta[graph]['edges'][orig][dest][idx]
):
return
delta.setdefault(graph, {}).setdefault('edge_val', {})\
.setdefault(orig, {}).setdefault(dest, {})\
.setdefault(idx, {})[key] = value
else:
if (
graph in delta and 'edges' in delta[graph] and
orig in delta[graph]['edges'] and dest in delta[graph]['edges'][orig]
and not delta[graph]['edges'][orig][dest]
):
return
delta.setdefault(graph, {}).setdefault('edge_val', {})\
.setdefault(orig, {}).setdefault(dest, {})[key] = value | [
"def",
"setedgeval",
"(",
"delta",
",",
"is_multigraph",
",",
"graph",
",",
"orig",
",",
"dest",
",",
"idx",
",",
"key",
",",
"value",
")",
":",
"if",
"is_multigraph",
"(",
"graph",
")",
":",
"if",
"(",
"graph",
"in",
"delta",
"and",
"'edges'",
"in",... | Change a delta to say that an edge stat was set to a certain value | [
"Change",
"a",
"delta",
"to",
"say",
"that",
"an",
"edge",
"stat",
"was",
"set",
"to",
"a",
"certain",
"value"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L252-L273 | train | 32,777 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.advancing | def advancing(self):
"""A context manager for when time is moving forward one turn at a time.
When used in LiSE, this means that the game is being simulated.
It changes how the caching works, making it more efficient.
"""
if self._forward:
raise ValueError("Already advancing")
self._forward = True
yield
self._forward = False | python | def advancing(self):
"""A context manager for when time is moving forward one turn at a time.
When used in LiSE, this means that the game is being simulated.
It changes how the caching works, making it more efficient.
"""
if self._forward:
raise ValueError("Already advancing")
self._forward = True
yield
self._forward = False | [
"def",
"advancing",
"(",
"self",
")",
":",
"if",
"self",
".",
"_forward",
":",
"raise",
"ValueError",
"(",
"\"Already advancing\"",
")",
"self",
".",
"_forward",
"=",
"True",
"yield",
"self",
".",
"_forward",
"=",
"False"
] | A context manager for when time is moving forward one turn at a time.
When used in LiSE, this means that the game is being simulated.
It changes how the caching works, making it more efficient. | [
"A",
"context",
"manager",
"for",
"when",
"time",
"is",
"moving",
"forward",
"one",
"turn",
"at",
"a",
"time",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L334-L345 | train | 32,778 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.batch | def batch(self):
"""A context manager for when you're creating lots of state.
Reads will be much slower in a batch, but writes will be faster.
You *can* combine this with ``advancing`` but it isn't any faster.
"""
if self._no_kc:
raise ValueError("Already in a batch")
self._no_kc = True
yield
self._no_kc = False | python | def batch(self):
"""A context manager for when you're creating lots of state.
Reads will be much slower in a batch, but writes will be faster.
You *can* combine this with ``advancing`` but it isn't any faster.
"""
if self._no_kc:
raise ValueError("Already in a batch")
self._no_kc = True
yield
self._no_kc = False | [
"def",
"batch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_no_kc",
":",
"raise",
"ValueError",
"(",
"\"Already in a batch\"",
")",
"self",
".",
"_no_kc",
"=",
"True",
"yield",
"self",
".",
"_no_kc",
"=",
"False"
] | A context manager for when you're creating lots of state.
Reads will be much slower in a batch, but writes will be faster.
You *can* combine this with ``advancing`` but it isn't any faster. | [
"A",
"context",
"manager",
"for",
"when",
"you",
"re",
"creating",
"lots",
"of",
"state",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L348-L360 | train | 32,779 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.get_delta | def get_delta(self, branch, turn_from, tick_from, turn_to, tick_to):
"""Get a dictionary describing changes to all graphs.
The keys are graph names. Their values are dictionaries of the graphs'
attributes' new values, with ``None`` for deleted keys. Also in those graph
dictionaries are special keys 'node_val' and 'edge_val' describing changes
to node and edge attributes, and 'nodes' and 'edges' full of booleans
indicating whether a node or edge exists.
"""
from functools import partial
if turn_from == turn_to:
return self.get_turn_delta(branch, turn_from, tick_from, tick_to)
delta = {}
graph_objs = self._graph_objs
if turn_to < turn_from:
updater = partial(update_backward_window, turn_from, tick_from, turn_to, tick_to)
gvbranches = self._graph_val_cache.presettings
nbranches = self._nodes_cache.presettings
nvbranches = self._node_val_cache.presettings
ebranches = self._edges_cache.presettings
evbranches = self._edge_val_cache.presettings
else:
updater = partial(update_window, turn_from, tick_from, turn_to, tick_to)
gvbranches = self._graph_val_cache.settings
nbranches = self._nodes_cache.settings
nvbranches = self._node_val_cache.settings
ebranches = self._edges_cache.settings
evbranches = self._edge_val_cache.settings
if branch in gvbranches:
updater(partial(setgraphval, delta), gvbranches[branch])
if branch in nbranches:
updater(partial(setnode, delta), nbranches[branch])
if branch in nvbranches:
updater(partial(setnodeval, delta), nvbranches[branch])
if branch in ebranches:
updater(partial(setedge, delta, lambda g: graph_objs[g].is_multigraph()), ebranches[branch])
if branch in evbranches:
updater(partial(setedgeval, delta, lambda g: graph_objs[g].is_multigraph()), evbranches[branch])
return delta | python | def get_delta(self, branch, turn_from, tick_from, turn_to, tick_to):
"""Get a dictionary describing changes to all graphs.
The keys are graph names. Their values are dictionaries of the graphs'
attributes' new values, with ``None`` for deleted keys. Also in those graph
dictionaries are special keys 'node_val' and 'edge_val' describing changes
to node and edge attributes, and 'nodes' and 'edges' full of booleans
indicating whether a node or edge exists.
"""
from functools import partial
if turn_from == turn_to:
return self.get_turn_delta(branch, turn_from, tick_from, tick_to)
delta = {}
graph_objs = self._graph_objs
if turn_to < turn_from:
updater = partial(update_backward_window, turn_from, tick_from, turn_to, tick_to)
gvbranches = self._graph_val_cache.presettings
nbranches = self._nodes_cache.presettings
nvbranches = self._node_val_cache.presettings
ebranches = self._edges_cache.presettings
evbranches = self._edge_val_cache.presettings
else:
updater = partial(update_window, turn_from, tick_from, turn_to, tick_to)
gvbranches = self._graph_val_cache.settings
nbranches = self._nodes_cache.settings
nvbranches = self._node_val_cache.settings
ebranches = self._edges_cache.settings
evbranches = self._edge_val_cache.settings
if branch in gvbranches:
updater(partial(setgraphval, delta), gvbranches[branch])
if branch in nbranches:
updater(partial(setnode, delta), nbranches[branch])
if branch in nvbranches:
updater(partial(setnodeval, delta), nvbranches[branch])
if branch in ebranches:
updater(partial(setedge, delta, lambda g: graph_objs[g].is_multigraph()), ebranches[branch])
if branch in evbranches:
updater(partial(setedgeval, delta, lambda g: graph_objs[g].is_multigraph()), evbranches[branch])
return delta | [
"def",
"get_delta",
"(",
"self",
",",
"branch",
",",
"turn_from",
",",
"tick_from",
",",
"turn_to",
",",
"tick_to",
")",
":",
"from",
"functools",
"import",
"partial",
"if",
"turn_from",
"==",
"turn_to",
":",
"return",
"self",
".",
"get_turn_delta",
"(",
"... | Get a dictionary describing changes to all graphs.
The keys are graph names. Their values are dictionaries of the graphs'
attributes' new values, with ``None`` for deleted keys. Also in those graph
dictionaries are special keys 'node_val' and 'edge_val' describing changes
to node and edge attributes, and 'nodes' and 'edges' full of booleans
indicating whether a node or edge exists. | [
"Get",
"a",
"dictionary",
"describing",
"changes",
"to",
"all",
"graphs",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L362-L407 | train | 32,780 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM._init_caches | def _init_caches(self):
from collections import defaultdict
from .cache import Cache, NodesCache, EdgesCache
self._where_cached = defaultdict(list)
self._global_cache = self.query._global_cache = {}
self._node_objs = node_objs = WeakValueDictionary()
self._get_node_stuff = (node_objs, self._node_exists, self._make_node)
self._edge_objs = edge_objs = WeakValueDictionary()
self._get_edge_stuff = (edge_objs, self._edge_exists, self._make_edge)
for k, v in self.query.global_items():
if k == 'branch':
self._obranch = v
elif k == 'turn':
self._oturn = int(v)
elif k == 'tick':
self._otick = int(v)
else:
self._global_cache[k] = v
self._childbranch = defaultdict(set)
"""Immediate children of a branch"""
self._branches = {}
"""Start time, end time, and parent of each branch"""
self._branch_parents = defaultdict(set)
"""Parents of a branch at any remove"""
self._turn_end = defaultdict(lambda: 0)
"""Tick on which a (branch, turn) ends"""
self._turn_end_plan = defaultdict(lambda: 0)
"""Tick on which a (branch, turn) ends, even if it hasn't been simulated"""
self._graph_objs = {}
self._plans = {}
self._branches_plans = defaultdict(set)
self._plan_ticks = defaultdict(lambda: defaultdict(list))
self._time_plan = {}
self._plans_uncommitted = []
self._plan_ticks_uncommitted = []
self._graph_val_cache = Cache(self)
self._graph_val_cache.setdb = self.query.graph_val_set
self._graph_val_cache.deldb = self.query.graph_val_del_time
self._nodes_cache = NodesCache(self)
self._nodes_cache.setdb = self.query.exist_node
self._nodes_cache.deldb = self.query.nodes_del_time
self._edges_cache = EdgesCache(self)
self._edges_cache.setdb = self.query.exist_edge
self._edges_cache.deldb = self.query.edges_del_time
self._node_val_cache = Cache(self)
self._node_val_cache.setdb = self.query.node_val_set
self._node_val_cache.deldb = self.query.node_val_del_time
self._edge_val_cache = Cache(self)
self._edge_val_cache.setdb = self.query.edge_val_set
self._edge_val_cache.deldb = self.query.edge_val_del_time | python | def _init_caches(self):
from collections import defaultdict
from .cache import Cache, NodesCache, EdgesCache
self._where_cached = defaultdict(list)
self._global_cache = self.query._global_cache = {}
self._node_objs = node_objs = WeakValueDictionary()
self._get_node_stuff = (node_objs, self._node_exists, self._make_node)
self._edge_objs = edge_objs = WeakValueDictionary()
self._get_edge_stuff = (edge_objs, self._edge_exists, self._make_edge)
for k, v in self.query.global_items():
if k == 'branch':
self._obranch = v
elif k == 'turn':
self._oturn = int(v)
elif k == 'tick':
self._otick = int(v)
else:
self._global_cache[k] = v
self._childbranch = defaultdict(set)
"""Immediate children of a branch"""
self._branches = {}
"""Start time, end time, and parent of each branch"""
self._branch_parents = defaultdict(set)
"""Parents of a branch at any remove"""
self._turn_end = defaultdict(lambda: 0)
"""Tick on which a (branch, turn) ends"""
self._turn_end_plan = defaultdict(lambda: 0)
"""Tick on which a (branch, turn) ends, even if it hasn't been simulated"""
self._graph_objs = {}
self._plans = {}
self._branches_plans = defaultdict(set)
self._plan_ticks = defaultdict(lambda: defaultdict(list))
self._time_plan = {}
self._plans_uncommitted = []
self._plan_ticks_uncommitted = []
self._graph_val_cache = Cache(self)
self._graph_val_cache.setdb = self.query.graph_val_set
self._graph_val_cache.deldb = self.query.graph_val_del_time
self._nodes_cache = NodesCache(self)
self._nodes_cache.setdb = self.query.exist_node
self._nodes_cache.deldb = self.query.nodes_del_time
self._edges_cache = EdgesCache(self)
self._edges_cache.setdb = self.query.exist_edge
self._edges_cache.deldb = self.query.edges_del_time
self._node_val_cache = Cache(self)
self._node_val_cache.setdb = self.query.node_val_set
self._node_val_cache.deldb = self.query.node_val_del_time
self._edge_val_cache = Cache(self)
self._edge_val_cache.setdb = self.query.edge_val_set
self._edge_val_cache.deldb = self.query.edge_val_del_time | [
"def",
"_init_caches",
"(",
"self",
")",
":",
"from",
"collections",
"import",
"defaultdict",
"from",
".",
"cache",
"import",
"Cache",
",",
"NodesCache",
",",
"EdgesCache",
"self",
".",
"_where_cached",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"_gl... | Immediate children of a branch | [
"Immediate",
"children",
"of",
"a",
"branch"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L504-L553 | train | 32,781 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.is_parent_of | def is_parent_of(self, parent, child):
"""Return whether ``child`` is a branch descended from ``parent`` at
any remove.
"""
if parent == 'trunk':
return True
if child == 'trunk':
return False
if child not in self._branches:
raise ValueError(
"The branch {} seems not to have ever been created".format(
child
)
)
if self._branches[child][0] == parent:
return True
return self.is_parent_of(parent, self._branches[child][0]) | python | def is_parent_of(self, parent, child):
"""Return whether ``child`` is a branch descended from ``parent`` at
any remove.
"""
if parent == 'trunk':
return True
if child == 'trunk':
return False
if child not in self._branches:
raise ValueError(
"The branch {} seems not to have ever been created".format(
child
)
)
if self._branches[child][0] == parent:
return True
return self.is_parent_of(parent, self._branches[child][0]) | [
"def",
"is_parent_of",
"(",
"self",
",",
"parent",
",",
"child",
")",
":",
"if",
"parent",
"==",
"'trunk'",
":",
"return",
"True",
"if",
"child",
"==",
"'trunk'",
":",
"return",
"False",
"if",
"child",
"not",
"in",
"self",
".",
"_branches",
":",
"raise... | Return whether ``child`` is a branch descended from ``parent`` at
any remove. | [
"Return",
"whether",
"child",
"is",
"a",
"branch",
"descended",
"from",
"parent",
"at",
"any",
"remove",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L655-L672 | train | 32,782 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM._copy_plans | def _copy_plans(self, branch_from, turn_from, tick_from):
"""Collect all plans that are active at the given time and copy them to the current branch"""
plan_ticks = self._plan_ticks
plan_ticks_uncommitted = self._plan_ticks_uncommitted
time_plan = self._time_plan
plans = self._plans
branch = self.branch
where_cached = self._where_cached
last_plan = self._last_plan
turn_end_plan = self._turn_end_plan
for plan_id in self._branches_plans[branch_from]:
_, start_turn, start_tick = plans[plan_id]
if start_turn > turn_from or (start_turn == turn_from and start_tick > tick_from):
continue
incremented = False
for turn, ticks in list(plan_ticks[plan_id].items()):
if turn < turn_from:
continue
for tick in ticks:
if turn == turn_from and tick < tick_from:
continue
if not incremented:
self._last_plan = last_plan = last_plan + 1
incremented = True
plans[last_plan] = branch, turn, tick
for cache in where_cached[branch_from, turn, tick]:
data = cache.settings[branch_from][turn][tick]
value = data[-1]
key = data[:-1]
args = key + (branch, turn, tick, value)
if hasattr(cache, 'setdb'):
cache.setdb(*args)
cache.store(*args, planning=True)
plan_ticks[last_plan][turn].append(tick)
plan_ticks_uncommitted.append((last_plan, turn, tick))
time_plan[branch, turn, tick] = last_plan
turn_end_plan[branch, turn] = tick | python | def _copy_plans(self, branch_from, turn_from, tick_from):
"""Collect all plans that are active at the given time and copy them to the current branch"""
plan_ticks = self._plan_ticks
plan_ticks_uncommitted = self._plan_ticks_uncommitted
time_plan = self._time_plan
plans = self._plans
branch = self.branch
where_cached = self._where_cached
last_plan = self._last_plan
turn_end_plan = self._turn_end_plan
for plan_id in self._branches_plans[branch_from]:
_, start_turn, start_tick = plans[plan_id]
if start_turn > turn_from or (start_turn == turn_from and start_tick > tick_from):
continue
incremented = False
for turn, ticks in list(plan_ticks[plan_id].items()):
if turn < turn_from:
continue
for tick in ticks:
if turn == turn_from and tick < tick_from:
continue
if not incremented:
self._last_plan = last_plan = last_plan + 1
incremented = True
plans[last_plan] = branch, turn, tick
for cache in where_cached[branch_from, turn, tick]:
data = cache.settings[branch_from][turn][tick]
value = data[-1]
key = data[:-1]
args = key + (branch, turn, tick, value)
if hasattr(cache, 'setdb'):
cache.setdb(*args)
cache.store(*args, planning=True)
plan_ticks[last_plan][turn].append(tick)
plan_ticks_uncommitted.append((last_plan, turn, tick))
time_plan[branch, turn, tick] = last_plan
turn_end_plan[branch, turn] = tick | [
"def",
"_copy_plans",
"(",
"self",
",",
"branch_from",
",",
"turn_from",
",",
"tick_from",
")",
":",
"plan_ticks",
"=",
"self",
".",
"_plan_ticks",
"plan_ticks_uncommitted",
"=",
"self",
".",
"_plan_ticks_uncommitted",
"time_plan",
"=",
"self",
".",
"_time_plan",
... | Collect all plans that are active at the given time and copy them to the current branch | [
"Collect",
"all",
"plans",
"that",
"are",
"active",
"at",
"the",
"given",
"time",
"and",
"copy",
"them",
"to",
"the",
"current",
"branch"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L710-L746 | train | 32,783 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.delete_plan | def delete_plan(self, plan):
"""Delete the portion of a plan that has yet to occur.
:arg plan: integer ID of a plan, as given by ``with self.plan() as plan:``
"""
branch, turn, tick = self._btt()
to_delete = []
plan_ticks = self._plan_ticks[plan]
for trn, tcks in plan_ticks.items(): # might improve performance to use a WindowDict for plan_ticks
if turn == trn:
for tck in tcks:
if tck >= tick:
to_delete.append((trn, tck))
elif trn > turn:
to_delete.extend((trn, tck) for tck in tcks)
# Delete stuff that happened at contradicted times, and then delete the times from the plan
where_cached = self._where_cached
time_plan = self._time_plan
for trn, tck in to_delete:
for cache in where_cached[branch, trn, tck]:
cache.remove(branch, trn, tck)
if hasattr(cache, 'deldb'):
cache.deldb(branch, trn, tck)
del where_cached[branch, trn, tck]
plan_ticks[trn].remove(tck)
if not plan_ticks[trn]:
del plan_ticks[trn]
del time_plan[branch, trn, tck] | python | def delete_plan(self, plan):
"""Delete the portion of a plan that has yet to occur.
:arg plan: integer ID of a plan, as given by ``with self.plan() as plan:``
"""
branch, turn, tick = self._btt()
to_delete = []
plan_ticks = self._plan_ticks[plan]
for trn, tcks in plan_ticks.items(): # might improve performance to use a WindowDict for plan_ticks
if turn == trn:
for tck in tcks:
if tck >= tick:
to_delete.append((trn, tck))
elif trn > turn:
to_delete.extend((trn, tck) for tck in tcks)
# Delete stuff that happened at contradicted times, and then delete the times from the plan
where_cached = self._where_cached
time_plan = self._time_plan
for trn, tck in to_delete:
for cache in where_cached[branch, trn, tck]:
cache.remove(branch, trn, tck)
if hasattr(cache, 'deldb'):
cache.deldb(branch, trn, tck)
del where_cached[branch, trn, tck]
plan_ticks[trn].remove(tck)
if not plan_ticks[trn]:
del plan_ticks[trn]
del time_plan[branch, trn, tck] | [
"def",
"delete_plan",
"(",
"self",
",",
"plan",
")",
":",
"branch",
",",
"turn",
",",
"tick",
"=",
"self",
".",
"_btt",
"(",
")",
"to_delete",
"=",
"[",
"]",
"plan_ticks",
"=",
"self",
".",
"_plan_ticks",
"[",
"plan",
"]",
"for",
"trn",
",",
"tcks"... | Delete the portion of a plan that has yet to occur.
:arg plan: integer ID of a plan, as given by ``with self.plan() as plan:`` | [
"Delete",
"the",
"portion",
"of",
"a",
"plan",
"that",
"has",
"yet",
"to",
"occur",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L748-L776 | train | 32,784 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM._nbtt | def _nbtt(self):
"""Increment the tick and return branch, turn, tick
Unless we're viewing the past, in which case raise HistoryError.
Idea is you use this when you want to advance time, which you
can only do once per branch, turn, tick.
"""
from .cache import HistoryError
branch, turn, tick = self._btt()
tick += 1
if (branch, turn) in self._turn_end_plan:
if tick > self._turn_end_plan[branch, turn]:
self._turn_end_plan[branch, turn] = tick
else:
tick = self._turn_end_plan[branch, turn] + 1
self._turn_end_plan[branch, turn] = tick
if self._turn_end[branch, turn] > tick:
raise HistoryError(
"You're not at the end of turn {}. Go to tick {} to change things".format(
turn, self._turn_end[branch, turn]
)
)
parent, turn_start, tick_start, turn_end, tick_end = self._branches[branch]
if turn < turn_end or (
turn == turn_end and tick < tick_end
):
raise HistoryError(
"You're in the past. Go to turn {}, tick {} to change things".format(turn_end, tick_end)
)
if self._planning:
if (turn, tick) in self._plan_ticks[self._last_plan]:
raise HistoryError(
"Trying to make a plan at {}, but that time already happened".format((branch, turn, tick))
)
self._plan_ticks[self._last_plan][turn].append(tick)
self._plan_ticks_uncommitted.append((self._last_plan, turn, tick))
self._time_plan[branch, turn, tick] = self._last_plan
self._otick = tick
return branch, turn, tick | python | def _nbtt(self):
"""Increment the tick and return branch, turn, tick
Unless we're viewing the past, in which case raise HistoryError.
Idea is you use this when you want to advance time, which you
can only do once per branch, turn, tick.
"""
from .cache import HistoryError
branch, turn, tick = self._btt()
tick += 1
if (branch, turn) in self._turn_end_plan:
if tick > self._turn_end_plan[branch, turn]:
self._turn_end_plan[branch, turn] = tick
else:
tick = self._turn_end_plan[branch, turn] + 1
self._turn_end_plan[branch, turn] = tick
if self._turn_end[branch, turn] > tick:
raise HistoryError(
"You're not at the end of turn {}. Go to tick {} to change things".format(
turn, self._turn_end[branch, turn]
)
)
parent, turn_start, tick_start, turn_end, tick_end = self._branches[branch]
if turn < turn_end or (
turn == turn_end and tick < tick_end
):
raise HistoryError(
"You're in the past. Go to turn {}, tick {} to change things".format(turn_end, tick_end)
)
if self._planning:
if (turn, tick) in self._plan_ticks[self._last_plan]:
raise HistoryError(
"Trying to make a plan at {}, but that time already happened".format((branch, turn, tick))
)
self._plan_ticks[self._last_plan][turn].append(tick)
self._plan_ticks_uncommitted.append((self._last_plan, turn, tick))
self._time_plan[branch, turn, tick] = self._last_plan
self._otick = tick
return branch, turn, tick | [
"def",
"_nbtt",
"(",
"self",
")",
":",
"from",
".",
"cache",
"import",
"HistoryError",
"branch",
",",
"turn",
",",
"tick",
"=",
"self",
".",
"_btt",
"(",
")",
"tick",
"+=",
"1",
"if",
"(",
"branch",
",",
"turn",
")",
"in",
"self",
".",
"_turn_end_p... | Increment the tick and return branch, turn, tick
Unless we're viewing the past, in which case raise HistoryError.
Idea is you use this when you want to advance time, which you
can only do once per branch, turn, tick. | [
"Increment",
"the",
"tick",
"and",
"return",
"branch",
"turn",
"tick"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L855-L895 | train | 32,785 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.commit | def commit(self):
"""Write the state of all graphs to the database and commit the transaction.
Also saves the current branch, turn, and tick.
"""
self.query.globl['branch'] = self._obranch
self.query.globl['turn'] = self._oturn
self.query.globl['tick'] = self._otick
set_branch = self.query.set_branch
for branch, (parent, turn_start, tick_start, turn_end, tick_end) in self._branches.items():
set_branch(branch, parent, turn_start, tick_start, turn_end, tick_end)
turn_end = self._turn_end
set_turn = self.query.set_turn
for (branch, turn), plan_end_tick in self._turn_end_plan.items():
set_turn(branch, turn, turn_end[branch], plan_end_tick)
if self._plans_uncommitted:
self.query.plans_insert_many(self._plans_uncommitted)
if self._plan_ticks_uncommitted:
self.query.plan_ticks_insert_many(self._plan_ticks_uncommitted)
self.query.commit()
self._plans_uncommitted = []
self._plan_ticks_uncommitted = [] | python | def commit(self):
"""Write the state of all graphs to the database and commit the transaction.
Also saves the current branch, turn, and tick.
"""
self.query.globl['branch'] = self._obranch
self.query.globl['turn'] = self._oturn
self.query.globl['tick'] = self._otick
set_branch = self.query.set_branch
for branch, (parent, turn_start, tick_start, turn_end, tick_end) in self._branches.items():
set_branch(branch, parent, turn_start, tick_start, turn_end, tick_end)
turn_end = self._turn_end
set_turn = self.query.set_turn
for (branch, turn), plan_end_tick in self._turn_end_plan.items():
set_turn(branch, turn, turn_end[branch], plan_end_tick)
if self._plans_uncommitted:
self.query.plans_insert_many(self._plans_uncommitted)
if self._plan_ticks_uncommitted:
self.query.plan_ticks_insert_many(self._plan_ticks_uncommitted)
self.query.commit()
self._plans_uncommitted = []
self._plan_ticks_uncommitted = [] | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"query",
".",
"globl",
"[",
"'branch'",
"]",
"=",
"self",
".",
"_obranch",
"self",
".",
"query",
".",
"globl",
"[",
"'turn'",
"]",
"=",
"self",
".",
"_oturn",
"self",
".",
"query",
".",
"globl",
... | Write the state of all graphs to the database and commit the transaction.
Also saves the current branch, turn, and tick. | [
"Write",
"the",
"state",
"of",
"all",
"graphs",
"to",
"the",
"database",
"and",
"commit",
"the",
"transaction",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L897-L919 | train | 32,786 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.new_graph | def new_graph(self, name, data=None, **attr):
"""Return a new instance of type Graph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'Graph')
g = Graph(self, name, data, **attr)
self._graph_objs[name] = g
return g | python | def new_graph(self, name, data=None, **attr):
"""Return a new instance of type Graph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'Graph')
g = Graph(self, name, data, **attr)
self._graph_objs[name] = g
return g | [
"def",
"new_graph",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"self",
".",
"_init_graph",
"(",
"name",
",",
"'Graph'",
")",
"g",
"=",
"Graph",
"(",
"self",
",",
"name",
",",
"data",
",",
"*",
"*",
"att... | Return a new instance of type Graph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state | [
"Return",
"a",
"new",
"instance",
"of",
"type",
"Graph",
"initialized",
"with",
"the",
"given",
"data",
"if",
"provided",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L933-L944 | train | 32,787 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.new_digraph | def new_digraph(self, name, data=None, **attr):
"""Return a new instance of type DiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'DiGraph')
dg = DiGraph(self, name, data, **attr)
self._graph_objs[name] = dg
return dg | python | def new_digraph(self, name, data=None, **attr):
"""Return a new instance of type DiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'DiGraph')
dg = DiGraph(self, name, data, **attr)
self._graph_objs[name] = dg
return dg | [
"def",
"new_digraph",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"self",
".",
"_init_graph",
"(",
"name",
",",
"'DiGraph'",
")",
"dg",
"=",
"DiGraph",
"(",
"self",
",",
"name",
",",
"data",
",",
"*",
"*",... | Return a new instance of type DiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state | [
"Return",
"a",
"new",
"instance",
"of",
"type",
"DiGraph",
"initialized",
"with",
"the",
"given",
"data",
"if",
"provided",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L946-L957 | train | 32,788 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.new_multigraph | def new_multigraph(self, name, data=None, **attr):
"""Return a new instance of type MultiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'MultiGraph')
mg = MultiGraph(self, name, data, **attr)
self._graph_objs[name] = mg
return mg | python | def new_multigraph(self, name, data=None, **attr):
"""Return a new instance of type MultiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'MultiGraph')
mg = MultiGraph(self, name, data, **attr)
self._graph_objs[name] = mg
return mg | [
"def",
"new_multigraph",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"self",
".",
"_init_graph",
"(",
"name",
",",
"'MultiGraph'",
")",
"mg",
"=",
"MultiGraph",
"(",
"self",
",",
"name",
",",
"data",
",",
"*... | Return a new instance of type MultiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state | [
"Return",
"a",
"new",
"instance",
"of",
"type",
"MultiGraph",
"initialized",
"with",
"the",
"given",
"data",
"if",
"provided",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L959-L970 | train | 32,789 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.new_multidigraph | def new_multidigraph(self, name, data=None, **attr):
"""Return a new instance of type MultiDiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'MultiDiGraph')
mdg = MultiDiGraph(self, name, data, **attr)
self._graph_objs[name] = mdg
return mdg | python | def new_multidigraph(self, name, data=None, **attr):
"""Return a new instance of type MultiDiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'MultiDiGraph')
mdg = MultiDiGraph(self, name, data, **attr)
self._graph_objs[name] = mdg
return mdg | [
"def",
"new_multidigraph",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"self",
".",
"_init_graph",
"(",
"name",
",",
"'MultiDiGraph'",
")",
"mdg",
"=",
"MultiDiGraph",
"(",
"self",
",",
"name",
",",
"data",
",... | Return a new instance of type MultiDiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state | [
"Return",
"a",
"new",
"instance",
"of",
"type",
"MultiDiGraph",
"initialized",
"with",
"the",
"given",
"data",
"if",
"provided",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L972-L983 | train | 32,790 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.get_graph | def get_graph(self, name):
"""Return a graph previously created with ``new_graph``,
``new_digraph``, ``new_multigraph``, or
``new_multidigraph``
:arg name: name of an existing graph
"""
if name in self._graph_objs:
return self._graph_objs[name]
graphtypes = {
'Graph': Graph,
'DiGraph': DiGraph,
'MultiGraph': MultiGraph,
'MultiDiGraph': MultiDiGraph
}
type_s = self.query.graph_type(name)
if type_s not in graphtypes:
raise GraphNameError(
"I don't know of a graph named {}".format(name)
)
g = graphtypes[type_s](self, name)
self._graph_objs[name] = g
return g | python | def get_graph(self, name):
"""Return a graph previously created with ``new_graph``,
``new_digraph``, ``new_multigraph``, or
``new_multidigraph``
:arg name: name of an existing graph
"""
if name in self._graph_objs:
return self._graph_objs[name]
graphtypes = {
'Graph': Graph,
'DiGraph': DiGraph,
'MultiGraph': MultiGraph,
'MultiDiGraph': MultiDiGraph
}
type_s = self.query.graph_type(name)
if type_s not in graphtypes:
raise GraphNameError(
"I don't know of a graph named {}".format(name)
)
g = graphtypes[type_s](self, name)
self._graph_objs[name] = g
return g | [
"def",
"get_graph",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_graph_objs",
":",
"return",
"self",
".",
"_graph_objs",
"[",
"name",
"]",
"graphtypes",
"=",
"{",
"'Graph'",
":",
"Graph",
",",
"'DiGraph'",
":",
"DiGraph",
",",... | Return a graph previously created with ``new_graph``,
``new_digraph``, ``new_multigraph``, or
``new_multidigraph``
:arg name: name of an existing graph | [
"Return",
"a",
"graph",
"previously",
"created",
"with",
"new_graph",
"new_digraph",
"new_multigraph",
"or",
"new_multidigraph"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L985-L1008 | train | 32,791 |
LogicalDash/LiSE | allegedb/allegedb/__init__.py | ORM.del_graph | def del_graph(self, name):
"""Remove all traces of a graph's existence from the database
:arg name: name of an existing graph
"""
# make sure the graph exists before deleting anything
self.get_graph(name)
self.query.del_graph(name)
if name in self._graph_objs:
del self._graph_objs[name] | python | def del_graph(self, name):
"""Remove all traces of a graph's existence from the database
:arg name: name of an existing graph
"""
# make sure the graph exists before deleting anything
self.get_graph(name)
self.query.del_graph(name)
if name in self._graph_objs:
del self._graph_objs[name] | [
"def",
"del_graph",
"(",
"self",
",",
"name",
")",
":",
"# make sure the graph exists before deleting anything",
"self",
".",
"get_graph",
"(",
"name",
")",
"self",
".",
"query",
".",
"del_graph",
"(",
"name",
")",
"if",
"name",
"in",
"self",
".",
"_graph_objs... | Remove all traces of a graph's existence from the database
:arg name: name of an existing graph | [
"Remove",
"all",
"traces",
"of",
"a",
"graph",
"s",
"existence",
"from",
"the",
"database"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L1010-L1020 | train | 32,792 |
niemasd/TreeSwift | treeswift/Tree.py | read_tree_dendropy | def read_tree_dendropy(tree):
'''Create a TreeSwift tree from a DendroPy tree
Args:
``tree`` (``dendropy.datamodel.treemodel``): A Dendropy ``Tree`` object
Returns:
``Tree``: A TreeSwift tree created from ``tree``
'''
out = Tree(); d2t = dict()
if not hasattr(tree, 'preorder_node_iter') or not hasattr(tree, 'seed_node') or not hasattr(tree, 'is_rooted'):
raise TypeError("tree must be a DendroPy Tree object")
if tree.is_rooted != True:
out.is_rooted = False
for node in tree.preorder_node_iter():
if node == tree.seed_node:
curr = out.root
else:
curr = Node(); d2t[node.parent_node].add_child(curr)
d2t[node] = curr; curr.edge_length = node.edge_length
if hasattr(node, 'taxon') and node.taxon is not None:
curr.label = node.taxon.label
else:
curr.label = node.label
return out | python | def read_tree_dendropy(tree):
'''Create a TreeSwift tree from a DendroPy tree
Args:
``tree`` (``dendropy.datamodel.treemodel``): A Dendropy ``Tree`` object
Returns:
``Tree``: A TreeSwift tree created from ``tree``
'''
out = Tree(); d2t = dict()
if not hasattr(tree, 'preorder_node_iter') or not hasattr(tree, 'seed_node') or not hasattr(tree, 'is_rooted'):
raise TypeError("tree must be a DendroPy Tree object")
if tree.is_rooted != True:
out.is_rooted = False
for node in tree.preorder_node_iter():
if node == tree.seed_node:
curr = out.root
else:
curr = Node(); d2t[node.parent_node].add_child(curr)
d2t[node] = curr; curr.edge_length = node.edge_length
if hasattr(node, 'taxon') and node.taxon is not None:
curr.label = node.taxon.label
else:
curr.label = node.label
return out | [
"def",
"read_tree_dendropy",
"(",
"tree",
")",
":",
"out",
"=",
"Tree",
"(",
")",
"d2t",
"=",
"dict",
"(",
")",
"if",
"not",
"hasattr",
"(",
"tree",
",",
"'preorder_node_iter'",
")",
"or",
"not",
"hasattr",
"(",
"tree",
",",
"'seed_node'",
")",
"or",
... | Create a TreeSwift tree from a DendroPy tree
Args:
``tree`` (``dendropy.datamodel.treemodel``): A Dendropy ``Tree`` object
Returns:
``Tree``: A TreeSwift tree created from ``tree`` | [
"Create",
"a",
"TreeSwift",
"tree",
"from",
"a",
"DendroPy",
"tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1199-L1223 | train | 32,793 |
niemasd/TreeSwift | treeswift/Tree.py | read_tree_newick | def read_tree_newick(newick):
'''Read a tree from a Newick string or file
Args:
``newick`` (``str``): Either a Newick string or the path to a Newick file (plain-text or gzipped)
Returns:
``Tree``: The tree represented by ``newick``. If the Newick file has multiple trees (one per line), a ``list`` of ``Tree`` objects will be returned
'''
if not isinstance(newick, str):
try:
newick = str(newick)
except:
raise TypeError("newick must be a str")
if newick.lower().endswith('.gz'): # gzipped file
f = gopen(expanduser(newick)); ts = f.read().decode().strip(); f.close()
elif isfile(expanduser(newick)): # plain-text file
f = open(expanduser(newick)); ts = f.read().strip(); f.close()
else:
ts = newick.strip()
lines = ts.splitlines()
if len(lines) != 1:
return [read_tree_newick(l) for l in lines]
try:
t = Tree(); t.is_rooted = ts.startswith('[&R]')
if ts[0] == '[':
ts = ']'.join(ts.split(']')[1:]).strip(); ts = ts.replace(', ',',')
n = t.root; i = 0
while i < len(ts):
if ts[i] == ';':
if i != len(ts)-1 or n != t.root:
raise RuntimeError(INVALID_NEWICK)
elif ts[i] == '(':
c = Node(); n.add_child(c); n = c
elif ts[i] == ')':
n = n.parent
elif ts[i] == ',':
n = n.parent; c = Node(); n.add_child(c); n = c
elif ts[i] == ':':
i += 1; ls = ''
while ts[i] != ',' and ts[i] != ')' and ts[i] != ';':
ls += ts[i]; i += 1
n.edge_length = float(ls); i -= 1
else:
label = ''
while ts[i] != ':' and ts[i] != ',' and ts[i] != ';' and ts[i] != ')':
label += ts[i]; i += 1
i -= 1; n.label = label
i += 1
except Exception as e:
raise RuntimeError("Failed to parse string as Newick: %s"%ts)
return t | python | def read_tree_newick(newick):
'''Read a tree from a Newick string or file
Args:
``newick`` (``str``): Either a Newick string or the path to a Newick file (plain-text or gzipped)
Returns:
``Tree``: The tree represented by ``newick``. If the Newick file has multiple trees (one per line), a ``list`` of ``Tree`` objects will be returned
'''
if not isinstance(newick, str):
try:
newick = str(newick)
except:
raise TypeError("newick must be a str")
if newick.lower().endswith('.gz'): # gzipped file
f = gopen(expanduser(newick)); ts = f.read().decode().strip(); f.close()
elif isfile(expanduser(newick)): # plain-text file
f = open(expanduser(newick)); ts = f.read().strip(); f.close()
else:
ts = newick.strip()
lines = ts.splitlines()
if len(lines) != 1:
return [read_tree_newick(l) for l in lines]
try:
t = Tree(); t.is_rooted = ts.startswith('[&R]')
if ts[0] == '[':
ts = ']'.join(ts.split(']')[1:]).strip(); ts = ts.replace(', ',',')
n = t.root; i = 0
while i < len(ts):
if ts[i] == ';':
if i != len(ts)-1 or n != t.root:
raise RuntimeError(INVALID_NEWICK)
elif ts[i] == '(':
c = Node(); n.add_child(c); n = c
elif ts[i] == ')':
n = n.parent
elif ts[i] == ',':
n = n.parent; c = Node(); n.add_child(c); n = c
elif ts[i] == ':':
i += 1; ls = ''
while ts[i] != ',' and ts[i] != ')' and ts[i] != ';':
ls += ts[i]; i += 1
n.edge_length = float(ls); i -= 1
else:
label = ''
while ts[i] != ':' and ts[i] != ',' and ts[i] != ';' and ts[i] != ')':
label += ts[i]; i += 1
i -= 1; n.label = label
i += 1
except Exception as e:
raise RuntimeError("Failed to parse string as Newick: %s"%ts)
return t | [
"def",
"read_tree_newick",
"(",
"newick",
")",
":",
"if",
"not",
"isinstance",
"(",
"newick",
",",
"str",
")",
":",
"try",
":",
"newick",
"=",
"str",
"(",
"newick",
")",
"except",
":",
"raise",
"TypeError",
"(",
"\"newick must be a str\"",
")",
"if",
"ne... | Read a tree from a Newick string or file
Args:
``newick`` (``str``): Either a Newick string or the path to a Newick file (plain-text or gzipped)
Returns:
``Tree``: The tree represented by ``newick``. If the Newick file has multiple trees (one per line), a ``list`` of ``Tree`` objects will be returned | [
"Read",
"a",
"tree",
"from",
"a",
"Newick",
"string",
"or",
"file"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1225-L1276 | train | 32,794 |
niemasd/TreeSwift | treeswift/Tree.py | read_tree_nexus | def read_tree_nexus(nexus):
'''Read a tree from a Nexus string or file
Args:
``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped)
Returns:
``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``) and values are ``Tree`` objects
'''
if not isinstance(nexus, str):
raise TypeError("nexus must be a str")
if nexus.lower().endswith('.gz'): # gzipped file
f = gopen(expanduser(nexus))
elif isfile(expanduser(nexus)): # plain-text file
f = open(expanduser(nexus))
else:
f = nexus.splitlines()
trees = dict()
for line in f:
if isinstance(line,bytes):
l = line.decode().strip()
else:
l = line.strip()
if l.lower().startswith('tree '):
i = l.index('='); left = l[:i].strip(); right = l[i+1:].strip()
name = ' '.join(left.split(' ')[1:])
trees[name] = read_tree_newick(right)
if hasattr(f,'close'):
f.close()
return trees | python | def read_tree_nexus(nexus):
'''Read a tree from a Nexus string or file
Args:
``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped)
Returns:
``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``) and values are ``Tree`` objects
'''
if not isinstance(nexus, str):
raise TypeError("nexus must be a str")
if nexus.lower().endswith('.gz'): # gzipped file
f = gopen(expanduser(nexus))
elif isfile(expanduser(nexus)): # plain-text file
f = open(expanduser(nexus))
else:
f = nexus.splitlines()
trees = dict()
for line in f:
if isinstance(line,bytes):
l = line.decode().strip()
else:
l = line.strip()
if l.lower().startswith('tree '):
i = l.index('='); left = l[:i].strip(); right = l[i+1:].strip()
name = ' '.join(left.split(' ')[1:])
trees[name] = read_tree_newick(right)
if hasattr(f,'close'):
f.close()
return trees | [
"def",
"read_tree_nexus",
"(",
"nexus",
")",
":",
"if",
"not",
"isinstance",
"(",
"nexus",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"nexus must be a str\"",
")",
"if",
"nexus",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.gz'",
")",
":",
... | Read a tree from a Nexus string or file
Args:
``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped)
Returns:
``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``) and values are ``Tree`` objects | [
"Read",
"a",
"tree",
"from",
"a",
"Nexus",
"string",
"or",
"file"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1395-L1424 | train | 32,795 |
niemasd/TreeSwift | treeswift/Tree.py | read_tree | def read_tree(input, schema):
'''Read a tree from a string or file
Args:
``input`` (``str``): Either a tree string, a path to a tree file (plain-text or gzipped), or a DendroPy Tree object
``schema`` (``str``): The schema of ``input`` (DendroPy, Newick, NeXML, or Nexus)
Returns:
* If the input is Newick, either a ``Tree`` object if ``input`` contains a single tree, or a ``list`` of ``Tree`` objects if ``input`` contains multiple trees (one per line)
* If the input is NeXML or Nexus, a ``dict`` of trees represented by ``input``, where keys are tree names (``str``) and values are ``Tree`` objects
'''
schema_to_function = {
'dendropy': read_tree_dendropy,
'newick': read_tree_newick,
'nexml': read_tree_nexml,
'nexus': read_tree_nexus
}
if schema.lower() not in schema_to_function:
raise ValueError("Invalid schema: %s (valid options: %s)" % (schema, ', '.join(sorted(schema_to_function.keys()))))
return schema_to_function[schema.lower()](input) | python | def read_tree(input, schema):
'''Read a tree from a string or file
Args:
``input`` (``str``): Either a tree string, a path to a tree file (plain-text or gzipped), or a DendroPy Tree object
``schema`` (``str``): The schema of ``input`` (DendroPy, Newick, NeXML, or Nexus)
Returns:
* If the input is Newick, either a ``Tree`` object if ``input`` contains a single tree, or a ``list`` of ``Tree`` objects if ``input`` contains multiple trees (one per line)
* If the input is NeXML or Nexus, a ``dict`` of trees represented by ``input``, where keys are tree names (``str``) and values are ``Tree`` objects
'''
schema_to_function = {
'dendropy': read_tree_dendropy,
'newick': read_tree_newick,
'nexml': read_tree_nexml,
'nexus': read_tree_nexus
}
if schema.lower() not in schema_to_function:
raise ValueError("Invalid schema: %s (valid options: %s)" % (schema, ', '.join(sorted(schema_to_function.keys()))))
return schema_to_function[schema.lower()](input) | [
"def",
"read_tree",
"(",
"input",
",",
"schema",
")",
":",
"schema_to_function",
"=",
"{",
"'dendropy'",
":",
"read_tree_dendropy",
",",
"'newick'",
":",
"read_tree_newick",
",",
"'nexml'",
":",
"read_tree_nexml",
",",
"'nexus'",
":",
"read_tree_nexus",
"}",
"if... | Read a tree from a string or file
Args:
``input`` (``str``): Either a tree string, a path to a tree file (plain-text or gzipped), or a DendroPy Tree object
``schema`` (``str``): The schema of ``input`` (DendroPy, Newick, NeXML, or Nexus)
Returns:
* If the input is Newick, either a ``Tree`` object if ``input`` contains a single tree, or a ``list`` of ``Tree`` objects if ``input`` contains multiple trees (one per line)
* If the input is NeXML or Nexus, a ``dict`` of trees represented by ``input``, where keys are tree names (``str``) and values are ``Tree`` objects | [
"Read",
"a",
"tree",
"from",
"a",
"string",
"or",
"file"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1426-L1447 | train | 32,796 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.avg_branch_length | def avg_branch_length(self, terminal=True, internal=True):
'''Compute the average length of the selected branches of this ``Tree``. Edges with length ``None`` will be treated as 0-length
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
Returns:
The average length of the selected branches
'''
if not isinstance(terminal, bool):
raise TypeError("terminal must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
if not internal and not terminal:
raise RuntimeError("Must select either internal or terminal branches (or both)")
tot = 0.; num = 0
for node in self.traverse_preorder():
if node.edge_length is not None and (internal and not node.is_leaf()) or (terminal and node.is_leaf()):
tot += node.edge_length; num += 1
return tot/num | python | def avg_branch_length(self, terminal=True, internal=True):
'''Compute the average length of the selected branches of this ``Tree``. Edges with length ``None`` will be treated as 0-length
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
Returns:
The average length of the selected branches
'''
if not isinstance(terminal, bool):
raise TypeError("terminal must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
if not internal and not terminal:
raise RuntimeError("Must select either internal or terminal branches (or both)")
tot = 0.; num = 0
for node in self.traverse_preorder():
if node.edge_length is not None and (internal and not node.is_leaf()) or (terminal and node.is_leaf()):
tot += node.edge_length; num += 1
return tot/num | [
"def",
"avg_branch_length",
"(",
"self",
",",
"terminal",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"terminal",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"terminal must be a bool\"",
")",
"if",
"not",
"i... | Compute the average length of the selected branches of this ``Tree``. Edges with length ``None`` will be treated as 0-length
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
Returns:
The average length of the selected branches | [
"Compute",
"the",
"average",
"length",
"of",
"the",
"selected",
"branches",
"of",
"this",
"Tree",
".",
"Edges",
"with",
"length",
"None",
"will",
"be",
"treated",
"as",
"0",
"-",
"length"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L40-L61 | train | 32,797 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.branch_lengths | def branch_lengths(self, terminal=True, internal=True):
'''Generator over the lengths of the selected branches of this ``Tree``. Edges with length ``None`` will be output as 0-length
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
'''
if not isinstance(terminal, bool):
raise TypeError("terminal must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
for node in self.traverse_preorder():
if (internal and not node.is_leaf()) or (terminal and node.is_leaf()):
if node.edge_length is None:
yield 0
else:
yield node.edge_length | python | def branch_lengths(self, terminal=True, internal=True):
'''Generator over the lengths of the selected branches of this ``Tree``. Edges with length ``None`` will be output as 0-length
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
'''
if not isinstance(terminal, bool):
raise TypeError("terminal must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
for node in self.traverse_preorder():
if (internal and not node.is_leaf()) or (terminal and node.is_leaf()):
if node.edge_length is None:
yield 0
else:
yield node.edge_length | [
"def",
"branch_lengths",
"(",
"self",
",",
"terminal",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"terminal",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"terminal must be a bool\"",
")",
"if",
"not",
"isin... | Generator over the lengths of the selected branches of this ``Tree``. Edges with length ``None`` will be output as 0-length
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False`` | [
"Generator",
"over",
"the",
"lengths",
"of",
"the",
"selected",
"branches",
"of",
"this",
"Tree",
".",
"Edges",
"with",
"length",
"None",
"will",
"be",
"output",
"as",
"0",
"-",
"length"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L63-L80 | train | 32,798 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.closest_leaf_to_root | def closest_leaf_to_root(self):
'''Return the leaf that is closest to the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the closest leaf to the root, and second value is the corresponding distance
'''
best = (None,float('inf')); d = dict()
for node in self.traverse_preorder():
if node.edge_length is None:
d[node] = 0
else:
d[node] = node.edge_length
if not node.is_root():
d[node] += d[node.parent]
if node.is_leaf() and d[node] < best[1]:
best = (node,d[node])
return best | python | def closest_leaf_to_root(self):
'''Return the leaf that is closest to the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the closest leaf to the root, and second value is the corresponding distance
'''
best = (None,float('inf')); d = dict()
for node in self.traverse_preorder():
if node.edge_length is None:
d[node] = 0
else:
d[node] = node.edge_length
if not node.is_root():
d[node] += d[node.parent]
if node.is_leaf() and d[node] < best[1]:
best = (node,d[node])
return best | [
"def",
"closest_leaf_to_root",
"(",
"self",
")",
":",
"best",
"=",
"(",
"None",
",",
"float",
"(",
"'inf'",
")",
")",
"d",
"=",
"dict",
"(",
")",
"for",
"node",
"in",
"self",
".",
"traverse_preorder",
"(",
")",
":",
"if",
"node",
".",
"edge_length",
... | Return the leaf that is closest to the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the closest leaf to the root, and second value is the corresponding distance | [
"Return",
"the",
"leaf",
"that",
"is",
"closest",
"to",
"the",
"root",
"and",
"the",
"corresponding",
"distance",
".",
"Edges",
"with",
"no",
"length",
"will",
"be",
"considered",
"to",
"have",
"a",
"length",
"of",
"0"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L82-L98 | train | 32,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.