text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def clean_promoted_guids(raw_promoted_guids): """ Verify that the promoted GUIDs are formatted correctly, otherwise strip it down into an empty list. """ valid = True for row in raw_promoted_guids: if len(row) != 2: valid = False break if not ( (...
[ "def", "clean_promoted_guids", "(", "raw_promoted_guids", ")", ":", "valid", "=", "True", "for", "row", "in", "raw_promoted_guids", ":", "if", "len", "(", "row", ")", "!=", "2", ":", "valid", "=", "False", "break", "if", "not", "(", "(", "isinstance", "(...
26.285714
0.001748
def raw_mode(): """ Enables terminal raw mode during the context. Note: Currently noop for Windows systems. Usage: :: with raw_mode(): do_some_stuff() """ if WIN: # No implementation for windows yet. yield # needed for the empty context manager to work ...
[ "def", "raw_mode", "(", ")", ":", "if", "WIN", ":", "# No implementation for windows yet.", "yield", "# needed for the empty context manager to work", "else", ":", "# imports are placed here because this will fail under Windows", "import", "tty", "import", "termios", "if", "no...
27.404762
0.000839
def renamed(self, name): """ Duplicate the datum and rename it """ duplicate = copy(self) duplicate._name = name return duplicate
[ "def", "renamed", "(", "self", ",", "name", ")", ":", "duplicate", "=", "copy", "(", "self", ")", "duplicate", ".", "_name", "=", "name", "return", "duplicate" ]
24.428571
0.011299
def _network_indicator_percentages(fields, network_indicators): """Encapsula el cálculo de indicadores de porcentaje (de errores, de campos recomendados/optativos utilizados, de datasets actualizados) sobre la red de nodos entera. Args: fields (dict): Diccionario con claves 'recomendado', 'opta...
[ "def", "_network_indicator_percentages", "(", "fields", ",", "network_indicators", ")", ":", "# Los porcentuales no se pueden sumar, tienen que ser recalculados", "percentages", "=", "{", "'datasets_meta_ok_pct'", ":", "(", "network_indicators", ".", "get", "(", "'datasets_meta...
42.711538
0.00044
def multi_dict(pairs): """ Given a set of key value pairs, create a dictionary. If a key occurs multiple times, stack the values into an array. Can be called like the regular dict(pairs) constructor Parameters ---------- pairs: (n,2) array of key, value pairs Returns ---------- ...
[ "def", "multi_dict", "(", "pairs", ")", ":", "result", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "k", ",", "v", "in", "pairs", ":", "result", "[", "k", "]", ".", "append", "(", "v", ")", "return", "result" ]
24.85
0.001938
def import_recursive(path): """ Recursively import all modules and packages Thanks http://stackoverflow.com/a/25562415/1267398 XXX: Needs UT :attr path: Path to package/module """ results = {} obj = importlib.import_module(path) results[path] = obj path = getattr(obj, '__path__'...
[ "def", "import_recursive", "(", "path", ")", ":", "results", "=", "{", "}", "obj", "=", "importlib", ".", "import_module", "(", "path", ")", "results", "[", "path", "]", "=", "obj", "path", "=", "getattr", "(", "obj", ",", "'__path__'", ",", "os", "....
33.333333
0.001621
def reset_weights(self): """Reset weights after a resampling step. """ if self.fk.isAPF: lw = (rs.log_mean_exp(self.logetat, W=self.W) - self.logetat[self.A]) self.wgts = rs.Weights(lw=lw) else: self.wgts = rs.Weights()
[ "def", "reset_weights", "(", "self", ")", ":", "if", "self", ".", "fk", ".", "isAPF", ":", "lw", "=", "(", "rs", ".", "log_mean_exp", "(", "self", ".", "logetat", ",", "W", "=", "self", ".", "W", ")", "-", "self", ".", "logetat", "[", "self", "...
33.111111
0.009804
def to_string(self): """Return a string that tries to reconstitute the variable decl.""" suffix = '%s %s' % (self.type, self.name) if self.initial_value: suffix += ' = ' + self.initial_value return suffix
[ "def", "to_string", "(", "self", ")", ":", "suffix", "=", "'%s %s'", "%", "(", "self", ".", "type", ",", "self", ".", "name", ")", "if", "self", ".", "initial_value", ":", "suffix", "+=", "' = '", "+", "self", ".", "initial_value", "return", "suffix" ]
40.5
0.008065
def update(self, cur_value, mesg=None): """Update progressbar with current value of process Parameters ---------- cur_value : number Current value of process. Should be <= max_value (but this is not enforced). The percent of the progressbar will be computed as ...
[ "def", "update", "(", "self", ",", "cur_value", ",", "mesg", "=", "None", ")", ":", "# Ensure floating-point division so we can get fractions of a percent", "# for the progressbar.", "self", ".", "cur_value", "=", "cur_value", "progress", "=", "float", "(", "self", "....
43.073171
0.001107
def get_gene_id(gene_name): '''Retrieve systematic yeast gene name from the common name. :param gene_name: Common name for yeast gene (e.g. ADE2). :type gene_name: str :returns: Systematic name for yeast gene (e.g. YOR128C). :rtype: str ''' from intermine.webservice import Service ser...
[ "def", "get_gene_id", "(", "gene_name", ")", ":", "from", "intermine", ".", "webservice", "import", "Service", "service", "=", "Service", "(", "'http://yeastmine.yeastgenome.org/yeastmine/service'", ")", "# Get a new query on the class (table) you will be querying:", "query", ...
35.2
0.00079
def flux_randomization(model, threshold, tfba, solver): """Find a random flux solution on the boundary of the solution space. The reactions in the threshold dictionary are constrained with the associated lower bound. Args: model: MetabolicModel to solve. threshold: dict of additional l...
[ "def", "flux_randomization", "(", "model", ",", "threshold", ",", "tfba", ",", "solver", ")", ":", "optimize", "=", "{", "}", "for", "reaction_id", "in", "model", ".", "reactions", ":", "if", "model", ".", "is_reversible", "(", "reaction_id", ")", ":", "...
34.5
0.00094
async def get_json( self, force: bool=False, silent: bool=False, cache: bool=True, ) -> Any: """Parses the body data as JSON and returns it. Arguments: force: Force JSON parsing even if the mimetype is not JSON. silent: Do not trigger error handling if parsing fails,...
[ "async", "def", "get_json", "(", "self", ",", "force", ":", "bool", "=", "False", ",", "silent", ":", "bool", "=", "False", ",", "cache", ":", "bool", "=", "True", ",", ")", "->", "Any", ":", "if", "cache", "and", "self", ".", "_cached_json", "is",...
33.103448
0.009109
def validate(self): """ validate: Makes sure topic is valid Args: None Returns: boolean indicating if topic is valid """ try: assert self.kind == content_kinds.TOPIC, "Assumption Failed: Node is supposed to be a topic" return super(TopicNode, self)...
[ "def", "validate", "(", "self", ")", ":", "try", ":", "assert", "self", ".", "kind", "==", "content_kinds", ".", "TOPIC", ",", "\"Assumption Failed: Node is supposed to be a topic\"", "return", "super", "(", "TopicNode", ",", "self", ")", ".", "validate", "(", ...
47.4
0.008282
def GetNeighbors(EPIC, season=None, model=None, neighbors=10, mag_range=(11., 13.), cdpp_range=None, aperture_name='k2sff_15', cadence='lc', **kwargs): ''' Return `neighbors` random bright stars on the same module as `EPIC`. :param int EPIC: The EPIC ID nu...
[ "def", "GetNeighbors", "(", "EPIC", ",", "season", "=", "None", ",", "model", "=", "None", ",", "neighbors", "=", "10", ",", "mag_range", "=", "(", "11.", ",", "13.", ")", ",", "cdpp_range", "=", "None", ",", "aperture_name", "=", "'k2sff_15'", ",", ...
36.107784
0.000484
def print_languages(ctx, param, value): """Callback for <all> flag. Prints formatted sorted list of supported languages and exits """ if not value or ctx.resilient_parsing: return try: langs = tts_langs() langs_str_list = sorted("{}: {}".format(k, langs[k]) for k in langs) ...
[ "def", "print_languages", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "not", "value", "or", "ctx", ".", "resilient_parsing", ":", "return", "try", ":", "langs", "=", "tts_langs", "(", ")", "langs_str_list", "=", "sorted", "(", "\"{}: {}\"", "...
38.071429
0.001832
def parse_pac_file(pacfile): """ Reads the pacfile and evaluates it in the Javascript engine created by init(). """ try: with open(pacfile) as f: pac_script = f.read() _pacparser.parse_pac_string(pac_script) except IOError: raise IOError('Could not read the pacfile: {}'.format(pacfile))
[ "def", "parse_pac_file", "(", "pacfile", ")", ":", "try", ":", "with", "open", "(", "pacfile", ")", "as", "f", ":", "pac_script", "=", "f", ".", "read", "(", ")", "_pacparser", ".", "parse_pac_string", "(", "pac_script", ")", "except", "IOError", ":", ...
28.090909
0.018809
def get(self, path, watch=None): """Returns the data of the specified node.""" _log.debug( "ZK: Getting {path}".format(path=path), ) return self.zk.get(path, watch)
[ "def", "get", "(", "self", ",", "path", ",", "watch", "=", "None", ")", ":", "_log", ".", "debug", "(", "\"ZK: Getting {path}\"", ".", "format", "(", "path", "=", "path", ")", ",", ")", "return", "self", ".", "zk", ".", "get", "(", "path", ",", "...
33.833333
0.009615
def xerrorbar(self, canvas, X, Y, error, color=None, label=None, **kwargs): """ Make an errorbar along the xaxis for points at (X,Y) on the canvas. if error is two dimensional, the lower error is error[:,0] and the upper error is error[:,1] the kwargs are plotting librar...
[ "def", "xerrorbar", "(", "self", ",", "canvas", ",", "X", ",", "Y", ",", "error", ",", "color", "=", "None", ",", "label", "=", "None", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "\"Implement all plot functions in AbstractPlottin...
53
0.008247
def attach_image(field, nested_fields, page, record_keeper=None): ''' Returns a function that attaches an image to page if it exists Currenlty assumes that images have already been imported and info has been stored in record_keeper ''' if (field in nested_fields) and nested_fields[field]: ...
[ "def", "attach_image", "(", "field", ",", "nested_fields", ",", "page", ",", "record_keeper", "=", "None", ")", ":", "if", "(", "field", "in", "nested_fields", ")", "and", "nested_fields", "[", "field", "]", ":", "foreign_image_id", "=", "nested_fields", "["...
41
0.000822
async def create_redis(address, *, db=None, password=None, ssl=None, encoding=None, commands_factory=Redis, parser=None, timeout=None, connection_cls=None, loop=None): """Creates high-level Redis interface. This function is a coroutine. "...
[ "async", "def", "create_redis", "(", "address", ",", "*", ",", "db", "=", "None", ",", "password", "=", "None", ",", "ssl", "=", "None", ",", "encoding", "=", "None", ",", "commands_factory", "=", "Redis", ",", "parser", "=", "None", ",", "timeout", ...
44.529412
0.001294
def update(did): """Update DDO of an existing asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@contex...
[ "def", "update", "(", "did", ")", ":", "required_attributes", "=", "[", "'@context'", ",", "'created'", ",", "'id'", ",", "'publicKey'", ",", "'authentication'", ",", "'proof'", ",", "'service'", "]", "required_metadata_base_attributes", "=", "[", "'name'", ",",...
46.203125
0.002428
def adjust_weights_discrepancy(self, resfile=None,original_ceiling=True): """adjusts the weights of each non-zero weight observation based on the residual in the pest residual file so each observations contribution to phi is 1.0 Parameters ---------- resfile : str ...
[ "def", "adjust_weights_discrepancy", "(", "self", ",", "resfile", "=", "None", ",", "original_ceiling", "=", "True", ")", ":", "if", "resfile", "is", "not", "None", ":", "self", ".", "resfile", "=", "resfile", "self", ".", "__res", "=", "None", "obs", "=...
42.416667
0.008646
def verbose(f): """ Add verbose flags and add logging handlers """ @click.pass_context def new_func(ctx, *args, **kwargs): global log verbosity = ["critical", "error", "warn", "info", "debug"][ int(min(ctx.obj.get("verbose", 0), 4)) ] log.setLevel(getattr(log...
[ "def", "verbose", "(", "f", ")", ":", "@", "click", ".", "pass_context", "def", "new_func", "(", "ctx", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "log", "verbosity", "=", "[", "\"critical\"", ",", "\"error\"", ",", "\"warn\"", ",...
34.897436
0.000715
def _update_trace_info(self, fields, hm): """Parses a trace line and updates the :attr:`status_info` attribute. Parameters ---------- fields : list List of the tab-seperated elements of the trace line hm : dict Maps the column IDs to their position in the...
[ "def", "_update_trace_info", "(", "self", ",", "fields", ",", "hm", ")", ":", "process", "=", "fields", "[", "hm", "[", "\"process\"", "]", "]", "if", "process", "not", "in", "self", ".", "processes", ":", "return", "# Get information from a single line of tra...
39.138889
0.000692
def generate_salt_cmd(target, module, args=None, kwargs=None): """ Generates a command (the arguments) for the `salt` or `salt-ssh` CLI """ args = args or [] kwargs = kwargs or {} target = target or '*' target = '"%s"' % target cmd = [target, module] for arg in args: cmd.appe...
[ "def", "generate_salt_cmd", "(", "target", ",", "module", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "args", "=", "args", "or", "[", "]", "kwargs", "=", "kwargs", "or", "{", "}", "target", "=", "target", "or", "'*'", "target", ...
29.071429
0.002381
def eigenvectors_rev(T, k, right=True, ncv=None, mu=None): r"""Compute eigenvectors of reversible transition matrix. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix (stochastic matrix) k : int Number of eigenvalues to compute right : bool, optional ...
[ "def", "eigenvectors_rev", "(", "T", ",", "k", ",", "right", "=", "True", ",", "ncv", "=", "None", ",", "mu", "=", "None", ")", ":", "if", "mu", "is", "None", ":", "mu", "=", "stationary_distribution", "(", "T", ")", "\"\"\" symmetrize T \"\"\"", "smu"...
31.243902
0.000757
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: """ Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check? """ log.info("Downloading from {} to {}", url, fi...
[ "def", "download", "(", "url", ":", "str", ",", "filename", ":", "str", ",", "skip_cert_verify", ":", "bool", "=", "True", ")", "->", "None", ":", "log", ".", "info", "(", "\"Downloading from {} to {}\"", ",", "url", ",", "filename", ")", "# urllib.request...
41.068966
0.00082
def search(query, query_type=DEFAULT_QUERY_TYPE): """Search database using parsed query. Executes a database search query from the given ``query`` (a ``Query`` object) and optionally accepts a list of search weights. By default, the search results are ordered by weight. :param query: containing te...
[ "def", "search", "(", "query", ",", "query_type", "=", "DEFAULT_QUERY_TYPE", ")", ":", "# Build the SQL statement.", "statement", ",", "arguments", "=", "_build_search", "(", "query", ")", "# Execute the SQL.", "if", "statement", "is", "None", "and", "arguments", ...
38.16
0.001022
def parse_ndxlist(output): """Parse output from make_ndx to build list of index groups:: groups = parse_ndxlist(output) output should be the standard output from ``make_ndx``, e.g.:: rc,output,junk = gromacs.make_ndx(..., input=('', 'q'), stdout=False, stderr=True) (or simply use rc...
[ "def", "parse_ndxlist", "(", "output", ")", ":", "m", "=", "NDXLIST", ".", "search", "(", "output", ")", "# make sure we pick up a proper full list", "grouplist", "=", "m", ".", "group", "(", "'LIST'", ")", "return", "parse_groups", "(", "grouplist", ")" ]
26.766667
0.002404
def deparagraph(element, doc): """Panflute filter function that converts content wrapped in a Para to Plain. Use this filter with pandoc as:: pandoc [..] --filter=lsstprojectmeta-deparagraph Only lone paragraphs are affected. Para elements with siblings (like a second Para) are left unaff...
[ "def", "deparagraph", "(", "element", ",", "doc", ")", ":", "if", "isinstance", "(", "element", ",", "Para", ")", ":", "# Check if siblings exist; don't process the paragraph in that case.", "if", "element", ".", "next", "is", "not", "None", ":", "return", "elemen...
39.071429
0.000892
def _address_rxp(self, addr): """ Create a regex string for addresses, that matches several representations: - with(out) '0x' prefix - `pex` version This function takes care of maintaining additional lookup keys for substring matches. In case the given string is n...
[ "def", "_address_rxp", "(", "self", ",", "addr", ")", ":", "try", ":", "addr", "=", "to_checksum_address", "(", "addr", ")", "rxp", "=", "'(?:0x)?'", "+", "pex", "(", "address_checksum_and_decode", "(", "addr", ")", ")", "+", "f'(?:{addr.lower()[10:]})?'", "...
48.8
0.009383
def version(self, pretty=False, best=False): """ Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. """ versions = [ self.os_release_attr('version_id'), self.lsb_release_attr('release'), self.distr...
[ "def", "version", "(", "self", ",", "pretty", "=", "False", ",", "best", "=", "False", ")", ":", "versions", "=", "[", "self", ".", "os_release_attr", "(", "'version_id'", ")", ",", "self", ".", "lsb_release_attr", "(", "'release'", ")", ",", "self", "...
40.787879
0.001451
def get_archives_to_prune(archives, hook_data): """Return list of keys to delete.""" files_to_skip = [] for i in ['current_archive_filename', 'old_archive_filename']: if hook_data.get(i): files_to_skip.append(hook_data[i]) archives.sort(key=itemgetter('LastModified'), ...
[ "def", "get_archives_to_prune", "(", "archives", ",", "hook_data", ")", ":", "files_to_skip", "=", "[", "]", "for", "i", "in", "[", "'current_archive_filename'", ",", "'old_archive_filename'", "]", ":", "if", "hook_data", ".", "get", "(", "i", ")", ":", "fil...
47
0.002088
def apply_host_template(resource_root, name, cluster_name, host_ids, start_roles): """ Apply a host template identified by name on the specified hosts and optionally start them. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @param host_...
[ "def", "apply_host_template", "(", "resource_root", ",", "name", ",", "cluster_name", ",", "host_ids", ",", "start_roles", ")", ":", "host_refs", "=", "[", "]", "for", "host_id", "in", "host_ids", ":", "host_refs", ".", "append", "(", "ApiHostRef", "(", "res...
36.95
0.013193
def project_events(self, initial_state, domain_events): """ Evolves initial state using the sequence of domain events and a mutator function. """ return reduce(self._mutator_func or self.mutate, domain_events, initial_state)
[ "def", "project_events", "(", "self", ",", "initial_state", ",", "domain_events", ")", ":", "return", "reduce", "(", "self", ".", "_mutator_func", "or", "self", ".", "mutate", ",", "domain_events", ",", "initial_state", ")" ]
50.4
0.015625
def getProgressPercentage(self): """Returns the progress percentage of this worksheet """ state = api.get_workflow_status_of(self) if state == "verified": return 100 steps = 0 query = dict(getWorksheetUID=api.get_uid(self)) analyses = api.search(query...
[ "def", "getProgressPercentage", "(", "self", ")", ":", "state", "=", "api", ".", "get_workflow_status_of", "(", "self", ")", "if", "state", "==", "\"verified\"", ":", "return", "100", "steps", "=", "0", "query", "=", "dict", "(", "getWorksheetUID", "=", "a...
34.5
0.00235
def exit(self): '''Close connection.''' self.output.write("Happy hacking!") self.output.nextLine() self.output.loseConnection()
[ "def", "exit", "(", "self", ")", ":", "self", ".", "output", ".", "write", "(", "\"Happy hacking!\"", ")", "self", ".", "output", ".", "nextLine", "(", ")", "self", ".", "output", ".", "loseConnection", "(", ")" ]
31
0.012579
def _cache(self, func, func_memory_level=1, **kwargs): """ Return a joblib.Memory object. The memory_level determines the level above which the wrapped function output is cached. By specifying a numeric value for this level, the user can to control the amount of cache memory use...
[ "def", "_cache", "(", "self", ",", "func", ",", "func_memory_level", "=", "1", ",", "*", "*", "kwargs", ")", ":", "verbose", "=", "getattr", "(", "self", ",", "'verbose'", ",", "0", ")", "# Creates attributes if they don't exist", "# This is to make creating the...
40.72
0.000959
def get_features_from_equation_file(filename): """ returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature ...
[ "def", "get_features_from_equation_file", "(", "filename", ")", ":", "features", "=", "[", "]", "for", "line", "in", "open", "(", "filename", ")", ":", "line", "=", "line", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "strip", "(", ")", "if", ...
21.666667
0.001842
def convert_sklearn_metric_function(scoring): """If ``scoring`` is a sklearn metric function, convert it to a sklearn scorer and return it. Otherwise, return ``scoring`` unchanged.""" if callable(scoring): module = getattr(scoring, '__module__', None) if ( hasattr(module, 'st...
[ "def", "convert_sklearn_metric_function", "(", "scoring", ")", ":", "if", "callable", "(", "scoring", ")", ":", "module", "=", "getattr", "(", "scoring", ",", "'__module__'", ",", "None", ")", "if", "(", "hasattr", "(", "module", ",", "'startswith'", ")", ...
44.769231
0.001684
def import_pipeline(url, pipeline_id, auth, json_payload, verify_ssl, overwrite = False): """Import a pipeline. This will completely overwrite the existing pipeline. Args: url (str): the host url in the form 'http://host:port/'. pipeline_id (str): the ID of of the exported pipel...
[ "def", "import_pipeline", "(", "url", ",", "pipeline_id", ",", "auth", ",", "json_payload", ",", "verify_ssl", ",", "overwrite", "=", "False", ")", ":", "parameters", "=", "{", "'overwrite'", ":", "overwrite", "}", "import_result", "=", "requests", ".", "pos...
39.814815
0.008174
def select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None): ''' Support these keywords where, values, orderby, limit and columns''' query = self.schema.query_builder.build_select(table, where, orderby, limit, columns) return table.to_table(self.execute(query,...
[ "def", "select_record", "(", "self", ",", "table", ",", "where", "=", "None", ",", "values", "=", "None", ",", "orderby", "=", "None", ",", "limit", "=", "None", ",", "columns", "=", "None", ")", ":", "query", "=", "self", ".", "schema", ".", "quer...
85.75
0.011561
def zadd(self, key, score, member, mode, client=None): """ Like ZADD, but supports different score update modes, in case the member already exists in the ZSET: - "nx": Don't update the score - "xx": Only update elements that already exist. Never add elements. - "min": Use...
[ "def", "zadd", "(", "self", ",", "key", ",", "score", ",", "member", ",", "mode", ",", "client", "=", "None", ")", ":", "if", "mode", "==", "'nx'", ":", "f", "=", "self", ".", "_zadd_noupdate", "elif", "mode", "==", "'xx'", ":", "f", "=", "self",...
41.7
0.002345
def grep_iter(target, pattern, **kwargs): """ Main grep function, as a memory efficient iterator. Note: this function does not support the 'quiet' or 'count' flags. :param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler. :param pattern: Gre...
[ "def", "grep_iter", "(", "target", ",", "pattern", ",", "*", "*", "kwargs", ")", ":", "# unify flags (convert shortcuts to full name)", "__fix_args", "(", "kwargs", ")", "# parse the params that are relevant to this function", "f_offset", "=", "kwargs", ".", "get", "(",...
34.4
0.002211
def add_user(self, user_obj): """Add a user object to the database Args: user_obj(scout.models.User): A dictionary with user information Returns: user_info(dict): a copy of what was inserted """ LOG.info("Adding user %s to the dat...
[ "def", "add_user", "(", "self", ",", "user_obj", ")", ":", "LOG", ".", "info", "(", "\"Adding user %s to the database\"", ",", "user_obj", "[", "'email'", "]", ")", "if", "not", "'_id'", "in", "user_obj", ":", "user_obj", "[", "'_id'", "]", "=", "user_obj"...
34.15
0.008547
def do_windowed(self, line): """ Un-fullscreen the current window """ self.bot.canvas.sink.trigger_fullscreen_action(False) print(self.response_prompt, file=self.stdout)
[ "def", "do_windowed", "(", "self", ",", "line", ")", ":", "self", ".", "bot", ".", "canvas", ".", "sink", ".", "trigger_fullscreen_action", "(", "False", ")", "print", "(", "self", ".", "response_prompt", ",", "file", "=", "self", ".", "stdout", ")" ]
34
0.009569
def get_model(token_num, embed_dim, encoder_num, decoder_num, head_num, hidden_dim, attention_activation=None, feed_forward_activation='relu', dropout_rate=0.0, use_same_embed=True, ...
[ "def", "get_model", "(", "token_num", ",", "embed_dim", ",", "encoder_num", ",", "decoder_num", ",", "head_num", ",", "hidden_dim", ",", "attention_activation", "=", "None", ",", "feed_forward_activation", "=", "'relu'", ",", "dropout_rate", "=", "0.0", ",", "us...
40.643478
0.001253
def mount(directory, lower_dir, upper_dir, mount_table=None): """Creates a mount""" return OverlayFS.mount(directory, lower_dir, upper_dir, mount_table=mount_table)
[ "def", "mount", "(", "directory", ",", "lower_dir", ",", "upper_dir", ",", "mount_table", "=", "None", ")", ":", "return", "OverlayFS", ".", "mount", "(", "directory", ",", "lower_dir", ",", "upper_dir", ",", "mount_table", "=", "mount_table", ")" ]
45.25
0.01087
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu' raw_devic...
[ "def", "call_for_each_tower", "(", "self", ",", "tower_fn", ")", ":", "ps_device", "=", "'cpu'", "if", "len", "(", "self", ".", "towers", ")", ">=", "4", "else", "'gpu'", "raw_devices", "=", "[", "'/gpu:{}'", ".", "format", "(", "k", ")", "for", "k", ...
41.588235
0.008299
def Bond(rhol, rhog, sigma, L): r'''Calculates Bond number, `Bo` also known as Eotvos number, for a fluid with the given liquid and gas densities, surface tension, and geometric parameter (usually length). .. math:: Bo = \frac{g(\rho_l-\rho_g)L^2}{\sigma} Parameters ---------- rhol...
[ "def", "Bond", "(", "rhol", ",", "rhog", ",", "sigma", ",", "L", ")", ":", "return", "(", "g", "*", "(", "rhol", "-", "rhog", ")", "*", "L", "**", "2", "/", "sigma", ")" ]
23.885714
0.001149
def extract_metric_name(self, metric_name): """ Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that the section name will contain the SAR types listed in self.supported_sar_types tuple :param str metric_name: Section name from the config :return...
[ "def", "extract_metric_name", "(", "self", ",", "metric_name", ")", ":", "for", "metric_type", "in", "self", ".", "supported_sar_types", ":", "if", "metric_type", "in", "metric_name", ":", "return", "metric_type", "logger", ".", "error", "(", "'Section [%s] does n...
54.214286
0.009067
def nameop_set_collided( cls, nameop, history_id_key, history_id ): """ Mark a nameop as collided """ nameop['__collided__'] = True nameop['__collided_history_id_key__'] = history_id_key nameop['__collided_history_id__'] = history_id
[ "def", "nameop_set_collided", "(", "cls", ",", "nameop", ",", "history_id_key", ",", "history_id", ")", ":", "nameop", "[", "'__collided__'", "]", "=", "True", "nameop", "[", "'__collided_history_id_key__'", "]", "=", "history_id_key", "nameop", "[", "'__collided_...
39.428571
0.01773
def input_text_with_keyboard_emulation(self, text): """ Works around the problem of emulating user interactions with text inputs. Emulates a key-down action on the first char of the input. This way, implementations which require key-down event to trigger auto-suggest are test...
[ "def", "input_text_with_keyboard_emulation", "(", "self", ",", "text", ")", ":", "ActionChains", "(", "self", ".", "driver", ")", ".", "key_down", "(", "text", ")", ".", "key_up", "(", "Keys", ".", "CONTROL", ")", ".", "perform", "(", ")" ]
60.875
0.008097
def launch_command(command, parameter=''): '''Can launch a cozy-monitor command :param command: The cozy-monitor command to launch :param parameter: The parameter to push on cozy-monitor if needed :returns: the command string ''' result = '' # Transform into an array if it not one if n...
[ "def", "launch_command", "(", "command", ",", "parameter", "=", "''", ")", ":", "result", "=", "''", "# Transform into an array if it not one", "if", "not", "isinstance", "(", "parameter", ",", "list", ")", ":", "parameter", "=", "[", "parameter", "]", "# Iter...
35.842105
0.001431
def record(self): # type: () -> bytes ''' A method to generate the string representing this UDF NSR Volume Structure. Parameters: None. Returns: A string representing this UDF BEA Volume Strucutre. ''' if not self._initialized: ...
[ "def", "record", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'UDF NSR Volume Structure not initialized'", ")", "return", "struct", ".", "pack", "(", "sel...
34.071429
0.008163
def get_free_memory(): """Return current free memory on the machine. Currently supported for Windows, Linux, MacOS. :returns: Free memory in MB unit :rtype: int """ if 'win32' in sys.platform: # windows return get_free_memory_win() elif 'linux' in sys.platform: # li...
[ "def", "get_free_memory", "(", ")", ":", "if", "'win32'", "in", "sys", ".", "platform", ":", "# windows", "return", "get_free_memory_win", "(", ")", "elif", "'linux'", "in", "sys", ".", "platform", ":", "# linux", "return", "get_free_memory_linux", "(", ")", ...
25.411765
0.002232
def url_name_for_action(self, action): """ Returns the reverse name for this action """ return "%s.%s_%s" % (self.module_name.lower(), self.model_name.lower(), action)
[ "def", "url_name_for_action", "(", "self", ",", "action", ")", ":", "return", "\"%s.%s_%s\"", "%", "(", "self", ".", "module_name", ".", "lower", "(", ")", ",", "self", ".", "model_name", ".", "lower", "(", ")", ",", "action", ")" ]
39
0.015075
def main(): """ command line script """ # boilerplate print("Ontospy " + ontospy.VERSION) ontospy.get_or_create_home_repo() ONTOSPY_LOCAL_MODELS = ontospy.get_home_location() opts, args = parse_options() sTime = time.time() # switch dir and start server startServer(port=DEFAULT_PORT, location=ONTOSPY_LOCAL_M...
[ "def", "main", "(", ")", ":", "# boilerplate", "print", "(", "\"Ontospy \"", "+", "ontospy", ".", "VERSION", ")", "ontospy", ".", "get_or_create_home_repo", "(", ")", "ONTOSPY_LOCAL_MODELS", "=", "ontospy", ".", "get_home_location", "(", ")", "opts", ",", "arg...
23.736842
0.036247
def is_import(self): """Whether the stage file was created with `dvc import`.""" return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1
[ "def", "is_import", "(", "self", ")", ":", "return", "not", "self", ".", "cmd", "and", "len", "(", "self", ".", "deps", ")", "==", "1", "and", "len", "(", "self", ".", "outs", ")", "==", "1" ]
54
0.012195
def get_person_usage(person, project, start, end): """Return a tuple of cpu hours and number of jobs for a person in a specific project Keyword arguments: person -- project -- The project the usage is from start -- start date end -- end date """ try: cache = PersonCache.obje...
[ "def", "get_person_usage", "(", "person", ",", "project", ",", "start", ",", "end", ")", ":", "try", ":", "cache", "=", "PersonCache", ".", "objects", ".", "get", "(", "person", "=", "person", ",", "project", "=", "project", ",", "date", "=", "datetime...
30.588235
0.001866
def _normalize_module(module, depth=2): """ Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. ...
[ "def", "_normalize_module", "(", "module", ",", "depth", "=", "2", ")", ":", "if", "inspect", ".", "ismodule", "(", "module", ")", ":", "return", "module", "elif", "isinstance", "(", "module", ",", "(", "str", ",", "unicode", ")", ")", ":", "return", ...
41.888889
0.001297
def execute_builtin_action(self, p_action_str, p_size=None): """ Executes built-in action specified in p_action_str. Currently supported actions are: 'up', 'down', 'home', 'end', 'first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit...
[ "def", "execute_builtin_action", "(", "self", ",", "p_action_str", ",", "p_size", "=", "None", ")", ":", "column_actions", "=", "[", "'first_column'", ",", "'last_column'", ",", "'prev_column'", ",", "'next_column'", ",", "'append_column'", ",", "'insert_column'", ...
39.97619
0.001163
def set_value(ctx, key, value): """Assigns values to config file entries. If the value is omitted, you will be prompted, with the input hidden if it is sensitive. \b $ ddev config set github.user foo New setting: [github] user = "foo" """ scrubbing = False if value is None: ...
[ "def", "set_value", "(", "ctx", ",", "key", ",", "value", ")", ":", "scrubbing", "=", "False", "if", "value", "is", "None", ":", "scrubbing", "=", "key", "in", "SECRET_KEYS", "value", "=", "click", ".", "prompt", "(", "'Value for `{}`'", ".", "format", ...
28.396226
0.001927
def _setup_metrics(self): """ Start metric exposition """ path = os.environ.get("prometheus_multiproc_dir") if not os.path.exists(self.metrics_dir): try: log.info("Creating metrics directory") os.makedirs(self.metrics_dir) e...
[ "def", "_setup_metrics", "(", "self", ")", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "\"prometheus_multiproc_dir\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "metrics_dir", ")", ":", "try", ":", "log", ".", ...
39.580645
0.002387
def _update_secrets(self): '''update secrets will take a secrets credential file either located at .sregistry or the environment variable SREGISTRY_CLIENT_SECRETS and update the current client secrets as well as the associated API base. For the case of using Docker H...
[ "def", "_update_secrets", "(", "self", ")", ":", "# If the user has defined secrets, use them", "credentials", "=", "self", ".", "_get_setting", "(", "'SREGISTRY_DOCKERHUB_SECRETS'", ")", "# First try for SINGULARITY exported, then try sregistry", "username", "=", "self", ".", ...
44.422222
0.002447
def activate(self, uid=None): """ Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNo...
[ "def", "activate", "(", "self", ",", "uid", "=", "None", ")", ":", "# Check input", "if", "uid", "is", "not", "None", ":", "if", "not", "isinstance", "(", "uid", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"uid must be a strin...
33.419355
0.001876
def parent(): """Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.e...
[ "def", "parent", "(", ")", ":", "if", "self", ".", "_parent", ":", "return", "self", ".", "_parent", "if", "\"BE_SHELL\"", "in", "os", ".", "environ", ":", "self", ".", "_parent", "=", "os", ".", "environ", "[", "\"BE_SHELL\"", "]", "else", ":", "# I...
32.688889
0.00066
def cluster_DBSCAN(data, eps=None, min_samples=None, n_clusters=None, maxiter=200, **kwargs): """ Identify clusters using DBSCAN algorithm. Parameters ---------- data : array_like array of size [n_samples, n_features]. eps : float The minimum 'distance' points...
[ "def", "cluster_DBSCAN", "(", "data", ",", "eps", "=", "None", ",", "min_samples", "=", "None", ",", "n_clusters", "=", "None", ",", "maxiter", "=", "200", ",", "*", "*", "kwargs", ")", ":", "if", "n_clusters", "is", "None", ":", "if", "eps", "is", ...
39.333333
0.001879
def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example: .. code-block:: bash salt '*' nfs.list_exports ''' ret = {} with salt.utils.files.fopen(exports, 'r') as efl: for line in salt.utils.stringutils.to_unicode(efl.read()).splitlines(): ...
[ "def", "list_exports", "(", "exports", "=", "'/etc/exports'", ")", ":", "ret", "=", "{", "}", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "exports", ",", "'r'", ")", "as", "efl", ":", "for", "line", "in", "salt", ".", "utils", "....
33.102564
0.000752
def load_orthologs(fo: IO, metadata: dict): """Load orthologs into ArangoDB Args: fo: file obj - orthologs file metadata: dict containing the metadata for orthologs """ version = metadata["metadata"]["version"] # LOAD ORTHOLOGS INTO ArangoDB with timy.Timer("Load Orthologs") a...
[ "def", "load_orthologs", "(", "fo", ":", "IO", ",", "metadata", ":", "dict", ")", ":", "version", "=", "metadata", "[", "\"metadata\"", "]", "[", "\"version\"", "]", "# LOAD ORTHOLOGS INTO ArangoDB", "with", "timy", ".", "Timer", "(", "\"Load Orthologs\"", ")"...
35.869565
0.00059
def video_load_time(self): """ Returns aggregate video load time for all pages. """ load_times = self.get_load_times('video') return round(mean(load_times), self.decimal_precision)
[ "def", "video_load_time", "(", "self", ")", ":", "load_times", "=", "self", ".", "get_load_times", "(", "'video'", ")", "return", "round", "(", "mean", "(", "load_times", ")", ",", "self", ".", "decimal_precision", ")" ]
35.833333
0.009091
def copyDoc(self, recursive): """Do a copy of the document info. If recursive, the content tree will be copied too as well as DTD, namespaces and entities. """ ret = libxml2mod.xmlCopyDoc(self._o, recursive) if ret is None:raise treeError('xmlCopyDoc() failed') __tmp...
[ "def", "copyDoc", "(", "self", ",", "recursive", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCopyDoc", "(", "self", ".", "_o", ",", "recursive", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlCopyDoc() failed'", ")", "__tmp", "=", ...
44.125
0.011111
async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent ...
[ "async", "def", "_auth_cram_md5", "(", "self", ",", "username", ",", "password", ")", ":", "mechanism", "=", "\"CRAM-MD5\"", "code", ",", "message", "=", "await", "self", ".", "do_cmd", "(", "\"AUTH\"", ",", "mechanism", ",", "success", "=", "(", "334", ...
37.735849
0.001949
def zoom(image, factor, dimension, hdr = False, order = 3): """ Zooms the provided image by the supplied factor in the supplied dimension. The factor is an integer determining how many slices should be put between each existing pair. If an image header (hdr) is supplied, its voxel spacing gets updat...
[ "def", "zoom", "(", "image", ",", "factor", ",", "dimension", ",", "hdr", "=", "False", ",", "order", "=", "3", ")", ":", "# check if supplied dimension is valid", "if", "dimension", ">=", "image", ".", "ndim", ":", "raise", "argparse", ".", "ArgumentError",...
43.46875
0.009142
def full_path_from_dirrecord(self, rec, rockridge=False): # type: (Union[dr.DirectoryRecord, udfmod.UDFFileEntry], bool) -> str ''' A method to get the absolute path of a directory record. Parameters: rec - The directory record to get the full path for. rockridge - Whe...
[ "def", "full_path_from_dirrecord", "(", "self", ",", "rec", ",", "rockridge", "=", "False", ")", ":", "# type: (Union[dr.DirectoryRecord, udfmod.UDFFileEntry], bool) -> str", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInvalidI...
40.568966
0.00249
def search(self, conn, filters, order_by, offset=None, count=None, timeout=None): ''' Search for model ids that match the provided filters. Arguments: * *filters* - A list of filters that apply to the search of one of the following two forms: 1. ``'co...
[ "def", "search", "(", "self", ",", "conn", ",", "filters", ",", "order_by", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "timeout", "=", "None", ")", ":", "# prepare the filters", "pipe", ",", "intersect", ",", "temp_id", "=", "self", "....
42.710145
0.001658
def battery(self): """ Current system batter status (:py:class:`Battery`). """ if self._voltage is None or self._current is None or self._level is None: return None return Battery(self._voltage, self._current, self._level)
[ "def", "battery", "(", "self", ")", ":", "if", "self", ".", "_voltage", "is", "None", "or", "self", ".", "_current", "is", "None", "or", "self", ".", "_level", "is", "None", ":", "return", "None", "return", "Battery", "(", "self", ".", "_voltage", ",...
38.285714
0.010949
def Size(self): """ Get the total size in bytes of the object. Returns: int: size. """ return s.uint8 + s.uint8 + GetVarSize(self.Attributes) + GetVarSize(self.inputs) + GetVarSize(self.outputs) + GetVarSize(self.Scripts)
[ "def", "Size", "(", "self", ")", ":", "return", "s", ".", "uint8", "+", "s", ".", "uint8", "+", "GetVarSize", "(", "self", ".", "Attributes", ")", "+", "GetVarSize", "(", "self", ".", "inputs", ")", "+", "GetVarSize", "(", "self", ".", "outputs", "...
33.375
0.010949
def prime_factors(n): """Lists prime factors of a given natural integer, from greatest to smallest :param n: Natural integer :rtype : list of all prime factors of the given natural n """ i = 2 while i <= sqrt(n): if n % i == 0: l = prime_factors(n/i) l.append(i) ...
[ "def", "prime_factors", "(", "n", ")", ":", "i", "=", "2", "while", "i", "<=", "sqrt", "(", "n", ")", ":", "if", "n", "%", "i", "==", "0", ":", "l", "=", "prime_factors", "(", "n", "/", "i", ")", "l", ".", "append", "(", "i", ")", "return",...
27.461538
0.00813
def random_bits(bits_count): """ Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value. :param bits_count: random bits to generate :return: int """ bytes_count = int(math.ceil(bits_count / 8)) random_value = int.from_bytes(os.urandom(bytes_count), byteorder=sys.byteorder) result_bi...
[ "def", "random_bits", "(", "bits_count", ")", ":", "bytes_count", "=", "int", "(", "math", ".", "ceil", "(", "bits_count", "/", "8", ")", ")", "random_value", "=", "int", ".", "from_bytes", "(", "os", ".", "urandom", "(", "bytes_count", ")", ",", "byte...
31.571429
0.028571
def sign(self, payload): """ Sign payload using the supplied authenticator """ if self.authenticator: return self.authenticator.signed(payload) return payload
[ "def", "sign", "(", "self", ",", "payload", ")", ":", "if", "self", ".", "authenticator", ":", "return", "self", ".", "authenticator", ".", "signed", "(", "payload", ")", "return", "payload" ]
38
0.010309
def _load_key(key_object): """ Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid ...
[ "def", "_load_key", "(", "key_object", ")", ":", "if", "key_object", ".", "algorithm", "==", "'ec'", ":", "curve_type", ",", "details", "=", "key_object", ".", "curve", "if", "curve_type", "!=", "'named'", ":", "raise", "AsymmetricKeyError", "(", "'OS X only s...
35.651685
0.001533
def get_application_groups(): """ Return the applications of the system, organized in various groups. These groups are not connected with the application names, but rather with a pattern of applications. """ groups = [] for title, groupdict in appsettings.FLUENT_DASHBOARD_APP_GROUPS: ...
[ "def", "get_application_groups", "(", ")", ":", "groups", "=", "[", "]", "for", "title", ",", "groupdict", "in", "appsettings", ".", "FLUENT_DASHBOARD_APP_GROUPS", ":", "# Allow to pass all possible arguments to the DashboardModule class.", "module_kwargs", "=", "groupdict"...
38.172414
0.001762
def create(*context, **kwargs): """ Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain ContextStack instanc...
[ "def", "create", "(", "*", "context", ",", "*", "*", "kwargs", ")", ":", "items", "=", "context", "context", "=", "ContextStack", "(", ")", "for", "item", "in", "items", ":", "if", "item", "is", "None", ":", "continue", "if", "isinstance", "(", "item...
35.222222
0.002046
def request(self, method, path, **options): """ Dispatches a request to the Razorpay HTTP API """ options = self._update_user_agent_header(options) url = "{}{}".format(self.base_url, path) response = getattr(self.session, method)(url, auth=self.auth, ...
[ "def", "request", "(", "self", ",", "method", ",", "path", ",", "*", "*", "options", ")", ":", "options", "=", "self", ".", "_update_user_agent_header", "(", "options", ")", "url", "=", "\"{}{}\"", ".", "format", "(", "self", ".", "base_url", ",", "pat...
41.125
0.001485
def build_process_isolation_temp_dir(self): ''' Create a temporary directory for process isolation to use. ''' path = tempfile.mkdtemp(prefix='ansible_runner_pi_', dir=self.process_isolation_path) os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) atexit.register(...
[ "def", "build_process_isolation_temp_dir", "(", "self", ")", ":", "path", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'ansible_runner_pi_'", ",", "dir", "=", "self", ".", "process_isolation_path", ")", "os", ".", "chmod", "(", "path", ",", "stat", ...
44.125
0.008333
def compile(self): """ This compiles the alias into a form that can be of most benefit to the en/decoder. """ if self._compiled: return self.decodable_properties = set() self.encodable_properties = set() self.inherited_dynamic = None s...
[ "def", "compile", "(", "self", ")", ":", "if", "self", ".", "_compiled", ":", "return", "self", ".", "decodable_properties", "=", "set", "(", ")", "self", ".", "encodable_properties", "=", "set", "(", ")", "self", ".", "inherited_dynamic", "=", "None", "...
29.377358
0.001243
def mget(self, ids, index=None, doc_type=None, **query_params): """ Get multi JSON documents. ids can be: list of tuple: (index, type, id) list of ids: index and doc_type are required """ if not ids: return [] body = [] for va...
[ "def", "mget", "(", "self", ",", "ids", ",", "index", "=", "None", ",", "doc_type", "=", "None", ",", "*", "*", "query_params", ")", ":", "if", "not", "ids", ":", "return", "[", "]", "body", "=", "[", "]", "for", "value", "in", "ids", ":", "if"...
35.463415
0.001339
def create(self, service_name, json, **kwargs): """Create a new AppNexus object""" return self._send(requests.post, service_name, json, **kwargs)
[ "def", "create", "(", "self", ",", "service_name", ",", "json", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_send", "(", "requests", ".", "post", ",", "service_name", ",", "json", ",", "*", "*", "kwargs", ")" ]
53
0.012422
def parse(self, text, fn=None): """ Parse the Mapfile """ if PY2 and not isinstance(text, unicode): # specify Unicode for Python 2.7 text = unicode(text, 'utf-8') if self.expand_includes: text = self.load_includes(text, fn=fn) try: ...
[ "def", "parse", "(", "self", ",", "text", ",", "fn", "=", "None", ")", ":", "if", "PY2", "and", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "# specify Unicode for Python 2.7", "text", "=", "unicode", "(", "text", ",", "'utf-8'", ")", "i...
31.8
0.002442
def active_user_organisations_resource(doc): """Get user.organisations subresouces""" if doc.get('type') == 'user' and doc.get('state') != 'deactivated': for org_id, resource in doc.get('organisations', {}).items(): if resource['state'] != 'deactivated': resource['id'] = org_...
[ "def", "active_user_organisations_resource", "(", "doc", ")", ":", "if", "doc", ".", "get", "(", "'type'", ")", "==", "'user'", "and", "doc", ".", "get", "(", "'state'", ")", "!=", "'deactivated'", ":", "for", "org_id", ",", "resource", "in", "doc", ".",...
52.125
0.002358
def POST(self, name): """ /models/{name}/run schema: { predictedFieldName: value timestamp: %m/%d/%y %H:%M } NOTE: predictedFieldName MUST be the same name specified when creating the model. returns: { "predictionNumber":<number of record>, ...
[ "def", "POST", "(", "self", ",", "name", ")", ":", "global", "g_models", "data", "=", "json", ".", "loads", "(", "web", ".", "data", "(", ")", ")", "data", "[", "\"timestamp\"", "]", "=", "datetime", ".", "datetime", ".", "strptime", "(", "data", "...
26.090909
0.00224
def fetch_object(self, obj_name, include_meta=False, chunk_size=None): """ Alias for self.fetch(); included for backwards compatibility """ return self.fetch(obj=obj_name, include_meta=include_meta, chunk_size=chunk_size)
[ "def", "fetch_object", "(", "self", ",", "obj_name", ",", "include_meta", "=", "False", ",", "chunk_size", "=", "None", ")", ":", "return", "self", ".", "fetch", "(", "obj", "=", "obj_name", ",", "include_meta", "=", "include_meta", ",", "chunk_size", "=",...
44
0.011152
def validate_filepath(file_path, platform=None, min_len=1, max_len=None): """Verifying whether the ``file_path`` is a valid file path or not. Args: file_path (str): File path to validate. platform (str, optional): .. include:: platform.txt min_len (int, optional)...
[ "def", "validate_filepath", "(", "file_path", ",", "platform", "=", "None", ",", "min_len", "=", "1", ",", "max_len", "=", "None", ")", ":", "FilePathSanitizer", "(", "platform", "=", "platform", ",", "min_len", "=", "min_len", ",", "max_len", "=", "max_le...
36.948718
0.002028
def distant_level(reference_level, distance, reference_distance=1.0): """ Calculates the sound pressure level in dependence of a distance where a perfect ball-shaped source and spread is assumed. reference_level: Sound pressure level in reference distance in dB distance: Distance to calculate s...
[ "def", "distant_level", "(", "reference_level", ",", "distance", ",", "reference_distance", "=", "1.0", ")", ":", "rel_dist", "=", "float", "(", "reference_distance", ")", "/", "float", "(", "distance", ")", "level", "=", "float", "(", "reference_level", ")", ...
44.230769
0.001704
def require_session(handler): """ Decorator to ensure a session is properly in the request """ @functools.wraps(handler) async def decorated(request: web.Request) -> web.Response: request_session_token = request.match_info['session'] session = session_from_request(request) if not ses...
[ "def", "require_session", "(", "handler", ")", ":", "@", "functools", ".", "wraps", "(", "handler", ")", "async", "def", "decorated", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "request_session_token", "=", "request...
49.285714
0.001422
def has_all_nonzero_section_lengths(neuron, threshold=0.0): '''Check presence of neuron sections with length not above threshold Arguments: neuron(Neuron): The neuron object to test threshold(float): value above which a section length is considered to be non-zero Returns: C...
[ "def", "has_all_nonzero_section_lengths", "(", "neuron", ",", "threshold", "=", "0.0", ")", ":", "bad_ids", "=", "[", "s", ".", "id", "for", "s", "in", "_nf", ".", "iter_sections", "(", "neuron", ".", "neurites", ")", "if", "section_length", "(", "s", "....
36.466667
0.001783
def copy(src, trg, transform=None): ''' copy items with optional fields transformation ''' source = open(src[0], src[1]) target = open(trg[0], trg[1], autocommit=1000) for item in source.get(): item = dict(item) if '_id' in item: del item['_id'] if transform: ...
[ "def", "copy", "(", "src", ",", "trg", ",", "transform", "=", "None", ")", ":", "source", "=", "open", "(", "src", "[", "0", "]", ",", "src", "[", "1", "]", ")", "target", "=", "open", "(", "trg", "[", "0", "]", ",", "trg", "[", "1", "]", ...
23.722222
0.002252
def Range(start, limit, delta): """ Range op. """ return np.arange(start, limit, delta, dtype=np.int32),
[ "def", "Range", "(", "start", ",", "limit", ",", "delta", ")", ":", "return", "np", ".", "arange", "(", "start", ",", "limit", ",", "delta", ",", "dtype", "=", "np", ".", "int32", ")", "," ]
23.2
0.008333
def _restart_on_unavailable(restart): """Restart iteration after :exc:`.ServiceUnavailable`. :type restart: callable :param restart: curried function returning iterator """ resume_token = b"" item_buffer = [] iterator = restart() while True: try: for item in iterator...
[ "def", "_restart_on_unavailable", "(", "restart", ")", ":", "resume_token", "=", "b\"\"", "item_buffer", "=", "[", "]", "iterator", "=", "restart", "(", ")", "while", "True", ":", "try", ":", "for", "item", "in", "iterator", ":", "item_buffer", ".", "appen...
26.25
0.001312