text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def word_wrap(self): """ Read-write setting determining whether lines of text in this shape are wrapped to fit within the shape's width. Valid values are True, False, or None. True and False turn word wrap on and off, respectively. Assigning None to word wrap causes any word wrap...
[ "def", "word_wrap", "(", "self", ")", ":", "return", "{", "ST_TextWrappingType", ".", "SQUARE", ":", "True", ",", "ST_TextWrappingType", ".", "NONE", ":", "False", ",", "None", ":", "None", "}", "[", "self", ".", "_txBody", ".", "bodyPr", ".", "wrap", ...
45
16.142857
def set_params(self, arg_params, aux_params): """Set parameter and aux values. Parameters ---------- arg_params : list of NDArray Source parameter arrays aux_params : list of NDArray Source aux arrays. """ for texec in self.execgrp.train_...
[ "def", "set_params", "(", "self", ",", "arg_params", ",", "aux_params", ")", ":", "for", "texec", "in", "self", ".", "execgrp", ".", "train_execs", ":", "texec", ".", "copy_params_from", "(", "arg_params", ",", "aux_params", ")" ]
28.692308
13.538462
def get_primary_command_usage(message=''): # type: (str) -> str """Return the usage string for the primary command.""" if not settings.merge_primary_command and None in settings.subcommands: return format_usage(settings.subcommands[None].__doc__) if not message: message = '\n{}\n'.format...
[ "def", "get_primary_command_usage", "(", "message", "=", "''", ")", ":", "# type: (str) -> str", "if", "not", "settings", ".", "merge_primary_command", "and", "None", "in", "settings", ".", "subcommands", ":", "return", "format_usage", "(", "settings", ".", "subco...
48.727273
16.727273
def _header_bytefmt_byteorder(geom_type, num_dims, big_endian, meta=None): """ Utility function to get the WKB header (endian byte + type header), byte format string, and byte order string. """ dim = _INT_TO_DIM_LABEL.get(num_dims) if dim is None: pass # TODO: raise type_byte_str =...
[ "def", "_header_bytefmt_byteorder", "(", "geom_type", ",", "num_dims", ",", "big_endian", ",", "meta", "=", "None", ")", ":", "dim", "=", "_INT_TO_DIM_LABEL", ".", "get", "(", "num_dims", ")", "if", "dim", "is", "None", ":", "pass", "# TODO: raise", "type_by...
27.473684
17.052632
def get_layer_groups(self): """ Return layers grouped """ return [ [self.policy_backbone, self.action_head], [self.value_backbone, [y for (x, y) in self.critic_head.named_parameters() if x.endswith('bias')]], # OpenAI regularizes only weight on the last layer. I'm jus...
[ "def", "get_layer_groups", "(", "self", ")", ":", "return", "[", "[", "self", ".", "policy_backbone", ",", "self", ".", "action_head", "]", ",", "[", "self", ".", "value_backbone", ",", "[", "y", "for", "(", "x", ",", "y", ")", "in", "self", ".", "...
54.125
31.5
def _build_doc(self): """ Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet ...
[ "def", "_build_doc", "(", "self", ")", ":", "from", "lxml", ".", "html", "import", "parse", ",", "fromstring", ",", "HTMLParser", "from", "lxml", ".", "etree", "import", "XMLSyntaxError", "parser", "=", "HTMLParser", "(", "recover", "=", "True", ",", "enco...
31.73913
18.434783
def search_evaluations(domain, **kwargs): """ domain: seattle, bothell, tacoma, pce_ap, pce_ol, pce_ielp, pce (case insensitive) args: year (required) term_name (required): Winter|Spring|Summer|Autumn curriculum_abbreviation course_number section_id student_id...
[ "def", "search_evaluations", "(", "domain", ",", "*", "*", "kwargs", ")", ":", "url", "=", "\"{}?{}\"", ".", "format", "(", "IAS_PREFIX", ",", "urlencode", "(", "kwargs", ")", ")", "data", "=", "get_resource", "(", "url", ",", "domain", ")", "evaluations...
29.4
14.6
def upload_file(self, simple_upload_url, chunked_upload_url, file_obj, chunk_size=CHUNK_SIZE, force_chunked=False, extra_data=None): """ Generic method to upload files to AmigoCloud. Can be used for different API endpoints. `file_obj` could be a fi...
[ "def", "upload_file", "(", "self", ",", "simple_upload_url", ",", "chunked_upload_url", ",", "file_obj", ",", "chunk_size", "=", "CHUNK_SIZE", ",", "force_chunked", "=", "False", ",", "extra_data", "=", "None", ")", ":", "if", "isinstance", "(", "file_obj", ",...
42.145161
18.435484
def to_bool(value): """ Convert a value to boolean :param value: the value to convert :type value: any type :return: a boolean value :rtype: a boolean """ if value is None: return None if isinstance(value, bool): return value elif isinstance(value, str): i...
[ "def", "to_bool", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "if", "value", "==", ...
23.176471
12.941176
def merge(self, other, reference_seq): '''Tries to merge this VcfRecord with other VcfRecord. Simple example (working in 0-based coords): ref = ACGT var1 = SNP at position 1, C->G var2 = SNP at position 3, T->A then this returns new variant, position=1, REF=CGT, ALT=GGA. ...
[ "def", "merge", "(", "self", ",", "other", ",", "reference_seq", ")", ":", "if", "self", ".", "CHROM", "!=", "other", ".", "CHROM", "or", "self", ".", "intersects", "(", "other", ")", "or", "len", "(", "self", ".", "ALT", ")", "!=", "1", "or", "l...
37.234043
19.234043
def update_institute(self, internal_id, sanger_recipient=None, coverage_cutoff=None, frequency_cutoff=None, display_name=None, remove_sanger=None, phenotype_groups=None, group_abbreviations=None, add_groups=None): """Update the information for an institute ...
[ "def", "update_institute", "(", "self", ",", "internal_id", ",", "sanger_recipient", "=", "None", ",", "coverage_cutoff", "=", "None", ",", "frequency_cutoff", "=", "None", ",", "display_name", "=", "None", ",", "remove_sanger", "=", "None", ",", "phenotype_grou...
43.98913
22.413043
def gets_service_instance_via_proxy(fn): ''' Decorator that connects to a target system (vCenter or ESXi host) using the proxy details and passes the connection (vim.ServiceInstance) to the decorated function. Supported proxies: esxi, esxcluster, esxdatacenter. Notes: 1. The decorated ...
[ "def", "gets_service_instance_via_proxy", "(", "fn", ")", ":", "fn_name", "=", "fn", ".", "__name__", "try", ":", "arg_names", ",", "args_name", ",", "kwargs_name", ",", "default_values", ",", "_", ",", "_", ",", "_", "=", "inspect", ".", "getfullargspec", ...
47.666667
20.935484
def store_item(self, item, item_type, key): """ Store a service response. :param item: The item as a :py:class:`oidcmsg.message.Message` subclass instance or a JSON document. :param item_type: The type of request or response :param key: The key under which the inform...
[ "def", "store_item", "(", "self", ",", "item", ",", "item_type", ",", "key", ")", ":", "try", ":", "_state", "=", "self", ".", "get_state", "(", "key", ")", "except", "KeyError", ":", "_state", "=", "State", "(", ")", "try", ":", "_state", "[", "it...
31.190476
16.333333
def close(self): """ Closes the lid""" self._geometry.lid_status = self._module.close() self._ctx.deck.recalculate_high_z() return self._geometry.lid_status
[ "def", "close", "(", "self", ")", ":", "self", ".", "_geometry", ".", "lid_status", "=", "self", ".", "_module", ".", "close", "(", ")", "self", ".", "_ctx", ".", "deck", ".", "recalculate_high_z", "(", ")", "return", "self", ".", "_geometry", ".", "...
36.8
8.6
def write_double(self, value, little_endian=True): """ Pack the value as a double and write 8 bytes to the stream. Args: value (number): the value to write to the stream. little_endian (bool): specify the endianness. (Default) Little endian. Returns: ...
[ "def", "write_double", "(", "self", ",", "value", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "pack", "(", "'%sd'", "%", "endian", ",", "va...
30.5625
19.8125
def solubility_parameter(self): r'''Solubility parameter of the chemical at its current temperature and pressure, in units of [Pa^0.5]. .. math:: \delta = \sqrt{\frac{\Delta H_{vap} - RT}{V_m}} Calculated based on enthalpy of vaporization and molar volume. Normally ...
[ "def", "solubility_parameter", "(", "self", ")", ":", "return", "solubility_parameter", "(", "T", "=", "self", ".", "T", ",", "Hvapm", "=", "self", ".", "Hvapm", ",", "Vml", "=", "self", ".", "Vml", ",", "Method", "=", "self", ".", "solubility_parameter_...
38.736842
24.315789
def _create_repo(line, filename): ''' Create repo ''' repo = {} if line.startswith('#'): repo['enabled'] = False line = line[1:] else: repo['enabled'] = True cols = salt.utils.args.shlex_split(line.strip()) repo['compressed'] = not cols[0] in 'src' repo['name'...
[ "def", "_create_repo", "(", "line", ",", "filename", ")", ":", "repo", "=", "{", "}", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "repo", "[", "'enabled'", "]", "=", "False", "line", "=", "line", "[", "1", ":", "]", "else", ":", "repo"...
26.444444
17.222222
def schedule_crawl_cli(spider_name, workflow_name, dont_force_crawl, kwarg): """Schedule a new crawl. Note: Currently the oaiharvesting is done on inspire side, before this, so it's not supported here yet. """ extra_kwargs = {} for extra_kwarg in kwarg: if '=' not in extra_k...
[ "def", "schedule_crawl_cli", "(", "spider_name", ",", "workflow_name", ",", "dont_force_crawl", ",", "kwarg", ")", ":", "extra_kwargs", "=", "{", "}", "for", "extra_kwarg", "in", "kwarg", ":", "if", "'='", "not", "in", "extra_kwarg", ":", "raise", "TypeError",...
30.722222
17.888889
def set_option(prs, keyword, required=False): """Set options of command line. Arguments: prs: parser object of argparse keyword: processing keyword required: True is required option (default is False) """ if keyword == 'server': prs.add_argument( '-s',...
[ "def", "set_option", "(", "prs", ",", "keyword", ",", "required", "=", "False", ")", ":", "if", "keyword", "==", "'server'", ":", "prs", ".", "add_argument", "(", "'-s'", ",", "dest", "=", "'server'", ",", "required", "=", "True", ",", "help", "=", "...
43.044776
20.089552
def _hyphenate(input, add_prefix=False): """Change underscores to hyphens so that object attributes can be easily tranlated to GPG option names. :param str input: The attribute to hyphenate. :param bool add_prefix: If True, add leading hyphens to the input. :rtype: str :return: The ``input`` wi...
[ "def", "_hyphenate", "(", "input", ",", "add_prefix", "=", "False", ")", ":", "ret", "=", "'--'", "if", "add_prefix", "else", "''", "ret", "+=", "input", ".", "replace", "(", "'_'", ",", "'-'", ")", "return", "ret" ]
36.583333
14
def start(self): """ Start the periodic runner """ if self._isRunning: return if self._cease.is_set(): self._cease.clear() # restart class Runner(threading.Thread): @classmethod def run(cls): nextRunAt = c...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "_isRunning", ":", "return", "if", "self", ".", "_cease", ".", "is_set", "(", ")", ":", "self", ".", "_cease", ".", "clear", "(", ")", "# restart", "class", "Runner", "(", "threading", ".", ...
27.37931
16.137931
def upload_batterystats(filename, username, password, bucket_name=BUCKET_NAME, bucket_desc=BUCKET_DESC): """ Works with CSVs generated by the Android app 'Battery Log' (https://play.google.com/store/apps/details?id=kr.hwangti.batterylog) """ zapi = pyzenobase.ZenobaseAPI(username, password) buc...
[ "def", "upload_batterystats", "(", "filename", ",", "username", ",", "password", ",", "bucket_name", "=", "BUCKET_NAME", ",", "bucket_desc", "=", "BUCKET_DESC", ")", ":", "zapi", "=", "pyzenobase", ".", "ZenobaseAPI", "(", "username", ",", "password", ")", "bu...
41.612903
25.419355
def display(self, img, title=None, colormap=None, style='image', subtitles=None, auto_contrast=False, contrast_level=None, **kws): """display image""" if title is not None: self.SetTitle(title) if subtitles is not None: self.subtitles = subtitles c...
[ "def", "display", "(", "self", ",", "img", ",", "title", "=", "None", ",", "colormap", "=", "None", ",", "style", "=", "'image'", ",", "subtitles", "=", "None", ",", "auto_contrast", "=", "False", ",", "contrast_level", "=", "None", ",", "*", "*", "k...
34.706667
15.226667
def register_action(*args, **kwarg): ''' Decorator for an action, the arguments order is not relevant, but it's best to use the same order as in the docopt for clarity. ''' def decorator(fun): KeywordArgumentParser._action_dict[frozenset(args)] = fun return fun return decorator
[ "def", "register_action", "(", "*", "args", ",", "*", "*", "kwarg", ")", ":", "def", "decorator", "(", "fun", ")", ":", "KeywordArgumentParser", ".", "_action_dict", "[", "frozenset", "(", "args", ")", "]", "=", "fun", "return", "fun", "return", "decorat...
34.444444
23.111111
def parse_excel(file_path: str, entrez_id_header, log_fold_change_header, adjusted_p_value_header, entrez_delimiter, base_mean_header=None) -> List[Gene]: """Read an excel file on differential expression values as Gene objects. :pa...
[ "def", "parse_excel", "(", "file_path", ":", "str", ",", "entrez_id_header", ",", "log_fold_change_header", ",", "adjusted_p_value_header", ",", "entrez_delimiter", ",", "base_mean_header", "=", "None", ")", "->", "List", "[", "Gene", "]", ":", "logger", ".", "i...
36.125
15.75
def patch_mock_desc(self, patch, *args, **kwarg): """ Context manager or decorator in order to patch a mock definition of service endpoint in a test. :param patch: Dictionary in order to update endpoint's mock definition :type patch: dict :param service_name: Name of ser...
[ "def", "patch_mock_desc", "(", "self", ",", "patch", ",", "*", "args", ",", "*", "*", "kwarg", ")", ":", "return", "PatchMockDescDefinition", "(", "patch", ",", "self", ",", "*", "args", ",", "*", "*", "kwarg", ")" ]
44.52381
24.142857
def add_mappings(self, defn: Definition, target: Dict) -> None: """ Process any mappings in defn, adding all of the mappings prefixes to the namespace map and add a link to the first mapping to the target @param defn: Class or Slot definition @param target: context target """ ...
[ "def", "add_mappings", "(", "self", ",", "defn", ":", "Definition", ",", "target", ":", "Dict", ")", "->", "None", ":", "self", ".", "add_id_prefixes", "(", "defn", ")", "for", "mapping", "in", "defn", ".", "mappings", ":", "if", "'://'", "in", "mappin...
44.823529
13.352941
def query_filter(query): """Translate a query-style string to a 'filter'. Query can be the following formats: Case Insensitive 'value' OR '*= value' Contains 'value*' OR '^= value' Begins with value '*value' OR '$= value' Ends with value '*value*' OR '_= value' Contains val...
[ "def", "query_filter", "(", "query", ")", ":", "try", ":", "return", "{", "'operation'", ":", "int", "(", "query", ")", "}", "except", "ValueError", ":", "pass", "if", "isinstance", "(", "query", ",", "string_types", ")", ":", "query", "=", "query", "....
30.093023
14.627907
def _add_dict_values(self, d1, d2): """ Merges the values of two dictionaries, which are expected to be dictionaries, e.g d1 = {'a': {'x': pqr}} d2 = {'a': {'y': lmn}, 'b': {'y': rst}} will return: {'a': {'x': pqr, 'y': lmn}, 'b': {'y': rst}}. Collisions of the keys of th...
[ "def", "_add_dict_values", "(", "self", ",", "d1", ",", "d2", ")", ":", "if", "d1", "is", "None", "and", "d2", "is", "None", ":", "return", "None", "d1", "=", "d1", "or", "{", "}", "d2", "=", "d2", "or", "{", "}", "added", "=", "{", "}", "for...
32.894737
20.684211
def validate_metadata(self, xml): """ Validates an XML SP Metadata. :param xml: Metadata's XML that will be validate :type xml: string :returns: The list of found errors :rtype: list """ assert isinstance(xml, compat.text_types) if len(xml) == ...
[ "def", "validate_metadata", "(", "self", ",", "xml", ")", ":", "assert", "isinstance", "(", "xml", ",", "compat", ".", "text_types", ")", "if", "len", "(", "xml", ")", "==", "0", ":", "raise", "Exception", "(", "'Empty string supplied as input'", ")", "err...
37.526316
26.473684
def add_unchecked(self, binsha, mode, name): """Add the given item to the tree, its correctness is assumed, which puts the caller into responsibility to assure the input is correct. For more information on the parameters, see ``add`` :param binsha: 20 byte binary sha""" self._cac...
[ "def", "add_unchecked", "(", "self", ",", "binsha", ",", "mode", ",", "name", ")", ":", "self", ".", "_cache", ".", "append", "(", "(", "binsha", ",", "mode", ",", "name", ")", ")" ]
57.666667
11
def integer_id(self): """Return the integer id in the last (kind, id) pair, if any. Returns: An integer id, or None if the key has a string id or is incomplete. """ id = self.id() if not isinstance(id, (int, long)): id = None return id
[ "def", "integer_id", "(", "self", ")", ":", "id", "=", "self", ".", "id", "(", ")", "if", "not", "isinstance", "(", "id", ",", "(", "int", ",", "long", ")", ")", ":", "id", "=", "None", "return", "id" ]
26.3
19.5
def _proxy_addr(self): """ Return proxy address to connect to as tuple object """ proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type) if not proxy_port: raise GeneralProxyError("Inv...
[ "def", "_proxy_addr", "(", "self", ")", ":", "proxy_type", ",", "proxy_addr", ",", "proxy_port", ",", "rdns", ",", "username", ",", "password", "=", "self", ".", "proxy", "proxy_port", "=", "proxy_port", "or", "DEFAULT_PORTS", ".", "get", "(", "proxy_type", ...
40.777778
15
def eval_from_json(json): """ Evaluates OBV from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float of OBV """ closes = poloniex.get_attribute(json, 'close') volumes = po...
[ "def", "eval_from_json", "(", "json", ")", ":", "closes", "=", "poloniex", ".", "get_attribute", "(", "json", ",", "'close'", ")", "volumes", "=", "poloniex", ".", "get_attribute", "(", "json", ",", "'volume'", ")", "obv", "=", "0", "for", "date", "in", ...
34.823529
19.411765
def ad_unif_fix(samples, pinf): """ Corrects the limiting distribution for a finite sample size. """ n = samples c = .01265 + .1757 / n if pinf < c: return (((.0037 / n + .00078) / n + .00006) / n) * g1(pinf / c) elif pinf < .8: return ((.01365 / n + .04213) / n) * g2((pinf -...
[ "def", "ad_unif_fix", "(", "samples", ",", "pinf", ")", ":", "n", "=", "samples", "c", "=", ".01265", "+", ".1757", "/", "n", "if", "pinf", "<", "c", ":", "return", "(", "(", "(", ".0037", "/", "n", "+", ".00078", ")", "/", "n", "+", ".00006", ...
30.166667
18.5
def is_repository_directory(cls, path): # type: (str) -> bool """ Return whether a directory path is a repository directory. """ logger.debug('Checking in %s for %s (%s)...', path, cls.dirname, cls.name) return os.path.exists(os.path.join(path, cls.di...
[ "def", "is_repository_directory", "(", "cls", ",", "path", ")", ":", "# type: (str) -> bool", "logger", ".", "debug", "(", "'Checking in %s for %s (%s)...'", ",", "path", ",", "cls", ".", "dirname", ",", "cls", ".", "name", ")", "return", "os", ".", "path", ...
40
10.25
def addr_info(addr): """ Interprets an address in standard tuple format to determine if it is valid, and, if so, which socket family it is. Returns the socket family. """ # If it's a string, it's in the UNIX family if isinstance(addr, basestring): return socket.AF_UNIX # Verif...
[ "def", "addr_info", "(", "addr", ")", ":", "# If it's a string, it's in the UNIX family", "if", "isinstance", "(", "addr", ",", "basestring", ")", ":", "return", "socket", ".", "AF_UNIX", "# Verify that addr is a tuple", "if", "not", "isinstance", "(", "addr", ",", ...
27.804348
19.108696
def system_find_projects(input_params={}, always_retry=True, **kwargs): """ Invokes the /system/findProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindProjects """ return DXHTTPRequest('/system/findProjects', input_params...
[ "def", "system_find_projects", "(", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/system/findProjects'", ",", "input_params", ",", "always_retry", "=", "always_retry", ",", ...
50.285714
31.142857
def size(col): """ Collection function: returns the length of the array or map stored in the column. :param col: name of column or expression >>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data']) >>> df.select(size(df.data)).collect() [Row(size(data)=3), Row(size(data)=1), Row(...
[ "def", "size", "(", "col", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "return", "Column", "(", "sc", ".", "_jvm", ".", "functions", ".", "size", "(", "_to_java_column", "(", "col", ")", ")", ")" ]
36.583333
19.75
def clear_to_reset(self, config_vars): """Clear all volatile information across a reset. The reset behavior is that: - uptime is reset to 0 - is `has_rtc` is True, the utc_offset is preserved - otherwise the utc_offset is cleared to none """ super(ClockManagerSu...
[ "def", "clear_to_reset", "(", "self", ",", "config_vars", ")", ":", "super", "(", "ClockManagerSubsystem", ",", "self", ")", ".", "clear_to_reset", "(", "config_vars", ")", "self", ".", "tick_counters", "=", "dict", "(", "fast", "=", "0", ",", "user1", "="...
33.666667
22.416667
def integrate(self, x, y0, params=(), atol=1e-8, rtol=1e-8, **kwargs): """ Integrate the system of ordinary differential equations. Solves the initial value problem (IVP). Parameters ---------- x : array_like or pair (start and final time) or float if float: ...
[ "def", "integrate", "(", "self", ",", "x", ",", "y0", ",", "params", "=", "(", ")", ",", "atol", "=", "1e-8", ",", "rtol", "=", "1e-8", ",", "*", "*", "kwargs", ")", ":", "arrs", "=", "self", ".", "to_arrays", "(", "x", ",", "y0", ",", "param...
41.631068
19.563107
def handle_request_parsing_error( err, _req, _schema, _err_status_code, _err_headers, ): """ This handles request parsing errors generated for example by schema field validation failing.""" abort(HTTPStatus.BAD_REQUEST, errors=err.messages)
[ "def", "handle_request_parsing_error", "(", "err", ",", "_req", ",", "_schema", ",", "_err_status_code", ",", "_err_headers", ",", ")", ":", "abort", "(", "HTTPStatus", ".", "BAD_REQUEST", ",", "errors", "=", "err", ".", "messages", ")" ]
28.3
17.2
def make_wcs_from_hpx(self, sum_ebins=False, proj='CAR', oversample=2, normalize=True): """Make a WCS object and convert HEALPix data into WCS projection NOTE: this re-calculates the mapping, if you have already calculated the mapping it is much faster to use c...
[ "def", "make_wcs_from_hpx", "(", "self", ",", "sum_ebins", "=", "False", ",", "proj", "=", "'CAR'", ",", "oversample", "=", "2", ",", "normalize", "=", "True", ")", ":", "self", ".", "_wcs_proj", "=", "proj", "self", ".", "_wcs_oversample", "=", "oversam...
35.40625
21.84375
def parent_callback(self, parent_fu): """Callback from executor future to update the parent. Args: - parent_fu (Future): Future returned by the executor along with callback Returns: - None Updates the super() with the result() or exception() """ ...
[ "def", "parent_callback", "(", "self", ",", "parent_fu", ")", ":", "if", "parent_fu", ".", "done", "(", ")", "is", "True", ":", "e", "=", "parent_fu", ".", "_exception", "if", "e", ":", "super", "(", ")", ".", "set_exception", "(", "e", ")", "else", ...
28.388889
19.444444
def reads(err_log): """ Parse the outputs from bbmerge to extract the total number of reads, as well as the number of reads that could be paired :param err_log: bbmerge outputs the stats in the error file :return: num_reads, the total number of reads, paired_reads, number of pair...
[ "def", "reads", "(", "err_log", ")", ":", "# Initialise variables", "num_reads", "=", "0", "paired_reads", "=", "0", "# Open the log file", "with", "open", "(", "err_log", ",", "'r'", ")", "as", "error_log", ":", "# Extract the necessary information", "for", "line...
42.157895
16.684211
def density_2d(self, x, y, Rs, rho0, center_x=0, center_y=0): """ projected two dimenstional NFW profile (kappa*Sigma_crit) :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (charact...
[ "def", "density_2d", "(", "self", ",", "x", ",", "y", ",", "Rs", ",", "rho0", ",", "center_x", "=", "0", ",", "center_y", "=", "0", ")", ":", "x_", "=", "x", "-", "center_x", "y_", "=", "y", "-", "center_y", "R", "=", "np", ".", "sqrt", "(", ...
31.9
14.2
def force_type(cls, response, environ=None): """Enforce that the WSGI response is a response object of the current type. Werkzeug will use the :class:`BaseResponse` internally in many situations like the exceptions. If you call :meth:`get_response` on an exception you will get back a r...
[ "def", "force_type", "(", "cls", ",", "response", ",", "environ", "=", "None", ")", ":", "if", "not", "isinstance", "(", "response", ",", "BaseResponse", ")", ":", "if", "environ", "is", "None", ":", "raise", "TypeError", "(", "\"cannot convert WSGI applicat...
44.297297
23.162162
def quietinterrupt(msg=None): """add a handler for SIGINT that optionally prints a given message. For stopping scripts without having to see the stacktrace. """ def handler(): if msg: print(msg, file=sys.stderr) sys.exit(1) signal.signal(signal.SIGINT, handler)
[ "def", "quietinterrupt", "(", "msg", "=", "None", ")", ":", "def", "handler", "(", ")", ":", "if", "msg", ":", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "signal", ".", "signal", "(", "s...
27.363636
16.636364
def handle_report_metric_data(self, data): """ data: a dict received from nni_manager, which contains: - 'parameter_id': id of the trial - 'value': metric value reported by nni.report_final_result() - 'type': report type, support {'FINAL', 'PERIODICAL'} ...
[ "def", "handle_report_metric_data", "(", "self", ",", "data", ")", ":", "if", "data", "[", "'type'", "]", "==", "'FINAL'", ":", "self", ".", "_handle_final_metric_data", "(", "data", ")", "elif", "data", "[", "'type'", "]", "==", "'PERIODICAL'", ":", "if",...
42
15
def init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """ global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickle', 'plain'] if init_type not in validate_init...
[ "def", "init", "(", "init_type", "=", "'plaintext_tcp'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "_module_instance", "reset", "(", ")", "validate_init_types", "=", "[", "'plaintext_tcp'", ",", "'plaintext'", ",", "'pickle_tcp'", ",", "...
35.36
20.88
def _deconstruct_single_qubit_matrix_into_gate_turns( mat: np.ndarray) -> Tuple[float, float, float]: """Breaks down a 2x2 unitary into gate parameters. Args: mat: The 2x2 unitary matrix to break down. Returns: A tuple containing the amount to rotate around an XY axis, the phase of ...
[ "def", "_deconstruct_single_qubit_matrix_into_gate_turns", "(", "mat", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "pre_phase", ",", "rotation", ",", "post_phase", "=", "(", "linalg", ".", "deconstruct_sin...
37.56
20.24
def tracedb(args): """ %prog tracedb <xml|lib|frg> Run `tracedb-to-frg.pl` within current folder. """ p = OptionParser(tracedb.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) action, = args assert action in ("xml", "lib", "frg") C...
[ "def", "tracedb", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "tracedb", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", ...
23.40625
19.40625
def get(self, id=None): """ 获取指定部门列表 https://work.weixin.qq.com/api/doc#90000/90135/90208 权限说明: 只能拉取token对应的应用的权限范围内的部门列表 :param id: 部门id。获取指定部门及其下的子部门。 如果不填,默认获取全量组织架构 :return: 部门列表 """ if id is None: res = self._get('department/lis...
[ "def", "get", "(", "self", ",", "id", "=", "None", ")", ":", "if", "id", "is", "None", ":", "res", "=", "self", ".", "_get", "(", "'department/list'", ")", "else", ":", "res", "=", "self", ".", "_get", "(", "'department/list'", ",", "params", "=", ...
24.705882
19.529412
def activated(self, value): """ Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value) ...
[ "def", "activated", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "bool", ",", "\"'{0}' attribute: '{1}' type is not 'bool'!\"", ".", "format", "(", "\"activated\"", ",", "value", ")"...
35.416667
21.75
def ASR_C(value, amount, width): """ The ARM ASR_C (arithmetic shift right with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value and carry result ...
[ "def", "ASR_C", "(", "value", ",", "amount", ",", "width", ")", ":", "assert", "amount", "<=", "width", "assert", "amount", ">", "0", "assert", "amount", "+", "width", "<=", "width", "*", "2", "value", "=", "Operators", ".", "SEXTEND", "(", "value", ...
31.888889
10.777778
def id_source(source, full=False): """ Returns the name of a website-scrapping function. """ if source not in source_ids: return '' if full: return source_ids[source][1] else: return source_ids[source][0]
[ "def", "id_source", "(", "source", ",", "full", "=", "False", ")", ":", "if", "source", "not", "in", "source_ids", ":", "return", "''", "if", "full", ":", "return", "source_ids", "[", "source", "]", "[", "1", "]", "else", ":", "return", "source_ids", ...
22.090909
14.272727
def get_domain(self, domain_name): """ Return a Domain by its domain_name """ return Domain.get_object(api_token=self.token, domain_name=domain_name)
[ "def", "get_domain", "(", "self", ",", "domain_name", ")", ":", "return", "Domain", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "domain_name", "=", "domain_name", ")" ]
36.2
10.2
def scatter(df, x, y, ax=None, legend=None, title=None, color=None, marker='o', linestyle=None, cmap=None, groupby=['model', 'scenario'], with_lines=False, **kwargs): """Plot data as a scatter chart. Parameters ---------- df : pd.DataFrame Data to plot as a long-form dat...
[ "def", "scatter", "(", "df", ",", "x", ",", "y", ",", "ax", "=", "None", ",", "legend", "=", "None", ",", "title", "=", "None", ",", "color", "=", "None", ",", "marker", "=", "'o'", ",", "linestyle", "=", "None", ",", "cmap", "=", "None", ",", ...
34.56383
18.212766
def load_demonstration(file_path): """ Loads and parses a demonstration file. :param file_path: Location of demonstration file (.demo). :return: BrainParameter and list of BrainInfos containing demonstration data. """ # First 32 bytes of file dedicated to meta-data. INITIAL_POS = 33 if...
[ "def", "load_demonstration", "(", "file_path", ")", ":", "# First 32 bytes of file dedicated to meta-data.", "INITIAL_POS", "=", "33", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "raise", "FileNotFoundError", "(", "\"The demonstration fi...
40.704545
17.431818
def __get_connection_cloudwatch(): """ Ensure connection to CloudWatch """ region = get_global_option('region') try: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to CloudWatch usi...
[ "def", "__get_connection_cloudwatch", "(", ")", ":", "region", "=", "get_global_option", "(", "'region'", ")", "try", ":", "if", "(", "get_global_option", "(", "'aws_access_key_id'", ")", "and", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", ":", "...
39.785714
18.892857
def unpackb(packed, **kwargs): ''' .. versionadded:: 2018.3.4 Wraps msgpack.unpack. By default, this function uses the msgpack module and falls back to msgpack_pure, if the msgpack is not available. You can pass an alternate msgpack module using the _msgpack_module argument. ''' msgpac...
[ "def", "unpackb", "(", "packed", ",", "*", "*", "kwargs", ")", ":", "msgpack_module", "=", "kwargs", ".", "pop", "(", "'_msgpack_module'", ",", "msgpack", ")", "return", "msgpack_module", ".", "unpackb", "(", "packed", ",", "*", "*", "kwargs", ")" ]
34.166667
24.333333
async def get_ticket(self, request): """Called to return the ticket for a request. Args: request: aiohttp Request object. Returns: A ticket (string like) object, or None if no ticket is available for the passed request. """ session = await ge...
[ "async", "def", "get_ticket", "(", "self", ",", "request", ")", ":", "session", "=", "await", "get_session", "(", "request", ")", "return", "session", ".", "get", "(", "self", ".", "cookie_name", ")" ]
31
15.666667
def _nodeSetValuesFromDict(self, dct): """ Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict """ if 'choices' in dct: self._configValues = list(dct['choices']) self._displayValues = list(dct['choices']) ...
[ "def", "_nodeSetValuesFromDict", "(", "self", ",", "dct", ")", ":", "if", "'choices'", "in", "dct", ":", "self", ".", "_configValues", "=", "list", "(", "dct", "[", "'choices'", "]", ")", "self", ".", "_displayValues", "=", "list", "(", "dct", "[", "'c...
46.25
10.625
def iter_leaf_names(self, is_leaf_fn=None): """Returns an iterator over the leaf names under this node.""" for n in self.iter_leaves(is_leaf_fn=is_leaf_fn): yield n.name
[ "def", "iter_leaf_names", "(", "self", ",", "is_leaf_fn", "=", "None", ")", ":", "for", "n", "in", "self", ".", "iter_leaves", "(", "is_leaf_fn", "=", "is_leaf_fn", ")", ":", "yield", "n", ".", "name" ]
48.5
9
def cartesian_to_poincare_polar(w): r""" Convert an array of 6D Cartesian positions to Poincaré symplectic polar coordinates. These are similar to cylindrical coordinates. Parameters ---------- w : array_like Input array of 6D Cartesian phase-space positions. Should have sha...
[ "def", "cartesian_to_poincare_polar", "(", "w", ")", ":", "R", "=", "np", ".", "sqrt", "(", "w", "[", "...", ",", "0", "]", "**", "2", "+", "w", "[", "...", ",", "1", "]", "**", "2", ")", "# phi = np.arctan2(w[...,1], w[...,0])", "phi", "=", "np", ...
26.918919
19.216216
def clean(self): """Wrapper for calling the clean method of services attribute :return: None """ logger.debug("Cleaning configuration objects before configuration sending:") types_creations = self.__class__.types_creations for o_type in types_creations: (_, _...
[ "def", "clean", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Cleaning configuration objects before configuration sending:\"", ")", "types_creations", "=", "self", ".", "__class__", ".", "types_creations", "for", "o_type", "in", "types_creations", ":", "(", ...
42.083333
17.583333
def _output_validators(self): """Output common validator types based on usage.""" if self._walk_for_type('Boolean'): print("from .validators import boolean") if self._walk_for_type('Integer'): print("from .validators import integer") vlist = self.override.get_vali...
[ "def", "_output_validators", "(", "self", ")", ":", "if", "self", ".", "_walk_for_type", "(", "'Boolean'", ")", ":", "print", "(", "\"from .validators import boolean\"", ")", "if", "self", ".", "_walk_for_type", "(", "'Integer'", ")", ":", "print", "(", "\"fro...
45.071429
10.142857
def convert_deps_to_pip(deps, project=None, r=True, include_index=True): """"Converts a Pipfile-formatted dependency to a pip-formatted one.""" from .vendor.requirementslib.models.requirements import Requirement dependencies = [] for dep_name, dep in deps.items(): if project: projec...
[ "def", "convert_deps_to_pip", "(", "deps", ",", "project", "=", "None", ",", "r", "=", "True", ",", "include_index", "=", "True", ")", ":", "from", ".", "vendor", ".", "requirementslib", ".", "models", ".", "requirements", "import", "Requirement", "dependenc...
41.347826
21
def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement, price, consumer_address, condition_ids): """ Process the agreement events during the register of the service agreement for the publisher side :param publisher_account: Acco...
[ "def", "process_agreement_events_publisher", "(", "publisher_account", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "consumer_address", ",", "condition_ids", ")", ":", "conditions_dict", "=", "service_agreement", ".", "condition_by_name", ...
40.02381
21.452381
def compare_config(self, other=None, text=False): """ Compares running config with another config. This other config can be either the *running* config or a :class:`~pyFG.forticonfig.FortiConfig`. The result of the comparison will be how to reach\ the state represented in the target conf...
[ "def", "compare_config", "(", "self", ",", "other", "=", "None", ",", "text", "=", "False", ")", ":", "if", "other", "is", "None", ":", "other", "=", "self", ".", "candidate_config", "if", "not", "text", ":", "return", "self", ".", "running_config", "....
44.46875
28.78125
def dip_pval_tabinterpol(dip, N): ''' dip - dip value computed from dip_from_cdf N - number of observations ''' # if qDiptab_df is None: # raise DataError("Tabulated p-values not available. See installation instructions.") if np.isnan(N) or N < 10: return ...
[ "def", "dip_pval_tabinterpol", "(", "dip", ",", "N", ")", ":", "# if qDiptab_df is None:", "# raise DataError(\"Tabulated p-values not available. See installation instructions.\")", "if", "np", ".", "isnan", "(", "N", ")", "or", "N", "<", "10", ":", "return", "np", ...
29.940375
11.054514
def list_availability_zones(call=None): ''' List all availability zones in the current region ''' ret = {} params = {'Action': 'DescribeZones', 'RegionId': get_location()} items = query(params) for zone in items['Zones']['Zone']: ret[zone['ZoneId']] = {} for i...
[ "def", "list_availability_zones", "(", "call", "=", "None", ")", ":", "ret", "=", "{", "}", "params", "=", "{", "'Action'", ":", "'DescribeZones'", ",", "'RegionId'", ":", "get_location", "(", ")", "}", "items", "=", "query", "(", "params", ")", "for", ...
24.9375
19.9375
def _flat_vports(self, connection_port): """Flat the virtual ports.""" vports = [] for vport in connection_port.virtual_ports: self._set_child_props(connection_port, vport) vports.append(vport) return vports
[ "def", "_flat_vports", "(", "self", ",", "connection_port", ")", ":", "vports", "=", "[", "]", "for", "vport", "in", "connection_port", ".", "virtual_ports", ":", "self", ".", "_set_child_props", "(", "connection_port", ",", "vport", ")", "vports", ".", "app...
36.714286
10.857143
def tarjan_recursive(g): """ Returns the strongly connected components of the graph @g in a topological order. @g is the graph represented as a dictionary { <vertex> : <successors of vertex> }. This function recurses --- l...
[ "def", "tarjan_recursive", "(", "g", ")", ":", "S", "=", "[", "]", "S_set", "=", "set", "(", ")", "index", "=", "{", "}", "lowlink", "=", "{", "}", "ret", "=", "[", "]", "def", "visit", "(", "v", ")", ":", "index", "[", "v", "]", "=", "len"...
34.025641
14.076923
def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return u...
[ "def", "get_loginclass", "(", "name", ")", ":", "userinfo", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "[", "'pw'", ",", "'usershow'", ",", "'-n'", ",", "name", "]", ")", "userinfo", "=", "userinfo", ".", "split", "(", "':'", ")", "return", "u...
19.111111
26
def py_bisplev(x, y, tck, dx=0, dy=0): '''Evaluate a bivariate B-spline or its derivatives. For scalars, returns a float; for other inputs, mimics the formats of SciPy's `bisplev`. Parameters ---------- x : float or list[float] x value (rank 1), [-] y : float or list[float] ...
[ "def", "py_bisplev", "(", "x", ",", "y", ",", "tck", ",", "dx", "=", "0", ",", "dy", "=", "0", ")", ":", "tx", ",", "ty", ",", "c", ",", "kx", ",", "ky", "=", "tck", "if", "isinstance", "(", "x", ",", "(", "float", ",", "int", ")", ")", ...
30.625
21.575
def read(self, file, *, fs): """ Write a row on the next line of given file. Prefix is used for newlines. """ for line in file: yield line.rstrip(self.eol)
[ "def", "read", "(", "self", ",", "file", ",", "*", ",", "fs", ")", ":", "for", "line", "in", "file", ":", "yield", "line", ".", "rstrip", "(", "self", ".", "eol", ")" ]
28.714286
6.142857
def _determine_validator_type(self, data_type, value, has_default): """Returns validator string for given data type, else None.""" data_type, nullable = unwrap_nullable(data_type) validator = None if is_list_type(data_type): item_validator = self._determine_validator_type( ...
[ "def", "_determine_validator_type", "(", "self", ",", "data_type", ",", "value", ",", "has_default", ")", ":", "data_type", ",", "nullable", "=", "unwrap_nullable", "(", "data_type", ")", "validator", "=", "None", "if", "is_list_type", "(", "data_type", ")", "...
43.61039
16.337662
def apply_xy_shift(ds, dx, dy, createcopy=True): """ Apply horizontal shift to GDAL dataset GeoTransform Returns: GDAL Dataset copy with updated GeoTransform """ print("X shift: ", dx) print("Y shift: ", dy) #Update geotransform gt_orig = ds.GetGeoTransform() gt_shift = ...
[ "def", "apply_xy_shift", "(", "ds", ",", "dx", ",", "dy", ",", "createcopy", "=", "True", ")", ":", "print", "(", "\"X shift: \"", ",", "dx", ")", "print", "(", "\"Y shift: \"", ",", "dy", ")", "#Update geotransform", "gt_orig", "=", "ds", ".", "GetGeoTr...
25.888889
16.851852
def jupyter_notebook_skeleton(): """Returns a dictionary with the elements of a Jupyter notebook""" py_version = sys.version_info notebook_skeleton = { "cells": [], "metadata": { "kernelspec": { "display_name": "Python " + str(py_version[0]), "lang...
[ "def", "jupyter_notebook_skeleton", "(", ")", ":", "py_version", "=", "sys", ".", "version_info", "notebook_skeleton", "=", "{", "\"cells\"", ":", "[", "]", ",", "\"metadata\"", ":", "{", "\"kernelspec\"", ":", "{", "\"display_name\"", ":", "\"Python \"", "+", ...
34.464286
14.178571
def prov_key(job_msg, extra=None): """Retrieves a MD5 sum from a function call. This takes into account the name of the function, the arguments and possibly a version number of the function, if that is given in the hints. This version can also be auto-generated by generating an MD5 hash from the fun...
[ "def", "prov_key", "(", "job_msg", ",", "extra", "=", "None", ")", ":", "m", "=", "hashlib", ".", "md5", "(", ")", "update_object_hash", "(", "m", ",", "job_msg", "[", "'data'", "]", "[", "'function'", "]", ")", "update_object_hash", "(", "m", ",", "...
41.842105
20.052632
def GenerarAjusteFisico(self): "Generar Ajuste Físico de Liquidación de Tabaco Verde (WSLTVv1.3)" # renombrar la clave principal de la estructura if 'liquidacion' in self.solicitud: liq = self.solicitud.pop('liquidacion') self.solicitud = liq # l...
[ "def", "GenerarAjusteFisico", "(", "self", ")", ":", "# renombrar la clave principal de la estructura", "if", "'liquidacion'", "in", "self", ".", "solicitud", ":", "liq", "=", "self", ".", "solicitud", ".", "pop", "(", "'liquidacion'", ")", "self", ".", "solicitud...
37.818182
12.636364
def lt(computation: BaseComputation) -> None: """ Lesser Comparison """ left, right = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if left < right: result = 1 else: result = 0 computation.stack_push(result)
[ "def", "lt", "(", "computation", ":", "BaseComputation", ")", "->", "None", ":", "left", ",", "right", "=", "computation", ".", "stack_pop", "(", "num_items", "=", "2", ",", "type_hint", "=", "constants", ".", "UINT256", ")", "if", "left", "<", "right", ...
21.666667
20.5
def switch_axis_limits(ax, which_axis): ''' Switch the axis limits of either x or y. Or both! ''' for a in which_axis: assert a in ('x', 'y') ax_limits = ax.axis() if a == 'x': ax.set_xlim(ax_limits[1], ax_limits[0]) else: ax.set_ylim(ax_limits[3],...
[ "def", "switch_axis_limits", "(", "ax", ",", "which_axis", ")", ":", "for", "a", "in", "which_axis", ":", "assert", "a", "in", "(", "'x'", ",", "'y'", ")", "ax_limits", "=", "ax", ".", "axis", "(", ")", "if", "a", "==", "'x'", ":", "ax", ".", "se...
29.454545
16.909091
def fromJSON(value): """loads the GP object from a JSON string """ j = json.loads(value) v = GPLong() if "defaultValue" in j: v.value = j['defaultValue'] else: v.value = j['value'] if 'paramName' in j: v.paramName = j['paramName'] ...
[ "def", "fromJSON", "(", "value", ")", ":", "j", "=", "json", ".", "loads", "(", "value", ")", "v", "=", "GPLong", "(", ")", "if", "\"defaultValue\"", "in", "j", ":", "v", ".", "value", "=", "j", "[", "'defaultValue'", "]", "else", ":", "v", ".", ...
29.307692
11.692308
def strings(filename, minimum=4): ''' A strings generator, similar to the Unix strings utility. @filename - The file to search for strings in. @minimum - The minimum string length to search for. Yeilds printable ASCII strings from filename. ''' result = "" with BlockFile(filename) as...
[ "def", "strings", "(", "filename", ",", "minimum", "=", "4", ")", ":", "result", "=", "\"\"", "with", "BlockFile", "(", "filename", ")", "as", "f", ":", "while", "True", ":", "(", "data", ",", "dlen", ")", "=", "f", ".", "read_block", "(", ")", "...
27
17.769231
def linearize_metrics(logged_metrics): """ Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_...
[ "def", "linearize_metrics", "(", "logged_metrics", ")", ":", "metrics_by_name", "=", "{", "}", "for", "metric_entry", "in", "logged_metrics", ":", "if", "metric_entry", ".", "name", "not", "in", "metrics_by_name", ":", "metrics_by_name", "[", "metric_entry", ".", ...
36.586207
12.724138
def connect( self, host_or_hosts, port_or_ports=7051, rpc_timeout=None, admin_timeout=None, ): """ Pass-through connection interface to the Kudu client Parameters ---------- host_or_hosts : string or list of strings If you ha...
[ "def", "connect", "(", "self", ",", "host_or_hosts", ",", "port_or_ports", "=", "7051", ",", "rpc_timeout", "=", "None", ",", "admin_timeout", "=", "None", ",", ")", ":", "self", ".", "client", "=", "kudu", ".", "connect", "(", "host_or_hosts", ",", "por...
28.258065
17.290323
def _prepare_resource_chunks(self, resources, resource_delim=','): """As in some VirusTotal API methods the call can be made for multiple resources at once this method prepares a list of concatenated resources according to the maximum number of resources per requests. Args: ...
[ "def", "_prepare_resource_chunks", "(", "self", ",", "resources", ",", "resource_delim", "=", "','", ")", ":", "return", "[", "self", ".", "_prepare_resource_chunk", "(", "resources", ",", "resource_delim", ",", "pos", ")", "for", "pos", "in", "range", "(", ...
48.928571
21.428571
def _decode(frame, tab): """Decode a frame with the help of the table.""" blocks = [] # Decode each block while frame: length, endseq = tab[frame[0]] blocks.extend([frame[1:length], endseq]) frame = frame[length:] # Remove one (and only one)...
[ "def", "_decode", "(", "frame", ",", "tab", ")", ":", "blocks", "=", "[", "]", "# Decode each block", "while", "frame", ":", "length", ",", "endseq", "=", "tab", "[", "frame", "[", "0", "]", "]", "blocks", ".", "extend", "(", "[", "frame", "[", "1"...
28.588235
16.823529
def estimate_hsz(self,R,z=0.,dR=10.**-8.,**kwargs): """ NAME: estimate_hsz PURPOSE: estimate the exponential scale length of the vertical dispersion at R INPUT: R - Galactocentric radius (can be Quantity) z= height (default: 0 pc) (can be...
[ "def", "estimate_hsz", "(", "self", ",", "R", ",", "z", "=", "0.", ",", "dR", "=", "10.", "**", "-", "8.", ",", "*", "*", "kwargs", ")", ":", "Rs", "=", "[", "R", "-", "dR", "/", "2.", ",", "R", "+", "dR", "/", "2.", "]", "sf", "=", "nu...
21.029412
25.205882
def _gather_exposed_methods(self): """ Searches for the exposed methods in the current microservice class. A method is considered exposed if it is decorated with the :py:func:`gemstone.public_method` or :py:func:`gemstone.private_api_method`. """ self._extract_methods_fr...
[ "def", "_gather_exposed_methods", "(", "self", ")", ":", "self", ".", "_extract_methods_from_container", "(", "self", ")", "for", "module", "in", "self", ".", "modules", ":", "self", ".", "_extract_methods_from_container", "(", "module", ")" ]
38.363636
20.181818
def tag_native_vlan(self, **kwargs): """Set tagging of native VLAN on trunk. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc) name (str): Name of interface. (1/0/5, 1/0/10, etc) mode (str): Trunk port mode (trunk, tr...
[ "def", "tag_native_vlan", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "enabled", "=", "kwargs", ".", "...
41.863014
19.643836
def _strBinary(n): """Conert an integer to binary (i.e., a string of 1s and 0s).""" results = [] for i in range(8): n, r = divmod(n, 2) results.append('01'[r]) results.reverse() return ''.join(results)
[ "def", "_strBinary", "(", "n", ")", ":", "results", "=", "[", "]", "for", "i", "in", "range", "(", "8", ")", ":", "n", ",", "r", "=", "divmod", "(", "n", ",", "2", ")", "results", ".", "append", "(", "'01'", "[", "r", "]", ")", "results", "...
28.75
14.75
def bootstrap_standby_leader(self): """ If we found 'standby' key in the configuration, we need to bootstrap not a real master, but a 'standby leader', that will take base backup from a remote master and start follow it. """ clone_source = self.get_remote_master() ...
[ "def", "bootstrap_standby_leader", "(", "self", ")", ":", "clone_source", "=", "self", ".", "get_remote_master", "(", ")", "msg", "=", "'clone from remote master {0}'", ".", "format", "(", "clone_source", ".", "conn_url", ")", "result", "=", "self", ".", "clone"...
44.076923
16.461538
def after_insert_oai_set(mapper, connection, target): """Update records on OAISet insertion.""" _new_percolator(spec=target.spec, search_pattern=target.search_pattern) sleep(2) update_affected_records.delay( search_pattern=target.search_pattern )
[ "def", "after_insert_oai_set", "(", "mapper", ",", "connection", ",", "target", ")", ":", "_new_percolator", "(", "spec", "=", "target", ".", "spec", ",", "search_pattern", "=", "target", ".", "search_pattern", ")", "sleep", "(", "2", ")", "update_affected_rec...
38.285714
17.285714
def isqrt(n): ''' given a non-negative integer n, return a pair (a,b) such that n = a * a * b where b is a square-free integer. If n is a perfect square, then a is its square root and b is one. ''' # TODO: replace with a more efficient implementation if n == 0: return n, 1 ...
[ "def", "isqrt", "(", "n", ")", ":", "# TODO: replace with a more efficient implementation", "if", "n", "==", "0", ":", "return", "n", ",", "1", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "'math domain error'", ")", "a", ",", "b", ",", "c", "="...
21.459459
23.837838
def profile_list(request, page=1, template_name='userena/profile_list.html', paginate_by=50, extra_context=None, **kwargs): # pragma: no cover """ Returns a list of all profiles that are public. It's possible to disable this by changing ``USERENA_DISABLE_PROFILE_LIST`` to ``True`` in y...
[ "def", "profile_list", "(", "request", ",", "page", "=", "1", ",", "template_name", "=", "'userena/profile_list.html'", ",", "paginate_by", "=", "50", ",", "extra_context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "warnings", ".", ...
33.096774
25.935484
def show_as(**mappings): """ Show a set of request and/or response fields in logs using a different key. Example: @show_as(id="foo_id") def create_foo(): return Foo(id=uuid4()) """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): ...
[ "def", "show_as", "(", "*", "*", "mappings", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "g", ".", "show_request_fields", "=", "mappings...
24.684211
16.894737
def wait(self): """ Wait until all transferred events have been sent. """ if self.error: raise self.error if not self.running: raise ValueError("Unable to send until client has been started.") try: self._handler.wait() except (e...
[ "def", "wait", "(", "self", ")", ":", "if", "self", ".", "error", ":", "raise", "self", ".", "error", "if", "not", "self", ".", "running", ":", "raise", "ValueError", "(", "\"Unable to send until client has been started.\"", ")", "try", ":", "self", ".", "...
42.823529
17.352941