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
TUT-ARG/sed_eval
sed_eval/sound_event.py
EventBasedMetrics.validate_offset
def validate_offset(reference_event, estimated_event, t_collar=0.200, percentage_of_length=0.5): """Validate estimated event based on event offset Parameters ---------- reference_event : dict Reference event. estimated_event : dict Estimated event. t_collar : float > 0, seconds First condition, Time collar with which the estimated offset has to be in order to be consider valid estimation. Default value 0.2 percentage_of_length : float in [0, 1] Second condition, percentage of the length within which the estimated offset has to be in order to be consider valid estimation. Default value 0.5 Returns ------- bool """ # Detect field naming style used and validate onset if 'event_offset' in reference_event and 'event_offset' in estimated_event: annotated_length = reference_event['event_offset'] - reference_event['event_onset'] return math.fabs(reference_event['event_offset'] - estimated_event['event_offset']) <= max(t_collar, percentage_of_length * annotated_length) elif 'offset' in reference_event and 'offset' in estimated_event: annotated_length = reference_event['offset'] - reference_event['onset'] return math.fabs(reference_event['offset'] - estimated_event['offset']) <= max(t_collar, percentage_of_length * annotated_length)
python
def validate_offset(reference_event, estimated_event, t_collar=0.200, percentage_of_length=0.5): """Validate estimated event based on event offset Parameters ---------- reference_event : dict Reference event. estimated_event : dict Estimated event. t_collar : float > 0, seconds First condition, Time collar with which the estimated offset has to be in order to be consider valid estimation. Default value 0.2 percentage_of_length : float in [0, 1] Second condition, percentage of the length within which the estimated offset has to be in order to be consider valid estimation. Default value 0.5 Returns ------- bool """ # Detect field naming style used and validate onset if 'event_offset' in reference_event and 'event_offset' in estimated_event: annotated_length = reference_event['event_offset'] - reference_event['event_onset'] return math.fabs(reference_event['event_offset'] - estimated_event['event_offset']) <= max(t_collar, percentage_of_length * annotated_length) elif 'offset' in reference_event and 'offset' in estimated_event: annotated_length = reference_event['offset'] - reference_event['onset'] return math.fabs(reference_event['offset'] - estimated_event['offset']) <= max(t_collar, percentage_of_length * annotated_length)
[ "def", "validate_offset", "(", "reference_event", ",", "estimated_event", ",", "t_collar", "=", "0.200", ",", "percentage_of_length", "=", "0.5", ")", ":", "# Detect field naming style used and validate onset", "if", "'event_offset'", "in", "reference_event", "and", "'eve...
Validate estimated event based on event offset Parameters ---------- reference_event : dict Reference event. estimated_event : dict Estimated event. t_collar : float > 0, seconds First condition, Time collar with which the estimated offset has to be in order to be consider valid estimation. Default value 0.2 percentage_of_length : float in [0, 1] Second condition, percentage of the length within which the estimated offset has to be in order to be consider valid estimation. Default value 0.5 Returns ------- bool
[ "Validate", "estimated", "event", "based", "on", "event", "offset" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/sound_event.py#L1633-L1668
train
35,200
TUT-ARG/sed_eval
sed_eval/io.py
load_event_list
def load_event_list(filename, **kwargs): """Load event list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [event onset (float >= 0)][delimiter][event offset (float >= 0)] - [event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][label] - [filename][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label] - [filename][delimiter][scene_label][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label] - [filename] Supported delimiters: ``,``, ``;``, ``tab`` Example of event list file:: 21.64715 23.00552 alert 36.91184 38.27021 alert 69.72575 71.09029 alert 63.53990 64.89827 alert 84.25553 84.83920 alert 20.92974 21.82661 clearthroat 28.39992 29.29679 clearthroat 80.47837 81.95937 clearthroat 44.48363 45.96463 clearthroat 78.13073 79.05953 clearthroat 15.17031 16.27235 cough 20.54931 21.65135 cough 27.79964 28.90168 cough 75.45959 76.32490 cough 70.81708 71.91912 cough 21.23203 22.55902 doorslam 7.546220 9.014880 doorslam 34.11303 35.04183 doorslam 45.86001 47.32867 doorslam Parameters ---------- filename : str Path to the csv-file Returns ------- list of dict Event list """ return dcase_util.containers.MetaDataContainer().load(filename=filename, **kwargs)
python
def load_event_list(filename, **kwargs): """Load event list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [event onset (float >= 0)][delimiter][event offset (float >= 0)] - [event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][label] - [filename][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label] - [filename][delimiter][scene_label][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label] - [filename] Supported delimiters: ``,``, ``;``, ``tab`` Example of event list file:: 21.64715 23.00552 alert 36.91184 38.27021 alert 69.72575 71.09029 alert 63.53990 64.89827 alert 84.25553 84.83920 alert 20.92974 21.82661 clearthroat 28.39992 29.29679 clearthroat 80.47837 81.95937 clearthroat 44.48363 45.96463 clearthroat 78.13073 79.05953 clearthroat 15.17031 16.27235 cough 20.54931 21.65135 cough 27.79964 28.90168 cough 75.45959 76.32490 cough 70.81708 71.91912 cough 21.23203 22.55902 doorslam 7.546220 9.014880 doorslam 34.11303 35.04183 doorslam 45.86001 47.32867 doorslam Parameters ---------- filename : str Path to the csv-file Returns ------- list of dict Event list """ return dcase_util.containers.MetaDataContainer().load(filename=filename, **kwargs)
[ "def", "load_event_list", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "return", "dcase_util", ".", "containers", ".", "MetaDataContainer", "(", ")", ".", "load", "(", "filename", "=", "filename", ",", "*", "*", "kwargs", ")" ]
Load event list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [event onset (float >= 0)][delimiter][event offset (float >= 0)] - [event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][label] - [filename][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label] - [filename][delimiter][scene_label][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label] - [filename] Supported delimiters: ``,``, ``;``, ``tab`` Example of event list file:: 21.64715 23.00552 alert 36.91184 38.27021 alert 69.72575 71.09029 alert 63.53990 64.89827 alert 84.25553 84.83920 alert 20.92974 21.82661 clearthroat 28.39992 29.29679 clearthroat 80.47837 81.95937 clearthroat 44.48363 45.96463 clearthroat 78.13073 79.05953 clearthroat 15.17031 16.27235 cough 20.54931 21.65135 cough 27.79964 28.90168 cough 75.45959 76.32490 cough 70.81708 71.91912 cough 21.23203 22.55902 doorslam 7.546220 9.014880 doorslam 34.11303 35.04183 doorslam 45.86001 47.32867 doorslam Parameters ---------- filename : str Path to the csv-file Returns ------- list of dict Event list
[ "Load", "event", "list", "from", "csv", "formatted", "text", "-", "file" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/io.py#L22-L70
train
35,201
TUT-ARG/sed_eval
sed_eval/io.py
load_scene_list
def load_scene_list(filename, **kwargs): """Load scene list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [filename][delimiter][scene label] - [filename][delimiter][segment start (float >= 0)][delimiter][segment stop (float >= 0)][delimiter][scene label] Supported delimiters: ``,``, ``;``, ``tab`` Example of scene list file:: scenes_stereo/supermarket09.wav supermarket scenes_stereo/tubestation10.wav tubestation scenes_stereo/quietstreet08.wav quietstreet scenes_stereo/restaurant05.wav restaurant scenes_stereo/busystreet05.wav busystreet scenes_stereo/openairmarket04.wav openairmarket scenes_stereo/quietstreet01.wav quietstreet scenes_stereo/supermarket05.wav supermarket scenes_stereo/openairmarket01.wav openairmarket Parameters ---------- filename : str Path to the csv-file Returns ------- list of dict Scene list """ return dcase_util.containers.MetaDataContainer().load(filename=filename, **kwargs)
python
def load_scene_list(filename, **kwargs): """Load scene list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [filename][delimiter][scene label] - [filename][delimiter][segment start (float >= 0)][delimiter][segment stop (float >= 0)][delimiter][scene label] Supported delimiters: ``,``, ``;``, ``tab`` Example of scene list file:: scenes_stereo/supermarket09.wav supermarket scenes_stereo/tubestation10.wav tubestation scenes_stereo/quietstreet08.wav quietstreet scenes_stereo/restaurant05.wav restaurant scenes_stereo/busystreet05.wav busystreet scenes_stereo/openairmarket04.wav openairmarket scenes_stereo/quietstreet01.wav quietstreet scenes_stereo/supermarket05.wav supermarket scenes_stereo/openairmarket01.wav openairmarket Parameters ---------- filename : str Path to the csv-file Returns ------- list of dict Scene list """ return dcase_util.containers.MetaDataContainer().load(filename=filename, **kwargs)
[ "def", "load_scene_list", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "return", "dcase_util", ".", "containers", ".", "MetaDataContainer", "(", ")", ".", "load", "(", "filename", "=", "filename", ",", "*", "*", "kwargs", ")" ]
Load scene list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [filename][delimiter][scene label] - [filename][delimiter][segment start (float >= 0)][delimiter][segment stop (float >= 0)][delimiter][scene label] Supported delimiters: ``,``, ``;``, ``tab`` Example of scene list file:: scenes_stereo/supermarket09.wav supermarket scenes_stereo/tubestation10.wav tubestation scenes_stereo/quietstreet08.wav quietstreet scenes_stereo/restaurant05.wav restaurant scenes_stereo/busystreet05.wav busystreet scenes_stereo/openairmarket04.wav openairmarket scenes_stereo/quietstreet01.wav quietstreet scenes_stereo/supermarket05.wav supermarket scenes_stereo/openairmarket01.wav openairmarket Parameters ---------- filename : str Path to the csv-file Returns ------- list of dict Scene list
[ "Load", "scene", "list", "from", "csv", "formatted", "text", "-", "file" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/io.py#L73-L107
train
35,202
TUT-ARG/sed_eval
sed_eval/io.py
load_file_pair_list
def load_file_pair_list(filename): """Load file pair list csv formatted text-file Format is [reference_file][delimiter][estimated_file] Supported delimiters: ``,``, ``;``, ``tab`` Example of file-list:: office_snr0_high_v2.txt office_snr0_high_v2_detected.txt office_snr0_med_v2.txt office_snr0_med_v2_detected.txt Parameters ---------- filename : str Path to the csv-file Returns ------- file_list: list File pair dicts in a list """ data = [] input_file = open(filename, 'rt') try: dialect = csv.Sniffer().sniff(input_file.readline(), [',', ';', '\t']) except csv.Error: raise ValueError('Unknown delimiter in file [{file}].'.format(file=filename)) input_file.seek(0) for row in csv.reader(input_file, dialect): if len(row) == 2: data.append( { 'reference_file': row[0], 'estimated_file': row[1] } ) else: raise ValueError('Unknown file pair list format in file [{file}].'.format(file=filename)) input_file.close() return data
python
def load_file_pair_list(filename): """Load file pair list csv formatted text-file Format is [reference_file][delimiter][estimated_file] Supported delimiters: ``,``, ``;``, ``tab`` Example of file-list:: office_snr0_high_v2.txt office_snr0_high_v2_detected.txt office_snr0_med_v2.txt office_snr0_med_v2_detected.txt Parameters ---------- filename : str Path to the csv-file Returns ------- file_list: list File pair dicts in a list """ data = [] input_file = open(filename, 'rt') try: dialect = csv.Sniffer().sniff(input_file.readline(), [',', ';', '\t']) except csv.Error: raise ValueError('Unknown delimiter in file [{file}].'.format(file=filename)) input_file.seek(0) for row in csv.reader(input_file, dialect): if len(row) == 2: data.append( { 'reference_file': row[0], 'estimated_file': row[1] } ) else: raise ValueError('Unknown file pair list format in file [{file}].'.format(file=filename)) input_file.close() return data
[ "def", "load_file_pair_list", "(", "filename", ")", ":", "data", "=", "[", "]", "input_file", "=", "open", "(", "filename", ",", "'rt'", ")", "try", ":", "dialect", "=", "csv", ".", "Sniffer", "(", ")", ".", "sniff", "(", "input_file", ".", "readline",...
Load file pair list csv formatted text-file Format is [reference_file][delimiter][estimated_file] Supported delimiters: ``,``, ``;``, ``tab`` Example of file-list:: office_snr0_high_v2.txt office_snr0_high_v2_detected.txt office_snr0_med_v2.txt office_snr0_med_v2_detected.txt Parameters ---------- filename : str Path to the csv-file Returns ------- file_list: list File pair dicts in a list
[ "Load", "file", "pair", "list", "csv", "formatted", "text", "-", "file" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/io.py#L110-L160
train
35,203
TUT-ARG/sed_eval
sed_eval/scene.py
SceneClassificationMetrics.class_wise_accuracy
def class_wise_accuracy(self, scene_label): """Class-wise accuracy Returns ------- dict results in a dictionary format """ if len(self.accuracies_per_class.shape) == 2: return { 'accuracy': float(numpy.mean(self.accuracies_per_class[:, self.scene_label_list.index(scene_label)])) } else: return { 'accuracy': float(numpy.mean(self.accuracies_per_class[self.scene_label_list.index(scene_label)])) }
python
def class_wise_accuracy(self, scene_label): """Class-wise accuracy Returns ------- dict results in a dictionary format """ if len(self.accuracies_per_class.shape) == 2: return { 'accuracy': float(numpy.mean(self.accuracies_per_class[:, self.scene_label_list.index(scene_label)])) } else: return { 'accuracy': float(numpy.mean(self.accuracies_per_class[self.scene_label_list.index(scene_label)])) }
[ "def", "class_wise_accuracy", "(", "self", ",", "scene_label", ")", ":", "if", "len", "(", "self", ".", "accuracies_per_class", ".", "shape", ")", "==", "2", ":", "return", "{", "'accuracy'", ":", "float", "(", "numpy", ".", "mean", "(", "self", ".", "...
Class-wise accuracy Returns ------- dict results in a dictionary format
[ "Class", "-", "wise", "accuracy" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/scene.py#L466-L484
train
35,204
TUT-ARG/sed_eval
sed_eval/util/scene_list.py
unique_scene_labels
def unique_scene_labels(scene_list): """Find the unique scene labels Parameters ---------- scene_list : list, shape=(n,) A list containing scene dicts Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ if isinstance(scene_list, dcase_util.containers.MetaDataContainer): return scene_list.unique_scene_labels else: labels = [] for item in scene_list: if 'scene_label' in item and item['scene_label'] not in labels: labels.append(item['scene_label']) labels.sort() return labels
python
def unique_scene_labels(scene_list): """Find the unique scene labels Parameters ---------- scene_list : list, shape=(n,) A list containing scene dicts Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ if isinstance(scene_list, dcase_util.containers.MetaDataContainer): return scene_list.unique_scene_labels else: labels = [] for item in scene_list: if 'scene_label' in item and item['scene_label'] not in labels: labels.append(item['scene_label']) labels.sort() return labels
[ "def", "unique_scene_labels", "(", "scene_list", ")", ":", "if", "isinstance", "(", "scene_list", ",", "dcase_util", ".", "containers", ".", "MetaDataContainer", ")", ":", "return", "scene_list", ".", "unique_scene_labels", "else", ":", "labels", "=", "[", "]", ...
Find the unique scene labels Parameters ---------- scene_list : list, shape=(n,) A list containing scene dicts Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order
[ "Find", "the", "unique", "scene", "labels" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/util/scene_list.py#L11-L35
train
35,205
TUT-ARG/sed_eval
sed_eval/util/event_roll.py
event_list_to_event_roll
def event_list_to_event_roll(source_event_list, event_label_list=None, time_resolution=0.01): """Convert event list into event roll, binary activity matrix Parameters ---------- source_event_list : list, shape=(n,) A list containing event dicts event_label_list : list, shape=(k,) or None A list of containing unique labels in alphabetical order (Default value = None) time_resolution : float > 0 Time resolution in seconds of the event roll (Default value = 0.01) Returns ------- event_roll: np.ndarray, shape=(m,k) Event roll """ if isinstance(source_event_list, dcase_util.containers.MetaDataContainer): max_offset_value = source_event_list.max_offset if event_label_list is None: event_label_list = source_event_list.unique_event_labels elif isinstance(source_event_list, list): max_offset_value = event_list.max_event_offset(source_event_list) if event_label_list is None: event_label_list = event_list.unique_event_labels(source_event_list) else: raise ValueError('Unknown source_event_list type.') # Initialize event roll event_roll = numpy.zeros((int(math.ceil(max_offset_value * 1 / time_resolution)), len(event_label_list))) # Fill-in event_roll for event in source_event_list: pos = event_label_list.index(event['event_label']) if 'event_onset' in event and 'event_offset' in event: event_onset = event['event_onset'] event_offset = event['event_offset'] elif 'onset' in event and 'offset' in event: event_onset = event['onset'] event_offset = event['offset'] onset = int(math.floor(event_onset * 1 / float(time_resolution))) offset = int(math.ceil(event_offset * 1 / float(time_resolution))) event_roll[onset:offset, pos] = 1 return event_roll
python
def event_list_to_event_roll(source_event_list, event_label_list=None, time_resolution=0.01): """Convert event list into event roll, binary activity matrix Parameters ---------- source_event_list : list, shape=(n,) A list containing event dicts event_label_list : list, shape=(k,) or None A list of containing unique labels in alphabetical order (Default value = None) time_resolution : float > 0 Time resolution in seconds of the event roll (Default value = 0.01) Returns ------- event_roll: np.ndarray, shape=(m,k) Event roll """ if isinstance(source_event_list, dcase_util.containers.MetaDataContainer): max_offset_value = source_event_list.max_offset if event_label_list is None: event_label_list = source_event_list.unique_event_labels elif isinstance(source_event_list, list): max_offset_value = event_list.max_event_offset(source_event_list) if event_label_list is None: event_label_list = event_list.unique_event_labels(source_event_list) else: raise ValueError('Unknown source_event_list type.') # Initialize event roll event_roll = numpy.zeros((int(math.ceil(max_offset_value * 1 / time_resolution)), len(event_label_list))) # Fill-in event_roll for event in source_event_list: pos = event_label_list.index(event['event_label']) if 'event_onset' in event and 'event_offset' in event: event_onset = event['event_onset'] event_offset = event['event_offset'] elif 'onset' in event and 'offset' in event: event_onset = event['onset'] event_offset = event['offset'] onset = int(math.floor(event_onset * 1 / float(time_resolution))) offset = int(math.ceil(event_offset * 1 / float(time_resolution))) event_roll[onset:offset, pos] = 1 return event_roll
[ "def", "event_list_to_event_roll", "(", "source_event_list", ",", "event_label_list", "=", "None", ",", "time_resolution", "=", "0.01", ")", ":", "if", "isinstance", "(", "source_event_list", ",", "dcase_util", ".", "containers", ".", "MetaDataContainer", ")", ":", ...
Convert event list into event roll, binary activity matrix Parameters ---------- source_event_list : list, shape=(n,) A list containing event dicts event_label_list : list, shape=(k,) or None A list of containing unique labels in alphabetical order (Default value = None) time_resolution : float > 0 Time resolution in seconds of the event roll (Default value = 0.01) Returns ------- event_roll: np.ndarray, shape=(m,k) Event roll
[ "Convert", "event", "list", "into", "event", "roll", "binary", "activity", "matrix" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/util/event_roll.py#L13-L71
train
35,206
TUT-ARG/sed_eval
sed_eval/util/event_roll.py
pad_event_roll
def pad_event_roll(event_roll, length): """Pad event roll's length to given length Parameters ---------- event_roll: np.ndarray, shape=(m,k) Event roll length : int Length to be padded Returns ------- event_roll: np.ndarray, shape=(m,k) Padded event roll """ if length > event_roll.shape[0]: padding = numpy.zeros((length-event_roll.shape[0], event_roll.shape[1])) event_roll = numpy.vstack((event_roll, padding)) return event_roll
python
def pad_event_roll(event_roll, length): """Pad event roll's length to given length Parameters ---------- event_roll: np.ndarray, shape=(m,k) Event roll length : int Length to be padded Returns ------- event_roll: np.ndarray, shape=(m,k) Padded event roll """ if length > event_roll.shape[0]: padding = numpy.zeros((length-event_roll.shape[0], event_roll.shape[1])) event_roll = numpy.vstack((event_roll, padding)) return event_roll
[ "def", "pad_event_roll", "(", "event_roll", ",", "length", ")", ":", "if", "length", ">", "event_roll", ".", "shape", "[", "0", "]", ":", "padding", "=", "numpy", ".", "zeros", "(", "(", "length", "-", "event_roll", ".", "shape", "[", "0", "]", ",", ...
Pad event roll's length to given length Parameters ---------- event_roll: np.ndarray, shape=(m,k) Event roll length : int Length to be padded Returns ------- event_roll: np.ndarray, shape=(m,k) Padded event roll
[ "Pad", "event", "roll", "s", "length", "to", "given", "length" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/util/event_roll.py#L74-L96
train
35,207
TUT-ARG/sed_eval
sed_eval/util/event_roll.py
match_event_roll_lengths
def match_event_roll_lengths(event_roll_a, event_roll_b, length=None): """Fix the length of two event rolls Parameters ---------- event_roll_a: np.ndarray, shape=(m1,k) Event roll A event_roll_b: np.ndarray, shape=(m2,k) Event roll B length: int, optional Length of the event roll, if none given, shorter event roll is padded to match longer one. Returns ------- event_roll_a: np.ndarray, shape=(max(m1,m2),k) Padded event roll A event_roll_b: np.ndarray, shape=(max(m1,m2),k) Padded event roll B """ # Fix durations of both event_rolls to be equal if length is None: length = max(event_roll_b.shape[0], event_roll_a.shape[0]) else: length = int(length) if length < event_roll_a.shape[0]: event_roll_a = event_roll_a[0:length, :] else: event_roll_a = pad_event_roll( event_roll=event_roll_a, length=length ) if length < event_roll_b.shape[0]: event_roll_b = event_roll_b[0:length, :] else: event_roll_b = pad_event_roll( event_roll=event_roll_b, length=length ) return event_roll_a, event_roll_b
python
def match_event_roll_lengths(event_roll_a, event_roll_b, length=None): """Fix the length of two event rolls Parameters ---------- event_roll_a: np.ndarray, shape=(m1,k) Event roll A event_roll_b: np.ndarray, shape=(m2,k) Event roll B length: int, optional Length of the event roll, if none given, shorter event roll is padded to match longer one. Returns ------- event_roll_a: np.ndarray, shape=(max(m1,m2),k) Padded event roll A event_roll_b: np.ndarray, shape=(max(m1,m2),k) Padded event roll B """ # Fix durations of both event_rolls to be equal if length is None: length = max(event_roll_b.shape[0], event_roll_a.shape[0]) else: length = int(length) if length < event_roll_a.shape[0]: event_roll_a = event_roll_a[0:length, :] else: event_roll_a = pad_event_roll( event_roll=event_roll_a, length=length ) if length < event_roll_b.shape[0]: event_roll_b = event_roll_b[0:length, :] else: event_roll_b = pad_event_roll( event_roll=event_roll_b, length=length ) return event_roll_a, event_roll_b
[ "def", "match_event_roll_lengths", "(", "event_roll_a", ",", "event_roll_b", ",", "length", "=", "None", ")", ":", "# Fix durations of both event_rolls to be equal", "if", "length", "is", "None", ":", "length", "=", "max", "(", "event_roll_b", ".", "shape", "[", "...
Fix the length of two event rolls Parameters ---------- event_roll_a: np.ndarray, shape=(m1,k) Event roll A event_roll_b: np.ndarray, shape=(m2,k) Event roll B length: int, optional Length of the event roll, if none given, shorter event roll is padded to match longer one. Returns ------- event_roll_a: np.ndarray, shape=(max(m1,m2),k) Padded event roll A event_roll_b: np.ndarray, shape=(max(m1,m2),k) Padded event roll B
[ "Fix", "the", "length", "of", "two", "event", "rolls" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/util/event_roll.py#L99-L148
train
35,208
TUT-ARG/sed_eval
sed_eval/util/event_list.py
filter_event_list
def filter_event_list(event_list, scene_label=None, event_label=None, filename=None): """Filter event list based on given fields Parameters ---------- event_list : list, shape=(n,) A list containing event dicts scene_label : str Scene label event_label : str Event label filename : str Filename Returns ------- event_list: list, shape=(n,) A list containing event dicts """ return dcase_util.containers.MetaDataContainer(event_list).filter( filename=filename, scene_label=scene_label, event_label=event_label )
python
def filter_event_list(event_list, scene_label=None, event_label=None, filename=None): """Filter event list based on given fields Parameters ---------- event_list : list, shape=(n,) A list containing event dicts scene_label : str Scene label event_label : str Event label filename : str Filename Returns ------- event_list: list, shape=(n,) A list containing event dicts """ return dcase_util.containers.MetaDataContainer(event_list).filter( filename=filename, scene_label=scene_label, event_label=event_label )
[ "def", "filter_event_list", "(", "event_list", ",", "scene_label", "=", "None", ",", "event_label", "=", "None", ",", "filename", "=", "None", ")", ":", "return", "dcase_util", ".", "containers", ".", "MetaDataContainer", "(", "event_list", ")", ".", "filter",...
Filter event list based on given fields Parameters ---------- event_list : list, shape=(n,) A list containing event dicts scene_label : str Scene label event_label : str Event label filename : str Filename Returns ------- event_list: list, shape=(n,) A list containing event dicts
[ "Filter", "event", "list", "based", "on", "given", "fields" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/util/event_list.py#L15-L43
train
35,209
TUT-ARG/sed_eval
sed_eval/util/event_list.py
unique_files
def unique_files(event_list): """Find the unique files Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique filenames in alphabetical order """ if isinstance(event_list, dcase_util.containers.MetaDataContainer): return event_list.unique_files else: files = {} for event in event_list: if 'file' in event: files[event['file']] = event['file'] elif 'filename' in event: files[event['filename']] = event['filename'] files = list(files.keys()) files.sort() return files
python
def unique_files(event_list): """Find the unique files Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique filenames in alphabetical order """ if isinstance(event_list, dcase_util.containers.MetaDataContainer): return event_list.unique_files else: files = {} for event in event_list: if 'file' in event: files[event['file']] = event['file'] elif 'filename' in event: files[event['filename']] = event['filename'] files = list(files.keys()) files.sort() return files
[ "def", "unique_files", "(", "event_list", ")", ":", "if", "isinstance", "(", "event_list", ",", "dcase_util", ".", "containers", ".", "MetaDataContainer", ")", ":", "return", "event_list", ".", "unique_files", "else", ":", "files", "=", "{", "}", "for", "eve...
Find the unique files Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique filenames in alphabetical order
[ "Find", "the", "unique", "files" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/util/event_list.py#L46-L75
train
35,210
TUT-ARG/sed_eval
sed_eval/util/event_list.py
unique_event_labels
def unique_event_labels(event_list): """Find the unique event labels Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique labels in alphabetical order """ if isinstance(event_list, dcase_util.containers.MetaDataContainer): return event_list.unique_event_labels else: labels = [] for event in event_list: if 'event_label' in event and event['event_label'] not in labels: labels.append(event['event_label']) labels.sort() return labels
python
def unique_event_labels(event_list): """Find the unique event labels Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique labels in alphabetical order """ if isinstance(event_list, dcase_util.containers.MetaDataContainer): return event_list.unique_event_labels else: labels = [] for event in event_list: if 'event_label' in event and event['event_label'] not in labels: labels.append(event['event_label']) labels.sort() return labels
[ "def", "unique_event_labels", "(", "event_list", ")", ":", "if", "isinstance", "(", "event_list", ",", "dcase_util", ".", "containers", ".", "MetaDataContainer", ")", ":", "return", "event_list", ".", "unique_event_labels", "else", ":", "labels", "=", "[", "]", ...
Find the unique event labels Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique labels in alphabetical order
[ "Find", "the", "unique", "event", "labels" ]
0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/util/event_list.py#L78-L103
train
35,211
rasguanabana/ytfs
ytfs/actions.py
YTActions.__getChannelId
def __getChannelId(self): """ Obtain channel id for channel name, if present in ``self.search_params``. """ if not self.search_params.get("channelId"): return api_fixed_url = "https://www.googleapis.com/youtube/v3/channels?part=id&maxResults=1&fields=items%2Fid&" url = api_fixed_url + urlencode({"key": self.api_key, "forUsername": self.search_params["channelId"]}) get = requests.get(url).json() try: self.search_params["channelId"] = get['items'][0]['id'] return # got it except IndexError: pass # try searching now... api_fixed_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel&fields=items%2Fid&" url = api_fixed_url + urlencode({"key": self.api_key, "q": self.search_params['channelId']}) get = requests.get(url).json() try: self.search_params["channelId"] = get['items'][0]['id']['channelId'] except IndexError: del self.search_params["channelId"]
python
def __getChannelId(self): """ Obtain channel id for channel name, if present in ``self.search_params``. """ if not self.search_params.get("channelId"): return api_fixed_url = "https://www.googleapis.com/youtube/v3/channels?part=id&maxResults=1&fields=items%2Fid&" url = api_fixed_url + urlencode({"key": self.api_key, "forUsername": self.search_params["channelId"]}) get = requests.get(url).json() try: self.search_params["channelId"] = get['items'][0]['id'] return # got it except IndexError: pass # try searching now... api_fixed_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel&fields=items%2Fid&" url = api_fixed_url + urlencode({"key": self.api_key, "q": self.search_params['channelId']}) get = requests.get(url).json() try: self.search_params["channelId"] = get['items'][0]['id']['channelId'] except IndexError: del self.search_params["channelId"]
[ "def", "__getChannelId", "(", "self", ")", ":", "if", "not", "self", ".", "search_params", ".", "get", "(", "\"channelId\"", ")", ":", "return", "api_fixed_url", "=", "\"https://www.googleapis.com/youtube/v3/channels?part=id&maxResults=1&fields=items%2Fid&\"", "url", "=",...
Obtain channel id for channel name, if present in ``self.search_params``.
[ "Obtain", "channel", "id", "for", "channel", "name", "if", "present", "in", "self", ".", "search_params", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/actions.py#L113-L141
train
35,212
rasguanabana/ytfs
ytfs/actions.py
YTActions.__searchParser
def __searchParser(self, query): """ Parse `query` for advanced search options. Parameters ---------- query : str Search query to parse. Besides a search query, user can specify additional search parameters and YTFS specific options. Syntax: Additional search parameters: ``option:value``. if `value` contains spaces, then surround it with parentheses; available parameters: `channel`, `max`, `before`, `after`, `order`. YTFS options: specify options between ``[`` and ``]``; Available options: `a`, `v`, `f`, `P`, `s`, `m`. If an option takes a parameter, then specify it beetween parentheses. Examples: ``channel:foo search query``, ``my favourite music [a]``, ``channel:(the famous funny cats channel) [vf(240)P] funny cats max:20``. Invalid parameters/options are ignored. Returns ------- params : tuple Tuple: 0 - dictionary of url GET parameters; 1 - dictionary of YTStor options. """ ret = dict() parse_params = True buf = "" ptr = "" p_avail = ("channel", "max", "before", "after", "order") opts = dict() par_open = False translate = { 'a': 'audio', 'v': 'video', 'f': 'format', 's': 'stream', 'P': 'stream', 'm': 'metadata', 'max': 'maxResults', 'channel': 'channelId', 'before': 'publishedBefore', 'after': 'publishedAfter', 'order': 'order', '': 'q' } for i in query+' ': if parse_params: if not par_open: if i == ' ': # flush buf try: if ret.get(translate[ptr]): ret[ translate[ptr] ] += ' ' else: ret[ translate[ptr] ] = '' ret[ translate[ptr] ] += buf except KeyError: pass ptr = "" buf = "" elif i == ':' and buf in p_avail: ptr = buf buf = "" elif not buf and i == '[': # buf must be empty parse_params = False ptr = "" elif i != '(': buf += i elif not (par_open == 1 and i == ')'): buf += i if i == '(': par_open += 1 if par_open > 0 and i == ')': par_open -= 1 else: if i == ']': parse_params = True par_open = False ptr = "" buf = "" elif ptr and not par_open and i == '(': par_open = True elif par_open: if i == ')': try: opts[ translate[ptr] ] = buf except KeyError: pass par_open = False buf = "" else: buf += i elif i.isalpha(): ptr = i try: opts[ translate[ptr] ] = not i.isupper() except KeyError: pass return (ret, opts)
python
def __searchParser(self, query): """ Parse `query` for advanced search options. Parameters ---------- query : str Search query to parse. Besides a search query, user can specify additional search parameters and YTFS specific options. Syntax: Additional search parameters: ``option:value``. if `value` contains spaces, then surround it with parentheses; available parameters: `channel`, `max`, `before`, `after`, `order`. YTFS options: specify options between ``[`` and ``]``; Available options: `a`, `v`, `f`, `P`, `s`, `m`. If an option takes a parameter, then specify it beetween parentheses. Examples: ``channel:foo search query``, ``my favourite music [a]``, ``channel:(the famous funny cats channel) [vf(240)P] funny cats max:20``. Invalid parameters/options are ignored. Returns ------- params : tuple Tuple: 0 - dictionary of url GET parameters; 1 - dictionary of YTStor options. """ ret = dict() parse_params = True buf = "" ptr = "" p_avail = ("channel", "max", "before", "after", "order") opts = dict() par_open = False translate = { 'a': 'audio', 'v': 'video', 'f': 'format', 's': 'stream', 'P': 'stream', 'm': 'metadata', 'max': 'maxResults', 'channel': 'channelId', 'before': 'publishedBefore', 'after': 'publishedAfter', 'order': 'order', '': 'q' } for i in query+' ': if parse_params: if not par_open: if i == ' ': # flush buf try: if ret.get(translate[ptr]): ret[ translate[ptr] ] += ' ' else: ret[ translate[ptr] ] = '' ret[ translate[ptr] ] += buf except KeyError: pass ptr = "" buf = "" elif i == ':' and buf in p_avail: ptr = buf buf = "" elif not buf and i == '[': # buf must be empty parse_params = False ptr = "" elif i != '(': buf += i elif not (par_open == 1 and i == ')'): buf += i if i == '(': par_open += 1 if par_open > 0 and i == ')': par_open -= 1 else: if i == ']': parse_params = True par_open = False ptr = "" buf = "" elif ptr and not par_open and i == '(': par_open = True elif par_open: if i == ')': try: opts[ translate[ptr] ] = buf except KeyError: pass par_open = False buf = "" else: buf += i elif i.isalpha(): ptr = i try: opts[ translate[ptr] ] = not i.isupper() except KeyError: pass return (ret, opts)
[ "def", "__searchParser", "(", "self", ",", "query", ")", ":", "ret", "=", "dict", "(", ")", "parse_params", "=", "True", "buf", "=", "\"\"", "ptr", "=", "\"\"", "p_avail", "=", "(", "\"channel\"", ",", "\"max\"", ",", "\"before\"", ",", "\"after\"", ",...
Parse `query` for advanced search options. Parameters ---------- query : str Search query to parse. Besides a search query, user can specify additional search parameters and YTFS specific options. Syntax: Additional search parameters: ``option:value``. if `value` contains spaces, then surround it with parentheses; available parameters: `channel`, `max`, `before`, `after`, `order`. YTFS options: specify options between ``[`` and ``]``; Available options: `a`, `v`, `f`, `P`, `s`, `m`. If an option takes a parameter, then specify it beetween parentheses. Examples: ``channel:foo search query``, ``my favourite music [a]``, ``channel:(the famous funny cats channel) [vf(240)P] funny cats max:20``. Invalid parameters/options are ignored. Returns ------- params : tuple Tuple: 0 - dictionary of url GET parameters; 1 - dictionary of YTStor options.
[ "Parse", "query", "for", "advanced", "search", "options", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/actions.py#L143-L274
train
35,213
rasguanabana/ytfs
ytfs/actions.py
YTActions.__search
def __search(self, pt=""): """ Method responsible for searching using YouTube API. Parameters ---------- pt : str Token of search results page. If ``None``, then the first page is downloaded. Returns ------- results : dict Parsed JSON returned by YouTube API. """ if not self.search_params.get('q') and not self.search_params.get('channelId'): return {'items': []} # no valid query - no results. api_fixed_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&fields=items(id%2Ckind%2Csnippet)%2CnextPageToken%2CprevPageToken&" d = {"key": self.api_key, "pageToken": pt} d.update(self.search_params) url = api_fixed_url + urlencode(d) try: get = requests.get(url) except requests.exceptions.ConnectionError: raise ConnectionError if get.status_code != 200: return {'items': []} # no valid query - no results. return get.json()
python
def __search(self, pt=""): """ Method responsible for searching using YouTube API. Parameters ---------- pt : str Token of search results page. If ``None``, then the first page is downloaded. Returns ------- results : dict Parsed JSON returned by YouTube API. """ if not self.search_params.get('q') and not self.search_params.get('channelId'): return {'items': []} # no valid query - no results. api_fixed_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&fields=items(id%2Ckind%2Csnippet)%2CnextPageToken%2CprevPageToken&" d = {"key": self.api_key, "pageToken": pt} d.update(self.search_params) url = api_fixed_url + urlencode(d) try: get = requests.get(url) except requests.exceptions.ConnectionError: raise ConnectionError if get.status_code != 200: return {'items': []} # no valid query - no results. return get.json()
[ "def", "__search", "(", "self", ",", "pt", "=", "\"\"", ")", ":", "if", "not", "self", ".", "search_params", ".", "get", "(", "'q'", ")", "and", "not", "self", ".", "search_params", ".", "get", "(", "'channelId'", ")", ":", "return", "{", "'items'", ...
Method responsible for searching using YouTube API. Parameters ---------- pt : str Token of search results page. If ``None``, then the first page is downloaded. Returns ------- results : dict Parsed JSON returned by YouTube API.
[ "Method", "responsible", "for", "searching", "using", "YouTube", "API", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/actions.py#L276-L309
train
35,214
rasguanabana/ytfs
ytfs/actions.py
YTActions.clean
def clean(self): """Clear the data. For each ``YTStor`` object present in this object ``clean`` method is executed.""" for s in self.visible_files.values(): s.clean() for s in [sub[1][x] for sub in self.avail_files.values() for x in sub[1]]: # Double list comprehensions aren't very s.clean()
python
def clean(self): """Clear the data. For each ``YTStor`` object present in this object ``clean`` method is executed.""" for s in self.visible_files.values(): s.clean() for s in [sub[1][x] for sub in self.avail_files.values() for x in sub[1]]: # Double list comprehensions aren't very s.clean()
[ "def", "clean", "(", "self", ")", ":", "for", "s", "in", "self", ".", "visible_files", ".", "values", "(", ")", ":", "s", ".", "clean", "(", ")", "for", "s", "in", "[", "sub", "[", "1", "]", "[", "x", "]", "for", "sub", "in", "self", ".", "...
Clear the data. For each ``YTStor`` object present in this object ``clean`` method is executed.
[ "Clear", "the", "data", ".", "For", "each", "YTStor", "object", "present", "in", "this", "object", "clean", "method", "is", "executed", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/actions.py#L477-L484
train
35,215
rasguanabana/ytfs
ytfs/stor.py
YTStor.obtainInfo
def obtainInfo(self): """ Method for obtaining information about the movie. """ try: info = self.ytdl.extract_info(self.yid, download=False) except youtube_dl.utils.DownloadError: raise ConnectionError if not self.preferences['stream']: self.url = (info['requested_formats'][0]['url'], info['requested_formats'][1]['url']) return True # else: for f in info['formats']: if 'filesize' not in f or not f['filesize']: f['filesize'] = float('inf') # next line won't fail, infinity, because unknown filesize is the least preferred # - for easy sorting - we'll get best quality and lowest filsize aud = {(-int(f['abr']), f['filesize'], f['url']) for f in info['formats'] if f.get('abr') and not f.get('height')} vid = {(-int(f['height']), f['filesize'], f['url']) for f in info['formats'] if not f.get('abr') and f.get('height')} full= {(-int(f['height']), f['filesize'], f['url']) for f in info['formats'] if f.get('abr') and f.get('height')} try: _f = int( self.preferences.get('format') ) # if valid format is present, then choose closes value _k = lambda x: abs(x[0] + _f) # +, because x[0] is negative except (ValueError, TypeError): _k = lambda d: d if self.preferences['audio'] and self.preferences['video']: fm = sorted(full, key=_k) elif self.preferences['audio']: fm = sorted(aud, key=_k) elif self.preferences['video']: fm = sorted(vid, key=_k) filesize = 0 i = -1 try: while filesize == 0: # some videos are problematic, we will try to find format with non-zero filesize i += 1 self.url = fm[i][2] if fm[i][1] == float('inf'): filesize = int(self.r_session.head(self.url).headers['content-length']) else: filesize = int(fm[i][1]) except IndexError: # finding filesize failed for every format self.url = (info['requested_formats'][0]['url'], info['requested_formats'][1]['url']) self.preferences['stream'] = False # hopefully non-stream download will work return True self.filesize = filesize return True
python
def obtainInfo(self): """ Method for obtaining information about the movie. """ try: info = self.ytdl.extract_info(self.yid, download=False) except youtube_dl.utils.DownloadError: raise ConnectionError if not self.preferences['stream']: self.url = (info['requested_formats'][0]['url'], info['requested_formats'][1]['url']) return True # else: for f in info['formats']: if 'filesize' not in f or not f['filesize']: f['filesize'] = float('inf') # next line won't fail, infinity, because unknown filesize is the least preferred # - for easy sorting - we'll get best quality and lowest filsize aud = {(-int(f['abr']), f['filesize'], f['url']) for f in info['formats'] if f.get('abr') and not f.get('height')} vid = {(-int(f['height']), f['filesize'], f['url']) for f in info['formats'] if not f.get('abr') and f.get('height')} full= {(-int(f['height']), f['filesize'], f['url']) for f in info['formats'] if f.get('abr') and f.get('height')} try: _f = int( self.preferences.get('format') ) # if valid format is present, then choose closes value _k = lambda x: abs(x[0] + _f) # +, because x[0] is negative except (ValueError, TypeError): _k = lambda d: d if self.preferences['audio'] and self.preferences['video']: fm = sorted(full, key=_k) elif self.preferences['audio']: fm = sorted(aud, key=_k) elif self.preferences['video']: fm = sorted(vid, key=_k) filesize = 0 i = -1 try: while filesize == 0: # some videos are problematic, we will try to find format with non-zero filesize i += 1 self.url = fm[i][2] if fm[i][1] == float('inf'): filesize = int(self.r_session.head(self.url).headers['content-length']) else: filesize = int(fm[i][1]) except IndexError: # finding filesize failed for every format self.url = (info['requested_formats'][0]['url'], info['requested_formats'][1]['url']) self.preferences['stream'] = False # hopefully non-stream download will work return True self.filesize = filesize return True
[ "def", "obtainInfo", "(", "self", ")", ":", "try", ":", "info", "=", "self", ".", "ytdl", ".", "extract_info", "(", "self", ".", "yid", ",", "download", "=", "False", ")", "except", "youtube_dl", ".", "utils", ".", "DownloadError", ":", "raise", "Conne...
Method for obtaining information about the movie.
[ "Method", "for", "obtaining", "information", "about", "the", "movie", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/stor.py#L205-L264
train
35,216
rasguanabana/ytfs
ytfs/stor.py
YTStor.registerHandler
def registerHandler(self, fh): # Do I even need that? possible FIXME. """ Register new file descriptor. Parameters ---------- fh : int File descriptor. """ self.fds.add(fh) self.atime = int(time()) # update access time self.lock.acquire() try: if (0, self.filesize) not in self.avail and self.preferences['stream'] is False: Downloader.fetch(self, None, fh) # lock forces other threads to wait, so fetch will perform just once. except requests.exceptions.ConnectionError: raise ConnectionError finally: self.lock.release()
python
def registerHandler(self, fh): # Do I even need that? possible FIXME. """ Register new file descriptor. Parameters ---------- fh : int File descriptor. """ self.fds.add(fh) self.atime = int(time()) # update access time self.lock.acquire() try: if (0, self.filesize) not in self.avail and self.preferences['stream'] is False: Downloader.fetch(self, None, fh) # lock forces other threads to wait, so fetch will perform just once. except requests.exceptions.ConnectionError: raise ConnectionError finally: self.lock.release()
[ "def", "registerHandler", "(", "self", ",", "fh", ")", ":", "# Do I even need that? possible FIXME.", "self", ".", "fds", ".", "add", "(", "fh", ")", "self", ".", "atime", "=", "int", "(", "time", "(", ")", ")", "# update access time", "self", ".", "lock",...
Register new file descriptor. Parameters ---------- fh : int File descriptor.
[ "Register", "new", "file", "descriptor", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/stor.py#L266-L290
train
35,217
rasguanabana/ytfs
ytfs/stor.py
YTStor.read
def read(self, offset, length, fh): """ Read data. Method returns data instantly, if they're avaialable and in ``self.safe_range``. Otherwise data is downloaded and then returned. Parameters ---------- offset : int Read offset length : int Length of data to read. fh : int File descriptor. """ current = (offset, offset + length) safe = [ current[0] - ( 8 * length ), current[1] + ( 16 * length ) ] if safe[0] < 0: safe[0] = 0 if safe[1] > self.filesize: safe[1] = self.filesize safe = tuple(safe) self.lock.acquire() try: dl = range_t({safe}) - self.avail for r in dl.toset(): try: Downloader.fetch(self, r, fh) # download is, let's say, atomic thanks to lock except requests.exceptions.ConnectionError: raise ConnectionError if self.disk + 1 < len(self.avail): self.data.rollover() self.disk += 1 finally: self.lock.release() self.data.seek(offset) return self.data.read(length)
python
def read(self, offset, length, fh): """ Read data. Method returns data instantly, if they're avaialable and in ``self.safe_range``. Otherwise data is downloaded and then returned. Parameters ---------- offset : int Read offset length : int Length of data to read. fh : int File descriptor. """ current = (offset, offset + length) safe = [ current[0] - ( 8 * length ), current[1] + ( 16 * length ) ] if safe[0] < 0: safe[0] = 0 if safe[1] > self.filesize: safe[1] = self.filesize safe = tuple(safe) self.lock.acquire() try: dl = range_t({safe}) - self.avail for r in dl.toset(): try: Downloader.fetch(self, r, fh) # download is, let's say, atomic thanks to lock except requests.exceptions.ConnectionError: raise ConnectionError if self.disk + 1 < len(self.avail): self.data.rollover() self.disk += 1 finally: self.lock.release() self.data.seek(offset) return self.data.read(length)
[ "def", "read", "(", "self", ",", "offset", ",", "length", ",", "fh", ")", ":", "current", "=", "(", "offset", ",", "offset", "+", "length", ")", "safe", "=", "[", "current", "[", "0", "]", "-", "(", "8", "*", "length", ")", ",", "current", "[",...
Read data. Method returns data instantly, if they're avaialable and in ``self.safe_range``. Otherwise data is downloaded and then returned. Parameters ---------- offset : int Read offset length : int Length of data to read. fh : int File descriptor.
[ "Read", "data", ".", "Method", "returns", "data", "instantly", "if", "they", "re", "avaialable", "and", "in", "self", ".", "safe_range", ".", "Otherwise", "data", "is", "downloaded", "and", "then", "returned", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/stor.py#L292-L335
train
35,218
rasguanabana/ytfs
ytfs/stor.py
YTStor.clean
def clean(self): """ Clear data. Explicitly close ``self.data`` if object is unused. """ self.closing = True # schedule for closing. if not self.fds: self.data.close()
python
def clean(self): """ Clear data. Explicitly close ``self.data`` if object is unused. """ self.closing = True # schedule for closing. if not self.fds: self.data.close()
[ "def", "clean", "(", "self", ")", ":", "self", ".", "closing", "=", "True", "# schedule for closing.", "if", "not", "self", ".", "fds", ":", "self", ".", "data", ".", "close", "(", ")" ]
Clear data. Explicitly close ``self.data`` if object is unused.
[ "Clear", "data", ".", "Explicitly", "close", "self", ".", "data", "if", "object", "is", "unused", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/stor.py#L337-L346
train
35,219
rasguanabana/ytfs
ytfs/stor.py
YTStor.unregisterHandler
def unregisterHandler(self, fh): """ Unregister a file descriptor. Clean data, if such operation has been scheduled. Parameters ---------- fh : int File descriptor. """ try: self.fds.remove(fh) except KeyError: pass self.lock.acquire() try: self.data.rollover() # rollover data on close. finally: self.lock.release() if self.closing and not self.fds: self.data.close()
python
def unregisterHandler(self, fh): """ Unregister a file descriptor. Clean data, if such operation has been scheduled. Parameters ---------- fh : int File descriptor. """ try: self.fds.remove(fh) except KeyError: pass self.lock.acquire() try: self.data.rollover() # rollover data on close. finally: self.lock.release() if self.closing and not self.fds: self.data.close()
[ "def", "unregisterHandler", "(", "self", ",", "fh", ")", ":", "try", ":", "self", ".", "fds", ".", "remove", "(", "fh", ")", "except", "KeyError", ":", "pass", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "data", ".", "...
Unregister a file descriptor. Clean data, if such operation has been scheduled. Parameters ---------- fh : int File descriptor.
[ "Unregister", "a", "file", "descriptor", ".", "Clean", "data", "if", "such", "operation", "has", "been", "scheduled", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/stor.py#L348-L374
train
35,220
rasguanabana/ytfs
ytfs/ytfs.py
fd_dict.push
def push(self, yts): """ Search for, add and return new file descriptor. Parameters ---------- yts : YTStor-obj or None ``YTStor`` object for which we want to allocate a descriptor or ``None``, if we allocate descriptor for a control file. Returns ------- k : int File descriptor. """ if not isinstance(yts, (YTStor, YTMetaStor, type(None))): raise TypeError("Expected YTStor object, YTMetaStor object or None.") k = 0 while k in self.keys(): k += 1 self[k] = yts return k
python
def push(self, yts): """ Search for, add and return new file descriptor. Parameters ---------- yts : YTStor-obj or None ``YTStor`` object for which we want to allocate a descriptor or ``None``, if we allocate descriptor for a control file. Returns ------- k : int File descriptor. """ if not isinstance(yts, (YTStor, YTMetaStor, type(None))): raise TypeError("Expected YTStor object, YTMetaStor object or None.") k = 0 while k in self.keys(): k += 1 self[k] = yts return k
[ "def", "push", "(", "self", ",", "yts", ")", ":", "if", "not", "isinstance", "(", "yts", ",", "(", "YTStor", ",", "YTMetaStor", ",", "type", "(", "None", ")", ")", ")", ":", "raise", "TypeError", "(", "\"Expected YTStor object, YTMetaStor object or None.\"",...
Search for, add and return new file descriptor. Parameters ---------- yts : YTStor-obj or None ``YTStor`` object for which we want to allocate a descriptor or ``None``, if we allocate descriptor for a control file. Returns ------- k : int File descriptor.
[ "Search", "for", "add", "and", "return", "new", "file", "descriptor", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L70-L95
train
35,221
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.__pathToTuple
def __pathToTuple(self, path): """ Convert directory or file path to its tuple identifier. Parameters ---------- path : str Path to convert. It can look like /, /directory, /directory/ or /directory/filename. Returns ------- tup_id : tuple Two element tuple identifier of directory/file of (`directory`, `filename`) format. If path leads to main directory, then both fields of tuple will be ``None``. If path leads to a directory, then field `filename` will be ``None``. Raises ------ YTFS.PathConvertError When invalid path is given. """ if not path or path.count('/') > 2: raise YTFS.PathConvertError("Bad path given") # empty or too deep path try: split = path.split('/') except (AttributeError, TypeError): raise TypeError("Path has to be string") #path is not a string if split[0]: raise YTFS.PathConvertError("Path needs to start with '/'") # path doesn't start with '/'. del split[0] try: if not split[-1]: split.pop() # given path ended with '/'. except IndexError: raise YTFS.PathConvertError("Bad path given") # at least one element in split should exist at the moment if len(split) > 2: raise YTFS.PathConvertError("Path is too deep. Max allowed level is 2") # should happen due to first check, but ... try: d = split[0] except IndexError: d = None try: f = split[1] except IndexError: f = None if not d and f: raise YTFS.PathConvertError("Bad path given") # filename is present, but directory is not #sheeeeeeiiit return (d, f)
python
def __pathToTuple(self, path): """ Convert directory or file path to its tuple identifier. Parameters ---------- path : str Path to convert. It can look like /, /directory, /directory/ or /directory/filename. Returns ------- tup_id : tuple Two element tuple identifier of directory/file of (`directory`, `filename`) format. If path leads to main directory, then both fields of tuple will be ``None``. If path leads to a directory, then field `filename` will be ``None``. Raises ------ YTFS.PathConvertError When invalid path is given. """ if not path or path.count('/') > 2: raise YTFS.PathConvertError("Bad path given") # empty or too deep path try: split = path.split('/') except (AttributeError, TypeError): raise TypeError("Path has to be string") #path is not a string if split[0]: raise YTFS.PathConvertError("Path needs to start with '/'") # path doesn't start with '/'. del split[0] try: if not split[-1]: split.pop() # given path ended with '/'. except IndexError: raise YTFS.PathConvertError("Bad path given") # at least one element in split should exist at the moment if len(split) > 2: raise YTFS.PathConvertError("Path is too deep. Max allowed level is 2") # should happen due to first check, but ... try: d = split[0] except IndexError: d = None try: f = split[1] except IndexError: f = None if not d and f: raise YTFS.PathConvertError("Bad path given") # filename is present, but directory is not #sheeeeeeiiit return (d, f)
[ "def", "__pathToTuple", "(", "self", ",", "path", ")", ":", "if", "not", "path", "or", "path", ".", "count", "(", "'/'", ")", ">", "2", ":", "raise", "YTFS", ".", "PathConvertError", "(", "\"Bad path given\"", ")", "# empty or too deep path", "try", ":", ...
Convert directory or file path to its tuple identifier. Parameters ---------- path : str Path to convert. It can look like /, /directory, /directory/ or /directory/filename. Returns ------- tup_id : tuple Two element tuple identifier of directory/file of (`directory`, `filename`) format. If path leads to main directory, then both fields of tuple will be ``None``. If path leads to a directory, then field `filename` will be ``None``. Raises ------ YTFS.PathConvertError When invalid path is given.
[ "Convert", "directory", "or", "file", "path", "to", "its", "tuple", "identifier", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L222-L277
train
35,222
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.__exists
def __exists(self, p): """ Check if file of given path exists. Parameters ---------- p : str or tuple Path or tuple identifier. Returns ------- exists : bool ``True``, if file exists. Otherwise ``False``. """ try: p = self.__pathToTuple(p) except TypeError: pass return ((not p[0] and not p[1]) or (p[0] in self.searches and not p[1]) or (p[0] in self.searches and p[1] in self.searches[p[0]]))
python
def __exists(self, p): """ Check if file of given path exists. Parameters ---------- p : str or tuple Path or tuple identifier. Returns ------- exists : bool ``True``, if file exists. Otherwise ``False``. """ try: p = self.__pathToTuple(p) except TypeError: pass return ((not p[0] and not p[1]) or (p[0] in self.searches and not p[1]) or (p[0] in self.searches and p[1] in self.searches[p[0]]))
[ "def", "__exists", "(", "self", ",", "p", ")", ":", "try", ":", "p", "=", "self", ".", "__pathToTuple", "(", "p", ")", "except", "TypeError", ":", "pass", "return", "(", "(", "not", "p", "[", "0", "]", "and", "not", "p", "[", "1", "]", ")", "...
Check if file of given path exists. Parameters ---------- p : str or tuple Path or tuple identifier. Returns ------- exists : bool ``True``, if file exists. Otherwise ``False``.
[ "Check", "if", "file", "of", "given", "path", "exists", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L279-L301
train
35,223
rasguanabana/ytfs
ytfs/ytfs.py
YTFS._pathdec
def _pathdec(method): """ Decorator that replaces string `path` argument with its tuple identifier. Parameters ---------- method : function Function/method to decorate. Returns ------- mod : function Function/method after decarotion. """ @wraps(method) # functools.wraps makes docs autogeneration easy and proper for decorated functions. def mod(self, path, *args): try: return method(self, self.__pathToTuple(path), *args) except YTFS.PathConvertError: raise FuseOSError(errno.EINVAL) return mod
python
def _pathdec(method): """ Decorator that replaces string `path` argument with its tuple identifier. Parameters ---------- method : function Function/method to decorate. Returns ------- mod : function Function/method after decarotion. """ @wraps(method) # functools.wraps makes docs autogeneration easy and proper for decorated functions. def mod(self, path, *args): try: return method(self, self.__pathToTuple(path), *args) except YTFS.PathConvertError: raise FuseOSError(errno.EINVAL) return mod
[ "def", "_pathdec", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "# functools.wraps makes docs autogeneration easy and proper for decorated functions.", "def", "mod", "(", "self", ",", "path", ",", "*", "args", ")", ":", "try", ":", "return", "method"...
Decorator that replaces string `path` argument with its tuple identifier. Parameters ---------- method : function Function/method to decorate. Returns ------- mod : function Function/method after decarotion.
[ "Decorator", "that", "replaces", "string", "path", "argument", "with", "its", "tuple", "identifier", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L303-L328
train
35,224
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.getattr
def getattr(self, tid, fh=None): """ File attributes. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int File descriptor. Unnecessary, therefore ignored. Returns ------- st : dict Dictionary that contains file attributes. See: ``man 2 stat``. """ if not self.__exists(tid): raise FuseOSError(errno.ENOENT) pt = self.PathType.get(tid) st = deepcopy(self.st) st['st_atime'] = int(time()) st['st_mtime'] = st['st_atime'] st['st_ctime'] = st['st_atime'] if pt is self.PathType.file: st['st_mode'] = stat.S_IFREG | 0o444 st['st_nlink'] = 1 st['st_size'] = self.searches[ tid[0] ][ tid[1] ].filesize st['st_ctime'] = self.searches[ tid[0] ][ tid[1] ].ctime st['st_mtime'] = st['st_ctime'] st['st_atime'] = self.searches[ tid[0] ][ tid[1] ].atime elif pt is self.PathType.ctrl: st['st_mode'] = stat.S_IFREG | 0o774 st['st_nlink'] = 1 st['st_size'] = len(self.__sh_script) elif pt is self.PathType.main: st['st_mode'] = stat.S_IFDIR | 0o774 st['st_blocks'] = math.ceil(st['st_size'] / st['st_blksize']) return st
python
def getattr(self, tid, fh=None): """ File attributes. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int File descriptor. Unnecessary, therefore ignored. Returns ------- st : dict Dictionary that contains file attributes. See: ``man 2 stat``. """ if not self.__exists(tid): raise FuseOSError(errno.ENOENT) pt = self.PathType.get(tid) st = deepcopy(self.st) st['st_atime'] = int(time()) st['st_mtime'] = st['st_atime'] st['st_ctime'] = st['st_atime'] if pt is self.PathType.file: st['st_mode'] = stat.S_IFREG | 0o444 st['st_nlink'] = 1 st['st_size'] = self.searches[ tid[0] ][ tid[1] ].filesize st['st_ctime'] = self.searches[ tid[0] ][ tid[1] ].ctime st['st_mtime'] = st['st_ctime'] st['st_atime'] = self.searches[ tid[0] ][ tid[1] ].atime elif pt is self.PathType.ctrl: st['st_mode'] = stat.S_IFREG | 0o774 st['st_nlink'] = 1 st['st_size'] = len(self.__sh_script) elif pt is self.PathType.main: st['st_mode'] = stat.S_IFDIR | 0o774 st['st_blocks'] = math.ceil(st['st_size'] / st['st_blksize']) return st
[ "def", "getattr", "(", "self", ",", "tid", ",", "fh", "=", "None", ")", ":", "if", "not", "self", ".", "__exists", "(", "tid", ")", ":", "raise", "FuseOSError", "(", "errno", ".", "ENOENT", ")", "pt", "=", "self", ".", "PathType", ".", "get", "("...
File attributes. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int File descriptor. Unnecessary, therefore ignored. Returns ------- st : dict Dictionary that contains file attributes. See: ``man 2 stat``.
[ "File", "attributes", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L331-L380
train
35,225
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.readdir
def readdir(self, tid, fh): """ Read directory contents. Lists visible elements of ``YTActions`` object. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int File descriptor. Ommited in the function body. Returns ------- list List of filenames, wich will be shown as directory content. """ ret = [] pt = self.PathType.get(tid) try: if pt is self.PathType.main: ret = list(self.searches) elif pt is self.PathType.subdir: ret = list(self.searches[tid[0]]) elif pt is self.PathType.file: raise FuseOSError(errno.ENOTDIR) else: raise FuseOSError(errno.ENOENT) except KeyError: raise FuseOSError(errno.ENOENT) return ['.', '..'] + ret
python
def readdir(self, tid, fh): """ Read directory contents. Lists visible elements of ``YTActions`` object. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int File descriptor. Ommited in the function body. Returns ------- list List of filenames, wich will be shown as directory content. """ ret = [] pt = self.PathType.get(tid) try: if pt is self.PathType.main: ret = list(self.searches) elif pt is self.PathType.subdir: ret = list(self.searches[tid[0]]) elif pt is self.PathType.file: raise FuseOSError(errno.ENOTDIR) else: raise FuseOSError(errno.ENOENT) except KeyError: raise FuseOSError(errno.ENOENT) return ['.', '..'] + ret
[ "def", "readdir", "(", "self", ",", "tid", ",", "fh", ")", ":", "ret", "=", "[", "]", "pt", "=", "self", ".", "PathType", ".", "get", "(", "tid", ")", "try", ":", "if", "pt", "is", "self", ".", "PathType", ".", "main", ":", "ret", "=", "list"...
Read directory contents. Lists visible elements of ``YTActions`` object. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int File descriptor. Ommited in the function body. Returns ------- list List of filenames, wich will be shown as directory content.
[ "Read", "directory", "contents", ".", "Lists", "visible", "elements", "of", "YTActions", "object", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L383-L419
train
35,226
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.mkdir
def mkdir(self, tid, mode): """ Directory creation. Search is performed. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. mode : int Ignored. """ pt = self.PathType.get(tid) if pt is self.PathType.invalid or pt is self.PathType.file: raise FuseOSError(errno.EPERM) if self.__exists(tid): raise FuseOSError(errno.EEXIST) try: dir_ent = YTActions(tid[0]) dir_ent.updateResults() except ConnectionError: raise FuseOSError(errno.ENETDOWN) self.searches[tid[0]] = dir_ent # now adding directory entry is legit, nothing failed. return 0
python
def mkdir(self, tid, mode): """ Directory creation. Search is performed. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. mode : int Ignored. """ pt = self.PathType.get(tid) if pt is self.PathType.invalid or pt is self.PathType.file: raise FuseOSError(errno.EPERM) if self.__exists(tid): raise FuseOSError(errno.EEXIST) try: dir_ent = YTActions(tid[0]) dir_ent.updateResults() except ConnectionError: raise FuseOSError(errno.ENETDOWN) self.searches[tid[0]] = dir_ent # now adding directory entry is legit, nothing failed. return 0
[ "def", "mkdir", "(", "self", ",", "tid", ",", "mode", ")", ":", "pt", "=", "self", ".", "PathType", ".", "get", "(", "tid", ")", "if", "pt", "is", "self", ".", "PathType", ".", "invalid", "or", "pt", "is", "self", ".", "PathType", ".", "file", ...
Directory creation. Search is performed. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. mode : int Ignored.
[ "Directory", "creation", ".", "Search", "is", "performed", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L422-L451
train
35,227
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.rename
def rename(self, old, new): """ Directory renaming support. Needed because many file managers create directories with default names, wich makes it impossible to perform a search without CLI. Name changes for files are not allowed, only for directories. Parameters ---------- old : str Old name. Converted to tuple identifier by ``_pathdec`` decorator. new : str New name. Converted to tuple identifier in actual function body. """ new = self.__pathToTuple(new) if not self.__exists(old): raise FuseOSError(errno.ENOENT) if self.PathType.get(old) is not self.PathType.subdir or self.PathType.get(new) is not self.PathType.subdir: raise FuseOSError(errno.EPERM) if self.__exists(new): raise FuseOSError(errno.EEXIST) try: new_dir_ent = YTActions(new[0]) new_dir_ent.updateResults() except ConnectionError: raise FuseOSError(errno.ENETDOWN) self.searches[new[0]] = new_dir_ent # as in mkdir try: del self.searches[old[0]] except KeyError: raise FuseOSError(errno.ENOENT) return 0
python
def rename(self, old, new): """ Directory renaming support. Needed because many file managers create directories with default names, wich makes it impossible to perform a search without CLI. Name changes for files are not allowed, only for directories. Parameters ---------- old : str Old name. Converted to tuple identifier by ``_pathdec`` decorator. new : str New name. Converted to tuple identifier in actual function body. """ new = self.__pathToTuple(new) if not self.__exists(old): raise FuseOSError(errno.ENOENT) if self.PathType.get(old) is not self.PathType.subdir or self.PathType.get(new) is not self.PathType.subdir: raise FuseOSError(errno.EPERM) if self.__exists(new): raise FuseOSError(errno.EEXIST) try: new_dir_ent = YTActions(new[0]) new_dir_ent.updateResults() except ConnectionError: raise FuseOSError(errno.ENETDOWN) self.searches[new[0]] = new_dir_ent # as in mkdir try: del self.searches[old[0]] except KeyError: raise FuseOSError(errno.ENOENT) return 0
[ "def", "rename", "(", "self", ",", "old", ",", "new", ")", ":", "new", "=", "self", ".", "__pathToTuple", "(", "new", ")", "if", "not", "self", ".", "__exists", "(", "old", ")", ":", "raise", "FuseOSError", "(", "errno", ".", "ENOENT", ")", "if", ...
Directory renaming support. Needed because many file managers create directories with default names, wich makes it impossible to perform a search without CLI. Name changes for files are not allowed, only for directories. Parameters ---------- old : str Old name. Converted to tuple identifier by ``_pathdec`` decorator. new : str New name. Converted to tuple identifier in actual function body.
[ "Directory", "renaming", "support", ".", "Needed", "because", "many", "file", "managers", "create", "directories", "with", "default", "names", "wich", "makes", "it", "impossible", "to", "perform", "a", "search", "without", "CLI", ".", "Name", "changes", "for", ...
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L454-L494
train
35,228
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.rmdir
def rmdir(self, tid): """ Directory removal. ``YTActions`` object under `tid` is told to clean all data, and then it is deleted. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. """ pt = self.PathType.get(tid) if pt is self.PathType.main: raise FuseOSError(errno.EINVAL) elif pt is not self.PathType.subdir: raise FuseOSError(errno.ENOTDIR) try: self.searches[tid[0]].clean() del self.searches[tid[0]] except KeyError: raise FuseOSError(errno.ENOENT) return 0
python
def rmdir(self, tid): """ Directory removal. ``YTActions`` object under `tid` is told to clean all data, and then it is deleted. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. """ pt = self.PathType.get(tid) if pt is self.PathType.main: raise FuseOSError(errno.EINVAL) elif pt is not self.PathType.subdir: raise FuseOSError(errno.ENOTDIR) try: self.searches[tid[0]].clean() del self.searches[tid[0]] except KeyError: raise FuseOSError(errno.ENOENT) return 0
[ "def", "rmdir", "(", "self", ",", "tid", ")", ":", "pt", "=", "self", ".", "PathType", ".", "get", "(", "tid", ")", "if", "pt", "is", "self", ".", "PathType", ".", "main", ":", "raise", "FuseOSError", "(", "errno", ".", "EINVAL", ")", "elif", "pt...
Directory removal. ``YTActions`` object under `tid` is told to clean all data, and then it is deleted. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator.
[ "Directory", "removal", ".", "YTActions", "object", "under", "tid", "is", "told", "to", "clean", "all", "data", "and", "then", "it", "is", "deleted", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L497-L522
train
35,229
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.open
def open(self, tid, flags): """ File open. ``YTStor`` object associated with this file is initialised and written to ``self.fds``. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. flags : int File open mode. Read-only access is allowed. Returns ------- int New file descriptor """ pt = self.PathType.get(tid) if pt is not self.PathType.file and pt is not self.PathType.ctrl: raise FuseOSError(errno.EINVAL) if pt is not self.PathType.ctrl and (flags & os.O_WRONLY or flags & os.O_RDWR): raise FuseOSError(errno.EPERM) if not self.__exists(tid): raise FuseOSError(errno.ENOENT) try: yts = self.searches[tid[0]][tid[1]] except KeyError: return self.fds.push(None) # for control file no association is needed. try: obI = yts.obtainInfo() # network may fail except ConnectionError: raise FuseOSError(errno.ENETDOWN) if obI: fh = self.fds.push(yts) try: yts.registerHandler(fh) except ConnectionError: raise FuseOSError(errno.ENETDOWN) return fh else: raise FuseOSError(errno.EINVAL)
python
def open(self, tid, flags): """ File open. ``YTStor`` object associated with this file is initialised and written to ``self.fds``. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. flags : int File open mode. Read-only access is allowed. Returns ------- int New file descriptor """ pt = self.PathType.get(tid) if pt is not self.PathType.file and pt is not self.PathType.ctrl: raise FuseOSError(errno.EINVAL) if pt is not self.PathType.ctrl and (flags & os.O_WRONLY or flags & os.O_RDWR): raise FuseOSError(errno.EPERM) if not self.__exists(tid): raise FuseOSError(errno.ENOENT) try: yts = self.searches[tid[0]][tid[1]] except KeyError: return self.fds.push(None) # for control file no association is needed. try: obI = yts.obtainInfo() # network may fail except ConnectionError: raise FuseOSError(errno.ENETDOWN) if obI: fh = self.fds.push(yts) try: yts.registerHandler(fh) except ConnectionError: raise FuseOSError(errno.ENETDOWN) return fh else: raise FuseOSError(errno.EINVAL)
[ "def", "open", "(", "self", ",", "tid", ",", "flags", ")", ":", "pt", "=", "self", ".", "PathType", ".", "get", "(", "tid", ")", "if", "pt", "is", "not", "self", ".", "PathType", ".", "file", "and", "pt", "is", "not", "self", ".", "PathType", "...
File open. ``YTStor`` object associated with this file is initialised and written to ``self.fds``. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. flags : int File open mode. Read-only access is allowed. Returns ------- int New file descriptor
[ "File", "open", ".", "YTStor", "object", "associated", "with", "this", "file", "is", "initialised", "and", "written", "to", "self", ".", "fds", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L539-L589
train
35,230
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.write
def write(self, tid, data, offset, fh): """ Write operation. Applicable only for control files - updateResults is called. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. data : bytes Ignored. offset : int Ignored. fh : int File descriptor. Returns ------- int Length of data written. """ if tid[1] == " next": d = True elif tid[1] == " prev": d = False else: raise FuseOSError(errno.EPERM) try: self.searches[tid[0]].updateResults(d) except KeyError: raise FuseOSError(errno.EINVAL) # sth went wrong... except ConnectionError: raise FuseOSError(errno.ENETDOWN) return len(data)
python
def write(self, tid, data, offset, fh): """ Write operation. Applicable only for control files - updateResults is called. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. data : bytes Ignored. offset : int Ignored. fh : int File descriptor. Returns ------- int Length of data written. """ if tid[1] == " next": d = True elif tid[1] == " prev": d = False else: raise FuseOSError(errno.EPERM) try: self.searches[tid[0]].updateResults(d) except KeyError: raise FuseOSError(errno.EINVAL) # sth went wrong... except ConnectionError: raise FuseOSError(errno.ENETDOWN) return len(data)
[ "def", "write", "(", "self", ",", "tid", ",", "data", ",", "offset", ",", "fh", ")", ":", "if", "tid", "[", "1", "]", "==", "\" next\"", ":", "d", "=", "True", "elif", "tid", "[", "1", "]", "==", "\" prev\"", ":", "d", "=", "False", "else", "...
Write operation. Applicable only for control files - updateResults is called. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. data : bytes Ignored. offset : int Ignored. fh : int File descriptor. Returns ------- int Length of data written.
[ "Write", "operation", ".", "Applicable", "only", "for", "control", "files", "-", "updateResults", "is", "called", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L633-L669
train
35,231
rasguanabana/ytfs
ytfs/ytfs.py
YTFS.release
def release(self, tid, fh): """ Close file. Descriptor is removed from ``self.fds``. Parameters ---------- tid : str Path to file. Ignored. fh : int File descriptor to release. """ try: try: self.fds[fh].unregisterHandler(fh) except AttributeError: pass del self.fds[fh] except KeyError: raise FuseOSError(errno.EBADF) return 0
python
def release(self, tid, fh): """ Close file. Descriptor is removed from ``self.fds``. Parameters ---------- tid : str Path to file. Ignored. fh : int File descriptor to release. """ try: try: self.fds[fh].unregisterHandler(fh) except AttributeError: pass del self.fds[fh] except KeyError: raise FuseOSError(errno.EBADF) return 0
[ "def", "release", "(", "self", ",", "tid", ",", "fh", ")", ":", "try", ":", "try", ":", "self", ".", "fds", "[", "fh", "]", ".", "unregisterHandler", "(", "fh", ")", "except", "AttributeError", ":", "pass", "del", "self", ".", "fds", "[", "fh", "...
Close file. Descriptor is removed from ``self.fds``. Parameters ---------- tid : str Path to file. Ignored. fh : int File descriptor to release.
[ "Close", "file", ".", "Descriptor", "is", "removed", "from", "self", ".", "fds", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/ytfs.py#L672-L697
train
35,232
rasguanabana/ytfs
ytfs/range_t.py
range_t.__match_l
def __match_l(self, k, _set): """ Method for searching subranges from `_set` that overlap on `k` range. Parameters ---------- k : tuple or list or range Range for which we search overlapping subranges from `_set`. _set : set Subranges set. Returns ------- matched : set Set of subranges from `_set` that overlaps on `k`. """ return {r for r in _set if k[0] in range(*r) or k[1] in range(*r) or (k[0] < r[0] and k[1] >= r[1])}
python
def __match_l(self, k, _set): """ Method for searching subranges from `_set` that overlap on `k` range. Parameters ---------- k : tuple or list or range Range for which we search overlapping subranges from `_set`. _set : set Subranges set. Returns ------- matched : set Set of subranges from `_set` that overlaps on `k`. """ return {r for r in _set if k[0] in range(*r) or k[1] in range(*r) or (k[0] < r[0] and k[1] >= r[1])}
[ "def", "__match_l", "(", "self", ",", "k", ",", "_set", ")", ":", "return", "{", "r", "for", "r", "in", "_set", "if", "k", "[", "0", "]", "in", "range", "(", "*", "r", ")", "or", "k", "[", "1", "]", "in", "range", "(", "*", "r", ")", "or"...
Method for searching subranges from `_set` that overlap on `k` range. Parameters ---------- k : tuple or list or range Range for which we search overlapping subranges from `_set`. _set : set Subranges set. Returns ------- matched : set Set of subranges from `_set` that overlaps on `k`.
[ "Method", "for", "searching", "subranges", "from", "_set", "that", "overlap", "on", "k", "range", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/range_t.py#L39-L57
train
35,233
rasguanabana/ytfs
ytfs/range_t.py
range_t.contains
def contains(self, val): """ Check if given value or range is present. Parameters ---------- val : int or tuple or list or range Range or integer being checked. Returns ------- retlen : int Length of overlapping with `val` subranges. """ (start, end) = self.__val_convert(val) # conversion retlen = 0 for r in self.__has: if start < r[1] and end > r[0]: retlen += ((end < r[1] and end) or r[1]) - ((start > r[0] and start) or r[0]) return retlen
python
def contains(self, val): """ Check if given value or range is present. Parameters ---------- val : int or tuple or list or range Range or integer being checked. Returns ------- retlen : int Length of overlapping with `val` subranges. """ (start, end) = self.__val_convert(val) # conversion retlen = 0 for r in self.__has: if start < r[1] and end > r[0]: retlen += ((end < r[1] and end) or r[1]) - ((start > r[0] and start) or r[0]) return retlen
[ "def", "contains", "(", "self", ",", "val", ")", ":", "(", "start", ",", "end", ")", "=", "self", ".", "__val_convert", "(", "val", ")", "# conversion", "retlen", "=", "0", "for", "r", "in", "self", ".", "__has", ":", "if", "start", "<", "r", "["...
Check if given value or range is present. Parameters ---------- val : int or tuple or list or range Range or integer being checked. Returns ------- retlen : int Length of overlapping with `val` subranges.
[ "Check", "if", "given", "value", "or", "range", "is", "present", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/range_t.py#L118-L141
train
35,234
rasguanabana/ytfs
ytfs/range_t.py
range_t.__add
def __add(self, val): """ Helper method for range addition. It is allowed to add only one compact subrange or ``range_t`` object at once. Parameters ---------- val : int or tuple or list or range Integer or range to add. Returns ------- __has : set ``self.__has`` extended by `val`. """ if not isinstance(val, range_t): #sanitize it val = {self.__val_convert(val)} # convert to a set, coz I like it that way. else: val = val.toset() __has = deepcopy(self.__has) # simply add to a set. __has.update(val) return __has
python
def __add(self, val): """ Helper method for range addition. It is allowed to add only one compact subrange or ``range_t`` object at once. Parameters ---------- val : int or tuple or list or range Integer or range to add. Returns ------- __has : set ``self.__has`` extended by `val`. """ if not isinstance(val, range_t): #sanitize it val = {self.__val_convert(val)} # convert to a set, coz I like it that way. else: val = val.toset() __has = deepcopy(self.__has) # simply add to a set. __has.update(val) return __has
[ "def", "__add", "(", "self", ",", "val", ")", ":", "if", "not", "isinstance", "(", "val", ",", "range_t", ")", ":", "#sanitize it", "val", "=", "{", "self", ".", "__val_convert", "(", "val", ")", "}", "# convert to a set, coz I like it that way.", "else", ...
Helper method for range addition. It is allowed to add only one compact subrange or ``range_t`` object at once. Parameters ---------- val : int or tuple or list or range Integer or range to add. Returns ------- __has : set ``self.__has`` extended by `val`.
[ "Helper", "method", "for", "range", "addition", ".", "It", "is", "allowed", "to", "add", "only", "one", "compact", "subrange", "or", "range_t", "object", "at", "once", "." ]
67dd9536a1faea09c8394f697529124f78e77cfa
https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/range_t.py#L195-L221
train
35,235
proycon/pynlpl
pynlpl/evaluation.py
AbstractExperiment.done
def done(self, warn=True): """Is the subprocess done?""" if not self.process: raise Exception("Not implemented yet or process not started yet, make sure to overload the done() method in your Experiment class") self.process.poll() if self.process.returncode == None: return False elif self.process.returncode > 0: raise ProcessFailed() else: self.endtime = datetime.datetime.now() return True
python
def done(self, warn=True): """Is the subprocess done?""" if not self.process: raise Exception("Not implemented yet or process not started yet, make sure to overload the done() method in your Experiment class") self.process.poll() if self.process.returncode == None: return False elif self.process.returncode > 0: raise ProcessFailed() else: self.endtime = datetime.datetime.now() return True
[ "def", "done", "(", "self", ",", "warn", "=", "True", ")", ":", "if", "not", "self", ".", "process", ":", "raise", "Exception", "(", "\"Not implemented yet or process not started yet, make sure to overload the done() method in your Experiment class\"", ")", "self", ".", ...
Is the subprocess done?
[ "Is", "the", "subprocess", "done?" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/evaluation.py#L453-L464
train
35,236
proycon/pynlpl
pynlpl/formats/giza.py
GizaSentenceAlignment.getalignedtarget
def getalignedtarget(self, index): """Returns target range only if source index aligns to a single consecutive range of target tokens.""" targetindices = [] target = None foundindex = -1 for sourceindex, targetindex in self.alignment: if sourceindex == index: targetindices.append(targetindex) if len(targetindices) > 1: for i in range(1,len(targetindices)): if abs(targetindices[i] - targetindices[i-1]) != 1: break # not consecutive foundindex = (min(targetindices), max(targetindices)) target = ' '.join(self.target[min(targetindices):max(targetindices)+1]) elif targetindices: foundindex = targetindices[0] target = self.target[foundindex] return target, foundindex
python
def getalignedtarget(self, index): """Returns target range only if source index aligns to a single consecutive range of target tokens.""" targetindices = [] target = None foundindex = -1 for sourceindex, targetindex in self.alignment: if sourceindex == index: targetindices.append(targetindex) if len(targetindices) > 1: for i in range(1,len(targetindices)): if abs(targetindices[i] - targetindices[i-1]) != 1: break # not consecutive foundindex = (min(targetindices), max(targetindices)) target = ' '.join(self.target[min(targetindices):max(targetindices)+1]) elif targetindices: foundindex = targetindices[0] target = self.target[foundindex] return target, foundindex
[ "def", "getalignedtarget", "(", "self", ",", "index", ")", ":", "targetindices", "=", "[", "]", "target", "=", "None", "foundindex", "=", "-", "1", "for", "sourceindex", ",", "targetindex", "in", "self", ".", "alignment", ":", "if", "sourceindex", "==", ...
Returns target range only if source index aligns to a single consecutive range of target tokens.
[ "Returns", "target", "range", "only", "if", "source", "index", "aligns", "to", "a", "single", "consecutive", "range", "of", "target", "tokens", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/giza.py#L108-L126
train
35,237
proycon/pynlpl
pynlpl/formats/giza.py
WordAlignment.targetword
def targetword(self, index, targetwords, alignment): """Return the aligned targetword for a specified index in the source words""" if alignment[index]: return targetwords[alignment[index]] else: return None
python
def targetword(self, index, targetwords, alignment): """Return the aligned targetword for a specified index in the source words""" if alignment[index]: return targetwords[alignment[index]] else: return None
[ "def", "targetword", "(", "self", ",", "index", ",", "targetwords", ",", "alignment", ")", ":", "if", "alignment", "[", "index", "]", ":", "return", "targetwords", "[", "alignment", "[", "index", "]", "]", "else", ":", "return", "None" ]
Return the aligned targetword for a specified index in the source words
[ "Return", "the", "aligned", "targetword", "for", "a", "specified", "index", "in", "the", "source", "words" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/giza.py#L225-L230
train
35,238
proycon/pynlpl
pynlpl/formats/giza.py
MultiWordAlignment.targetwords
def targetwords(self, index, targetwords, alignment): """Return the aligned targetwords for a specified index in the source words""" return [ targetwords[x] for x in alignment[index] ]
python
def targetwords(self, index, targetwords, alignment): """Return the aligned targetwords for a specified index in the source words""" return [ targetwords[x] for x in alignment[index] ]
[ "def", "targetwords", "(", "self", ",", "index", ",", "targetwords", ",", "alignment", ")", ":", "return", "[", "targetwords", "[", "x", "]", "for", "x", "in", "alignment", "[", "index", "]", "]" ]
Return the aligned targetwords for a specified index in the source words
[ "Return", "the", "aligned", "targetwords", "for", "a", "specified", "index", "in", "the", "source", "words" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/giza.py#L274-L276
train
35,239
proycon/pynlpl
pynlpl/algorithms.py
sum_to_n
def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number """Produce all lists of `size` positive integers in decreasing order that add up to `n`.""" if size == 1: yield [n] return if limit is None: limit = n start = (n + size - 1) // size stop = min(limit, n - size + 1) + 1 for i in range(start, stop): for tail in sum_to_n(n - i, size - 1, i): yield [i] + tail
python
def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number """Produce all lists of `size` positive integers in decreasing order that add up to `n`.""" if size == 1: yield [n] return if limit is None: limit = n start = (n + size - 1) // size stop = min(limit, n - size + 1) + 1 for i in range(start, stop): for tail in sum_to_n(n - i, size - 1, i): yield [i] + tail
[ "def", "sum_to_n", "(", "n", ",", "size", ",", "limit", "=", "None", ")", ":", "#from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number", "if", "size", "==", "1", ":", "yield", "[", "n", "]", "return", "if", "limit", "is", "...
Produce all lists of `size` positive integers in decreasing order that add up to `n`.
[ "Produce", "all", "lists", "of", "size", "positive", "integers", "in", "decreasing", "order", "that", "add", "up", "to", "n", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/algorithms.py#L19-L31
train
35,240
proycon/pynlpl
pynlpl/formats/cql.py
TokenExpression.nfa
def nfa(self, nextstate): """Returns an initial state for an NFA""" if self.interval: mininterval, maxinterval = self.interval #pylint: disable=unpacking-non-sequence nextstate2 = nextstate for i in range(maxinterval): state = State(transitions=[(self,self.match, nextstate2)]) if i+1> mininterval: if nextstate is not nextstate2: state.transitions.append((self,self.match, nextstate)) if maxinterval == MAXINTERVAL: state.epsilon.append(state) break nextstate2 = state return state else: state = State(transitions=[(self,self.match, nextstate)]) return state
python
def nfa(self, nextstate): """Returns an initial state for an NFA""" if self.interval: mininterval, maxinterval = self.interval #pylint: disable=unpacking-non-sequence nextstate2 = nextstate for i in range(maxinterval): state = State(transitions=[(self,self.match, nextstate2)]) if i+1> mininterval: if nextstate is not nextstate2: state.transitions.append((self,self.match, nextstate)) if maxinterval == MAXINTERVAL: state.epsilon.append(state) break nextstate2 = state return state else: state = State(transitions=[(self,self.match, nextstate)]) return state
[ "def", "nfa", "(", "self", ",", "nextstate", ")", ":", "if", "self", ".", "interval", ":", "mininterval", ",", "maxinterval", "=", "self", ".", "interval", "#pylint: disable=unpacking-non-sequence", "nextstate2", "=", "nextstate", "for", "i", "in", "range", "(...
Returns an initial state for an NFA
[ "Returns", "an", "initial", "state", "for", "an", "NFA" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/cql.py#L170-L186
train
35,241
proycon/pynlpl
pynlpl/formats/cql.py
Query.nfa
def nfa(self): """convert the expression into an NFA""" finalstate = State(final=True) nextstate = finalstate for tokenexpr in reversed(self): state = tokenexpr.nfa(nextstate) nextstate = state return NFA(state)
python
def nfa(self): """convert the expression into an NFA""" finalstate = State(final=True) nextstate = finalstate for tokenexpr in reversed(self): state = tokenexpr.nfa(nextstate) nextstate = state return NFA(state)
[ "def", "nfa", "(", "self", ")", ":", "finalstate", "=", "State", "(", "final", "=", "True", ")", "nextstate", "=", "finalstate", "for", "tokenexpr", "in", "reversed", "(", "self", ")", ":", "state", "=", "tokenexpr", ".", "nfa", "(", "nextstate", ")", ...
convert the expression into an NFA
[ "convert", "the", "expression", "into", "an", "NFA" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/cql.py#L236-L243
train
35,242
proycon/pynlpl
pynlpl/statistics.py
stddev
def stddev(values, meanval=None): #from AI: A Modern Appproach """The standard deviation of a set of values. Pass in the mean if you already know it.""" if meanval == None: meanval = mean(values) return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) )
python
def stddev(values, meanval=None): #from AI: A Modern Appproach """The standard deviation of a set of values. Pass in the mean if you already know it.""" if meanval == None: meanval = mean(values) return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) )
[ "def", "stddev", "(", "values", ",", "meanval", "=", "None", ")", ":", "#from AI: A Modern Appproach", "if", "meanval", "==", "None", ":", "meanval", "=", "mean", "(", "values", ")", "return", "math", ".", "sqrt", "(", "sum", "(", "[", "(", "x", "-", ...
The standard deviation of a set of values. Pass in the mean if you already know it.
[ "The", "standard", "deviation", "of", "a", "set", "of", "values", ".", "Pass", "in", "the", "mean", "if", "you", "already", "know", "it", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L588-L592
train
35,243
proycon/pynlpl
pynlpl/statistics.py
FrequencyList.save
def save(self, filename, addnormalised=False): """Save a frequency list to file, can be loaded later using the load method""" f = io.open(filename,'w',encoding='utf-8') for line in self.output("\t", addnormalised): f.write(line + '\n') f.close()
python
def save(self, filename, addnormalised=False): """Save a frequency list to file, can be loaded later using the load method""" f = io.open(filename,'w',encoding='utf-8') for line in self.output("\t", addnormalised): f.write(line + '\n') f.close()
[ "def", "save", "(", "self", ",", "filename", ",", "addnormalised", "=", "False", ")", ":", "f", "=", "io", ".", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "for", "line", "in", "self", ".", "output", "(", "\"\\t\"", "...
Save a frequency list to file, can be loaded later using the load method
[ "Save", "a", "frequency", "list", "to", "file", "can", "be", "loaded", "later", "using", "the", "load", "method" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L64-L69
train
35,244
proycon/pynlpl
pynlpl/statistics.py
FrequencyList.output
def output(self,delimiter = '\t', addnormalised=False): """Print a representation of the frequency list""" for type, count in self: if isinstance(type,tuple) or isinstance(type,list): if addnormalised: yield " ".join((u(x) for x in type)) + delimiter + str(count) + delimiter + str(count/self.total) else: yield " ".join((u(x) for x in type)) + delimiter + str(count) elif isstring(type): if addnormalised: yield type + delimiter + str(count) + delimiter + str(count/self.total) else: yield type + delimiter + str(count) else: if addnormalised: yield str(type) + delimiter + str(count) + delimiter + str(count/self.total) else: yield str(type) + delimiter + str(count)
python
def output(self,delimiter = '\t', addnormalised=False): """Print a representation of the frequency list""" for type, count in self: if isinstance(type,tuple) or isinstance(type,list): if addnormalised: yield " ".join((u(x) for x in type)) + delimiter + str(count) + delimiter + str(count/self.total) else: yield " ".join((u(x) for x in type)) + delimiter + str(count) elif isstring(type): if addnormalised: yield type + delimiter + str(count) + delimiter + str(count/self.total) else: yield type + delimiter + str(count) else: if addnormalised: yield str(type) + delimiter + str(count) + delimiter + str(count/self.total) else: yield str(type) + delimiter + str(count)
[ "def", "output", "(", "self", ",", "delimiter", "=", "'\\t'", ",", "addnormalised", "=", "False", ")", ":", "for", "type", ",", "count", "in", "self", ":", "if", "isinstance", "(", "type", ",", "tuple", ")", "or", "isinstance", "(", "type", ",", "lis...
Print a representation of the frequency list
[ "Print", "a", "representation", "of", "the", "frequency", "list" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L182-L199
train
35,245
proycon/pynlpl
pynlpl/statistics.py
Distribution.entropy
def entropy(self, base = 2): """Compute the entropy of the distribution""" entropy = 0 if not base and self.base: base = self.base for type in self._dist: if not base: entropy += self._dist[type] * -math.log(self._dist[type]) else: entropy += self._dist[type] * -math.log(self._dist[type], base) return entropy
python
def entropy(self, base = 2): """Compute the entropy of the distribution""" entropy = 0 if not base and self.base: base = self.base for type in self._dist: if not base: entropy += self._dist[type] * -math.log(self._dist[type]) else: entropy += self._dist[type] * -math.log(self._dist[type], base) return entropy
[ "def", "entropy", "(", "self", ",", "base", "=", "2", ")", ":", "entropy", "=", "0", "if", "not", "base", "and", "self", ".", "base", ":", "base", "=", "self", ".", "base", "for", "type", "in", "self", ".", "_dist", ":", "if", "not", "base", ":...
Compute the entropy of the distribution
[ "Compute", "the", "entropy", "of", "the", "distribution" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L270-L279
train
35,246
proycon/pynlpl
pynlpl/statistics.py
Distribution.output
def output(self,delimiter = '\t', freqlist = None): """Generator yielding formatted strings expressing the time and probabily for each item in the distribution""" for type, prob in self: if freqlist: if isinstance(type,list) or isinstance(type, tuple): yield " ".join(type) + delimiter + str(freqlist[type]) + delimiter + str(prob) else: yield type + delimiter + str(freqlist[type]) + delimiter + str(prob) else: if isinstance(type,list) or isinstance(type, tuple): yield " ".join(type) + delimiter + str(prob) else: yield type + delimiter + str(prob)
python
def output(self,delimiter = '\t', freqlist = None): """Generator yielding formatted strings expressing the time and probabily for each item in the distribution""" for type, prob in self: if freqlist: if isinstance(type,list) or isinstance(type, tuple): yield " ".join(type) + delimiter + str(freqlist[type]) + delimiter + str(prob) else: yield type + delimiter + str(freqlist[type]) + delimiter + str(prob) else: if isinstance(type,list) or isinstance(type, tuple): yield " ".join(type) + delimiter + str(prob) else: yield type + delimiter + str(prob)
[ "def", "output", "(", "self", ",", "delimiter", "=", "'\\t'", ",", "freqlist", "=", "None", ")", ":", "for", "type", ",", "prob", "in", "self", ":", "if", "freqlist", ":", "if", "isinstance", "(", "type", ",", "list", ")", "or", "isinstance", "(", ...
Generator yielding formatted strings expressing the time and probabily for each item in the distribution
[ "Generator", "yielding", "formatted", "strings", "expressing", "the", "time", "and", "probabily", "for", "each", "item", "in", "the", "distribution" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L316-L328
train
35,247
proycon/pynlpl
pynlpl/clients/freeling.py
FreeLingClient.process
def process(self, sourcewords, debug=False): """Process a list of words, passing it to the server and realigning the output with the original words""" if isinstance( sourcewords, list ) or isinstance( sourcewords, tuple ): sourcewords_s = " ".join(sourcewords) else: sourcewords_s = sourcewords sourcewords = sourcewords.split(' ') self.socket.sendall(sourcewords_s.encode(self.encoding) +'\n\0') if debug: print("Sent:",sourcewords_s.encode(self.encoding),file=sys.stderr) results = [] done = False while not done: data = b"" while not data: buffer = self.socket.recv(self.BUFSIZE) if debug: print("Buffer: ["+repr(buffer)+"]",file=sys.stderr) if buffer[-1] == '\0': data += buffer[:-1] done = True break else: data += buffer data = u(data,self.encoding) if debug: print("Received:",data,file=sys.stderr) for i, line in enumerate(data.strip(' \t\0\r\n').split('\n')): if not line.strip(): done = True break else: cols = line.split(" ") subwords = cols[0].lower().split("_") if len(cols) > 2: #this seems a bit odd? for word in subwords: #split multiword expressions results.append( (word, cols[1], cols[2], i, len(subwords) > 1 ) ) #word, lemma, pos, index, multiword? sourcewords = [ w.lower() for w in sourcewords ] alignment = [] for i, sourceword in enumerate(sourcewords): found = False best = 0 distance = 999999 for j, (targetword, lemma, pos, index, multiword) in enumerate(results): if sourceword == targetword and abs(i-j) < distance: found = True best = j distance = abs(i-j) if found: alignment.append(results[best]) else: alignment.append((None,None,None,None,False)) #no alignment found return alignment
python
def process(self, sourcewords, debug=False): """Process a list of words, passing it to the server and realigning the output with the original words""" if isinstance( sourcewords, list ) or isinstance( sourcewords, tuple ): sourcewords_s = " ".join(sourcewords) else: sourcewords_s = sourcewords sourcewords = sourcewords.split(' ') self.socket.sendall(sourcewords_s.encode(self.encoding) +'\n\0') if debug: print("Sent:",sourcewords_s.encode(self.encoding),file=sys.stderr) results = [] done = False while not done: data = b"" while not data: buffer = self.socket.recv(self.BUFSIZE) if debug: print("Buffer: ["+repr(buffer)+"]",file=sys.stderr) if buffer[-1] == '\0': data += buffer[:-1] done = True break else: data += buffer data = u(data,self.encoding) if debug: print("Received:",data,file=sys.stderr) for i, line in enumerate(data.strip(' \t\0\r\n').split('\n')): if not line.strip(): done = True break else: cols = line.split(" ") subwords = cols[0].lower().split("_") if len(cols) > 2: #this seems a bit odd? for word in subwords: #split multiword expressions results.append( (word, cols[1], cols[2], i, len(subwords) > 1 ) ) #word, lemma, pos, index, multiword? sourcewords = [ w.lower() for w in sourcewords ] alignment = [] for i, sourceword in enumerate(sourcewords): found = False best = 0 distance = 999999 for j, (targetword, lemma, pos, index, multiword) in enumerate(results): if sourceword == targetword and abs(i-j) < distance: found = True best = j distance = abs(i-j) if found: alignment.append(results[best]) else: alignment.append((None,None,None,None,False)) #no alignment found return alignment
[ "def", "process", "(", "self", ",", "sourcewords", ",", "debug", "=", "False", ")", ":", "if", "isinstance", "(", "sourcewords", ",", "list", ")", "or", "isinstance", "(", "sourcewords", ",", "tuple", ")", ":", "sourcewords_s", "=", "\" \"", ".", "join",...
Process a list of words, passing it to the server and realigning the output with the original words
[ "Process", "a", "list", "of", "words", "passing", "it", "to", "the", "server", "and", "realigning", "the", "output", "with", "the", "original", "words" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/freeling.py#L43-L101
train
35,248
proycon/pynlpl
pynlpl/formats/folia.py
checkversion
def checkversion(version, REFVERSION=FOLIAVERSION): """Checks FoLiA version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal""" try: for refversion, docversion in zip([int(x) for x in REFVERSION.split('.')], [int(x) for x in version.split('.')]): if docversion > refversion: return 1 #doc is newer than library elif docversion < refversion: return -1 #doc is older than library return 0 #versions are equal except ValueError: raise ValueError("Unable to parse document FoLiA version, invalid syntax")
python
def checkversion(version, REFVERSION=FOLIAVERSION): """Checks FoLiA version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal""" try: for refversion, docversion in zip([int(x) for x in REFVERSION.split('.')], [int(x) for x in version.split('.')]): if docversion > refversion: return 1 #doc is newer than library elif docversion < refversion: return -1 #doc is older than library return 0 #versions are equal except ValueError: raise ValueError("Unable to parse document FoLiA version, invalid syntax")
[ "def", "checkversion", "(", "version", ",", "REFVERSION", "=", "FOLIAVERSION", ")", ":", "try", ":", "for", "refversion", ",", "docversion", "in", "zip", "(", "[", "int", "(", "x", ")", "for", "x", "in", "REFVERSION", ".", "split", "(", "'.'", ")", "...
Checks FoLiA version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal
[ "Checks", "FoLiA", "version", "returns", "1", "if", "the", "document", "is", "newer", "than", "the", "library", "-", "1", "if", "it", "is", "older", "0", "if", "it", "is", "equal" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L199-L209
train
35,249
proycon/pynlpl
pynlpl/formats/folia.py
xmltreefromstring
def xmltreefromstring(s): """Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml""" if sys.version < '3': #Python 2 if isinstance(s,unicode): #pylint: disable=undefined-variable s = s.encode('utf-8') try: return ElementTree.parse(StringIO(s), ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(StringIO(s), ElementTree.XMLParser()) #older lxml, may leak!!!! else: #Python 3 if isinstance(s,str): s = s.encode('utf-8') try: return ElementTree.parse(BytesIO(s), ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(BytesIO(s), ElementTree.XMLParser())
python
def xmltreefromstring(s): """Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml""" if sys.version < '3': #Python 2 if isinstance(s,unicode): #pylint: disable=undefined-variable s = s.encode('utf-8') try: return ElementTree.parse(StringIO(s), ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(StringIO(s), ElementTree.XMLParser()) #older lxml, may leak!!!! else: #Python 3 if isinstance(s,str): s = s.encode('utf-8') try: return ElementTree.parse(BytesIO(s), ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(BytesIO(s), ElementTree.XMLParser())
[ "def", "xmltreefromstring", "(", "s", ")", ":", "if", "sys", ".", "version", "<", "'3'", ":", "#Python 2", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "#pylint: disable=undefined-variable", "s", "=", "s", ".", "encode", "(", "'utf-8'", ")", "...
Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml
[ "Internal", "function", "deals", "with", "different", "Python", "versions", "unicode", "strings", "versus", "bytes", "and", "with", "the", "leak", "bug", "in", "lxml" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L543-L560
train
35,250
proycon/pynlpl
pynlpl/formats/folia.py
xmltreefromfile
def xmltreefromfile(filename): """Internal function to read an XML file""" try: return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(filename, ElementTree.XMLParser())
python
def xmltreefromfile(filename): """Internal function to read an XML file""" try: return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(filename, ElementTree.XMLParser())
[ "def", "xmltreefromfile", "(", "filename", ")", ":", "try", ":", "return", "ElementTree", ".", "parse", "(", "filename", ",", "ElementTree", ".", "XMLParser", "(", "collect_ids", "=", "False", ")", ")", "except", "TypeError", ":", "return", "ElementTree", "....
Internal function to read an XML file
[ "Internal", "function", "to", "read", "an", "XML", "file" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L562-L567
train
35,251
proycon/pynlpl
pynlpl/formats/folia.py
commonancestors
def commonancestors(Class, *args): """Generator function to find common ancestors of a particular type for any two or more FoLiA element instances. The function produces all common ancestors of the type specified, starting from the closest one up to the most distant one. Parameters: Class: The type of ancestor to find, should be the :class:`AbstractElement` class or any subclass thereof (not an instance!) *args: The elements to find the common ancestors of, elements are instances derived from :class:`AbstractElement` Yields: instance derived from :class:`AbstractElement`: A common ancestor of the arguments, an instance of the specified ``Class``. """ commonancestors = None #pylint: disable=redefined-outer-name for sibling in args: ancestors = list( sibling.ancestors(Class) ) if commonancestors is None: commonancestors = copy(ancestors) else: removeancestors = [] for a in commonancestors: #pylint: disable=not-an-iterable if not a in ancestors: removeancestors.append(a) for a in removeancestors: commonancestors.remove(a) if commonancestors: for commonancestor in commonancestors: yield commonancestor
python
def commonancestors(Class, *args): """Generator function to find common ancestors of a particular type for any two or more FoLiA element instances. The function produces all common ancestors of the type specified, starting from the closest one up to the most distant one. Parameters: Class: The type of ancestor to find, should be the :class:`AbstractElement` class or any subclass thereof (not an instance!) *args: The elements to find the common ancestors of, elements are instances derived from :class:`AbstractElement` Yields: instance derived from :class:`AbstractElement`: A common ancestor of the arguments, an instance of the specified ``Class``. """ commonancestors = None #pylint: disable=redefined-outer-name for sibling in args: ancestors = list( sibling.ancestors(Class) ) if commonancestors is None: commonancestors = copy(ancestors) else: removeancestors = [] for a in commonancestors: #pylint: disable=not-an-iterable if not a in ancestors: removeancestors.append(a) for a in removeancestors: commonancestors.remove(a) if commonancestors: for commonancestor in commonancestors: yield commonancestor
[ "def", "commonancestors", "(", "Class", ",", "*", "args", ")", ":", "commonancestors", "=", "None", "#pylint: disable=redefined-outer-name", "for", "sibling", "in", "args", ":", "ancestors", "=", "list", "(", "sibling", ".", "ancestors", "(", "Class", ")", ")"...
Generator function to find common ancestors of a particular type for any two or more FoLiA element instances. The function produces all common ancestors of the type specified, starting from the closest one up to the most distant one. Parameters: Class: The type of ancestor to find, should be the :class:`AbstractElement` class or any subclass thereof (not an instance!) *args: The elements to find the common ancestors of, elements are instances derived from :class:`AbstractElement` Yields: instance derived from :class:`AbstractElement`: A common ancestor of the arguments, an instance of the specified ``Class``.
[ "Generator", "function", "to", "find", "common", "ancestors", "of", "a", "particular", "type", "for", "any", "two", "or", "more", "FoLiA", "element", "instances", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L594-L621
train
35,252
proycon/pynlpl
pynlpl/formats/folia.py
AbstractElement.description
def description(self): """Obtain the description associated with the element. Raises: :class:`NoSuchAnnotation` if there is no associated description.""" for e in self: if isinstance(e, Description): return e.value raise NoSuchAnnotation
python
def description(self): """Obtain the description associated with the element. Raises: :class:`NoSuchAnnotation` if there is no associated description.""" for e in self: if isinstance(e, Description): return e.value raise NoSuchAnnotation
[ "def", "description", "(", "self", ")", ":", "for", "e", "in", "self", ":", "if", "isinstance", "(", "e", ",", "Description", ")", ":", "return", "e", ".", "value", "raise", "NoSuchAnnotation" ]
Obtain the description associated with the element. Raises: :class:`NoSuchAnnotation` if there is no associated description.
[ "Obtain", "the", "description", "associated", "with", "the", "element", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L722-L730
train
35,253
proycon/pynlpl
pynlpl/formats/folia.py
AbstractElement.findcorrectionhandling
def findcorrectionhandling(self, cls): """Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused""" if cls == "current": return CorrectionHandling.CURRENT elif cls == "original": return CorrectionHandling.ORIGINAL #backward compatibility else: correctionhandling = None #but any other class may be anything #Do we have corrections at all? otherwise no need to bother for correction in self.select(Correction): #yes, in which branch is the text class found? found = False hastext = False if correction.hasnew(): found = True doublecorrection = correction.new().count(Correction) > 0 if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now for t in correction.new().select(TextContent): hastext = True if t.cls == cls: if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT: return None #inconsistent else: correctionhandling = CorrectionHandling.CURRENT break elif correction.hascurrent(): found = True doublecorrection = correction.current().count(Correction) > 0 if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now for t in correction.current().select(TextContent): hastext = True if t.cls == cls: if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT: return None #inconsistent else: correctionhandling = CorrectionHandling.CURRENT break if correction.hasoriginal(): found = True doublecorrection = correction.original().count(Correction) > 0 if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now for t in correction.original().select(TextContent): hastext = True if t.cls == cls: if correctionhandling is not None and correctionhandling != CorrectionHandling.ORIGINAL: return None #inconsistent else: correctionhandling = CorrectionHandling.ORIGINAL break if correctionhandling is None: #well, we couldn't find our textclass in any correction, just fall back to current and let text validation fail if needed return CorrectionHandling.CURRENT
python
def findcorrectionhandling(self, cls): """Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused""" if cls == "current": return CorrectionHandling.CURRENT elif cls == "original": return CorrectionHandling.ORIGINAL #backward compatibility else: correctionhandling = None #but any other class may be anything #Do we have corrections at all? otherwise no need to bother for correction in self.select(Correction): #yes, in which branch is the text class found? found = False hastext = False if correction.hasnew(): found = True doublecorrection = correction.new().count(Correction) > 0 if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now for t in correction.new().select(TextContent): hastext = True if t.cls == cls: if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT: return None #inconsistent else: correctionhandling = CorrectionHandling.CURRENT break elif correction.hascurrent(): found = True doublecorrection = correction.current().count(Correction) > 0 if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now for t in correction.current().select(TextContent): hastext = True if t.cls == cls: if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT: return None #inconsistent else: correctionhandling = CorrectionHandling.CURRENT break if correction.hasoriginal(): found = True doublecorrection = correction.original().count(Correction) > 0 if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now for t in correction.original().select(TextContent): hastext = True if t.cls == cls: if correctionhandling is not None and correctionhandling != CorrectionHandling.ORIGINAL: return None #inconsistent else: correctionhandling = CorrectionHandling.ORIGINAL break if correctionhandling is None: #well, we couldn't find our textclass in any correction, just fall back to current and let text validation fail if needed return CorrectionHandling.CURRENT
[ "def", "findcorrectionhandling", "(", "self", ",", "cls", ")", ":", "if", "cls", "==", "\"current\"", ":", "return", "CorrectionHandling", ".", "CURRENT", "elif", "cls", "==", "\"original\"", ":", "return", "CorrectionHandling", ".", "ORIGINAL", "#backward compati...
Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused
[ "Find", "the", "proper", "correctionhandling", "given", "a", "textclass", "by", "looking", "in", "the", "underlying", "corrections", "where", "it", "is", "reused" ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L774-L826
train
35,254
proycon/pynlpl
pynlpl/formats/folia.py
AbstractElement.textvalidation
def textvalidation(self, warnonly=None): """Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid. Parameters: warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5) Returns: bool """ if warnonly is None and self.doc and self.doc.version: warnonly = (checkversion(self.doc.version, '1.5.0') < 0) #warn only for documents older than FoLiA v1.5 valid = True for cls in self.doc.textclasses: if self.hastext(cls, strict=True) and not isinstance(self, (Linebreak, Whitespace)): if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Text validation on " + repr(self),file=stderr) correctionhandling = self.findcorrectionhandling(cls) if correctionhandling is None: #skipping text validation, correction is too complex (nested) to handle for now; just assume valid (benefit of the doubt) if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] SKIPPING Text validation on " + repr(self) + ", too complex to handle (nested corrections or inconsistent use)",file=stderr) return True #just assume it's valid then strictnormtext = self.text(cls,retaintokenisation=False,strict=True, normalize_spaces=True) deepnormtext = self.text(cls,retaintokenisation=False,strict=False, normalize_spaces=True) if strictnormtext != deepnormtext: valid = False deviation = 0 for i, (c1,c2) in enumerate(zip(strictnormtext,deepnormtext)): if c1 != c2: deviation = i break msg = "Text for " + self.__class__.__name__ + ", ID " + str(self.id) + ", class " + cls + ", is inconsistent: EXPECTED (after normalization) *****>\n" + deepnormtext + "\n****> BUT FOUND (after normalization) ****>\n" + strictnormtext + "\n******* DEVIATION POINT: " + strictnormtext[max(0,deviation-10):deviation] + "<*HERE*>" + strictnormtext[deviation:deviation+10] if warnonly: print("TEXT VALIDATION ERROR: " + msg,file=sys.stderr) else: raise InconsistentText(msg) #validate offsets tc = self.textcontent(cls) if tc.offset is not None: #we can't validate the reference of this element yet since it may point to higher level elements still being created!! we store it in a buffer that will #be processed by pendingvalidation() after parsing and prior to serialisation if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Queing element for later offset validation: " + repr(self),file=stderr) self.doc.offsetvalidationbuffer.append( (self, cls) ) return valid
python
def textvalidation(self, warnonly=None): """Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid. Parameters: warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5) Returns: bool """ if warnonly is None and self.doc and self.doc.version: warnonly = (checkversion(self.doc.version, '1.5.0') < 0) #warn only for documents older than FoLiA v1.5 valid = True for cls in self.doc.textclasses: if self.hastext(cls, strict=True) and not isinstance(self, (Linebreak, Whitespace)): if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Text validation on " + repr(self),file=stderr) correctionhandling = self.findcorrectionhandling(cls) if correctionhandling is None: #skipping text validation, correction is too complex (nested) to handle for now; just assume valid (benefit of the doubt) if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] SKIPPING Text validation on " + repr(self) + ", too complex to handle (nested corrections or inconsistent use)",file=stderr) return True #just assume it's valid then strictnormtext = self.text(cls,retaintokenisation=False,strict=True, normalize_spaces=True) deepnormtext = self.text(cls,retaintokenisation=False,strict=False, normalize_spaces=True) if strictnormtext != deepnormtext: valid = False deviation = 0 for i, (c1,c2) in enumerate(zip(strictnormtext,deepnormtext)): if c1 != c2: deviation = i break msg = "Text for " + self.__class__.__name__ + ", ID " + str(self.id) + ", class " + cls + ", is inconsistent: EXPECTED (after normalization) *****>\n" + deepnormtext + "\n****> BUT FOUND (after normalization) ****>\n" + strictnormtext + "\n******* DEVIATION POINT: " + strictnormtext[max(0,deviation-10):deviation] + "<*HERE*>" + strictnormtext[deviation:deviation+10] if warnonly: print("TEXT VALIDATION ERROR: " + msg,file=sys.stderr) else: raise InconsistentText(msg) #validate offsets tc = self.textcontent(cls) if tc.offset is not None: #we can't validate the reference of this element yet since it may point to higher level elements still being created!! we store it in a buffer that will #be processed by pendingvalidation() after parsing and prior to serialisation if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Queing element for later offset validation: " + repr(self),file=stderr) self.doc.offsetvalidationbuffer.append( (self, cls) ) return valid
[ "def", "textvalidation", "(", "self", ",", "warnonly", "=", "None", ")", ":", "if", "warnonly", "is", "None", "and", "self", ".", "doc", "and", "self", ".", "doc", ".", "version", ":", "warnonly", "=", "(", "checkversion", "(", "self", ".", "doc", "....
Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid. Parameters: warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5) Returns: bool
[ "Run", "text", "validation", "on", "this", "element", ".", "Checks", "whether", "any", "text", "redundancy", "is", "consistent", "and", "whether", "offsets", "are", "valid", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L829-L873
train
35,255
proycon/pynlpl
pynlpl/formats/folia.py
AbstractElement.speech_speaker
def speech_speaker(self): """Retrieves the speaker of the audio or video file associated with the element. The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly. Returns: str or None if not found """ if self.speaker: return self.speaker elif self.parent: return self.parent.speech_speaker() else: return None
python
def speech_speaker(self): """Retrieves the speaker of the audio or video file associated with the element. The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly. Returns: str or None if not found """ if self.speaker: return self.speaker elif self.parent: return self.parent.speech_speaker() else: return None
[ "def", "speech_speaker", "(", "self", ")", ":", "if", "self", ".", "speaker", ":", "return", "self", ".", "speaker", "elif", "self", ".", "parent", ":", "return", "self", ".", "parent", ".", "speech_speaker", "(", ")", "else", ":", "return", "None" ]
Retrieves the speaker of the audio or video file associated with the element. The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly. Returns: str or None if not found
[ "Retrieves", "the", "speaker", "of", "the", "audio", "or", "video", "file", "associated", "with", "the", "element", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1004-L1017
train
35,256
proycon/pynlpl
pynlpl/formats/folia.py
AbstractElement.feat
def feat(self,subset): """Obtain the feature class value of the specific subset. If a feature occurs multiple times, the values will be returned in a list. Example:: sense = word.annotation(folia.Sense) synset = sense.feat('synset') Returns: str or list """ r = None for f in self: if isinstance(f, Feature) and f.subset == subset: if r: #support for multiclass features if isinstance(r,list): r.append(f.cls) else: r = [r, f.cls] else: r = f.cls if r is None: raise NoSuchAnnotation else: return r
python
def feat(self,subset): """Obtain the feature class value of the specific subset. If a feature occurs multiple times, the values will be returned in a list. Example:: sense = word.annotation(folia.Sense) synset = sense.feat('synset') Returns: str or list """ r = None for f in self: if isinstance(f, Feature) and f.subset == subset: if r: #support for multiclass features if isinstance(r,list): r.append(f.cls) else: r = [r, f.cls] else: r = f.cls if r is None: raise NoSuchAnnotation else: return r
[ "def", "feat", "(", "self", ",", "subset", ")", ":", "r", "=", "None", "for", "f", "in", "self", ":", "if", "isinstance", "(", "f", ",", "Feature", ")", "and", "f", ".", "subset", "==", "subset", ":", "if", "r", ":", "#support for multiclass features...
Obtain the feature class value of the specific subset. If a feature occurs multiple times, the values will be returned in a list. Example:: sense = word.annotation(folia.Sense) synset = sense.feat('synset') Returns: str or list
[ "Obtain", "the", "feature", "class", "value", "of", "the", "specific", "subset", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1114-L1140
train
35,257
proycon/pynlpl
pynlpl/formats/folia.py
AbstractElement.copy
def copy(self, newdoc=None, idsuffix=""): """Make a deep copy of this element and all its children. Parameters: newdoc (:class:`Document`): The document the copy should be associated with. idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (prevents duplicate IDs when making copies for the same document). If set to ``True``, a random suffix will be generated. Returns: a copy of the element """ if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children c = deepcopy(self) if idsuffix: c.addidsuffix(idsuffix) c.setparents() c.setdoc(newdoc) return c
python
def copy(self, newdoc=None, idsuffix=""): """Make a deep copy of this element and all its children. Parameters: newdoc (:class:`Document`): The document the copy should be associated with. idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (prevents duplicate IDs when making copies for the same document). If set to ``True``, a random suffix will be generated. Returns: a copy of the element """ if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children c = deepcopy(self) if idsuffix: c.addidsuffix(idsuffix) c.setparents() c.setdoc(newdoc) return c
[ "def", "copy", "(", "self", ",", "newdoc", "=", "None", ",", "idsuffix", "=", "\"\"", ")", ":", "if", "idsuffix", "is", "True", ":", "idsuffix", "=", "\".copy.\"", "+", "\"%08x\"", "%", "random", ".", "getrandbits", "(", "32", ")", "#random 32-bit hash f...
Make a deep copy of this element and all its children. Parameters: newdoc (:class:`Document`): The document the copy should be associated with. idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (prevents duplicate IDs when making copies for the same document). If set to ``True``, a random suffix will be generated. Returns: a copy of the element
[ "Make", "a", "deep", "copy", "of", "this", "element", "and", "all", "its", "children", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1234-L1250
train
35,258
proycon/pynlpl
pynlpl/formats/folia.py
AbstractElement.copychildren
def copychildren(self, newdoc=None, idsuffix=""): """Generator creating a deep copy of the children of this element. Invokes :meth:`copy` on all children, parameters are the same. """ if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children for c in self: if isinstance(c, AbstractElement): yield c.copy(newdoc,idsuffix)
python
def copychildren(self, newdoc=None, idsuffix=""): """Generator creating a deep copy of the children of this element. Invokes :meth:`copy` on all children, parameters are the same. """ if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children for c in self: if isinstance(c, AbstractElement): yield c.copy(newdoc,idsuffix)
[ "def", "copychildren", "(", "self", ",", "newdoc", "=", "None", ",", "idsuffix", "=", "\"\"", ")", ":", "if", "idsuffix", "is", "True", ":", "idsuffix", "=", "\".copy.\"", "+", "\"%08x\"", "%", "random", ".", "getrandbits", "(", "32", ")", "#random 32-bi...
Generator creating a deep copy of the children of this element. Invokes :meth:`copy` on all children, parameters are the same.
[ "Generator", "creating", "a", "deep", "copy", "of", "the", "children", "of", "this", "element", "." ]
7707f69a91caaa6cde037f0d0379f1d42500a68b
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1252-L1260
train
35,259
noxdafox/clipspy
clips/classes.py
ClassSlot.public
def public(self): """True if the Slot is public.""" return bool(lib.EnvSlotPublicP(self._env, self._cls, self._name))
python
def public(self): """True if the Slot is public.""" return bool(lib.EnvSlotPublicP(self._env, self._cls, self._name))
[ "def", "public", "(", "self", ")", ":", "return", "bool", "(", "lib", ".", "EnvSlotPublicP", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ")", ")" ]
True if the Slot is public.
[ "True", "if", "the", "Slot", "is", "public", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L441-L443
train
35,260
noxdafox/clipspy
clips/classes.py
ClassSlot.initializable
def initializable(self): """True if the Slot is initializable.""" return bool(lib.EnvSlotInitableP(self._env, self._cls, self._name))
python
def initializable(self): """True if the Slot is initializable.""" return bool(lib.EnvSlotInitableP(self._env, self._cls, self._name))
[ "def", "initializable", "(", "self", ")", ":", "return", "bool", "(", "lib", ".", "EnvSlotInitableP", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ")", ")" ]
True if the Slot is initializable.
[ "True", "if", "the", "Slot", "is", "initializable", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L446-L448
train
35,261
noxdafox/clipspy
clips/classes.py
ClassSlot.writable
def writable(self): """True if the Slot is writable.""" return bool(lib.EnvSlotWritableP(self._env, self._cls, self._name))
python
def writable(self): """True if the Slot is writable.""" return bool(lib.EnvSlotWritableP(self._env, self._cls, self._name))
[ "def", "writable", "(", "self", ")", ":", "return", "bool", "(", "lib", ".", "EnvSlotWritableP", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ")", ")" ]
True if the Slot is writable.
[ "True", "if", "the", "Slot", "is", "writable", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L451-L453
train
35,262
noxdafox/clipspy
clips/classes.py
ClassSlot.accessible
def accessible(self): """True if the Slot is directly accessible.""" return bool(lib.EnvSlotDirectAccessP(self._env, self._cls, self._name))
python
def accessible(self): """True if the Slot is directly accessible.""" return bool(lib.EnvSlotDirectAccessP(self._env, self._cls, self._name))
[ "def", "accessible", "(", "self", ")", ":", "return", "bool", "(", "lib", ".", "EnvSlotDirectAccessP", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ")", ")" ]
True if the Slot is directly accessible.
[ "True", "if", "the", "Slot", "is", "directly", "accessible", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L456-L458
train
35,263
noxdafox/clipspy
clips/classes.py
ClassSlot.sources
def sources(self): """A tuple containing the names of the Class sources for this Slot. The Python equivalent of the CLIPS slot-sources function. """ data = clips.data.DataObject(self._env) lib.EnvSlotSources(self._env, self._cls, self._name, data.byref) return tuple(data.value) if isinstance(data.value, list) else ()
python
def sources(self): """A tuple containing the names of the Class sources for this Slot. The Python equivalent of the CLIPS slot-sources function. """ data = clips.data.DataObject(self._env) lib.EnvSlotSources(self._env, self._cls, self._name, data.byref) return tuple(data.value) if isinstance(data.value, list) else ()
[ "def", "sources", "(", "self", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "lib", ".", "EnvSlotSources", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ",", "data", ...
A tuple containing the names of the Class sources for this Slot. The Python equivalent of the CLIPS slot-sources function.
[ "A", "tuple", "containing", "the", "names", "of", "the", "Class", "sources", "for", "this", "Slot", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L474-L484
train
35,264
noxdafox/clipspy
clips/classes.py
ClassSlot.facets
def facets(self): """A tuple containing the facets for this Slot. The Python equivalent of the CLIPS slot-facets function. """ data = clips.data.DataObject(self._env) lib.EnvSlotFacets(self._env, self._cls, self._name, data.byref) return tuple(data.value) if isinstance(data.value, list) else ()
python
def facets(self): """A tuple containing the facets for this Slot. The Python equivalent of the CLIPS slot-facets function. """ data = clips.data.DataObject(self._env) lib.EnvSlotFacets(self._env, self._cls, self._name, data.byref) return tuple(data.value) if isinstance(data.value, list) else ()
[ "def", "facets", "(", "self", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "lib", ".", "EnvSlotFacets", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ",", "data", ...
A tuple containing the facets for this Slot. The Python equivalent of the CLIPS slot-facets function.
[ "A", "tuple", "containing", "the", "facets", "for", "this", "Slot", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L500-L510
train
35,265
noxdafox/clipspy
clips/classes.py
ClassSlot.allowed_classes
def allowed_classes(self): """Iterate over the allowed classes for this slot. The Python equivalent of the CLIPS slot-allowed-classes function. """ data = clips.data.DataObject(self._env) lib.EnvSlotAllowedClasses( self._env, self._cls, self._name, data.byref) if isinstance(data.value, list): for klass in classes(self._env, data.value): yield klass
python
def allowed_classes(self): """Iterate over the allowed classes for this slot. The Python equivalent of the CLIPS slot-allowed-classes function. """ data = clips.data.DataObject(self._env) lib.EnvSlotAllowedClasses( self._env, self._cls, self._name, data.byref) if isinstance(data.value, list): for klass in classes(self._env, data.value): yield klass
[ "def", "allowed_classes", "(", "self", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "lib", ".", "EnvSlotAllowedClasses", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ...
Iterate over the allowed classes for this slot. The Python equivalent of the CLIPS slot-allowed-classes function.
[ "Iterate", "over", "the", "allowed", "classes", "for", "this", "slot", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L554-L567
train
35,266
noxdafox/clipspy
clips/classes.py
Instance.name
def name(self): """Instance name.""" return ffi.string(lib.EnvGetInstanceName(self._env, self._ist)).decode()
python
def name(self): """Instance name.""" return ffi.string(lib.EnvGetInstanceName(self._env, self._ist)).decode()
[ "def", "name", "(", "self", ")", ":", "return", "ffi", ".", "string", "(", "lib", ".", "EnvGetInstanceName", "(", "self", ".", "_env", ",", "self", ".", "_ist", ")", ")", ".", "decode", "(", ")" ]
Instance name.
[ "Instance", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L627-L629
train
35,267
noxdafox/clipspy
clips/classes.py
Instance.instance_class
def instance_class(self): """Instance class.""" return Class(self._env, lib.EnvGetInstanceClass(self._env, self._ist))
python
def instance_class(self): """Instance class.""" return Class(self._env, lib.EnvGetInstanceClass(self._env, self._ist))
[ "def", "instance_class", "(", "self", ")", ":", "return", "Class", "(", "self", ".", "_env", ",", "lib", ".", "EnvGetInstanceClass", "(", "self", ".", "_env", ",", "self", ".", "_ist", ")", ")" ]
Instance class.
[ "Instance", "class", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L632-L634
train
35,268
noxdafox/clipspy
clips/classes.py
Instance.send
def send(self, message, arguments=None): """Send a message to the Instance. Message arguments must be provided as a string. """ output = clips.data.DataObject(self._env) instance = clips.data.DataObject( self._env, dtype=CLIPSType.INSTANCE_ADDRESS) instance.value = self._ist args = arguments.encode() if arguments is not None else ffi.NULL lib.EnvSend( self._env, instance.byref, message.encode(), args, output.byref) return output.value
python
def send(self, message, arguments=None): """Send a message to the Instance. Message arguments must be provided as a string. """ output = clips.data.DataObject(self._env) instance = clips.data.DataObject( self._env, dtype=CLIPSType.INSTANCE_ADDRESS) instance.value = self._ist args = arguments.encode() if arguments is not None else ffi.NULL lib.EnvSend( self._env, instance.byref, message.encode(), args, output.byref) return output.value
[ "def", "send", "(", "self", ",", "message", ",", "arguments", "=", "None", ")", ":", "output", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "instance", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", ...
Send a message to the Instance. Message arguments must be provided as a string.
[ "Send", "a", "message", "to", "the", "Instance", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L636-L652
train
35,269
noxdafox/clipspy
clips/classes.py
Instance.delete
def delete(self): """Delete the instance.""" if lib.EnvDeleteInstance(self._env, self._ist) != 1: raise CLIPSError(self._env)
python
def delete(self): """Delete the instance.""" if lib.EnvDeleteInstance(self._env, self._ist) != 1: raise CLIPSError(self._env)
[ "def", "delete", "(", "self", ")", ":", "if", "lib", ".", "EnvDeleteInstance", "(", "self", ".", "_env", ",", "self", ".", "_ist", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")" ]
Delete the instance.
[ "Delete", "the", "instance", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L654-L657
train
35,270
noxdafox/clipspy
clips/classes.py
Instance.unmake
def unmake(self): """This method is equivalent to delete except that it uses message-passing instead of directly deleting the instance. """ if lib.EnvUnmakeInstance(self._env, self._ist) != 1: raise CLIPSError(self._env)
python
def unmake(self): """This method is equivalent to delete except that it uses message-passing instead of directly deleting the instance. """ if lib.EnvUnmakeInstance(self._env, self._ist) != 1: raise CLIPSError(self._env)
[ "def", "unmake", "(", "self", ")", ":", "if", "lib", ".", "EnvUnmakeInstance", "(", "self", ".", "_env", ",", "self", ".", "_ist", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")" ]
This method is equivalent to delete except that it uses message-passing instead of directly deleting the instance.
[ "This", "method", "is", "equivalent", "to", "delete", "except", "that", "it", "uses", "message", "-", "passing", "instead", "of", "directly", "deleting", "the", "instance", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L659-L665
train
35,271
noxdafox/clipspy
clips/classes.py
MessageHandler.name
def name(self): """MessageHandler name.""" return ffi.string(lib.EnvGetDefmessageHandlerName( self._env, self._cls, self._idx)).decode()
python
def name(self): """MessageHandler name.""" return ffi.string(lib.EnvGetDefmessageHandlerName( self._env, self._cls, self._idx)).decode()
[ "def", "name", "(", "self", ")", ":", "return", "ffi", ".", "string", "(", "lib", ".", "EnvGetDefmessageHandlerName", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_idx", ")", ")", ".", "decode", "(", ")" ]
MessageHandler name.
[ "MessageHandler", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L700-L703
train
35,272
noxdafox/clipspy
clips/classes.py
MessageHandler.type
def type(self): """MessageHandler type.""" return ffi.string(lib.EnvGetDefmessageHandlerType( self._env, self._cls, self._idx)).decode()
python
def type(self): """MessageHandler type.""" return ffi.string(lib.EnvGetDefmessageHandlerType( self._env, self._cls, self._idx)).decode()
[ "def", "type", "(", "self", ")", ":", "return", "ffi", ".", "string", "(", "lib", ".", "EnvGetDefmessageHandlerType", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_idx", ")", ")", ".", "decode", "(", ")" ]
MessageHandler type.
[ "MessageHandler", "type", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L706-L709
train
35,273
noxdafox/clipspy
clips/classes.py
MessageHandler.deletable
def deletable(self): """True if the MessageHandler can be deleted.""" return bool(lib.EnvIsDefmessageHandlerDeletable( self._env, self._cls, self._idx))
python
def deletable(self): """True if the MessageHandler can be deleted.""" return bool(lib.EnvIsDefmessageHandlerDeletable( self._env, self._cls, self._idx))
[ "def", "deletable", "(", "self", ")", ":", "return", "bool", "(", "lib", ".", "EnvIsDefmessageHandlerDeletable", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_idx", ")", ")" ]
True if the MessageHandler can be deleted.
[ "True", "if", "the", "MessageHandler", "can", "be", "deleted", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L724-L727
train
35,274
noxdafox/clipspy
clips/classes.py
MessageHandler.undefine
def undefine(self): """Undefine the MessageHandler. Python equivalent of the CLIPS undefmessage-handler command. The object becomes unusable after this method has been called. """ if lib.EnvUndefmessageHandler(self._env, self._cls, self._idx) != 1: raise CLIPSError(self._env) self._env = None
python
def undefine(self): """Undefine the MessageHandler. Python equivalent of the CLIPS undefmessage-handler command. The object becomes unusable after this method has been called. """ if lib.EnvUndefmessageHandler(self._env, self._cls, self._idx) != 1: raise CLIPSError(self._env) self._env = None
[ "def", "undefine", "(", "self", ")", ":", "if", "lib", ".", "EnvUndefmessageHandler", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_idx", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", "...
Undefine the MessageHandler. Python equivalent of the CLIPS undefmessage-handler command. The object becomes unusable after this method has been called.
[ "Undefine", "the", "MessageHandler", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L729-L740
train
35,275
noxdafox/clipspy
clips/environment.py
Environment.load
def load(self, path): """Load a set of constructs into the CLIPS data base. Constructs can be in text or binary format. The Python equivalent of the CLIPS load command. """ try: self._load_binary(path) except CLIPSError: self._load_text(path)
python
def load(self, path): """Load a set of constructs into the CLIPS data base. Constructs can be in text or binary format. The Python equivalent of the CLIPS load command. """ try: self._load_binary(path) except CLIPSError: self._load_text(path)
[ "def", "load", "(", "self", ",", "path", ")", ":", "try", ":", "self", ".", "_load_binary", "(", "path", ")", "except", "CLIPSError", ":", "self", ".", "_load_text", "(", "path", ")" ]
Load a set of constructs into the CLIPS data base. Constructs can be in text or binary format. The Python equivalent of the CLIPS load command.
[ "Load", "a", "set", "of", "constructs", "into", "the", "CLIPS", "data", "base", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/environment.py#L103-L114
train
35,276
noxdafox/clipspy
clips/environment.py
Environment.save
def save(self, path, binary=False): """Save a set of constructs into the CLIPS data base. If binary is True, the constructs will be saved in binary format. The Python equivalent of the CLIPS load command. """ if binary: ret = lib.EnvBsave(self._env, path.encode()) else: ret = lib.EnvSave(self._env, path.encode()) if ret == 0: raise CLIPSError(self._env)
python
def save(self, path, binary=False): """Save a set of constructs into the CLIPS data base. If binary is True, the constructs will be saved in binary format. The Python equivalent of the CLIPS load command. """ if binary: ret = lib.EnvBsave(self._env, path.encode()) else: ret = lib.EnvSave(self._env, path.encode()) if ret == 0: raise CLIPSError(self._env)
[ "def", "save", "(", "self", ",", "path", ",", "binary", "=", "False", ")", ":", "if", "binary", ":", "ret", "=", "lib", ".", "EnvBsave", "(", "self", ".", "_env", ",", "path", ".", "encode", "(", ")", ")", "else", ":", "ret", "=", "lib", ".", ...
Save a set of constructs into the CLIPS data base. If binary is True, the constructs will be saved in binary format. The Python equivalent of the CLIPS load command.
[ "Save", "a", "set", "of", "constructs", "into", "the", "CLIPS", "data", "base", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/environment.py#L126-L139
train
35,277
noxdafox/clipspy
clips/environment.py
Environment.batch_star
def batch_star(self, path): """Evaluate the commands contained in the specific path. The Python equivalent of the CLIPS batch* command. """ if lib.EnvBatchStar(self._env, path.encode()) != 1: raise CLIPSError(self._env)
python
def batch_star(self, path): """Evaluate the commands contained in the specific path. The Python equivalent of the CLIPS batch* command. """ if lib.EnvBatchStar(self._env, path.encode()) != 1: raise CLIPSError(self._env)
[ "def", "batch_star", "(", "self", ",", "path", ")", ":", "if", "lib", ".", "EnvBatchStar", "(", "self", ".", "_env", ",", "path", ".", "encode", "(", ")", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")" ]
Evaluate the commands contained in the specific path. The Python equivalent of the CLIPS batch* command.
[ "Evaluate", "the", "commands", "contained", "in", "the", "specific", "path", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/environment.py#L141-L148
train
35,278
noxdafox/clipspy
clips/environment.py
Environment.build
def build(self, construct): """Build a single construct in CLIPS. The Python equivalent of the CLIPS build command. """ if lib.EnvBuild(self._env, construct.encode()) != 1: raise CLIPSError(self._env)
python
def build(self, construct): """Build a single construct in CLIPS. The Python equivalent of the CLIPS build command. """ if lib.EnvBuild(self._env, construct.encode()) != 1: raise CLIPSError(self._env)
[ "def", "build", "(", "self", ",", "construct", ")", ":", "if", "lib", ".", "EnvBuild", "(", "self", ".", "_env", ",", "construct", ".", "encode", "(", ")", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")" ]
Build a single construct in CLIPS. The Python equivalent of the CLIPS build command.
[ "Build", "a", "single", "construct", "in", "CLIPS", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/environment.py#L150-L157
train
35,279
noxdafox/clipspy
clips/environment.py
Environment.eval
def eval(self, construct): """Evaluate an expression returning its value. The Python equivalent of the CLIPS eval command. """ data = clips.data.DataObject(self._env) if lib.EnvEval(self._env, construct.encode(), data.byref) != 1: raise CLIPSError(self._env) return data.value
python
def eval(self, construct): """Evaluate an expression returning its value. The Python equivalent of the CLIPS eval command. """ data = clips.data.DataObject(self._env) if lib.EnvEval(self._env, construct.encode(), data.byref) != 1: raise CLIPSError(self._env) return data.value
[ "def", "eval", "(", "self", ",", "construct", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "if", "lib", ".", "EnvEval", "(", "self", ".", "_env", ",", "construct", ".", "encode", "(", ")", ",", "d...
Evaluate an expression returning its value. The Python equivalent of the CLIPS eval command.
[ "Evaluate", "an", "expression", "returning", "its", "value", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/environment.py#L159-L170
train
35,280
noxdafox/clipspy
clips/environment.py
Environment.define_function
def define_function(self, function, name=None): """Define the Python function within the CLIPS environment. If a name is given, it will be the function name within CLIPS. Otherwise, the name of the Python function will be used. The Python function will be accessible within CLIPS via its name as if it was defined via the `deffunction` construct. """ name = name if name is not None else function.__name__ ENVIRONMENT_DATA[self._env].user_functions[name] = function self.build(DEFFUNCTION.format(name))
python
def define_function(self, function, name=None): """Define the Python function within the CLIPS environment. If a name is given, it will be the function name within CLIPS. Otherwise, the name of the Python function will be used. The Python function will be accessible within CLIPS via its name as if it was defined via the `deffunction` construct. """ name = name if name is not None else function.__name__ ENVIRONMENT_DATA[self._env].user_functions[name] = function self.build(DEFFUNCTION.format(name))
[ "def", "define_function", "(", "self", ",", "function", ",", "name", "=", "None", ")", ":", "name", "=", "name", "if", "name", "is", "not", "None", "else", "function", ".", "__name__", "ENVIRONMENT_DATA", "[", "self", ".", "_env", "]", ".", "user_functio...
Define the Python function within the CLIPS environment. If a name is given, it will be the function name within CLIPS. Otherwise, the name of the Python function will be used. The Python function will be accessible within CLIPS via its name as if it was defined via the `deffunction` construct.
[ "Define", "the", "Python", "function", "within", "the", "CLIPS", "environment", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/environment.py#L188-L202
train
35,281
noxdafox/clipspy
clips/router.py
Router.activate
def activate(self): """Activate the Router.""" if lib.EnvActivateRouter(self._env, self._name.encode()) == 0: raise RuntimeError("Unable to activate router %s" % self._name)
python
def activate(self): """Activate the Router.""" if lib.EnvActivateRouter(self._env, self._name.encode()) == 0: raise RuntimeError("Unable to activate router %s" % self._name)
[ "def", "activate", "(", "self", ")", ":", "if", "lib", ".", "EnvActivateRouter", "(", "self", ".", "_env", ",", "self", ".", "_name", ".", "encode", "(", ")", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"Unable to activate router %s\"", "%", "se...
Activate the Router.
[ "Activate", "the", "Router", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/router.py#L45-L48
train
35,282
noxdafox/clipspy
clips/router.py
Router.deactivate
def deactivate(self): """Deactivate the Router.""" if lib.EnvDeactivateRouter(self._env, self._name.encode()) == 0: raise RuntimeError("Unable to deactivate router %s" % self._name)
python
def deactivate(self): """Deactivate the Router.""" if lib.EnvDeactivateRouter(self._env, self._name.encode()) == 0: raise RuntimeError("Unable to deactivate router %s" % self._name)
[ "def", "deactivate", "(", "self", ")", ":", "if", "lib", ".", "EnvDeactivateRouter", "(", "self", ".", "_env", ",", "self", ".", "_name", ".", "encode", "(", ")", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"Unable to deactivate router %s\"", "%",...
Deactivate the Router.
[ "Deactivate", "the", "Router", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/router.py#L50-L53
train
35,283
noxdafox/clipspy
clips/router.py
Router.delete
def delete(self): """Delete the Router.""" if lib.EnvDeleteRouter(self._env, self._name.encode()) == 0: raise RuntimeError("Unable to delete router %s" % self._name)
python
def delete(self): """Delete the Router.""" if lib.EnvDeleteRouter(self._env, self._name.encode()) == 0: raise RuntimeError("Unable to delete router %s" % self._name)
[ "def", "delete", "(", "self", ")", ":", "if", "lib", ".", "EnvDeleteRouter", "(", "self", ".", "_env", ",", "self", ".", "_name", ".", "encode", "(", ")", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"Unable to delete router %s\"", "%", "self", ...
Delete the Router.
[ "Delete", "the", "Router", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/router.py#L55-L58
train
35,284
noxdafox/clipspy
clips/router.py
Router.add_to_environment
def add_to_environment(self, environment): """Add the router to the given environment.""" self._env = environment._env self._userdata = ffi.new_handle(self) ENVIRONMENT_DATA[self._env].routers[self.name] = self lib.EnvAddRouterWithContext( self._env, self._name.encode(), self._priority, lib.query_function, lib.print_function, lib.getc_function, lib.ungetc_function, lib.exit_function, self._userdata)
python
def add_to_environment(self, environment): """Add the router to the given environment.""" self._env = environment._env self._userdata = ffi.new_handle(self) ENVIRONMENT_DATA[self._env].routers[self.name] = self lib.EnvAddRouterWithContext( self._env, self._name.encode(), self._priority, lib.query_function, lib.print_function, lib.getc_function, lib.ungetc_function, lib.exit_function, self._userdata)
[ "def", "add_to_environment", "(", "self", ",", "environment", ")", ":", "self", ".", "_env", "=", "environment", ".", "_env", "self", ".", "_userdata", "=", "ffi", ".", "new_handle", "(", "self", ")", "ENVIRONMENT_DATA", "[", "self", ".", "_env", "]", "....
Add the router to the given environment.
[ "Add", "the", "router", "to", "the", "given", "environment", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/router.py#L60-L74
train
35,285
noxdafox/clipspy
clips/data.py
DataObject.value
def value(self): """Return the DATA_OBJECT stored value.""" dtype = lib.get_data_type(self._data) dvalue = lib.get_data_value(self._data) if dvalue == ffi.NULL: return None return self.python_value(dtype, dvalue)
python
def value(self): """Return the DATA_OBJECT stored value.""" dtype = lib.get_data_type(self._data) dvalue = lib.get_data_value(self._data) if dvalue == ffi.NULL: return None return self.python_value(dtype, dvalue)
[ "def", "value", "(", "self", ")", ":", "dtype", "=", "lib", ".", "get_data_type", "(", "self", ".", "_data", ")", "dvalue", "=", "lib", ".", "get_data_value", "(", "self", ".", "_data", ")", "if", "dvalue", "==", "ffi", ".", "NULL", ":", "return", ...
Return the DATA_OBJECT stored value.
[ "Return", "the", "DATA_OBJECT", "stored", "value", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/data.py#L58-L66
train
35,286
noxdafox/clipspy
clips/data.py
DataObject.value
def value(self, value): """Sets the DATA_OBJECT stored value.""" dtype = TYPES[type(value)] if self._type is None else self._type lib.set_data_type(self._data, dtype) lib.set_data_value(self._data, self.clips_value(value))
python
def value(self, value): """Sets the DATA_OBJECT stored value.""" dtype = TYPES[type(value)] if self._type is None else self._type lib.set_data_type(self._data, dtype) lib.set_data_value(self._data, self.clips_value(value))
[ "def", "value", "(", "self", ",", "value", ")", ":", "dtype", "=", "TYPES", "[", "type", "(", "value", ")", "]", "if", "self", ".", "_type", "is", "None", "else", "self", ".", "_type", "lib", ".", "set_data_type", "(", "self", ".", "_data", ",", ...
Sets the DATA_OBJECT stored value.
[ "Sets", "the", "DATA_OBJECT", "stored", "value", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/data.py#L69-L74
train
35,287
noxdafox/clipspy
clips/data.py
DataObject.python_value
def python_value(self, dtype, dvalue): """Convert a CLIPS type into Python.""" try: return CONVERTERS[dtype](dvalue) except KeyError: if dtype == clips.common.CLIPSType.MULTIFIELD: return self.multifield_to_list() if dtype == clips.common.CLIPSType.FACT_ADDRESS: return clips.facts.new_fact(self._env, lib.to_pointer(dvalue)) if dtype == clips.common.CLIPSType.INSTANCE_ADDRESS: return clips.classes.Instance(self._env, lib.to_pointer(dvalue)) return None
python
def python_value(self, dtype, dvalue): """Convert a CLIPS type into Python.""" try: return CONVERTERS[dtype](dvalue) except KeyError: if dtype == clips.common.CLIPSType.MULTIFIELD: return self.multifield_to_list() if dtype == clips.common.CLIPSType.FACT_ADDRESS: return clips.facts.new_fact(self._env, lib.to_pointer(dvalue)) if dtype == clips.common.CLIPSType.INSTANCE_ADDRESS: return clips.classes.Instance(self._env, lib.to_pointer(dvalue)) return None
[ "def", "python_value", "(", "self", ",", "dtype", ",", "dvalue", ")", ":", "try", ":", "return", "CONVERTERS", "[", "dtype", "]", "(", "dvalue", ")", "except", "KeyError", ":", "if", "dtype", "==", "clips", ".", "common", ".", "CLIPSType", ".", "MULTIF...
Convert a CLIPS type into Python.
[ "Convert", "a", "CLIPS", "type", "into", "Python", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/data.py#L76-L88
train
35,288
noxdafox/clipspy
clips/data.py
DataObject.clips_value
def clips_value(self, dvalue): """Convert a Python type into CLIPS.""" try: return VALUES[type(dvalue)](self._env, dvalue) except KeyError: if isinstance(dvalue, (list, tuple)): return self.list_to_multifield(dvalue) if isinstance(dvalue, (clips.facts.Fact)): return dvalue._fact if isinstance(dvalue, (clips.classes.Instance)): return dvalue._ist return ffi.NULL
python
def clips_value(self, dvalue): """Convert a Python type into CLIPS.""" try: return VALUES[type(dvalue)](self._env, dvalue) except KeyError: if isinstance(dvalue, (list, tuple)): return self.list_to_multifield(dvalue) if isinstance(dvalue, (clips.facts.Fact)): return dvalue._fact if isinstance(dvalue, (clips.classes.Instance)): return dvalue._ist return ffi.NULL
[ "def", "clips_value", "(", "self", ",", "dvalue", ")", ":", "try", ":", "return", "VALUES", "[", "type", "(", "dvalue", ")", "]", "(", "self", ".", "_env", ",", "dvalue", ")", "except", "KeyError", ":", "if", "isinstance", "(", "dvalue", ",", "(", ...
Convert a Python type into CLIPS.
[ "Convert", "a", "Python", "type", "into", "CLIPS", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/data.py#L90-L102
train
35,289
noxdafox/clipspy
clips/agenda.py
Agenda.agenda_changed
def agenda_changed(self): """True if any rule activation changes have occurred.""" value = bool(lib.EnvGetAgendaChanged(self._env)) lib.EnvSetAgendaChanged(self._env, int(False)) return value
python
def agenda_changed(self): """True if any rule activation changes have occurred.""" value = bool(lib.EnvGetAgendaChanged(self._env)) lib.EnvSetAgendaChanged(self._env, int(False)) return value
[ "def", "agenda_changed", "(", "self", ")", ":", "value", "=", "bool", "(", "lib", ".", "EnvGetAgendaChanged", "(", "self", ".", "_env", ")", ")", "lib", ".", "EnvSetAgendaChanged", "(", "self", ".", "_env", ",", "int", "(", "False", ")", ")", "return",...
True if any rule activation changes have occurred.
[ "True", "if", "any", "rule", "activation", "changes", "have", "occurred", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L64-L69
train
35,290
noxdafox/clipspy
clips/agenda.py
Agenda.rules
def rules(self): """Iterate over the defined Rules.""" rule = lib.EnvGetNextDefrule(self._env, ffi.NULL) while rule != ffi.NULL: yield Rule(self._env, rule) rule = lib.EnvGetNextDefrule(self._env, rule)
python
def rules(self): """Iterate over the defined Rules.""" rule = lib.EnvGetNextDefrule(self._env, ffi.NULL) while rule != ffi.NULL: yield Rule(self._env, rule) rule = lib.EnvGetNextDefrule(self._env, rule)
[ "def", "rules", "(", "self", ")", ":", "rule", "=", "lib", ".", "EnvGetNextDefrule", "(", "self", ".", "_env", ",", "ffi", ".", "NULL", ")", "while", "rule", "!=", "ffi", ".", "NULL", ":", "yield", "Rule", "(", "self", ".", "_env", ",", "rule", "...
Iterate over the defined Rules.
[ "Iterate", "over", "the", "defined", "Rules", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L125-L132
train
35,291
noxdafox/clipspy
clips/agenda.py
Agenda.find_rule
def find_rule(self, rule): """Find a Rule by name.""" defrule = lib.EnvFindDefrule(self._env, rule.encode()) if defrule == ffi.NULL: raise LookupError("Rule '%s' not found" % defrule) return Rule(self._env, defrule)
python
def find_rule(self, rule): """Find a Rule by name.""" defrule = lib.EnvFindDefrule(self._env, rule.encode()) if defrule == ffi.NULL: raise LookupError("Rule '%s' not found" % defrule) return Rule(self._env, defrule)
[ "def", "find_rule", "(", "self", ",", "rule", ")", ":", "defrule", "=", "lib", ".", "EnvFindDefrule", "(", "self", ".", "_env", ",", "rule", ".", "encode", "(", ")", ")", "if", "defrule", "==", "ffi", ".", "NULL", ":", "raise", "LookupError", "(", ...
Find a Rule by name.
[ "Find", "a", "Rule", "by", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L134-L140
train
35,292
noxdafox/clipspy
clips/agenda.py
Agenda.reorder
def reorder(self, module=None): """Reorder the Activations in the Agenda. If no Module is specified, the current one is used. To be called after changing the conflict resolution strategy. """ module = module._mdl if module is not None else ffi.NULL lib.EnvReorderAgenda(self._env, module)
python
def reorder(self, module=None): """Reorder the Activations in the Agenda. If no Module is specified, the current one is used. To be called after changing the conflict resolution strategy. """ module = module._mdl if module is not None else ffi.NULL lib.EnvReorderAgenda(self._env, module)
[ "def", "reorder", "(", "self", ",", "module", "=", "None", ")", ":", "module", "=", "module", ".", "_mdl", "if", "module", "is", "not", "None", "else", "ffi", ".", "NULL", "lib", ".", "EnvReorderAgenda", "(", "self", ".", "_env", ",", "module", ")" ]
Reorder the Activations in the Agenda. If no Module is specified, the current one is used. To be called after changing the conflict resolution strategy.
[ "Reorder", "the", "Activations", "in", "the", "Agenda", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L142-L152
train
35,293
noxdafox/clipspy
clips/agenda.py
Agenda.refresh
def refresh(self, module=None): """Recompute the salience values of the Activations on the Agenda and then reorder the agenda. The Python equivalent of the CLIPS refresh-agenda command. If no Module is specified, the current one is used. """ module = module._mdl if module is not None else ffi.NULL lib.EnvRefreshAgenda(self._env, module)
python
def refresh(self, module=None): """Recompute the salience values of the Activations on the Agenda and then reorder the agenda. The Python equivalent of the CLIPS refresh-agenda command. If no Module is specified, the current one is used. """ module = module._mdl if module is not None else ffi.NULL lib.EnvRefreshAgenda(self._env, module)
[ "def", "refresh", "(", "self", ",", "module", "=", "None", ")", ":", "module", "=", "module", ".", "_mdl", "if", "module", "is", "not", "None", "else", "ffi", ".", "NULL", "lib", ".", "EnvRefreshAgenda", "(", "self", ".", "_env", ",", "module", ")" ]
Recompute the salience values of the Activations on the Agenda and then reorder the agenda. The Python equivalent of the CLIPS refresh-agenda command. If no Module is specified, the current one is used.
[ "Recompute", "the", "salience", "values", "of", "the", "Activations", "on", "the", "Agenda", "and", "then", "reorder", "the", "agenda", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L154-L164
train
35,294
noxdafox/clipspy
clips/agenda.py
Agenda.activations
def activations(self): """Iterate over the Activations in the Agenda.""" activation = lib.EnvGetNextActivation(self._env, ffi.NULL) while activation != ffi.NULL: yield Activation(self._env, activation) activation = lib.EnvGetNextActivation(self._env, activation)
python
def activations(self): """Iterate over the Activations in the Agenda.""" activation = lib.EnvGetNextActivation(self._env, ffi.NULL) while activation != ffi.NULL: yield Activation(self._env, activation) activation = lib.EnvGetNextActivation(self._env, activation)
[ "def", "activations", "(", "self", ")", ":", "activation", "=", "lib", ".", "EnvGetNextActivation", "(", "self", ".", "_env", ",", "ffi", ".", "NULL", ")", "while", "activation", "!=", "ffi", ".", "NULL", ":", "yield", "Activation", "(", "self", ".", "...
Iterate over the Activations in the Agenda.
[ "Iterate", "over", "the", "Activations", "in", "the", "Agenda", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L166-L173
train
35,295
noxdafox/clipspy
clips/agenda.py
Agenda.clear
def clear(self): """Deletes all activations in the agenda.""" if lib.EnvDeleteActivation(self._env, ffi.NULL) != 1: raise CLIPSError(self._env)
python
def clear(self): """Deletes all activations in the agenda.""" if lib.EnvDeleteActivation(self._env, ffi.NULL) != 1: raise CLIPSError(self._env)
[ "def", "clear", "(", "self", ")", ":", "if", "lib", ".", "EnvDeleteActivation", "(", "self", ".", "_env", ",", "ffi", ".", "NULL", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")" ]
Deletes all activations in the agenda.
[ "Deletes", "all", "activations", "in", "the", "agenda", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L175-L178
train
35,296
noxdafox/clipspy
clips/agenda.py
Rule.name
def name(self): """Rule name.""" return ffi.string(lib.EnvGetDefruleName(self._env, self._rule)).decode()
python
def name(self): """Rule name.""" return ffi.string(lib.EnvGetDefruleName(self._env, self._rule)).decode()
[ "def", "name", "(", "self", ")", ":", "return", "ffi", ".", "string", "(", "lib", ".", "EnvGetDefruleName", "(", "self", ".", "_env", ",", "self", ".", "_rule", ")", ")", ".", "decode", "(", ")" ]
Rule name.
[ "Rule", "name", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L228-L230
train
35,297
noxdafox/clipspy
clips/agenda.py
Rule.module
def module(self): """The module in which the Rule is defined. Python equivalent of the CLIPS defrule-module command. """ modname = ffi.string(lib.EnvDefruleModule(self._env, self._rule)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, defmodule)
python
def module(self): """The module in which the Rule is defined. Python equivalent of the CLIPS defrule-module command. """ modname = ffi.string(lib.EnvDefruleModule(self._env, self._rule)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, defmodule)
[ "def", "module", "(", "self", ")", ":", "modname", "=", "ffi", ".", "string", "(", "lib", ".", "EnvDefruleModule", "(", "self", ".", "_env", ",", "self", ".", "_rule", ")", ")", "defmodule", "=", "lib", ".", "EnvFindDefmodule", "(", "self", ".", "_en...
The module in which the Rule is defined. Python equivalent of the CLIPS defrule-module command.
[ "The", "module", "in", "which", "the", "Rule", "is", "defined", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L233-L242
train
35,298
noxdafox/clipspy
clips/agenda.py
Rule.watch_firings
def watch_firings(self, flag): """Whether or not the Rule firings are being watched.""" lib.EnvSetDefruleWatchFirings(self._env, int(flag), self._rule)
python
def watch_firings(self, flag): """Whether or not the Rule firings are being watched.""" lib.EnvSetDefruleWatchFirings(self._env, int(flag), self._rule)
[ "def", "watch_firings", "(", "self", ",", "flag", ")", ":", "lib", ".", "EnvSetDefruleWatchFirings", "(", "self", ".", "_env", ",", "int", "(", "flag", ")", ",", "self", ".", "_rule", ")" ]
Whether or not the Rule firings are being watched.
[ "Whether", "or", "not", "the", "Rule", "firings", "are", "being", "watched", "." ]
b22d71a6da821c1715d8fa00d7d75cabc09ed364
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L255-L257
train
35,299