code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def tracefunc_xml(func): funcname = meta_util_six.get_funcname(func) def wrp_tracefunc2(*args, **kwargs): verbose = kwargs.get('verbose', True) if verbose: print('<%s>' % (funcname,)) with util_print.Indenter(' '): ret = func(*args, **kwargs) if verbose...
Causes output of function to be printed in an XML style block
def _index_document(self, document, force=False): query = text( ) self.execute(query, **document)
Adds dataset document to the index.
def iterkeys(self): "Returns an iterator over the keys of ConfigMap." return chain(self._pb.StringMap.keys(), self._pb.IntMap.keys(), self._pb.FloatMap.keys(), self._pb.BoolMap.keys())
Returns an iterator over the keys of ConfigMap.
def removePhenotypeAssociationSet(self, phenotypeAssociationSet): q = models.Phenotypeassociationset.delete().where( models.Phenotypeassociationset.id == phenotypeAssociationSet.getId()) q.execute()
Remove a phenotype association set from the repo
def hash_values(values, alg="md5"): import hashlib if alg not in ['md5', 'sha1', 'sha256']: raise Exception("Invalid hashing algorithm!") hasher = getattr(hashlib, alg) if type(values) == str: output = hasher(values).hexdigest() elif type(values) == list: output = list() ...
Hash a list of values.
def send_email(self, user, subject, msg): print('To:', user) print('Subject:', subject) print(msg)
Should be overwritten in the setup
def action_to_approve(self): template = self.env.ref( 'document_page_approval.email_template_new_draft_need_approval') approver_gid = self.env.ref( 'document_page_approval.group_document_approver_user') for rec in self: if rec.state != 'draft': ...
Set a change request as to approve
def query(self, parents=None): q = Select([]) q = self.project(q, parent=True) q = self.filter(q, parents=parents) if self.parent is None: subq = Select([self.var]) subq = self.filter(subq, parents=parents) subq = subq.offset(self.node.offset) ...
Compose the query and generate SPARQL.
def _build_tag_param_list(params, tags): keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1
helper function to build a tag parameter list to send
def random_id(k=5): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k))
Random id to use for AWS identifiers.
def unpack(self, unpacker): (a, b, c, d) = unpacker.unpack_struct(_HHHH) self.inner_info_ref = a self.outer_info_ref = b self.name_ref = c self.access_flags = d
unpack this instance with data from unpacker
def handle_unsuback(self): self.logger.info("UNSUBACK received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventUnsuback(mid) self.push_event(evt) return NC.ERR_SUCCESS
Handle incoming UNSUBACK packet.
def save(self, commit=True): for localized_field in self.instance.localized_fields: setattr(self.instance, localized_field, self.cleaned_data[localized_field]) return super(LocalisedForm, self).save(commit)
Override save method to also save the localised fields.
def fetch(url, timeout=5, userAgent=None, only_mime_types=None): headers = {} if userAgent: headers['User-agent'] = str(userAgent) else: headers['User-agent'] = ua.random response = requests.get(url, headers=headers, timeout=timeout) if only_mime_types: assert isinstance(only...
Retrieves the raw content of the URL.
def max_normal_germline_depth(in_file, params, somatic_info): bcf_in = pysam.VariantFile(in_file) depths = [] for rec in bcf_in: stats = _is_possible_loh(rec, bcf_in, params, somatic_info) if tz.get_in(["normal", "depth"], stats): depths.append(tz.get_in(["normal", "depth"], stat...
Calculate threshold for excluding potential heterozygotes based on normal depth.
def to_json(self): result = { 'sys': {} } for k, v in self.sys.items(): if k in ['space', 'content_type', 'created_by', 'updated_by', 'published_by']: v = v.to_json() if k in ['created_at', 'updated_at', 'deleted_at', ...
Returns the JSON representation of the resource.
def model(self): if self.is_bootloader: out = self.fastboot.getvar('product').strip() lines = out.decode('utf-8').split('\n', 1) if lines: tokens = lines[0].split(' ') if len(tokens) > 1: return tokens[1].lower() ...
The Android code name for the device.
def import_object(object_name): package, name = object_name.rsplit('.', 1) return getattr(importlib.import_module(package), name)
Import an object from its Fully Qualified Name.
def connected(self): return self.websocket is not None and \ self.websocket.sock is not None and \ self.websocket.sock.connected
If connected to server.
def _get_ticks(self, opts): opts, _ = self._get_opts(opts, None) if "xticks" not in opts: if "xticks" not in self.chart_opts: self.err(self.dlinear_, "Please set the xticks option for this chart to work") return else: ...
Check if xticks and yticks are set
def example_df(): country_names = ['Germany', 'France', 'Indonesia', 'Ireland', 'Spain', 'Vatican'] population = [82521653, 66991000, 255461700, 4761865, 46549045, None] population_time = [dt.datetime(20...
Create an example dataframe.
def cli(ctx, ids, query, filters, details, interval): if details: display = 'details' else: display = 'compact' from_date = None auto_refresh = True while auto_refresh: try: auto_refresh, from_date = ctx.invoke(query_cmd, ids=ids, query=query, ...
Watch for new alerts.
def fetch(self, year, week, overwrite=False): self.config['overwrite_files'] = overwrite time_start = time.time() self._fetch_pageviews(self.storage, year, week, ip_users=False) self._fetch_downloads(self.storage, year, week, ip_users=False) self._fetch_pageviews(self.storage, ye...
Fetch PageViews and Downloads from Elasticsearch.
def register_logger(self, logger): handler = CommandHandler(self) handler.setFormatter(CommandFormatter()) logger.handlers = [handler] logger.propagate = False output = self.output level = logging.WARNING if output.is_debug(): level = logging.DEBUG ...
Register a new logger.
def acceptNavigationRequest(self, url, navigation_type, isMainFrame): if navigation_type == QWebEnginePage.NavigationTypeLinkClicked: self.linkClicked.emit(url) return False return True
Overloaded method to handle links ourselves
def reset(cls): cls._func_from_name = {} cls._func_from_hash = {} cls._func_hash = {} register = cls._do_register for (func, hash_name, hash_new) in cls._std_func_data: register(func, func.name, hash_name, hash_new) assert set(cls._func_hash) == set(Func)
Reset the registry to the standard multihash functions.
def on_message(self, data): data = json.loads(data) if not data["name"] is None: logging.debug("%s: receiving message %s" % (data["name"], data["data"])) fct = getattr(self, "on_" + data["name"]) try: res = fct(Struct(data["data"])) except:...
Parsing data, and try to call responding message
def detect(self, fstring, fname=None): if fname is not None and '.' in fname: extension = fname.rsplit('.', 1)[1] if extension in {'pdf', 'html', 'xml'}: return False return True
Have a stab at most files.
def to_file(self, filename): with open(filename, 'wb') as f: f.write(self.to_bytes())
Writes the contents of the CCACHE object to a file
def com_google_fonts_check_glyphnames_max_length(ttFont): if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get( "post") and ttFont["post"].formatType == 3.0: yield PASS, ("TrueType fonts with a format 3.0 post table contain no " "glyph names.") else: failed = False for name...
Check that glyph names do not exceed max length.
def _load_parameters(self): "Retrieve a list of available parameters from the database" parameters = self._get_json('allparam/s') data = {} for parameter in parameters: data[parameter['Name'].lower()] = parameter self._parameters = ParametersContainer(data)
Retrieve a list of available parameters from the database
def _find_parameter(cls, dct): num_found = 0 field = None for key, val in dct.iteritems(): if isinstance(val, DataType) and val.is_key: field = key num_found += 1 if num_found > 1: raise SetupError(502) elif num_found == 0: ...
Search for the 'key=True' case, and confirm no more than one parameter has that property.
def remove_locations(node): def fix(node): if 'lineno' in node._attributes and hasattr(node, 'lineno'): del node.lineno if 'col_offset' in node._attributes and hasattr(node, 'col_offset'): del node.col_offset for child in iter_child_nodes(node): fix(child)...
Removes locations from the given AST tree completely
def process_set(line, annotations): matches = re.match('SET\s+(\w+)\s*=\s*"?(.*?)"?\s*$', line) key = None if matches: key = matches.group(1) val = matches.group(2) if key == "STATEMENT_GROUP": annotations["statement_group"] = val elif key == "Citation": annotations["...
Convert annotations into nanopub_bel annotations format
def build_select(query_obj): return build_select_query(query_obj.source, query_obj.fields, query_obj.filter, skip=query_obj.skip, \ limit=query_obj.limit, sort=query_obj.sort, distinct=query_obj.distinct)
Given a Query obj, return the corresponding sql
def count_emails(self, conditions={}): url = self.EMAILS_COUNT_URL + "?" for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.produ...
Count all certified emails
def stop(self): self._stop_event.set() if not self.persistence: return if self._cancel_save is not None: self._cancel_save() self._cancel_save = None self.persistence.save_sensors()
Stop the background thread.
def _compute_input_activations(self, X): n_samples = X.shape[0] mlp_acts = np.zeros((n_samples, self.n_hidden)) if (self._use_mlp_input): b = self.components_['biases'] w = self.components_['weights'] mlp_acts = self.alpha * (safe_sparse_dot(X, w) + b) ...
Compute input activations given X
def divsin_fc(fdata): nrows = fdata.shape[0] ncols = fdata.shape[1] L = int(nrows / 2) L2 = L - 2 g = np.zeros([nrows, ncols], dtype=np.complex128) g[L2, :] = 2 * 1j * fdata[L - 1, :] for k in xrange(L2, -L2, -1): g[k - 1, :] = 2 * 1j * fdata[k, :] + g[k + 1, :] fdata[:, :] = g
Apply divide by sine in the Fourier domain.
def close(self) -> None: if not self._closed: self._async_client.close() self._io_loop.close() self._closed = True
Closes the HTTPClient, freeing any resources used.
def build_command(self, config, **kwargs): command = ['perl', self.script, CLI_OPTIONS['config']['option'], config] for key, value in kwargs.items(): if value: command.append(CLI_OPTIONS[key]['option']) if value is True: command.append(CLI_...
Builds the command to execute MIP.
def _check_spawnable(source_channels, target_channels): if len(target_channels) != len(set(target_channels)): raise Exception('Spawn channels must be unique') return source_channels.issubset( set(target_channels))
Check whether gate is spawnable on the target channels.
def _on_capacity_data(self, conn, command, kwargs, response, capacity): if self._analyzing: self.consumed_capacities.append((command, capacity)) if self._query_rate_limit is not None: self._query_rate_limit.on_capacity( conn, command, kwargs, response, capacity ...
Log the received consumed capacity data
def main(args=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-V", "--version", action="version", version=__version__, help="show version number and exit") parser.add_argument("-l", "--local", action="store_true", default=Fals...
Parse command-line arguments, tconvert inputs, and print
def PDBasXMLwithSymwithPolarH(self, id): print _WARNING h_s_xml = urllib.urlopen("http://www.cmbi.ru.nl/wiwsd/rest/PDBasXMLwithSymwithPolarH/id/" + id) self.raw = h_s_xml p = self.parser h_s_smcra = p.read(h_s_xml, 'WHATIF_Output') return h_s_smcra
Adds Hydrogen Atoms to a Structure.
def _add_boundaries(self, interval): begin = interval.begin end = interval.end if begin in self.boundary_table: self.boundary_table[begin] += 1 else: self.boundary_table[begin] = 1 if end in self.boundary_table: self.boundary_table[end] += 1 ...
Records the boundaries of the interval in the boundary table.
def ipv4_range_type(string): import re ip_format = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' if not re.match("^{}$".format(ip_format), string): if not re.match("^{ip_format}-{ip_format}$".format(ip_format=ip_format), string): raise ValueError return string
Validates an IPv4 address or address range.
def add(self, indices, values): for i, v in zip(indices, values): self.buffer[i] = numpy.append(self.buffer[i], v) self.buffer_expire[i] = numpy.append(self.buffer_expire[i], self.time) self.advance_time()
Add triggers in 'values' to the buffers indicated by the indices
def open_report_template_path(self): directory_name = QFileDialog.getExistingDirectory( self, self.tr('Templates directory'), self.leReportTemplatePath.text(), QFileDialog.ShowDirsOnly) if directory_name: self.leReportTemplatePath.setText(direc...
Open File dialog to choose the report template path.
def validate(self, *args, **kwds): if self.behavior: return self.behavior.validate(self, *args, **kwds) return True
Call the behavior's validate method, or return True.
def _categorize(self, category): self.torrents = [result for result in self.torrents if result.category == category]
Remove torrents with unwanted category from self.torrents
def receive_reply(self, msg, content): reply_head = content.head() if reply_head == 'error': comment = content.gets('comment') logger.error('Got error reply: "%s"' % comment) else: extractions = content.gets('ekb') self.extractions.append(extractio...
Handle replies with reading results.
def _validate_node_name(self, var_value): var_values = var_value if isinstance(var_value, list) else [var_value] for item in var_values: if (not isinstance(item, str)) or ( isinstance(item, str) and ( (" " in item) or an...
Validate NodeName pseudo-type.
def _generate_routes(self, namespace): self.cur_namespace = namespace if self.args.auth_type is not None: self.supported_auth_types = [auth_type.strip().lower() for auth_type in self.args.auth_type.split(',')] check_route_name_conflict(namespace) for route in namespace.routes...
Generates Python methods that correspond to routes in the namespace.
def getStat(cls, obj, name): objClass = type(obj) for theClass in objClass.__mro__: if theClass == object: break for value in theClass.__dict__.values(): if isinstance(value, Stat) and value.getName() == name: return value
Gets the stat for the given object with the given name, or None if no such stat exists.
def delete(self, row): i = self._get_key_index(row) del self.keys[i]
Delete a track value
def guess_number_format(self, rb=1, align=1, **fmt_args): fct = fmt.guess_formatter(self.actual_values, **fmt_args) return self.apply_number_format(fct, rb=rb, align=align)
Determine the most appropriate formatter by inspected all the region values
def validate(self, data): if 'verb' in data and data['verb'] != self.__class__.__name__: raise ValidationError( 'This is not a valid OAI-PMH verb:{0}'.format(data['verb']), field_names=['verb'], ) if 'from_' in data and 'until' in data and \ ...
Check range between dates under keys ``from_`` and ``until``.
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: N = rank(tensor0) axes = list(range(N)) return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes))
Return the inner product between two states
def scc(graph): order = [] vis = {vertex: False for vertex in graph} graph_transposed = {vertex: [] for vertex in graph} for (v, neighbours) in graph.iteritems(): for u in neighbours: add_edge(graph_transposed, u, v) for v in graph: if not vis[v]: dfs_transpos...
Computes the strongly connected components of a graph
def errors_as_dict(self): errors = [] for e in self.errors: errors.append({ 'file': e.term.file_name, 'row': e.term.row if e.term else '<unknown>', 'col': e.term.col if e.term else '<unknown>', 'term': e.term.join if e.term else...
Return parse errors as a dict
def _on_split_requested(self): orientation = self.sender().text() widget = self.widget(self.tab_under_menu()) if 'horizontally' in orientation: self.split_requested.emit( widget, QtCore.Qt.Horizontal) else: self.split_requested.emit( ...
Emits the split requested signal with the desired orientation.
def charm_dir(): d = os.environ.get('JUJU_CHARM_DIR') if d is not None: return d return os.environ.get('CHARM_DIR')
Return the root directory of the current charm
def from_dict(cls, database, key, data, clear=False): hsh = cls(database, key) if clear: hsh.clear() hsh.update(data) return hsh
Create and populate a Hash object from a data dictionary.
def compute_default(kwargs): ranked_default = kwargs.get('default') typ = kwargs.get('type', str) default = ranked_default.value if ranked_default else None if default is None: return 'None' if typ == list: default_str = '[{}]'.format(','.join(["'{}'".format(s) for s in default])) el...
Compute the default value to display in help for an option registered with these kwargs.
def parse_firefox (url_data): filename = url_data.get_os_filename() for url, name in firefox.parse_bookmark_file(filename): url_data.add_url(url, name=name)
Parse a Firefox3 bookmark file.
def python_value(self, dtype, dvalue): try: return CONVERTERS[dtype](dvalue) except KeyError: if dtype == clips.common.CLIPSType.MULTIFIELD: return self.multifield_to_list() if dtype == clips.common.CLIPSType.FACT_ADDRESS: return clips....
Convert a CLIPS type into Python.
def init_registered(self, request): created_items = models.DefaultPriceListItem.init_from_registered_resources() if created_items: message = ungettext( _('Price item was created: %s.') % created_items[0].name, _('Price items were created: %s.') % ', '.join(ite...
Create default price list items for each registered resource.
def save_example_fit(fit): json_directory = os.path.join('examples', 'json') plot_directory = os.path.join('examples', 'plots') if not os.path.isdir(json_directory): os.makedirs(json_directory) if not os.path.isdir(plot_directory): os.makedirs(plot_directory) fit.to_json(os.path.join(json_directory,...
Save fit result to a json file and a plot to an svg file.
def format_str(self): if self.static: return self.route.replace('%','%%') out, i = '', 0 for token, value in self.tokens(): if token == 'TXT': out += value.replace('%','%%') elif token == 'ANON': out += '%%(anon%d)s' % i; i+=1 elif token == 'VAR': ...
Return a format string with named fields.
def watch_for_events(): fd = inotify.init() try: wd = inotify.add_watch(fd, '/tmp', inotify.IN_CLOSE_WRITE) while True: for event in inotify.get_events(fd): print("event:", event.name, event.get_mask_description()) finally: os.close(fd)
Wait for events and print them to stdout.
def basename(path): base_path = path.strip(SEP) sep_ind = base_path.rfind(SEP) if sep_ind < 0: return path return base_path[sep_ind + 1:]
Rightmost part of path after separator.
def render(self, template_name, variables=None): if variables is None: variables = {} template = self._engine.get_template(template_name) return template.render(**variables)
Render a template with the passed variables.
def update_backend(self, service_id, version_number, name_key, **kwargs): body = self._formdata(kwargs, FastlyBackend.FIELDS) content = self._fetch("/service/%s/version/%d/backend/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyBackend(self, content)
Update the backend for a particular service and version.
def Reverse(self, y): return self._Bisect(y, self.ys, self.xs)
Looks up y and returns the corresponding value of x.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): _ = stderr, time_taken, args, knowledge_base self.CheckReturn(cmd, return_val) result = rdf_protodict.AttributedDict() for entry in self._field_parser.ParseEntries(stdout): line_str = " ".join(entry) ...
Parse the mount command output.
def bk_green(cls): "Make the text background color green." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_GREEN cls._set_text_attributes(wAttributes)
Make the text background color green.
def fmt_subst(regex, subst): return lambda text: re.sub(regex, subst, text) if text else text
Replace regex with string.
def next_frame_ae_tiny(): hparams = next_frame_tiny() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.batch_size = 8 hparams.dropout = 0.4 return hparams
Conv autoencoder, tiny set for testing.
def make_c_args(arg_pairs): logging.debug(arg_pairs) c_args = [ '{} {}'.format(arg_type, arg_name) if arg_name else arg_type for dummy_number, arg_type, arg_name in sorted(arg_pairs) ] return ', '.join(c_args)
Build a C argument list from return type and arguments pairs.
def write(self, msg, level=logging.INFO): if msg is not None and len(msg.strip()) > 0: self.logger.log(level, msg)
method implements stream write interface, allowing to redirect stdout to logger
def _set_expressions(self, expressions): self.expressions = {} for key, item in expressions.items(): self.expressions[key] = {'function': item}
Extract expressions and variables from the user provided expressions.
def cmd_as_file(cmd, *args, **kwargs): kwargs['stdout'] = subprocess.PIPE stdin = kwargs.pop('stdin', None) if isinstance(stdin, basestring): with tempfile.TemporaryFile() as stdin_file: stdin_file.write(stdin) stdin_file.seek(0) kwargs['stdin'] = stdin_file ...
Launch `cmd` and treat its stdout as a file object
def _add_flags(flags, new_flags): flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags
Combine ``flags`` and ``new_flags``
def _decode_meta(self, meta, **extra): _meta = json.loads(meta) if meta else {} _meta.update(extra) return _meta
Decode and load underlying meta structure to dict and apply optional extra values.
def _get_tags(c): tags_ = [] for tagstr in c.run("git tag", hide=True).stdout.strip().split("\n"): try: tags_.append(Version(tagstr)) except ValueError: pass return sorted(tags_)
Return sorted list of release-style tags as semver objects.
def add_attr2fields(self, attr_name, attr_val, fields=[], exclude=[], include_all_if_empty=True): for f in self.filter_fields(fields, exclude, include_all_if_empty): f = self.fields[f.name] org_val = f.widget.attrs.get(attr_name, '') f.widget.attrs[attr_name] = '%s %s' % (org...
add attr to fields
def links(self): links = super(OffsetLimitPaginatedList, self).links if self._page.offset + self._page.limit < self.count: links["next"] = Link.for_( self._operation, self._ns, qs=self._page.next_page.to_items(), **self._context...
Include previous and next links.
def render(template, context=None, **kwargs): renderer = Renderer() return renderer.render(template, context, **kwargs)
Return the given template string rendered using the given context.
def _f(self, x, user_data=None): p_gen = x[self._Pg.i1:self._Pg.iN + 1] q_gen = x[self._Qg.i1:self._Qg.iN + 1] xx = r_[p_gen, q_gen] * self._base_mva if len(self._ipol) > 0: f = sum([g.total_cost(xx[i]) for i,g in enumerate(self._gn)]) else: f = 0 ...
Evaluates the objective function.
async def get_entity(self): if not self.entity and await self.get_input_entity(): try: self._entity =\ await self._client.get_entity(self._input_entity) except ValueError: pass return self._entity
Returns `entity` but will make an API call if necessary.
def start(self, *args, **kwargs): if args: LOG.debug("args: %s" % str(args)) if kwargs: LOG.debug("kwargs: %s" % str(kwargs)) try: self._server.start() self._server.proxyInit() return True except Exception as err: LO...
Start the server thread if it wasn't created with autostart = True.
def prt_paths(paths, prt=sys.stdout): pat = "PATHES: {GO} L{L:02} D{D:02}\n" for path in paths: for go_obj in path: prt.write(pat.format(GO=go_obj.id, L=go_obj.level, D=go_obj.depth)) prt.write("\n")
Print list of paths.
def count(cls, iterable): iterable = iter(iterable) count = 0 while True: try: next(iterable) except StopIteration: break count += 1 return count
Returns the number of items in an iterable.
def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None): if voxelspacing is None: voxelspacing = [1.] * image.ndim if offset is None: offset = [0] * image.ndim sigma = _create_structure_array(sigma, voxelspacing) smoothed = gaussian_filte...
Internal, single-image version of `shifted_mean_gauss`.
def can_join_group(self, project): if project.class_.is_locked or project.group_max < 2: return False u2g = self.fetch_group_assoc(project) if u2g: return len(list(u2g.group.users)) < project.group_max return True
Return whether or not user can join a group on `project`.
def convert_to_btc_on(self, amount, currency, date_obj): if isinstance(amount, Decimal): use_decimal = True else: use_decimal = self._force_decimal start = date_obj.strftime('%Y-%m-%d') end = date_obj.strftime('%Y-%m-%d') url = ( 'https://api.c...
Convert X amount to BTC based on given date rate
def fastp_read_n_plot(self): data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent') pconfig = { 'id': 'fastp-seq-content-n-plot', 'title': 'Fastp: Read N Content', 'xlab': 'Read Position', 'ylab': 'R1 Bef...
Make the read N content plot for Fastp
def evaluate_emb(emb, labels): d_mat = get_distance_matrix(emb) d_mat = d_mat.asnumpy() labels = labels.asnumpy() names = [] accs = [] for k in [1, 2, 4, 8, 16]: names.append('Recall@%d' % k) correct, cnt = 0.0, 0.0 for i in range(emb.shape[0]): d_mat[i, i] = ...
Evaluate embeddings based on Recall@k.
def format_entry(record, show_level=False, colorize=False): if show_level: log_str = u'{}: {}'.format(record.levelname, record.getMessage()) else: log_str = record.getMessage() if colorize and record.levelname in LOG_COLORS: log_str = u'<span color="{}">'.format(LOG_COLORS[record.lev...
Format a log entry according to its level and context