code stringlengths 1 18.2k |
|---|
def best_identities(self): """Returns identities of the best HSP in alignment. """ if len(self.hsp_list) > 0: return round(float(self.hsp_list[0].identities) / float(self.hsp_list[0].align_length) * 100, 1) |
def get_id(self): """Returns unique id of an alignment. """ return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) |
def render_template(template, **context): """Renders a given template and context. :param template: The template name :param context: the variables that should be available in the context of the template. """ parts = template.split('/') renderer = _get_renderer(parts[:-1]) return renderer.render(renderer.load_template(... |
def open(pattern, read_only=False): """ Return a root descriptor to work with one or multiple NetCDF files. Keyword arguments: pattern -- a list of filenames or a string pattern. """ root = NCObject.open(pattern, read_only=read_only) return root, root.is_new |
def getvar(root, name, vtype='', dimensions=(), digits=0, fill_value=None, source=None): """ Return a variable from a NCFile or NCPackage instance. If the variable doesn't exists create it. Keyword arguments: root -- the root descriptor returned by the 'open' function name -- the name of the variable vtype -- the type ... |
def loader(pattern, dimensions=None, distributed_dim='time', read_only=False): """ It provide a root descriptor to be used inside a with statement. It automatically close the root when the with statement finish. Keyword arguments: root -- the root descriptor returned by the 'open' function """ if dimensions: root = tai... |
def dict_copy(func): "copy dict args, to avoid modifying caller's copy" def proxy(*args, **kwargs): new_args = [] new_kwargs = {} for var in kwargs: if isinstance(kwargs[var], dict): new_kwargs[var] = dict(kwargs[var]) else: new_kwargs[var] = kwargs[var] for arg in args: if isinstance(arg, dict): new_args.append(dict(a... |
def is_listish(obj): """Check if something quacks like a list.""" if isinstance(obj, (list, tuple, set)): return True return is_sequence(obj) |
def unique_list(lst): """Make a list unique, retaining order of initial appearance.""" uniq = [] for item in lst: if item not in uniq: uniq.append(item) return uniq |
def _get_main_language(): """ returns the main language :return: """ try: main_language = TransLanguage.objects.filter(main_language=True).get() return main_language.code except TransLanguage.DoesNotExist: return 'es' |
def fields_need_translation(self, elem, destination_lang): """ Detect if the tuple needs translation and which fields has to be translated :param elem :param destination_lang: :return: """ fields = self._get_translated_field_names(elem) elem_langs = elem.get_available_languages() # if we don't have a translation for th... |
def check_compatibility(datasets, reqd_num_features=None): """ Checks whether the given MLdataset instances are compatible i.e. with same set of subjects, each beloning to the same class in all instances. Checks the first dataset in the list against the rest, and returns a boolean array. Parameters ---------- datasets ... |
mismatch in dimensionality from that specified size_descriptor : tuple A tuple with values for (num_samples, reqd_num_features) - num_samples must be common for all datasets that are evaluated for compatibility - reqd_num_features is None (when no check on dimensionality is perfomed), or list of corresponding dimension... |
for all reqd_num_features = [int(reqd_num_features)] * num_datasets check_dimensionality = True else: # to enable iteration reqd_num_features = [None,] * num_datasets pivot = datasets[0] if not isinstance(pivot, MLDataset): pivot = MLDataset(pivot) if check_dimensionality and pivot.num_features != reqd_num_features[0]:... |
def cli_run(): """ Command line interface This interface saves you coding effort to: - display basic info (classes, sizes etc) about datasets - display meta data (class membership) for samples - perform basic arithmetic (add multiple classes or feature sets) """ path_list, meta_requested, summary_requested, add_path_li... |
def print_info(ds, ds_path=None): "Prints basic summary of a given dataset." if ds_path is None: bname = '' else: bname = basename(ds_path) dashes = '-' * len(bname) print('\n{}\n{}\n{:full}'.format(dashes, bname, ds)) return |
def print_meta(ds, ds_path=None): "Prints meta data for subjects in given dataset." print('\n#' + ds_path) for sub, cls in ds.classes.items(): print('{},{}'.format(sub, cls)) return |
def combine_and_save(add_path_list, out_path): """ Combines whatever datasets that can be combined, and save the bigger dataset to a given location. """ add_path_list = list(add_path_list) # first one! first_ds_path = add_path_list[0] print('Starting with {}'.format(first_ds_path)) combined = MLDataset(first_ds_path) f... |
def get_parser(): """Argument specifier. """ parser = argparse.ArgumentParser(prog='pyradigm') parser.add_argument('path_list', nargs='*', action='store', default=None, help='List of paths to display info about.') parser.add_argument('-m', '--meta', action='store_true', dest='meta_requested', required=False, default=Fa... |
def parse_args(): """Arg parser. """ parser = get_parser() if len(sys.argv) < 2: parser.print_help() logging.warning('Too few arguments!') parser.exit(1) # parsing try: params = parser.parse_args() except Exception as exc: print(exc) raise ValueError('Unable to parse command-line arguments.') path_list = list() if para... |
path_list = set(path_list) add_path_list = set(add_path_list) return path_list, params.meta_requested, params.summary_requested, \ add_path_list, out_path |
def data_and_labels(self): """ Dataset features and labels in a matrix form for learning. Also returns sample_ids in the same order. Returns ------- data_matrix : ndarray 2D array of shape [num_samples, num_features] with features corresponding row-wise to sample_ids labels : ndarray Array of numeric labels for each sa... |
def data(self, values, feature_names=None): """ Populates this dataset with the provided data. Usage of this method is discourage (unless you know what you are doing). Parameters ---------- values : dict dict of features keyed in by sample ids. feature_names : list of str New feature names for the new features, if avai... |
have same len arrays self.__num_features = len(values[self.keys[0]]) if feature_names is None: self.__feature_names = self.__str_names(self.num_features) else: self.feature_names = feature_names else: raise ValueError('data input must be a dictionary!') |
def labels(self, values): """Class labels (such as 1, 2, -1, 'A', 'B' etc.) for each sample in the dataset.""" if isinstance(values, dict): if self.__data is not None and len(self.__data) != len(values): raise ValueError( 'number of samples do not match the previously assigned data') elif set(self.keys) != set(list(val... |
def classes(self, values): """Classes setter.""" if isinstance(values, dict): if self.__data is not None and len(self.__data) != len(values): raise ValueError( 'number of samples do not match the previously assigned data') elif set(self.keys) != set(list(values)): raise ValueError('sample ids do not match the previousl... |
def feature_names(self, names): "Stores the text labels for features" if len(names) != self.num_features: raise ValueError("Number of names do not match the number of features!") if not isinstance(names, (Sequence, np.ndarray, np.generic)): raise ValueError("Input is not a sequence. " "Ensure names are in the same orde... |
def glance(self, nitems=5): """Quick and partial glance of the data matrix. Parameters ---------- nitems : int Number of items to glance from the dataset. Default : 5 Returns ------- dict """ nitems = max([1, min([nitems, self.num_samples - 1])]) return self.__take(nitems, iter(self.__data.items())) |
def summarize_classes(self): """ Summary of classes: names, numeric labels and sizes Returns ------- tuple : class_set, label_set, class_sizes class_set : list List of names of all the classes label_set : list Label for each class in class_set class_sizes : list Size of each class (number of samples) """ class_sizes = ... |
def check_features(self, features): """ Method to ensure data to be added is not empty and vectorized. Parameters ---------- features : iterable Any data that can be converted to a numpy array. Returns ------- features : numpy array Flattened non-empty numpy array. Raises ------ ValueError If input data is empty. """ i... |
def add_sample(self, sample_id, features, label, class_id=None, overwrite=False, feature_names=None): """Adds a new sample to the dataset with its features, label and class ID. This is the preferred way to construct the dataset. Parameters ---------- sample_id : str, int The identifier that uniquely identifies this sam... |
overwrite=False), or If dimensionality of the current sample does not match the current, or If `feature_names` do not match existing names TypeError If sample to be added is of different data type compared to existing samples. """ if sample_id in self.__data and not overwrite: raise ValueError('{} already exists in thi... |
= type(features) self.__num_features = features.size if isinstance(features, np.ndarray) else len( features) if feature_names is None: self.__feature_names = self.__str_names(self.num_features) else: if self.__num_features != features.size: raise ValueError('dimensionality of this sample ({}) ' 'does not match existing... |
def del_sample(self, sample_id): """ Method to remove a sample from the dataset. Parameters ---------- sample_id : str sample id to be removed. Raises ------ UserWarning If sample id to delete was not found in the dataset. """ if sample_id not in self.__data: warnings.warn('Sample to delete not found in the dataset - n... |
def get_feature_subset(self, subset_idx): """ Returns the subset of features indexed numerically. Parameters ---------- subset_idx : list, ndarray List of indices to features to be returned Returns ------- MLDataset : MLDataset with subset of features requested. Raises ------ UnboundLocalError If input indices are out ... |
def keys_with_value(dictionary, value): "Returns a subset of keys from the dict with the value supplied." subset = [key for key in dictionary if dictionary[key] == value] return subset |
def get_class(self, class_id): """ Returns a smaller dataset belonging to the requested classes. Parameters ---------- class_id : str or list identifier(s) of the class(es) to be returned. Returns ------- MLDataset With subset of samples belonging to the given class(es). Raises ------ ValueError If one or more of the r... |
def transform(self, func, func_description=None): """ Applies a given a function to the features of each subject and returns a new dataset with other info unchanged. Parameters ---------- func : callable A valid callable that takes in a single ndarray and returns a single ndarray. Ensure the transformed dimensionality ... |
import MLDataset thickness = MLDataset(in_path='ADNI_thickness.csv') pcg_thickness = thickness.apply_xfm(func=get_pcg, description = 'applying ROI mask for PCG') pcg_median = pcg_thickness.apply_xfm(func=np.median, description='median per subject') Complex example with function taking more than one argument: .. code-bl... |
def random_subset_ids_by_count(self, count_per_class=1): """ Returns a random subset of sample ids of specified size by count, within each class. Parameters ---------- count_per_class : int Exact number of samples per each class. Returns ------- subset : list Combined list of sample ids from all classes. """ class_size... |
this_class is None: # warning if none were selected warnings.warn('No subjects from class {} were selected.'.format(class_id)) else: subsets_this_class = this_class[0:count_per_class] subsets.extend(subsets_this_class) if len(subsets) > 0: return subsets else: warnings.warn('Zero samples were selected. Returning an emp... |
def random_subset_ids(self, perc_per_class=0.5): """ Returns a random subset of sample ids (size in percentage) within each class. Parameters ---------- perc_per_class : float Fraction of samples per class Returns ------- subset : list Combined list of sample ids from all classes. Raises ------ ValueError If no subject... |
works in-place! random.shuffle(this_class) # calculating the requested number of samples subset_size_this_class = np.int64(np.floor(class_size * perc_per_class)) # clipping the range to [1, n] subset_size_this_class = max(1, min(class_size, subset_size_this_class)) if subset_size_this_class < 1 or len(this_class) < 1 o... |
def random_subset(self, perc_in_class=0.5): """ Returns a random sub-dataset (of specified size by percentage) within each class. Parameters ---------- perc_in_class : float Fraction of samples to be taken from each class. Returns ------- subdataset : MLDataset random sub-dataset of specified size. """ subsets = self.r... |
def sample_ids_in_class(self, class_id): """ Returns a list of sample ids belonging to a given class. Parameters ---------- class_id : str class id to query. Returns ------- subset_ids : list List of sample ids belonging to a given class. """ # subset_ids = [sid for sid in self.keys if self.classes[sid] == class_id] su... |
def get_subset(self, subset_ids): """ Returns a smaller dataset identified by their keys/sample IDs. Parameters ---------- subset_ids : list List od sample IDs to extracted from the dataset. Returns ------- sub-dataset : MLDataset sub-dataset containing only requested sample IDs. """ num_existing_keys = sum([1 for key ... |
None: classes = self.__get_subset_from_dict(self.__classes, subset_ids) else: classes = None subdataset = MLDataset(data=data, labels=labels, classes=classes) # Appending the history subdataset.description += '\n Subset derived from: ' + self.description subdataset.feature_names = self.__feature_names subdataset.__dtyp... |
def get_data_matrix_in_order(self, subset_ids): """ Returns a numpy array of features, rows in the same order as subset_ids Parameters ---------- subset_ids : list List od sample IDs to extracted from the dataset. Returns ------- matrix : ndarray Matrix of features, for each id in subset_ids, in order. """ if len(subse... |
in enumerate(subset_ids): matrix[idx, :] = self.__data[sid] return matrix |
def get(self, item, not_found_value=None): "Method like dict.get() which can return specified value if key not found" if item in self.keys: return self.__data[item] else: return not_found_value |
def label_set(self): """Set of labels in the dataset corresponding to class_set.""" label_set = list() for class_ in self.class_set: samples_in_class = self.sample_ids_in_class(class_) label_set.append(self.labels[samples_in_class[0]]) return label_set |
def add_classes(self, classes): """ Helper to rename the classes, if provided by a dict keyed in by the orignal keys Parameters ---------- classes : dict Dict of class named keyed in by sample IDs. Raises ------ TypeError If classes is not a dict. ValueError If all samples in dataset are not present in input dict, or o... |
def __copy(self, other): """Copy constructor.""" self.__data = copy.deepcopy(other.data) self.__classes = copy.deepcopy(other.classes) self.__labels = copy.deepcopy(other.labels) self.__dtype = copy.deepcopy(other.dtype) self.__description = copy.deepcopy(other.description) self.__feature_names = copy.deepcopy(other.fe... |
def __load(self, path): """Method to load the serialized dataset from disk.""" try: path = os.path.abspath(path) with open(path, 'rb') as df: # loaded_dataset = pickle.load(df) self.__data, self.__classes, self.__labels, \ self.__dtype, self.__description, \ self.__num_features, self.__feature_names = pickle.load(df) #... |
def __load_arff(self, arff_path, encode_nonnumeric=False): """Loads a given dataset saved in Weka's ARFF format. """ try: from scipy.io.arff import loadarff arff_data, arff_meta = loadarff(arff_path) except: raise ValueError('Error loading the ARFF dataset!') attr_names = arff_meta.names()[:-1] # last column is class a... |
# initializing the key containers, before calling self.add_sample self.__data = OrderedDict() self.__labels = OrderedDict() self.__classes = OrderedDict() num_samples = len(arff_data) num_digits = len(str(num_samples)) make_id = lambda index: 'row{index:0{nd}d}'.format(index=index, nd=num_digits) sample_classes = [cls.... |
def save(self, file_path): """ Method to save the dataset to disk. Parameters ---------- file_path : str File path to save the current dataset to Raises ------ IOError If saving to disk is not successful. """ # TODO need a file format that is flexible and efficient to allow the following: # 1) being able to read just m... |
raise |
def __validate(data, classes, labels): "Validator of inputs." if not isinstance(data, dict): raise TypeError( 'data must be a dict! keys: sample ID or any unique identifier') if not isinstance(labels, dict): raise TypeError( 'labels must be a dict! keys: sample ID or any unique identifier') if classes is not None: if n... |
def extend(self, other): """ Method to extend the dataset vertically (add samples from anotehr dataset). Parameters ---------- other : MLDataset second dataset to be combined with the current (different samples, but same dimensionality) Raises ------ TypeError if input is not an MLDataset. """ if not isinstance(other, ... |
def validate_word_size(word_size, BLAST_SETS): """Validate word size in blast/tblastn form. """ blast_min_int_word_size = BLAST_SETS.min_word_size blast_max_int_word_size = BLAST_SETS.max_word_size blast_word_size_error = BLAST_SETS.get_word_size_error() try: if len(word_size) <= 0: raise forms.ValidationError(blast_wo... |
def validate_sequence(sequence: str, sequence_is_as_nucleotide=True): """Validate sequence in blast/tblastn form. """ tmp_seq = tempfile.NamedTemporaryFile(mode="wb+", delete=False) if len(str(sequence).strip()) == 0: raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG) if str(sequence).strip()[0] !=... |
def check_allowed_letters(seq, allowed_letters_as_set): """Validate sequence: Rise an error if sequence contains undesirable letters. """ # set of unique letters in sequence seq_set = set(seq) not_allowed_letters_in_seq = [x for x in seq_set if str(x).upper() not in allowed_letters_as_set] if len(not_allowed_letters_in... |
def _repeat(func): """Repeats func(...) call until something other than None is returned.""" @functools.wraps(func) def wrapper(*args, **kwargs): """Repeats the call until True is returned.""" ret = None while ret is None: ret = func(*args, **kwargs) return ret return wrapper |
def init(pandocversion=None, doc=None): """Sets or determines the pandoc version. This must be called. The pandoc version is needed for multi-version support. See: https://github.com/jgm/pandoc/issues/2640 Returns the pandoc version.""" # This requires some care because we can't be sure that a call to 'pandoc' # will w... |
not doc is None: if 'pandoc-api-version' in doc: # This could be either 1.18 or 1.19; there is no way to # distinguish them (but there isn't a use case in pandoc-fignos # and friends where it matters) _PANDOCVERSION = '1.18' return _PANDOCVERSION # Get the command try: # Get the path for the parent process if os.name =... |
# pylint: disable=bare-except pandocversion = '' # Test the result and if it is OK then store it in _PANDOCVERSION if pattern.match(pandocversion): _PANDOCVERSION = pandocversion if _PANDOCVERSION is None: msg = """Cannot determine pandoc version. Please file an issue at https://github.com/tomduck/pandocfiltering/issue... |
def get_meta(meta, name): """Retrieves the metadata variable 'name' from the 'meta' dict.""" assert name in meta data = meta[name] if data['t'] in ['MetaString', 'MetaBool']: return data['c'] elif data['t'] == 'MetaInlines': # Handle bug in pandoc 2.2.3 and 2.2.3.1: Return boolean value rather # than strings, as approp... |
def elt(eltType, numargs): # pylint: disable=invalid-name """Returns Element(*value) to create pandoc json elements. This should be used in place of pandocfilters.elt(). This version ensures that the content is stored in a list, not a tuple. """ def Element(*value): # pylint: disable=invalid-name """Creates an element.... |
def _getel(key, value): """Returns an element given a key and value.""" if key in ['HorizontalRule', 'Null']: return elt(key, 0)() elif key in ['Plain', 'Para', 'BlockQuote', 'BulletList', 'DefinitionList', 'HorizontalRule', 'Null']: return elt(key, 1)(value) return elt(key, len(value))(*value) |
def quotify(x): """Replaces Quoted elements in element list 'x' with quoted strings. Pandoc uses the Quoted element in its json when --smart is enabled. Output to TeX/pdf automatically triggers --smart. stringify() ignores Quoted elements. Use quotify() first to replace Quoted elements in 'x' with quoted strings. 'x' s... |
'', {}), join_strings, '', {}) |
def dollarfy(x): """Replaces Math elements in element list 'x' with a $-enclosed string. stringify() passes through TeX math. Use dollarfy(x) first to replace Math elements with math strings set in dollars. 'x' should be a deep copy so that the underlying document is left untouched. Returns 'x'.""" def _dollarfy(key, v... |
def extract_attrs(x, n): """Extracts attributes from element list 'x' beginning at index 'n'. The elements encapsulating the attributes (typically a series of Str and Space elements) are removed from 'x'. Items before index 'n' are left unchanged. Returns the attributes in pandoc format. A ValueError is raised if attri... |
in strings flag = False # Flags that an attributes list was found i = 0 # Initialization for i, v in enumerate(x[n:]): # Scan through the list if v and v['t'] == 'Str': # Scan for } outside of a quote for j, c in enumerate(v['c']): if c == quotechar: # This is an end quote quotechar = None elif c in ['"', "'"]: # This ... |
process it # Delete empty and extracted elements if x[n+i]['t'] == 'Str' and not x[n+i]['c']: del x[n+i] del x[n:n+i] # Process the attrs attrstr = stringify(dollarfy(quotify(seq))).strip() attrs = PandocAttributes(attrstr, 'markdown').to_pandoc() # Remove extranneous quotes from kvs for i, (k, v) in enumerate(attrs[2]... |
def _join_strings(x): """Joins adjacent Str elements found in the element list 'x'.""" for i in range(len(x)-1): # Process successive pairs of elements if x[i]['t'] == 'Str' and x[i+1]['t'] == 'Str': x[i]['c'] += x[i+1]['c'] del x[i+1] # In-place deletion of element from list return None # Forces processing to repeat r... |
def join_strings(key, value, fmt, meta): # pylint: disable=unused-argument """Joins adjacent Str elements in the 'value' list.""" if key in ['Para', 'Plain']: _join_strings(value) elif key == 'Image': _join_strings(value[-2]) elif key == 'Table': _join_strings(value[-5]) |
def _is_broken_ref(key1, value1, key2, value2): """True if this is a broken reference; False otherwise.""" # A link followed by a string may represent a broken reference if key1 != 'Link' or key2 != 'Str': return False # Assemble the parts n = 0 if _PANDOCVERSION < '1.16' else 1 if isinstance(value1[n][0]['c'], list): ... |
def _repair_refs(x): """Performs the repair on the element list 'x'.""" if _PANDOCVERSION is None: raise RuntimeError('Module uninitialized. Please call init().') # Scan the element list x for i in range(len(x)-1): # Check for broken references if _is_broken_ref(x[i]['t'], x[i]['c'] if 'c' in x[i] else [], x[i+1]['t'],... |
"c":[]}, "citationHash":0}], [Str('@' + label)]) if prefix: if i > 0 and x[i-1]['t'] == 'Str': x[i-1]['c'] = x[i-1]['c'] + prefix del x[i] else: x[i] = Str(prefix) else: del x[i] return None # Forces processing to repeat return True |
def repair_refs(key, value, fmt, meta): # pylint: disable=unused-argument """Using "-f markdown+autolink_bare_uris" with pandoc < 1.18 splits a reference like "{@fig:one}" into email Link and Str elements. This function replaces the mess with the Cite and Str elements we normally get. Call this before any reference pro... |
def _extract_modifier(x, i, attrs): """Extracts the */+/! modifier in front of the Cite at index 'i' of the element list 'x'. The modifier is stored in 'attrs'. Returns the updated index 'i'.""" global _cleveref_tex_flag # pylint: disable=global-statement assert x[i]['t'] == 'Cite' assert i > 0 # Check the previous ele... |
def _remove_brackets(x, i): """Removes curly brackets surrounding the Cite element at index 'i' in the element list 'x'. It is assumed that the modifier has been extracted. Empty strings are deleted from 'x'.""" assert x[i]['t'] == 'Cite' assert i > 0 and i < len(x) - 1 # Check if the surrounding elements are strings i... |
def _process_refs(x, labels): """Strips surrounding curly braces and adds modifiers to the attributes of Cite elements. Only references with labels in the 'labels' list are processed. Repeats processing (via decorator) until no more broken references are found.""" # Scan the element list x for Cite elements with known ... |
0 and i < len(x)-1: _remove_brackets(x, i) # The element list may be changed return None # Forces processing to repeat via _repeat decorator return True |
def process_refs_factory(labels): """Returns process_refs(key, value, fmt, meta) action that processes text around a reference. Only references with labels found in the 'labels' list are processed. Consider the markdown "{+@fig:1}", which represents a reference to a figure. "@" denotes a reference, "fig:1" is the refer... |
key in ['Para', 'Plain']: _process_refs(value, labels) elif key == 'Image': _process_refs(value[-2], labels) elif key == 'Table': _process_refs(value[-5], labels) elif key == 'Span': _process_refs(value[-1], labels) elif key == 'Emph': _process_refs(value, labels) elif key == 'Strong': _process_refs(value, labels) retu... |
def replace_refs_factory(references, use_cleveref_default, use_eqref, plusname, starname, target): """Returns replace_refs(key, value, fmt, meta) action that replaces references with format-specific content. The content is determined using the 'references' dict, which associates reference labels with numbers or string ... |
value, meta): r"""Inserts TeX to support clever referencing in LaTeX documents if the key isn't a RawBlock. If the key is a RawBlock, then check the value to see if the TeX was already inserted. The \providecommand macro is used to fake the cleveref package's behaviour if it is not provided in the template via \usepack... |
False # Cancels further attempts ret = [] # Check first to see if fakery is turned off if not 'xnos-cleveref-fake' in meta or \ check_bool(get_meta(meta, 'xnos-cleveref-fake')): # Cleveref fakery tex2 = [ r'% pandoc-xnos: cleveref fakery', r'\newcommand{\plusnamesingular}{}', r'\newcommand{\starnamesingular}{}', r'\new... |
plusname[0] if plus else starname[0] # Name used by cref # The replacement depends on the output format if fmt == 'latex': if use_cleveref: # Renew commands needed for cleveref fakery if not 'xnos-cleveref-fake' in meta or \ check_bool(get_meta(meta, 'xnos-cleveref-fake')): faketex = (r'\xrefname' if plus else r'\Xrefn... |
([Str(name), Space()] if use_cleveref else []) + [link] return ret def replace_refs(key, value, fmt, meta): # pylint: disable=unused-argument """Replaces references with format-specific content.""" if fmt == 'latex' and _cleveref_tex_flag: # Put the cleveref TeX fakery in front of the first block element # that isn't a... |
def attach_attrs_factory(f, extract_attrs=extract_attrs, allow_space=False): """Returns attach_attrs(key, value, fmt, meta) action that reads and attaches attributes to unattributed elements generated by the pandocfilters function f (e.g. pandocfilters.Math, etc). The extract_attrs() function should read the attributes... |
Image: Add pandoc's figure marker if warranted if len(value) == 1 and value[0]['t'] == 'Image': value[0]['c'][-1][1] = 'fig:' return attach_attrs |
def detach_attrs_factory(f): """Returns detach_attrs(key, value, fmt, meta) action that detaches attributes attached to elements of type f (e.g. pandocfilters.Math, etc). Attributes provided natively by pandoc will be left as is.""" # Get the name and standard length name = f.__closure__[0].cell_contents n = f.__closur... |
def insert_secnos_factory(f): """Returns insert_secnos(key, value, fmt, meta) action that inserts section numbers into the attributes of elements of type f. """ # Get the name and standard length name = f.__closure__[0].cell_contents n = f.__closure__[1].cell_contents def insert_secnos(key, value, fmt, meta): # pylint:... |
attributes assert len(value[0]) == 3 assert isinstance(value[0][0], STRTYPES) assert isinstance(value[0][1], list) assert isinstance(value[0][2], list) # Insert the section number into the attributes s = '.'.join([str(m) for m in sec]) value[0][2].insert(0, ['secno', s]) return insert_secnos |
def delete_secnos_factory(f): """Returns delete_secnos(key, value, fmt, meta) action that deletes section numbers from the attributes of elements of type f. """ # Get the name and standard length name = f.__closure__[0].cell_contents n = f.__closure__[1].cell_contents def delete_secnos(key, value, fmt, meta): # pylint:... |
def insert_rawblocks_factory(rawblocks): r"""Returns insert_rawblocks(key, value, fmt, meta) action that inserts non-duplicate RawBlock elements. """ # pylint: disable=unused-argument def insert_rawblocks(key, value, fmt, meta): """Inserts non-duplicate RawBlock elements.""" if not rawblocks: return None # Put the RawB... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.