text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def is_valid_varname(self, name, item): """ Valid variable name, checked against global context. """ check_valid_varname(name, self._custom_units, self._structs, self._constants, item) if name in self._globals: raise VariableDeclarationException( 'Invalid name "%s", p...
[ "def", "is_valid_varname", "(", "self", ",", "name", ",", "item", ")", ":", "check_valid_varname", "(", "name", ",", "self", ".", "_custom_units", ",", "self", ".", "_structs", ",", "self", ".", "_constants", ",", "item", ")", "if", "name", "in", "self",...
48.625
0.007576
def openattachment(self, attachid): """ Get the contents of the attachment with the given attachment ID. Returns a file-like object. """ attachments = self.get_attachments(None, attachid) data = attachments["attachments"][str(attachid)] xmlrpcbinary = data["data"]...
[ "def", "openattachment", "(", "self", ",", "attachid", ")", ":", "attachments", "=", "self", ".", "get_attachments", "(", "None", ",", "attachid", ")", "data", "=", "attachments", "[", "\"attachments\"", "]", "[", "str", "(", "attachid", ")", "]", "xmlrpcb...
31.785714
0.004367
def _get_revision(self, revision): """ For git backend we always return integer here. This way we ensure that changset's revision attribute would become integer. """ is_null = lambda o: len(o) == revision.count('0') try: self.revisions[0] except (Key...
[ "def", "_get_revision", "(", "self", ",", "revision", ")", ":", "is_null", "=", "lambda", "o", ":", "len", "(", "o", ")", "==", "revision", ".", "count", "(", "'0'", ")", "try", ":", "self", ".", "revisions", "[", "0", "]", "except", "(", "KeyError...
39.577778
0.004384
def total_capacity(self): """ Find the total task capacity available for this channel. Query all the enabled hosts for this channel and sum up all the capacities. Each task has a "weight". Each task will be in "FREE" state until there is enough capacity for the task's "...
[ "def", "total_capacity", "(", "self", ")", ":", "# Ensure this task's channel has spare capacity for this task.", "total_capacity", "=", "0", "hosts", "=", "yield", "self", ".", "hosts", "(", "enabled", "=", "True", ")", "for", "host", "in", "hosts", ":", "total_c...
39.210526
0.002621
def add_macro(self,name,value): """ Add a variable (macro) for this node. This can be different for each node in the DAG, even if they use the same CondorJob. Within the CondorJob, the value of the macro can be referenced as '$(name)' -- for instance, to define a unique output or error file fo...
[ "def", "add_macro", "(", "self", ",", "name", ",", "value", ")", ":", "macro", "=", "self", ".", "__bad_macro_chars", ".", "sub", "(", "r''", ",", "name", ")", "self", ".", "__opts", "[", "macro", "]", "=", "value" ]
41.916667
0.009728
def tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. """ cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
[ "def", "tree_sph", "(", "polar", ",", "azimuthal", ",", "n", ",", "standardization", ",", "symbolic", "=", "False", ")", ":", "cos", "=", "numpy", ".", "vectorize", "(", "sympy", ".", "cos", ")", "if", "symbolic", "else", "numpy", ".", "cos", "# Conven...
31.4
0.002472
def read(author, kind): """ Attempts to read the cache to fetch missing arguments. This method will attempt to find a '.license' file in the 'CACHE_DIRECTORY', to read any arguments that were not passed to the license utility. Arguments: author (str): The author passed, if any. k...
[ "def", "read", "(", "author", ",", "kind", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "CACHE_PATH", ")", ":", "raise", "LicenseError", "(", "'No cache found. You must '", "'supply at least -a and -k.'", ")", "cache", "=", "read_cache", "(", ...
26.357143
0.001307
def get_chacra_repo(shaman_url): """ From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string. """ shaman_response = get_request(shaman_url) chacra_url = shaman_response.geturl() chacra_response = get_request(chacra_url) ...
[ "def", "get_chacra_repo", "(", "shaman_url", ")", ":", "shaman_response", "=", "get_request", "(", "shaman_url", ")", "chacra_url", "=", "shaman_response", ".", "geturl", "(", ")", "chacra_response", "=", "get_request", "(", "chacra_url", ")", "return", "chacra_re...
34
0.002865
def get_default_config(self): """ Returns the default collector settings """ config = super(NfsCollector, self).get_default_config() config.update({ 'path': 'nfs' }) return config
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "NfsCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'nfs'", "}", ")", "return", "config" ]
27
0.007968
def get_payroll_totals(month_work_entries, month_leave_entries): """Summarizes monthly work and leave totals, grouped by user. Returns (labels, rows). labels -> {'billable': [proj_labels], 'nonbillable': [proj_labels]} rows -> [{ name: name of user, billable, nonbillable...
[ "def", "get_payroll_totals", "(", "month_work_entries", ",", "month_leave_entries", ")", ":", "def", "_get_user_info", "(", "entries", ")", ":", "\"\"\"Helper for getting the associated user's first and last name.\"\"\"", "fname", "=", "entries", "[", "0", "]", ".", "get"...
42.773913
0.000199
def write_interactions(G, path, delimiter=' ', encoding='utf-8'): """Write a DyNetx graph in interaction list format. Parameters ---------- G : graph A DyNetx graph. path : basestring The desired output filename delimiter : character ...
[ "def", "write_interactions", "(", "G", ",", "path", ",", "delimiter", "=", "' '", ",", "encoding", "=", "'utf-8'", ")", ":", "for", "line", "in", "generate_interactions", "(", "G", ",", "delimiter", ")", ":", "line", "+=", "'\\n'", "path", ".", "write", ...
23.473684
0.002155
def matches_sample(output, target, threshold, is_correct, actual_output): """ Check if a sample with the given network output, target output, and threshold is the classification (is_correct, actual_output) like true positive or false negative """ return (bool(output > threshold) ...
[ "def", "matches_sample", "(", "output", ",", "target", ",", "threshold", ",", "is_correct", ",", "actual_output", ")", ":", "return", "(", "bool", "(", "output", ">", "threshold", ")", "==", "bool", "(", "target", ")", ")", "==", "is_correct", "and", "ac...
65.166667
0.012626
def compare_table_cols(a, b): """ Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise. """ return cmp(sorted((col.Name, col.Type) for col in a.getElementsByTagName(ligolw.Column.tagName)), sorted((col.Name, col.Type) for col in...
[ "def", "compare_table_cols", "(", "a", ",", "b", ")", ":", "return", "cmp", "(", "sorted", "(", "(", "col", ".", "Name", ",", "col", ".", "Type", ")", "for", "col", "in", "a", ".", "getElementsByTagName", "(", "ligolw", ".", "Column", ".", "tagName",...
51.714286
0.021739
def get_extra(request): """Return information about a module / collection that cannot be cached.""" settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict if args['page_ident_hash']: context_id, context_version = split_ident...
[ "def", "get_extra", "(", "request", ")", ":", "settings", "=", "get_current_registry", "(", ")", ".", "settings", "exports_dirs", "=", "settings", "[", "'exports-directories'", "]", ".", "split", "(", ")", "args", "=", "request", ".", "matchdict", "if", "arg...
45.35
0.00054
def add_argument(self, *args, **kwargs): """ add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...) """ # if no positional args are supplied or only one is supplied and # it doesn't look like an option string, par...
[ "def", "add_argument", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# if no positional args are supplied or only one is supplied and\r", "# it doesn't look like an option string, parse a positional\r", "# argument\r", "chars", "=", "self", ".", "prefix_c...
42.358974
0.001183
def get_assessment_taken_form_for_create(self, assessment_offered_id, assessment_taken_record_types): """Gets the assessment taken form for creating new assessments taken. A new form should be requested for each create transaction. arg: assessment_offered_id (osid.id.Id): the ``Id`` of the ...
[ "def", "get_assessment_taken_form_for_create", "(", "self", ",", "assessment_offered_id", ",", "assessment_taken_record_types", ")", ":", "if", "not", "isinstance", "(", "assessment_offered_id", ",", "ABCId", ")", ":", "raise", "errors", ".", "InvalidArgument", "(", "...
47.7
0.002054
def update_user(self, user_id, **kwargs): """Update a user.""" body = self._formdata(kwargs, FastlyUser.FIELDS) content = self._fetch("/user/%s" % user_id, method="PUT", body=body) return FastlyUser(self, content)
[ "def", "update_user", "(", "self", ",", "user_id", ",", "*", "*", "kwargs", ")", ":", "body", "=", "self", ".", "_formdata", "(", "kwargs", ",", "FastlyUser", ".", "FIELDS", ")", "content", "=", "self", ".", "_fetch", "(", "\"/user/%s\"", "%", "user_id...
43.4
0.027149
def elapsed(self): ''' Returns elapsed crawl time as a float in seconds. This metric includes all the time that a site was in active rotation, including any time it spent waiting for its turn to be brozzled. In contrast `Site.active_brozzling_time` only counts time when a ...
[ "def", "elapsed", "(", "self", ")", ":", "dt", "=", "0", "for", "ss", "in", "self", ".", "starts_and_stops", "[", ":", "-", "1", "]", ":", "dt", "+=", "(", "ss", "[", "'stop'", "]", "-", "ss", "[", "'start'", "]", ")", ".", "total_seconds", "("...
39.263158
0.003927
def _merge_args_with_kwargs(args_dict, kwargs_dict): """Merge args with kwargs.""" ret = args_dict.copy() ret.update(kwargs_dict) return ret
[ "def", "_merge_args_with_kwargs", "(", "args_dict", ",", "kwargs_dict", ")", ":", "ret", "=", "args_dict", ".", "copy", "(", ")", "ret", ".", "update", "(", "kwargs_dict", ")", "return", "ret" ]
30.4
0.00641
def matches_address(self, address): """returns whether this account knows about an email address :param str address: address to look up :rtype: bool """ if self.address == address: return True for alias in self.aliases: if alias == address: ...
[ "def", "matches_address", "(", "self", ",", "address", ")", ":", "if", "self", ".", "address", "==", "address", ":", "return", "True", "for", "alias", "in", "self", ".", "aliases", ":", "if", "alias", "==", "address", ":", "return", "True", "if", "self...
31.571429
0.004396
def remove_config_lock(name): ''' Release config lock previously held. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.remove_config_lock ''' ret = _default_ret(name) ret.update({ 'changes': __sal...
[ "def", "remove_config_lock", "(", "name", ")", ":", "ret", "=", "_default_ret", "(", "name", ")", "ret", ".", "update", "(", "{", "'changes'", ":", "__salt__", "[", "'panos.remove_config_lock'", "]", "(", ")", ",", "'result'", ":", "True", "}", ")", "ret...
17.227273
0.0025
def search_packages_info(query): """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ installed = {} for p in pkg_re...
[ "def", "search_packages_info", "(", "query", ")", ":", "installed", "=", "{", "}", "for", "p", "in", "pkg_resources", ".", "working_set", ":", "installed", "[", "canonicalize_name", "(", "p", ".", "project_name", ")", "]", "=", "p", "query_names", "=", "["...
40.619718
0.000677
def chunk(iterator, max_size): """Chunk a list/set/etc. :param iter iterator: The iterable object to chunk. :param int max_size: Max size of each chunk. Remainder chunk may be smaller. :return: Yield list of items. :rtype: iter """ gen = iter(iterator) while True: chunked = lis...
[ "def", "chunk", "(", "iterator", ",", "max_size", ")", ":", "gen", "=", "iter", "(", "iterator", ")", "while", "True", ":", "chunked", "=", "list", "(", ")", "for", "i", ",", "item", "in", "enumerate", "(", "gen", ")", ":", "chunked", ".", "append"...
26.210526
0.003876
def zadd(self, name, *args, **kwargs): """ Set any number of score, element-name pairs to the key ``name``. Pairs can be specified in two ways: As ``*args``, in the form of:: score1, name1, score2, name2, ... or as ``**kwargs``, in the form of:: name1=...
[ "def", "zadd", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pieces", "=", "[", "]", "if", "args", ":", "if", "len", "(", "args", ")", "%", "2", "!=", "0", ":", "raise", "ValueError", "(", "\"ZADD requires an equ...
32.357143
0.002144
def relation(self, node): """ Translate a relation node into SQLQuery. :param node: a treebrd node :return: a SQLQuery object for the tree rooted at node """ return self.query(select_block=str(node.attributes), from_block=node.name)
[ "def", "relation", "(", "self", ",", "node", ")", ":", "return", "self", ".", "query", "(", "select_block", "=", "str", "(", "node", ".", "attributes", ")", ",", "from_block", "=", "node", ".", "name", ")" ]
37.375
0.006536
def get_analysis_dict( root, pos, form ): ''' Takes *root*, *pos* and *form* from Filosoft's mrf input and reformats as EstNLTK's analysis dict: { "clitic": string, "ending": string, "form": string, "partofspeech": string, ...
[ "def", "get_analysis_dict", "(", "root", ",", "pos", ",", "form", ")", ":", "import", "sys", "result", "=", "{", "CLITIC", ":", "\"\"", ",", "ENDING", ":", "\"\"", ",", "FORM", ":", "form", ",", "POSTAG", ":", "pos", ",", "ROOT", ":", "\"\"", "}", ...
36.945946
0.015681
def _from_java(cls, java_stage): """ Given a Java TrainValidationSplitModel, create and return a Python wrapper of it. Used for ML persistence. """ # Load information from java_stage to the instance. bestModel = JavaParams._from_java(java_stage.bestModel()) estim...
[ "def", "_from_java", "(", "cls", ",", "java_stage", ")", ":", "# Load information from java_stage to the instance.", "bestModel", "=", "JavaParams", ".", "_from_java", "(", "java_stage", ".", "bestModel", "(", ")", ")", "estimator", ",", "epms", ",", "evaluator", ...
43.95
0.003341
def is_running(self): """Property method that returns a bool specifying if the process is currently running. This will return true if the state is active, idle or initializing. :rtype: bool """ return self._state in [self.STATE_ACTIVE, sel...
[ "def", "is_running", "(", "self", ")", ":", "return", "self", ".", "_state", "in", "[", "self", ".", "STATE_ACTIVE", ",", "self", ".", "STATE_IDLE", ",", "self", ".", "STATE_INITIALIZING", "]" ]
34.454545
0.005141
def port_profile_vlan_profile_switchport_access_mac_group_vlan_classification_access_vlan_access_vlan_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") ...
[ "def", "port_profile_vlan_profile_switchport_access_mac_group_vlan_classification_access_vlan_access_vlan_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "port_profile", "=", "ET", ".", "SubElement", "(",...
58.526316
0.004425
def revert_cnf(node): """Reverts a parse tree (RuleNode) to its original non-CNF form (Node).""" if isinstance(node, T): return node # Reverts TERM rule. if node.rule.lhs.name.startswith('__T_'): return node.children[0] else: children = [] for child in map(revert_cnf,...
[ "def", "revert_cnf", "(", "node", ")", ":", "if", "isinstance", "(", "node", ",", "T", ")", ":", "return", "node", "# Reverts TERM rule.", "if", "node", ".", "rule", ".", "lhs", ".", "name", ".", "startswith", "(", "'__T_'", ")", ":", "return", "node",...
40.318182
0.004405
def repository_factory(vcs_type, **kw): """ Instantiate a :class:`Repository` object based on the given type and arguments. :param vcs_type: One of the strings 'bazaar', 'bzr', 'git', 'hg' or 'mercurial' or a subclass of :class:`Repository`. :param kw: The keyword arguments to :fun...
[ "def", "repository_factory", "(", "vcs_type", ",", "*", "*", "kw", ")", ":", "# Resolve VCS aliases to Repository subclasses.", "if", "isinstance", "(", "vcs_type", ",", "string_types", ")", ":", "vcs_type", "=", "vcs_type", ".", "lower", "(", ")", "for", "cls",...
50.266667
0.003253
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 move(self, dest, changelist=0, force=False): """Renames/moves the file to dest :param dest: Destination to move the file to :type dest: str :param changelist: Changelist to add the move to :type changelist: :class:`.Changelist` :param force: Force the move to an exis...
[ "def", "move", "(", "self", ",", "dest", ",", "changelist", "=", "0", ",", "force", "=", "False", ")", ":", "cmd", "=", "[", "'move'", "]", "if", "force", ":", "cmd", ".", "append", "(", "'-f'", ")", "if", "changelist", ":", "cmd", "+=", "[", "...
27.16
0.002845
def sponsor_tagged_image(sponsor, tag): """returns the corresponding url from the tagged image list.""" if sponsor.files.filter(tag_name=tag).exists(): return sponsor.files.filter(tag_name=tag).first().tagged_file.item.url return ''
[ "def", "sponsor_tagged_image", "(", "sponsor", ",", "tag", ")", ":", "if", "sponsor", ".", "files", ".", "filter", "(", "tag_name", "=", "tag", ")", ".", "exists", "(", ")", ":", "return", "sponsor", ".", "files", ".", "filter", "(", "tag_name", "=", ...
49.6
0.003968
def addFeaturesSearchOptions(parser): """ Adds common options to a features search command line parser. """ addFeatureSetIdArgument(parser) addFeaturesReferenceNameArgument(parser) addStartArgument(parser) addEndArgument(parser) addParentFeatureIdArgument(parser) addFeatureTypesArgum...
[ "def", "addFeaturesSearchOptions", "(", "parser", ")", ":", "addFeatureSetIdArgument", "(", "parser", ")", "addFeaturesReferenceNameArgument", "(", "parser", ")", "addStartArgument", "(", "parser", ")", "addEndArgument", "(", "parser", ")", "addParentFeatureIdArgument", ...
32.2
0.003021
def sequence(values): """ Wrap a list of Python values as an Ibis sequence type Parameters ---------- values : list Should all be None or the same type Returns ------- seq : Sequence """ import ibis.expr.operations as ops return ops.ValueList(values).to_expr()
[ "def", "sequence", "(", "values", ")", ":", "import", "ibis", ".", "expr", ".", "operations", "as", "ops", "return", "ops", ".", "ValueList", "(", "values", ")", ".", "to_expr", "(", ")" ]
18.625
0.003195
def add_collection(self, path, c_name, c_type, c_doc, c_version="unknown", c_scope="", c_namedargs="yes", c_doc_format="ROBOT"): """Insert data into the collection table""" if path is not None: # We want to store the normalized form of the path in the # dat...
[ "def", "add_collection", "(", "self", ",", "path", ",", "c_name", ",", "c_type", ",", "c_doc", ",", "c_version", "=", "\"unknown\"", ",", "c_scope", "=", "\"\"", ",", "c_namedargs", "=", "\"yes\"", ",", "c_doc_format", "=", "\"ROBOT\"", ")", ":", "if", "...
43.882353
0.005249
def gsum_(self, col: str, index_col: bool=True) -> "Ds": """ Group by and sum column :param col: column to group :type col: str :param index_col: :type index_col: bool :return: a dataswim instance :rtype: Ds :example: ``ds2 = ds.gsum("Col 1")`` ...
[ "def", "gsum_", "(", "self", ",", "col", ":", "str", ",", "index_col", ":", "bool", "=", "True", ")", "->", "\"Ds\"", ":", "try", ":", "df", "=", "self", ".", "df", ".", "copy", "(", ")", "df", "=", "df", ".", "groupby", "(", "[", "col", "]",...
28.904762
0.007974
def parse_datetime(dt_str, format): """Create a timezone-aware datetime object from a datetime string.""" t = time.strptime(dt_str, format) return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC)
[ "def", "parse_datetime", "(", "dt_str", ",", "format", ")", ":", "t", "=", "time", ".", "strptime", "(", "dt_str", ",", "format", ")", "return", "datetime", "(", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", ",", "t", ...
54
0.004566
def get_requirements(self, reqts, extras=None, env=None): """ Base method to get dependencies, given a set of extras to satisfy and an optional environment context. :param reqts: A list of sometimes-wanted dependencies, perhaps dependent on extras and environment. ...
[ "def", "get_requirements", "(", "self", ",", "reqts", ",", "extras", "=", "None", ",", "env", "=", "None", ")", ":", "if", "self", ".", "_legacy", ":", "result", "=", "reqts", "else", ":", "result", "=", "[", "]", "extras", "=", "get_extras", "(", ...
45.195122
0.001057
def render_noderef(self, ontol, n, query_ids=None, **args): """ Render a node object """ if query_ids is None: query_ids = [] marker = "" if n in query_ids: marker = " * " label = ontol.label(n) s = None if label is not None...
[ "def", "render_noderef", "(", "self", ",", "ontol", ",", "n", ",", "query_ids", "=", "None", ",", "*", "*", "args", ")", ":", "if", "query_ids", "is", "None", ":", "query_ids", "=", "[", "]", "marker", "=", "\"\"", "if", "n", "in", "query_ids", ":"...
28.5
0.003086
def check_summary_health(summary_file, **kwargs): """Checks the health of a sample from the FastQC summary file. Parses the FastQC summary file and tests whether the sample is good or not. There are four categories that cannot fail, and two that must pass in order for the sample pass this check. If the...
[ "def", "check_summary_health", "(", "summary_file", ",", "*", "*", "kwargs", ")", ":", "# Store the summary categories that cannot fail. If they fail, do not", "# proceed with this sample", "fail_sensitive", "=", "kwargs", ".", "get", "(", "\"fail_sensitive\"", ",", "[", "\...
31.770642
0.00028
def __convert_keys_2(header, d): """ Convert lpd to noaa keys for this one section :param str header: Section header :param dict d: Metadata :return dict: Metadata w/ converted keys """ d_out = {} try: for k, v in d.items(): tr...
[ "def", "__convert_keys_2", "(", "header", ",", "d", ")", ":", "d_out", "=", "{", "}", "try", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "try", ":", "noaa_key", "=", "LIPD_NOAA_MAP_BY_SECTION", "[", "header", "]", "[", "k", ...
43.619048
0.005342
def _parse_cli_facter_results(facter_results): '''Parse key value pairs printed with "=>" separators. YAML is preferred output scheme for facter. >>> list(_parse_cli_facter_results("""foo => bar ... baz => 1 ... foo_bar => True""")) [('foo', 'bar'), ('baz', '1'), ('foo_bar', 'True')] >>> li...
[ "def", "_parse_cli_facter_results", "(", "facter_results", ")", ":", "last_key", ",", "last_value", "=", "None", ",", "[", "]", "for", "line", "in", "filter", "(", "None", ",", "facter_results", ".", "splitlines", "(", ")", ")", ":", "res", "=", "line", ...
32.756757
0.001603
def blockstack_backup_restore(working_dir, block_number): """ Restore the database from a backup in the backups/ directory. If block_number is None, then use the latest backup. NOT THREAD SAFE Return True on success Raise an exception on error """ db = BlockstackDB.get_readwrite_instan...
[ "def", "blockstack_backup_restore", "(", "working_dir", ",", "block_number", ")", ":", "db", "=", "BlockstackDB", ".", "get_readwrite_instance", "(", "working_dir", ",", "restore", "=", "True", ",", "restore_block_height", "=", "block_number", ")", "try", ":", "db...
27.157895
0.003745
def load(self): """ Load the Certificate object from DigitalOcean. Requires self.id to be set. """ data = self.get_data("certificates/%s" % self.id) certificate = data["certificate"] for attr in certificate.keys(): setattr(self, attr, certifi...
[ "def", "load", "(", "self", ")", ":", "data", "=", "self", ".", "get_data", "(", "\"certificates/%s\"", "%", "self", ".", "id", ")", "certificate", "=", "data", "[", "\"certificate\"", "]", "for", "attr", "in", "certificate", ".", "keys", "(", ")", ":"...
26.153846
0.005682
def update_trial_stats(self, trial, result): """Update result for trial. Called after trial has finished an iteration - will decrement iteration count. TODO(rliaw): The other alternative is to keep the trials in and make sure they're not set as pending later.""" assert trial in...
[ "def", "update_trial_stats", "(", "self", ",", "trial", ",", "result", ")", ":", "assert", "trial", "in", "self", ".", "_live_trials", "assert", "self", ".", "_get_result_time", "(", "result", ")", ">=", "0", "delta", "=", "self", ".", "_get_result_time", ...
39.666667
0.003284
def eq_obj_contents(l, r): """ Compares object contents, supports slots :param l: :param r: :return: """ if l.__class__ is not r.__class__: return False if hasattr(l, "__slots__"): return eq_obj_slots(l, r) else: return l.__dict__ == r.__dict__
[ "def", "eq_obj_contents", "(", "l", ",", "r", ")", ":", "if", "l", ".", "__class__", "is", "not", "r", ".", "__class__", ":", "return", "False", "if", "hasattr", "(", "l", ",", "\"__slots__\"", ")", ":", "return", "eq_obj_slots", "(", "l", ",", "r", ...
22.461538
0.006579
def make_splice_junction_df(fn, type='gene'): """Read the Gencode gtf file and make a pandas dataframe describing the splice junctions Parameters ---------- filename : str of filename Filename of the Gencode gtf file Returns ------- df : pandas.DataFrame Dataframe of ...
[ "def", "make_splice_junction_df", "(", "fn", ",", "type", "=", "'gene'", ")", ":", "import", "itertools", "as", "it", "import", "HTSeq", "import", "numpy", "as", "np", "# GFF_Reader has an option for end_included. However, I think it is", "# backwards. So if your gtf is en...
39.431818
0.004498
def vectorize(data, cloud=None, api_key=None, version=None, **kwargs): """ Support for raw features from the custom collections API """ batch = detect_batch(data) data = data_preprocess(data, batch=batch) url_params = {"batch": batch, "api_key": api_key, "version": version, "method": "vectorize"...
[ "def", "vectorize", "(", "data", ",", "cloud", "=", "None", ",", "api_key", "=", "None", ",", "version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "batch", "=", "detect_batch", "(", "data", ")", "data", "=", "data_preprocess", "(", "data", ",",...
50.375
0.007317
def GET(self, courseid): # pylint: disable=arguments-differ """ GET request """ course = self.get_course(courseid) return self.show_page(course)
[ "def", "GET", "(", "self", ",", "courseid", ")", ":", "# pylint: disable=arguments-differ", "course", "=", "self", ".", "get_course", "(", "courseid", ")", "return", "self", ".", "show_page", "(", "course", ")" ]
41.5
0.011834
def finalize(state, block): """Apply rewards and commit.""" if state.is_METROPOLIS(): br = state.config['BYZANTIUM_BLOCK_REWARD'] nr = state.config['BYZANTIUM_NEPHEW_REWARD'] else: br = state.config['BLOCK_REWARD'] nr = state.config['NEPHEW_REWARD'] delta = int(...
[ "def", "finalize", "(", "state", ",", "block", ")", ":", "if", "state", ".", "is_METROPOLIS", "(", ")", ":", "br", "=", "state", ".", "config", "[", "'BYZANTIUM_BLOCK_REWARD'", "]", "nr", "=", "state", ".", "config", "[", "'BYZANTIUM_NEPHEW_REWARD'", "]", ...
34.913043
0.002424
def get_event_discount(self, id, discount_id, **data): """ GET /events/:id/discounts/:discount_id/ Gets a :format:`discount` by ID as the key ``discount``. """ return self.get("/events/{0}/discounts/{0}/".format(id,discount_id), data=data)
[ "def", "get_event_discount", "(", "self", ",", "id", ",", "discount_id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/events/{0}/discounts/{0}/\"", ".", "format", "(", "id", ",", "discount_id", ")", ",", "data", "=", "data", ")...
40.285714
0.017361
def get_mapping_actions(image=None, imageId=None, in_digests=[], bundle={}): """ Given an image, image_id, digests, and a bundle, determine which policies and whitelists to evaluate. :param image: Image obj :param imageId: image id string :param in_digests: candidate digests :param bundle:...
[ "def", "get_mapping_actions", "(", "image", "=", "None", ",", "imageId", "=", "None", ",", "in_digests", "=", "[", "]", ",", "bundle", "=", "{", "}", ")", ":", "if", "not", "image", "or", "not", "bundle", ":", "raise", "Exception", "(", "\"input error\...
41.137725
0.004832
def from_filepath(filepath, strict = True, parse_ligands = False): '''A function to replace the old constructor call where a filename was passed in.''' return PDB(read_file(filepath), strict = strict, parse_ligands = parse_ligands)
[ "def", "from_filepath", "(", "filepath", ",", "strict", "=", "True", ",", "parse_ligands", "=", "False", ")", ":", "return", "PDB", "(", "read_file", "(", "filepath", ")", ",", "strict", "=", "strict", ",", "parse_ligands", "=", "parse_ligands", ")" ]
81.666667
0.048583
def do_action_to_ancestors(analysis_request, transition_id): """Promotes the transitiion passed in to ancestors, if any """ parent_ar = analysis_request.getParentAnalysisRequest() if parent_ar: do_action_for(parent_ar, transition_id)
[ "def", "do_action_to_ancestors", "(", "analysis_request", ",", "transition_id", ")", ":", "parent_ar", "=", "analysis_request", ".", "getParentAnalysisRequest", "(", ")", "if", "parent_ar", ":", "do_action_for", "(", "parent_ar", ",", "transition_id", ")" ]
42
0.003891
def resize_img(fname, targ, path, new_path, fn=None): """ Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ. """ if fn is None: fn = resize_fn(targ) dest = os.path.join(path_for(path, new_path, targ), fname) if os.path.exis...
[ "def", "resize_img", "(", "fname", ",", "targ", ",", "path", ",", "new_path", ",", "fn", "=", "None", ")", ":", "if", "fn", "is", "None", ":", "fn", "=", "resize_fn", "(", "targ", ")", "dest", "=", "os", ".", "path", ".", "join", "(", "path_for",...
42.272727
0.006316
def visit_package(self, node): """visit an astroid.Package node * optionally tag the node with a unique id """ if self.tag: node.uid = self.generate_id() for subelmt in node.values(): self.visit(subelmt)
[ "def", "visit_package", "(", "self", ",", "node", ")", ":", "if", "self", ".", "tag", ":", "node", ".", "uid", "=", "self", ".", "generate_id", "(", ")", "for", "subelmt", "in", "node", ".", "values", "(", ")", ":", "self", ".", "visit", "(", "su...
29
0.007435
def rouge_2(hypotheses, references): """ Calculate ROUGE-2 F1, precision, recall scores """ rouge_2 = [ rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses, references) ] rouge_2_f, _, _ = map(np.mean, zip(*rouge_2)) return rouge_2_f
[ "def", "rouge_2", "(", "hypotheses", ",", "references", ")", ":", "rouge_2", "=", "[", "rouge_n", "(", "[", "hyp", "]", ",", "[", "ref", "]", ",", "2", ")", "for", "hyp", ",", "ref", "in", "zip", "(", "hypotheses", ",", "references", ")", "]", "r...
29.444444
0.003663
def iter_headers(self): ''' Yield (header, value) tuples, skipping headers that are not allowed with the current response status code. ''' headers = self._headers.iteritems() bad_headers = self.bad_headers.get(self.status_code) if bad_headers: headers = [h for h i...
[ "def", "iter_headers", "(", "self", ")", ":", "headers", "=", "self", ".", "_headers", ".", "iteritems", "(", ")", "bad_headers", "=", "self", ".", "bad_headers", ".", "get", "(", "self", ".", "status_code", ")", "if", "bad_headers", ":", "headers", "=",...
44.076923
0.003419
def _aload8(ins): ''' Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _addr(ins.quad[2]) output.append('ld a, (hl)') output.append('push af') return output
[ "def", "_aload8", "(", "ins", ")", ":", "output", "=", "_addr", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'ld a, (hl)'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
25.8
0.003745
def get_filename(self, checksum): """ :param checksum: checksum :return: filename no storage base part """ filename = None for _filename, metadata in self._log.items(): if metadata['checksum'] == checksum: filename = _filename b...
[ "def", "get_filename", "(", "self", ",", "checksum", ")", ":", "filename", "=", "None", "for", "_filename", ",", "metadata", "in", "self", ".", "_log", ".", "items", "(", ")", ":", "if", "metadata", "[", "'checksum'", "]", "==", "checksum", ":", "filen...
30.727273
0.005747
def indexFromItem(self, regItem, col=0): """ Gets the index (with column=0) for the row that contains the regItem If col is negative, it is counted from the end """ if col < 0: col = len(self.attrNames) - col try: row = self.registry.items.index(regIte...
[ "def", "indexFromItem", "(", "self", ",", "regItem", ",", "col", "=", "0", ")", ":", "if", "col", "<", "0", ":", "col", "=", "len", "(", "self", ".", "attrNames", ")", "-", "col", "try", ":", "row", "=", "self", ".", "registry", ".", "items", "...
36
0.006772
def kill(timeout=15): ''' Kill the salt minion. timeout int seconds to wait for the minion to die. If you have a monitor that restarts ``salt-minion`` when it dies then this is a great way to restart after a minion upgrade. CLI example:: >$ salt minion[12] minion.kill ...
[ "def", "kill", "(", "timeout", "=", "15", ")", ":", "ret", "=", "{", "'killed'", ":", "None", ",", "'retcode'", ":", "1", ",", "}", "comment", "=", "[", "]", "pid", "=", "__grains__", ".", "get", "(", "'pid'", ")", "if", "not", "pid", ":", "com...
30.720588
0.000928
def get_filter_specification_visitor(name, registry=None): """ Returns a the class registered as the filter specification visitor utility under the given name (one of the :const:`everest.querying.base.EXPRESSION_KINDS` constants). :returns: class implementing :class:`everest.interfaces.IFil...
[ "def", "get_filter_specification_visitor", "(", "name", ",", "registry", "=", "None", ")", ":", "if", "registry", "is", "None", ":", "registry", "=", "get_current_registry", "(", ")", "return", "registry", ".", "getUtility", "(", "IFilterSpecificationVisitor", ","...
39.916667
0.002041
def addEventListener(self, event: str, listener: _EventListenerType ) -> None: """Add event listener to this node. ``event`` is a string which determines the event type when the new listener called. Acceptable events are same as JavaScript, without ``on``. For e...
[ "def", "addEventListener", "(", "self", ",", "event", ":", "str", ",", "listener", ":", "_EventListenerType", ")", "->", "None", ":", "self", ".", "_add_event_listener", "(", "event", ",", "listener", ")" ]
47
0.006263
def make_get_request(url, params, headers, connection): """ Helper function that makes an HTTP GET request to the given firebase endpoint. Timeout is 60 seconds. `url`: The full URL of the firebase endpoint (DSN appended.) `params`: Python dict that is appended to the URL like a querystring. `he...
[ "def", "make_get_request", "(", "url", ",", "params", ",", "headers", ",", "connection", ")", ":", "timeout", "=", "getattr", "(", "connection", ",", "'timeout'", ")", "response", "=", "connection", ".", "get", "(", "url", ",", "params", "=", "params", "...
50.083333
0.003265
def _updateItemComboBoxIndex(self, item, column, num): """Callback for comboboxes: notifies us that a combobox for the given item and column has changed""" item._combobox_current_index[column] = num item._combobox_current_value[column] = item._combobox_option_list[column][num][0]
[ "def", "_updateItemComboBoxIndex", "(", "self", ",", "item", ",", "column", ",", "num", ")", ":", "item", ".", "_combobox_current_index", "[", "column", "]", "=", "num", "item", ".", "_combobox_current_value", "[", "column", "]", "=", "item", ".", "_combobox...
75.25
0.013158
def _set_motion_handle(self, event): """Sets motion handle to currently grabbed handle """ item = self.grabbed_item handle = self.grabbed_handle pos = event.x, event.y self.motion_handle = HandleInMotion(item, handle, self.view) self.motion_handle.GLUE_DISTANCE = ...
[ "def", "_set_motion_handle", "(", "self", ",", "event", ")", ":", "item", "=", "self", ".", "grabbed_item", "handle", "=", "self", ".", "grabbed_handle", "pos", "=", "event", ".", "x", ",", "event", ".", "y", "self", ".", "motion_handle", "=", "HandleInM...
43.111111
0.005051
def process_mav(self, mlog, flightmode_selections): '''process one file''' self.vars = {} idx = 0 all_false = True for s in flightmode_selections: if s: all_false = False # pre-calc right/left axes self.num_fields = len(self.fields) ...
[ "def", "process_mav", "(", "self", ",", "mlog", ",", "flightmode_selections", ")", ":", "self", ".", "vars", "=", "{", "}", "idx", "=", "0", "all_false", "=", "True", "for", "s", "in", "flightmode_selections", ":", "if", "s", ":", "all_false", "=", "Fa...
36.226415
0.003043
def connect(): """Connect controller to handle token exchange and query Uber API.""" # Exchange authorization code for acceess token and create session session = auth_flow.get_session(request.url) client = UberRidesClient(session) # Fetch profile for rider profile = client.get_rider_profile()....
[ "def", "connect", "(", ")", ":", "# Exchange authorization code for acceess token and create session", "session", "=", "auth_flow", ".", "get_session", "(", "request", ".", "url", ")", "client", "=", "UberRidesClient", "(", "session", ")", "# Fetch profile for rider", "...
31.37931
0.001066
def run(self): """ Run the receiver thread """ dataOut = array.array('B', [0xFF]) waitTime = 0 emptyCtr = 0 # Try up to 10 times to enable the safelink mode with self._radio_manager as cradio: for _ in range(10): resp = cradio.send_packet((0xf...
[ "def", "run", "(", "self", ")", ":", "dataOut", "=", "array", ".", "array", "(", "'B'", ",", "[", "0xFF", "]", ")", "waitTime", "=", "0", "emptyCtr", "=", "0", "# Try up to 10 times to enable the safelink mode", "with", "self", ".", "_radio_manager", "as", ...
37.298969
0.000539
async def _trigger_event(self, event, *args, **kwargs): """Invoke an event handler.""" run_async = kwargs.pop('run_async', False) ret = None if event in self.handlers: if asyncio.iscoroutinefunction(self.handlers[event]) is True: if run_async: ...
[ "async", "def", "_trigger_event", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "run_async", "=", "kwargs", ".", "pop", "(", "'run_async'", ",", "False", ")", "ret", "=", "None", "if", "event", "in", "self", ".", "...
43.888889
0.002477
def get_function_from_config(item): """ Import the function to get profile by handle. """ config = get_configuration() func_path = config.get(item) module_path, func_name = func_path.rsplit(".", 1) module = importlib.import_module(module_path) func = getattr(module, func_name) return...
[ "def", "get_function_from_config", "(", "item", ")", ":", "config", "=", "get_configuration", "(", ")", "func_path", "=", "config", ".", "get", "(", "item", ")", "module_path", ",", "func_name", "=", "func_path", ".", "rsplit", "(", "\".\"", ",", "1", ")",...
31.6
0.003077
def calc(self, *args, **kwargs): """ :type args: list[DataFrame] """ cases = kwargs.pop('_cases', []) if not isinstance(cases, Iterable): cases = [cases, ] result_callback = kwargs.pop('_result_callback', None) execute_now = kwargs.pop('execute_now', T...
[ "def", "calc", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cases", "=", "kwargs", ".", "pop", "(", "'_cases'", ",", "[", "]", ")", "if", "not", "isinstance", "(", "cases", ",", "Iterable", ")", ":", "cases", "=", "[", "ca...
34.827586
0.003854
def _romanize(word: str) -> str: """ :param str word: Thai word to be romanized, should have already been tokenized. :return: Spells out how the Thai word should be pronounced. """ if not isinstance(word, str) or not word: return "" word = _replace_vowels(_normalize(word)) res = _RE...
[ "def", "_romanize", "(", "word", ":", "str", ")", "->", "str", ":", "if", "not", "isinstance", "(", "word", ",", "str", ")", "or", "not", "word", ":", "return", "\"\"", "word", "=", "_replace_vowels", "(", "_normalize", "(", "word", ")", ")", "res", ...
27.45
0.003521
def _start_indieauth(self, me, redirect_url, state, scope): """Helper for both authentication and authorization. Kicks off IndieAuth by fetching the authorization endpoint from the user's homepage and redirecting to it. Args: me (string): the authing user's URL. if it does not...
[ "def", "_start_indieauth", "(", "self", ",", "me", ",", "redirect_url", ",", "state", ",", "scope", ")", ":", "if", "not", "me", ".", "startswith", "(", "'http://'", ")", "and", "not", "me", ".", "startswith", "(", "'https://'", ")", ":", "me", "=", ...
39.166667
0.001186
def Gregory_Scott(x, rhol, rhog): r'''Calculates void fraction in two-phase flow according to the model of [1]_ as given in [2]_ and [3]_. .. math:: \alpha = \frac{x}{\rho_g}\left[C_0\left(\frac{x}{\rho_g} + \frac{1-x} {\rho_l}\right) +\frac{v_{gm}}{G} \right]^{-1} .. math...
[ "def", "Gregory_Scott", "(", "x", ",", "rhol", ",", "rhog", ")", ":", "C0", "=", "1.19", "return", "x", "/", "rhog", "*", "(", "C0", "*", "(", "x", "/", "rhog", "+", "(", "1", "-", "x", ")", "/", "rhol", ")", ")", "**", "-", "1" ]
31.730769
0.00823
def serialize(self): """Serialize this segment to a ``Segment`` message. Returns: ``Segment`` message. """ segment = hangouts_pb2.Segment( type=self.type_, text=self.text, formatting=hangouts_pb2.Formatting( bold=self.is_bo...
[ "def", "serialize", "(", "self", ")", ":", "segment", "=", "hangouts_pb2", ".", "Segment", "(", "type", "=", "self", ".", "type_", ",", "text", "=", "self", ".", "text", ",", "formatting", "=", "hangouts_pb2", ".", "Formatting", "(", "bold", "=", "self...
31.157895
0.003279
def getHeader(filename, handle=None): """ Return a copy of the PRIMARY header, along with any group/extension header for this filename specification. """ _fname, _extn = parseFilename(filename) # Allow the user to provide an already opened PyFITS object # to derive the header from... # ...
[ "def", "getHeader", "(", "filename", ",", "handle", "=", "None", ")", ":", "_fname", ",", "_extn", "=", "parseFilename", "(", "filename", ")", "# Allow the user to provide an already opened PyFITS object", "# to derive the header from...", "#", "if", "not", "handle", ...
33.05
0.002939
def filter_by(zips=_zips, **kwargs): """ Use `kwargs` to select for desired attributes from list of zipcode dicts """ return [z for z in zips if all([k in z and z[k] == v for k, v in kwargs.items()])]
[ "def", "filter_by", "(", "zips", "=", "_zips", ",", "*", "*", "kwargs", ")", ":", "return", "[", "z", "for", "z", "in", "zips", "if", "all", "(", "[", "k", "in", "z", "and", "z", "[", "k", "]", "==", "v", "for", "k", ",", "v", "in", "kwargs...
68.666667
0.014423
def get_block_iter(self, start_block=None, start_block_num=None, reverse=True): """Returns an iterator that traverses blocks in block number order. Args: start_block (:obj:`BlockWrapper`): the block from which traversal begins start_block_n...
[ "def", "get_block_iter", "(", "self", ",", "start_block", "=", "None", ",", "start_block_num", "=", "None", ",", "reverse", "=", "True", ")", ":", "start", "=", "None", "if", "start_block_num", ":", "if", "len", "(", "start_block_num", ")", "<", "2", ":"...
35.942857
0.002322
def interleave(*arrays,**kwargs): ''' arr1 = [1,2,3,4] arr2 = ['a','b','c','d'] arr3 = ['@','#','%','*'] interleave(arr1,arr2,arr3) ''' anum = arrays.__len__() rslt = [] length = arrays[0].__len__() for j in range(0,length): for i in range(0,anum): ...
[ "def", "interleave", "(", "*", "arrays", ",", "*", "*", "kwargs", ")", ":", "anum", "=", "arrays", ".", "__len__", "(", ")", "rslt", "=", "[", "]", "length", "=", "arrays", "[", "0", "]", ".", "__len__", "(", ")", "for", "j", "in", "range", "("...
25.266667
0.010178
def generate_lambda_functions(): """Create the Blockade lambda functions.""" logger.debug("[#] Setting up the Lambda functions") aws_lambda = boto3.client('lambda', region_name=PRIMARY_REGION) functions = aws_lambda.list_functions().get('Functions') existing_funcs = [x['FunctionName'] for x in funct...
[ "def", "generate_lambda_functions", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up the Lambda functions\"", ")", "aws_lambda", "=", "boto3", ".", "client", "(", "'lambda'", ",", "region_name", "=", "PRIMARY_REGION", ")", "functions", "=", "aws_lambda"...
39.277778
0.00207
def resume_trial(self, trial): """Resumes PAUSED trials. This is a blocking call.""" assert trial.status == Trial.PAUSED, trial.status self.start_trial(trial)
[ "def", "resume_trial", "(", "self", ",", "trial", ")", ":", "assert", "trial", ".", "status", "==", "Trial", ".", "PAUSED", ",", "trial", ".", "status", "self", ".", "start_trial", "(", "trial", ")" ]
35.8
0.010929
def add_next_tick_callback(self, callback, callback_id=None): """ Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tick_callback.""" def wrapper(*args, **kwargs): # this 'removed' flag is a hack because Tornado has no way # to re...
[ "def", "add_next_tick_callback", "(", "self", ",", "callback", ",", "callback_id", "=", "None", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# this 'removed' flag is a hack because Tornado has no way", "# to remove a \"next tick\" ...
41.227273
0.003233
def total(self): """ Get a list of counts for all of Unsplash :return [Stat]: The Unsplash Stat. """ url = "/stats/total" result = self._get(url) return StatModel.parse(result)
[ "def", "total", "(", "self", ")", ":", "url", "=", "\"/stats/total\"", "result", "=", "self", ".", "_get", "(", "url", ")", "return", "StatModel", ".", "parse", "(", "result", ")" ]
25
0.008584
def _copy_data(instream, outstream): """Copy data from one stream to another. :type instream: :class:`io.BytesIO` or :class:`io.StringIO` or file :param instream: A byte stream or open file to read from. :param file outstream: The file descriptor of a tmpfile to write to. """ sent = 0 whil...
[ "def", "_copy_data", "(", "instream", ",", "outstream", ")", ":", "sent", "=", "0", "while", "True", ":", "if", "(", "(", "_py3k", "and", "isinstance", "(", "instream", ",", "str", ")", ")", "or", "(", "not", "_py3k", "and", "isinstance", "(", "instr...
41.360465
0.001922
def rotate_backups(self, location, load_config=True, prepare=False): """ Rotate the backups in a directory according to a flexible rotation scheme. :param location: Any value accepted by :func:`coerce_location()`. :param load_config: If :data:`True` (so by default) the rotation scheme ...
[ "def", "rotate_backups", "(", "self", ",", "location", ",", "load_config", "=", "True", ",", "prepare", "=", "False", ")", ":", "rotation_commands", "=", "[", "]", "location", "=", "coerce_location", "(", "location", ")", "# Load configuration overrides by user?",...
54.875
0.002014
def add_connection(self, name, **kwargs): """Adds a connection to the configuration This method will add a connection to the configuration. The connection added is only available for the lifetime of the object and is not persisted. Note: If a call is made to load()...
[ "def", "add_connection", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "name", "=", "'connection:{}'", ".", "format", "(", "name", ")", "self", ".", "add_section", "(", "name", ")", "for", "key", ",", "value", "in", "list", "(", "kwarg...
37.916667
0.002144
def severity(self): """ Severity level of the event. One of ``INFO``, ``WATCH``, ``WARNING``, ``DISTRESS``, ``CRITICAL`` or ``SEVERE``. """ if self._proto.HasField('severity'): return yamcs_pb2.Event.EventSeverity.Name(self._proto.severity) return None
[ "def", "severity", "(", "self", ")", ":", "if", "self", ".", "_proto", ".", "HasField", "(", "'severity'", ")", ":", "return", "yamcs_pb2", ".", "Event", ".", "EventSeverity", ".", "Name", "(", "self", ".", "_proto", ".", "severity", ")", "return", "No...
38.125
0.00641
def mail_sent_contains_html(self): """ Test that an email contains the HTML (assert HTML in) in the multiline as one of its MIME alternatives. The HTML is normalised by passing through Django's :func:`django.test.html.parse_html`. Example: .. code-block:: gherkin And I have sent ...
[ "def", "mail_sent_contains_html", "(", "self", ")", ":", "for", "email", "in", "mail", ".", "outbox", ":", "try", ":", "html", "=", "next", "(", "content", "for", "content", ",", "mime", "in", "email", ".", "alternatives", "if", "mime", "==", "'text/html...
28
0.000933
def _send(self, *messages): """Send message.""" if not self.transport: return False messages = [message.encode('ascii') for message in messages] data = b'' while messages: message = messages.pop(0) if len(data + message) + 1 > self.parent.cfg....
[ "def", "_send", "(", "self", ",", "*", "messages", ")", ":", "if", "not", "self", ".", "transport", ":", "return", "False", "messages", "=", "[", "message", ".", "encode", "(", "'ascii'", ")", "for", "message", "in", "messages", "]", "data", "=", "b'...
28.294118
0.004024
def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(TextEntry, self).to_api_repr() info["textPayload"] = self.payload return info
[ "def", "to_api_repr", "(", "self", ")", ":", "info", "=", "super", "(", "TextEntry", ",", "self", ")", ".", "to_api_repr", "(", ")", "info", "[", "\"textPayload\"", "]", "=", "self", ".", "payload", "return", "info" ]
31.5
0.010309
def read_legacy_cfg_files(self, cfg_files, alignak_env_files=None): # pylint: disable=too-many-nested-blocks,too-many-statements # pylint: disable=too-many-branches, too-many-locals """Read and parse the Nagios legacy configuration files and store their content into a StringIO object whi...
[ "def", "read_legacy_cfg_files", "(", "self", ",", "cfg_files", ",", "alignak_env_files", "=", "None", ")", ":", "# pylint: disable=too-many-nested-blocks,too-many-statements", "# pylint: disable=too-many-branches, too-many-locals", "cfg_buffer", "=", "''", "if", "not", "cfg_fil...
45.908537
0.00286
def predict(self, x): """ This function calculates the new output value `y` from input array `x`. **Args:** * `x` : input vector (1 dimension array) in length of filter. **Returns:** * `y` : output value (float) calculated from input array. """ y = np...
[ "def", "predict", "(", "self", ",", "x", ")", ":", "y", "=", "np", ".", "dot", "(", "self", ".", "w", ",", "x", ")", "return", "y" ]
22.533333
0.005682
def media(self, uri): """Play a media file.""" try: local_path, _ = urllib.request.urlretrieve(uri) metadata = mutagen.File(local_path, easy=True) if metadata.tags: self._tags = metadata.tags title = self._tags.get(TAG_TITLE, []) ...
[ "def", "media", "(", "self", ",", "uri", ")", ":", "try", ":", "local_path", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "uri", ")", "metadata", "=", "mutagen", ".", "File", "(", "local_path", ",", "easy", "=", "True", ")", "i...
45.884615
0.001642
def _build_lv_grid(ding0_grid, network): """ Build eDisGo LV grid from Ding0 data Parameters ---------- ding0_grid: ding0.MVGridDing0 Ding0 MV grid object Returns ------- list of LVGrid LV grids dict Dictionary containing a mapping of LV stations in Ding0 to...
[ "def", "_build_lv_grid", "(", "ding0_grid", ",", "network", ")", ":", "lv_station_mapping", "=", "{", "}", "lv_grids", "=", "[", "]", "lv_grid_mapping", "=", "{", "}", "for", "la", "in", "ding0_grid", ".", "grid_district", ".", "_lv_load_areas", ":", "for", ...
41.443609
0.000532
def apply_template(template, *args, **kw): """Applies every callable in any Mapping or Iterable""" if six.callable(template): return template(*args, **kw) if isinstance(template, six.string_types): return template if isinstance(template, collections.Mapping): return template.__cl...
[ "def", "apply_template", "(", "template", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "six", ".", "callable", "(", "template", ")", ":", "return", "template", "(", "*", "args", ",", "*", "*", "kw", ")", "if", "isinstance", "(", "template...
48.727273
0.005495
def compute(self, cost_matrix): """ Compute the indexes for the lowest-cost pairings between rows and columns in the database. Returns a list of (row, column) tuples that can be used to traverse the matrix. :Parameters: cost_matrix : list of lists The...
[ "def", "compute", "(", "self", ",", "cost_matrix", ")", ":", "self", ".", "C", "=", "self", ".", "pad_matrix", "(", "cost_matrix", ")", "self", ".", "n", "=", "len", "(", "self", ".", "C", ")", "self", ".", "original_length", "=", "len", "(", "cost...
33.877193
0.005033