code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
logger = logging.getLogger(__name__) logger.debug('[%s] deblur system call params %s, input_fp %s' % (mp.current_process().name, params, input_fp)) # construct command script_name = "deblur" script_subprogram = "workflow" command = [script_name, script_subpr...
def deblur_system_call(params, input_fp)
Build deblur command for subprocess. Parameters ---------- params: list of str parameter settings to pass to deblur CLI input_fp : str name of the input fasta file to deblur Returns ------- stdout: string process output directed to standard output stderr: string...
4.01178
4.030858
0.995267
try: # This is where you do your actual work return functor(*args, **kwargs) except Exception: # Put all exception text into an exception and raise that raise Exception("".join(traceback.format_exception(*sys.exc_info())))
def run_functor(functor, *args, **kwargs)
Given a functor, run it and return its result. We can use this with multiprocessing.map and map it over a list of job functors to do them. Handles getting more than multiprocessing's pitiful exception output This function was derived from: http://stackoverflow.com/a/16618842/19741 This code was a...
5.003894
5.302186
0.943742
logger = logging.getLogger(__name__) logger.info('parallel deblur started for %d inputs' % len(inputs)) # remove the irrelevant parameters remove_param_list = ['-O', '--jobs-to-start', '--seqs-fp', '--pos-ref-db-fp', '--neg-ref-db-fp'] skipnext = False newparams = ...
def parallel_deblur(inputs, params, pos_ref_db_fp, neg_ref_dp_fp, jobs_to_start=1)
Dispatch execution over a pool of processors This code was adopted from the American Gut project: https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py Parameters ---------- inputs : iterable of str File paths to input per-sample sequence files params : list of st...
2.942707
2.908999
1.011587
logger = logging.getLogger(__name__) kw = {} if sniff_fasta(input_fp)[0]: format = 'fasta' elif sniff_fastq(input_fp)[0]: format = 'fastq' kw['variant'] = _get_fastq_variant(input_fp) else: # usually happens when the fasta file is empty # so need to retu...
def sequence_generator(input_fp)
Yield (id, sequence) from an input file Parameters ---------- input_fp : filepath A filepath, which can be any valid fasta or fastq file within the limitations of scikit-bio's IO registry. Notes ----- The use of this method is a stopgap to replicate the existing `parse_fasta` ...
4.293672
4.25495
1.009101
# counters for the number of trimmed and total sequences logger = logging.getLogger(__name__) okseqs = 0 totseqs = 0 if trim_len < -1: raise ValueError("Invalid trim_len: %d" % trim_len) for label, seq in input_seqs: totseqs += 1 if trim_len == -1: ok...
def trim_seqs(input_seqs, trim_len, left_trim_len)
Trim FASTA sequences to specified length. Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format trim_len : int Sequence trimming length. Specify a value of -1 to disable trimming. left_trim_len : int Sequence trimmi...
3.117738
3.063743
1.017624
logger = logging.getLogger(__name__) logger.info('dereplicate seqs file %s' % seqs_fp) log_name = "%s.log" % output_fp params = ['vsearch', '--derep_fulllength', seqs_fp, '--output', output_fp, '--sizeout', '--fasta_width', '0', '--minuniquesize', str(min_size), ...
def dereplicate_seqs(seqs_fp, output_fp, min_size=2, use_log=False, threads=1)
Dereplicate FASTA sequences and remove singletons using VSEARCH. Parameters ---------- seqs_fp : string filepath to FASTA sequence file output_fp : string file path to dereplicated sequences (FASTA format) min_size : integer, optional discard sequences with an abundance valu...
3.407756
3.373843
1.010052
logger = logging.getLogger(__name__) logger.info('build_index_sortmerna files %s to' ' dir %s' % (ref_fp, working_dir)) all_db = [] for db in ref_fp: fasta_dir, fasta_filename = split(db) index_basename = splitext(fasta_filename)[0] db_output = join(working_d...
def build_index_sortmerna(ref_fp, working_dir)
Build a SortMeRNA index for all reference databases. Parameters ---------- ref_fp: tuple filepaths to FASTA reference databases working_dir: string working directory path where to store the indexed database Returns ------- all_db: tuple filepaths to SortMeRNA indexe...
3.369129
3.223405
1.045208
logger = logging.getLogger(__name__) logger.debug('filter_minreads_started. minreads=%d' % minreads) samp_sum = table.sum(axis='sample') samp_ids = table.ids(axis='sample') bad_samples = samp_ids[samp_sum < minreads] if len(bad_samples) > 0: logger.warn('removed %d samples with read...
def filter_minreads_samples_from_table(table, minreads=1, inplace=True)
Filter samples from biom table that have less than minreads reads total Paraneters ---------- table : biom.Table the biom table to filter minreads : int (optional) the minimal number of reads in a sample in order to keep it inplace : bool (optional) if True, filter the b...
3.159625
3.278537
0.96373
'''Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file ''' logger = logging.getLogger(__name__) logger.debug('saving biom table sequences to ...
def fasta_from_biom(table, fasta_file_name)
Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file
2.123549
1.947781
1.09024
logger = logging.getLogger(__name__) logger.info('getting 16s sequences from the biom table') # remove artifacts from the fasta file. output is in clean_fp fasta file clean_fp, num_seqs_left, tmp_files = remove_artifacts_seqs(fasta_filename, ref_fp, ...
def remove_artifacts_from_biom_table(table_filename, fasta_filename, ref_fp, biom_table_dir, ref_db_fp, threads=1, ...
Remove artifacts from a biom table using SortMeRNA Parameters ---------- table : str name of the biom table file fasta_filename : str the fasta file containing all the sequences of the biom table Returns ------- tmp_files : list of str The temp files created during ...
2.839221
2.855935
0.994148
logger = logging.getLogger(__name__) logger.info('multiple_sequence_alignment seqs file %s' % seqs_fp) # for mafft we use -1 to denote all threads and not 0 if threads == 0: threads = -1 if stat(seqs_fp).st_size == 0: logger.warning('msa failed. file %s has no reads' % seqs_fp...
def multiple_sequence_alignment(seqs_fp, threads=1)
Perform multiple sequence alignment on FASTA file using MAFFT. Parameters ---------- seqs_fp: string filepath to FASTA file for multiple sequence alignment threads: integer, optional number of threads to use. 0 to use all threads Returns ------- msa_fp : str name of...
4.113053
3.945954
1.042347
logger = logging.getLogger(__name__) logger.info('remove_chimeras_denovo_from_seqs seqs file %s' 'to working dir %s' % (seqs_fp, working_dir)) output_fp = join( working_dir, "%s.no_chimeras" % basename(seqs_fp)) # we use the parameters dn=0.000001, xn=1000, minh=10000000 ...
def remove_chimeras_denovo_from_seqs(seqs_fp, working_dir, threads=1)
Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads : int number of threads (0 for all cores) Returns ------- ...
4.635466
4.751561
0.975567
logger = logging.getLogger(__name__) logger.info('split_sequence_file_on_sample_ids_to_files' ' for file %s into dir %s' % (seqs, outdir)) outputs = {} for bits in sequence_generator(seqs): sample = sample_id_from_read_id(bits[0]) if sample not in outputs: ...
def split_sequence_file_on_sample_ids_to_files(seqs, outdir)
Split FASTA file on sample IDs. Parameters ---------- seqs: file handler file handler to demultiplexed FASTA file outdir: string dirpath to output split FASTA files
2.675387
2.739714
0.97652
logger = logging.getLogger(__name__) logger.debug('write_biom_table to file %s' % biom_fp) with biom_open(biom_fp, 'w') as f: table.to_hdf5(h5grp=f, generated_by="deblur") logger.debug('wrote to BIOM file %s' % biom_fp)
def write_biom_table(table, biom_fp)
Write BIOM table to file. Parameters ---------- table: biom.table an instance of a BIOM table biom_fp: string filepath to output BIOM table
3.649153
3.725982
0.97938
logger = logging.getLogger(__name__) logger.debug('get_files_for_table input dir %s, ' 'file-ending %s' % (input_dir, file_end)) names = [] for cfile in glob(join(input_dir, "*%s" % file_end)): if not isfile(cfile): continue sample_id = basename(cfile)[:...
def get_files_for_table(input_dir, file_end='.trim.derep.no_artifacts' '.msa.deblur.no_chimeras')
Get a list of files to add to the output table Parameters: ----------- input_dir : string name of the directory containing the deblurred fasta files file_end : string the ending of all the fasta files to be added to the table (default '.fasta.trim.derep.no_artifacts.msa.deblur.n...
2.431873
2.470947
0.984186
if filename is None: tstr = time.ctime() tstr = tstr.replace(' ', '.') tstr = tstr.replace(':', '.') filename = 'deblur.log.%s' % tstr logging.basicConfig(filename=filename, level=level, format='%(levelname)s(%(thread)d)' '%(as...
def start_log(level=logging.DEBUG, filename=None)
start the logger for the run Parameters ---------- level : int, optional logging.DEBUG, logging.INFO etc. for the log level (between 0-50). filename : str, optional name of the filename to save the log to or None (default) to use deblur.log.TIMESTAMP
2.939533
2.879953
1.020688
logger = logging.getLogger(__name__) logger.debug('system call: %s' % cmd) if stdoutfilename: with open(stdoutfilename, 'w') as f: proc = subprocess.Popen(cmd, universal_newlines=True, shell=False, stdout=f, std...
def _system_call(cmd, stdoutfilename=None)
Execute the command `cmd` Parameters ---------- cmd : str The string containing the command to be run. stdoutfilename : str Name of the file to save stdout to or None (default) to not save to file stderrfilename : str Name of the file to save stderr to or None ...
2.428184
2.466136
0.984611
try: seqs = [Sequence(id, seq) for id, seq in input_seqs] except Exception: seqs = [] if len(seqs) == 0: logger = logging.getLogger(__name__) logger.warn('No sequences found in fasta file!') return None # Check that all the sequence lengths (aligned and una...
def get_sequences(input_seqs)
Returns a list of Sequences Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format Returns ------- list of Sequence Raises ------ ValueError If no sequences where found in `input_seqs` If all the se...
2.644526
2.582088
1.024181
prefix, suffix = re.split('(?<=size=)\w+', self.label, maxsplit=1) new_count = int(round(self.frequency)) new_label = "%s%d%s" % (prefix, new_count, suffix) return ">%s\n%s\n" % (new_label, self.sequence)
def to_fasta(self)
Returns a string with the sequence in fasta format Returns ------- str The FASTA representation of the sequence
4.759672
4.659937
1.021403
output = [] for key, value in options.items(): if isinstance(value, (dict, list)): value = json.dumps(value) output.append("data-{name}='{value}'".format( name=key, value=mark_safe(value))) return mark_safe(...
def render_select2_options_code(self, options, id_)
Render options for select2.
3.174818
2.937096
1.080938
if id_: options = self.render_select2_options_code( dict(self.get_options()), id_) return mark_safe(self.html.format(id=id_, options=options)) return u''
def render_js_code(self, id_, *args, **kwargs)
Render html container for Select2 widget with options.
7.03252
5.246098
1.340524
output = super(Select2Mixin, self).render( name, value, attrs=attrs, **kwargs) id_ = attrs['id'] output += self.render_js_code( id_, name, value, attrs=attrs, **kwargs) return mark_safe(output)
def render(self, name, value, attrs=None, **kwargs)
Extend base class's `render` method by appending javascript inline text to html output.
3.266753
3.272053
0.99838
if self.builder.name in ('djangohtml', 'json') and node['win_console_text']: # Put a mark on the document object signaling the fact the directive # has been used on it. self.document._console_directive_used_flag = True uid = node['uid'] self.body.append('''\ <div class="...
def visit_console_html(self, node)
Generate HTML for the console directive.
3.01514
2.92807
1.029736
widgets = widgets or {} meta_fields = meta_fields or {} # TODO: assert attrs is of type `dict` for field in model._meta.fields: if isinstance(field, ForeignKey) or field.choices: widgets.update({field.name: Select2(select2attrs=attrs)}) for field in model._meta.many_to_ma...
def select2_modelform_meta(model, meta_fields=None, widgets=None, attrs=None, **kwargs)
Return `Meta` class with Select2-enabled widgets for fields with choices (e.g. ForeignKey, CharField, etc) for use with ModelForm. Arguments: model - a model class to create `Meta` class for. meta_fields - dictionary with `Meta` class fields, for example, {'fields': ['id', 'nam...
2.462765
2.752095
0.894869
classname = '%sForm' % model._meta.object_name meta = select2_modelform_meta(model, attrs=attrs) return type(classname, (form_class,), {'Meta': meta})
def select2_modelform( model, attrs=None, form_class=es2_forms.FixedModelForm)
Return ModelForm class for model with select2 widgets. Arguments: attrs: select2 widget attributes (width, for example) of type `dict`. form_class: modelform base class, `forms.ModelForm` by default. :: SomeModelForm = select2_modelform(models.SomeModelBanner) is the same like:: ...
3.484848
4.010036
0.869032
for match in self.regex.finditer(text): for name, _ in self.lexicon: m = match.group(name) if m is not None: yield (name, m) break yield (EOF, None)
def lex(self, text)
Yield (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module.
3.729601
3.600119
1.035966
gen = self.lexer.lex(text) next_val_fn = partial(next, *(gen,)) commands = [] token = next_val_fn() while token[0] is not EOF: command, token = self.rule_svg_transform(next_val_fn, token) commands.append(command) return commands
def parse(self, text)
Parse a string of SVG transform="" data.
5.85453
5.258167
1.113417
gen = self.lexer.lex(text) next_val_fn = partial(next, *(gen,)) token = next_val_fn() return self.rule_svg_path(next_val_fn, token)
def parse(self, text)
Parse a string of SVG <path> data.
8.605795
8.186047
1.051276
if elems is None: elems = {} id = node.getAttribute('id') if id != '': elems[id] = node if node.hasChildNodes(): for child in node.childNodes: # from http://www.w3.org/TR/DOM-Level-2-Core/idl-definitions.html # we are only really interested in nodes o...
def findElementsWithId(node, elems=None)
Returns all elements with id attributes
2.645437
2.642258
1.001203
global referencingProps if ids is None: ids = {} # TODO: input argument ids is clunky here (see below how it is called) # GZ: alternative to passing dict, use **kwargs # if this node is a style element, parse its text into CSS if node.nodeName == 'style' and node.namespaceURI == NS...
def findReferencedElements(node, ids=None)
Returns IDs of all referenced elements - node is the node at which to start the search. - returns a map which has the id as key and each value is is a list of nodes Currently looks at 'xlink:href' and all attributes in 'referencingProps'
4.166889
3.942093
1.057024
global _num_elements_removed num = 0 # Remove certain unreferenced elements outside of defs removeTags = ['linearGradient', 'radialGradient', 'pattern'] identifiedElements = findElementsWithId(doc.documentElement) referencedIDs = findReferencedElements(doc.documentElement) for id in i...
def removeUnreferencedElements(doc, keepDefs)
Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>. Also vacuums the defs of any non-referenced renderable elements. Returns the number of unreferenced elements removed from the document.
3.657634
3.661466
0.998953
num = 0 identifiedElements = findElementsWithId(doc.documentElement) if unprotectedElements is None: unprotectedElements = identifiedElements referencedIDs = findReferencedElements(doc.documentElement) # Make idList (list of idnames) sorted by reference count # descending, so the ...
def shortenIDs(doc, prefix, unprotectedElements=None)
Shortens ID names used in the document. ID names referenced the most often are assigned the shortest ID names. If the list unprotectedElements is provided, only IDs from this list will be shortened. Returns the number of bytes saved by shortening ID names in the document.
5.067146
5.075846
0.998286
rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) return prefix + rid
def intToID(idnum, prefix)
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz.
2.547026
2.479019
1.027433
num = 0 definingNode = identifiedElements[idFrom] definingNode.setAttribute("id", idTo) del identifiedElements[idFrom] identifiedElements[idTo] = definingNode num += len(idFrom) - len(idTo) # Update references to renamed node referringNodes = referencedIDs.get(idFrom) if refe...
def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs)
Changes the ID name from idFrom to idTo, on the declaring element as well as all references in the document doc. Updates identifiedElements and referencedIDs. Does not handle the case where idTo is already the ID name of another element in doc. Returns the number of bytes saved by this replacement...
3.028007
2.961022
1.022622
u identifiedElements = findElementsWithId(doc.documentElement) if not (options.protect_ids_noninkscape or options.protect_ids_list or options.protect_ids_prefix): return identifiedElements if options.protect_ids_list: protect_ids_list = options.protect_ids_list.sp...
def unprotected_ids(doc, options)
u"""Returns a list of unprotected IDs within the document doc.
2.741404
2.609456
1.050565
global _num_ids_removed keepTags = ['font'] num = 0 for id in identifiedElements: node = identifiedElements[id] if id not in referencedIDs and node.nodeName not in keepTags: node.removeAttribute('id') _num_ids_removed += 1 num += 1 return num
def removeUnreferencedIDs(referencedIDs, identifiedElements)
Removes the unreferenced ID attributes. Returns the number of ID attributes removed
4.305677
4.094758
1.051509
global _num_elements_removed num = 0 groupsToRemove = [] # Only consider <g> elements for promotion if this element isn't a <switch>. # (partial fix for bug 594930, required by the SVG spec however) if not (node.nodeType == Node.ELEMENT_NODE and node.nodeName == 'switch'): for chil...
def removeNestedGroups(node)
This walks further and further down the tree, removing groups which do not have any attributes or a title/desc child and promoting their children up one level
3.552742
3.356106
1.05859
num = 0 childElements = [] # recurse first into the children (depth-first) for child in elem.childNodes: if child.nodeType == Node.ELEMENT_NODE: # only add and recurse if the child is not referenced elsewhere if not child.getAttribute('id') in referencedElements: ...
def moveCommonAttributesToParentGroup(elem, referencedElements)
This recursively calls this function on all children of the passed in element and then iterates over all child elements and removes common inheritable attributes from the children and places them in the parent group. But only if the parent contains nothing but element children and whitespace. The attribut...
3.261899
3.194206
1.021193
num = 0 childElements = [] # recurse first into the children (depth-first) for child in elem.childNodes: if child.nodeType == Node.ELEMENT_NODE: childElements.append(child) num += removeUnusedAttributesOnParent(child) # only process the children if there are mo...
def removeUnusedAttributesOnParent(elem)
This recursively calls this function on all children of the element passed in, then removes any unused attributes on this elem if none of the children inherit it
2.303844
2.276896
1.011835
u if node.nodeType == Node.ELEMENT_NODE and len(node.getAttribute('style')) > 0: styleMap = {} rawStyles = node.getAttribute('style').split(';') for style in rawStyles: propval = style.split(':') if len(propval) == 2: styleMap[propval[0].strip()] =...
def _getStyle(node)
u"""Returns the style attribute of a node as a dictionary.
2.485222
2.311092
1.075345
u fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap]) if fixedStyle != '': node.setAttribute('style', fixedStyle) elif node.getAttribute('style'): node.removeAttribute('style') return node
def _setStyle(node, styleMap)
u"""Sets the style attribute of a node to the dictionary ``styleMap``.
4.558249
4.354014
1.046907
parentNode = node.parentNode # return None if we reached the Document element if parentNode.nodeType == Node.DOCUMENT_NODE: return None # check styles first (they take precedence over presentation attributes) styles = _getStyle(parentNode) if style in styles: value = style...
def styleInheritedFromParent(node, style)
Returns the value of 'style' that is inherited from the parents of the passed-in node Warning: This method only considers presentation attributes and inline styles, any style sheets are ignored!
4.151217
3.973063
1.04484
# Comment, text and CDATA nodes don't have attributes and aren't containers so they can't inherit attributes if node.nodeType != Node.ELEMENT_NODE: return False if nodeIsChild: # if the current child node sets a new value for 'style' # we can stop the search in the current bran...
def styleInheritedByChild(node, style, nodeIsChild=False)
Returns whether 'style' is inherited by any children of the passed-in node If False is returned, it is guaranteed that 'style' can safely be removed from the passed-in node without influencing visual output of it's children If True is returned, the passed-in node should not have its text-based attribu...
5.326589
5.093828
1.045695
# Cached result of a prior call? try: return node.mayContainTextNodes except AttributeError: pass result = True # Default value # Comment, text and CDATA nodes don't have attributes and aren't containers if node.nodeType != Node.ELEMENT_NODE: result = False # N...
def mayContainTextNodes(node)
Returns True if the passed-in node is probably a text element, or at least one of its descendants is probably a text element. If False is returned, it is guaranteed that the passed-in node has no business having text-based attributes. If True is returned, the passed-in node should not have its text-ba...
6.160302
5.962933
1.033099
u taintedSet.add(taintedAttribute) if taintedAttribute == 'marker': taintedSet |= set(['marker-start', 'marker-mid', 'marker-end']) if taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']: taintedSet.add('marker') return taintedSet
def taint(taintedSet, taintedAttribute)
u"""Adds an attribute to a set of attributes. Related attributes are also included.
2.748278
2.917598
0.941966
if not node.hasAttribute(attribute.name): return 0 # differentiate between text and numeric values if isinstance(attribute.value, str): if node.getAttribute(attribute.name) == attribute.value: if (attribute.conditions is None) or attribute.conditions(node): ...
def removeDefaultAttributeValue(node, attribute)
Removes the DefaultAttribute 'attribute' from 'node' if specified conditions are fulfilled Warning: Does NOT check if the attribute is actually valid for the passed element type for increased preformance!
2.806179
2.680017
1.047075
u num = 0 if node.nodeType != Node.ELEMENT_NODE: return 0 # Conditionally remove all default attributes defined in 'default_attributes' (a list of 'DefaultAttribute's) # # For increased performance do not iterate the whole list for each element but run only on valid subsets # - 'def...
def removeDefaultAttributeValues(node, options, tainted=set())
u"""'tainted' keeps a set of attributes defined in parent nodes. For such attributes, we don't delete attributes with default values.
3.821084
3.886059
0.98328
s = value if s in colors: s = colors[s] rgbpMatch = rgbp.match(s) if rgbpMatch is not None: r = int(float(rgbpMatch.group(1)) * 255.0 / 100.0) g = int(float(rgbpMatch.group(2)) * 255.0 / 100.0) b = int(float(rgbpMatch.group(3)) * 255.0 / 100.0) s = '#%02x%0...
def convertColor(value)
Converts the input color string and returns a #RRGGBB (or #RGB if possible) string
1.529593
1.499458
1.020097
numBytes = 0 if element.nodeType != Node.ELEMENT_NODE: return 0 # set up list of color attributes for each element type attrsToConvert = [] if element.nodeName in ['rect', 'circle', 'ellipse', 'polygon', 'line', 'polyline', 'path', 'g', 'a']: attrsT...
def convertColors(element)
Recursively converts all color properties into #RRGGBB format if shorter
2.572314
2.508298
1.025522
i = 0 # (wsp)? comma-or-wsp-separated coordinate pairs (wsp)? # coordinate-pair = coordinate comma-or-wsp coordinate # coordinate = sign? integer # comma-wsp: (wsp+ comma? wsp*) | (comma wsp*) ws_nums = re.split(r"\s*[\s,]\s*", s.strip()) nums = [] # also, if 100-100 is found, spl...
def parseListOfPoints(s)
Parse string into a list of points. Returns a list containing an even number of coordinate strings
4.47844
4.527705
0.989119
global _num_points_removed_from_polygon pts = parseListOfPoints(elem.getAttribute('points')) N = len(pts) / 2 if N >= 2: (startx, starty) = pts[:2] (endx, endy) = pts[-2:] if startx == endx and starty == endy: del pts[-2:] _num_points_removed_from_po...
def cleanPolygon(elem, options)
Remove unnecessary closing point of polygon points attribute
3.946712
3.710324
1.063711
pts = parseListOfPoints(elem.getAttribute('points')) elem.setAttribute('points', scourCoordinates(pts, options, True))
def cleanPolyline(elem, options)
Scour the polyline points attribute
10.523517
6.922814
1.520121
cmd = cmd.lower() if cmd in ['c', 's', 'q']: indices = range(len(data)) if cmd == 'c': # c: (x1 y1 x2 y2 x y)+ return [index for index in indices if (index % 6) < 4] elif cmd in ['s', 'q']: # s: (x2 y2 x y)+ q: (x1 y1 x y)+ return [index for index in indi...
def controlPoints(cmd, data)
Checks if there are control points in the path data Returns the indices of all values in the path data which are control points
3.623774
3.298129
1.098736
if cmd.lower() == 'a': # a: (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ indices = range(len(data)) return [index for index in indices if (index % 7) in [3, 4]] return []
def flags(cmd, data)
Checks if there are flags in the path data Returns the indices of all values in the path data which are flags
8.165822
7.626184
1.070761
# elliptical arc commands must have comma/wsp separating the coordinates # this fixes an issue outlined in Fix https://bugs.launchpad.net/scour/+bug/412754 return ''.join([cmd + scourCoordinates(data, options, control_points=controlPoints(cmd, data), ...
def serializePath(pathObj, options)
Reserializes the path data with some cleanups.
17.629555
18.35211
0.960628
return ' '.join([command + '(' + ' '.join([scourUnitlessLength(number) for number in numbers]) + ')' for command, numbers in transformObj])
def serializeTransform(transformObj)
Reserializes the transform data with some cleanups.
15.651014
17.141924
0.913026
if data is not None: newData = [] c = 0 previousCoord = '' for coord in data: is_control_point = c in control_points scouredCoord = scourUnitlessLength(coord, renderer_workaround=options.renderer_workaround, ...
def scourCoordinates(data, options, force_whitespace=False, control_points=[], flags=[])
Serializes coordinate data with some cleanups: - removes all trailing zeros after the decimal - integerize coordinates if possible - removes extraneous whitespace - adds spaces between values in a subcommand if required (or if force_whitespace is True)
5.937282
6.03712
0.983463
length = SVGLength(length) return scourUnitlessLength(length.value) + Unit.str(length.units)
def scourLength(length)
Scours a length. Accepts units.
14.434246
11.929675
1.209945
length = getcontext().create_decimal(str(length)) initial_length = length # reduce numeric precision # plus() corresponds to the unary prefix plus operator and applies context precision and rounding if is_control_point: length = scouringContextC.plus(length) else: length = s...
def scourUnitlessLength(length, renderer_workaround=False, is_control_point=False): # length is of a numeric type if not isinstance(length, Decimal)
Scours the numeric part of a length only. Does not accept units. This is faster than scourLength on elements guaranteed not to contain units.
4.974795
4.994122
0.99613
num = 0 styles = _getStyle(element) for lengthAttr in ['opacity', 'flood-opacity', 'fill-opacity', 'stroke-opacity', 'stop-opacity', 'stroke-miterlimit', 'stroke-dashoffset', 'letter-spacing', 'word-spacing', 'kerning', 'font-size-ad...
def reducePrecision(element)
Because opacities, letter spacings, stroke widths and all that don't need to be preserved in SVG files with 9 digits of precision. Takes all of these attributes, in the given element node and its children, and reduces their precision to the current Decimal context's precision. Also checks for the attri...
3.426053
3.125912
1.096017
# First, we put the new angle in the range ]-360, 360[. # The modulo operator yields results with the sign of the # divisor, so for negative dividends, we preserve the sign # of the angle. if angle < 0: angle %= -360 else: angle %= 360 # 720 degrees is unnecessary, as 36...
def optimizeAngle(angle)
Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[.
7.429236
6.244359
1.189752
num = 0 for transformAttr in ['transform', 'patternTransform', 'gradientTransform']: val = element.getAttribute(transformAttr) if val != '': transform = svg_transform_parser.parse(val) optimizeTransform(transform) newVal = serializeTransform(transform)...
def optimizeTransforms(element, options)
Attempts to optimise transform specifications on the given node and its children. Returns the number of bytes saved after performing these reductions.
2.817588
2.732739
1.031049
global _num_bytes_saved_in_comments num = 0 if isinstance(element, xml.dom.minidom.Comment): _num_bytes_saved_in_comments += len(element.data) element.parentNode.removeChild(element) num += 1 else: for subelement in element.childNodes[:]: num += removeCo...
def removeComments(element)
Removes comments from the element and its children.
3.230079
3.309402
0.976031
import base64 global _num_rasters_embedded href = element.getAttributeNS(NS['XLINK'], 'href') # if xlink:href is set, then grab the id if href != '' and len(href) > 1: ext = os.path.splitext(os.path.basename(href))[1].lower()[1:] # only operate on files with 'png', 'jpg', and...
def embedRasters(element, options)
Converts raster references to inline images. NOTE: there are size limits to base64-encoding handling in browsers
4.707113
4.649898
1.012305
format_path = os.getenv('FORMAT_PATH', 'format_files') try: spec = importlib.util.spec_from_file_location( "format_mod", f"{format_path}/{format_}.py") format_mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(format_mod) except FileNotFoundError: ...
def get_format(format_)
Find format schema in $FORMAT_PATH or nerium/schema
2.785722
2.0474
1.360614
'''Set a new (or updating existing) key value pair. Args: key: A string containing the key namespace value: A str, int, or bool value Raises: NotImplementedError: an unsupported value-type was provided ''' value_type = type(value) if ...
def set_property(self, key, value)
Set a new (or updating existing) key value pair. Args: key: A string containing the key namespace value: A str, int, or bool value Raises: NotImplementedError: an unsupported value-type was provided
3.834198
2.883018
1.329925
'''Save current property list representation to the original file.''' with open(self.filename, 'w') as plist_file: plist_file.write(str(self.soup))
def save(self)
Save current property list representation to the original file.
11.480737
5.438659
2.11095
for user in self.users: obj = self.users[user] if obj.side == side: return user
def fetch_userid(self, side)
Return the userid for the specified bed side.
4.233682
3.576333
1.183805
_LOGGER.debug('Initializing pyEight Version: %s', __version__) await self.fetch_token() if self._token is not None: await self.fetch_device_list() await self.assign_users() return True else: # We couldn't authenticate r...
async def start(self)
Start api initialization.
7.276535
6.253891
1.163521
url = '{}/login'.format(API_URL) payload = 'email={}&password={}'.format(self._email, self._password) reg = await self.api_post(url, None, payload) if reg is None: _LOGGER.error('Unable to authenticate and fetch eight token.') else: self._userid ...
async def fetch_token(self)
Fetch new session token from api.
4.387291
4.074363
1.076804
url = '{}/users/me'.format(API_URL) dlist = await self.api_get(url) if dlist is None: _LOGGER.error('Unable to fetch eight devices.') else: self._devices = dlist['user']['devices'] _LOGGER.debug('Devices: %s', self._devices)
async def fetch_device_list(self)
Fetch list of devices.
4.880181
4.520159
1.079648
device = self._devices[0] url = '{}/devices/{}?filter=ownerId,leftUserId,rightUserId' \ .format(API_URL, device) data = await self.api_get(url) if data is None: _LOGGER.error('Unable to assign eight device users.') else: # Find the si...
async def assign_users(self)
Update device properties.
2.95314
2.859098
1.032892
# Check which side is active, if both are return the average tmp = None tmp2 = None for user in self.users: obj = self.users[user] if obj.current_values['processing']: if tmp is None: tmp = obj.current_values['room_temp...
def room_temperature(self)
Return room temperature for both sides of bed.
2.574181
2.451864
1.049887
self._device_json.insert(0, data) self._device_json.pop()
def handle_device_json(self, data)
Manage the device json list.
6.643573
4.727118
1.405417
url = '{}/devices/{}?offlineView=true'.format(API_URL, self.deviceid) # Check for access token expiration (every 15days) exp_delta = datetime.strptime(self._expdate, '%Y-%m-%dT%H:%M:%S.%fZ') \ - datetime.fromtimestamp(time.time()) # Renew 1hr before expiration ...
async def update_device_data(self)
Update device data json.
6.572481
6.319992
1.039951
request = None headers = DEFAULT_HEADERS.copy() headers.update({'Session-Token': self._token}) try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): request = await self._api_session.get( url, headers=headers, p...
async def api_get(self, url, params=None)
Make api fetch request.
2.730529
2.648529
1.030961
put = None headers = DEFAULT_HEADERS.copy() headers.update({'Session-Token': self._token}) try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): put = await self._api_session.put( url, headers=headers, data=data...
async def api_put(self, url, data=None)
Make api post request.
2.826438
2.75406
1.02628
versions = [] for req_range in requirements: try: version = self._detected_versions[req_range.name] except KeyError: try: version = req_range.requirement.detect_version() except ArcanaRequirementNotFound...
def satisfy(self, *requirements)
Checks whether the given requirements are satisfiable within the given execution context Parameter --------- requirements : list(Requirement) List of requirements to check whether they are satisfiable
2.897653
3.290709
0.880556
match = re.search(r'^([A-P])(\d{1,2})$', housecode.upper()) if match: house_index = int(match.group(2)) if 1 <= house_index <= 16: return (ord(match.group(1)) - ord('A')) * 16 + house_index - 1 raise ValueError("Invalid X10 housecode: %s" % housecode)
def housecode_to_index(housecode)
Convert a X10 housecode to a zero-based index
2.883805
2.40398
1.199596
if index < 0 or index > 255: raise ValueError quotient, remainder = divmod(index, 16) return chr(quotient+ord('A')) + '{:02d}'.format(remainder+1)
def index_to_housecode(index)
Convert a zero-based index to a X10 housecode.
3.179592
3.018121
1.053501
checksum = int(msg[-2:], 16) for char in msg[:-2]: checksum += ord(char) if (checksum % 256) != 0: raise ValueError("Elk message checksum invalid")
def _check_checksum(msg)
Ensure checksum in message is good.
4.262866
3.691047
1.154921
try: if int(msg[:2], 16) != (len(msg) - 2): raise ValueError("Elk message length incorrect") _check_checksum(msg) except IndexError: raise ValueError("Elk message length incorrect")
def _check_message_valid(msg)
Check packet length valid and that checksum is good.
5.721923
3.978983
1.438036
if value_format == 2: value = value[0] << 8 + value[1] return MessageEncode('0Dcw{:02d}{:05d}00'.format(index+1, value), None)
def cw_encode(index, value, value_format)
cw: Write a custom value.
7.312082
7.22544
1.011991
return MessageEncode( '2Edm{:1d}{:1d}{:1d}{:05d}{:^<16.16}{:^<16.16}00' .format(keypad_area+1, clear, beep, timeout, line1, line2), None )
def dm_encode(keypad_area, clear, beep, timeout, line1, line2)
dm: Display message on keypad.
6.603776
6.703355
0.985145
return MessageEncode('11pc{hc}{fc:02d}{ec:02d}{time:04d}00'. format(hc=index_to_housecode(index), fc=function_code, ec=extended_code, time=time), None)
def pc_encode(index, function_code, extended_code, time)
pc: Control any PLC device.
7.206452
7.147338
1.008271
if zone < 0: zone = 0 elif zone > Max.ZONES.value: zone = 999 else: zone += 1 return MessageEncode('10zb{zone:03d}{area:1d}{code:06d}00'.format( zone=zone, area=area+1, code=user_code), 'ZB')
def zb_encode(zone, area, user_code)
zb: Zone bypass. Zone < 0 unbypass all; Zone > Max bypass all.
5.341724
4.867491
1.097429
if message_type not in self._handlers: self._handlers[message_type] = [] if handler not in self._handlers[message_type]: self._handlers[message_type].append(handler)
def add_handler(self, message_type, handler)
Manage callbacks for message handlers.
1.808094
1.703302
1.061523
_check_message_valid(msg) cmd = msg[2:4] decoder = getattr(self, '_{}_decode'.format(cmd.lower()), None) if not decoder: cmd = 'unknown' decoder = self._unknown_decode decoded_msg = decoder(msg) for handler in self._handlers.get(cmd, []): ...
def decode(self, msg)
Decode an Elk message by passing to appropriate decoder
4.028337
3.759663
1.071462
return {'armed_statuses': [x for x in msg[4:12]], 'arm_up_states': [x for x in msg[12:20]], 'alarm_states': [x for x in msg[20:28]]}
def _as_decode(self, msg)
AS: Arming status report.
4.473455
3.841769
1.164426
if int(msg[4:6]) > 0: index = int(msg[4:6])-1 return {'values': [self._cr_one_custom_value_decode(index, msg[6:12])]} else: part = 6 ret = [] for i in range(Max.SETTINGS.value): ret.append(self._cr_one_custom_value_deco...
def _cr_decode(self, msg)
CR: Custom values
4.544038
4.184429
1.08594
output_status = [x == '1' for x in msg[4:4+Max.OUTPUTS.value]] return {'output_status': output_status}
def _cs_decode(self, msg)
CS: Output status for all outputs.
13.427375
7.62172
1.761725
return {'area': int(msg[4:5])-1, 'is_exit': msg[5:6] == '0', 'timer1': int(msg[6:9]), 'timer2': int(msg[9:12]), 'armed_status': msg[12:13]}
def _ee_decode(self, msg)
EE: Entry/exit timer report.
4.5643
3.823888
1.193628
code = msg[4:16] if re.match(r'(0\d){6}', code): code = re.sub(r'0(\d)', r'\1', code) return {'code': code, 'user': int(msg[16:19])-1, 'keypad': int(msg[19:21])-1}
def _ic_decode(self, msg)
IC: Send Valid Or Invalid User Code Format.
4.30888
3.90818
1.102528
return {'keypad_areas': [ord(x)-0x31 for x in msg[4:4+Max.KEYPADS.value]]}
def _ka_decode(self, msg)
KA: Keypad areas for all keypads.
21.537825
11.566393
1.862104
keypad_temps = [] zone_temps = [] for i in range(16): keypad_temps.append(int(msg[4+3*i:7+3*i]) - 40) zone_temps.append(int(msg[52+3*i:55+3*i]) - 60) return {'keypad_temps': keypad_temps, 'zone_temps': zone_temps}
def _lw_decode(self, msg)
LW: temperatures from all keypads and zones 1-16.
2.594444
2.000928
1.29662
housecode = msg[4:7] return {'housecode': housecode, 'index': housecode_to_index(housecode), 'light_level': int(msg[7:9])}
def _pc_decode(self, msg)
PC: PLC (lighting) change.
6.026153
5.45085
1.105544
desc_ch1 = msg[9] show_on_keypad = ord(desc_ch1) >= 0x80 if show_on_keypad: desc_ch1 = chr(ord(desc_ch1) & 0x7f) return {'desc_type': int(msg[4:6]), 'unit': int(msg[6:9])-1, 'desc': (desc_ch1+msg[10:25]).rstrip(), 'show_on_keypad': sho...
def _sd_decode(self, msg)
SD: Description text.
3.840871
3.601471
1.066473
group = int(msg[4:5]) temperature = int(msg[7:10]) if group == 0: temperature -= 60 elif group == 1: temperature -= 40 return {'group': group, 'device': int(msg[5:7])-1, 'temperature': temperature}
def _st_decode(self, msg)
ST: Temperature update.
4.14975
3.660796
1.133565
return {'thermostat_index': int(msg[4:6])-1, 'mode': int(msg[6]), 'hold': msg[7] == '1', 'fan': int(msg[8]), 'current_temp': int(msg[9:11]), 'heat_setpoint': int(msg[11:13]), 'cool_setpoint': int(msg[13:15]), 'humidity': int(msg[15:17])}
def _tr_decode(self, msg)
TR: Thermostat data response.
2.685482
2.409195
1.11468
elkm1_version = "{}.{}.{}".format(int(msg[4:6], 16), int(msg[6:8], 16), int(msg[8:10], 16)) xep_version = "{}.{}.{}".format(int(msg[10:12], 16), int(msg[12:14], 16), int(msg[14:16], 16)) return {'elkm1_ver...
def _vn_decode(self, msg)
VN: Version information.
1.982725
1.897335
1.045005