text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _find_and_cache_best_function(self, dispatch_type): """Finds the best implementation of this function given a type. This function caches the result, and uses locking for thread safety. Returns: Implementing function, in below order of preference: 1. Explicitly regis...
[ "def", "_find_and_cache_best_function", "(", "self", ",", "dispatch_type", ")", ":", "result", "=", "self", ".", "_dispatch_table", ".", "get", "(", "dispatch_type", ")", "if", "result", ":", "return", "result", "# The outer try ensures the lock is always released.", ...
44.902439
22.195122
def recall(self, mode='all'): """Recalls from the file specified by :attr:`~SR850.filename`. :param mode: Specifies the recall mode. ======= ================================================== Value Description ======= ===========================================...
[ "def", "recall", "(", "self", ",", "mode", "=", "'all'", ")", ":", "if", "mode", "==", "'all'", ":", "self", ".", "_write", "(", "'RDAT'", ")", "elif", "mode", "==", "'state'", ":", "self", ".", "_write", "(", "'RSET'", ")", "else", ":", "raise", ...
38.05
19
def read_tags(filename): """Reads values of "magic tags" defined in the given Python file. :param filename: Python filename to read the tags from :return: Dictionary of tags """ with open(filename) as f: ast_tree = ast.parse(f.read(), filename) res = {} for node in ast.walk(ast_tre...
[ "def", "read_tags", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "ast_tree", "=", "ast", ".", "parse", "(", "f", ".", "read", "(", ")", ",", "filename", ")", "res", "=", "{", "}", "for", "node", "in", "ast", ...
27.083333
18.333333
def _wrap(func, msg): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" @functools.wraps(func) def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) # turn off fi...
[ "def", "_wrap", "(", "func", ",", "msg", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "simplefilter", "(", "'always'", ",", "DeprecationWarning", ...
43.25
19.333333
def update_variable(self, variable, value) -> None: """Assign the given value(s) to the given target or base variable. If the assignment fails, |ChangeItem.update_variable| raises an error like the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pu...
[ "def", "update_variable", "(", "self", ",", "variable", ",", "value", ")", "->", "None", ":", "try", ":", "variable", "(", "value", ")", "except", "BaseException", ":", "objecttools", ".", "augment_excmessage", "(", "f'When trying to update a target variable of '", ...
46.76
20
def bg_compensate(img, sigma, splinepoints, scale): '''Reads file, subtracts background. Returns [compensated image, background].''' from PIL import Image import pylab from matplotlib.image import pil_to_array from centrosome.filter import canny import matplotlib img = Image.open(img) ...
[ "def", "bg_compensate", "(", "img", ",", "sigma", ",", "splinepoints", ",", "scale", ")", ":", "from", "PIL", "import", "Image", "import", "pylab", "from", "matplotlib", ".", "image", "import", "pil_to_array", "from", "centrosome", ".", "filter", "import", "...
35.982456
19.175439
def infer(self, pattern=False): """https://github.com/frictionlessdata/datapackage-py#package """ # Files if pattern: # No base path if not self.__base_path: message = 'Base path is required for pattern infer' raise exceptions.Dat...
[ "def", "infer", "(", "self", ",", "pattern", "=", "False", ")", ":", "# Files", "if", "pattern", ":", "# No base path", "if", "not", "self", ".", "__base_path", ":", "message", "=", "'Base path is required for pattern infer'", "raise", "exceptions", ".", "DataPa...
38.533333
24.8
def build_fptree(self, transactions, root_value, root_count, frequent, headers): """ Build the FP tree and return the root node. """ root = FPNode(root_value, root_count, None) for transaction in transactions: sorted_items = [x for x in transacti...
[ "def", "build_fptree", "(", "self", ",", "transactions", ",", "root_value", ",", "root_count", ",", "frequent", ",", "headers", ")", ":", "root", "=", "FPNode", "(", "root_value", ",", "root_count", ",", "None", ")", "for", "transaction", "in", "transactions...
37.071429
16.071429
def _process_genotype_backgrounds(self, limit=None): """ This table provides a mapping of genotypes to background genotypes Note that the background_id is also a genotype_id. Makes these triples: <ZFIN:genotype_id> GENO:has_reference_part <ZFIN:background_id> <ZFIN:backg...
[ "def", "_process_genotype_backgrounds", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "model", "=", "Model", "(", "graph", ...
37.69697
22.69697
def tmatrix_cov(C, row=None): r"""Covariance tensor for the non-reversible transition matrix ensemble Normally the covariance tensor cov(p_ij, p_kl) would carry four indices (i,j,k,l). In the non-reversible case rows are independent so that cov(p_ij, p_kl)=0 for i not equal to k. Therefore the function...
[ "def", "tmatrix_cov", "(", "C", ",", "row", "=", "None", ")", ":", "if", "row", "is", "None", ":", "alpha", "=", "C", "+", "1.0", "# Dirichlet parameters", "alpha0", "=", "alpha", ".", "sum", "(", "axis", "=", "1", ")", "# Sum of paramters (per row)", ...
27.697674
22.325581
def transforms(self): """Return an array of arrays of column transforms. #The return value is an list of list, with each list being a segment of column transformations, and #each segment having one entry per column. """ tr = [] for c in self.columns: tr.app...
[ "def", "transforms", "(", "self", ")", ":", "tr", "=", "[", "]", "for", "c", "in", "self", ".", "columns", ":", "tr", ".", "append", "(", "c", ".", "expanded_transform", ")", "return", "six", ".", "moves", ".", "zip_longest", "(", "*", "tr", ")" ]
28.923077
22.692308
def Initialize(self): """Open the delegate object.""" if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( delegate, mode=self.mode, token=self.token, age=self.age_policy)
[ "def", "Initialize", "(", "self", ")", ":", "if", "\"r\"", "in", "self", ".", "mode", ":", "delegate", "=", "self", ".", "Get", "(", "self", ".", "Schema", ".", "DELEGATE", ")", "if", "delegate", ":", "self", ".", "delegate", "=", "aff4", ".", "FAC...
37.571429
14.571429
def vm_present(name, vmconfig, config=None): ''' Ensure vm is present on the computenode name : string hostname of vm vmconfig : dict options to set for the vm config : dict fine grain control over vm_present .. note:: The following configuration properties can...
[ "def", "vm_present", "(", "name", ",", "vmconfig", ",", "config", "=", "None", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'co...
43.979215
25.692841
def __find_args_separator(self, decl_string, start_pos): """implementation details""" bracket_depth = 0 for index, ch in enumerate(decl_string[start_pos:]): if ch not in (self.__begin, self.__end, self.__separator): continue # I am interested only in < and > ...
[ "def", "__find_args_separator", "(", "self", ",", "decl_string", ",", "start_pos", ")", ":", "bracket_depth", "=", "0", "for", "index", ",", "ch", "in", "enumerate", "(", "decl_string", "[", "start_pos", ":", "]", ")", ":", "if", "ch", "not", "in", "(", ...
40
10.875
def _nt_on_change(self, key, value, isNew): """NetworkTables global listener callback""" self._send_update({"k": key, "v": value, "n": isNew})
[ "def", "_nt_on_change", "(", "self", ",", "key", ",", "value", ",", "isNew", ")", ":", "self", ".", "_send_update", "(", "{", "\"k\"", ":", "key", ",", "\"v\"", ":", "value", ",", "\"n\"", ":", "isNew", "}", ")" ]
52
8
def phoncontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT): """See :meth:`AbstractElement.phoncontent`""" if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandli...
[ "def", "phoncontent", "(", "self", ",", "cls", "=", "'current'", ",", "correctionhandling", "=", "CorrectionHandling", ".", "CURRENT", ")", ":", "if", "cls", "==", "'original'", ":", "correctionhandling", "=", "CorrectionHandling", ".", "ORIGINAL", "#backward comp...
60.916667
27.166667
def _get_pydot(self): """Return pydot package. Load pydot, if necessary.""" if self.pydot: return self.pydot self.pydot = __import__("pydot") return self.pydot
[ "def", "_get_pydot", "(", "self", ")", ":", "if", "self", ".", "pydot", ":", "return", "self", ".", "pydot", "self", ".", "pydot", "=", "__import__", "(", "\"pydot\"", ")", "return", "self", ".", "pydot" ]
33
10.5
def user(name, id='', user='', priv='', password='', status='active'): ''' Ensures that a user is configured on the device. Due to being unable to verify the user password. This is a forced operation. .. versionadded:: 2019.2.0 name: The name of the module function to execute. id(int): The us...
[ "def", "user", "(", "name", ",", "id", "=", "''", ",", "user", "=", "''", ",", "priv", "=", "''", ",", "password", "=", "''", ",", "status", "=", "'active'", ")", ":", "ret", "=", "_default_ret", "(", "name", ")", "user_conf", "=", "__salt__", "[...
26.149254
24.507463
def get_right_geo_fhs(self, dsid, fhs): """Find the right geographical file handlers for given dataset ID *dsid*.""" ds_info = self.ids[dsid] req_geo, rem_geo = self._get_req_rem_geo(ds_info) desired, other = split_desired_other(fhs, req_geo, rem_geo) if desired: try:...
[ "def", "get_right_geo_fhs", "(", "self", ",", "dsid", ",", "fhs", ")", ":", "ds_info", "=", "self", ".", "ids", "[", "dsid", "]", "req_geo", ",", "rem_geo", "=", "self", ".", "_get_req_rem_geo", "(", "ds_info", ")", "desired", ",", "other", "=", "split...
37.230769
15.538462
def _get_bundles_by_type(self, type): """Get a dictionary of bundles for requested type. Args: type: 'javascript' or 'css' """ bundles = {} bundle_definitions = self.config.get(type) if bundle_definitions is None: return bundles # bundle n...
[ "def", "_get_bundles_by_type", "(", "self", ",", "type", ")", ":", "bundles", "=", "{", "}", "bundle_definitions", "=", "self", ".", "config", ".", "get", "(", "type", ")", "if", "bundle_definitions", "is", "None", ":", "return", "bundles", "# bundle name: c...
41.242424
13.757576
def visit_Module(self, node): """ Visit the whole module and add all import at the top level. >> import numpy.linalg Becomes >> import numpy """ node.body = [k for k in (self.visit(n) for n in node.body) if k] imports = [ast.Import([ast.alias(i, mangle...
[ "def", "visit_Module", "(", "self", ",", "node", ")", ":", "node", ".", "body", "=", "[", "k", "for", "k", "in", "(", "self", ".", "visit", "(", "n", ")", "for", "n", "in", "node", ".", "body", ")", "if", "k", "]", "imports", "=", "[", "ast",...
27.125
21.5
def split_package(package): """ Split package in name, version arch and build tag. """ name = ver = arch = build = [] split = package.split("-") if len(split) > 2: build = split[-1] build_a, build_b = "", "" build_a = build[:1] if build[1:2].isdigit(): ...
[ "def", "split_package", "(", "package", ")", ":", "name", "=", "ver", "=", "arch", "=", "build", "=", "[", "]", "split", "=", "package", ".", "split", "(", "\"-\"", ")", "if", "len", "(", "split", ")", ">", "2", ":", "build", "=", "split", "[", ...
26.833333
9.5
def remap_link_target(path, absolute=False): """ remap a link target to a static URL if it's prefixed with @ """ if path.startswith('@'): # static resource return static_url(path[1:], absolute=absolute) if absolute: # absolute-ify whatever the URL is return urllib.parse.urlj...
[ "def", "remap_link_target", "(", "path", ",", "absolute", "=", "False", ")", ":", "if", "path", ".", "startswith", "(", "'@'", ")", ":", "# static resource", "return", "static_url", "(", "path", "[", "1", ":", "]", ",", "absolute", "=", "absolute", ")", ...
32.272727
17.818182
def lab_office(self, column=None, value=None, **kwargs): """Abbreviations, names, and locations of labratories and offices.""" return self._resolve_call('GIC_LAB_OFFICE', column, value, **kwargs)
[ "def", "lab_office", "(", "self", ",", "column", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_resolve_call", "(", "'GIC_LAB_OFFICE'", ",", "column", ",", "value", ",", "*", "*", "kwargs", ")" ]
69.666667
17.333333
def run(self, params): """Main run method for PyMOC tool. Takes a list of command line arguments to process. Each operation is performed on a current "running" MOC object. """ self.params = list(reversed(params)) if not self.params: self.help() ...
[ "def", "run", "(", "self", ",", "params", ")", ":", "self", ".", "params", "=", "list", "(", "reversed", "(", "params", ")", ")", "if", "not", "self", ".", "params", ":", "self", ".", "help", "(", ")", "return", "while", "self", ".", "params", ":...
27.034483
21.206897
def is_waiting_for_input(self): """ could make one step further :return: """ return self.waiting_for and \ not isinstance(self.waiting_for, forking.SwitchOnValue) and \ not is_base_type(self.waiting_for)
[ "def", "is_waiting_for_input", "(", "self", ")", ":", "return", "self", ".", "waiting_for", "and", "not", "isinstance", "(", "self", ".", "waiting_for", ",", "forking", ".", "SwitchOnValue", ")", "and", "not", "is_base_type", "(", "self", ".", "waiting_for", ...
33.25
10.75
def explain_prediction_df(estimator, doc, **kwargs): # type: (...) -> pd.DataFrame """ Explain prediction and export explanation to ``pandas.DataFrame`` All keyword arguments are passed to :func:`eli5.explain_prediction`. Weights of all features are exported by default. """ kwargs = _set_default...
[ "def", "explain_prediction_df", "(", "estimator", ",", "doc", ",", "*", "*", "kwargs", ")", ":", "# type: (...) -> pd.DataFrame", "kwargs", "=", "_set_defaults", "(", "kwargs", ")", "return", "format_as_dataframe", "(", "eli5", ".", "explain_prediction", "(", "est...
45.777778
10.666667
def convert_site_dm3_table_intensity(sites_df): """ Convert MagIC site headers to short/readable headers for a figure (used by ipmag.sites_extract) Intensity data only. Parameters ---------- sites_df : pandas DataFrame sites information Returns --------- int_df : pandas...
[ "def", "convert_site_dm3_table_intensity", "(", "sites_df", ")", ":", "# now for the intensities", "has_vadms", ",", "has_vdms", "=", "False", ",", "False", "if", "'int_abs'", "not", "in", "sites_df", ":", "sites_df", "[", "'int_abs'", "]", "=", "None", "if", "'...
44.313953
20.430233
def dump_TDDFT_data_in_GW_run(self, TDDFT_dump=True): """ :param TDDFT_dump: boolen :return: set the do_tddft variable to one in cell.in """ if TDDFT_dump == True: self.BSE_TDDFT_options.update(do_bse=0, do_tddft=1) else: self.BSE_TDDFT_options.upd...
[ "def", "dump_TDDFT_data_in_GW_run", "(", "self", ",", "TDDFT_dump", "=", "True", ")", ":", "if", "TDDFT_dump", "==", "True", ":", "self", ".", "BSE_TDDFT_options", ".", "update", "(", "do_bse", "=", "0", ",", "do_tddft", "=", "1", ")", "else", ":", "self...
37.444444
13.666667
def totz(when, tz=None): """ Return a date, time, or datetime converted to a datetime in the given timezone. If when is a datetime and has no timezone it is assumed to be local time. Date and time objects are also assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be convert...
[ "def", "totz", "(", "when", ",", "tz", "=", "None", ")", ":", "if", "when", "is", "None", ":", "return", "None", "when", "=", "to_datetime", "(", "when", ")", "if", "when", ".", "tzinfo", "is", "None", ":", "when", "=", "when", ".", "replace", "(...
39.769231
21.769231
def visitShapeExprDecl(self, ctx: ShExDocParser.ShapeExprDeclContext): """ shapeExprDecl: shapeExprLabel (shapeExpression | KW_EXTERNAL) """ label = self.context.shapeexprlabel_to_IRI(ctx.shapeExprLabel()) if self.context.schema.shapes is None: self.context.schema.shapes = [] ...
[ "def", "visitShapeExprDecl", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "ShapeExprDeclContext", ")", ":", "label", "=", "self", ".", "context", ".", "shapeexprlabel_to_IRI", "(", "ctx", ".", "shapeExprLabel", "(", ")", ")", "if", "self", ".", "conte...
48.833333
13.583333
def title(self): """ The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME """ name = c.namemap_lookup(self.id) if name is None: name = self._title + " " + client.get_semester_...
[ "def", "title", "(", "self", ")", ":", "name", "=", "c", ".", "namemap_lookup", "(", "self", ".", "id", ")", "if", "name", "is", "None", ":", "name", "=", "self", ".", "_title", "+", "\" \"", "+", "client", ".", "get_semester_title", "(", "self", "...
44.555556
20.777778
def get_constant_state(self): """Read state that was written in "first_part" mode. Returns: a structure """ ret = self.constant_states[self.next_constant_state] self.next_constant_state += 1 return ret
[ "def", "get_constant_state", "(", "self", ")", ":", "ret", "=", "self", ".", "constant_states", "[", "self", ".", "next_constant_state", "]", "self", ".", "next_constant_state", "+=", "1", "return", "ret" ]
24.888889
16.777778
def _stream_annotation(file_name, pb_dir): """ Stream an entire remote annotation file from physiobank Parameters ---------- file_name : str The name of the annotation file to be read. pb_dir : str The physiobank directory where the annotation file is located. """ # Ful...
[ "def", "_stream_annotation", "(", "file_name", ",", "pb_dir", ")", ":", "# Full url of annotation file", "url", "=", "posixpath", ".", "join", "(", "config", ".", "db_index_url", ",", "pb_dir", ",", "file_name", ")", "# Get the content", "response", "=", "requests...
26.333333
20.5
def retarget_with_change_points(song, cp_times, duration): """Create a composition of a song of a given duration that reaches music change points at specified times. This is still under construction. It might not work as well with more than 2 ``cp_times`` at the moment. Here's an example of retarge...
[ "def", "retarget_with_change_points", "(", "song", ",", "cp_times", ",", "duration", ")", ":", "analysis", "=", "song", ".", "analysis", "beat_length", "=", "analysis", "[", "BEAT_DUR_KEY", "]", "beats", "=", "np", ".", "array", "(", "analysis", "[", "\"beat...
37.506849
19.575342
def serialize(obj, **options): ''' Serialize Python data to YAML. :param obj: the data structure to serialize :param options: options given to lower yaml module. ''' options.setdefault('Dumper', Dumper) try: response = yaml.dump(obj, **options) if response.endswith('\n...\n...
[ "def", "serialize", "(", "obj", ",", "*", "*", "options", ")", ":", "options", ".", "setdefault", "(", "'Dumper'", ",", "Dumper", ")", "try", ":", "response", "=", "yaml", ".", "dump", "(", "obj", ",", "*", "*", "options", ")", "if", "response", "....
29.631579
15.210526
def parse_qc(self, qc_file): """ Parse phantompeakqualtools (spp) QC table and return quality metrics. :param str qc_file: Path to phantompeakqualtools output file, which contains sample quality measurements. """ import pandas as pd series = pd.Series() ...
[ "def", "parse_qc", "(", "self", ",", "qc_file", ")", ":", "import", "pandas", "as", "pd", "series", "=", "pd", ".", "Series", "(", ")", "try", ":", "with", "open", "(", "qc_file", ")", "as", "handle", ":", "line", "=", "handle", ".", "readlines", "...
34.333333
17.666667
def get_user_data(self, subid, params=None): ''' /v1/server/get_user_data GET - account Retrieves the (base64 encoded) user-data for this subscription. Link: https://www.vultr.com/api/#server_get_user_data ''' params = update_params(params, {'SUBID': subid}) retu...
[ "def", "get_user_data", "(", "self", ",", "subid", ",", "params", "=", "None", ")", ":", "params", "=", "update_params", "(", "params", ",", "{", "'SUBID'", ":", "subid", "}", ")", "return", "self", ".", "request", "(", "'/v1/server/get_user_data'", ",", ...
41.111111
21.555556
def get_color_map(name): """ Return a colormap as (redmap, greenmap, bluemap) Arguments: name -- the name of the colormap. If unrecognized, will default to 'jet'. """ redmap = [0] greenmap = [0] bluemap = [0] if name == 'white': # essentially a noop redmap = [0, 1] ...
[ "def", "get_color_map", "(", "name", ")", ":", "redmap", "=", "[", "0", "]", "greenmap", "=", "[", "0", "]", "bluemap", "=", "[", "0", "]", "if", "name", "==", "'white'", ":", "# essentially a noop", "redmap", "=", "[", "0", ",", "1", "]", "greenma...
110.904762
89.190476
def trigger_arbitrary_job(repo_name, builder, revision, auth, files=None, dry_run=False, extra_properties=None): """ Request buildapi to trigger a job for us. We return the request or None if dry_run is True. Raises BuildapiAuthError if credentials are invalid. """ as...
[ "def", "trigger_arbitrary_job", "(", "repo_name", ",", "builder", ",", "revision", ",", "auth", ",", "files", "=", "None", ",", "dry_run", "=", "False", ",", "extra_properties", "=", "None", ")", ":", "assert", "len", "(", "revision", ")", "==", "40", ",...
36.04878
24.878049
def workspace_backup_undo(ctx): """ Restore the last backup """ backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup)) backup_manager.undo()
[ "def", "workspace_backup_undo", "(", "ctx", ")", ":", "backup_manager", "=", "WorkspaceBackupManager", "(", "Workspace", "(", "ctx", ".", "resolver", ",", "directory", "=", "ctx", ".", "directory", ",", "mets_basename", "=", "ctx", ".", "mets_basename", ",", "...
43.666667
27
def agent_key_info_from_key_id(key_id): """Find a matching key in the ssh-agent. @param key_id {str} Either a private ssh key fingerprint, e.g. 'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to an ssh private key file (like ssh's IdentityFile config option). @return {dict} w...
[ "def", "agent_key_info_from_key_id", "(", "key_id", ")", ":", "# Need the fingerprint of the key we're using for signing. If it", "# is a path to a priv key, then we need to load it.", "if", "not", "FINGERPRINT_RE", ".", "match", "(", "key_id", ")", ":", "ssh_key", "=", "load_s...
37.372549
19.862745
def summaries(self): """Yield (name, (value, value, ...)) for each summary in the file.""" length = self.summary_length step = self.summary_step for record_number, n_summaries, summary_data in self.summary_records(): name_data = self.read_record(record_number + 1) ...
[ "def", "summaries", "(", "self", ")", ":", "length", "=", "self", ".", "summary_length", "step", "=", "self", ".", "summary_step", "for", "record_number", ",", "n_summaries", ",", "summary_data", "in", "self", ".", "summary_records", "(", ")", ":", "name_dat...
50.666667
13.916667
def setup_TreeRegression(self, covariation=True): """instantiate a TreeRegression object and set its tip_value and branch_value function to defaults that are sensible for treetime instances. Parameters ---------- covariation : bool, optional account for phylogenetic ...
[ "def", "setup_TreeRegression", "(", "self", ",", "covariation", "=", "True", ")", ":", "from", ".", "treeregression", "import", "TreeRegression", "tip_value", "=", "lambda", "x", ":", "np", ".", "mean", "(", "x", ".", "raw_date_constraint", ")", "if", "(", ...
45.481481
24.333333
def _from_pointer(pointer, incref): """Wrap an existing :c:type:`cairo_scaled_font_t *` cdata pointer. :type incref: bool :param incref: Whether increase the :ref:`reference count <refcounting>` now. :return: A new :class:`ScaledFont` instance. """ if pointe...
[ "def", "_from_pointer", "(", "pointer", ",", "incref", ")", ":", "if", "pointer", "==", "ffi", ".", "NULL", ":", "raise", "ValueError", "(", "'Null pointer'", ")", "if", "incref", ":", "cairo", ".", "cairo_scaled_font_reference", "(", "pointer", ")", "self",...
34.25
15.0625
def pcapname(dev): """Get the device pcap name by device name or Scapy NetworkInterface """ if isinstance(dev, NetworkInterface): if dev.is_invalid(): return None return dev.pcap_name try: return IFACES.dev_from_name(dev).pcap_name except ValueError: retu...
[ "def", "pcapname", "(", "dev", ")", ":", "if", "isinstance", "(", "dev", ",", "NetworkInterface", ")", ":", "if", "dev", ".", "is_invalid", "(", ")", ":", "return", "None", "return", "dev", ".", "pcap_name", "try", ":", "return", "IFACES", ".", "dev_fr...
29.25
14.833333
def arcs(self): """Get information about the arcs available in the code. Returns a sorted list of line number pairs. Line numbers have been normalized to the first line of multiline statements. """ all_arcs = [] for l1, l2 in self.byte_parser._all_arcs(): f...
[ "def", "arcs", "(", "self", ")", ":", "all_arcs", "=", "[", "]", "for", "l1", ",", "l2", "in", "self", ".", "byte_parser", ".", "_all_arcs", "(", ")", ":", "fl1", "=", "self", ".", "first_line", "(", "l1", ")", "fl2", "=", "self", ".", "first_lin...
33.714286
15.928571
def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/fo...
[ "def", "process", "(", "self", ",", "config", ",", "grains", ")", ":", "ret", "=", "[", "]", "b_config", "=", "copy", ".", "deepcopy", "(", "config", ")", "if", "'enabled'", "in", "b_config", "and", "not", "b_config", "[", "'enabled'", "]", ":", "ret...
45.247525
20.376238
def _HasOOOWrite(self, path): """Returns whether the path has had an out-of-order write.""" # Check the sizes of each path before the current one. size = tf.io.gfile.stat(path).length old_size = self._finalized_sizes.get(path, None) if size != old_size: if old_size is None: logger.erro...
[ "def", "_HasOOOWrite", "(", "self", ",", "path", ")", ":", "# Check the sizes of each path before the current one.", "size", "=", "tf", ".", "io", ".", "gfile", ".", "stat", "(", "path", ")", ".", "length", "old_size", "=", "self", ".", "_finalized_sizes", "."...
40.466667
18.266667
def pformat(self, consumed_capacity=None): """ Pretty format for insertion into table pformat """ consumed_capacity = consumed_capacity or {} lines = [] parts = ["GLOBAL", self.index_type, "INDEX", self.name] if self.status != "ACTIVE": parts.insert(0, "[%s]" % self.s...
[ "def", "pformat", "(", "self", ",", "consumed_capacity", "=", "None", ")", ":", "consumed_capacity", "=", "consumed_capacity", "or", "{", "}", "lines", "=", "[", "]", "parts", "=", "[", "\"GLOBAL\"", ",", "self", ".", "index_type", ",", "\"INDEX\"", ",", ...
44.25
15.5
def _input_as_multifile(self, data): """For use with the -profile option This input handler expects data to be a tuple containing two filenames. Index 0 will be set to -in1 and index 1 to -in2 """ if data: try: filename1, filename2 = data ...
[ "def", "_input_as_multifile", "(", "self", ",", "data", ")", ":", "if", "data", ":", "try", ":", "filename1", ",", "filename2", "=", "data", "except", ":", "raise", "ValueError", ",", "\"Expected two filenames\"", "self", ".", "Parameters", "[", "'-in'", "]"...
33.1875
16.8125
def get_xy(self, yidx, xidx=0): """ Return stored data for the given indices for plot :param yidx: the indices of the y-axis variables(1-indexing) :param xidx: the index of the x-axis variables :return: None """ assert isinstance(xidx, int) if isinstance(...
[ "def", "get_xy", "(", "self", ",", "yidx", ",", "xidx", "=", "0", ")", ":", "assert", "isinstance", "(", "xidx", ",", "int", ")", "if", "isinstance", "(", "yidx", ",", "int", ")", ":", "yidx", "=", "[", "yidx", "]", "t_vars", "=", "self", ".", ...
27.944444
17.277778
def average(self, projection=None): """ Takes the average of elements in the sequence >>> seq([1, 2]).average() 1.5 >>> seq([('a', 1), ('b', 2)]).average(lambda x: x[1]) :param projection: function to project on the sequence before taking the average :return: a...
[ "def", "average", "(", "self", ",", "projection", "=", "None", ")", ":", "length", "=", "self", ".", "size", "(", ")", "if", "projection", ":", "return", "sum", "(", "self", ".", "map", "(", "projection", ")", ")", "/", "length", "else", ":", "retu...
29.882353
19.294118
def get_tag_names(self): """Returns the set of tag names present in the XML.""" root = etree.fromstring(self.xml_full_text.encode('utf-8')) return self.get_children_tag_names(root)
[ "def", "get_tag_names", "(", "self", ")", ":", "root", "=", "etree", ".", "fromstring", "(", "self", ".", "xml_full_text", ".", "encode", "(", "'utf-8'", ")", ")", "return", "self", ".", "get_children_tag_names", "(", "root", ")" ]
50.25
12.75
def fileChunkIter(file_object, file_chunk_size=65536): """ Return an iterator to a file-like object that yields fixed size chunks :param file_object: a file-like object :param file_chunk_size: maximum size of chunk """ while True: chunk = file_object.read(file_chunk_size) if chu...
[ "def", "fileChunkIter", "(", "file_object", ",", "file_chunk_size", "=", "65536", ")", ":", "while", "True", ":", "chunk", "=", "file_object", ".", "read", "(", "file_chunk_size", ")", "if", "chunk", ":", "yield", "chunk", "else", ":", "break" ]
28.230769
17.153846
def get_matching_session(self, session, db_session, timediff=5): """ Tries to match a session with it's counterpart. For bait session it will try to match it with honeypot sessions and the other way around. :param session: session object which will be used as base for query. :pa...
[ "def", "get_matching_session", "(", "self", ",", "session", ",", "db_session", ",", "timediff", "=", "5", ")", ":", "db_session", "=", "db_session", "min_datetime", "=", "session", ".", "timestamp", "-", "timedelta", "(", "seconds", "=", "timediff", ")", "ma...
51.875
23.975
def calc_model_cosine(self, decimate=None, mode='err'): """ Calculates the cosine of the residuals with the model. Parameters ---------- decimate : Int or None, optional Decimate the residuals by `decimate` pixels. If None, no decimation is us...
[ "def", "calc_model_cosine", "(", "self", ",", "decimate", "=", "None", ",", "mode", "=", "'err'", ")", ":", "#we calculate the model cosine only in the data space of the", "#sampled indices", "if", "mode", "==", "'err'", ":", "expected_error", "=", "self", ".", "fin...
45.294118
23.45098
def brew_query_parts(self): """ Make columns, group_bys, filters, havings """ columns, group_bys, filters, havings = [], [], set(), set() for ingredient in self.ingredients(): if ingredient.query_columns: columns.extend(ingredient.query_columns) if...
[ "def", "brew_query_parts", "(", "self", ")", ":", "columns", ",", "group_bys", ",", "filters", ",", "havings", "=", "[", "]", ",", "[", "]", ",", "set", "(", ")", ",", "set", "(", ")", "for", "ingredient", "in", "self", ".", "ingredients", "(", ")"...
35.4
11.9
def load_installed_plugins(self): """ :rtype: list of Plugin """ result = [] plugin_dirs = [d for d in os.listdir(self.plugin_path) if os.path.isdir(os.path.join(self.plugin_path, d))] settings = constants.SETTINGS for d in plugin_dirs: if d == "__pycache__": ...
[ "def", "load_installed_plugins", "(", "self", ")", ":", "result", "=", "[", "]", "plugin_dirs", "=", "[", "d", "for", "d", "in", "os", ".", "listdir", "(", "self", ".", "plugin_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "pat...
41.428571
21.619048
def get_headline(self, name): """Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: ServiceMessage: the headline or None if no headline has been set """ return self._loop.run_coroutine(self._cl...
[ "def", "get_headline", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_loop", ".", "run_coroutine", "(", "self", ".", "_client", ".", "get_headline", "(", "name", ")", ")" ]
30.363636
25.636364
def get_min_row_num(mention): """Return the lowest row number that a Mention occupies. :param mention: The Mention to evaluate. If a candidate is given, default to its first Mention. :rtype: integer or None """ span = _to_span(mention) if span.sentence.is_tabular(): return span....
[ "def", "get_min_row_num", "(", "mention", ")", ":", "span", "=", "_to_span", "(", "mention", ")", "if", "span", ".", "sentence", ".", "is_tabular", "(", ")", ":", "return", "span", ".", "sentence", ".", "cell", ".", "row_start", "else", ":", "return", ...
30.166667
15.416667
def list_workers(config, *, filter_by_queues=None): """ Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen to ...
[ "def", "list_workers", "(", "config", ",", "*", ",", "filter_by_queues", "=", "None", ")", ":", "celery_app", "=", "create_app", "(", "config", ")", "worker_stats", "=", "celery_app", ".", "control", ".", "inspect", "(", ")", ".", "stats", "(", ")", "que...
32.176471
21.647059
def downloaded(name, version=None, pkgs=None, fromrepo=None, ignore_epoch=None, **kwargs): ''' .. versionadded:: 2017.7.0 Ensure that the package is downloaded, and that it is the correct version (if specified). Currently s...
[ "def", "downloaded", "(", "name", ",", "version", "=", "None", ",", "pkgs", "=", "None", ",", "fromrepo", "=", "None", ",", "ignore_epoch", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":...
34.897436
21.641026
def interpolate_nearest(self, xi, yi, zdata): """ Nearest-neighbour interpolation. Calls nearnd to find the index of the closest neighbours to xi,yi Parameters ---------- xi : float / array of floats, shape (l,) x coordinates on the Cartesian plane ...
[ "def", "interpolate_nearest", "(", "self", ",", "xi", ",", "yi", ",", "zdata", ")", ":", "if", "zdata", ".", "size", "!=", "self", ".", "npoints", ":", "raise", "ValueError", "(", "'zdata should be same size as mesh'", ")", "zdata", "=", "self", ".", "_shu...
34.846154
17.615385
def compute_stop_stats( feed: "Feed", dates: List[str], stop_ids: Optional[List[str]] = None, headway_start_time: str = "07:00:00", headway_end_time: str = "19:00:00", *, split_directions: bool = False, ) -> DataFrame: """ Compute stats for all stops for the given dates. Optional...
[ "def", "compute_stop_stats", "(", "feed", ":", "\"Feed\"", ",", "dates", ":", "List", "[", "str", "]", ",", "stop_ids", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "headway_start_time", ":", "str", "=", "\"07:00:00\"", ",", "h...
32.414286
19.242857
def _set_user(self, v, load=False): """ Setter method for user, mapped from YANG variable /snmp_server/user (list) If this variable is read-only (config: false) in the source YANG file, then _set_user is considered as a private method. Backends looking to populate this variable should do so via ...
[ "def", "_set_user", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
142.772727
69.090909
def evaluate(self, m): """Search for comments.""" g = m.groupdict() if g["strings"]: self.line_num += g['strings'].count('\n') elif g["code"]: self.line_num += g["code"].count('\n') else: if g['block']: self.evaluate_block(g) ...
[ "def", "evaluate", "(", "self", ",", "m", ")", ":", "g", "=", "m", ".", "groupdict", "(", ")", "if", "g", "[", "\"strings\"", "]", ":", "self", ".", "line_num", "+=", "g", "[", "'strings'", "]", ".", "count", "(", "'\\n'", ")", "elif", "g", "["...
32.529412
12.882353
def _sample_template(sample, out_dir): """R code to get QC for one sample""" bam_fn = dd.get_work_bam(sample) genome = dd.get_genome_build(sample) if genome in supported: peaks = sample.get("peaks_files", []).get("main") if peaks: r_code = ("library(ChIPQC);\n" ...
[ "def", "_sample_template", "(", "sample", ",", "out_dir", ")", ":", "bam_fn", "=", "dd", ".", "get_work_bam", "(", "sample", ")", "genome", "=", "dd", ".", "get_genome_build", "(", "sample", ")", "if", "genome", "in", "supported", ":", "peaks", "=", "sam...
41.294118
9.352941
def check_precondition(self, key, value): ''' Override to check for timeout ''' timeout = float(value) curr_time = self.get_current_time() if curr_time > timeout: return True return False
[ "def", "check_precondition", "(", "self", ",", "key", ",", "value", ")", ":", "timeout", "=", "float", "(", "value", ")", "curr_time", "=", "self", ".", "get_current_time", "(", ")", "if", "curr_time", ">", "timeout", ":", "return", "True", "return", "Fa...
27.444444
13.444444
def cublasDestroy(handle): """ Release CUBLAS resources. Releases hardware resources used by CUBLAS. Parameters ---------- handle : void_p CUBLAS context. """ status = _libcublas.cublasDestroy_v2(ctypes.c_void_p(handle)) cublasCheckStatus(status)
[ "def", "cublasDestroy", "(", "handle", ")", ":", "status", "=", "_libcublas", ".", "cublasDestroy_v2", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", "cublasCheckStatus", "(", "status", ")" ]
19.2
20.666667
def GetCustomJsonFieldMapping(message_type, python_name=None, json_name=None): """Return the appropriate remapping for the given field, or None.""" return _FetchRemapping(message_type, 'field', python_name=python_name, json_name=json_name, mappings=_JSON_FIE...
[ "def", "GetCustomJsonFieldMapping", "(", "message_type", ",", "python_name", "=", "None", ",", "json_name", "=", "None", ")", ":", "return", "_FetchRemapping", "(", "message_type", ",", "'field'", ",", "python_name", "=", "python_name", ",", "json_name", "=", "j...
65.6
19.2
def _check_equals_spacing(self, tokens, i): """Check the spacing of a single equals sign.""" if self._has_valid_type_annotation(tokens, i): self._check_space(tokens, i, (_MUST, _MUST)) elif self._inside_brackets("(") or self._inside_brackets("lambda"): self._check_space(t...
[ "def", "_check_equals_spacing", "(", "self", ",", "tokens", ",", "i", ")", ":", "if", "self", ".", "_has_valid_type_annotation", "(", "tokens", ",", "i", ")", ":", "self", ".", "_check_space", "(", "tokens", ",", "i", ",", "(", "_MUST", ",", "_MUST", "...
52.125
16.875
def is_notifying(cls, user_or_email, instance): """Check if the watch created by notify exists.""" return super(InstanceEvent, cls).is_notifying(user_or_email, object_id=instance.pk)
[ "def", "is_notifying", "(", "cls", ",", "user_or_email", ",", "instance", ")", ":", "return", "super", "(", "InstanceEvent", ",", "cls", ")", ".", "is_notifying", "(", "user_or_email", ",", "object_id", "=", "instance", ".", "pk", ")" ]
62.25
17.75
def search(self, tid, seller_nick): '''taobao.logistics.trace.search 物流流转信息查询 用户根据淘宝交易号查询物流流转信息,如2010-8-10 15:23:00到达杭州集散地''' request = TOPRequest('taobao.logistics.address.add') request['tid'] = tid request['seller_nick'] = seller_nick self.create(self.execute(r...
[ "def", "search", "(", "self", ",", "tid", ",", "seller_nick", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.logistics.address.add'", ")", "request", "[", "'tid'", "]", "=", "tid", "request", "[", "'seller_nick'", "]", "=", "seller_nick", "self", ".",...
37.777778
13.333333
def create_figures(n, *fig_args, **fig_kwargs): '''Create multiple figures. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs ...
[ "def", "create_figures", "(", "n", ",", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", ":", "return", "[", "create_figure", "(", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", "for", "_", "in", "range", "(", "n", ")", "]" ]
41.545455
25
def load_data_file_to_net(self, filename): ''' Load Clustergrammer's dat format (saved as JSON). ''' inst_dat = self.load_json_to_dict(filename) load_data.load_data_to_net(self, inst_dat)
[ "def", "load_data_file_to_net", "(", "self", ",", "filename", ")", ":", "inst_dat", "=", "self", ".", "load_json_to_dict", "(", "filename", ")", "load_data", ".", "load_data_to_net", "(", "self", ",", "inst_dat", ")" ]
33.666667
15.666667
def all_blocks(self): status = OrderedDict.fromkeys(parameters.BLOCKS.keys()) status['13AE'] = ['discovery complete', '50', '24.05'] status['13AO'] = ['discovery complete', '36', '24.40'] status['13BL'] = ['discovery complete', '79', '24.48'] status['14BH'] = ['discovery running...
[ "def", "all_blocks", "(", "self", ")", ":", "status", "=", "OrderedDict", ".", "fromkeys", "(", "parameters", ".", "BLOCKS", ".", "keys", "(", ")", ")", "status", "[", "'13AE'", "]", "=", "[", "'discovery complete'", ",", "'50'", ",", "'24.05'", "]", "...
39.08
22.28
def _can_be_double(x): """ Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrower, or when is an integer that can be safely converted to double (if the roundtrip conversion works). """ return ((np.issubdtype(...
[ "def", "_can_be_double", "(", "x", ")", ":", "return", "(", "(", "np", ".", "issubdtype", "(", "x", ".", "dtype", ",", "np", ".", "floating", ")", "and", "x", ".", "dtype", ".", "itemsize", "<=", "np", ".", "dtype", "(", "float", ")", ".", "items...
37.538462
18.461538
def create(cls, name, servers=None, time_range='yesterday', all_logs=False, filter_for_delete=None, comment=None, **kwargs): """ Create a new delete log task. Provide True to all_logs to delete all log types. Otherwise provide kwargs to specify each log by type of interest...
[ "def", "create", "(", "cls", ",", "name", ",", "servers", "=", "None", ",", "time_range", "=", "'yesterday'", ",", "all_logs", "=", "False", ",", "filter_for_delete", "=", "None", ",", "comment", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", ...
45.041667
20.125
def camel_to_underscore(string): """Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string. """ string = FIRST_CAP_RE.sub(r'\1_\2', string) return ALL_CAP_R...
[ "def", "camel_to_underscore", "(", "string", ")", ":", "string", "=", "FIRST_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "string", ")", "return", "ALL_CAP_RE", ".", "sub", "(", "r'\\1_\\2'", ",", "string", ")", ".", "lower", "(", ")" ]
26.076923
17.307692
def lookup_character_keycode(self, character): """ Looks up the keysym for the character then returns the keycode mapping for that keysym. """ keysym = self.string_to_keysym.get(character, 0) if keysym == 0: keysym = self.string_to_keysym.get(KEYSYMS[character...
[ "def", "lookup_character_keycode", "(", "self", ",", "character", ")", ":", "keysym", "=", "self", ".", "string_to_keysym", ".", "get", "(", "character", ",", "0", ")", "if", "keysym", "==", "0", ":", "keysym", "=", "self", ".", "string_to_keysym", ".", ...
41.222222
15
def run_preassembly(stmts_in, **kwargs): """Run preassembly on a list of statements. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to preassemble. return_toplevel : Optional[bool] If True, only the top-level statements are returned. If False,...
[ "def", "run_preassembly", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "dump_pkl_unique", "=", "kwargs", ".", "get", "(", "'save_unique'", ")", "belief_scorer", "=", "kwargs", ".", "get", "(", "'belief_scorer'", ")", "use_hierarchies", "=", "kwargs", ...
45.415385
19.261538
def _get_mean(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # Zhao et al. 2006 - Vs30 + Rrup mean_zh06, stds1 = super().get_mean_and_...
[ "def", "_get_mean", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# Zhao et al. 2006 - Vs30 + Rrup", "mean_zh06", ",", "stds1", "=", "super", "(", ")", ".", "get_mean_and_stddevs", "(", "sites", ",", "rup", ...
46.8
17.2
def renew_token(self): """Convenience method: renew Vault token""" url = _url_joiner(self._vault_url, 'v1/auth/token/renew-self') resp = requests.get(url, headers=self._headers) resp.raise_for_status() data = resp.json() if data.get('errors'): raise VaultExcep...
[ "def", "renew_token", "(", "self", ")", ":", "url", "=", "_url_joiner", "(", "self", ".", "_vault_url", ",", "'v1/auth/token/renew-self'", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", ")", "resp", "....
43.777778
18.555556
def cache_clean(path=None, runas=None, env=None, force=False): ''' Clean cached NPM packages. If no path for a specific package is provided the entire cache will be cleared. path The cache subpath to delete, or None to clear the entire cache runas The user to run NPM with env...
[ "def", "cache_clean", "(", "path", "=", "None", ",", "runas", "=", "None", ",", "env", "=", "None", ",", "force", "=", "False", ")", ":", "env", "=", "env", "or", "{", "}", "if", "runas", ":", "uid", "=", "salt", ".", "utils", ".", "user", ".",...
23.8
26.64
def create_order_line_item(cls, order_line_item, **kwargs): """Create OrderLineItem Create a new OrderLineItem This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_order_line_item(order_line...
[ "def", "create_order_line_item", "(", "cls", ",", "order_line_item", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_create_order_li...
43.666667
21.761905
def rebalance(self, weight, child, base=np.nan, update=True): """ Rebalance a child to a given weight. This is a helper method to simplify code logic. This method is used when we want to se the weight of a particular child to a set amount. It is similar to allocate, but it calcu...
[ "def", "rebalance", "(", "self", ",", "weight", ",", "child", ",", "base", "=", "np", ".", "nan", ",", "update", "=", "True", ")", ":", "# if weight is 0 - we want to close child", "if", "weight", "==", "0", ":", "if", "child", "in", "self", ".", "childr...
39.765957
19.553191
def enhance_pubmed_annotations(pubmed: Mapping[str, Any]) -> Mapping[str, Any]: """Enhance pubmed namespace IDs Add additional entity and annotation types to annotations Use preferred id for namespaces as needed Add strings from Title, Abstract matching Pubtator BioConcept spans NOTE - basically d...
[ "def", "enhance_pubmed_annotations", "(", "pubmed", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Mapping", "[", "str", ",", "Any", "]", ":", "text", "=", "pubmed", "[", "\"title\"", "]", "+", "pubmed", "[", "\"abstract\"", "]", "annotations",...
33.810345
24.87931
def _handle_get(self, request_data): """ An OCSP GET request contains the DER-in-base64 encoded OCSP request in the HTTP request URL. """ der = base64.b64decode(request_data) ocsp_request = self._parse_ocsp_request(der) return self._build_http_response(ocsp_reques...
[ "def", "_handle_get", "(", "self", ",", "request_data", ")", ":", "der", "=", "base64", ".", "b64decode", "(", "request_data", ")", "ocsp_request", "=", "self", ".", "_parse_ocsp_request", "(", "der", ")", "return", "self", ".", "_build_http_response", "(", ...
39.375
11.375
def set_vocabulary(self, peer_id, from_dialogue=None, update=False): """ Получает вокабулар из функции get_vocabulary и делает его активным. """ self.tokens_array = self.get_vocabulary( peer_id, from_dialogue, update ) self.create_base...
[ "def", "set_vocabulary", "(", "self", ",", "peer_id", ",", "from_dialogue", "=", "None", ",", "update", "=", "False", ")", ":", "self", ".", "tokens_array", "=", "self", ".", "get_vocabulary", "(", "peer_id", ",", "from_dialogue", ",", "update", ")", "self...
28.363636
19.272727
def AddFilterOptions(self, argument_group): """Adds the filter options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. """ names = ['artifact_filters', 'date_filters', 'filter_file'] helpers_manager.ArgumentHelperManager.AddCommandLineArguments(...
[ "def", "AddFilterOptions", "(", "self", ",", "argument_group", ")", ":", "names", "=", "[", "'artifact_filters'", ",", "'date_filters'", ",", "'filter_file'", "]", "helpers_manager", ".", "ArgumentHelperManager", ".", "AddCommandLineArguments", "(", "argument_group", ...
44.4
20.533333
def update_normals(self, normals): """ Update the triangle normals. """ normals = np.array(normals, dtype=np.float32) self._vbo_n.set_data(normals)
[ "def", "update_normals", "(", "self", ",", "normals", ")", ":", "normals", "=", "np", ".", "array", "(", "normals", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "_vbo_n", ".", "set_data", "(", "normals", ")" ]
26
9.428571
def stop(self): """ trigger clean up by hand, needs to be done when not using context management via 'with' statement - will terminate loop process - show a last progress -> see the full 100% on exit - releases terminal reservation """...
[ "def", "stop", "(", "self", ")", ":", "super", "(", "Progress", ",", "self", ")", ".", "stop", "(", ")", "terminal", ".", "terminal_unreserve", "(", "progress_obj", "=", "self", ",", "verbose", "=", "self", ".", "verbose", ")", "if", "self", ".", "sh...
35.375
13.541667
def copy(tree, source_filename): """ Copy file in tree, show a progress bar during operations, and return the sha1 sum of copied file. """ #_, ext = os.path.splitext(source_filename) filehash = sha1() with printer.progress(os.path.getsize(source_filename)) as update: with open(source...
[ "def", "copy", "(", "tree", ",", "source_filename", ")", ":", "#_, ext = os.path.splitext(source_filename)", "filehash", "=", "sha1", "(", ")", "with", "printer", ".", "progress", "(", "os", ".", "path", ".", "getsize", "(", "source_filename", ")", ")", "as", ...
48.6
16.28
def fromDataset(datatype, value, metadata=None, tmap=None): """ Return a representation of dataset argument as an instance of the class corresponding to its datatype """ if tmap is None: tmap = typemap return tmap[datatype.upper()].fromDataset(value, meta...
[ "def", "fromDataset", "(", "datatype", ",", "value", ",", "metadata", "=", "None", ",", "tmap", "=", "None", ")", ":", "if", "tmap", "is", "None", ":", "tmap", "=", "typemap", "return", "tmap", "[", "datatype", ".", "upper", "(", ")", "]", ".", "fr...
36.222222
18.222222
def latlon(location, throttle=0.5, center=True, round_digits=2): '''Look up the latitude/longitude coordinates of a given location using the Google Maps API. The result is cached to avoid redundant API requests. throttle: send at most one request in this many seconds center: return the center of th...
[ "def", "latlon", "(", "location", ",", "throttle", "=", "0.5", ",", "center", "=", "True", ",", "round_digits", "=", "2", ")", ":", "global", "last_read", "if", "isinstance", "(", "location", ",", "list", ")", ":", "return", "map", "(", "lambda", "x", ...
38.824561
25.245614
def add_edge(self, ind_node, dep_node): """ Add an edge (dependency) between the specified nodes. Args: ind_node (str): The independent node to add an edge to. dep_node (str): The dependent node that has a dependency on the ind_node. Raises: ...
[ "def", "add_edge", "(", "self", ",", "ind_node", ",", "dep_node", ")", ":", "graph", "=", "self", ".", "graph", "if", "ind_node", "not", "in", "graph", ":", "raise", "KeyError", "(", "'independent node %s does not exist'", "%", "ind_node", ")", "if", "dep_no...
38.692308
17
def parse_file(self, sg_file=None, data=None): """Parse a sensor graph file into an AST describing the file. This function builds the statements list for this parser. If you pass ``sg_file``, it will be interpreted as the path to a file to parse. If you pass ``data`` it will be directl...
[ "def", "parse_file", "(", "self", ",", "sg_file", "=", "None", ",", "data", "=", "None", ")", ":", "if", "sg_file", "is", "not", "None", "and", "data", "is", "not", "None", ":", "raise", "ArgumentError", "(", "\"You must pass either a path to an sgf file or th...
40.548387
24.096774
def info(cwd, targets=None, user=None, username=None, password=None, fmt='str'): ''' Display the Subversion information from the checkout. cwd The path to the Subversion repository targets : None files, directories, and URLs to pass to the c...
[ "def", "info", "(", "cwd", ",", "targets", "=", "None", ",", "user", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "fmt", "=", "'str'", ")", ":", "opts", "=", "list", "(", ")", "if", "fmt", "==", "'xml'", ":", "o...
22.909091
23.236364
def _set_config_mode(self, v, load=False): """ Setter method for config_mode, mapped from YANG variable /interface/fc_port/config_mode (interface-fc-config-mode-type) If this variable is read-only (config: false) in the source YANG file, then _set_config_mode is considered as a private method. Backe...
[ "def", "_set_config_mode", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "ba...
98.416667
48.208333