text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def remove_binaries(package_dir=False): """Remove all binaries for the current platform Parameters ---------- package_dir: bool If True, remove all binaries from the `resources` directory of the qpsphere package. If False, remove all binaries from the user's cache directory. ...
[ "def", "remove_binaries", "(", "package_dir", "=", "False", ")", ":", "paths", "=", "[", "]", "if", "package_dir", ":", "pdir", "=", "RESCR_PATH", "else", ":", "pdir", "=", "CACHE_PATH", "for", "pp", "in", "pdir", ".", "iterdir", "(", ")", ":", "if", ...
24.043478
0.001739
def _gather_pillar(pillarenv, pillar_override): ''' Whenever a state run starts, gather the pillar data fresh ''' pillar = salt.pillar.get_pillar( __opts__, __grains__, __opts__['id'], __opts__['saltenv'], pillar_override=pillar_override, pillarenv=pillare...
[ "def", "_gather_pillar", "(", "pillarenv", ",", "pillar_override", ")", ":", "pillar", "=", "salt", ".", "pillar", ".", "get_pillar", "(", "__opts__", ",", "__grains__", ",", "__opts__", "[", "'id'", "]", ",", "__opts__", "[", "'saltenv'", "]", ",", "pilla...
28.75
0.002105
def set_result(self, rval: bool) -> None: """ Set the result of the evaluation. If the result is true, prune all of the children that didn't cut it :param rval: Result of evaluation """ self.result = rval if self.result: self.nodes = [pn for pn in self.nodes if pn.re...
[ "def", "set_result", "(", "self", ",", "rval", ":", "bool", ")", "->", "None", ":", "self", ".", "result", "=", "rval", "if", "self", ".", "result", ":", "self", ".", "nodes", "=", "[", "pn", "for", "pn", "in", "self", ".", "nodes", "if", "pn", ...
39.75
0.009231
def on_timer(self, event): """Timer event handler Parameters ---------- event : instance of Event The event. """ # Set relative speed and acceleration rel_speed = event.dt rel_acc = 0.1 # Get what's forward pf, pr, pl, pu = s...
[ "def", "on_timer", "(", "self", ",", "event", ")", ":", "# Set relative speed and acceleration", "rel_speed", "=", "event", ".", "dt", "rel_acc", "=", "0.1", "# Get what's forward", "pf", ",", "pr", ",", "pl", ",", "pu", "=", "self", ".", "_get_directions", ...
38.542553
0.000807
def record_source(self, src, prg=''): """ function to collect raw data from the web and hard drive Examples - new source file for ontologies, email contacts list, folder for xmas photos """ self._log(self.logFileSource , force_to_string(src), prg)
[ "def", "record_source", "(", "self", ",", "src", ",", "prg", "=", "''", ")", ":", "self", ".", "_log", "(", "self", ".", "logFileSource", ",", "force_to_string", "(", "src", ")", ",", "prg", ")" ]
47
0.013937
def _dtype_to_default_stata_fmt(dtype, column, dta_version=114, force_strl=False): """ Map numpy dtype to stata's default format for this type. Not terribly important since users can change this in Stata. Semantics are object -> "%DDs" where DD is the length of the stri...
[ "def", "_dtype_to_default_stata_fmt", "(", "dtype", ",", "column", ",", "dta_version", "=", "114", ",", "force_strl", "=", "False", ")", ":", "# TODO: Refactor to combine type with format", "# TODO: expand this to handle a default datetime format?", "if", "dta_version", "<", ...
40.222222
0.000449
def validate_proxies_config(cls, proxies): """ Specific config validation method for the "proxies" portion of a config. Checks that each proxy defines a port and a list of `upstreams`, and that each upstream entry has a host and port defined. """ for name, proxy ...
[ "def", "validate_proxies_config", "(", "cls", ",", "proxies", ")", ":", "for", "name", ",", "proxy", "in", "six", ".", "iteritems", "(", "proxies", ")", ":", "if", "\"port\"", "not", "in", "proxy", ":", "raise", "ValueError", "(", "\"No port defined for prox...
41.208333
0.001976
def _gen_memd_wrappers(cls, factory): """Generates wrappers for all the memcached operations. :param factory: A function to be called to return the wrapped method. It will be called with two arguments; the first is the unbound method being wrapped, and the second is the name ...
[ "def", "_gen_memd_wrappers", "(", "cls", ",", "factory", ")", ":", "d", "=", "{", "}", "for", "n", "in", "cls", ".", "_MEMCACHED_OPERATIONS", ":", "for", "variant", "in", "(", "n", ",", "n", "+", "\"_multi\"", ")", ":", "try", ":", "d", "[", "varia...
39
0.002275
def destripe_plus(inputfile, suffix='strp', stat='pmode1', maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, scimask1=None, scimask2=None, dqbits=None, rpt_clean=0, atol=0.01, cte_correct=True, clobber=False, verbose=True): r"""Cali...
[ "def", "destripe_plus", "(", "inputfile", ",", "suffix", "=", "'strp'", ",", "stat", "=", "'pmode1'", ",", "maxiter", "=", "15", ",", "sigrej", "=", "2.0", ",", "lower", "=", "None", ",", "upper", "=", "None", ",", "binwidth", "=", "0.3", ",", "scima...
38.492268
0.000261
def dummyListOfDicts(size=100): """ returns a list (of the given size) of dicts with fake data. some dictionary keys are missing for some of the items. """ titles="ahp,halfwidth,peak,expT,expI,sweep".split(",") ld=[] #list of dicts for i in range(size): d={} for t in titles: ...
[ "def", "dummyListOfDicts", "(", "size", "=", "100", ")", ":", "titles", "=", "\"ahp,halfwidth,peak,expT,expI,sweep\"", ".", "split", "(", "\",\"", ")", "ld", "=", "[", "]", "#list of dicts", "for", "i", "in", "range", "(", "size", ")", ":", "d", "=", "{"...
35.4375
0.024055
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str: """ From a consistent list of dictionaries mapping fieldnames to values, make a TSV file. """ if not dictlist: return "" fieldnames = dictlist[0].keys() tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n" for d i...
[ "def", "dictlist_to_tsv", "(", "dictlist", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "str", ":", "if", "not", "dictlist", ":", "return", "\"\"", "fieldnames", "=", "dictlist", "[", "0", "]", ".", "keys", "(", ")", "tsv"...
33.666667
0.00241
def get_stories(label_type): """ Returns a list of the stories in the Na corpus. """ prefixes = get_story_prefixes(label_type) texts = list(set([prefix.split(".")[0].split("/")[1] for prefix in prefixes])) return texts
[ "def", "get_stories", "(", "label_type", ")", ":", "prefixes", "=", "get_story_prefixes", "(", "label_type", ")", "texts", "=", "list", "(", "set", "(", "[", "prefix", ".", "split", "(", "\".\"", ")", "[", "0", "]", ".", "split", "(", "\"/\"", ")", "...
38.333333
0.008511
def stringer(x): """ Takes an object and makes it stringy >>> print(stringer({'a': 1, 2: 3, 'b': [1, 'c', 2.5]})) {'b': ['1', 'c', '2.5'], 'a': '1', '2': '3'} """ if isinstance(x, string_types): return x if isinstance(x, (list, tuple)): return [stringer(y) for y in x] if ...
[ "def", "stringer", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "string_types", ")", ":", "return", "x", "if", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "stringer", "(", "y", ")", "for", "y", ...
32.461538
0.002304
def id_nameDAVID(df,GTF=None,name_id=None): """ Given a DAVIDenrich output it converts ensembl gene ids to genes names and adds this column to the output :param df: a dataframe output from DAVIDenrich :param GTF: a GTF dataframe from readGTF() :param name_id: instead of a gtf dataframe a dataframe ...
[ "def", "id_nameDAVID", "(", "df", ",", "GTF", "=", "None", ",", "name_id", "=", "None", ")", ":", "if", "name_id", "is", "None", ":", "gene_name", "=", "retrieve_GTF_field", "(", "'gene_name'", ",", "GTF", ")", "gene_id", "=", "retrieve_GTF_field", "(", ...
39.860465
0.023918
def execution_time(self, value): """ Force the execution_time to always be a datetime :param value: :return: """ if value: self._execution_time = parse(value) if isinstance(value, type_check) else value
[ "def", "execution_time", "(", "self", ",", "value", ")", ":", "if", "value", ":", "self", ".", "_execution_time", "=", "parse", "(", "value", ")", "if", "isinstance", "(", "value", ",", "type_check", ")", "else", "value" ]
31.875
0.01145
def load_precision(filename): """ Load a CLASS precision file into a dictionary. Parameters ---------- filename : str the name of an existing file to load, or one in the files included as part of the CLASS source Returns ------- dict : the precision parameters l...
[ "def", "load_precision", "(", "filename", ")", ":", "# also look in data dir", "path", "=", "_find_file", "(", "filename", ")", "r", "=", "dict", "(", ")", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "exec", "(", "f", ".", "read", "...
20.521739
0.002024
def sed(self, name, **kwargs): """Generate a spectral energy distribution (SED) for a source. This function will fit the normalization of the source in each energy bin. By default the SED will be generated with the analysis energy bins but a custom binning can be defined with t...
[ "def", "sed", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "timer", "=", "Timer", ".", "create", "(", "start", "=", "True", ")", "name", "=", "self", ".", "roi", ".", "get_source_by_name", "(", "name", ")", ".", "name", "# Create sc...
35.56
0.001094
def http_request(self, verb, uri, data=None, headers=None, files=None, response_format=None, is_rdf = True, stream = False ): ''' Primary route for all HTTP requests to repository. Ability to set most parameters for requests library, with some additional convenience parameters as well....
[ "def", "http_request", "(", "self", ",", "verb", ",", "uri", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "files", "=", "None", ",", "response_format", "=", "None", ",", "is_rdf", "=", "True", ",", "stream", "=", "False", ")", ":", "...
35.104478
0.036394
def is_unit_or_unitstring(value): """must be an astropy.unit""" if is_unit(value)[0]: return True, value try: unit = units.Unit(value) except: return False, value else: return True, unit
[ "def", "is_unit_or_unitstring", "(", "value", ")", ":", "if", "is_unit", "(", "value", ")", "[", "0", "]", ":", "return", "True", ",", "value", "try", ":", "unit", "=", "units", ".", "Unit", "(", "value", ")", "except", ":", "return", "False", ",", ...
22.9
0.008403
def get(src_hdfs_path, dest_path, **kwargs): """\ Copy the contents of ``src_hdfs_path`` to ``dest_path``. ``dest_path`` is forced to be interpreted as an ordinary local path (see :func:`~path.abspath`). The source file is opened for reading and the copy is opened for writing. Additional keyword ...
[ "def", "get", "(", "src_hdfs_path", ",", "dest_path", ",", "*", "*", "kwargs", ")", ":", "cp", "(", "src_hdfs_path", ",", "path", ".", "abspath", "(", "dest_path", ",", "local", "=", "True", ")", ",", "*", "*", "kwargs", ")" ]
44.2
0.002217
def remove(self): """ Remove the directory. """ lib.gp_camera_folder_remove_dir( self._cam._cam, self.parent.path.encode(), self.name.encode(), self._cam._ctx)
[ "def", "remove", "(", "self", ")", ":", "lib", ".", "gp_camera_folder_remove_dir", "(", "self", ".", "_cam", ".", "_cam", ",", "self", ".", "parent", ".", "path", ".", "encode", "(", ")", ",", "self", ".", "name", ".", "encode", "(", ")", ",", "sel...
39
0.01005
def __bindings(self): """Binds events to handlers""" self.textctrl.Bind(wx.EVT_TEXT, self.OnText) self.fontbutton.Bind(wx.EVT_BUTTON, self.OnFont) self.Bind(csel.EVT_COLOURSELECT, self.OnColor)
[ "def", "__bindings", "(", "self", ")", ":", "self", ".", "textctrl", ".", "Bind", "(", "wx", ".", "EVT_TEXT", ",", "self", ".", "OnText", ")", "self", ".", "fontbutton", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "OnFont", ")", "s...
36.833333
0.00885
def StartAndWait(self): """Starts the task and waits until it is done.""" self.StartTask() self.WaitUntilTaskDone(pydaq.DAQmx_Val_WaitInfinitely) self.ClearTask()
[ "def", "StartAndWait", "(", "self", ")", ":", "self", ".", "StartTask", "(", ")", "self", ".", "WaitUntilTaskDone", "(", "pydaq", ".", "DAQmx_Val_WaitInfinitely", ")", "self", ".", "ClearTask", "(", ")" ]
38
0.010309
def fit_sparse(model_matrix, response, model, model_coefficients_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_iterations=None, maximum_full_sweeps_per_iteration=1, lea...
[ "def", "fit_sparse", "(", "model_matrix", ",", "response", ",", "model", ",", "model_coefficients_start", ",", "tolerance", ",", "l1_regularizer", ",", "l2_regularizer", "=", "None", ",", "maximum_iterations", "=", "None", ",", "maximum_full_sweeps_per_iteration", "="...
39.173228
0.001176
def load(self): """Return the current load. The load is represented as a float, where 1.0 represents having hit one of the flow control limits, and values between 0.0 and 1.0 represent how close we are to them. (0.5 means we have exactly half of what the flow control setting all...
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "_leaser", "is", "None", ":", "return", "0", "return", "max", "(", "[", "self", ".", "_leaser", ".", "message_count", "/", "self", ".", "_flow_control", ".", "max_messages", ",", "self", ".", "...
36.52
0.002134
def decision_function(self, X=None): """Output the decision value of the prediction. if X is not equal to self.test_raw_data\\_, i.e. predict is not called, first generate the test_data after getting the test_data, get the decision value via self.clf. if X is None, test_data\\_ ...
[ "def", "decision_function", "(", "self", ",", "X", "=", "None", ")", ":", "if", "X", "is", "not", "None", "and", "not", "self", ".", "_is_equal_to_test_raw_data", "(", "X", ")", ":", "for", "x", "in", "X", ":", "assert", "len", "(", "x", ")", "==",...
45.574074
0.000796
def namedb_get_all_importing_namespace_hashes( self, current_block ): """ Get the list of all non-expired preordered and revealed namespace hashes. """ query = "SELECT preorder_hash FROM namespaces WHERE (op = ? AND reveal_block < ?) OR (op = ? AND block_number < ?);" args = (NAMESPACE_REVEAL, curr...
[ "def", "namedb_get_all_importing_namespace_hashes", "(", "self", ",", "current_block", ")", ":", "query", "=", "\"SELECT preorder_hash FROM namespaces WHERE (op = ? AND reveal_block < ?) OR (op = ? AND block_number < ?);\"", "args", "=", "(", "NAMESPACE_REVEAL", ",", "current_block",...
42.357143
0.016502
def send_approve_mail(request, user): """ Sends an email to staff in listed in the setting ``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``. """ approval_emails = split_addresses(settings.ACCOUNTS_APPROVAL_EMAILS) if not approv...
[ "def", "send_approve_mail", "(", "request", ",", "user", ")", ":", "approval_emails", "=", "split_addresses", "(", "settings", ".", "ACCOUNTS_APPROVAL_EMAILS", ")", "if", "not", "approval_emails", ":", "return", "context", "=", "{", "\"request\"", ":", "request", ...
39.5
0.001374
def get_current_cmus(): """ Get the current song from cmus. """ result = subprocess.run('cmus-remote -Q'.split(' '), check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) info = {} for line in result.stdout.decode().split('\n'): line = line.split(' ')...
[ "def", "get_current_cmus", "(", ")", ":", "result", "=", "subprocess", ".", "run", "(", "'cmus-remote -Q'", ".", "split", "(", "' '", ")", ",", "check", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", ...
30.619048
0.001508
def build_import_pattern(mapping1, mapping2): u""" mapping1: A dict mapping py3k modules to all possible py2k replacements mapping2: A dict mapping py2k modules to the things they do This builds a HUGE pattern to match all ways that things can be imported """ # py3k: urllib.request, py2k: ('urll...
[ "def", "build_import_pattern", "(", "mapping1", ",", "mapping2", ")", ":", "# py3k: urllib.request, py2k: ('urllib2', 'urllib')", "yield", "from_import", "%", "(", "all_modules_subpattern", "(", ")", ")", "for", "py3k", ",", "py2k", "in", "mapping1", ".", "items", "...
44.45
0.001101
def get_qtls_from_mapqtl_data(matrix, threshold, inputfile): """Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective...
[ "def", "get_qtls_from_mapqtl_data", "(", "matrix", ",", "threshold", ",", "inputfile", ")", ":", "trait_name", "=", "inputfile", ".", "split", "(", "')_'", ",", "1", ")", "[", "1", "]", ".", "split", "(", "'.mqo'", ")", "[", "0", "]", "qtls", "=", "[...
31.285714
0.000886
def listen(cls, event, func): """Add a callback for a signal against the class""" signal(event).connect(func, sender=cls)
[ "def", "listen", "(", "cls", ",", "event", ",", "func", ")", ":", "signal", "(", "event", ")", ".", "connect", "(", "func", ",", "sender", "=", "cls", ")" ]
45
0.014599
def get_hostname(): ''' Determines the current hostname by probing ``uname -n``. Falls back to ``hostname`` in case of problems. |appteardown| if both failed (usually they don't but consider this if you are debugging weird problems..) :returns: The hostname as string. Domain parts wil...
[ "def", "get_hostname", "(", ")", ":", "h", "=", "shell_run", "(", "'uname -n'", ",", "critical", "=", "False", ",", "verbose", "=", "False", ")", "if", "not", "h", ":", "h", "=", "shell_run", "(", "'hostname'", ",", "critical", "=", "False", ",", "ve...
32.611111
0.001656
def modifie(self, key: str, value: Any) -> None: """Store the modification. `value` should be dumped in DB compatible format.""" if key in self.FIELDS_OPTIONS: self.modifie_options(key, value) else: self.modifications[key] = value
[ "def", "modifie", "(", "self", ",", "key", ":", "str", ",", "value", ":", "Any", ")", "->", "None", ":", "if", "key", "in", "self", ".", "FIELDS_OPTIONS", ":", "self", ".", "modifie_options", "(", "key", ",", "value", ")", "else", ":", "self", ".",...
45.5
0.010791
def main(): """Main function.""" time_start = time.time() logging.info('loading vocab file from dataset: %s', args.vocab) vocab_obj = nlp.data.utils._load_pretrained_vocab(args.vocab) tokenizer = BERTTokenizer( vocab=vocab_obj, lower='uncased' in args.vocab) input_files = [] for inp...
[ "def", "main", "(", ")", ":", "time_start", "=", "time", ".", "time", "(", ")", "logging", ".", "info", "(", "'loading vocab file from dataset: %s'", ",", "args", ".", "vocab", ")", "vocab_obj", "=", "nlp", ".", "data", ".", "utils", ".", "_load_pretrained...
34.45614
0.001485
def write_namespaces(self, namespaces): """write the module-level namespace-generating callable.""" self.printer.writelines( "def _mako_get_namespace(context, name):", "try:", "return context.namespaces[(__name__, name)]", "except KeyError:...
[ "def", "write_namespaces", "(", "self", ",", "namespaces", ")", ":", "self", ".", "printer", ".", "writelines", "(", "\"def _mako_get_namespace(context, name):\"", ",", "\"try:\"", ",", "\"return context.namespaces[(__name__, name)]\"", ",", "\"except KeyError:\"", ",", "...
44.946237
0.001404
def stem(self, word): """Return the stem of a word according to the Schinke stemmer. Parameters ---------- word : str The word to stem Returns ------- str Word stem Examples -------- >>> stmr = Schinke() >...
[ "def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "lower", "(", ")", ")", ")", "word", "=", "''", ".", "join", "(", "c", "for", "c", "in", "word", "if", "c", "in", ...
26.735537
0.000596
def adjacent(predicate, iterable, distance=1): """Return an iterable over `(bool, item)` tuples where the `item` is drawn from *iterable* and the `bool` indicates whether that item satisfies the *predicate* or is adjacent to an item that does. For example, to find whether items are adjacent to a ``3``:...
[ "def", "adjacent", "(", "predicate", ",", "iterable", ",", "distance", "=", "1", ")", ":", "# Allow distance=0 mainly for testing that it reproduces results with map()", "if", "distance", "<", "0", ":", "raise", "ValueError", "(", "'distance must be at least 0'", ")", "...
41.945946
0.00063
def handle(cls, value, **kwargs): """Use a value from the environment or fall back to a default if the environment doesn't contain the variable. Format of value: <env_var>::<default value> For example: Groups: ${default app_security_groups::sg-12345,sg-6789...
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "try", ":", "env_var_name", ",", "default_val", "=", "value", ".", "split", "(", "\"::\"", ",", "1", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Invalid ...
33.310345
0.002012
def preScale(self, sx, sy): """Calculate pre scaling and replace current matrix.""" self.a *= sx self.b *= sx self.c *= sy self.d *= sy return self
[ "def", "preScale", "(", "self", ",", "sx", ",", "sy", ")", ":", "self", ".", "a", "*=", "sx", "self", ".", "b", "*=", "sx", "self", ".", "c", "*=", "sy", "self", ".", "d", "*=", "sy", "return", "self" ]
27
0.010256
def find_amp_phase(angle, data, npeaks=3, min_amp=None, min_phase=None): """Estimate amplitude and phase of an approximately sinusoidal quantity using `scipy.optimize.curve_fit`. Phase is defined as the angle at which the cosine curve fit reaches its first peak. It is assumed that phase is positiv...
[ "def", "find_amp_phase", "(", "angle", ",", "data", ",", "npeaks", "=", "3", ",", "min_amp", "=", "None", ",", "min_phase", "=", "None", ")", ":", "# First subtract the mean of the data\r", "data", "=", "data", "-", "data", ".", "mean", "(", ")", "# Make s...
35.666667
0.001605
def get_ngroups(self, field=None): ''' Returns ngroups count if it was specified in the query, otherwise ValueError. If grouping on more than one field, provide the field argument to specify which count you are looking for. ''' field = field if field else self._determine_group_f...
[ "def", "get_ngroups", "(", "self", ",", "field", "=", "None", ")", ":", "field", "=", "field", "if", "field", "else", "self", ".", "_determine_group_field", "(", "field", ")", "if", "'ngroups'", "in", "self", ".", "data", "[", "'grouped'", "]", "[", "f...
52.8
0.009311
def get_next_iteration(self, iteration, iteration_kwargs={}): """ Returns a SH iteration with only evaluations on the biggest budget Parameters ---------- iteration: int the index of the iteration to be instantiated Returns ------- SuccessiveHalving: the SuccessiveHalving iteration with the ...
[ "def", "get_next_iteration", "(", "self", ",", "iteration", ",", "iteration_kwargs", "=", "{", "}", ")", ":", "budgets", "=", "[", "self", ".", "max_budget", "]", "ns", "=", "[", "self", ".", "budget_per_iteration", "//", "self", ".", "max_budget", "]", ...
29.4
0.042834
def __EncodedAttribute_generic_encode_rgb24(self, rgb24, width=0, height=0, quality=0, format=_ImageFormat.RawImage): """Internal usage only""" if not is_seq(rgb24): raise TypeError("Expected sequence (str, numpy.ndarray, list, tuple " "or bytearray) as first argument") is_s...
[ "def", "__EncodedAttribute_generic_encode_rgb24", "(", "self", ",", "rgb24", ",", "width", "=", "0", ",", "height", "=", "0", ",", "quality", "=", "0", ",", "format", "=", "_ImageFormat", ".", "RawImage", ")", ":", "if", "not", "is_seq", "(", "rgb24", ")...
43.911111
0.001485
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account. :param remote: The remote application. :returns: The HTML response. """ if not current_user.is_authenticated: return current_app.login_manager.unauthorized() remote_account = RemoteAccount.get(user_...
[ "def", "disconnect_handler", "(", "remote", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "current_user", ".", "is_authenticated", ":", "return", "current_app", ".", "login_manager", ".", "unauthorized", "(", ")", "remote_account", "=", "...
36.434783
0.001163
def updateMesh(self, polydata): """ Overwrite the polygonal mesh of the actor with a new one. """ self.poly = polydata self.mapper.SetInputData(polydata) self.mapper.Modified() return self
[ "def", "updateMesh", "(", "self", ",", "polydata", ")", ":", "self", ".", "poly", "=", "polydata", "self", ".", "mapper", ".", "SetInputData", "(", "polydata", ")", "self", ".", "mapper", ".", "Modified", "(", ")", "return", "self" ]
29.625
0.008197
def Y_ampl(self, new_y_scale): """Make scaling on Y axis using predefined values""" self.parent.value('y_scale', new_y_scale) self.parent.traces.display()
[ "def", "Y_ampl", "(", "self", ",", "new_y_scale", ")", ":", "self", ".", "parent", ".", "value", "(", "'y_scale'", ",", "new_y_scale", ")", "self", ".", "parent", ".", "traces", ".", "display", "(", ")" ]
43.75
0.011236
def Print(self): """Prints the hypotheses and their probabilities.""" for hypo, prob in sorted(self.Items()): print(hypo, prob)
[ "def", "Print", "(", "self", ")", ":", "for", "hypo", ",", "prob", "in", "sorted", "(", "self", ".", "Items", "(", ")", ")", ":", "print", "(", "hypo", ",", "prob", ")" ]
38
0.012903
def processFiles(args): """ Generates and error checks each file's information before the compilation actually starts """ to_process = [] for filename in args['filenames']: file = dict() if args['include']: file['include'] = INCLUDE_STRING + ''.join( ['-...
[ "def", "processFiles", "(", "args", ")", ":", "to_process", "=", "[", "]", "for", "filename", "in", "args", "[", "'filenames'", "]", ":", "file", "=", "dict", "(", ")", "if", "args", "[", "'include'", "]", ":", "file", "[", "'include'", "]", "=", "...
40.472727
0.001316
def rollback(self): """Implementation of NAPALM method rollback.""" commands = [] commands.append('configure replace flash:rollback-0') commands.append('write memory') self.device.run_commands(commands)
[ "def", "rollback", "(", "self", ")", ":", "commands", "=", "[", "]", "commands", ".", "append", "(", "'configure replace flash:rollback-0'", ")", "commands", ".", "append", "(", "'write memory'", ")", "self", ".", "device", ".", "run_commands", "(", "commands"...
39.5
0.008264
def start(): r"""Starts ec. """ processPendingModules() if not state.main_module_name in ModuleMembers: # don't start the core when main is not Ec-ed return MainModule = sys.modules[state.main_module_name] if not MainModule.__ec_member__.Members: # there was some error while loading script(...
[ "def", "start", "(", ")", ":", "processPendingModules", "(", ")", "if", "not", "state", ".", "main_module_name", "in", "ModuleMembers", ":", "# don't start the core when main is not Ec-ed\r", "return", "MainModule", "=", "sys", ".", "modules", "[", "state", ".", "...
20.724138
0.031797
def generate_oauth2_headers(self): """Generates header for oauth2 """ encoded_credentials = base64.b64encode(('{0}:{1}'.format(self.consumer_key,self.consumer_secret)).encode('utf-8')) headers={ 'Authorization':'Basic {0}'.format(encoded_credentials.decode('utf-8')), ...
[ "def", "generate_oauth2_headers", "(", "self", ")", ":", "encoded_credentials", "=", "base64", ".", "b64encode", "(", "(", "'{0}:{1}'", ".", "format", "(", "self", ".", "consumer_key", ",", "self", ".", "consumer_secret", ")", ")", ".", "encode", "(", "'utf-...
40
0.017115
def _add_snps( self, snps, discrepant_snp_positions_threshold, discrepant_genotypes_threshold, save_output, ): """ Add SNPs to this Individual. Parameters ---------- snps : SNPs SNPs to add discrepant_snp_positions_threshol...
[ "def", "_add_snps", "(", "self", ",", "snps", ",", "discrepant_snp_positions_threshold", ",", "discrepant_genotypes_threshold", ",", "save_output", ",", ")", ":", "discrepant_positions", "=", "pd", ".", "DataFrame", "(", ")", "discrepant_genotypes", "=", "pd", ".", ...
36.579618
0.002034
def get_points(orig, dest, taillen): """Return a pair of lists of points for use making an arrow. The first list is the beginning and end point of the trunk of the arrow. The second list is the arrowhead. """ # Adjust the start and end points so they're on the first non-transparent pixel. # y...
[ "def", "get_points", "(", "orig", ",", "dest", ",", "taillen", ")", ":", "# Adjust the start and end points so they're on the first non-transparent pixel.", "# y = slope(x-ox) + oy", "# x = (y - oy) / slope + ox", "ox", ",", "oy", "=", "orig", ".", "center", "ow", ",", "o...
32.198473
0.00046
def depth_atleast(list_, depth): r""" Returns if depth of list is at least ``depth`` Args: list_ (list): depth (int): Returns: bool: True CommandLine: python -m utool.util_dict --exec-depth_atleast --show Example: >>> # DISABLE_DOCTEST >>> from...
[ "def", "depth_atleast", "(", "list_", ",", "depth", ")", ":", "if", "depth", "==", "0", ":", "return", "True", "else", ":", "try", ":", "return", "all", "(", "[", "depth_atleast", "(", "item", ",", "depth", "-", "1", ")", "for", "item", "in", "list...
23.733333
0.00135
def nsum0(lx): """ Accepts log-values as input, exponentiates them, sums down the rows (first dimension), normalizes and returns the result. Handles underflow by rescaling so that the largest values is exactly 1.0. """ lx = numpy.asarray(lx) base = lx.max() x = numpy.exp(lx - base) ssum = x.sum(0) r...
[ "def", "nsum0", "(", "lx", ")", ":", "lx", "=", "numpy", ".", "asarray", "(", "lx", ")", "base", "=", "lx", ".", "max", "(", ")", "x", "=", "numpy", ".", "exp", "(", "lx", "-", "base", ")", "ssum", "=", "x", ".", "sum", "(", "0", ")", "re...
28.0625
0.021552
def unblock_all(self): """ Unblock all emitters in this group. """ self.unblock() for em in self._emitters.values(): em.unblock()
[ "def", "unblock_all", "(", "self", ")", ":", "self", ".", "unblock", "(", ")", "for", "em", "in", "self", ".", "_emitters", ".", "values", "(", ")", ":", "em", ".", "unblock", "(", ")" ]
28
0.011561
def version(self) -> Optional[str]: """ 获取 http 版本 """ if self._version is None: self._version = self._parser.get_http_version() return self._version
[ "def", "version", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "_version", "is", "None", ":", "self", ".", "_version", "=", "self", ".", "_parser", ".", "get_http_version", "(", ")", "return", "self", ".", "_version" ]
27.857143
0.00995
def _2ndDerivInt(x,y,z,dens,densDeriv,b2,c2,i,j,glx=None,glw=None): """Integral that gives the 2nd derivative of the potential in x,y,z""" def integrand(s): t= 1/s**2.-1. m= numpy.sqrt(x**2./(1.+t)+y**2./(b2+t)+z**2./(c2+t)) return (densDeriv(m) *(x/(1.+t)*(i==0)+y/(b2+t)...
[ "def", "_2ndDerivInt", "(", "x", ",", "y", ",", "z", ",", "dens", ",", "densDeriv", ",", "b2", ",", "c2", ",", "i", ",", "j", ",", "glx", "=", "None", ",", "glw", "=", "None", ")", ":", "def", "integrand", "(", "s", ")", ":", "t", "=", "1",...
49.285714
0.046942
def set_marginal_histogram_title(ax, fmt, color, label=None, rotated=False): """ Sets the title of the marginal histograms. Parameters ---------- ax : Axes The `Axes` instance for the plot. fmt : str The string to add to the title. color : str The color of the text to ad...
[ "def", "set_marginal_histogram_title", "(", "ax", ",", "fmt", ",", "color", ",", "label", "=", "None", ",", "rotated", "=", "False", ")", ":", "# get rotation angle of the title", "rotation", "=", "270", "if", "rotated", "else", "0", "# get how much to displace ti...
32.5
0.000415
def to_str(string): """ Return the given string (either byte string or Unicode string) converted to native-str, that is, a byte string on Python 2, or a Unicode string on Python 3. Return ``None`` if ``string`` is ``None``. :param str string: the string to convert to native-str :rtype: nat...
[ "def", "to_str", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "None", "if", "isinstance", "(", "string", ",", "str", ")", ":", "return", "string", "if", "PY2", ":", "return", "string", ".", "encode", "(", "\"utf-8\"", ")", "r...
27.722222
0.001938
def attach_team(context, id, team_id): """attach_team(context, id, team_id) Attach a team to a topic. >>> dcictl topic-attach-team [OPTIONS] :param string id: ID of the topic to attach to [required] :param string team_id: ID of the team to attach to this topic [required] """ team_id = tea...
[ "def", "attach_team", "(", "context", ",", "id", ",", "team_id", ")", ":", "team_id", "=", "team_id", "or", "identity", ".", "my_team_id", "(", "context", ")", "result", "=", "topic", ".", "attach_team", "(", "context", ",", "id", "=", "id", ",", "team...
35.076923
0.002137
def visit_Div(self, node: AST, dfltChaining: bool = True) -> str: """Return division sign.""" return '/' if self.compact else ' / '
[ "def", "visit_Div", "(", "self", ",", "node", ":", "AST", ",", "dfltChaining", ":", "bool", "=", "True", ")", "->", "str", ":", "return", "'/'", "if", "self", ".", "compact", "else", "' / '" ]
48.333333
0.013605
def flush(self): """Forces a flush from the internal queue to the server""" queue = self.queue size = queue.qsize() queue.join() self.log.debug('successfully flushed %s items.', size)
[ "def", "flush", "(", "self", ")", ":", "queue", "=", "self", ".", "queue", "size", "=", "queue", ".", "qsize", "(", ")", "queue", ".", "join", "(", ")", "self", ".", "log", ".", "debug", "(", "'successfully flushed %s items.'", ",", "size", ")" ]
36.333333
0.008969
def hugoniot_t_single(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=3. * constants.R, t_ref=300., c_v=0.): """ internal function to calculate pressure along Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in k...
[ "def", "hugoniot_t_single", "(", "rho", ",", "rho0", ",", "c0", ",", "s", ",", "gamma0", ",", "q", ",", "theta0", ",", "n", ",", "mass", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ",", "t_ref", "=", "300.", ",", "c_v", "=", "0.", ")...
41.103448
0.00082
def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]): """ Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint] """ for trigger, entry_point in plugins.items(): try: p...
[ "def", "print_plugin_list", "(", "plugins", ":", "Dict", "[", "str", ",", "pkg_resources", ".", "EntryPoint", "]", ")", ":", "for", "trigger", ",", "entry_point", "in", "plugins", ".", "items", "(", ")", ":", "try", ":", "plugin_class", "=", "entry_point",...
30.894737
0.001653
def scan(self, data, part): """Scan a string. Parameters ---------- data : `str` String to scan. part : `bool` True if data is partial. Returns ------- `generator` of (`str` or `markovchain.scanner.Scanner.END`) Token ...
[ "def", "scan", "(", "self", ",", "data", ",", "part", ")", ":", "if", "not", "self", ".", "end_chars", ":", "yield", "from", "data", "self", ".", "start", "=", "self", ".", "start", "or", "bool", "(", "data", ")", "self", ".", "end", "=", "False"...
27.810811
0.001878
def is_app_folder(self, folder): """ checks if a folder """ with open('%s/%s/build.gradle' % (self.path, folder)) as f: for line in f.readlines(): if config.gradle_plugin in line: return True return False
[ "def", "is_app_folder", "(", "self", ",", "folder", ")", ":", "with", "open", "(", "'%s/%s/build.gradle'", "%", "(", "self", ".", "path", ",", "folder", ")", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "if", "con...
26.777778
0.016064
def cache_get(key): """ Wrapper for ``cache.get``. The expiry time for the cache entry is stored with the entry. If the expiry time has past, put the stale entry back into cache, and don't return it to trigger a fake cache miss. """ packed = cache.get(_hashed_key(key)) if packed is None:...
[ "def", "cache_get", "(", "key", ")", ":", "packed", "=", "cache", ".", "get", "(", "_hashed_key", "(", "key", ")", ")", "if", "packed", "is", "None", ":", "return", "None", "value", ",", "refresh_time", ",", "refreshed", "=", "packed", "if", "(", "ti...
35.133333
0.001848
def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'): """A generic function to load mnist-like dataset. Parameters: ---------- shape : tuple The shape of digit images. path : str The path that the data is downloaded to. name : str T...
[ "def", "_load_mnist_dataset", "(", "shape", ",", "path", ",", "name", "=", "'mnist'", ",", "url", "=", "'http://yann.lecun.com/exdb/mnist/'", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "# Define functions for loading ...
46.377049
0.000692
def add_method(function, klass, name=None): '''Add an existing function to a class as a method. Note: Consider using the extend decorator as a more readable alternative to using this function directly. Args: function: The function to be added to the class klass. klass: Th...
[ "def", "add_method", "(", "function", ",", "klass", ",", "name", "=", "None", ")", ":", "# Should we be using functools.update_wrapper in here?\r", "if", "name", "is", "None", ":", "name", "=", "function_name", "(", "function", ")", "if", "hasattr", "(", "klass"...
34.586207
0.00097
def get_file(self, name, save_to, add_to_cache=True, force_refresh=False, _lock_exclusive=False): """Retrieves file identified by ``name``. The file is saved as ``save_to``. If ``add_to_cache`` is ``True``, the file is added to the local store. If ``force_refresh`` is ...
[ "def", "get_file", "(", "self", ",", "name", ",", "save_to", ",", "add_to_cache", "=", "True", ",", "force_refresh", "=", "False", ",", "_lock_exclusive", "=", "False", ")", ":", "uname", ",", "version", "=", "split_name", "(", "name", ")", "lock", "=", ...
41.322581
0.001525
def usage(path): ''' Show in which disk the chunks are allocated. CLI Example: .. code-block:: bash salt '*' btrfs.usage /your/mountpoint ''' out = __salt__['cmd.run_all']("btrfs filesystem usage {0}".format(path)) salt.utils.fsutils._verify_run(out) ret = {} for section ...
[ "def", "usage", "(", "path", ")", ":", "out", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "\"btrfs filesystem usage {0}\"", ".", "format", "(", "path", ")", ")", "salt", ".", "utils", ".", "fsutils", ".", "_verify_run", "(", "out", ")", "ret", "=", ...
26.869565
0.001563
def ast2str(expr, level=0, names=None): """convert compiled ast to gene_reaction_rule str Parameters ---------- expr : str string for a gene reaction rule, e.g "a and b" level : int internal use only names : dict Dict where each element id a gene identifier and the value...
[ "def", "ast2str", "(", "expr", ",", "level", "=", "0", ",", "names", "=", "None", ")", ":", "if", "isinstance", "(", "expr", ",", "Expression", ")", ":", "return", "ast2str", "(", "expr", ".", "body", ",", "0", ",", "names", ")", "if", "hasattr", ...
35.5
0.000685
def update_serial(self, new_serial): """Updates the serial number of a device. The "serial number" used with adb's `-s` arg is not necessarily the actual serial number. For remote devices, it could be a combination of host names and port numbers. This is used for when such iden...
[ "def", "update_serial", "(", "self", ",", "new_serial", ")", ":", "new_serial", "=", "str", "(", "new_serial", ")", "if", "self", ".", "has_active_service", ":", "raise", "DeviceError", "(", "self", ",", "'Cannot change device serial number when there is service runni...
38.735294
0.002222
def find_store_dirs(cls): """ Returns the primary package directory and any additional ones from QUILT_PACKAGE_DIRS. """ store_dirs = [default_store_location()] extra_dirs_str = os.getenv('QUILT_PACKAGE_DIRS') if extra_dirs_str: store_dirs.extend(extra_dirs_st...
[ "def", "find_store_dirs", "(", "cls", ")", ":", "store_dirs", "=", "[", "default_store_location", "(", ")", "]", "extra_dirs_str", "=", "os", ".", "getenv", "(", "'QUILT_PACKAGE_DIRS'", ")", "if", "extra_dirs_str", ":", "store_dirs", ".", "extend", "(", "extra...
39
0.008357
def requests_admin(request, pk): """Table display of each request for a given product. Allows the given Page pk to refer to a direct parent of the ProductVariant model or be the ProductVariant model itself. This allows for the standard longclaw product modelling philosophy where ProductVariant refe...
[ "def", "requests_admin", "(", "request", ",", "pk", ")", ":", "page", "=", "Page", ".", "objects", ".", "get", "(", "pk", "=", "pk", ")", ".", "specific", "if", "hasattr", "(", "page", ",", "'variants'", ")", ":", "requests", "=", "ProductRequest", "...
38.47619
0.001208
def get(self, master_id): """ Get a list of revisions by master ID :param master_id: :return: """ collection_name = self.request.headers.get("collection") self.client = BaseAsyncMotorDocument("%s_revisions" % collection_name) limit = self.get_query_argum...
[ "def", "get", "(", "self", ",", "master_id", ")", ":", "collection_name", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "\"collection\"", ")", "self", ".", "client", "=", "BaseAsyncMotorDocument", "(", "\"%s_revisions\"", "%", "collection_name"...
40.766667
0.000798
def now(years=0, days=0, hours=0, minutes=0, seconds=0): """ :param years: int delta of years from now :param days: int delta of days from now :param hours: int delta of hours from now :param minutes: int delta of minutes from now :param seconds: float delta of seconds from now :retur...
[ "def", "now", "(", "years", "=", "0", ",", "days", "=", "0", ",", "hours", "=", "0", ",", "minutes", "=", "0", ",", "seconds", "=", "0", ")", ":", "date_time", "=", "datetime", ".", "utcnow", "(", ")", "date_time", "+=", "timedelta", "(", "days",...
42.153846
0.001786
def set_tile(self, codepoint: int, tile: np.array) -> None: """Upload a tile into this array. The tile can be in 32-bit color (height, width, rgba), or grey-scale (height, width). The tile should have a dtype of ``np.uint8``. This data may need to be sent to graphics card memory, this...
[ "def", "set_tile", "(", "self", ",", "codepoint", ":", "int", ",", "tile", ":", "np", ".", "array", ")", "->", "None", ":", "tile", "=", "np", ".", "ascontiguousarray", "(", "tile", ",", "dtype", "=", "np", ".", "uint8", ")", "if", "tile", ".", "...
39.923077
0.001881
def _SMOTE(T, N, k, h = 1.0): """ Returns (N/100) * n_minority_samples synthetic minority samples. Parameters ---------- T : array-like, shape = [n_minority_samples, n_features] Holds the minority samples N : percetange of new synthetic samples: n_synthetic_samples = N/100 * n_m...
[ "def", "_SMOTE", "(", "T", ",", "N", ",", "k", ",", "h", "=", "1.0", ")", ":", "n_minority_samples", ",", "n_features", "=", "T", ".", "shape", "if", "N", "<", "100", ":", "#create synthetic samples only for a subset of T.", "#TODO: select random minortiy sample...
29.4
0.009875
def infographic_people_section_notes_extractor( impact_report, component_metadata): """Extracting notes for people section in the infographic. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_rep...
[ "def", "infographic_people_section_notes_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "extra_args", "=", "component_metadata", ".", "extra_args", "provenance", "=", "impact_report", ".", "impact_function", ".", "provenance", "hazard_keywords", "=",...
34
0.000433
def _filter(self, value): """ Predicate used to exclude, False, or include, True, a computed value. """ if self.ignores and value in self.ignores: return False return True
[ "def", "_filter", "(", "self", ",", "value", ")", ":", "if", "self", ".", "ignores", "and", "value", "in", "self", ".", "ignores", ":", "return", "False", "return", "True" ]
31
0.008969
def x_build_action( self, node ): ''' Given a build action log, process into the corresponding test log and specific test log sub-part. ''' action_node = node name = self.get_child(action_node,tag='name') if name: name = self.get_data(name) ...
[ "def", "x_build_action", "(", "self", ",", "node", ")", ":", "action_node", "=", "node", "name", "=", "self", ".", "get_child", "(", "action_node", ",", "tag", "=", "'name'", ")", "if", "name", ":", "name", "=", "self", ".", "get_data", "(", "name", ...
50.4
0.012275
def generateBatches(tasks, givens): """ A function to generate a batch of commands to run in a specific order as to meet all the dependencies for each command. For example, the commands with no dependencies are run first, and the commands with the most deep dependencies are run last """ _rem...
[ "def", "generateBatches", "(", "tasks", ",", "givens", ")", ":", "_removeGivensFromTasks", "(", "tasks", ",", "givens", ")", "batches", "=", "[", "]", "while", "tasks", ":", "batch", "=", "set", "(", ")", "for", "task", ",", "dependencies", "in", "tasks"...
28.724138
0.001161
def _extract_object_params(self, name): """ Extract object params, return as dict """ params = self.request.query_params.lists() params_map = {} prefix = name[:-1] offset = len(prefix) for name, value in params: if name.startswith(prefix): ...
[ "def", "_extract_object_params", "(", "self", ",", "name", ")", ":", "params", "=", "self", ".", "request", ".", "query_params", ".", "lists", "(", ")", "params_map", "=", "{", "}", "prefix", "=", "name", "[", ":", "-", "1", "]", "offset", "=", "len"...
32.714286
0.002121
def load_config(self, conf_path): """ Load config from an ``andes.conf`` file. This function creates a ``configparser.ConfigParser`` object to read the specified conf file and calls the ``load_config`` function of the config instances of the system and the routines. Par...
[ "def", "load_config", "(", "self", ",", "conf_path", ")", ":", "if", "conf_path", "is", "None", ":", "return", "conf", "=", "configparser", ".", "ConfigParser", "(", ")", "conf", ".", "read", "(", "conf_path", ")", "self", ".", "config", ".", "load_confi...
28.862069
0.002312
def format_currency(number, currency, format, locale=babel.numbers.LC_NUMERIC, force_frac=None, format_type='standard'): """Same as ``babel.numbers.format_currency``, but has ``force_frac`` argument instead of ``currency_digits``. If the ``force_frac`` argument is given, the argument is...
[ "def", "format_currency", "(", "number", ",", "currency", ",", "format", ",", "locale", "=", "babel", ".", "numbers", ".", "LC_NUMERIC", ",", "force_frac", "=", "None", ",", "format_type", "=", "'standard'", ")", ":", "locale", "=", "babel", ".", "core", ...
39.111111
0.000924
def build_a(self): """Calculates the total absorption from water, phytoplankton and CDOM a = awater + acdom + aphi """ lg.info('Building total absorption') self.a = self.a_water + self.a_cdom + self.a_phi
[ "def", "build_a", "(", "self", ")", ":", "lg", ".", "info", "(", "'Building total absorption'", ")", "self", ".", "a", "=", "self", ".", "a_water", "+", "self", ".", "a_cdom", "+", "self", ".", "a_phi" ]
34.142857
0.008163
def load_signal(signal_handler, get_header=False): """ ----- Brief ----- Function that returns a dictionary with the data contained inside 'signal_name' file (stored in the biosignalsnotebooks signal samples directory). ----------- Description ----------- Biosignalsnotebooks lib...
[ "def", "load_signal", "(", "signal_handler", ",", "get_header", "=", "False", ")", ":", "available_signals", "=", "[", "\"ecg_4000_Hz\"", ",", "\"ecg_5_min\"", ",", "\"ecg_sample\"", ",", "\"ecg_20_sec_10_Hz\"", ",", "\"ecg_20_sec_100_Hz\"", ",", "\"ecg_20_sec_1000_Hz\"...
36.757576
0.002408
def get_field_kwargs(field_name, model_field): """ Creates a default instance of a basic non-relational field. """ kwargs = {} validator_kwarg = list(model_field.validators) # The following will only be used by ModelField classes. # Gets removed for everything else. kwargs['model_field'...
[ "def", "get_field_kwargs", "(", "field_name", ",", "model_field", ")", ":", "kwargs", "=", "{", "}", "validator_kwarg", "=", "list", "(", "model_field", ".", "validators", ")", "# The following will only be used by ModelField classes.", "# Gets removed for everything else."...
38.650888
0.000448
def add_weights(self, name, nin, nout, mean=0, std=0, sparsity=0, diagonal=0): '''Helper method to create a new weight matrix. Parameters ---------- name : str Name of the parameter to add. nin : int Size of "input" for this weight matrix. nout : ...
[ "def", "add_weights", "(", "self", ",", "name", ",", "nin", ",", "nout", ",", "mean", "=", "0", ",", "std", "=", "0", ",", "sparsity", "=", "0", ",", "diagonal", "=", "0", ")", ":", "glorot", "=", "1", "/", "np", ".", "sqrt", "(", "nin", "+",...
44.342857
0.001261
def _add_defaults_python(self): """getting python files""" if self.distribution.has_pure_modules(): build_py = self.get_finalized_command('build_py') self.filelist.extend(build_py.get_source_files()) # This functionality is incompatible with include_package_data, and ...
[ "def", "_add_defaults_python", "(", "self", ")", ":", "if", "self", ".", "distribution", ".", "has_pure_modules", "(", ")", ":", "build_py", "=", "self", ".", "get_finalized_command", "(", "'build_py'", ")", "self", ".", "filelist", ".", "extend", "(", "buil...
61.846154
0.002451
def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += literal.count('\n') return (literal, template) # There...
[ "def", "grab_literal", "(", "template", ",", "l_del", ")", ":", "global", "_CURRENT_LINE", "try", ":", "# Look for the next tag and move the template to it", "literal", ",", "template", "=", "template", ".", "split", "(", "l_del", ",", "1", ")", "_CURRENT_LINE", "...
29.733333
0.002174
def is_line_layer(layer): """Check if a QGIS layer is vector and its geometries are lines. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains lines, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer....
[ "def", "is_line_layer", "(", "layer", ")", ":", "try", ":", "return", "(", "layer", ".", "type", "(", ")", "==", "QgsMapLayer", ".", "VectorLayer", ")", "and", "(", "layer", ".", "geometryType", "(", ")", "==", "QgsWkbTypes", ".", "LineGeometry", ")", ...
28.933333
0.002232
def close_first_file(self): """ Attemtps to close the first **Script_Editor_tabWidget** Widget tab Model editor file. :return: Method success. :rtype: bool """ editor = self.get_current_editor() if len(self.__model.list_editors()) == 1 and editor.is_untitled and...
[ "def", "close_first_file", "(", "self", ")", ":", "editor", "=", "self", ".", "get_current_editor", "(", ")", "if", "len", "(", "self", ".", "__model", ".", "list_editors", "(", ")", ")", "==", "1", "and", "editor", ".", "is_untitled", "and", "not", "e...
34.416667
0.009434
def input_schema_clean(input_, input_schema): """ Updates schema default values with input data. :param input_: Input data :type input_: dict :param input_schema: Input schema :type input_schema: dict :returns: Nested dict with data (defaul values updated with input data) :rtype: dict...
[ "def", "input_schema_clean", "(", "input_", ",", "input_schema", ")", ":", "if", "input_schema", ".", "get", "(", "'type'", ")", "==", "'object'", ":", "try", ":", "defaults", "=", "get_object_defaults", "(", "input_schema", ")", "except", "NoObjectDefaults", ...
29.263158
0.001742
def sample(self, sample_indices=None, num_samples=1): """ returns samples according to the KDE Parameters ---------- sample_inices: list of ints Indices into the training data used as centers for the samples num_samples: int if samples_indices is None, this specifies how many samples ...
[ "def", "sample", "(", "self", ",", "sample_indices", "=", "None", ",", "num_samples", "=", "1", ")", ":", "if", "sample_indices", "is", "None", ":", "sample_indices", "=", "np", ".", "random", ".", "choice", "(", "self", ".", "data", ".", "shape", "[",...
27.566667
0.044393
def obtain_hosting_device_credentials_from_config(): """Obtains credentials from config file and stores them in memory. To be called before hosting device templates defined in the config file are created. """ cred_dict = get_specific_config('cisco_hosting_device_credential') attr_info = { ...
[ "def", "obtain_hosting_device_credentials_from_config", "(", ")", ":", "cred_dict", "=", "get_specific_config", "(", "'cisco_hosting_device_credential'", ")", "attr_info", "=", "{", "'name'", ":", "{", "'allow_post'", ":", "True", ",", "'allow_put'", ":", "True", ",",...
48.793103
0.000693
def picture( relationshiplist, picname, picdescription, pixelwidth=None, pixelheight=None, nochangeaspect=True, nochangearrowheads=True, imagefiledict=None): """ Take a relationshiplist, picture file name, and return a paragraph containing the image and an updated relationshiplist ...
[ "def", "picture", "(", "relationshiplist", ",", "picname", ",", "picdescription", ",", "pixelwidth", "=", "None", ",", "pixelheight", "=", "None", ",", "nochangeaspect", "=", "True", ",", "nochangearrowheads", "=", "True", ",", "imagefiledict", "=", "None", ")...
36.861878
0.000292