text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def bcc(self, bcc): ''' :param bcc: Email addresses for the 'Bcc' API field. :type bcc: :keyword:`list` or `str` ''' if isinstance(bcc, basestring): bcc = bcc.split(',') self._bcc = bcc
[ "def", "bcc", "(", "self", ",", "bcc", ")", ":", "if", "isinstance", "(", "bcc", ",", "basestring", ")", ":", "bcc", "=", "bcc", ".", "split", "(", "','", ")", "self", ".", "_bcc", "=", "bcc" ]
29.75
0.008163
def executemany(self, query, args): """Run several data against one query PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'. In other form of queries, just run :meth:`execute` many times. """ if not args: return m = RE_INSERT_VALUES.matc...
[ "def", "executemany", "(", "self", ",", "query", ",", "args", ")", ":", "if", "not", "args", ":", "return", "m", "=", "RE_INSERT_VALUES", ".", "match", "(", "query", ")", "if", "m", ":", "q_prefix", "=", "m", ".", "group", "(", "1", ")", "q_values"...
36.96
0.00211
def character_delta(self, char, *, store=True): """Return a dictionary of changes to ``char`` since previous call.""" ret = self.character_stat_delta(char, store=store) nodes = self.character_nodes_delta(char, store=store) chara = self._real.character[char] if nodes: ...
[ "def", "character_delta", "(", "self", ",", "char", ",", "*", ",", "store", "=", "True", ")", ":", "ret", "=", "self", ".", "character_stat_delta", "(", "char", ",", "store", "=", "store", ")", "nodes", "=", "self", ".", "character_nodes_delta", "(", "...
42.717949
0.002347
def from_packed(cls, packed): """Unpack diploid genotypes that have been bit-packed into single bytes. Parameters ---------- packed : ndarray, uint8, shape (n_variants, n_samples) Bit-packed diploid genotype array. Returns ------- g : Genotyp...
[ "def", "from_packed", "(", "cls", ",", "packed", ")", ":", "# check arguments", "packed", "=", "np", ".", "asarray", "(", "packed", ")", "check_ndim", "(", "packed", ",", "2", ")", "check_dtype", "(", "packed", ",", "'u1'", ")", "packed", "=", "memoryvie...
26
0.001951
def _submit_jobs(self, force, ipyclient, name_fields, name_separator, dry_run): """ Download the accessions into a the designated workdir. If file already exists it will only be overwritten if force=True. Temporary files are removed. ...
[ "def", "_submit_jobs", "(", "self", ",", "force", ",", "ipyclient", ",", "name_fields", ",", "name_separator", ",", "dry_run", ")", ":", "## get Run data with default fields (1,4,6,30)", "df", "=", "self", ".", "fetch_runinfo", "(", "range", "(", "31", ")", ",",...
39.087379
0.01187
def remote_update(self, updates): """ I am called by the worker's L{buildbot_worker.base.WorkerForBuilderBase.sendUpdate} so I can receive updates from the running remote command. @type updates: list of [object, int] @param updates: list of updates from the remote comma...
[ "def", "remote_update", "(", "self", ",", "updates", ")", ":", "updates", "=", "decode", "(", "updates", ")", "self", ".", "worker", ".", "messageReceivedFromWorker", "(", ")", "max_updatenum", "=", "0", "for", "(", "update", ",", "num", ")", "in", "upda...
39.4
0.001982
def _numbered_style(): """Create a numbered list style.""" style = ListStyle(name='_numbered_list') lls = ListLevelStyleNumber(level=1) lls.setAttribute('displaylevels', 1) lls.setAttribute('numsuffix', '. ') lls.setAttribute('numformat', '1') llp = ListLevelProperties() llp.setAttri...
[ "def", "_numbered_style", "(", ")", ":", "style", "=", "ListStyle", "(", "name", "=", "'_numbered_list'", ")", "lls", "=", "ListLevelStyleNumber", "(", "level", "=", "1", ")", "lls", ".", "setAttribute", "(", "'displaylevels'", ",", "1", ")", "lls", ".", ...
26.535714
0.001299
def _parse_coroutine(self): """ Parser state machine. Every 'yield' expression returns the next byte. """ while True: d = yield if d == int2byte(0): pass # NOP # Go to state escaped. elif d == IAC: ...
[ "def", "_parse_coroutine", "(", "self", ")", ":", "while", "True", ":", "d", "=", "yield", "if", "d", "==", "int2byte", "(", "0", ")", ":", "pass", "# NOP", "# Go to state escaped.", "elif", "d", "==", "IAC", ":", "d2", "=", "yield", "if", "d2", "=="...
28.87234
0.001426
def clean(self): """ Se agrega la verificación que las contraseñas ingresadas sean iguales """ cleaned_data = super().clean() psw = cleaned_data.get("password") pswr = cleaned_data.get("password_repetir") if psw != pswr: self.add_error('password', ValidationError(_('Las claves ingresadas...
[ "def", "clean", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", ")", ".", "clean", "(", ")", "psw", "=", "cleaned_data", ".", "get", "(", "\"password\"", ")", "pswr", "=", "cleaned_data", ".", "get", "(", "\"password_repetir\"", ")", "if", "p...
34.6
0.008451
def parse(text): '''Parse a geoid from text and return a tuple (level, code, validity)''' if '@' in text: spatial, validity = text.split('@') else: spatial = text validity = 'latest' if ':' not in spatial: raise GeoIDError('Bad GeoID format: {0}'.format(text)) # count...
[ "def", "parse", "(", "text", ")", ":", "if", "'@'", "in", "text", ":", "spatial", ",", "validity", "=", "text", ".", "split", "(", "'@'", ")", "else", ":", "spatial", "=", "text", "validity", "=", "'latest'", "if", "':'", "not", "in", "spatial", ":...
34.133333
0.001901
def add_user_to_template(self, template_id, account_id=None, email_address=None): ''' Gives the specified Account access to the specified Template Args: template_id (str): The id of the template to give the account access to account_id (str): The id of the account t...
[ "def", "add_user_to_template", "(", "self", ",", "template_id", ",", "account_id", "=", "None", ",", "email_address", "=", "None", ")", ":", "return", "self", ".", "_add_remove_user_template", "(", "self", ".", "TEMPLATE_ADD_USER_URL", ",", "template_id", ",", "...
42.125
0.01016
def get_top_n_action_types(self, top_n): """Returns the top N actions by count.""" # Count action types action_type_to_counts = dict() for action in self.actions: actiontype = action.actiontype if actiontype not in action_type_to_counts: action_typ...
[ "def", "get_top_n_action_types", "(", "self", ",", "top_n", ")", ":", "# Count action types", "action_type_to_counts", "=", "dict", "(", ")", "for", "action", "in", "self", ".", "actions", ":", "actiontype", "=", "action", ".", "actiontype", "if", "actiontype", ...
39.1
0.001248
def as_dict(self): """ Return a ditionary mapping time slide IDs to offset dictionaries. """ d = {} for row in self: if row.time_slide_id not in d: d[row.time_slide_id] = offsetvector.offsetvector() if row.instrument in d[row.time_slide_id]: raise KeyError("'%s': duplicate instrument '%s'" % (...
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "{", "}", "for", "row", "in", "self", ":", "if", "row", ".", "time_slide_id", "not", "in", "d", ":", "d", "[", "row", ".", "time_slide_id", "]", "=", "offsetvector", ".", "offsetvector", "(", ")", ...
31.307692
0.0358
def expected_peer_units(): """Get a generator for units we expect to join peer relation based on goal-state. The local unit is excluded from the result to make it easy to gauge completion of all peers joining the relation with existing hook tools. Example usage: log('peer {} of {} joined peer ...
[ "def", "expected_peer_units", "(", ")", ":", "if", "not", "has_juju_version", "(", "\"2.4.0\"", ")", ":", "# goal-state first appeared in 2.4.0.", "raise", "NotImplementedError", "(", "\"goal-state\"", ")", "_goal_state", "=", "goal_state", "(", ")", "return", "(", ...
34.48
0.001129
def _register_entry_point_module(self, entry_point, module): """ Private method that registers an entry_point with a provided module. """ records_map = self._map_entry_point_module(entry_point, module) self.store_records_for_package(entry_point, list(records_map.keys()))...
[ "def", "_register_entry_point_module", "(", "self", ",", "entry_point", ",", "module", ")", ":", "records_map", "=", "self", ".", "_map_entry_point_module", "(", "entry_point", ",", "module", ")", "self", ".", "store_records_for_package", "(", "entry_point", ",", ...
40.814815
0.001773
def parse_params(args): """ Parse the params file args, create and return Assembly object.""" ## check that params.txt file is correctly formatted. try: with open(args.params) as paramsin: plines = paramsin.readlines() except IOError as _: sys.exit(" No params file found") ...
[ "def", "parse_params", "(", "args", ")", ":", "## check that params.txt file is correctly formatted.", "try", ":", "with", "open", "(", "args", ".", "params", ")", "as", "paramsin", ":", "plines", "=", "paramsin", ".", "readlines", "(", ")", "except", "IOError",...
36.533333
0.008294
def get_uri_template(urlname, args=None, prefix=""): ''' Utility function to return an URI Template from a named URL in django Copied from django-digitalpaper. Restrictions: - Only supports named urls! i.e. url(... name="toto") - Only support one namespace level - Only returns the first URL...
[ "def", "get_uri_template", "(", "urlname", ",", "args", "=", "None", ",", "prefix", "=", "\"\"", ")", ":", "def", "_convert", "(", "template", ",", "args", "=", "None", ")", ":", "\"\"\"URI template converter\"\"\"", "if", "not", "args", ":", "args", "=", ...
43.981132
0.00042
def handle(cls, value, **kwargs): """Split the supplied string on the given delimiter, providing a list. Format of value: <delimiter>::<value> For example: Subnets: ${split ,::subnet-1,subnet-2,subnet-3} Would result in the variable `Subnets` getting a list c...
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "try", ":", "delimiter", ",", "text", "=", "value", ".", "split", "(", "\"::\"", ",", "1", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Invalid value for ...
33.16129
0.00189
def _merge_a_into_b_simple(self, a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. Do not do any checking. """ for k, v in a.items(): b[k] = v return b
[ "def", "_merge_a_into_b_simple", "(", "self", ",", "a", ",", "b", ")", ":", "for", "k", ",", "v", "in", "a", ".", "items", "(", ")", ":", "b", "[", "k", "]", "=", "v", "return", "b" ]
39.428571
0.010638
def remove_other_ldflags(self, flags, target_name=None, configuration_name=None): """ Removes the given flags from the OTHER_LDFLAGS section of the target on the configurations :param flags: A string or array of strings. If none, removes all values from the flag. :param target_name: Targ...
[ "def", "remove_other_ldflags", "(", "self", ",", "flags", ",", "target_name", "=", "None", ",", "configuration_name", "=", "None", ")", ":", "self", ".", "remove_flags", "(", "XCBuildConfigurationFlags", ".", "OTHER_LDFLAGS", ",", "flags", ",", "target_name", ",...
70.888889
0.012384
def maybe_infer_freq(freq): """ Comparing a DateOffset to the string "infer" raises, so we need to be careful about comparisons. Make a dummy variable `freq_infer` to signify the case where the given freq is "infer" and set freq to None to avoid comparison trouble later on. Parameters ----...
[ "def", "maybe_infer_freq", "(", "freq", ")", ":", "freq_infer", "=", "False", "if", "not", "isinstance", "(", "freq", ",", "DateOffset", ")", ":", "# if a passed freq is None, don't infer automatically", "if", "freq", "!=", "'infer'", ":", "freq", "=", "frequencie...
28.76
0.001346
def has_reduction(expr): """Does `expr` contain a reduction? Parameters ---------- expr : ibis.expr.types.Expr An ibis expression Returns ------- truth_value : bool Whether or not there's at least one reduction in `expr` Notes ----- The ``isinstance(op, ops.Tab...
[ "def", "has_reduction", "(", "expr", ")", ":", "def", "fn", "(", "expr", ")", ":", "op", "=", "expr", ".", "op", "(", ")", "if", "isinstance", "(", "op", ",", "ops", ".", "TableNode", ")", ":", "# don't go below any table nodes", "return", "lin", ".", ...
25.933333
0.001239
def onCall(self, n): #pylint: disable=invalid-name """ Adds a condition for when the stub is called. When the condition is met, a special return value can be returned. Adds the specified call number into the condition list. For example, when the stub function is called the secon...
[ "def", "onCall", "(", "self", ",", "n", ")", ":", "#pylint: disable=invalid-name", "cond_oncall", "=", "n", "+", "1", "return", "_SinonStubCondition", "(", "copy", "=", "self", ".", "_copy", ",", "oncall", "=", "cond_oncall", ",", "cond_args", "=", "self", ...
43.5
0.010225
def either(self): """Transform pattern into an equivalent, with only top-level Either.""" # Currently the pattern will not be equivalent, but more "narrow", # although good enough to reason about list arguments. if not hasattr(self, 'children'): return Either(Required(self)) ...
[ "def", "either", "(", "self", ")", ":", "# Currently the pattern will not be equivalent, but more \"narrow\",", "# although good enough to reason about list arguments.", "if", "not", "hasattr", "(", "self", ",", "'children'", ")", ":", "return", "Either", "(", "Required", "...
50.375
0.001826
def log_part(self): """ Log what has been captured so far """ self.cap_stdout.seek(self._pos) text = self.cap_stdout.read() self._pos = self.cap_stdout.tell() self.parts.append(text) self.text = text
[ "def", "log_part", "(", "self", ")", ":", "self", ".", "cap_stdout", ".", "seek", "(", "self", ".", "_pos", ")", "text", "=", "self", ".", "cap_stdout", ".", "read", "(", ")", "self", ".", "_pos", "=", "self", ".", "cap_stdout", ".", "tell", "(", ...
34.428571
0.008097
def componentsintobranch(idf, branch, listofcomponents, fluid=None): """insert a list of components into a branch fluid is only needed if there are air and water nodes in same object fluid is Air or Water or ''. if the fluid is Steam, use Water""" if fluid is None: fluid = '' componentli...
[ "def", "componentsintobranch", "(", "idf", ",", "branch", ",", "listofcomponents", ",", "fluid", "=", "None", ")", ":", "if", "fluid", "is", "None", ":", "fluid", "=", "''", "componentlist", "=", "[", "item", "[", "0", "]", "for", "item", "in", "listof...
48.172414
0.002105
def awaitTermination(self, timeout=None): """Waits for the termination of `this` query, either by :func:`query.stop()` or by an exception. If the query has terminated with an exception, then the exception will be thrown. If `timeout` is set, it returns whether the query has terminated or not wit...
[ "def", "awaitTermination", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", ":", "if", "not", "isinstance", "(", "timeout", ",", "(", "int", ",", "float", ")", ")", "or", "timeout", "<", "0", ":", "raise", "...
57.333333
0.00858
def standard(target, mol_weight='pore.molecular_weight', density='pore.density'): r""" Calculates the molar density from the molecular weight and mass density Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This con...
[ "def", "standard", "(", "target", ",", "mol_weight", "=", "'pore.molecular_weight'", ",", "density", "=", "'pore.density'", ")", ":", "MW", "=", "target", "[", "mol_weight", "]", "rho", "=", "target", "[", "density", "]", "value", "=", "rho", "/", "MW", ...
31.590909
0.001397
def scale_timeseries_unit(tsunit, scaling='density'): """Scale the unit of a `TimeSeries` to match that of a `FrequencySeries` Parameters ---------- tsunit : `~astropy.units.UnitBase` input unit from `TimeSeries` scaling : `str` type of frequency series, either 'density' for a PSD, ...
[ "def", "scale_timeseries_unit", "(", "tsunit", ",", "scaling", "=", "'density'", ")", ":", "# set units", "if", "scaling", "==", "'density'", ":", "baseunit", "=", "units", ".", "Hertz", "elif", "scaling", "==", "'spectrum'", ":", "baseunit", "=", "units", "...
28.928571
0.001195
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv # setup command line parser parser = U.OptionParser(version="%prog version: $Id$", usage=usage, ...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "# setup command line parser", "parser", "=", "U", ".", "OptionParser", "(", "version", "=", "\"%prog version: $Id$\"", ",", "usage", "=", ...
32.094595
0.000408
def get_err(snr): """ Get approximate scatters from SNR as determined in the code, snr_test.py Order: Teff, logg, MH, CM, NM, alpha """ quad_terms = np.array( [3.11e-3, 1.10e-5, 6.95e-6, 5.05e-6, 4.65e-6, 4.10e-6]) lin_terms = np.array( [-0.869, -2.07e-3, -1.40e-3, -1.03e-3,...
[ "def", "get_err", "(", "snr", ")", ":", "quad_terms", "=", "np", ".", "array", "(", "[", "3.11e-3", ",", "1.10e-5", ",", "6.95e-6", ",", "5.05e-6", ",", "4.65e-6", ",", "4.10e-6", "]", ")", "lin_terms", "=", "np", ".", "array", "(", "[", "-", "0.86...
37.75
0.009044
def text2text_distill_iterator(source_txt_path, target_txt_path, distill_txt_path): """Yield dicts for Text2TextProblem.generate_samples from lines of files.""" for inputs, targets, dist_targets in zip( txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path), ...
[ "def", "text2text_distill_iterator", "(", "source_txt_path", ",", "target_txt_path", ",", "distill_txt_path", ")", ":", "for", "inputs", ",", "targets", ",", "dist_targets", "in", "zip", "(", "txt_line_iterator", "(", "source_txt_path", ")", ",", "txt_line_iterator", ...
61.714286
0.009132
def series_lstrip(series, startswith='http://', ignorecase=True): """ Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str """ return series_strip(series, startswith=startswith, endswith=None, startsorendswith=None, ignorecase=ignorecase)
[ "def", "series_lstrip", "(", "series", ",", "startswith", "=", "'http://'", ",", "ignorecase", "=", "True", ")", ":", "return", "series_strip", "(", "series", ",", "startswith", "=", "startswith", ",", "endswith", "=", "None", ",", "startsorendswith", "=", "...
90.666667
0.010949
def export_dict(mesh, encoding=None): """ Export a mesh to a dict Parameters ------------ mesh : Trimesh object Mesh to be exported encoding : str, or None 'base64' Returns ------------- """ def encode(item, dtype=None): if encoding is No...
[ "def", "export_dict", "(", "mesh", ",", "encoding", "=", "None", ")", ":", "def", "encode", "(", "item", ",", "dtype", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "return", "item", ".", "tolist", "(", ")", "else", ":", "if", "dtype"...
28.44186
0.000791
def fulfill(self, method, *args, **kwargs): """ Fulfill an HTTP request to Keen's API. """ return getattr(self.session, method)(*args, **kwargs)
[ "def", "fulfill", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "getattr", "(", "self", ".", "session", ",", "method", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
31.6
0.012346
def iterateBlocksFrom(block): """Generator, which iterates QTextBlocks from block until the End of a document But, yields not more than MAX_SEARCH_OFFSET_LINES """ count = 0 while block.isValid() and count < MAX_SEARCH_OFFSET_LINES: yield block block = blo...
[ "def", "iterateBlocksFrom", "(", "block", ")", ":", "count", "=", "0", "while", "block", ".", "isValid", "(", ")", "and", "count", "<", "MAX_SEARCH_OFFSET_LINES", ":", "yield", "block", "block", "=", "block", ".", "next", "(", ")", "count", "+=", "1" ]
38.222222
0.008523
def in_hours(self, office=None, when=None): """ Finds if it is business hours in the given office. :param office: Office ID to look up, or None to check if any office is in business hours. :type office: str or None :param datetime.datetime when: When to check the office is open, or None for now. :returns...
[ "def", "in_hours", "(", "self", ",", "office", "=", "None", ",", "when", "=", "None", ")", ":", "if", "when", "==", "None", ":", "when", "=", "datetime", ".", "now", "(", "tz", "=", "utc", ")", "if", "office", "==", "None", ":", "for", "office", ...
23.172414
0.035714
def project_drawn(cb, msg): """ Projects a drawn element to the declared coordinate system """ stream = cb.streams[0] old_data = stream.data stream.update(data=msg['data']) element = stream.element stream.update(data=old_data) proj = cb.plot.projection if not isinstance(element, ...
[ "def", "project_drawn", "(", "cb", ",", "msg", ")", ":", "stream", "=", "cb", ".", "streams", "[", "0", "]", "old_data", "=", "stream", ".", "data", "stream", ".", "update", "(", "data", "=", "msg", "[", "'data'", "]", ")", "element", "=", "stream"...
29.866667
0.002165
def look(self): """Look at the next token.""" old_token = next(self) result = self.current self.push(result) self.current = old_token return result
[ "def", "look", "(", "self", ")", ":", "old_token", "=", "next", "(", "self", ")", "result", "=", "self", ".", "current", "self", ".", "push", "(", "result", ")", "self", ".", "current", "=", "old_token", "return", "result" ]
27
0.010256
def compute_score(subtitle, video, hearing_impaired=None): """Compute the score of the `subtitle` against the `video` with `hearing_impaired` preference. :func:`compute_score` uses the :meth:`Subtitle.get_matches <subliminal.subtitle.Subtitle.get_matches>` method and applies the scores (either from :data:`...
[ "def", "compute_score", "(", "subtitle", ",", "video", ",", "hearing_impaired", "=", "None", ")", ":", "logger", ".", "info", "(", "'Computing score of %r for video %r with %r'", ",", "subtitle", ",", "video", ",", "dict", "(", "hearing_impaired", "=", "hearing_im...
40.369231
0.002232
def make_zone_file(json_zone_file_input, origin=None, ttl=None, template=None): """ Generate the DNS zonefile, given a json-encoded description of the zone file (@json_zone_file) and the template to fill in (@template) json_zone_file = { "$origin": origin server, "$ttl": default time...
[ "def", "make_zone_file", "(", "json_zone_file_input", ",", "origin", "=", "None", ",", "ttl", "=", "None", ",", "template", "=", "None", ")", ":", "if", "template", "is", "None", ":", "template", "=", "DEFAULT_TEMPLATE", "[", ":", "]", "# careful...", "jso...
38.55
0.001686
def _traverse_options(cls, obj, opt_type, opts, specs=None, keyfn=None, defaults=True): """ Traverses the supplied object getting all options in opts for the specified opt_type and specs. Also takes into account the plotting class defaults for plot options. If a keyfn is supplied...
[ "def", "_traverse_options", "(", "cls", ",", "obj", ",", "opt_type", ",", "opts", ",", "specs", "=", "None", ",", "keyfn", "=", "None", ",", "defaults", "=", "True", ")", ":", "def", "lookup", "(", "x", ")", ":", "\"\"\"\n Looks up options for o...
46.075
0.002125
def _upload_dir_icommands_cli(local_dir, irods_dir, config=None, metadata=None): """ Upload directory recursively via the standard icommands CLI. example: irsync -Kvar -R $resource $local_dir i:$irods_dir go to https://docs.irods.org/4.2.0/icommands/user/#irsync for more info """ args = ["-K","...
[ "def", "_upload_dir_icommands_cli", "(", "local_dir", ",", "irods_dir", ",", "config", "=", "None", ",", "metadata", "=", "None", ")", ":", "args", "=", "[", "\"-K\"", ",", "\"-v\"", ",", "\"-a\"", ",", "\"-r\"", "]", "if", "config", ":", "if", "config",...
37.933333
0.010292
def get_source_and_pgp_key(source_and_key): """Look for a pgp key ID or ascii-armor key in the given input. :param source_and_key: Sting, "source_spec|keyid" where '|keyid' is optional. :returns (source_spec, key_id OR None) as a tuple. Returns None for key_id if there was no '|' in the so...
[ "def", "get_source_and_pgp_key", "(", "source_and_key", ")", ":", "try", ":", "source", ",", "key", "=", "source_and_key", ".", "split", "(", "'|'", ",", "2", ")", "return", "source", ",", "key", "or", "None", "except", "ValueError", ":", "return", "source...
37.692308
0.001992
def get_running_step_changes(write: bool = False) -> list: """...""" project = cd.project.get_internal_project() running_steps = list(filter( lambda step: step.is_running, project.steps )) def get_changes(step): step_data = writing.step_writer.serialize(step) if wr...
[ "def", "get_running_step_changes", "(", "write", ":", "bool", "=", "False", ")", "->", "list", ":", "project", "=", "cd", ".", "project", ".", "get_internal_project", "(", ")", "running_steps", "=", "list", "(", "filter", "(", "lambda", "step", ":", "step"...
25.304348
0.001656
def _generate_base_namespace_module(self, api, namespace): """Creates a module for the namespace. All data types and routes are represented as Python classes.""" self.cur_namespace = namespace generate_module_header(self) if namespace.doc is not None: self.emit('"""...
[ "def", "_generate_base_namespace_module", "(", "self", ",", "api", ",", "namespace", ")", ":", "self", ".", "cur_namespace", "=", "namespace", "generate_module_header", "(", "self", ")", "if", "namespace", ".", "doc", "is", "not", "None", ":", "self", ".", "...
42.06383
0.000989
def normal_right_down(self, event): """ Handles the right mouse button being clicked when the tool is in the 'normal' state. If the event occurred on this tool's component (or any contained component of that component), the method opens a context menu with menu items from any to...
[ "def", "normal_right_down", "(", "self", ",", "event", ")", ":", "x", "=", "event", ".", "x", "y", "=", "event", ".", "y", "# First determine what component or components we are going to hittest", "# on. If our component is a container, then we add its non-container", "# com...
34.95
0.001392
def find_window(self, highlight_locations): """Getting the HIGHLIGHT_NUM_CHARS_BEFORE_MATCH setting to find how many characters before the first word found should be removed from the window """ if len(self.text_block) <= self.max_length: return (0, self.max_length) ...
[ "def", "find_window", "(", "self", ",", "highlight_locations", ")", ":", "if", "len", "(", "self", ".", "text_block", ")", "<=", "self", ".", "max_length", ":", "return", "(", "0", ",", "self", ".", "max_length", ")", "num_chars_before", "=", "getattr", ...
30.115385
0.002475
def start(self, context): """Construct the SQLAlchemy engine and session factory.""" if __debug__: log.info("Connecting SQLAlchemy database layer.", extra=dict( uri = redact_uri(self.uri), config = self.config, alias = self.alias, )) # Construct the engine. engine = self.engine = cre...
[ "def", "start", "(", "self", ",", "context", ")", ":", "if", "__debug__", ":", "log", ".", "info", "(", "\"Connecting SQLAlchemy database layer.\"", ",", "extra", "=", "dict", "(", "uri", "=", "redact_uri", "(", "self", ".", "uri", ")", ",", "config", "=...
27.095238
0.056027
def axis_sort(S, axis=-1, index=False, value=None): '''Sort an array along its rows or columns. Examples -------- Visualize NMF output for a spectrogram S >>> # Sort the columns of W by peak frequency bin >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> S = np.abs(librosa.st...
[ "def", "axis_sort", "(", "S", ",", "axis", "=", "-", "1", ",", "index", "=", "False", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "np", ".", "argmax", "if", "S", ".", "ndim", "!=", "2", ":", "raise", "...
28.894737
0.000352
def dir(base_dir: str, rr_id: str) -> str: """ Return correct subdirectory of input base dir for artifacts corresponding to input rev reg id. :param base_dir: base directory for tails files, thereafter split by cred def id :param rr_id: rev reg id """ return join(base_d...
[ "def", "dir", "(", "base_dir", ":", "str", ",", "rr_id", ":", "str", ")", "->", "str", ":", "return", "join", "(", "base_dir", ",", "rev_reg_id2cred_def_id", "(", "rr_id", ")", ")" ]
38.444444
0.011299
def pad_faces(im, faces): r""" Pads the input image at specified faces. This shape of image is same as the output image of add_boundary_regions function. Parameters ---------- im : ND_array The image that needs to be padded faces : list of strings Labels indicating where im...
[ "def", "pad_faces", "(", "im", ",", "faces", ")", ":", "if", "im", ".", "ndim", "!=", "im", ".", "squeeze", "(", ")", ".", "ndim", ":", "warnings", ".", "warn", "(", "'Input image conains a singleton axis:'", "+", "str", "(", "im", ".", "shape", ")", ...
32.857143
0.000603
def autocomplete(force=False): " Shell autocompletion support. " if 'MAKESITE_AUTO_COMPLETE' not in environ and not force: return commands = filter(lambda cmd: cmd != 'main', ACTIONS.keys()) cwords = environ['COMP_WORDS'].split()[1:] cword = int(environ['COMP_CWORD']) try: cu...
[ "def", "autocomplete", "(", "force", "=", "False", ")", ":", "if", "'MAKESITE_AUTO_COMPLETE'", "not", "in", "environ", "and", "not", "force", ":", "return", "commands", "=", "filter", "(", "lambda", "cmd", ":", "cmd", "!=", "'main'", ",", "ACTIONS", ".", ...
41.804878
0.002281
def setsebools(pairs, persist=False): ''' Set the value of multiple booleans CLI Example: .. code-block:: bash salt '*' selinux.setsebools '{virt_use_usb: on, squid_use_tproxy: off}' ''' if not isinstance(pairs, dict): return {} if persist: cmd = 'setsebool -P ' ...
[ "def", "setsebools", "(", "pairs", ",", "persist", "=", "False", ")", ":", "if", "not", "isinstance", "(", "pairs", ",", "dict", ")", ":", "return", "{", "}", "if", "persist", ":", "cmd", "=", "'setsebool -P '", "else", ":", "cmd", "=", "'setsebool '",...
26.526316
0.001916
def interpret(self, msg): """ Create a slide show """ self.captions = msg.get('captions', '.') for item in msg['slides']: self.add(item)
[ "def", "interpret", "(", "self", ",", "msg", ")", ":", "self", ".", "captions", "=", "msg", ".", "get", "(", "'captions'", ",", "'.'", ")", "for", "item", "in", "msg", "[", "'slides'", "]", ":", "self", ".", "add", "(", "item", ")" ]
25.142857
0.016484
def ylim(name, min, max): """ This function will set the y axis range displayed for a specific tplot variable. Parameters: name : str The name of the tplot variable that you wish to set y limits for. min : flt The start of the y axis. max : flt ...
[ "def", "ylim", "(", "name", ",", "min", ",", "max", ")", ":", "if", "name", "not", "in", "data_quants", ".", "keys", "(", ")", ":", "print", "(", "\"That name is currently not in pytplot.\"", ")", "return", "temp_data_quant", "=", "data_quants", "[", "name",...
27.15625
0.011111
def arping(net, timeout=2, cache=0, verbose=None, **kargs): """Send ARP who-has requests to determine which hosts are up arping(net, [cache=0,] [iface=conf.iface,] [verbose=conf.verb]) -> None Set cache=True if you want arping to modify internal ARP-Cache""" if verbose is None: verbose = conf.verb a...
[ "def", "arping", "(", "net", ",", "timeout", "=", "2", ",", "cache", "=", "0", ",", "verbose", "=", "None", ",", "*", "*", "kargs", ")", ":", "if", "verbose", "is", "None", ":", "verbose", "=", "conf", ".", "verb", "ans", ",", "unans", "=", "sr...
43.875
0.008368
def audit(*args): """Decorator to register an audit. These are used to generate audits that can be run on a deployed system that matches the given configuration :param args: List of functions to filter tests against :type args: List[Callable[Dict]] """ def wrapper(f): test_name = f...
[ "def", "audit", "(", "*", "args", ")", ":", "def", "wrapper", "(", "f", ")", ":", "test_name", "=", "f", ".", "__name__", "if", "_audits", ".", "get", "(", "test_name", ")", ":", "raise", "RuntimeError", "(", "\"Test name '{}' used more than once\"", ".", ...
34.086957
0.001241
def services(self): """ returns the services in the current folder """ self._services = [] params = { "f" : "json" } json_dict = self._get(url=self._currentURL, param_dict=params, securi...
[ "def", "services", "(", "self", ")", ":", "self", ".", "_services", "=", "[", "]", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "json_dict", "=", "self", ".", "_get", "(", "url", "=", "self", ".", "_currentURL", ",", "param_dict", "=", "params"...
44.761905
0.008333
def estimate_rotation(self, camera, ransac_threshold=7.0): """Estimate the rotation between first and last frame It uses RANSAC where the error metric is the reprojection error of the points from the last frame to the first frame. Parameters ----------------- camera : C...
[ "def", "estimate_rotation", "(", "self", ",", "camera", ",", "ransac_threshold", "=", "7.0", ")", ":", "if", "self", ".", "axis", "is", "None", ":", "x", "=", "self", ".", "points", "[", ":", ",", "0", ",", ":", "]", ".", "T", "y", "=", "self", ...
47.806452
0.011905
def collapse( self, direction ): """ Collapses this splitter handle before or after other widgets based on \ the inputed CollapseDirection. :param direction | <XSplitterHandle.CollapseDirection> :return <bool> | success """ if ( self.isC...
[ "def", "collapse", "(", "self", ",", "direction", ")", ":", "if", "(", "self", ".", "isCollapsed", "(", ")", ")", ":", "return", "False", "splitter", "=", "self", ".", "parent", "(", ")", "if", "(", "not", "splitter", ")", ":", "return", "False", "...
32.133333
0.019134
def stop_reactor_on_state_machine_finish(state_machine): """ Wait for a state machine to be finished and stops the reactor :param state_machine: the state machine to synchronize with """ wait_for_state_machine_finished(state_machine) from twisted.internet import reactor if reactor.running: ...
[ "def", "stop_reactor_on_state_machine_finish", "(", "state_machine", ")", ":", "wait_for_state_machine_finished", "(", "state_machine", ")", "from", "twisted", ".", "internet", "import", "reactor", "if", "reactor", ".", "running", ":", "plugins", ".", "run_hook", "(",...
39.5
0.002475
def put(self, url, body=None, **kwargs): """ Send a PUT request. :param str url: Sub URL for the request. You MUST not specify neither base url nor api version prefix. :param dict body: (optional) Dictionary of body attributes that will be wrapped with envelope and json encoded. ...
[ "def", "put", "(", "self", ",", "url", ",", "body", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'put'", ",", "url", ",", "body", "=", "body", ",", "*", "*", "kwargs", ")" ]
52.083333
0.009434
def df_nc(self,x): ''' Wrapper of the derivative of *f*: takes an input x with size of the not fixed dimensions expands it and evaluates the gradient of the entire function. ''' x = np.atleast_2d(x) xx = self.context_manager._expand_vector(x) _, df_nocontext_xx = ...
[ "def", "df_nc", "(", "self", ",", "x", ")", ":", "x", "=", "np", ".", "atleast_2d", "(", "x", ")", "xx", "=", "self", ".", "context_manager", ".", "_expand_vector", "(", "x", ")", "_", ",", "df_nocontext_xx", "=", "self", ".", "f_df", "(", "xx", ...
44.8
0.013129
def Areml_eigh(self): """compute the eigenvalue decomposition of Astar""" s,U = LA.eigh(self.Areml(),lower=True) i_pos = (s>1e-10) s = s[i_pos] U = U[:,i_pos] return s,U
[ "def", "Areml_eigh", "(", "self", ")", ":", "s", ",", "U", "=", "LA", ".", "eigh", "(", "self", ".", "Areml", "(", ")", ",", "lower", "=", "True", ")", "i_pos", "=", "(", "s", ">", "1e-10", ")", "s", "=", "s", "[", "i_pos", "]", "U", "=", ...
30.142857
0.032258
def competition_files(self): """List of competition files.""" command = [ "kaggle", "datasets" if "/" in self._competition_name else "competitions", "files", "-v", self._competition_name, ] output = _run_kaggle_command(command, self._competition_name) return s...
[ "def", "competition_files", "(", "self", ")", ":", "command", "=", "[", "\"kaggle\"", ",", "\"datasets\"", "if", "\"/\"", "in", "self", ".", "_competition_name", "else", "\"competitions\"", ",", "\"files\"", ",", "\"-v\"", ",", "self", ".", "_competition_name", ...
30.153846
0.002475
def update_properties_cache(sender, instance, action, reverse, model, pk_set, **kwargs): "Property cache actualization at POI save. It will not work yet after property removal." if action == 'post_add': instance.save_properties_cache()
[ "def", "update_properties_cache", "(", "sender", ",", "instance", ",", "action", ",", "reverse", ",", "model", ",", "pk_set", ",", "*", "*", "kwargs", ")", ":", "if", "action", "==", "'post_add'", ":", "instance", ".", "save_properties_cache", "(", ")" ]
62
0.011952
def get(self, ids, **kwargs): """ Method to get interfaces by their ids. :param ids: List containing identifiers of interfaces. :return: Dict containing interfaces. """ url = build_uri_with_ids('api/v3/interface/%s/', ids) return super(ApiInterfaceRequest, self)...
[ "def", "get", "(", "self", ",", "ids", ",", "*", "*", "kwargs", ")", ":", "url", "=", "build_uri_with_ids", "(", "'api/v3/interface/%s/'", ",", "ids", ")", "return", "super", "(", "ApiInterfaceRequest", ",", "self", ")", ".", "get", "(", "self", ".", "...
34.6
0.008451
def solveConsKinkedR(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rboro,Rsave, PermGroFac,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool): ''' Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks), and ...
[ "def", "solveConsKinkedR", "(", "solution_next", ",", "IncomeDstn", ",", "LivPrb", ",", "DiscFac", ",", "CRRA", ",", "Rboro", ",", "Rsave", ",", "PermGroFac", ",", "BoroCnstArt", ",", "aXtraGrid", ",", "vFuncBool", ",", "CubicBool", ")", ":", "solver", "=", ...
46.5
0.009543
def parse(url, engine=None, conn_max_age=0, ssl_require=False): """Parses a database URL.""" if url == 'sqlite://:memory:': # this is a special case, because if we pass this URL into # urlparse, urlparse will choke trying to interpret "memory" # as a port number return { ...
[ "def", "parse", "(", "url", ",", "engine", "=", "None", ",", "conn_max_age", "=", "0", ",", "ssl_require", "=", "False", ")", ":", "if", "url", "==", "'sqlite://:memory:'", ":", "# this is a special case, because if we pass this URL into", "# urlparse, urlparse will c...
30.837209
0.001096
def load_plugins(self, directory): """ Loads plugins from the specified directory. `directory` is the full path to a directory containing python modules which each contain a subclass of the Plugin class. There is no criteria for a valid plugin at this level - any python ...
[ "def", "load_plugins", "(", "self", ",", "directory", ")", ":", "# walk directory", "for", "filename", "in", "os", ".", "listdir", "(", "directory", ")", ":", "# path to file", "filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filena...
39.607143
0.001761
def all_low_level_calls(self): """ recursive version of low_level calls """ if self._all_low_level_calls is None: self._all_low_level_calls = self._explore_functions(lambda x: x.low_level_calls) return self._all_low_level_calls
[ "def", "all_low_level_calls", "(", "self", ")", ":", "if", "self", ".", "_all_low_level_calls", "is", "None", ":", "self", ".", "_all_low_level_calls", "=", "self", ".", "_explore_functions", "(", "lambda", "x", ":", "x", ".", "low_level_calls", ")", "return",...
44.333333
0.01107
def getblockhash(self, index: int) -> str: '''Returns the hash of the block at ; index 0 is the genesis block.''' return cast(str, self.api_fetch('getblockhash?index=' + str(index)))
[ "def", "getblockhash", "(", "self", ",", "index", ":", "int", ")", "->", "str", ":", "return", "cast", "(", "str", ",", "self", ".", "api_fetch", "(", "'getblockhash?index='", "+", "str", "(", "index", ")", ")", ")" ]
49
0.01005
def _start_dequeue_thread(self): """ Internal method to start dequeue thread. """ self._dequeueThread = Thread(target=self._dequeue_function) self._dequeueThread.daemon = True self._dequeueThread.start()
[ "def", "_start_dequeue_thread", "(", "self", ")", ":", "self", ".", "_dequeueThread", "=", "Thread", "(", "target", "=", "self", ".", "_dequeue_function", ")", "self", ".", "_dequeueThread", ".", "daemon", "=", "True", "self", ".", "_dequeueThread", ".", "st...
41.4
0.028436
def set_portfast(self, name, value=None, default=False, disable=False): """Configures the portfast value for the specified interface Args: name (string): The interface identifier to configure. The name must be the full interface name (eg Ethernet1, not Et1) val...
[ "def", "set_portfast", "(", "self", ",", "name", ",", "value", "=", "None", ",", "default", "=", "False", ",", "disable", "=", "False", ")", ":", "if", "value", "is", "False", ":", "disable", "=", "True", "string", "=", "'spanning-tree portfast'", "cmds"...
37.580645
0.001674
def height(cls, path): """ Get the locally-stored block height """ if os.path.exists( path ): sb = os.stat( path ) h = (sb.st_size / BLOCK_HEADER_SIZE) - 1 return h else: return None
[ "def", "height", "(", "cls", ",", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "sb", "=", "os", ".", "stat", "(", "path", ")", "h", "=", "(", "sb", ".", "st_size", "/", "BLOCK_HEADER_SIZE", ")", "-", "1", "...
26.1
0.022222
def __create_driver_from_browser_config(self): ''' Reads the config value for browser type. ''' try: browser_type = self._config_reader.get( WebDriverFactory.BROWSER_TYPE_CONFIG) except KeyError: _wtflog("%s missing is missing from config f...
[ "def", "__create_driver_from_browser_config", "(", "self", ")", ":", "try", ":", "browser_type", "=", "self", ".", "_config_reader", ".", "get", "(", "WebDriverFactory", ".", "BROWSER_TYPE_CONFIG", ")", "except", "KeyError", ":", "_wtflog", "(", "\"%s missing is mis...
40.757576
0.002179
async def Append(self, stream) -> None: """Append a message directly to a user's mailbox. If the backend session defines a :attr:`~pymap.interfaces.session.SessionInterface.filter_set`, the active filter implementation will be applied to the appended message, such that the messa...
[ "async", "def", "Append", "(", "self", ",", "stream", ")", "->", "None", ":", "from", ".", "grpc", ".", "admin_pb2", "import", "AppendRequest", ",", "AppendResponse", ",", "ERROR_RESPONSE", "request", ":", "AppendRequest", "=", "await", "stream", ".", "recv_...
45.648148
0.000794
def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list ...
[ "def", "discover_single_case", "(", "self", ",", "module", ",", "case_attributes", ")", ":", "# Find single case", "case", "=", "module", "loader", "=", "self", ".", "_loader", "for", "index", ",", "component", "in", "enumerate", "(", "case_attributes", ")", "...
38.59375
0.00158
def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None): """ Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout que...
[ "def", "answer_pre_checkout_query", "(", "self", ",", "pre_checkout_query_id", ",", "ok", ",", "error_message", "=", "None", ")", ":", "assert_type_or_raise", "(", "pre_checkout_query_id", ",", "unicode_type", ",", "parameter_name", "=", "\"pre_checkout_query_id\"", ")"...
55.045455
0.008925
def get_short_lambda_body_text(lambda_func): """Return the source of a (short) lambda function. If it's impossible to obtain, returns None. """ try: source_lines, _ = inspect.getsourcelines(lambda_func) except (IOError, TypeError): return None # skip `def`-ed functions and long ...
[ "def", "get_short_lambda_body_text", "(", "lambda_func", ")", ":", "try", ":", "source_lines", ",", "_", "=", "inspect", ".", "getsourcelines", "(", "lambda_func", ")", "except", "(", "IOError", ",", "TypeError", ")", ":", "return", "None", "# skip `def`-ed func...
43.327869
0.00037
def element_text_color_should_be(self, locator, expected): """Verifies the element identified by `locator` has the expected text color (it verifies the CSS attribute color). Color should be in RGBA format. Example of rgba format: rgba(RED, GREEN, BLUE, ALPHA) | *Argument* | *Description* | *Example* | | l...
[ "def", "element_text_color_should_be", "(", "self", ",", "locator", ",", "expected", ")", ":", "self", ".", "_info", "(", "\"Verifying element '%s' has text color '%s'\"", "%", "(", "locator", ",", "expected", ")", ")", "self", ".", "_check_element_css_value", "(", ...
42.615385
0.021201
def query_all(current_page_num=1): ''' 查询所有未登录用户的访问记录 ToDo: ``None`` ? ''' return TabLog.select().where(TabLog.user_id == 'None').order_by(TabLog.time_out.desc()).paginate( current_page_num, CMS_CFG['list_num'] )
[ "def", "query_all", "(", "current_page_num", "=", "1", ")", ":", "return", "TabLog", ".", "select", "(", ")", ".", "where", "(", "TabLog", ".", "user_id", "==", "'None'", ")", ".", "order_by", "(", "TabLog", ".", "time_out", ".", "desc", "(", ")", ")...
33.25
0.010989
def _param_to_matrix(self): """ Convert parameters defined in `self._params` to `cvxopt.matrix` :return None """ for item in self._params: self.__dict__[item] = matrix(self.__dict__[item], tc='d')
[ "def", "_param_to_matrix", "(", "self", ")", ":", "for", "item", "in", "self", ".", "_params", ":", "self", ".", "__dict__", "[", "item", "]", "=", "matrix", "(", "self", ".", "__dict__", "[", "item", "]", ",", "tc", "=", "'d'", ")" ]
30.25
0.008032
def get_q_home(env): """Derive q home from the environment""" q_home = env.get('QHOME') if q_home: return q_home for v in ['VIRTUAL_ENV', 'HOME']: prefix = env.get(v) if prefix: q_home = os.path.join(prefix, 'q') if os.path.isdir(q_home): r...
[ "def", "get_q_home", "(", "env", ")", ":", "q_home", "=", "env", ".", "get", "(", "'QHOME'", ")", "if", "q_home", ":", "return", "q_home", "for", "v", "in", "[", "'VIRTUAL_ENV'", ",", "'HOME'", "]", ":", "prefix", "=", "env", ".", "get", "(", "v", ...
30.9375
0.001961
def addIVMInputs(imageObjectList,ivmlist): """ Add IVM filenames provided by user to outputNames dictionary for each input imageObject. """ if ivmlist is None: return for img,ivmname in zip(imageObjectList,ivmlist): img.updateIVMName(ivmname)
[ "def", "addIVMInputs", "(", "imageObjectList", ",", "ivmlist", ")", ":", "if", "ivmlist", "is", "None", ":", "return", "for", "img", ",", "ivmname", "in", "zip", "(", "imageObjectList", ",", "ivmlist", ")", ":", "img", ".", "updateIVMName", "(", "ivmname",...
33.5
0.018182
def get_color_cycle(n, cmap="rainbow", rotations=3): """Get a list of RGBA colors following a colormap. Useful for plotting lots of elements, keeping the color of each unique. Parameters ---------- n : integer The number of colors to return. cmap : string (optional) The colorma...
[ "def", "get_color_cycle", "(", "n", ",", "cmap", "=", "\"rainbow\"", ",", "rotations", "=", "3", ")", ":", "cmap", "=", "colormaps", "[", "cmap", "]", "if", "np", ".", "mod", "(", "n", ",", "rotations", ")", "==", "0", ":", "per", "=", "np", ".",...
27.827586
0.002395
def contour_mask(self, contour): """ Generates a binary image with only the given contour filled in. """ # fill in new data new_data = np.zeros(self.data.shape) num_boundary = contour.boundary_pixels.shape[0] boundary_px_ij_swapped = np.zeros([num_boundary, 1, 2]) boundar...
[ "def", "contour_mask", "(", "self", ",", "contour", ")", ":", "# fill in new data", "new_data", "=", "np", ".", "zeros", "(", "self", ".", "data", ".", "shape", ")", "num_boundary", "=", "contour", ".", "boundary_pixels", ".", "shape", "[", "0", "]", "bo...
50.875
0.002413
def enableBranch(self, enabled): """ Sets the enabled member to True or False for a node and all it's children """ self.enabled = enabled for child in self.childItems: child.enableBranch(enabled)
[ "def", "enableBranch", "(", "self", ",", "enabled", ")", ":", "self", ".", "enabled", "=", "enabled", "for", "child", "in", "self", ".", "childItems", ":", "child", ".", "enableBranch", "(", "enabled", ")" ]
39
0.012552
def searchRootOfTree(reducibleChildren: Set[LNode], nodeFromTree: LNode): """ Walk tree of nodes to root :param reducibleChildren: nodes which are part of tree :param nodeFromTree: node where to start the search """ while True: out_e = nodeFromTree.east[0].outgoingEdges # node ...
[ "def", "searchRootOfTree", "(", "reducibleChildren", ":", "Set", "[", "LNode", "]", ",", "nodeFromTree", ":", "LNode", ")", ":", "while", "True", ":", "out_e", "=", "nodeFromTree", ".", "east", "[", "0", "]", ".", "outgoingEdges", "# node has no successors", ...
31
0.00149
def _cmp(self, other): """ Compare two Project Haystack version strings, then return -1 if self < other, 0 if self == other or 1 if self > other. """ if not isinstance(other, Version): other = Version(other) num1 = self.version_num...
[ "def", "_cmp", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Version", ")", ":", "other", "=", "Version", "(", "other", ")", "num1", "=", "self", ".", "version_nums", "num2", "=", "other", ".", "version_nums", "#...
30.975
0.002347
def memoize(f): ''' Caches result of a function From: https://goo.gl/aXt4Qy >>> import time >>> @memoize ... def test(msg): ... # Processing for result that takes time ... time.sleep(1) ... return msg >>> >>> for i in range(5): ... start = time.time(...
[ "def", "memoize", "(", "f", ")", ":", "class", "memodict", "(", "dict", ")", ":", "@", "wraps", "(", "f", ")", "def", "__getitem__", "(", "self", ",", "*", "args", ")", ":", "return", "super", "(", "memodict", ",", "self", ")", ".", "__getitem__", ...
25.162791
0.001779
def model_functions(vk, model): """Fill the model with functions""" def get_vk_extension_functions(): names = set() for extension in get_extensions_filtered(vk): for req in extension['require']: if 'command' not in req: continue fo...
[ "def", "model_functions", "(", "vk", ",", "model", ")", ":", "def", "get_vk_extension_functions", "(", ")", ":", "names", "=", "set", "(", ")", "for", "extension", "in", "get_extensions_filtered", "(", "vk", ")", ":", "for", "req", "in", "extension", "[", ...
34.727273
0.000463
def draw(self, milliseconds, surface): """Draw out the tilemap.""" self.drawn_rects = [] cam = Ragnarok.get_world().Camera cX, cY, cXMax, cYMax = cam.get_cam_bounds() #Draw out only the tiles visible to the camera. start_pos = self.pixels_to_tiles( (cX, cY) ) sta...
[ "def", "draw", "(", "self", ",", "milliseconds", ",", "surface", ")", ":", "self", ".", "drawn_rects", "=", "[", "]", "cam", "=", "Ragnarok", ".", "get_world", "(", ")", ".", "Camera", "cX", ",", "cY", ",", "cXMax", ",", "cYMax", "=", "cam", ".", ...
45.409091
0.010784
def _get_line_array_construct(self): """ Returns a construct for an array of line data. """ from_bus = integer.setResultsName("fbus") to_bus = integer.setResultsName("tbus") s_rating = real.setResultsName("s_rating") # MVA v_rating = real.setResultsName("v_rating") # kV ...
[ "def", "_get_line_array_construct", "(", "self", ")", ":", "from_bus", "=", "integer", ".", "setResultsName", "(", "\"fbus\"", ")", "to_bus", "=", "integer", ".", "setResultsName", "(", "\"tbus\"", ")", "s_rating", "=", "real", ".", "setResultsName", "(", "\"s...
49.633333
0.009881
def process_patches(self, pset, stmt, elem, altname=None): """Process patches for data node `name` from `pset`. `stmt` provides the context in YANG and `elem` is the parent element in the output schema. Refinements adding documentation and changing the config status are immediately appl...
[ "def", "process_patches", "(", "self", ",", "pset", ",", "stmt", ",", "elem", ",", "altname", "=", "None", ")", ":", "if", "altname", ":", "name", "=", "altname", "else", ":", "name", "=", "stmt", ".", "arg", "new_pset", "=", "{", "}", "augments", ...
44.5
0.001374
def start_span(self, request, headers, peer_host, peer_port): """ Start a new server-side span. If the span has already been started by `start_basic_span`, this method only adds baggage from the headers. :param request: inbound tchannel.tornado.request.Request :param headers: di...
[ "def", "start_span", "(", "self", ",", "request", ",", "headers", ",", "peer_host", ",", "peer_port", ")", ":", "parent_context", "=", "None", "# noinspection PyBroadException", "try", ":", "if", "headers", "and", "hasattr", "(", "headers", ",", "'iteritems'", ...
43.340909
0.001538
def get_engine(self, name=None): """Retrieves an engine by name.""" engine = self._engines.get(name) if not engine: raise PapermillException("No engine named '{}' found".format(name)) return engine
[ "def", "get_engine", "(", "self", ",", "name", "=", "None", ")", ":", "engine", "=", "self", ".", "_engines", ".", "get", "(", "name", ")", "if", "not", "engine", ":", "raise", "PapermillException", "(", "\"No engine named '{}' found\"", ".", "format", "("...
39.333333
0.008299
def to_dict(self): """Return all the details of this MLPipeline in a dict. The dict structure contains all the `__init__` arguments of the MLPipeline, as well as the current hyperparameter values and the specification of the tunable_hyperparameters:: { "prim...
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "'primitives'", ":", "self", ".", "primitives", ",", "'init_params'", ":", "self", ".", "init_params", ",", "'input_names'", ":", "self", ".", "input_names", ",", "'output_names'", ":", "self", ".", "...
36.3125
0.001117
def p_single_statement_systemcall(self, p): 'single_statement : systemcall SEMICOLON' p[0] = SingleStatement(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_single_statement_systemcall", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SingleStatement", "(", "p", "[", "1", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ...
46
0.010695