text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def build_strain_specific_models(self, joblib=False, cores=1, force_rerun=False): """Wrapper function for _build_strain_specific_model""" if len(self.df_orthology_matrix) == 0: raise RuntimeError('Empty orthology matrix, please calculate first!') ref_functional_genes = [g.id for g in...
[ "def", "build_strain_specific_models", "(", "self", ",", "joblib", "=", "False", ",", "cores", "=", "1", ",", "force_rerun", "=", "False", ")", ":", "if", "len", "(", "self", ".", "df_orthology_matrix", ")", "==", "0", ":", "raise", "RuntimeError", "(", ...
62.722222
0.006981
def compile_for_aexec(source, filename="<aexec>", mode="single", dont_imply_dedent=False, local={}): """Return a list of (coroutine object, abstract base tree).""" flags = ast.PyCF_ONLY_AST if dont_imply_dedent: flags |= codeop.PyCF_DONT_IMPLY_DEDENT if compat.PY35: ...
[ "def", "compile_for_aexec", "(", "source", ",", "filename", "=", "\"<aexec>\"", ",", "mode", "=", "\"single\"", ",", "dont_imply_dedent", "=", "False", ",", "local", "=", "{", "}", ")", ":", "flags", "=", "ast", ".", "PyCF_ONLY_AST", "if", "dont_imply_dedent...
44.045455
0.00101
def objectid_search(gaiaid, gaia_mirror=None, columns=('source_id', 'ra','dec', 'phot_g_mean_mag', 'phot_bp_mean_mag', 'phot_rp_mean_mag', ...
[ "def", "objectid_search", "(", "gaiaid", ",", "gaia_mirror", "=", "None", ",", "columns", "=", "(", "'source_id'", ",", "'ra'", ",", "'dec'", ",", "'phot_g_mean_mag'", ",", "'phot_bp_mean_mag'", ",", "'phot_rp_mean_mag'", ",", "'l'", ",", "'b'", ",", "'paralla...
38.982759
0.00151
def read_data(data_file, dataformat, name_mode): """ Load data_file described by a dataformat dict. Parameters ---------- data_file : str Path to data file, including extension. dataformat : dict A dataformat dict, see example below. name_mode : str How to identyfy s...
[ "def", "read_data", "(", "data_file", ",", "dataformat", ",", "name_mode", ")", ":", "with", "open", "(", "data_file", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "if", "'meta_regex'", "in", "dataformat", ".", "keys", "(", ")", ...
37.634783
0.002927
def norm(vec): """Compute the (standard l2) norm of a vector. Parameters ---------- vec: array of shape (dim,) Returns ------- The l2 norm of vec. """ result = 0.0 for i in range(vec.shape[0]): result += vec[i] ** 2 return np.sqrt(result)
[ "def", "norm", "(", "vec", ")", ":", "result", "=", "0.0", "for", "i", "in", "range", "(", "vec", ".", "shape", "[", "0", "]", ")", ":", "result", "+=", "vec", "[", "i", "]", "**", "2", "return", "np", ".", "sqrt", "(", "result", ")" ]
18.533333
0.003425
async def read(cls, node): """Get list of `Bcache`'s for `node`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node must be a Node or str, not %s" ...
[ "async", "def", "read", "(", "cls", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "str", ")", ":", "system_id", "=", "node", "elif", "isinstance", "(", "node", ",", "Node", ")", ":", "system_id", "=", "node", ".", "system_id", "else", ...
35.6
0.00365
def on_timer(self): """Executes flush(). Ignores any errors to make sure one exception doesn't halt the whole flushing process. """ try: self.flush() except Exception as e: log.exception('Error while flushing: %s', e) self._set_timer()
[ "def", "on_timer", "(", "self", ")", ":", "try", ":", "self", ".", "flush", "(", ")", "except", "Exception", "as", "e", ":", "log", ".", "exception", "(", "'Error while flushing: %s'", ",", "e", ")", "self", ".", "_set_timer", "(", ")" ]
33.222222
0.006515
def add_tab(self, title="Yeah!", block_events=True): """ Adds a tab to the area, and creates the layout for this tab. """ self._widget.blockSignals(block_events) # create a widget to go in the tab tab = GridLayout() self.tabs.append(tab) tab.set_parent(se...
[ "def", "add_tab", "(", "self", ",", "title", "=", "\"Yeah!\"", ",", "block_events", "=", "True", ")", ":", "self", ".", "_widget", ".", "blockSignals", "(", "block_events", ")", "# create a widget to go in the tab", "tab", "=", "GridLayout", "(", ")", "self", ...
30.590909
0.004323
def rdann(record_name, extension, sampfrom=0, sampto=None, shift_samps=False, pb_dir=None, return_label_elements=['symbol'], summarize_labels=False): """ Read a WFDB annotation file record_name.extension and return an Annotation object. Parameters ---------- record_name : st...
[ "def", "rdann", "(", "record_name", ",", "extension", ",", "sampfrom", "=", "0", ",", "sampto", "=", "None", ",", "shift_samps", "=", "False", ",", "pb_dir", "=", "None", ",", "return_label_elements", "=", "[", "'symbol'", "]", ",", "summarize_labels", "="...
39.883333
0.000612
def _get_index(self,index): """Get the current block index, validating and checking status. Returns None if the demo is finished""" if index is None: if self.finished: print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.' ...
[ "def", "_get_index", "(", "self", ",", "index", ")", ":", "if", "index", "is", "None", ":", "if", "self", ".", "finished", ":", "print", ">>", "io", ".", "stdout", ",", "'Demo finished. Use <demo_name>.reset() if you want to rerun it.'", "return", "None", "inde...
33.461538
0.008949
def cp_file(): """ dumps databases into /backups, uploads to s3, deletes backups older than a month fab -f ./fabfile.py backup_dbs """ args = parser.parse_args() copy_file(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name, args.file, args.s3_folder)
[ "def", "cp_file", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "copy_file", "(", "args", ".", "aws_access_key_id", ",", "args", ".", "aws_secret_access_key", ",", "args", ".", "bucket_name", ",", "args", ".", "file", ",", "args", "....
35.75
0.010239
def undelete(request, message_id, success_url=None): """ Recovers a message from trash. This is achieved by removing the ``(sender|recipient)_deleted_at`` from the model. """ user = request.user message = get_object_or_404(Message, id=message_id) undeleted = False if success_url is None:...
[ "def", "undelete", "(", "request", ",", "message_id", ",", "success_url", "=", "None", ")", ":", "user", "=", "request", ".", "user", "message", "=", "get_object_or_404", "(", "Message", ",", "id", "=", "message_id", ")", "undeleted", "=", "False", "if", ...
36.08
0.00324
def send_email(self, user, subject, msg): """Should be overwritten in the setup""" print('To:', user) print('Subject:', subject) print(msg)
[ "def", "send_email", "(", "self", ",", "user", ",", "subject", ",", "msg", ")", ":", "print", "(", "'To:'", ",", "user", ")", "print", "(", "'Subject:'", ",", "subject", ")", "print", "(", "msg", ")" ]
33.4
0.011696
def read_len( f ): """Read a 'LEN' file and return a mapping from chromosome to length""" mapping = dict() for line in f: fields = line.split() mapping[ fields[0] ] = int( fields[1] ) return mapping
[ "def", "read_len", "(", "f", ")", ":", "mapping", "=", "dict", "(", ")", "for", "line", "in", "f", ":", "fields", "=", "line", ".", "split", "(", ")", "mapping", "[", "fields", "[", "0", "]", "]", "=", "int", "(", "fields", "[", "1", "]", ")"...
32
0.030435
def get_temperature(self): """Get current temperature in celsius.""" try: request = requests.get( '{}/temp'.format(self.resource), timeout=self.timeout, allow_redirects=False) self.temperature = request.json()['compensated'] return self.temperature ...
[ "def", "get_temperature", "(", "self", ")", ":", "try", ":", "request", "=", "requests", ".", "get", "(", "'{}/temp'", ".", "format", "(", "self", ".", "resource", ")", ",", "timeout", "=", "self", ".", "timeout", ",", "allow_redirects", "=", "False", ...
45.181818
0.005917
def register_prefs(*args, **kwargs): """Registers preferences that should be handled by siteprefs. Expects preferences as *args. Use keyword arguments to batch apply params supported by ``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``. Batch kwargs: :param ...
[ "def", "register_prefs", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "swap_settings_module", "=", "bool", "(", "kwargs", ".", "get", "(", "'swap_settings_module'", ",", "True", ")", ")", "if", "__PATCHED_LOCALS_SENTINEL", "not", "in", "get_frame_local...
34.935484
0.005391
def dht_get(self, key, *keys, **kwargs): """Queries the DHT for its best value related to given key. There may be several different values for a given key stored in the DHT; in this context *best* means the record that is most desirable. There is no one metric for *best*: it depends ent...
[ "def", "dht_get", "(", "self", ",", "key", ",", "*", "keys", ",", "*", "*", "kwargs", ")", ":", "args", "=", "(", "key", ",", ")", "+", "keys", "res", "=", "self", ".", "_client", ".", "request", "(", "'/dht/get'", ",", "args", ",", "decoder", ...
37.344828
0.0018
def unlink_from(self, provider): ''' 解绑特定第三方平台 ''' if type(provider) != str: raise TypeError('input should be a string') self.link_with(provider, None) # self._sync_auth_data(provider) return self
[ "def", "unlink_from", "(", "self", ",", "provider", ")", ":", "if", "type", "(", "provider", ")", "!=", "str", ":", "raise", "TypeError", "(", "'input should be a string'", ")", "self", ".", "link_with", "(", "provider", ",", "None", ")", "# self._sync_auth_...
28.444444
0.007576
def add_table( table_name, table, cache=False, cache_scope=_CS_FOREVER, copy_col=True): """ Register a table with Orca. Parameters ---------- table_name : str Should be globally unique to this table. table : pandas.DataFrame or function If a function, the functio...
[ "def", "add_table", "(", "table_name", ",", "table", ",", "cache", "=", "False", ",", "cache_scope", "=", "_CS_FOREVER", ",", "copy_col", "=", "True", ")", ":", "if", "isinstance", "(", "table", ",", "Callable", ")", ":", "table", "=", "TableFuncWrapper", ...
35.363636
0.000625
def _set_mongodb_host_val(key, default, mongodb_host, mongodb_defaults): """ Set a value in a 'cascade' fashion for mongodb_host[key] Within 'mongodb', as a last resort, its hardcoded default value is going to be picked. :param key: key name :param default: default last resort value :param...
[ "def", "_set_mongodb_host_val", "(", "key", ",", "default", ",", "mongodb_host", ",", "mongodb_defaults", ")", ":", "# If mongodb_host[key] is not already set, its value is going to be picked", "# from mongodb_defaults[key]", "if", "key", "not", "in", "mongodb_host", ":", "if...
41.666667
0.000978
def get(self, request, enterprise_uuid, course_id): """ Handle the enrollment of enterprise learner in the provided course. Based on `enterprise_uuid` in URL, the view will decide which enterprise customer's course enrollment record should be created. Depending on the value of ...
[ "def", "get", "(", "self", ",", "request", ",", "enterprise_uuid", ",", "course_id", ")", ":", "enrollment_course_mode", "=", "request", ".", "GET", ".", "get", "(", "'course_mode'", ")", "enterprise_catalog_uuid", "=", "request", ".", "GET", ".", "get", "("...
44.067416
0.001995
def split(self, dimension): """! @brief Split current block into two spatial blocks in specified dimension. @param[in] dimension (uint): Dimension where current block should be split. @return (tuple) Pair of new split blocks from current block. """ first_max_c...
[ "def", "split", "(", "self", ",", "dimension", ")", ":", "first_max_corner", "=", "self", ".", "__max_corner", "[", ":", "]", "second_min_corner", "=", "self", ".", "__min_corner", "[", ":", "]", "split_border", "=", "(", "self", ".", "__max_corner", "[", ...
39.111111
0.008322
def delay_for( self, wait: typing.Union[int, float], identifier: typing.Any, ) -> bool: """Defer the execution of a function for some number of seconds. Args: wait (typing.Union[int, float]): A numeric value that represents the number ...
[ "def", "delay_for", "(", "self", ",", "wait", ":", "typing", ".", "Union", "[", "int", ",", "float", "]", ",", "identifier", ":", "typing", ".", "Any", ",", ")", "->", "bool", ":", "raise", "NotImplementedError", "(", ")" ]
38.35
0.003817
def seq2array(seq, fill_overhangs=True, ambiguous_character='N'): """ Take the raw sequence, substitute the "overhanging" gaps with 'N' (missequenced), and convert the sequence to the numpy array of chars. Parameters ---------- seq : Biopython.SeqRecord, str, iterable Sequence as an ob...
[ "def", "seq2array", "(", "seq", ",", "fill_overhangs", "=", "True", ",", "ambiguous_character", "=", "'N'", ")", ":", "try", ":", "sequence", "=", "''", ".", "join", "(", "seq", ")", "except", "TypeError", ":", "sequence", "=", "seq", "sequence", "=", ...
30.878788
0.004757
def create_iam(self): """Create IAM resources.""" utils.banner("Creating IAM") iam.create_iam_resources(env=self.env, app=self.app)
[ "def", "create_iam", "(", "self", ")", ":", "utils", ".", "banner", "(", "\"Creating IAM\"", ")", "iam", ".", "create_iam_resources", "(", "env", "=", "self", ".", "env", ",", "app", "=", "self", ".", "app", ")" ]
38
0.012903
def verify_duplicates(duplicates, uniques): """Verify that a set of intersections had expected duplicates. .. note:: This is a helper used only by :func:`generic_intersect`. Args: duplicates (List[.Intersection]): List of intersections corresponding to duplicates that were filt...
[ "def", "verify_duplicates", "(", "duplicates", ",", "uniques", ")", ":", "for", "uniq1", ",", "uniq2", "in", "itertools", ".", "combinations", "(", "uniques", ",", "2", ")", ":", "if", "same_intersection", "(", "uniq1", ",", "uniq2", ")", ":", "raise", "...
37.862745
0.000505
def histogram(self, stat, value, tags=None): """Report a histogram.""" self._log('histogram', stat, value, tags)
[ "def", "histogram", "(", "self", ",", "stat", ",", "value", ",", "tags", "=", "None", ")", ":", "self", ".", "_log", "(", "'histogram'", ",", "stat", ",", "value", ",", "tags", ")" ]
42
0.015625
def heat_wave_max_length(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS'): # Dev note : we should decide if it is deg K or C r"""Heat wave max length Maximum length of heat waves over a given period. A heat wave is defined as an event whe...
[ "def", "heat_wave_max_length", "(", "tasmin", ",", "tasmax", ",", "thresh_tasmin", "=", "'22.0 degC'", ",", "thresh_tasmax", "=", "'30 degC'", ",", "window", "=", "3", ",", "freq", "=", "'YS'", ")", ":", "# Dev note : we should decide if it is deg K or C", "thresh_t...
42.754386
0.005616
def _compute_magnitude(self, rup, C): """ Compute the first term of the equation described on p. 199: ``b1 + b2 * M + b3 * M**2`` """ return C['b1'] + (C['b2'] * rup.mag) + (C['b3'] * (rup.mag ** 2))
[ "def", "_compute_magnitude", "(", "self", ",", "rup", ",", "C", ")", ":", "return", "C", "[", "'b1'", "]", "+", "(", "C", "[", "'b2'", "]", "*", "rup", ".", "mag", ")", "+", "(", "C", "[", "'b3'", "]", "*", "(", "rup", ".", "mag", "**", "2"...
33.428571
0.008333
def plot_latent_scatter(self, labels=None, which_indices=None, legend=True, plot_limits=None, marker='<>^vsd', num_samples=1000, projection='2d', **kwar...
[ "def", "plot_latent_scatter", "(", "self", ",", "labels", "=", "None", ",", "which_indices", "=", "None", ",", "legend", "=", "True", ",", "plot_limits", "=", "None", ",", "marker", "=", "'<>^vsd'", ",", "num_samples", "=", "1000", ",", "projection", "=", ...
46.62069
0.003623
def set_format_key_value(self, key, value): '''Add a new key/value pair. Key in column 9 (FORMAT) and value in column 10. If key already exists, then updates the value to the new given value''' if self.format_keys is None: self.format_keys = [] self.FORMAT = {} ...
[ "def", "set_format_key_value", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "format_keys", "is", "None", ":", "self", ".", "format_keys", "=", "[", "]", "self", ".", "FORMAT", "=", "{", "}", "if", "key", "not", "in", "self", ...
41.7
0.004695
def give_consent(): """ Serves up the consent in the popup window. """ if not ('hitId' in request.args and 'assignmentId' in request.args and 'workerId' in request.args): raise ExperimentError('hit_assign_worker_id_not_set_in_consent') hit_id = request.args['hitId'] assignmen...
[ "def", "give_consent", "(", ")", ":", "if", "not", "(", "'hitId'", "in", "request", ".", "args", "and", "'assignmentId'", "in", "request", ".", "args", "and", "'workerId'", "in", "request", ".", "args", ")", ":", "raise", "ExperimentError", "(", "'hit_assi...
35.75
0.001362
def validateDtd(self, doc, dtd): """Try to validate the document against the dtd instance Basically it does check all the definitions in the DtD. Note the the internal subset (if present) is de-coupled (i.e. not used), which could give problems if ID or IDREF is present....
[ "def", "validateDtd", "(", "self", ",", "doc", ",", "dtd", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "dtd", "is", "None", ":", "dtd__o", "=", "None", "else", ":", "dtd__o"...
44.416667
0.011029
def neighbours(healpix_index, nside, order='ring'): """ Find all the HEALPix pixels that are the neighbours of a HEALPix pixel Parameters ---------- healpix_index : `~numpy.ndarray` Array of HEALPix pixels nside : int Number of pixels along the side of each of the 12 top-level H...
[ "def", "neighbours", "(", "healpix_index", ",", "nside", ",", "order", "=", "'ring'", ")", ":", "_validate_nside", "(", "nside", ")", "nside", "=", "np", ".", "asarray", "(", "nside", ",", "dtype", "=", "np", ".", "intc", ")", "if", "_validate_order", ...
31.0625
0.003902
def alias(self, person, identity, path=KISSmetrics.ALIAS_PATH): """Map `person` to `identity`; actions done by one resolve to other. :param person: consider as same individual ``identity``; the source of the alias operation :type person: str or unicode :param iden...
[ "def", "alias", "(", "self", ",", "person", ",", "identity", ",", "path", "=", "KISSmetrics", ".", "ALIAS_PATH", ")", ":", "this_request", "=", "request", ".", "alias", "(", "self", ".", "key", ",", "person", ",", "identity", ",", "scheme", "=", "self"...
46.916667
0.00116
def get_terminal_size(): """Get (width, height) of the current terminal.""" try: import fcntl, termios, struct # fcntl module only available on Unix return struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')) except: return (40, 80)
[ "def", "get_terminal_size", "(", ")", ":", "try", ":", "import", "fcntl", ",", "termios", ",", "struct", "# fcntl module only available on Unix", "return", "struct", ".", "unpack", "(", "'hh'", ",", "fcntl", ".", "ioctl", "(", "1", ",", "termios", ".", "TIOC...
39
0.014337
def tree_structures_for(self, prefix, current_oid, parent_oids, prefixes): """ Return the entries for this commit, the entries of the parent commits, and the difference between the two (current_files - parent_files) """ if prefix and prefixes and prefix not in prefixes: ...
[ "def", "tree_structures_for", "(", "self", ",", "prefix", ",", "current_oid", ",", "parent_oids", ",", "prefixes", ")", ":", "if", "prefix", "and", "prefixes", "and", "prefix", "not", "in", "prefixes", ":", "return", "empty", ",", "empty", "parent_files", "=...
43.571429
0.00321
def create_table(self, name, fields=[], key="id"): """Creates a new table. Creates a table with the given name, containing the list of given fields. Since SQLite uses manifest typing, no data type need be supplied. The primary key is "id" by default, an ...
[ "def", "create_table", "(", "self", ",", "name", ",", "fields", "=", "[", "]", ",", "key", "=", "\"id\"", ")", ":", "for", "f", "in", "fields", ":", "if", "f", "==", "key", ":", "fields", ".", "remove", "(", "key", ")", "sql", "=", "\"create tabl...
33.863636
0.013055
def get_version_with_beta(version_info: FileVersionResult) -> str: """ Get the project's version string *with* a beta build label based on UTC. :param version_info: The current version_info of the project. :return: The project's version string, with a beta build number. """ if not version_info...
[ "def", "get_version_with_beta", "(", "version_info", ":", "FileVersionResult", ")", "->", "str", ":", "if", "not", "version_info", ":", "raise", "TypeError", "(", "\"version_info cannot be 'None'!\"", ")", "if", "not", "version_info", ".", "uniform", ":", "raise", ...
32.285714
0.001074
def transpose(self, semitone): """ Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll. ...
[ "def", "transpose", "(", "self", ",", "semitone", ")", ":", "if", "semitone", ">", "0", "and", "semitone", "<", "128", ":", "self", ".", "pianoroll", "[", ":", ",", "semitone", ":", "]", "=", "self", ".", "pianoroll", "[", ":", ",", ":", "(", "12...
39.058824
0.004412
def generate_sample(self, initial_pos, num_samples, stepsize=None): """ Returns a generator type object whose each iteration yields a sample Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting ...
[ "def", "generate_sample", "(", "self", ",", "initial_pos", ",", "num_samples", ",", "stepsize", "=", "None", ")", ":", "initial_pos", "=", "_check_1d_array_object", "(", "initial_pos", ",", "'initial_pos'", ")", "_check_length_equal", "(", "initial_pos", ",", "sel...
38.438596
0.00267
def _cut(dna, index, restriction_enzyme): '''Cuts template once at the specified index. :param dna: DNA to cut :type dna: coral.DNA :param index: index at which to cut :type index: int :param restriction_enzyme: Enzyme with which to cut :type restriction_enzyme: coral.RestrictionSite :r...
[ "def", "_cut", "(", "dna", ",", "index", ",", "restriction_enzyme", ")", ":", "# TODO: handle case where cut site is outside of recognition sequence,", "# for both circular and linear cases where site is at index 0", "# Find absolute indices at which to cut", "cut_site", "=", "restrict...
32.928571
0.000702
def _size(self): """ :return: how many bits is this slice selecting """ assert isinstance(self, Value) return int(self.val[0]) - int(self.val[1])
[ "def", "_size", "(", "self", ")", ":", "assert", "isinstance", "(", "self", ",", "Value", ")", "return", "int", "(", "self", ".", "val", "[", "0", "]", ")", "-", "int", "(", "self", ".", "val", "[", "1", "]", ")" ]
30
0.010811
def pclass(self, bases): """ Create a ``pyrsistent.PClass`` subclass representing this class. :param tuple bases: Additional base classes to give the resulting class. These will appear to the left of ``PClass``. """ def discard_constant_fields(cls, **kwargs): ...
[ "def", "pclass", "(", "self", ",", "bases", ")", ":", "def", "discard_constant_fields", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "def", "ctor", "(", ")", ":", "return", "super", "(", "huh", ",", "cls", ")", ".", "__new__", "(", "cls", ",", ...
35.543478
0.004167
def get_neurommsig_scores(graph: BELGraph, genes: List[Gene], annotation: str = 'Subgraph', ora_weight: Optional[float] = None, hub_weight: Optional[float] = None, top_percent: Optional[floa...
[ "def", "get_neurommsig_scores", "(", "graph", ":", "BELGraph", ",", "genes", ":", "List", "[", "Gene", "]", ",", "annotation", ":", "str", "=", "'Subgraph'", ",", "ora_weight", ":", "Optional", "[", "float", "]", "=", "None", ",", "hub_weight", ":", "Opt...
43.638298
0.002861
def auth_provider_add_user(self, auth_provider_id, username): """ Transform an institutional affiliates UID, such as a Duke NetID, to a DDS specific user identity; can be used by clients prior to calling DDS APIs that require a DDS user in the request payload. Returns user details. Can b...
[ "def", "auth_provider_add_user", "(", "self", ",", "auth_provider_id", ",", "username", ")", ":", "url", "=", "\"/auth_providers/{}/affiliates/{}/dds_user/\"", ".", "format", "(", "auth_provider_id", ",", "username", ")", "return", "self", ".", "_post", "(", "url", ...
63.181818
0.007092
def get_chain(self, index): """Assemble and return the chain leading from a given node to the merkle root of this tree. """ chain = [] this = self.leaves[index] chain.append((this.val, 'SELF')) while this.p: chain.append((this.sib.val, this.sib.side)) ...
[ "def", "get_chain", "(", "self", ",", "index", ")", ":", "chain", "=", "[", "]", "this", "=", "self", ".", "leaves", "[", "index", "]", "chain", ".", "append", "(", "(", "this", ".", "val", ",", "'SELF'", ")", ")", "while", "this", ".", "p", ":...
35.363636
0.007519
def unlock(self): """ Unmarks the remote server as currently being deployed to. """ self.init() r = self.local_renderer if self.file_exists(r.env.lockfile_path): self.vprint('Unlocking %s.' % r.env.lockfile_path) r.run_or_local('rm -f {lockfile_pat...
[ "def", "unlock", "(", "self", ")", ":", "self", ".", "init", "(", ")", "r", "=", "self", ".", "local_renderer", "if", "self", ".", "file_exists", "(", "r", ".", "env", ".", "lockfile_path", ")", ":", "self", ".", "vprint", "(", "'Unlocking %s.'", "%"...
35.111111
0.006173
def list_presets(cfg, out=sys.stdout): """Write a human readable list of available presets to out. :param cfg: ConfigParser instance :param out: file object to write to """ for section in cfg.sections(): if section.startswith("preset:"): out.write((section.replace("preset:", "")...
[ "def", "list_presets", "(", "cfg", ",", "out", "=", "sys", ".", "stdout", ")", ":", "for", "section", "in", "cfg", ".", "sections", "(", ")", ":", "if", "section", ".", "startswith", "(", "\"preset:\"", ")", ":", "out", ".", "write", "(", "(", "sec...
39.090909
0.002273
def run_command(self, cmd, sudo=False, capture=True, quiet=None, return_result=False): '''run_command is a wrapper for the global run_command, checking first for sudo and exiting on error if needed. The message is retur...
[ "def", "run_command", "(", "self", ",", "cmd", ",", "sudo", "=", "False", ",", "capture", "=", "True", ",", "quiet", "=", "None", ",", "return_result", "=", "False", ")", ":", "# First preference to function, then to client setting", "if", "quiet", "==", "None...
32.25641
0.005401
def Exp(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Calculates the exponential of an input vertex :param input_vertex: the vertex """ return Double(context.jvm_view().ExpVertex, label, cast_to_double_vertex(input_vertex))
[ "def", "Exp", "(", "input_vertex", ":", "vertex_constructor_param_types", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Vertex", ":", "return", "Double", "(", "context", ".", "jvm_view", "(", ")", ".", "ExpVertex", ",", "label", ...
40.571429
0.02069
def update_customer_group_by_id(cls, customer_group_id, customer_group, **kwargs): """Update CustomerGroup Update attributes of CustomerGroup This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.up...
[ "def", "update_customer_group_by_id", "(", "cls", ",", "customer_group_id", ",", "customer_group", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", ...
49.818182
0.006267
def indices(db=None): ''' Show all indices in the database CLI Example: .. code-block:: bash salt '*' sqlite3.indices /root/test.db ''' cur = _connect(db) if not cur: return False cur.execute( "SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;"...
[ "def", "indices", "(", "db", "=", "None", ")", ":", "cur", "=", "_connect", "(", "db", ")", "if", "not", "cur", ":", "return", "False", "cur", ".", "execute", "(", "\"SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;\"", ")", "rows", "=", "cur",...
17.45
0.002717
def on_sdl_keydown ( self, event ): "press ESCAPE to quit the application" key = event.key.keysym.sym if key == SDLK_ESCAPE: self.running = False
[ "def", "on_sdl_keydown", "(", "self", ",", "event", ")", ":", "key", "=", "event", ".", "key", ".", "keysym", ".", "sym", "if", "key", "==", "SDLK_ESCAPE", ":", "self", ".", "running", "=", "False" ]
30.8
0.056962
def detect_duplicate_repos(repos1, repos2): """Return duplicate repos dict if repo_dir same and vcs different. :param repos1: list of repo expanded dicts :type repos1: list of :py:dict :param repos2: list of repo expanded dicts :type repos2: list of :py:dict :rtype: list of dicts or None :r...
[ "def", "detect_duplicate_repos", "(", "repos1", ",", "repos2", ")", ":", "dupes", "=", "[", "]", "path_dupe_repos", "=", "[", "]", "curpaths", "=", "[", "r", "[", "'repo_dir'", "]", "for", "r", "in", "repos1", "]", "newpaths", "=", "[", "r", "[", "'r...
29.3125
0.002064
def render_simple_edge(self, name, edge, edge_settings, label="call"): """ Render edge without label """ self.gv_graph.edge(self.get_path_from_name(name), self.get_path_from_name(edge.to), label=label, **edge_settings)
[ "def", "render_simple_edge", "(", "self", ",", "name", ",", "edge", ",", "edge_settings", ",", "label", "=", "\"call\"", ")", ":", "self", ".", "gv_graph", ".", "edge", "(", "self", ".", "get_path_from_name", "(", "name", ")", ",", "self", ".", "get_path...
49.2
0.012
def file_or_filename(input): """ Return a file-like object ready to be read from the beginning. `input` is either a filename (gz/bz2 also supported) or a file-like object supporting seek. """ if isinstance(input, string_types): # input was a filename: open as file yield smart_open(i...
[ "def", "file_or_filename", "(", "input", ")", ":", "if", "isinstance", "(", "input", ",", "string_types", ")", ":", "# input was a filename: open as file", "yield", "smart_open", "(", "input", ")", "else", ":", "# input already a file-like object; just reset to the beginn...
33.615385
0.004454
def save(self, user, commit=True): """ Persist user and emit event """ self.is_instance(user) schema = UpdateSchema() valid = schema.process(user) if not valid: return valid db.session.add(user) if commit: db.session.commit() eve...
[ "def", "save", "(", "self", ",", "user", ",", "commit", "=", "True", ")", ":", "self", ".", "is_instance", "(", "user", ")", "schema", "=", "UpdateSchema", "(", ")", "valid", "=", "schema", ".", "process", "(", "user", ")", "if", "not", "valid", ":...
23.733333
0.005405
def remove_transcript(self,tx_id): """Remove a transcript from the locus by its id :param tx_id: :type tx_id: string """ txs = self.get_transcripts() if tx_id not in [x.id for x in txs]: return tx = [x for x in txs if x.id==tx_id][0] for n in [x for x in self.g.get_nodes()]: ...
[ "def", "remove_transcript", "(", "self", ",", "tx_id", ")", ":", "txs", "=", "self", ".", "get_transcripts", "(", ")", "if", "tx_id", "not", "in", "[", "x", ".", "id", "for", "x", "in", "txs", "]", ":", "return", "tx", "=", "[", "x", "for", "x", ...
28.125
0.017204
def update_fleet(ImageName=None, Name=None, InstanceType=None, ComputeCapacity=None, VpcConfig=None, MaxUserDurationInSeconds=None, DisconnectTimeoutInSeconds=None, DeleteVpcConfig=None, Description=None, DisplayName=None, EnableDefaultInternetAccess=None): """ Updates an existing fleet. All the attributes exce...
[ "def", "update_fleet", "(", "ImageName", "=", "None", ",", "Name", "=", "None", ",", "InstanceType", "=", "None", ",", "ComputeCapacity", "=", "None", ",", "VpcConfig", "=", "None", ",", "MaxUserDurationInSeconds", "=", "None", ",", "DisconnectTimeoutInSeconds",...
40.542056
0.005401
def cli(ctx, path, renku_home, use_external_storage): """Check common Renku commands used in various situations.""" ctx.obj = LocalClient( path=path, renku_home=renku_home, use_external_storage=use_external_storage, )
[ "def", "cli", "(", "ctx", ",", "path", ",", "renku_home", ",", "use_external_storage", ")", ":", "ctx", ".", "obj", "=", "LocalClient", "(", "path", "=", "path", ",", "renku_home", "=", "renku_home", ",", "use_external_storage", "=", "use_external_storage", ...
35.285714
0.003953
async def save_albums(self, *albums): """Save one or more albums to the current user’s ‘Your Music’ library. Parameters ---------- albums : Sequence[Union[Album, str]] A sequence of artist objects or spotify IDs """ _albums = [(obj if isinstance(obj, str) els...
[ "async", "def", "save_albums", "(", "self", ",", "*", "albums", ")", ":", "_albums", "=", "[", "(", "obj", "if", "isinstance", "(", "obj", ",", "str", ")", "else", "obj", ".", "id", ")", "for", "obj", "in", "albums", "]", "await", "self", ".", "u...
39.9
0.004902
def since(self, ts): """ Tail the oplog, starting from ts. """ while True: items = super(TailingOplog, self).since(ts) for doc in items: yield doc ts = doc['ts']
[ "def", "since", "(", "self", ",", "ts", ")", ":", "while", "True", ":", "items", "=", "super", "(", "TailingOplog", ",", "self", ")", ".", "since", "(", "ts", ")", "for", "doc", "in", "items", ":", "yield", "doc", "ts", "=", "doc", "[", "'ts'", ...
26.777778
0.008032
def image_write(image, filename, ri=False): """ Write an ANTsImage to file ANTsR function: `antsImageWrite` Arguments --------- image : ANTsImage image to save to file filename : string name of file to which image will be saved ri : boolean if True, return ima...
[ "def", "image_write", "(", "image", ",", "filename", ",", "ri", "=", "False", ")", ":", "if", "filename", ".", "endswith", "(", "'.npy'", ")", ":", "img_array", "=", "image", ".", "numpy", "(", ")", "img_header", "=", "{", "'origin'", ":", "image", "...
30.3125
0.006993
def handle_line(self, line): """Read one line.""" if line.kind == ConfigLine.KIND_HEADER: self.enter_block(line.header) else: self.insert_line(line)
[ "def", "handle_line", "(", "self", ",", "line", ")", ":", "if", "line", ".", "kind", "==", "ConfigLine", ".", "KIND_HEADER", ":", "self", ".", "enter_block", "(", "line", ".", "header", ")", "else", ":", "self", ".", "insert_line", "(", "line", ")" ]
31.833333
0.010204
def serializer(self, create=False, many=False): """ Decorator to mark a :class:`Serializer` subclass for a specific purpose, ie, to be used during object creation **or** for serializing lists of objects. :param create: Whether or not this serializer is for object creation. :para...
[ "def", "serializer", "(", "self", ",", "create", "=", "False", ",", "many", "=", "False", ")", ":", "if", "create", "and", "many", ":", "raise", "Exception", "(", "'Can only set one of `create` or `many` to `True`'", ")", "def", "wrapper", "(", "cls", ")", "...
40.764706
0.005642
def activate_introjs(driver): """ Allows you to use IntroJS Tours with SeleniumBase https://introjs.com/ """ intro_css = constants.IntroJS.MIN_CSS intro_js = constants.IntroJS.MIN_JS verify_script = ("""// Verify IntroJS activated var intro2 = introJs(); ...
[ "def", "activate_introjs", "(", "driver", ")", ":", "intro_css", "=", "constants", ".", "IntroJS", ".", "MIN_CSS", "intro_js", "=", "constants", ".", "IntroJS", ".", "MIN_JS", "verify_script", "=", "(", "\"\"\"// Verify IntroJS activated\n var intro2...
36.366667
0.000893
def add_albumart(albumart, song_title): ''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: ...
[ "def", "add_albumart", "(", "albumart", ",", "song_title", ")", ":", "try", ":", "img", "=", "urlopen", "(", "albumart", ")", "# Gets album art from url", "except", "Exception", ":", "log", ".", "log_error", "(", "\"* Could not add album art\"", ",", "indented", ...
22.103448
0.001495
def takeAt( self, index ): """ Removes the widget from the rollout at the inputed index. :param index | <int> :return <QWidget> || None """ layout = self.widget().layout() item = layout.takeAt(index) if ( not item ): ...
[ "def", "takeAt", "(", "self", ",", "index", ")", ":", "layout", "=", "self", ".", "widget", "(", ")", ".", "layout", "(", ")", "item", "=", "layout", ".", "takeAt", "(", "index", ")", "if", "(", "not", "item", ")", ":", "return", "None", "return"...
26.071429
0.02381
def prepare_create_transaction(*, signers, recipients=None, asset=None, metadata=None): """Prepares a ``"CREATE"`` transaction payload, ready to be fulfilled. Args: signers (:...
[ "def", "prepare_create_transaction", "(", "*", ",", "signers", ",", "recipients", "=", "None", ",", "asset", "=", "None", ",", "metadata", "=", "None", ")", ":", "if", "not", "isinstance", "(", "signers", ",", "(", "list", ",", "tuple", ")", ")", ":", ...
32.634921
0.000472
def set_window_iconify_callback(window, cbfun): """ Sets the iconify callback for the specified window. Wrapper for: GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ...
[ "def", "set_window_iconify_callback", "(", "window", ",", "cbfun", ")", ":", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_long", ")", ")", ".", "conten...
41.238095
0.002257
async def del_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT): """ Remove the specified Data-ID from the list of alternative commands. Only one occurrence is deleted. If the Data-ID appears multiple times in the list of alternative commands, this command must be repeated to ...
[ "async", "def", "del_alternative", "(", "self", ",", "alt", ",", "timeout", "=", "OTGW_DEFAULT_TIMEOUT", ")", ":", "cmd", "=", "OTGW_CMD_DEL_ALT", "alt", "=", "int", "(", "alt", ")", "if", "alt", "<", "1", "or", "alt", ">", "255", ":", "return", "None"...
41.52381
0.002242
def str_cmd(cmd, cwd, env): """ Runs the command and returns its stdout and stderr. """ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env) stdout_builder, stderr_builder = proc.async_stdout_stderr_builder(process) process.wait() s...
[ "def", "str_cmd", "(", "cmd", ",", "cwd", ",", "env", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "cwd", ",", "env"...
44.7
0.015351
def list(self, path): """GET /<path>?list=true :param path: :type path: :return: :rtype: """ try: payload = { 'list': True } return self._adapter.get('/v1/{0}'.format(path), params=payload).json() except...
[ "def", "list", "(", "self", ",", "path", ")", ":", "try", ":", "payload", "=", "{", "'list'", ":", "True", "}", "return", "self", ".", "_adapter", ".", "get", "(", "'/v1/{0}'", ".", "format", "(", "path", ")", ",", "params", "=", "payload", ")", ...
23.6
0.008152
def select(*queries, **kwargs): """ Builds a function that will execute the specified queries against a list of Nodes. """ def make_query(*args): def simple_query(nodes): if len(args) == 0: return nodes pred = args[0] results = [] ...
[ "def", "select", "(", "*", "queries", ",", "*", "*", "kwargs", ")", ":", "def", "make_query", "(", "*", "args", ")", ":", "def", "simple_query", "(", "nodes", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "return", "nodes", "pred", "="...
31.694444
0.000425
def pop(self, queue_name): """ Pops a task off the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_name: string :returns: The data for the task. :rtype: string """ cls = self.__class__ ...
[ "def", "pop", "(", "self", ",", "queue_name", ")", ":", "cls", "=", "self", ".", "__class__", "queue", "=", "cls", ".", "queues", ".", "get", "(", "queue_name", ",", "[", "]", ")", "if", "queue", ":", "task_id", "=", "queue", ".", "pop", "(", "0"...
26.764706
0.004246
def parseStr(self, st) : """Parses a string""" self.data = st.replace('\r', '\n') self.data = self.data.replace('\n\n', '\n') self.data = self.data.split('\n')
[ "def", "parseStr", "(", "self", ",", "st", ")", ":", "self", ".", "data", "=", "st", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "self", ".", "data", "=", "self", ".", "data", ".", "replace", "(", "'\\n\\n'", ",", "'\\n'", ")", "self", ".", ...
32.6
0.041916
def add_gwb(psr, dist=1, ngw=1000, seed=None, flow=1e-8, fhigh=1e-5, gwAmp=1e-20, alpha=-0.66, logspacing=True): """Add a stochastic background from inspiraling binaries, using the tempo2 code that underlies the GWbkgrd plugin. Here 'dist' is the pulsar distance [in kpc]; 'ngw' is the number of...
[ "def", "add_gwb", "(", "psr", ",", "dist", "=", "1", ",", "ngw", "=", "1000", ",", "seed", "=", "None", ",", "flow", "=", "1e-8", ",", "fhigh", "=", "1e-5", ",", "gwAmp", "=", "1e-20", ",", "alpha", "=", "-", "0.66", ",", "logspacing", "=", "Tr...
39.28
0.010934
def edge_length_check(length, edge): """ Raises error if length is not in interval [0, edge.length] """ try: assert 0 <= length <= edge.length except AssertionError: if length < 0: raise TreeError('Negative edge-lengths are disallowed') raise TreeError( 'This ...
[ "def", "edge_length_check", "(", "length", ",", "edge", ")", ":", "try", ":", "assert", "0", "<=", "length", "<=", "edge", ".", "length", "except", "AssertionError", ":", "if", "length", "<", "0", ":", "raise", "TreeError", "(", "'Negative edge-lengths are d...
42.3
0.002315
def _arburg2(X, order): """This version is 10 times faster than arburg, but the output rho is not correct. returns [1 a0,a1, an-1] """ x = np.array(X) N = len(x) if order <= 0.: raise ValueError("order must be > 0") # Initialisation # ------ rho, den rho = sum(abs(x)**2....
[ "def", "_arburg2", "(", "X", ",", "order", ")", ":", "x", "=", "np", ".", "array", "(", "X", ")", "N", "=", "len", "(", "x", ")", "if", "order", "<=", "0.", ":", "raise", "ValueError", "(", "\"order must be > 0\"", ")", "# Initialisation", "# ------ ...
25.913793
0.004487
def imagetransformer2d_base_8l_8_32_big(): """hparams fo 8 layer big 2d model for cifar 10.""" hparams = image_transformer2d_base() hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 2048 hparams.num_decoder_layers = 8 hparams.batch_size = 1 hparams.layer_prepostprocess_dropout = 0....
[ "def", "imagetransformer2d_base_8l_8_32_big", "(", ")", ":", "hparams", "=", "image_transformer2d_base", "(", ")", "hparams", ".", "num_heads", "=", "16", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "nu...
33
0.029478
def move_left(self): """Make the drone move left.""" self.at(ardrone.at.pcmd, True, -self.speed, 0, 0, 0)
[ "def", "move_left", "(", "self", ")", ":", "self", ".", "at", "(", "ardrone", ".", "at", ".", "pcmd", ",", "True", ",", "-", "self", ".", "speed", ",", "0", ",", "0", ",", "0", ")" ]
39.666667
0.016529
def set(self, child, min_occurs=1, max_occurs=1): """Set the schema for the sequence children. @param child: The schema that children must match. @param min_occurs: The minimum number of children the sequence must have. @param max_occurs: The maximum number of children the s...
[ "def", "set", "(", "self", ",", "child", ",", "min_occurs", "=", "1", ",", "max_occurs", "=", "1", ")", ":", "if", "isinstance", "(", "child", ",", "LeafSchema", ")", ":", "raise", "RuntimeError", "(", "\"Sequence can't have leaf children\"", ")", "if", "s...
41.791667
0.001949
def encrypt(self, message): """ Encrypt the given message """ if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode('utf-8')).hexdigest()
[ "def", "encrypt", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "(", "bytes", ",", "str", ")", ")", ":", "raise", "TypeError", "return", "hashlib", ".", "sha1", "(", "message", ".", "encode", "(", "'utf-8'", "...
30.857143
0.013514
def _getEventFromUid(self, request, uid): """Try and find a child event with the given UID.""" event = getEventFromUid(request, uid) if event.get_ancestors().filter(id=self.id).exists(): # only return event if it is a descendant return event
[ "def", "_getEventFromUid", "(", "self", ",", "request", ",", "uid", ")", ":", "event", "=", "getEventFromUid", "(", "request", ",", "uid", ")", "if", "event", ".", "get_ancestors", "(", ")", ".", "filter", "(", "id", "=", "self", ".", "id", ")", ".",...
47.333333
0.00692
def geturi(self): """Return the recombined version of the original URI as a string.""" fragment = self.fragment if fragment is None: return self.uri elif isinstance(fragment, bytes): return self.uri + b'#' + fragment else: return self.uri + u'#...
[ "def", "geturi", "(", "self", ")", ":", "fragment", "=", "self", ".", "fragment", "if", "fragment", "is", "None", ":", "return", "self", ".", "uri", "elif", "isinstance", "(", "fragment", ",", "bytes", ")", ":", "return", "self", ".", "uri", "+", "b'...
36
0.006024
def timed_loop(name=None, rgstr_stamps=None, save_itrs=SET['SI'], loop_end_stamp=None, end_stamp_unique=SET['UN'], keep_prev_subdivisions=SET['KS'], keep_end_subdivisions=SET['KS'], quick_print=SET['QP']): """ ...
[ "def", "timed_loop", "(", "name", "=", "None", ",", "rgstr_stamps", "=", "None", ",", "save_itrs", "=", "SET", "[", "'SI'", "]", ",", "loop_end_stamp", "=", "None", ",", "end_stamp_unique", "=", "SET", "[", "'UN'", "]", ",", "keep_prev_subdivisions", "=", ...
42.421053
0.002021
def _guess_group(info): """Add the first group to get report with some factor""" value = "fake" if "metadata" in info: if info["metadata"]: return ",".join(map(str, info["metadata"].values())) return value
[ "def", "_guess_group", "(", "info", ")", ":", "value", "=", "\"fake\"", "if", "\"metadata\"", "in", "info", ":", "if", "info", "[", "\"metadata\"", "]", ":", "return", "\",\"", ".", "join", "(", "map", "(", "str", ",", "info", "[", "\"metadata\"", "]",...
33.571429
0.004149
def _offbid(self, markups, withholds): """ Converts arrays of percentage price markups and capacity withholds into offers/bids and submits them to the marketplace. """ for i, g in enumerate(self.generators): ratedPMin = self._g0[g]["p_min"] ratedPMax = self._g0[g]...
[ "def", "_offbid", "(", "self", ",", "markups", ",", "withholds", ")", ":", "for", "i", ",", "g", "in", "enumerate", "(", "self", ".", "generators", ")", ":", "ratedPMin", "=", "self", ".", "_g0", "[", "g", "]", "[", "\"p_min\"", "]", "ratedPMax", "...
38.134146
0.000935
def cmd_gasheli(self, args): '''gas help commands''' usage = "Usage: gasheli <start|stop|set>" if len(args) < 1: print(usage) return if args[0] == "start": self.start_motor() elif args[0] == "stop": self.stop_motor() elif ar...
[ "def", "cmd_gasheli", "(", "self", ",", "args", ")", ":", "usage", "=", "\"Usage: gasheli <start|stop|set>\"", "if", "len", "(", "args", ")", "<", "1", ":", "print", "(", "usage", ")", "return", "if", "args", "[", "0", "]", "==", "\"start\"", ":", "sel...
29.5
0.004695
def elements(self, using, value): """Find elements in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return a List<Element ...
[ "def", "elements", "(", "self", ",", "using", ",", "value", ")", ":", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_ELEMENTS", ",", "{", "'using'", ":", "using", ",", "'value'", ":", "value", "}", ")" ]
26.6
0.005445
def _ensure_frames(cls, documents): """ Ensure all items in a list are frames by converting those that aren't. """ frames = [] for document in documents: if not isinstance(document, Frame): frames.append(cls(document)) else: ...
[ "def", "_ensure_frames", "(", "cls", ",", "documents", ")", ":", "frames", "=", "[", "]", "for", "document", "in", "documents", ":", "if", "not", "isinstance", "(", "document", ",", "Frame", ")", ":", "frames", ".", "append", "(", "cls", "(", "document...
32.363636
0.005464
def restructuredtext(text, **kwargs): """ Applies reStructuredText conversion to a string, and returns the HTML. """ from docutils import core parts = core.publish_parts(source=text, writer_name='html4css1', **kwargs) return ...
[ "def", "restructuredtext", "(", "text", ",", "*", "*", "kwargs", ")", ":", "from", "docutils", "import", "core", "parts", "=", "core", ".", "publish_parts", "(", "source", "=", "text", ",", "writer_name", "=", "'html4css1'", ",", "*", "*", "kwargs", ")",...
29.727273
0.005935
def inside_nonspeech(self, index): """ If ``index`` is contained in a nonspeech interval, return a pair ``(interval_begin, interval_end)`` such that ``interval_begin <= index < interval_end``, i.e., ``interval_end`` is assumed not to be included. Otherwise, return ``None...
[ "def", "inside_nonspeech", "(", "self", ",", "index", ")", ":", "self", ".", "_ensure_mfcc_mask", "(", ")", "if", "(", "index", "<", "0", ")", "or", "(", "index", ">=", "self", ".", "all_length", ")", "or", "(", "self", ".", "__mfcc_mask", "[", "inde...
38.4
0.005085
def CreateStorageWriter(cls, storage_format, session, path): """Creates a storage writer. Args: session (Session): session the storage changes are part of. path (str): path to the storage file. storage_format (str): storage format. Returns: StorageWriter: a storage writer or None i...
[ "def", "CreateStorageWriter", "(", "cls", ",", "storage_format", ",", "session", ",", "path", ")", ":", "if", "storage_format", "==", "definitions", ".", "STORAGE_FORMAT_SQLITE", ":", "return", "sqlite_writer", ".", "SQLiteStorageFileWriter", "(", "session", ",", ...
33.8125
0.003597
def _get_normalized_args(parser): """Return the parsed command line arguments. Support the case when executed from a shebang, where all the parameters come in sys.argv[1] in a single string separated by spaces (in this case, the third parameter is what is being executed) """ env = os.enviro...
[ "def", "_get_normalized_args", "(", "parser", ")", ":", "env", "=", "os", ".", "environ", "if", "'_'", "in", "env", "and", "env", "[", "'_'", "]", "!=", "sys", ".", "argv", "[", "0", "]", "and", "len", "(", "sys", ".", "argv", ")", ">=", "1", "...
40.076923
0.003752
def get_launch_configs(self, asgs): """Return a mapping of launch configs for the given set of asgs""" config_names = set() for a in asgs: if 'LaunchConfigurationName' not in a: continue config_names.add(a['LaunchConfigurationName']) if not config_...
[ "def", "get_launch_configs", "(", "self", ",", "asgs", ")", ":", "config_names", "=", "set", "(", ")", "for", "a", "in", "asgs", ":", "if", "'LaunchConfigurationName'", "not", "in", "a", ":", "continue", "config_names", ".", "add", "(", "a", "[", "'Launc...
42.176471
0.002729
def _request(self, method, path, server=None, **kwargs): """Execute a request to the cluster A server is selected from the server pool. """ while True: next_server = server or self._get_server() try: response = self.server_pool[next_server].reques...
[ "def", "_request", "(", "self", ",", "method", ",", "path", ",", "server", "=", "None", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "next_server", "=", "server", "or", "self", ".", "_get_server", "(", ")", "try", ":", "response", "=", ...
48.840909
0.001369
def set_cropped_metadata(input_doc, output_doc, metadata_info): """Set the metadata for the output document. Mostly just copied over, but "Producer" has a string appended to indicate that this program modified the file. That allows for the undo operation to make sure that this program cropped the file...
[ "def", "set_cropped_metadata", "(", "input_doc", ",", "output_doc", ",", "metadata_info", ")", ":", "# Setting metadata with pyPdf requires low-level pyPdf operations, see", "# http://stackoverflow.com/questions/2574676/change-metadata-of-pdf-file-with-pypdf", "if", "not", "metadata_info...
47.085106
0.005755
def str_kwargs(self): """ Generator that yields a dict of values corresponding to the ...
[ "def", "str_kwargs", "(", "self", ")", ":", "iys", ",", "ims", ",", "ids", ",", "ihmsfs", "=", "sofa_time", ".", "jd_dtf", "(", "self", ".", "scale", ".", "upper", "(", ")", ".", "encode", "(", "'utf8'", ")", ",", "6", ",", "self", ".", "jd1", ...
57.7
0.005114