signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def __init__(self, word, format, type, index_in_timed_response = None): | self.type = type<EOL>self.format = format<EOL>self.phonetic_representation = None<EOL>self.index_in_timed_response = index_in_timed_response<EOL>if self.format == "<STR_LIT>":<EOL><INDENT>self.text = word.string.lower()<EOL>self.original_text = [word.string.lower()] <EOL>self.start_time = word.start<EOL>self.end_time =... | Initialization of Unit object.
:param word: Original word that the Unit represents.
:type word: If format is "TextGrid", this must be a TextGrid.Word object.
If format is "csv", this must be a string.
:param str format: 'TextGrid' or 'csv'
:pa... | f13479:c2:m0 |
def __str__(self): | return self.text<EOL> | Enables the str() function. Returns the simplest textual representation of the Unit. | f13479:c2:m1 |
def __init__(self,response_type,<EOL>letter_or_category,<EOL>quiet = False,<EOL>cmudict = None, <EOL>english_words = None, <EOL>lemmas = None, <EOL>names = None, <EOL>permissible_words = None): | self.type = response_type<EOL>self.letter_or_category = letter_or_category<EOL>self.quiet = quiet<EOL>self.cmudict = cmudict<EOL>self.english_words = english_words<EOL>self.lemmas = lemmas<EOL>self.names = names<EOL>self.permissible_words = permissible_words<EOL>self.unit_list = []<EOL>self.timing_included = None<EOL>s... | Initializes a ParsedResponse object.
:param str response_type: 'PHONETIC' or 'SEMANTIC - used for determining whether
lemmatization/tokenization should be done during initialization
:param str letter_or_category: letter (for type='PHONETIC') or string (for type='SEMANTIC'... | f13479:c3:m0 |
def __iter__(self): | return iter(self.unit_list)<EOL> | Makes the object iterable, iterates over the list of units in the ParsedResponse. | f13479:c3:m1 |
def __len__(self): | return len(self.unit_list)<EOL> | Implements len(), returns length of the list of units in the ParsedResponse. | f13479:c3:m2 |
def __getitem__(self,i): | return self.unit_list[i]<EOL> | Implements e.g. parsed_response[i] to return the ith Unit in the ParsedResponse. | f13479:c3:m3 |
def create_from_csv(self,token_list): | self.timing_included = False<EOL>for entry in token_list:<EOL><INDENT>self.unit_list.append(Unit(entry, format = "<STR_LIT>", type = self.type))<EOL><DEDENT>if self.type == "<STR_LIT>":<EOL><INDENT>self.lemmatize()<EOL>self.tokenize()<EOL><DEDENT> | Fills the ParsedResponse object with a list of words/tokens originally from a .csv file.
:param list token_list: List of strings corresponding to words in the subject response.
Modifies:
- self.timing_included: csv files do not include timing information
- self.unit_list: fills... | f13479:c3:m4 |
def create_from_textgrid(self,word_list): | self.timing_included = True<EOL>for i, entry in enumerate(word_list):<EOL><INDENT>self.unit_list.append(Unit(entry, format="<STR_LIT>",<EOL>type=self.type,<EOL>index_in_timed_response=i))<EOL><DEDENT>if self.type == "<STR_LIT>":<EOL><INDENT>self.lemmatize()<EOL>self.tokenize()<EOL><DEDENT> | Fills the ParsedResponse object with a list of TextGrid.Word objects originally from a .TextGrid file.
:param list word_list: List of TextGrid.Word objects corresponding to words/tokens in the subject response.
Modifies:
- self.timing_included: TextGrid files include timing information
... | f13479:c3:m5 |
def lemmatize(self): | for unit in self.unit_list:<EOL><INDENT>if lemmatizer.lemmatize(unit.text) in self.lemmas:<EOL><INDENT>unit.text = lemmatizer.lemmatize(unit.text)<EOL><DEDENT><DEDENT> | Lemmatize all Units in self.unit_list.
Modifies:
- self.unit_list: converts the .text property into its lemmatized form.
This method lemmatizes all inflected variants of permissible words to
those words' respective canonical forms. This is done to ensure that
each instance ... | f13479:c3:m6 |
def tokenize(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL><DEDENT>compound_word_dict = {}<EOL>for compound_length in range(<NUM_LIT:5>,<NUM_LIT:1>,-<NUM_LIT:1>):<EOL><INDENT>compound_word_dict[compound_length] = [name for name in self.names if len(name.split()) == compound_length]<EOL><DEDENT>current_index = <N... | Tokenizes all multiword names in the list of Units.
Modifies:
- (indirectly) self.unit_list, by combining words into compound words.
This is done because many names may be composed of multiple words, e.g.,
'grizzly bear'. In order to count the number of permissible words
ge... | f13479:c3:m7 |
def make_compound_word(self, start_index, how_many): | if not self.quiet:<EOL><INDENT>compound_word = "<STR_LIT>"<EOL>for word in self.unit_list[start_index:start_index + how_many]:<EOL><INDENT>compound_word += "<STR_LIT:U+0020>" + word.text<EOL><DEDENT>print(compound_word.strip(), "<STR_LIT>","<STR_LIT:_>".join(compound_word.split()))<EOL><DEDENT>for other_unit in range(<... | Combines two Units in self.unit_list to make a compound word token.
:param int start_index: Index of first Unit in self.unit_list to be combined
:param int how_many: Index of how many Units in self.unit_list to be combined.
Modifies:
- self.unit_list: Modifies the Unit correspo... | f13479:c3:m8 |
def remove_unit(self, index): | if not self.quiet:<EOL><INDENT>print("<STR_LIT>", self.unit_list[index].text)<EOL><DEDENT>self.unit_list.pop(index)<EOL> | Removes the unit at the given index in self.unit_list. Does not modify any other units. | f13479:c3:m9 |
def combine_same_stem_units(self, index): | if not self.quiet:<EOL><INDENT>combined_word = "<STR_LIT>"<EOL>for word in self.unit_list[index:index + <NUM_LIT:2>]:<EOL><INDENT>for original_word in word.original_text:<EOL><INDENT>combined_word += "<STR_LIT:U+0020>" + original_word<EOL><DEDENT><DEDENT>print(combined_word.strip(), "<STR_LIT>","<STR_LIT:/>".join(combi... | Combines adjacent words with the same stem into a single unit.
:param int index: Index of Unit in self.unit_list to be combined with the
subsequent Unit.
Modifies:
- self.unit_list: Modifies the .original_text property of the Unit
corresponding to the in... | f13479:c3:m10 |
def display(self): | table_list = []<EOL>table_list.append(("<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>", "<STR_LIT>"))<EOL>for unit in self.unit_list:<EOL><INDENT>table_list.append((unit.text,<EOL>"<STR_LIT:/>".join(unit.original_text),<EOL>unit.start_time,<EOL>unit.end_time,<EOL>unit.phonetic_representation))<EOL><DEDENT>print_table(t... | Pretty-prints the ParsedResponse to the screen. | f13479:c3:m11 |
def generate_phonetic_representation(self, word): | with NamedTemporaryFile() as temp_file:<EOL><INDENT>temp_file.write(word)<EOL>t2pargs = [os.path.abspath(os.path.join(os.path.dirname(__file__),'<STR_LIT>')),<EOL>'<STR_LIT>', os.path.join(data_path, '<STR_LIT>'),<EOL>temp_file.name]<EOL>temp_file.seek(<NUM_LIT:0>)<EOL>output, error = subprocess.Popen(<EOL>t2pargs, std... | Returns a generated phonetic representation for a word.
:param str word: a word to be phoneticized.
:return: A list of phonemes representing the phoneticized word.
This method is used for words for which there is no pronunication
entry in the CMU dictionary. The function generates a
pronunication for the word in the ... | f13479:c3:m12 |
def modify_phonetic_representation(self, phonetic_representation): | for i in range(len(phonetic_representation)):<EOL><INDENT>phonetic_representation[i] = re.sub('<STR_LIT>', '<STR_LIT>', phonetic_representation[i])<EOL><DEDENT>multis = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<S... | Returns a compact phonetic representation given a CMUdict-formatted representation.
:param list phonetic_representation: a phonetic representation in standard
CMUdict formatting, i.e. a list of phonemes like ['HH', 'EH0', 'L', 'OW1']
:returns: A string representing a custom phonetic represe... | f13479:c3:m13 |
def clean(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print(self.display())<EOL><DEDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL><DEDENT>current_index = <NUM_LIT:0><EOL>while current_index < len(self.unit_list):<EOL><INDENT>word = self.unit_list[current_index]... | Removes any Units that are not applicable given the current semantic or phonetic category.
Modifies:
- self.unit_list: Removes Units from this list that do not fit into the clustering category.
it does by by either combining units to make compound words, combining units with the
... | f13479:c3:m14 |
def __init__(self,<EOL>response_category,<EOL>response_file_path,<EOL>target_file_path=None,<EOL>collection_types=["<STR_LIT>", "<STR_LIT>"],<EOL>similarity_measures=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"], <EOL>clustering_parameter=<NUM_LIT>, <EOL>quiet=False,<EOL>similarity_file = None,<EOL>threshold = None): | self.valid_semantic_categories = ['<STR_LIT>', '<STR_LIT>']<EOL>self.valid_phonetic_categories = ['<STR_LIT:a>', '<STR_LIT:f>', '<STR_LIT:s>', '<STR_LIT:p>']<EOL>self.valid_semantic_measures = ['<STR_LIT>']<EOL>self.valid_phonemic_measures = ['<STR_LIT>', '<STR_LIT>']<EOL>self.vowels = ['<STR_LIT>', '<STR_LIT>', '<STR_... | Initialize for VFClust analysis of a verbal phonetic or semantic fluency test response.
response_file_path -- filepath for a comma-separated string comprising a
file ID and the words, pauses, etc., produced during the
attempt. Or, if the response format is a TextGrid fil... | f13479:c4:m0 |
def load_lsa_information(self): | if not (<NUM_LIT> < int(self.clustering_parameter) < <NUM_LIT>):<EOL><INDENT>raise Exception('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL><DEDENT>if not self.quiet:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>with open(os.path.join(data_path, self.category + '<STR_LIT:_>' +<EOL>os.path.join('<STR_LIT>',<EOL>'<STR_LIT>' +<EOL>str(... | Loads a dictionary from disk that maps permissible words to their LSA term vectors. | f13479:c4:m1 |
def get_similarity_measures(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>", self.current_similarity_measure, "<STR_LIT>")<EOL><DEDENT>self.compute_similarity_scores()<EOL> | Helper function for computing similarity measures. | f13479:c4:m2 |
def get_collections(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>" + self.current_collection_type + "<STR_LIT>")<EOL><DEDENT>self.compute_collections()<EOL>if not self.quiet:<EOL><INDENT>print(self.current_similarity_measure, self.current_collection_type, "<STR_LIT>")<EOL>table_contents = [("<STR_LIT>","<STR_LIT>","<STR_LIT>... | Helper function for determining what the clusters/chains/other collections are. | f13479:c4:m3 |
def get_collection_measures(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>", self.current_collection_type, "<STR_LIT>")<EOL><DEDENT>self.compute_collection_measures() <EOL>self.compute_collection_measures(no_singletons = True) <EOL>self.compute_pairwise_similarity_score()<EOL>if not self.quiet:<EOL><INDENT>collection_measures = [x f... | Helper function for calculating measurements derived from clusters/chains/collections | f13479:c4:m4 |
def get_raw_counts(self): | <EOL>words = []<EOL>labels = []<EOL>words_said = set()<EOL>for unit in self.parsed_response:<EOL><INDENT>word = unit.text<EOL>test = False<EOL>if self.type == "<STR_LIT>":<EOL><INDENT>test = (word.startswith(self.letter) and<EOL>"<STR_LIT>" not in word and "<STR_LIT>" not in word and "<STR_LIT:!>" not in word and <EOL>... | Determines counts for unique words, repetitions, etc using the raw text response.
Adds the following measures to the self.measures dictionary:
- COUNT_total_words: count of words (i.e. utterances with semantic content) spoken
by the subject. Filled pauses, silences, coughs, breaths,... | f13479:c4:m5 |
def compute_similarity_score(self, unit1, unit2): | if self.type == "<STR_LIT>":<EOL><INDENT>word1 = unit1.phonetic_representation<EOL>word2 = unit2.phonetic_representation<EOL>if self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>word1_length, word2_length = len(word1), len(word2)<EOL>if word1_length > word2_length:<EOL><INDENT>word1, word2 = word2, word1<EOL>... | Returns the similarity score between two words.
The type of similarity scoring method used depends on the currently active
method and clustering type.
:param unit1: Unit object corresponding to the first word.
:type unit1: Unit
:param unit2: Unit object corresponding to the s... | f13479:c4:m6 |
def compute_similarity_scores(self): | for i,unit in enumerate(self.parsed_response):<EOL><INDENT>if i < len(self.parsed_response) - <NUM_LIT:1>:<EOL><INDENT>next_unit = self.parsed_response[i + <NUM_LIT:1>]<EOL>self.similarity_scores.append(self.compute_similarity_score(unit, next_unit))<EOL><DEDENT><DEDENT>if not self.quiet:<EOL><INDENT>print(self.current... | Produce a list of similarity scores for each contiguous pair in a response.
Calls compute_similarity_score method for every adjacent pair of words. The results
are not used in clustering; this is merely to provide a visual representation to
print to the screen.
Modifies:
- ... | f13479:c4:m7 |
def compute_collections(self): | if self.custom_threshold:<EOL><INDENT>self.similarity_threshold = self.custom_threshold<EOL><DEDENT>elif self.type == "<STR_LIT>":<EOL><INDENT>if self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>phonetic_similarity_thresholds = {'<STR_LIT:a>': <NUM_LIT>,<EOL>'<STR_LIT:b>': <NUM_LIT>,<EOL>'<STR_LIT:c>': <NUM_... | Finds the collections (clusters,chains) that exist in parsed_response.
Modified:
- self.collection_sizes: populated with a list of integers indicating
the number of units belonging to each collection
- self.collection_indices: populated with a list of strings indicating
... | f13479:c4:m8 |
def compute_pairwise_similarity_score(self): | pairs = []<EOL>all_scores = []<EOL>for i, unit in enumerate(self.parsed_response):<EOL><INDENT>for j, other_unit in enumerate(self.parsed_response):<EOL><INDENT>if i != j:<EOL><INDENT>pair = (i, j)<EOL>rev_pair = (j, i)<EOL>if pair not in pairs and rev_pair not in pairs:<EOL><INDENT>score = self.compute_similarity_scor... | Computes the average pairwise similarity score between all pairs of Units.
The pairwise similarity is calculated as the sum of similarity scores for all pairwise
word pairs in a response -- except any pair composed of a word and
itself -- divided by the total number of words in an attempt. I.e.... | f13479:c4:m9 |
def compute_collection_measures(self, no_singletons=False): | prefix = "<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:_>" + self.current_collection_type + "<STR_LIT:_>"<EOL>if no_singletons:<EOL><INDENT>prefix += "<STR_LIT>"<EOL><DEDENT>if no_singletons:<EOL><INDENT>collection_sizes_temp = [x for x in self.collection_sizes if x != <NUM_LIT:1>]<EOL><DEDENT>else: <EOL><I... | Computes summaries of measures using the discovered collections.
:param no_singletons: if True, omits collections of length 1 from all measures
and includes "no_singletons_" in the measure name.
Adds the following measures to the self.measures dictionary, prefaced by
COLLECTION_(si... | f13479:c4:m10 |
def compute_duration_measures(self): | prefix = "<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:_>" + self.current_collection_type + "<STR_LIT:_>"<EOL>if self.response_format == '<STR_LIT>':<EOL><INDENT>self.compute_response_vowel_duration("<STR_LIT>") <EOL>self.compute_response_continuant_duration("<STR_LIT>")<EOL>self.compute_between_collection... | Helper function for computing measures derived from timing information.
These are only computed if the response is textgrid with timing information.
All times are in seconds. | f13479:c4:m11 |
def compute_response_vowel_duration(self, prefix): | durations = []<EOL>for word in self.full_timed_response:<EOL><INDENT>if word.phones:<EOL><INDENT>for phone in word.phones:<EOL><INDENT>if phone.string in self.vowels:<EOL><INDENT>durations.append(phone.end - phone.start)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(durations)if len... | Computes mean vowel duration in entire response.
:param str prefix: Prefix for the key entry in self.measures.
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_response_vowel_duration_mean: average
vowel duration o... | f13479:c4:m12 |
def compute_response_continuant_duration(self, prefix): | durations = []<EOL>for word in self.full_timed_response:<EOL><INDENT>if word.phones:<EOL><INDENT>for phone in word.phones:<EOL><INDENT>if phone.string in self.continuants:<EOL><INDENT>durations.append(phone.end - phone.start)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(durations)i... | Computes mean duration for continuants in response.
:param str prefix: Prefix for the key entry in self.measures.
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_response_continuant_duration_mean: average
vowel du... | f13479:c4:m13 |
def compute_between_collection_interval_duration(self, prefix): | durations = [] <EOL>for collection in self.collection_list:<EOL><INDENT>start = collection[<NUM_LIT:0>].start_time<EOL>end = collection[-<NUM_LIT:1>].end_time<EOL>durations.append((start, end))<EOL><DEDENT>interstices = [durations[i + <NUM_LIT:1>][<NUM_LIT:0>] - durations[i][<NUM_LIT:1>] for i, d in enumerate(duration... | Calculates BETWEEN-collection intervals for the current collection and measure type
and takes their mean.
:param str prefix: Prefix for the key entry in self.measures.
Negative intervals (for overlapping clusters) are counted as 0 seconds. Intervals are
calculated as being the dif... | f13479:c4:m14 |
def compute_within_collection_interval_duration(self, prefix): | interstices = []<EOL>for cluster in self.collection_list:<EOL><INDENT>if len(cluster) > <NUM_LIT:1>:<EOL><INDENT>for i in range(len(cluster)):<EOL><INDENT>if i != len(cluster) - <NUM_LIT:1>:<EOL><INDENT>interstice = cluster[i+<NUM_LIT:1>].start_time - cluster[i].end_time<EOL>interstices.append(interstice)<EOL><DEDENT><... | Calculates mean between-word duration WITHIN collections.
:param str prefix: Prefix for the key entry in self.measures.
Calculates the mean time between the end of each word in the collection
and the beginning of the next word. Note that these times do not necessarily
reflect pauses, ... | f13479:c4:m15 |
def compute_within_collection_vowel_duration(self, prefix, no_singletons=False): | if no_singletons:<EOL><INDENT>min_size = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>prefix += "<STR_LIT>"<EOL>min_size = <NUM_LIT:1><EOL><DEDENT>durations = []<EOL>for cluster in self.collection_list:<EOL><INDENT>if len(cluster) >= min_size:<EOL><INDENT>for word in cluster:<EOL><INDENT>word = self.full_timed_response[wo... | Computes the mean duration of vowels from Units within clusters.
:param str prefix: Prefix for the key entry in self.measures
:param bool no_singletons: If False, excludes collections of length 1 from calculations
and adds "no_singletons" to the prefix
Adds the following measures t... | f13479:c4:m16 |
def compute_within_collection_continuant_duration(self, prefix, no_singletons=False): | if no_singletons:<EOL><INDENT>min_size = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>prefix += "<STR_LIT>"<EOL>min_size = <NUM_LIT:1><EOL><DEDENT>durations = []<EOL>for cluster in self.collection_list:<EOL><INDENT>if len(cluster) >= min_size:<EOL><INDENT>for word in cluster:<EOL><INDENT>word = self.full_timed_response[wo... | Computes the mean duration of continuants from Units within clusters.
:param str prefix: Prefix for the key entry in self.measures
:param bool no_singletons: If False, excludes collections of length 1 from calculations
and adds "no_singletons" to the prefix
Adds the following measu... | f13479:c4:m17 |
def print_output(self): | if self.response_format == "<STR_LIT>":<EOL><INDENT>for key in self.measures:<EOL><INDENT>if "<STR_LIT>" in key:<EOL><INDENT>self.measures[key] = "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print(self.type.upper() + "<STR_LIT>")<EOL>keys = [e for e in self.measures if '<STR_LIT>' ... | Outputs final list of measures to screen a csv file.
The .csv file created has the same name as the input file, with
"vfclust_TYPE_CATEGORY" appended to the filename, where TYPE indicates
the type of task performed done (SEMANTIC or PHONETIC) and CATEGORY
indicates the category requirem... | f13479:c4:m18 |
def __init__(self, textgrid): | textgrid = open(textgrid, '<STR_LIT:r>').read()<EOL>self.word_intervals = textgrid[textgrid.index('<STR_LIT>'):textgrid.index('<STR_LIT>')]<EOL>self.word_intervals = self.word_intervals.split('<STR_LIT>')<EOL>del self.word_intervals[-<NUM_LIT:1>]<EOL>self.word_intervals = [interval + '<STR_LIT:$>' for interval in <EOL>... | Extract word and phone intervals from a TextGrid.
These word and phone intervals contain the words and phones themselves,
as well as their respective start and end times in the audio recording. | f13480:c0:m0 |
def parse_phones(self): | phones = []<EOL>for i in self.phone_intervals:<EOL><INDENT>start = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip('<STR_LIT:\t>').strip('<STR_LIT:\n>'))<EOL>end = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip('<STR_LIT:\t>').strip('<STR_LI... | Parse TextGrid phone intervals.
This method parses the phone intervals in a TextGrid to extract each
phone and each phone's start and end times in the audio recording. For
each phone, it instantiates the class Phone(), with the phone and its
start and end times as attributes of that cla... | f13480:c0:m1 |
def parse_words(self): | phones = self.parse_phones()<EOL>words = []<EOL>for i in self.word_intervals:<EOL><INDENT>start = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip('<STR_LIT:\t>').strip('<STR_LIT:\n>'))<EOL>end = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip... | Parse TextGrid word intervals.
This method parses the word intervals in a TextGrid to extract each
word and each word's start and end times in the audio recording. For
each word, it instantiates the class Word(), with the word and its
start and end times as attributes of that class inst... | f13480:c0:m2 |
def mv_release(m): | release = getattr(m, '<STR_LIT>', None)<EOL>if release is not None:<EOL><INDENT>release()<EOL><DEDENT> | Release memoryview | f13499:m0 |
def logical_lines(lines): | if isinstance(lines, string_types):<EOL><INDENT>lines = StringIO(lines)<EOL><DEDENT>buf = []<EOL>for line in lines:<EOL><INDENT>if buf and not line.startswith('<STR_LIT:U+0020>'):<EOL><INDENT>chunk = '<STR_LIT>'.join(buf).strip()<EOL>if chunk:<EOL><INDENT>yield chunk<EOL><DEDENT>buf[:] = []<EOL><DEDENT>buf.append(line)... | Merge lines into chunks according to q rules | f13504:m0 |
def q(line, cell=None, _ns=None): | if cell is None:<EOL><INDENT>return pyq.q(line)<EOL><DEDENT>if _ns is None:<EOL><INDENT>_ns = vars(sys.modules['<STR_LIT:__main__>'])<EOL><DEDENT>input = output = None<EOL>preload = []<EOL>outs = {}<EOL>try:<EOL><INDENT>h = pyq.q('<STR_LIT>')<EOL>if line:<EOL><INDENT>for opt, value in getopt(line.split(), "<STR_LIT>")[... | Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr | f13504:m2 |
def load_ipython_extension(ipython): | ipython.register_magic_function(q, '<STR_LIT>')<EOL>fmr = ipython.display_formatter.formatters['<STR_LIT>']<EOL>fmr.for_type(pyq.K, _q_formatter)<EOL> | Register %q and %%q magics and pretty display for K objects | f13504:m4 |
def get_unit(a): | typestr = a.dtype.str<EOL>i = typestr.find('<STR_LIT:[>')<EOL>if i == -<NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>", a.dtype)<EOL><DEDENT>return typestr[i + <NUM_LIT:1>: -<NUM_LIT:1>]<EOL> | Extract the time unit from array's dtype | f13505:m0 |
def dtypeof(x): | t = abs(x._t)<EOL>if t < <NUM_LIT:20>:<EOL><INDENT>return _DTYPES[t]<EOL><DEDENT>return '<STR_LIT:O>'<EOL> | Return the dtype corresponding to a given q object | f13505:m1 |
def k2a(a, x): | func, scale = None, <NUM_LIT:1><EOL>t = abs(x._t)<EOL>if <NUM_LIT:12> <= t <= <NUM_LIT:15>:<EOL><INDENT>unit = get_unit(a)<EOL>attr, shift, func, scale = _UNIT[unit]<EOL>a[:] = getattr(x, attr).data<EOL>a += shift<EOL><DEDENT>elif <NUM_LIT:16> <= t <= <NUM_LIT>:<EOL><INDENT>unit = get_unit(a)<EOL>func, scale = _SCALE[u... | Rescale data from a K object x to array a. | f13505:m2 |
def array(self, dtype=None): | t = self._t<EOL>if <NUM_LIT:11> <= t < <NUM_LIT>:<EOL><INDENT>dtype = dtypeof(self)<EOL>a = numpy.empty(len(self), dtype)<EOL>k2a(a, self)<EOL>return a<EOL><DEDENT>if t == <NUM_LIT>:<EOL><INDENT>if dtype is None:<EOL><INDENT>dtype = list(zip(self.cols, (dtypeof(c) for c in self.flip.value)))<EOL><DEDENT>dtype = numpy.d... | An implementation of __array__() | f13505:m3 |
def d9(x): | return K._d9(K._kp(x))<EOL> | like K._d9, but takes python bytes | f13507:m2 |
def versions(): | stream = sys.stdout if _PY3K else sys.stderr<EOL>print('<STR_LIT>', __version__, file=stream)<EOL>if _np is not None:<EOL><INDENT>print('<STR_LIT>', _np.__version__, file=stream)<EOL><DEDENT>print('<STR_LIT>' % tuple(q('<STR_LIT>')), file=stream)<EOL>print('<STR_LIT>', sys.version, file=stream)<EOL> | Report versions | f13507:m9 |
def __getitem__(self, x): | try:<EOL><INDENT>return _K.__getitem__(self, x)<EOL><DEDENT>except (TypeError, NotImplementedError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>start, stop, step = x.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>i = K(x)<EOL>if self._t == <NUM_LIT> and i._t < <NUM_LIT:0>:<EOL><INDENT>return self.... | >>> k("10 20 30 40 50")[k("1 3")]
k('20 40')
>>> k("`a`b`c!1 2 3")['b']
2 | f13507:c0:m5 |
def __getattr__(self, a): | t = self._t<EOL>if t == <NUM_LIT>:<EOL><INDENT>return self._k(<NUM_LIT:0>, '<STR_LIT>' % a, self)<EOL><DEDENT>if t == <NUM_LIT>:<EOL><INDENT>if self._k(<NUM_LIT:0>, "<STR_LIT>", self):<EOL><INDENT>if a == '<STR_LIT>':<EOL><INDENT>raise AttributeError<EOL><DEDENT>return self._k(<NUM_LIT:0>, '<STR_LIT>' % a, self)<EOL><D... | table columns can be accessed via dot notation
>>> q("([]a:1 2 3; b:10 20 30)").a
k('1 2 3') | f13507:c0:m6 |
def __int__(self): | t = self._t<EOL>if t >= <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return int(self.inspect(self._fields[-t]))<EOL> | converts K scalars to python int
>>> [int(q(x)) for x in '1b 2h 3 4e `5 6.0 2000.01.08'.split()]
[1, 2, 3, 4, 5, 6, 7] | f13507:c0:m7 |
def __float__(self): | t = self._t<EOL>if t >= <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return float(self.inspect(self._fields[-t]))<EOL> | converts K scalars to python float
>>> [float(q(x)) for x in '1b 2h 3 4e `5 6.0 2000.01.08'.split()]
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] | f13507:c0:m8 |
def __eq__(self, other): | try:<EOL><INDENT>other = K(other)<EOL><DEDENT>except TypeError:<EOL><INDENT>return False<EOL><DEDENT>return bool(k('<STR_LIT>')(self, other))<EOL> | >>> K(1) == K(1)
True
>>> K(1) == None
False | f13507:c0:m11 |
def __ne__(self, other): | return bool(k('<STR_LIT>')(self, other))<EOL> | >>> K(1) != K(2)
True | f13507:c0:m12 |
def __contains__(self, item): | if self._t:<EOL><INDENT>x = q('<STR_LIT>', item, self)<EOL><DEDENT>else:<EOL><INDENT>x = q('<STR_LIT>', item, self)<EOL><DEDENT>return bool(x)<EOL> | membership test
>>> 1 in q('1 2 3')
True
>>> 'abc' not in q('(1;2.0;`abc)')
False | f13507:c0:m13 |
def keys(self): | return self._k(<NUM_LIT:0>, '<STR_LIT:key>', self)<EOL> | returns q('key', self)
Among other uses, enables interoperability between q and
python dicts.
>>> from collections import OrderedDict
>>> OrderedDict(q('`a`b!1 2'))
OrderedDict([('a', 1), ('b', 2)])
>>> d = {}; d.update(q('`a`b!1 2'))
>>> list(sorted(d.items()))... | f13507:c0:m14 |
def show(self, start=<NUM_LIT:0>, geometry=None, output=None): | if output is None:<EOL><INDENT>output = sys.stdout<EOL><DEDENT>if geometry is None:<EOL><INDENT>geometry = q.value(kp("<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>geometry = self._I(geometry)<EOL><DEDENT>if start < <NUM_LIT:0>:<EOL><INDENT>start += q.count(self)<EOL><DEDENT>if self._id() != nil._id():<EOL><INDENT>r = se... | pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
y| 2 20
z| 3 30
the first optional argument... | f13507:c0:m15 |
def select(self, columns=(), by=(), where=(), **kwds): | return self._seu('<STR_LIT>', columns, by, where, kwds)<EOL> | select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3 | f13507:c0:m18 |
def exec_(self, columns=(), by=(), where=(), **kwds): | return self._seu('<STR_LIT>', columns, by, where, kwds)<EOL> | exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3 | f13507:c0:m19 |
def update(self, columns=(), by=(), where=(), **kwds): | return self._seu('<STR_LIT>', columns, by, where, kwds)<EOL> | update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30 | f13507:c0:m20 |
def __fspath__(self): | if self._t != -<NUM_LIT:11>: <EOL><INDENT>raise TypeError<EOL><DEDENT>sym = str(self)<EOL>if not sym.startswith('<STR_LIT::>'):<EOL><INDENT>raise TypeError<EOL><DEDENT>return sym[<NUM_LIT:1>:]<EOL> | Return the file system path representation of the object. | f13507:c0:m24 |
def __complex__(self): | if self._t != <NUM_LIT> or self.key != ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return complex(float(self))<EOL><DEDENT>return complex(float(self.re), float(self.im))<EOL> | Called to implement the built-in function complex(). | f13507:c0:m25 |
@classmethod<EOL><INDENT>def dict(cls, *args, **kwds):<DEDENT> | if args:<EOL><INDENT>if len(args) > <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>x = args[<NUM_LIT:0>]<EOL>keys = []<EOL>vals = []<EOL>try:<EOL><INDENT>x_keys = x.keys<EOL><DEDENT>except AttributeError:<EOL><INDENT>for k, v in x:<EOL><INDENT>keys.append(k)<EOL>vals.append(v)<EOL><DEDENT><DEDENT>els... | Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yielding (key, value) pairs
K.dict(**k... | f13507:c0:m26 |
def __call__(self, m=None, *args): | try:<EOL><INDENT>return K._k(<NUM_LIT:0>, m, *map(K, args))<EOL><DEDENT>except TypeError:<EOL><INDENT>if m is not None:<EOL><INDENT>raise<EOL><DEDENT>if self._cmd is None:<EOL><INDENT>from .cmd import Cmd<EOL>object.__setattr__(self, '<STR_LIT>', Cmd())<EOL><DEDENT>self._cmd.cmdloop()<EOL><DEDENT> | Execute q code. | f13507:c1:m1 |
def console_size(fd=<NUM_LIT:1>): | try:<EOL><INDENT>import fcntl<EOL>import termios<EOL>import struct<EOL><DEDENT>except ImportError:<EOL><INDENT>size = os.getenv('<STR_LIT>', <NUM_LIT>), os.getenv('<STR_LIT>', <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>size = struct.unpack('<STR_LIT>', fcntl.ioctl(fd, termios.TIOCGWINSZ,<EOL>b'<STR_LIT>'))<EOL><DEDENT>re... | Return console size as a (LINES, COLUMNS) tuple | f13508:m0 |
def run(q_prompt=False): | lines, columns = console_size()<EOL>q(r'<STR_LIT>' % (lines, columns))<EOL>if len(sys.argv) > <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>q(r'<STR_LIT>' % sys.argv[<NUM_LIT:1>])<EOL><DEDENT>except kerr as e:<EOL><INDENT>print(e)<EOL>raise SystemExit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>del sys.argv[<NUM_LIT:1>]<EOL... | Run a prompt-toolkit based REPL | f13508:m1 |
def precmd(self, line): | if line.startswith('<STR_LIT>'):<EOL><INDENT>if not q("<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>q("<STR_LIT>")<EOL><DEDENT>except kerr:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT>if line == '<STR_LIT>':<EOL><INDENT>line += "<STR_LIT>"<EOL><DEDENT>return line<EOL> | Support for help | f13509:c0:m1 |
def onecmd(self, line): | if line == '<STR_LIT:\\>':<EOL><INDENT>return True<EOL><DEDENT>elif line == '<STR_LIT>':<EOL><INDENT>print('<STR_LIT:\r>', end='<STR_LIT>')<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>v = q(line)<EOL><DEDENT>except kerr as e:<EOL><INDENT>print("<STR_LIT>" % e.args[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL>... | Interpret the line | f13509:c0:m2 |
def get_bottom_toolbar_tokens(cli): | mem = q('<STR_LIT>', '<STR_LIT>') // <NUM_LIT> <EOL>return [(Token.Toolbar, "<STR_LIT>".format(KDB_INFO, mem))]<EOL> | Return a list of tokens for the bottom toolbar | f13510:m0 |
def get_prompt_tokens(_): | namespace = q(r'<STR_LIT>')<EOL>if namespace == '<STR_LIT:.>':<EOL><INDENT>namespace = '<STR_LIT>'<EOL><DEDENT>return [(Token.Generic.Prompt, '<STR_LIT>' % namespace)]<EOL> | Return a list of tokens for the prompt | f13510:m1 |
def cmdloop(self, intro=None): | style = style_from_pygments(BasicStyle, style_dict)<EOL>self.preloop()<EOL>stop = None<EOL>while not stop:<EOL><INDENT>line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,<EOL>get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,<EOL>history=history, style=style, true_color=True,<EOL>on_exit='<STR_LIT>', on_a... | A Cmd.cmdloop implementation | f13510:m2 |
def get_completions(self, document, complete_event): | <EOL>m = HSYM_RE.match(document.text_before_cursor)<EOL>if m:<EOL><INDENT>text = m.group(<NUM_LIT:1>)<EOL>doc = Document(text, len(text))<EOL>for c in self.path_completer.get_completions(doc, complete_event):<EOL><INDENT>yield c<EOL><DEDENT><DEDENT>else:<EOL><INDENT>word_before_cursor = document.get_word_before_cursor(... | Yield completions | f13510:c0:m1 |
def add_data_file(data_files, target, source): | for t, f in data_files:<EOL><INDENT>if t == target:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data_files.append((target, []))<EOL>f = data_files[-<NUM_LIT:1>][<NUM_LIT:1>]<EOL><DEDENT>if source not in f:<EOL><INDENT>f.append(source)<EOL><DEDENT> | Add an entry to data_files | f13511:m0 |
def get_q_home(env): | q_home = env.get('<STR_LIT>')<EOL>if q_home:<EOL><INDENT>return q_home<EOL><DEDENT>for v in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>prefix = env.get(v)<EOL>if prefix:<EOL><INDENT>q_home = os.path.join(prefix, '<STR_LIT:q>')<EOL>if os.path.isdir(q_home):<EOL><INDENT>return q_home<EOL><DEDENT><DEDENT><DEDENT>if WINDOWS:<... | Derive q home from the environment | f13511:m2 |
def get_q_version(q_home): | with open(os.path.join(q_home, '<STR_LIT>')) as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>return line[<NUM_LIT:2>:<NUM_LIT:5>]<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'<EOL> | Return version of q installed at q_home | f13511:m5 |
def compactness_frompts(geoseries): | measure = (<EOL><NUM_LIT:4> * <NUM_LIT> * (<EOL>(geoseries.unary_union).convex_hull.area)<EOL>) / (<EOL>(geoseries.unary_union).convex_hull.length<EOL>)<EOL>return measure<EOL> | Inverse of 4 * pi * Area / perimeter^2 | f13513:m2 |
def _get_target_nearest(self): | reps_query = """<STR_LIT>""".format(<EOL>maxorigin=self.origins.index.max(),<EOL>origin_table=self.origin_table,<EOL>target_table=self.target_table<EOL>)<EOL>nearest_reps = self.context.query(<EOL>reps_query,<EOL>decode_geom=True<EOL>)<EOL>nearest_reps = gpd.GeoDataFrame(nearest_reps, geometry='<STR_LIT>')<EOL>init_lab... | Get nearest target for each origin | f13513:c0:m2 |
def _get_demand_graph(self): | <EOL>K = self.origins.shape[<NUM_LIT:0>]<EOL>demand = self.nearest_targets.groupby('<STR_LIT>')['<STR_LIT>'].count().to_dict()<EOL>self.targets = self.targets.sort_values('<STR_LIT>').reset_index(drop=True)<EOL>g = nx.DiGraph()<EOL>g.add_nodes_from(self.targets['<STR_LIT>'], demand=-<NUM_LIT:1>)<EOL>for idx in demand:<... | create demand graph | f13513:c0:m3 |
def calc(self, maxiter=<NUM_LIT:100>, fixedprec=<NUM_LIT>): | source_data_holder = []<EOL>N = self.targets.shape[<NUM_LIT:0>]<EOL>K = self.origins.shape[<NUM_LIT:0>]<EOL>M, demand = self._get_demand_graph()<EOL>max_dist_trip = <NUM_LIT> <EOL>cost_holder = []<EOL>itercnt = <NUM_LIT:0><EOL>while True:<EOL><INDENT>itercnt += <NUM_LIT:1><EOL>logging.info(f'<STR_LIT>')<EOL>g = nx.DiG... | Min Cost Flow | f13513:c0:m4 |
def results_to_table(self): | <EOL>baseline_labels = self.nearest_targets['<STR_LIT>'].values<EOL>mcf_labels = self.results['<STR_LIT>']['<STR_LIT>'].values<EOL>outcome = pd.DataFrame({<EOL>'<STR_LIT>': [<EOL>'<STR_LIT>'.format(lng=v[<NUM_LIT:0>], lat=v[<NUM_LIT:1>])<EOL>for v in zip(self.results['<STR_LIT>']['<STR_LIT>'].values, self.results['<STR... | Process self.results and send to carto table | f13513:c0:m5 |
def is_profile_in_legacy_format(profile): | if isinstance(profile, dict):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(profile, str):<EOL><INDENT>try:<EOL><INDENT>profile = json.loads(profile)<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>if "<STR_LIT>" in profile:<EOL><INDENT>return False<... | Is a given profile JSON object in legacy format? | f13516:m1 |
def profile_v3_to_proofs(profile, fqdn, refresh=False, address = None): | proofs = []<EOL>try:<EOL><INDENT>test = list(profile.items())<EOL><DEDENT>except:<EOL><INDENT>return proofs<EOL><DEDENT>if '<STR_LIT>' in profile:<EOL><INDENT>accounts = profile['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return proofs<EOL><DEDENT>for account in accounts:<EOL><INDENT>if '<STR_LIT>' in account and accoun... | Convert profile format v3 to proofs | f13519:m5 |
def find_label(label, label_color, label_description): | edit = None<EOL>for name, values in label_list.items():<EOL><INDENT>color, description = values<EOL>if isinstance(name, tuple):<EOL><INDENT>old_name = name[<NUM_LIT:0>]<EOL>new_name = name[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>old_name = name<EOL>new_name = name<EOL><DEDENT>if label.lower() == old_name.lower():<EO... | Find label. | f13524:m0 |
def update_labels(repo): | updated = set()<EOL>for label in repo.get_labels():<EOL><INDENT>edit = find_label(label.name, label.color, label.description)<EOL>if edit is not None:<EOL><INDENT>print('<STR_LIT>'.format(edit.new, edit.color, edit.description))<EOL>label.edit(edit.new, edit.color, edit.description)<EOL>updated.add(edit.old)<EOL>update... | Update labels. | f13524:m1 |
def get_auth(): | import getpass<EOL>user = input("<STR_LIT>") <EOL>pswd = getpass.getpass('<STR_LIT>')<EOL>return Github(user, pswd)<EOL> | Get authentication. | f13524:m2 |
def main(): | if len(sys.argv) > <NUM_LIT:1> and os.path.exists(sys.argv[<NUM_LIT:1>]):<EOL><INDENT>try:<EOL><INDENT>with open(sys.argv[<NUM_LIT:1>], '<STR_LIT:r>') as f:<EOL><INDENT>user_name, password = f.read().strip().split('<STR_LIT::>')<EOL><DEDENT>git = Github(user_name, password)<EOL>password = None<EOL><DEDENT>except Except... | Main. | f13524:m3 |
def setUp(self): | sv.purge()<EOL>self.quirks = True<EOL> | Setup. | f13525:c2:m0 |
def skip_quirks(func): | def skip_if(self, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if self.quirks is True:<EOL><INDENT>raise pytest.skip('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return func(self, *args, **kwargs)<EOL><DEDENT><DEDENT>return skip_if<EOL> | Decorator that skips when quirks mode is enabled. | f13526:m0 |
def skip_py3(func): | def skip_if(self, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if PY3:<EOL><INDENT>raise pytest.skip('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return func(self, *args, **kwargs)<EOL><DEDENT><DEDENT>return skip_if<EOL> | Decorator that skips when running in Python 3. | f13526:m1 |
def available_parsers(*parsers): | ran_test = False<EOL>for parser in parsers:<EOL><INDENT>if (<EOL>(parser in ('<STR_LIT>', '<STR_LIT>') and not LXML_PRESENT) or<EOL>(parser == '<STR_LIT>' and not HTML5LIB_PRESENT)<EOL>):<EOL><INDENT>print('<STR_LIT>'.format(parser))<EOL><DEDENT>else:<EOL><INDENT>ran_test = True<EOL>yield parser<EOL><DEDENT><DEDENT>if ... | Filter a list of parsers, down to the available ones.
If there are none, report the test as skipped to pytest. | f13526:m2 |
def wrap_xhtml(self, html): | return """<STR_LIT>""".format(html)<EOL> | Wrap HTML content with XHTML header and body. | f13526:c0:m0 |
def setUp(self): | sv.purge()<EOL>self.quirks = False<EOL> | Setup. | f13526:c0:m1 |
def purge(self): | sv.purge()<EOL> | Purge cache. | f13526:c0:m2 |
def compile_pattern(self, selectors, namespaces=None, custom=None, flags=<NUM_LIT:0>): | print('<STR_LIT>', selectors)<EOL>flags |= sv.DEBUG<EOL>if self.quirks:<EOL><INDENT>flags |= sv._QUIRKS<EOL><DEDENT>return sv.compile(selectors, namespaces=namespaces, custom=custom, flags=flags)<EOL> | Compile pattern. | f13526:c0:m3 |
def soup(self, markup, parser): | print('<STR_LIT>', parser)<EOL>return bs4.BeautifulSoup(textwrap.dedent(markup.replace('<STR_LIT:\r\n>', '<STR_LIT:\n>')), parser)<EOL> | Get soup. | f13526:c0:m4 |
def get_parsers(self, flags): | mode = flags & <NUM_LIT><EOL>if mode == HTML:<EOL><INDENT>parsers = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif mode == PYHTML:<EOL><INDENT>parsers = ('<STR_LIT>',)<EOL><DEDENT>elif mode == LXML_HTML:<EOL><INDENT>parsers = ('<STR_LIT>',)<EOL><DEDENT>elif mode in (HTML5, <NUM_LIT:0>):<EOL><INDENT>parsers = ... | Get parsers. | f13526:c0:m5 |
def assert_raises(self, pattern, exception, namespace=None, custom=None): | print('<STR_LIT>')<EOL>with self.assertRaises(exception):<EOL><INDENT>self.compile_pattern(pattern, namespaces=namespace, custom=custom)<EOL><DEDENT> | Assert raises. | f13526:c0:m6 |
def assert_selector(self, markup, selectors, expected_ids, namespaces={}, custom=None, flags=<NUM_LIT:0>): | parsers = self.get_parsers(flags)<EOL>print('<STR_LIT>')<EOL>selector = self.compile_pattern(selectors, namespaces, custom)<EOL>for parser in available_parsers(*parsers):<EOL><INDENT>soup = self.soup(markup, parser)<EOL>ids = []<EOL>for el in selector.select(soup):<EOL><INDENT>print('<STR_LIT>', el.name)<EOL>ids.append... | Assert selector. | f13526:c0:m7 |
def setUp(self): | self.purge()<EOL>self.quirks = True<EOL> | Setup. | f13527:c1:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.