text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def evaluate(reference_beats, estimated_beats, **kwargs): """Compute all metrics for the given reference and estimated annotations. Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> estimated_beats = mir_eval.io.load_events('estimated.txt') >>> scores = mir_ev...
[ "def", "evaluate", "(", "reference_beats", ",", "estimated_beats", ",", "*", "*", "kwargs", ")", ":", "# Trim beat times at the beginning of the annotations", "reference_beats", "=", "util", ".", "filter_kwargs", "(", "trim_beats", ",", "reference_beats", ",", "*", "*...
36.716418
0.000396
def col_iter(self): """Get an iterator over all columns in the Sudoku""" for k in utils.range_(self.side): yield self.col(k)
[ "def", "col_iter", "(", "self", ")", ":", "for", "k", "in", "utils", ".", "range_", "(", "self", ".", "side", ")", ":", "yield", "self", ".", "col", "(", "k", ")" ]
37.25
0.013158
def download_file(self, regex, dest_dir): """Downloads a file by regex from the specified S3 bucket This method takes a regular expression as the arg, and attempts to download the file to the specified dest_dir as the destination directory. This method sets the downloaded filename ...
[ "def", "download_file", "(", "self", ",", "regex", ",", "dest_dir", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.download_file'", ")", "if", "not", "isinstance", "(", "regex", ",", "basestring", ")", ":", "lo...
44.965517
0.001502
def complete_url(self, url): """ Completes a given URL with this instance's URL base. """ if self.base_url: return urlparse.urljoin(self.base_url, url) else: return url
[ "def", "complete_url", "(", "self", ",", "url", ")", ":", "if", "self", ".", "base_url", ":", "return", "urlparse", ".", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", "else", ":", "return", "url" ]
31.166667
0.015625
def _parsedate_tz(data): """Convert date to extended time tuple. The last (additional) element is the time zone offset in seconds, except if the timezone was specified as -0000. In that case the last element is None. This indicates a UTC timestamp that explicitly declaims knowledge of the source ...
[ "def", "_parsedate_tz", "(", "data", ")", ":", "if", "not", "data", ":", "return", "data", "=", "data", ".", "split", "(", ")", "# The FWS after the comma after the day-of-week is optional, so search and", "# adjust for this.", "if", "data", "[", "0", "]", ".", "e...
29.686957
0.001417
def zipkin_tween(handler, registry): """ Factory for pyramid tween to handle zipkin server logging. Note that even if the request isn't sampled, Zipkin attributes are generated and pushed into threadlocal storage, so `create_http_headers_for_new_span` and `zipkin_span` will have access to the proper...
[ "def", "zipkin_tween", "(", "handler", ",", "registry", ")", ":", "def", "tween", "(", "request", ")", ":", "zipkin_settings", "=", "_get_settings_from_request", "(", "request", ")", "tracer", "=", "get_default_tracer", "(", ")", "tween_kwargs", "=", "dict", "...
39.055556
0.000925
def fetch_time_output(marker, format_s, ins): """ Fetch the output /usr/bin/time from a. Args: marker: The marker that limits the time output format_s: The format string used to parse the timings ins: A list of lines we look for the output. Returns: A list of timing tup...
[ "def", "fetch_time_output", "(", "marker", ",", "format_s", ",", "ins", ")", ":", "from", "parse", "import", "parse", "timings", "=", "[", "x", "for", "x", "in", "ins", "if", "marker", "in", "x", "]", "res", "=", "[", "parse", "(", "format_s", ",", ...
27.882353
0.002041
def _trim_zeros_float(str_floats, na_rep='NaN'): """ Trims zeros, leaving just one before the decimal points if need be. """ trimmed = str_floats def _is_number(x): return (x != na_rep and not x.endswith('inf')) def _cond(values): finite = [x for x in values if _is_number(x)] ...
[ "def", "_trim_zeros_float", "(", "str_floats", ",", "na_rep", "=", "'NaN'", ")", ":", "trimmed", "=", "str_floats", "def", "_is_number", "(", "x", ")", ":", "return", "(", "x", "!=", "na_rep", "and", "not", "x", ".", "endswith", "(", "'inf'", ")", ")",...
34.5
0.00141
def bootstrap(parser=None, args=None, descriptors=None): """Bootstrap a feat process, handling command line arguments. @param parser: the option parser to use; more options will be added to the parser; if not specified or None a new one will be created @type parser: optparse.OptionParser or...
[ "def", "bootstrap", "(", "parser", "=", "None", ",", "args", "=", "None", ",", "descriptors", "=", "None", ")", ":", "tee", "=", "log", ".", "init", "(", ")", "# The purpose of having log buffer here, is to be able to dump the", "# log lines to a journal after establi...
37.532051
0.000166
def export_envar(self, key, val): """Export an environment variable.""" line = "export " + key + "=" + str(val) self._add(line)
[ "def", "export_envar", "(", "self", ",", "key", ",", "val", ")", ":", "line", "=", "\"export \"", "+", "key", "+", "\"=\"", "+", "str", "(", "val", ")", "self", ".", "_add", "(", "line", ")" ]
37
0.013245
def get_visualizations(): """Get the available visualizations from the request context. Put the visualizations in the request context if they are not yet there. Returns: :obj:`list` of instances of :class:`.BaseVisualization` or derived class """ if not hasattr(g, 'visualizations'...
[ "def", "get_visualizations", "(", ")", ":", "if", "not", "hasattr", "(", "g", ",", "'visualizations'", ")", ":", "g", ".", "visualizations", "=", "{", "}", "for", "VisClass", "in", "_get_visualization_classes", "(", ")", ":", "vis", "=", "VisClass", "(", ...
34.6
0.001876
def print_block_num_row(block_num, cliques, next_cliques): """Print out a row of padding and a row with the block number. Includes the branches prior to this block number.""" n_cliques = len(cliques) if n_cliques == 0: print('| {}'.format(block_num)) return def mapper(clique): ...
[ "def", "print_block_num_row", "(", "block_num", ",", "cliques", ",", "next_cliques", ")", ":", "n_cliques", "=", "len", "(", "cliques", ")", "if", "n_cliques", "==", "0", ":", "print", "(", "'| {}'", ".", "format", "(", "block_num", ")", ")", "return", ...
33.111111
0.001631
def get_suitable_vis_list_classes(objs): """Retuns a list of VisList classes that can handle a list of objects.""" from f311 import explorer as ex ret = [] for class_ in classes_vis(): if isinstance(class_, ex.VisList): flag_can = True for obj in objs: i...
[ "def", "get_suitable_vis_list_classes", "(", "objs", ")", ":", "from", "f311", "import", "explorer", "as", "ex", "ret", "=", "[", "]", "for", "class_", "in", "classes_vis", "(", ")", ":", "if", "isinstance", "(", "class_", ",", "ex", ".", "VisList", ")",...
30.75
0.001972
def _fetch(self, url, method='GET', params=None, headers=None, body='', max_redirects=5, content_parser=None): """ Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: ...
[ "def", "_fetch", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "max_redirects", "=", "5", ",", "content_parser", "=", "None", ")", ":", "# 'magic' using _kwar...
36.2
0.000733
def xstatus(self): """ UNIX-like exit status, only coherent if the context has stopped. """ return max(node.xstatus for node in self.nodes) if len(self.nodes) else 0
[ "def", "xstatus", "(", "self", ")", ":", "return", "max", "(", "node", ".", "xstatus", "for", "node", "in", "self", ".", "nodes", ")", "if", "len", "(", "self", ".", "nodes", ")", "else", "0" ]
32.166667
0.015152
def prepend(self, _, child, name=None): """Adds childs to this tag, starting from the first position.""" self._insert(child, prepend=True, name=name) return self
[ "def", "prepend", "(", "self", ",", "_", ",", "child", ",", "name", "=", "None", ")", ":", "self", ".", "_insert", "(", "child", ",", "prepend", "=", "True", ",", "name", "=", "name", ")", "return", "self" ]
45.5
0.010811
def filter_evidence_source(stmts_in, source_apis, policy='one', **kwargs): """Filter to statements that have evidence from a given set of sources. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. source_apis : list[str] A list of sour...
[ "def", "filter_evidence_source", "(", "stmts_in", ",", "source_apis", ",", "policy", "=", "'one'", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Filtering %d statements to evidence source \"%s\" of: %s...'", "%", "(", "len", "(", "stmts_in", ")"...
40.857143
0.000569
def derivatives(self, x, y, coeffs, beta, center_x=0, center_y=0): """ returns df/dx and df/dy of the function """ shapelets = self._createShapelet(coeffs) n_order = self._get_num_n(len(coeffs)) dx_shapelets = self._dx_shapelets(shapelets, beta) dy_shapelets = sel...
[ "def", "derivatives", "(", "self", ",", "x", ",", "y", ",", "coeffs", ",", "beta", ",", "center_x", "=", "0", ",", "center_y", "=", "0", ")", ":", "shapelets", "=", "self", ".", "_createShapelet", "(", "coeffs", ")", "n_order", "=", "self", ".", "_...
47.352941
0.002436
def _fmto_groups(self): """Mapping from group to a set of formatoptions""" ret = defaultdict(set) for key in self: ret[getattr(self, key).group].add(getattr(self, key)) return dict(ret)
[ "def", "_fmto_groups", "(", "self", ")", ":", "ret", "=", "defaultdict", "(", "set", ")", "for", "key", "in", "self", ":", "ret", "[", "getattr", "(", "self", ",", "key", ")", ".", "group", "]", ".", "add", "(", "getattr", "(", "self", ",", "key"...
37.333333
0.008734
def calculateHiddenLayerActivation(self, features): """ Calculate activation level of the hidden layer :param features feature matrix with dimension (numSamples, numInputs) :return: activation level (numSamples, numHiddenNeurons) """ if self.activationFunction is "sig": H = sigmoidActFunc(...
[ "def", "calculateHiddenLayerActivation", "(", "self", ",", "features", ")", ":", "if", "self", ".", "activationFunction", "is", "\"sig\"", ":", "H", "=", "sigmoidActFunc", "(", "features", ",", "self", ".", "inputWeights", ",", "self", ".", "bias", ")", "els...
37.583333
0.008658
def get_default_config(self): """ Return the default config for the handler """ config = super(MQTTHandler, self).get_default_config() config.update({ }) return config
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "MQTTHandler", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "}", ")", "return", "config" ]
21.6
0.008889
def fetch_weighted_complexity(self, recalculate_metrics=False): """ Calculates indicator value according to metrics weights Uses metrics in database args: recalculate_metrics: If true metrics values are updated before using weights """...
[ "def", "fetch_weighted_complexity", "(", "self", ",", "recalculate_metrics", "=", "False", ")", ":", "# TODO: implment metrics recalculation", "max_total", "=", "sum", "(", "[", "self", ".", "metrics_weights", "[", "metric_name", "]", "for", "metric_name", "in", "se...
35.575758
0.002488
def _read_data_type_rpl(self, length): """Read IPv6-Route RPL Source data. Structure of IPv6-Route RPL Source data [RFC 6554]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-...
[ "def", "_read_data_type_rpl", "(", "self", ",", "length", ")", ":", "_cmpr", "=", "self", ".", "_read_binary", "(", "1", ")", "_padr", "=", "self", ".", "_read_binary", "(", "1", ")", "_resv", "=", "self", ".", "_read_fileng", "(", "2", ")", "_inti", ...
44.607143
0.000783
def send_emission(self): """ emit and remove the first emission in the queue """ if self._emit_queue.empty(): return emit = self._emit_queue.get() emit()
[ "def", "send_emission", "(", "self", ")", ":", "if", "self", ".", "_emit_queue", ".", "empty", "(", ")", ":", "return", "emit", "=", "self", ".", "_emit_queue", ".", "get", "(", ")", "emit", "(", ")" ]
25.75
0.00939
def convert_to_unicode( tscii_input ): """ convert a byte-ASCII encoded string into equivalent Unicode string in the UTF-8 notation.""" output = list() prev = None prev2x = None # need a look ahead of 2 tokens atleast for char in tscii_input: ## print "%2x"%ord(char) # debugging ...
[ "def", "convert_to_unicode", "(", "tscii_input", ")", ":", "output", "=", "list", "(", ")", "prev", "=", "None", "prev2x", "=", "None", "# need a look ahead of 2 tokens atleast", "for", "char", "in", "tscii_input", ":", "## print \"%2x\"%ord(char) # debugging", "if", ...
33.098039
0.017837
def word_similarity_explorer(corpus, category, category_name, not_category_name, target_term, nlp=None, alpha=0.01, m...
[ "def", "word_similarity_explorer", "(", "corpus", ",", "category", ",", "category_name", ",", "not_category_name", ",", "target_term", ",", "nlp", "=", "None", ",", "alpha", "=", "0.01", ",", "max_p_val", "=", "0.1", ",", "*", "*", "kwargs", ")", ":", "if"...
40.537037
0.001784
def paragraph(self, content): """ Turn the first paragraph of text into the summary text """ if not self._out.description: self._out.description = content return ' '
[ "def", "paragraph", "(", "self", ",", "content", ")", ":", "if", "not", "self", ".", "_out", ".", "description", ":", "self", ".", "_out", ".", "description", "=", "content", "return", "' '" ]
39.4
0.00995
def flush(self): """Force the queue of Primitives to compile, execute on the Controller, and fulfill promises with the data returned.""" self.stages = [] self.stagenames = [] if not self.queue: return if self.print_statistics:#pragma: no cover print("LEN...
[ "def", "flush", "(", "self", ")", ":", "self", ".", "stages", "=", "[", "]", "self", ".", "stagenames", "=", "[", "]", "if", "not", "self", ".", "queue", ":", "return", "if", "self", ".", "print_statistics", ":", "#pragma: no cover", "print", "(", "\...
32.382353
0.0097
def advance_job_status(namespace: str, job: Job, duration: float, err: Optional[Exception]): """Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals. """ ...
[ "def", "advance_job_status", "(", "namespace", ":", "str", ",", "job", ":", "Job", ",", "duration", ":", "float", ",", "err", ":", "Optional", "[", "Exception", "]", ")", ":", "duration", "=", "human_duration", "(", "duration", ")", "if", "not", "err", ...
35.347826
0.000598
def reverse(self): """ Reverse all bumpers """ if not self.test_drive and self.bumps: map(lambda b: b.reverse(), self.bumpers)
[ "def", "reverse", "(", "self", ")", ":", "if", "not", "self", ".", "test_drive", "and", "self", ".", "bumps", ":", "map", "(", "lambda", "b", ":", "b", ".", "reverse", "(", ")", ",", "self", ".", "bumpers", ")" ]
37.75
0.012987
def on_capacity(self, connection, command, query_kwargs, response, capacity): """ Hook that runs in response to a 'returned capacity' event """ now = time.time() args = (connection, command, query_kwargs, response, capacity) # Check total against the total_cap ...
[ "def", "on_capacity", "(", "self", ",", "connection", ",", "command", ",", "query_kwargs", ",", "response", ",", "capacity", ")", ":", "now", "=", "time", ".", "time", "(", ")", "args", "=", "(", "connection", ",", "command", ",", "query_kwargs", ",", ...
49.666667
0.001519
def get_conf_d_files(path): """ Return alphabetical ordered :class:`list` of the *.conf* files placed in the path. *path* is a directory path. :: >>> get_conf_d_files('conf/conf.d/') ['conf/conf.d/10-base.conf', 'conf/conf.d/99-dev.conf'] """ if not os.path.isdir(path): ...
[ "def", "get_conf_d_files", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "raise", "ValueError", "(", "\"'%s' is not a directory\"", "%", "path", ")", "files_mask", "=", "os", ".", "path", ".", "join", "(", ...
34.214286
0.002033
def update_dvs(dvs_ref, dvs_config_spec): ''' Updates a distributed virtual switch with the config_spec. dvs_ref The DVS reference. dvs_config_spec The updated config spec (vim.VMwareDVSConfigSpec) to be applied to the DVS. ''' dvs_name = get_managed_object_name(dvs_ref...
[ "def", "update_dvs", "(", "dvs_ref", ",", "dvs_config_spec", ")", ":", "dvs_name", "=", "get_managed_object_name", "(", "dvs_ref", ")", "log", ".", "trace", "(", "'Updating dvs \\'%s\\''", ",", "dvs_name", ")", "try", ":", "task", "=", "dvs_ref", ".", "Reconfi...
34.62963
0.001041
def is_replication_enabled(host=None, core_name=None): ''' SLAVE CALL Check for errors, and determine if a slave is replicating or not. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this ...
[ "def", "is_replication_enabled", "(", "host", "=", "None", ",", "core_name", "=", "None", ")", ":", "ret", "=", "_get_return_dict", "(", ")", "success", "=", "True", "# since only slaves can call this let's check the config:", "if", "_is_master", "(", ")", "and", ...
41.25
0.000658
def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the 'append=True' keyword argument. There are two differences between pat...
[ "def", "write_text", "(", "self", ",", "text", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ",", "linesep", "=", "os", ".", "linesep", ",", "append", "=", "False", ")", ":", "if", "isinstance", "(", "text", ",", "unicode", ")", ":", ...
40.295455
0.000826
def create_all_recommendations(self, cores, ip_views=False): """Calculate the recommendations for all records.""" global _store _store = self.store _create_all_recommendations(cores, ip_views, self.config)
[ "def", "create_all_recommendations", "(", "self", ",", "cores", ",", "ip_views", "=", "False", ")", ":", "global", "_store", "_store", "=", "self", ".", "store", "_create_all_recommendations", "(", "cores", ",", "ip_views", ",", "self", ".", "config", ")" ]
46.6
0.008439
def _checkTypeSchemaConsistency(self, actualType, onDiskSchema): """ Called for all known types at database startup: make sure that what we know (in memory) about this type agrees with what is stored about this type in the database. @param actualType: A L{MetaItem} instance whic...
[ "def", "_checkTypeSchemaConsistency", "(", "self", ",", "actualType", ",", "onDiskSchema", ")", ":", "# make sure that both the runtime and the database both know about this", "# type; if they don't both know, we can't check that their views are", "# consistent", "try", ":", "inMemoryS...
47.826087
0.001336
def _prepare_doc(func, args, delimiter_chars): """From the function docstring get the arg parse description and arguments help message. If there is no docstring simple description and help message are created. Args: func: the function that needs argument parsing args: name of th...
[ "def", "_prepare_doc", "(", "func", ",", "args", ",", "delimiter_chars", ")", ":", "_LOG", ".", "debug", "(", "\"Preparing doc for '%s'\"", ",", "func", ".", "__name__", ")", "if", "not", "func", ".", "__doc__", ":", "return", "_get_default_help_message", "(",...
43.12
0.002268
def compile_migrations(migrator, models, reverse=False): """Compile migrations for given models.""" source = migrator.orm.values() if reverse: source, models = models, source migrations = diff_many(models, source, migrator, reverse=reverse) if not migrations: return False migra...
[ "def", "compile_migrations", "(", "migrator", ",", "models", ",", "reverse", "=", "False", ")", ":", "source", "=", "migrator", ".", "orm", ".", "values", "(", ")", "if", "reverse", ":", "source", ",", "models", "=", "models", ",", "source", "migrations"...
34.833333
0.002331
def scaled_pressure_encode(self, time_boot_ms, press_abs, press_diff, temperature): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. time_boot_ms ...
[ "def", "scaled_pressure_encode", "(", "self", ",", "time_boot_ms", ",", "press_abs", ",", "press_diff", ",", "temperature", ")", ":", "return", "MAVLink_scaled_pressure_message", "(", "time_boot_ms", ",", "press_abs", ",", "press_diff", ",", "temperature", ")" ]
59.615385
0.010165
def fit(self, X, R): """Compute Hierarchical Topographical Factor Analysis Model [Manning2014-1][Manning2014-2] Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. ...
[ "def", "fit", "(", "self", ",", "X", ",", "R", ")", ":", "self", ".", "_check_input", "(", "X", ",", "R", ")", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "\"Start to fit HTFA\"", ")", "self", ".", "n_dim", "=", "R", "[", "0", ...
34.258065
0.001832
def show_window_options(self, option=None, g=False): """ Return a dict of options for the window. For familiarity with tmux, the option ``option`` param forwards to pick a single option, forwarding to :meth:`Window.show_window_option`. Parameters ---------- opti...
[ "def", "show_window_options", "(", "self", ",", "option", "=", "None", ",", "g", "=", "False", ")", ":", "tmux_args", "=", "tuple", "(", ")", "if", "g", ":", "tmux_args", "+=", "(", "'-g'", ",", ")", "if", "option", ":", "return", "self", ".", "sho...
28.214286
0.001631
def update(self): """Update the stats using SNMP.""" # For each plugins, call the update method for p in self._plugins: if self._plugins[p].is_disable(): # If current plugin is disable # then continue to next plugin continue ...
[ "def", "update", "(", "self", ")", ":", "# For each plugins, call the update method", "for", "p", "in", "self", ".", "_plugins", ":", "if", "self", ".", "_plugins", "[", "p", "]", ".", "is_disable", "(", ")", ":", "# If current plugin is disable", "# then contin...
36.26087
0.002336
def _support_enumeration_gen(payoff_matrices): """ Main body of `support_enumeration_gen`. Parameters ---------- payoff_matrices : tuple(ndarray(float, ndim=2)) Tuple of payoff matrices, of shapes (m, n) and (n, m), respectively. Yields ------ out : tuple(ndarray(float,...
[ "def", "_support_enumeration_gen", "(", "payoff_matrices", ")", ":", "nums_actions", "=", "payoff_matrices", "[", "0", "]", ".", "shape", "n_min", "=", "min", "(", "nums_actions", ")", "for", "k", "in", "range", "(", "1", ",", "n_min", "+", "1", ")", ":"...
35.333333
0.000656
def rect_helper(x0, y0, x1, y1): """Rectangle helper""" x0, y0, x1, y1 = force_int(x0, y0, x1, y1) if x0 > x1: x0, x1 = x1, x0 if y0 > y1: y0, y1 = y1, y0 return x0, y0, x1, y1
[ "def", "rect_helper", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "force_int", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", "if", "x0", ">", "x1", ":", "x0", ",", "x1", "=", "x1", ...
29.125
0.008333
def get_rand_int(encoding='latin1', avoid=[]): ''' encoding-->str: one of ENCODINGS avoid-->list of int: to void (unprintable chars etc) Returns-->int that can be converted to requested encoding which is NOT in avoid ''' UNICODE_LIMIT = 0x10ffff # See: https://en.wikipedia.org/...
[ "def", "get_rand_int", "(", "encoding", "=", "'latin1'", ",", "avoid", "=", "[", "]", ")", ":", "UNICODE_LIMIT", "=", "0x10ffff", "# See: https://en.wikipedia.org/wiki/UTF-8#Invalid_code_points", "SURROGATE_RANGE", "=", "(", "0xD800", ",", "0xDFFF", ")", "if", "enco...
31.806452
0.000984
def get_time_ranges(ranges): ''' :param ranges: :return: ''' # get the current time now = int(time.time()) # form the new time_slots = dict() for key, value in ranges.items(): time_slots[key] = (now - value[0], now - value[1], value[2]) return (now, time_slots)
[ "def", "get_time_ranges", "(", "ranges", ")", ":", "# get the current time", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "# form the new", "time_slots", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "ranges", ".", "items", "(",...
18.266667
0.027778
def magic(adata, name_list=None, k=10, a=15, t='auto', n_pca=100, knn_dist='euclidean', random_state=None, n_jobs=None, verbose=False, copy=None, **kwargs): """Markov Affinity-based Graph Imputation of Cell...
[ "def", "magic", "(", "adata", ",", "name_list", "=", "None", ",", "k", "=", "10", ",", "a", "=", "15", ",", "t", "=", "'auto'", ",", "n_pca", "=", "100", ",", "knn_dist", "=", "'euclidean'", ",", "random_state", "=", "None", ",", "n_jobs", "=", "...
40.293706
0.001524
def createArchiveExample(fileName): """ Creates Combine Archive containing the given file. :param fileName: file to include in the archive :return: None """ print('*' * 80) print('Create archive') print('*' * 80) archive = CombineArchive() archive.addFile( fileName, # file...
[ "def", "createArchiveExample", "(", "fileName", ")", ":", "print", "(", "'*'", "*", "80", ")", "print", "(", "'Create archive'", ")", "print", "(", "'*'", "*", "80", ")", "archive", "=", "CombineArchive", "(", ")", "archive", ".", "addFile", "(", "fileNa...
29.702128
0.001387
def set_input(self,filename,pass_to_command_line=True): """ Add an input to the node by adding a --input option. @param filename: option argument to pass as input. @bool pass_to_command_line: add input as a variable option. """ self.__input = filename if pass_to_command_line: self.add_...
[ "def", "set_input", "(", "self", ",", "filename", ",", "pass_to_command_line", "=", "True", ")", ":", "self", ".", "__input", "=", "filename", "if", "pass_to_command_line", ":", "self", ".", "add_var_opt", "(", "'input'", ",", "filename", ")", "self", ".", ...
37.1
0.010526
def _read(self, source): """ Reads and parses the config source :param file/str source: Config source URL (http/https), or string, file name, or file pointer. """ if source.startswith('http://') or source.startswith('https://'): source = url_content(source, cache...
[ "def", "_read", "(", "self", ",", "source", ")", ":", "if", "source", ".", "startswith", "(", "'http://'", ")", "or", "source", ".", "startswith", "(", "'https://'", ")", ":", "source", "=", "url_content", "(", "source", ",", "cache_duration", "=", "self...
42.4
0.009238
def create_alias(alias_name, alias_command): """ Create an alias. Args: alias_name: The name of the alias. alias_command: The command that the alias points to. """ alias_name, alias_command = alias_name.strip(), alias_command.strip() alias_table = get_alias_table() if alias_...
[ "def", "create_alias", "(", "alias_name", ",", "alias_command", ")", ":", "alias_name", ",", "alias_command", "=", "alias_name", ".", "strip", "(", ")", ",", "alias_command", ".", "strip", "(", ")", "alias_table", "=", "get_alias_table", "(", ")", "if", "ali...
31.733333
0.002041
def _mix(color1, color2, weight=0.5, **kwargs): """ Mixes two colors together. """ weight = float(weight) c1 = color1.value c2 = color2.value p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight w = p * 2 - 1 a = c1[3] - c2[3] w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)...
[ "def", "_mix", "(", "color1", ",", "color2", ",", "weight", "=", "0.5", ",", "*", "*", "kwargs", ")", ":", "weight", "=", "float", "(", "weight", ")", "c1", "=", "color1", ".", "value", "c2", "=", "color2", ".", "value", "p", "=", "0.0", "if", ...
30.466667
0.002123
def rename_axis(self, mapper=sentinel, **kwargs): """ Set the name of the axis for the index or columns. Parameters ---------- mapper : scalar, list-like, optional Value to set the axis name attribute. index, columns : scalar, list-like, dict-like or function...
[ "def", "rename_axis", "(", "self", ",", "mapper", "=", "sentinel", ",", "*", "*", "kwargs", ")", ":", "axes", ",", "kwargs", "=", "self", ".", "_construct_axes_from_arguments", "(", "(", ")", ",", "kwargs", ",", "sentinel", "=", "sentinel", ")", "copy", ...
35.811111
0.000302
def parse_args(method_name, param_defs, args, kwargs, external_param_processor, extra_parameter_errors): """ Parse arguments for suds web service operation invocation functions. Suds prepares Python function objects for invoking web service operations. This function implements generic binding agnos...
[ "def", "parse_args", "(", "method_name", ",", "param_defs", ",", "args", ",", "kwargs", ",", "external_param_processor", ",", "extra_parameter_errors", ")", ":", "arg_parser", "=", "_ArgParser", "(", "method_name", ",", "param_defs", ",", "external_param_processor", ...
52.836364
0.001014
def empty(shape, ctx=None, dtype=None, stype=None): """Returns a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the curren...
[ "def", "empty", "(", "shape", ",", "ctx", "=", "None", ",", "dtype", "=", "None", ",", "stype", "=", "None", ")", ":", "if", "stype", "is", "None", "or", "stype", "==", "'default'", ":", "return", "_empty_ndarray", "(", "shape", ",", "ctx", ",", "d...
30.441176
0.001873
def urldecode(query): """Decode a query string in x-www-form-urlencoded format into a sequence of two-element tuples. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce correct formatting of the query string by validation. If validation fails a ValueError will be raised. url...
[ "def", "urldecode", "(", "query", ")", ":", "# Check if query contains invalid characters", "if", "query", "and", "not", "set", "(", "query", ")", "<=", "urlencoded", ":", "error", "=", "(", "\"Error trying to decode a non urlencoded string. \"", "\"Found invalid characte...
43.765957
0.000476
def seek_realtime(self, realtime): """Seek to a matching journal entry nearest to `timestamp` time. Argument `realtime` must be either an integer UNIX timestamp (in microseconds since the beginning of the UNIX epoch), or an float UNIX timestamp (in seconds since the beginning of the UNI...
[ "def", "seek_realtime", "(", "self", ",", "realtime", ")", ":", "if", "isinstance", "(", "realtime", ",", "_datetime", ".", "datetime", ")", ":", "realtime", "=", "int", "(", "float", "(", "realtime", ".", "strftime", "(", "\"%s.%f\"", ")", ")", "*", "...
42.85
0.002283
def dump_queue(self, *names): """Debug-log some of the queues. ``names`` may include any of "worker", "available", "priorities", "expiration", "workers", or "reservations_ITEM" filling in some specific item. """ conn = redis.StrictRedis(connection_pool=self.pool) ...
[ "def", "dump_queue", "(", "self", ",", "*", "names", ")", ":", "conn", "=", "redis", ".", "StrictRedis", "(", "connection_pool", "=", "self", ".", "pool", ")", "for", "name", "in", "names", ":", "if", "name", "==", "'worker'", ":", "logger", ".", "de...
47.7
0.00137
def user_parser(user): """ Parses a user object """ if __is_deleted(user): return deleted_parser(user) if user['id'] in item_types: raise Exception('Not a user name') if type(user['id']) == int: raise Exception('Not a user name') return User( user['id'], ...
[ "def", "user_parser", "(", "user", ")", ":", "if", "__is_deleted", "(", "user", ")", ":", "return", "deleted_parser", "(", "user", ")", "if", "user", "[", "'id'", "]", "in", "item_types", ":", "raise", "Exception", "(", "'Not a user name'", ")", "if", "t...
21.2
0.002257
def imagetransformer_base_12l_8h_big(): """big 1d model for conditional image generation.""" hparams = imagetransformer_sep_channels_8l_8h() hparams.filter_size = 1024 hparams.num_decoder_layers = 12 hparams.batch_size = 1 hparams.hidden_size = 512 hparams.learning_rate_warmup_steps = 4000 hparams.sampl...
[ "def", "imagetransformer_base_12l_8h_big", "(", ")", ":", "hparams", "=", "imagetransformer_sep_channels_8l_8h", "(", ")", "hparams", ".", "filter_size", "=", "1024", "hparams", ".", "num_decoder_layers", "=", "12", "hparams", ".", "batch_size", "=", "1", "hparams",...
33.25
0.029268
def process(self, makeGlyphs=True, makeKerning=True, makeInfo=True): """ Process the input file and generate the instances. """ if self.logger: self.logger.info("Reading %s", self.path) self.readInstances(makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo) self...
[ "def", "process", "(", "self", ",", "makeGlyphs", "=", "True", ",", "makeKerning", "=", "True", ",", "makeInfo", "=", "True", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "\"Reading %s\"", ",", "self", ".", "pa...
57.666667
0.008547
def _reconnect(self): """Reconnect to JLigier and subscribe to the tags.""" log.debug("Reconnecting to JLigier...") self._disconnect() self._connect() self._update_subscriptions()
[ "def", "_reconnect", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Reconnecting to JLigier...\"", ")", "self", ".", "_disconnect", "(", ")", "self", ".", "_connect", "(", ")", "self", ".", "_update_subscriptions", "(", ")" ]
35.666667
0.009132
def K2OSiO2(self, Left=35, Right=79, X0=30, X1=90, X_Gap=7, Base=0, Top=19, Y0=1, Y1=19, Y_Gap=19, FontSize=12, xlabel=r'$SiO_2 wt\%$', ylabel=r'$K_2O wt\%$', width=12, height=12, dpi=300): self.setWindowTitle('K2OSiO2 diagram ') self.axes.clear() #self.axes.axis('off') ...
[ "def", "K2OSiO2", "(", "self", ",", "Left", "=", "35", ",", "Right", "=", "79", ",", "X0", "=", "30", ",", "X1", "=", "90", ",", "X_Gap", "=", "7", ",", "Base", "=", "0", ",", "Top", "=", "19", ",", "Y0", "=", "1", ",", "Y1", "=", "19", ...
36.128571
0.009004
def register(cls, code, name, hash_name=None, hash_new=None): """Add an application-specific function to the registry. Registers a function with the given `code` (an integer) and `name` (a string, which is added both with only hyphens and only underscores), as well as an optional `hash_...
[ "def", "register", "(", "cls", ",", "code", ",", "name", ",", "hash_name", "=", "None", ",", "hash_new", "=", "None", ")", ":", "if", "not", "_is_app_specific_func", "(", "code", ")", ":", "raise", "ValueError", "(", "\"only application-specific functions can ...
46.860465
0.000972
def convert_model(prototxt_fname, caffemodel_fname, output_prefix=None): """Convert caffe model Parameters ---------- prototxt_fname : str Filename of the prototxt model definition caffemodel_fname : str Filename of the binary caffe model output_prefix : str, optinoal ...
[ "def", "convert_model", "(", "prototxt_fname", ",", "caffemodel_fname", ",", "output_prefix", "=", "None", ")", ":", "sym", ",", "input_dim", "=", "convert_symbol", "(", "prototxt_fname", ")", "arg_shapes", ",", "_", ",", "aux_shapes", "=", "sym", ".", "infer_...
43.740541
0.001329
def remove_labels(self, test): """ Remove labels from this cell. The function or callable ``test`` is called for each label in the cell. If its return value evaluates to ``True``, the corresponding label is removed from the cell. Parameters ---------- t...
[ "def", "remove_labels", "(", "self", ",", "test", ")", ":", "ii", "=", "0", "while", "ii", "<", "len", "(", "self", ".", "labels", ")", ":", "if", "test", "(", "self", ".", "labels", "[", "ii", "]", ")", ":", "self", ".", "labels", ".", "pop", ...
26.65625
0.002262
def fetch_sel(self, ipmicmd, clear=False): """Fetch SEL entries Return an iterable of SEL entries. If clearing is requested, the fetch and clear will be done as an atomic operation, assuring no entries are dropped. :param ipmicmd: The Command object to use to interrogate :param clear:...
[ "def", "fetch_sel", "(", "self", ",", "ipmicmd", ",", "clear", "=", "False", ")", ":", "records", "=", "[", "]", "# First we do a fetch all without reservation, reducing the risk", "# of having a long lived reservation that gets canceled in the middle", "endat", "=", "self", ...
51.241379
0.001321
def import_users(self): """ save users to local DB """ self.message('saving users into local DB') saved_users = self.saved_admins # loop over all extracted unique email addresses for email in self.email_set: owner = self.users_dict[email].get('owner') #...
[ "def", "import_users", "(", "self", ")", ":", "self", ".", "message", "(", "'saving users into local DB'", ")", "saved_users", "=", "self", ".", "saved_admins", "# loop over all extracted unique email addresses", "for", "email", "in", "self", ".", "email_set", ":", ...
40.736842
0.00227
def to_long(base, lookup_f, s): """ Convert an array to a (possibly bignum) integer, along with a prefix value of how many prefixed zeros there are. base: the source base lookup_f: a function to convert an element of s to a value between 0 and base-1. s: the value to conv...
[ "def", "to_long", "(", "base", ",", "lookup_f", ",", "s", ")", ":", "prefix", "=", "0", "v", "=", "0", "for", "c", "in", "s", ":", "v", "*=", "base", "try", ":", "v", "+=", "lookup_f", "(", "c", ")", "except", "Exception", ":", "raise", "ValueE...
26
0.001686
def sample_orbit(self, Npts=100, primary=None, trailing=True, timespan=None, useTrueAnomaly=True): """ Returns a nested list of xyz positions along the osculating orbit of the particle. If primary is not passed, returns xyz positions along the Jacobi osculating orbit (with mu = G*Minc, ...
[ "def", "sample_orbit", "(", "self", ",", "Npts", "=", "100", ",", "primary", "=", "None", ",", "trailing", "=", "True", ",", "timespan", "=", "None", ",", "useTrueAnomaly", "=", "True", ")", ":", "pts", "=", "[", "]", "if", "primary", "is", "None", ...
55.212766
0.010223
def get_data(param, data): """Retrieve weather parameter.""" try: for (_, selected_time_entry) in data: loc_data = selected_time_entry['location'] if param not in loc_data: continue if param == 'precipitation': new_state = loc_data[par...
[ "def", "get_data", "(", "param", ",", "data", ")", ":", "try", ":", "for", "(", "_", ",", "selected_time_entry", ")", "in", "data", ":", "loc_data", "=", "selected_time_entry", "[", "'location'", "]", "if", "param", "not", "in", "loc_data", ":", "continu...
45.12
0.000868
def get_matches(lf, candidate_set, match_values=[1, -1]): """Return a list of candidates that are matched by a particular LF. A simple helper function to see how many matches (non-zero by default) an LF gets. :param lf: The labeling function to apply to the candidate_set :param candidate_set: The ...
[ "def", "get_matches", "(", "lf", ",", "candidate_set", ",", "match_values", "=", "[", "1", ",", "-", "1", "]", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "matches", "=", "[", "]", "for", "c", "in", "candidate_set", ":...
35.55
0.00137
def poll(self, endpoint, pFormat=PrometheusFormat.PROTOBUF, headers=None): """ Polls the metrics from the prometheus metrics endpoint provided. Defaults to the protobuf format, but can use the formats specified by the PrometheusFormat class. Custom headers can be added to the def...
[ "def", "poll", "(", "self", ",", "endpoint", ",", "pFormat", "=", "PrometheusFormat", ".", "PROTOBUF", ",", "headers", "=", "None", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "if", "'accept-encoding'", "not", "in", "headers",...
42.102941
0.002389
def user_error(status_code, title, detail, pointer): """Create and return a general user error response that is jsonapi compliant. Required args: status_code: The HTTP status code associated with the problem. title: A short summary of the problem. detail: An explanation specific to the ...
[ "def", "user_error", "(", "status_code", ",", "title", ",", "detail", ",", "pointer", ")", ":", "response", "=", "{", "'errors'", ":", "[", "{", "'status'", ":", "status_code", ",", "'source'", ":", "{", "'pointer'", ":", "'{0}'", ".", "format", "(", "...
33.416667
0.002424
def MobileDeviceConfigurationProfile(self, data=None, subset=None): """{dynamic_docstring}""" return self.factory.get_object( jssobjects.MobileDeviceConfigurationProfile, data, subset)
[ "def", "MobileDeviceConfigurationProfile", "(", "self", ",", "data", "=", "None", ",", "subset", "=", "None", ")", ":", "return", "self", ".", "factory", ".", "get_object", "(", "jssobjects", ".", "MobileDeviceConfigurationProfile", ",", "data", ",", "subset", ...
52.25
0.009434
def get_servo_position(self): """ Gets the current position of Herkulex Args: none Returns: int: position of the servo- 0 to 1023 Raises: SerialException: Error occured while opening serial port """ #global SERPORT data = [...
[ "def", "get_servo_position", "(", "self", ")", ":", "#global SERPORT", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", "."...
28.515152
0.011305
def _rule_container(self): """ Parses the production rule:: container : NAME '{' (option | block)* '}' EOF Returns tuple (type_name, options_list, blocks_list). """ type_name = self._get_token(self.RE_NAME) self._expect_token('{') # consume elem...
[ "def", "_rule_container", "(", "self", ")", ":", "type_name", "=", "self", ".", "_get_token", "(", "self", ".", "RE_NAME", ")", "self", ".", "_expect_token", "(", "'{'", ")", "# consume elements if available", "options", "=", "[", "]", "blocks", "=", "[", ...
31.348837
0.001439
def add_annotation_type(self, doc, annotation_type): """Sets the annotation type. Raises CardinalityError if already set. OrderError if no annotator defined before. Raises SPDXValueError if invalid value. """ if len(doc.annotations) != 0: if not self.annotation_type_s...
[ "def", "add_annotation_type", "(", "self", ",", "doc", ",", "annotation_type", ")", ":", "if", "len", "(", "doc", ".", "annotations", ")", "!=", "0", ":", "if", "not", "self", ".", "annotation_type_set", ":", "self", ".", "annotation_type_set", "=", "True"...
46.352941
0.002488
def get_contract_from_name(self, contract_name): """ Return a contract from a name Args: contract_name (str): name of the contract Returns: Contract """ return next((c for c in self.contracts if c.name == contract_name), None)
[ "def", "get_contract_from_name", "(", "self", ",", "contract_name", ")", ":", "return", "next", "(", "(", "c", "for", "c", "in", "self", ".", "contracts", "if", "c", ".", "name", "==", "contract_name", ")", ",", "None", ")" ]
32.666667
0.009934
def update(self): """ Updates @ 10Hz to give smooth running clock. """ try: # update counter self.counter += 1 g = get_root(self).globals # current time now = Time.now() # configure times self.utc.con...
[ "def", "update", "(", "self", ")", ":", "try", ":", "# update counter", "self", ".", "counter", "+=", "1", "g", "=", "get_root", "(", "self", ")", ".", "globals", "# current time", "now", "=", "Time", ".", "now", "(", ")", "# configure times", "self", ...
45.982609
0.002221
def path_to_url2(path): """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) drive, path = os.path.splitdrive(path) filepath = path.split(os.path.sep) url = '/'.join([urllib.quote(part) for part ...
[ "def", "path_to_url2", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "drive", ",", "path", "=", "os", ".", "path", ".", "splitdrive", "(", "path", ")", "file...
33.833333
0.002398
def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE): """ Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. ...
[ "def", "get_criteria", "(", "self", ",", "sess", ",", "model", ",", "advx", ",", "y", ",", "batch_size", "=", "BATCH_SIZE", ")", ":", "names", ",", "factory", "=", "self", ".", "extra_criteria", "(", ")", "factory", "=", "_CriteriaFactory", "(", "model",...
40.521739
0.001048
def svd(g, svdcut=1e-12, wgts=False, add_svdnoise=False): """ Apply SVD cuts to collection of |GVar|\s in ``g``. Standard usage is, for example, :: svdcut = ... gmod = svd(g, svdcut=svdcut) where ``g`` is an array of |GVar|\s or a dictionary containing |GVar|\s and/or arrays of |GVar|...
[ "def", "svd", "(", "g", ",", "svdcut", "=", "1e-12", ",", "wgts", "=", "False", ",", "add_svdnoise", "=", "False", ")", ":", "# replace g by a copy of g", "if", "hasattr", "(", "g", ",", "'keys'", ")", ":", "is_dict", "=", "True", "g", "=", "BufferDict...
38.808333
0.002198
def convert(self): """ Copies data from RAPID netCDF output to a CF-compliant netCDF file. """ try: log('Processing %s ...' % self.rapid_output_file_list[0]) time_start_conversion = datetime.utcnow() # Validate the raw netCDF file ...
[ "def", "convert", "(", "self", ")", ":", "try", ":", "log", "(", "'Processing %s ...'", "%", "self", ".", "rapid_output_file_list", "[", "0", "]", ")", "time_start_conversion", "=", "datetime", ".", "utcnow", "(", ")", "# Validate the raw netCDF file\r", "log", ...
37.734694
0.001054
def write_raw_file(secret, dest): """Writes an actual secret out to a file""" secret_file = None secret_filename = abspath(dest) if sys.version_info >= (3, 0): if not isinstance(secret, str): secret_file = open(secret_filename, 'wb') if not secret_file: secret_file = ope...
[ "def", "write_raw_file", "(", "secret", ",", "dest", ")", ":", "secret_file", "=", "None", "secret_filename", "=", "abspath", "(", "dest", ")", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "if", "not", "isinstance", "(", "secre...
30.142857
0.002299
async def list_presets(self): """ Listing presets :return: (list of presets) :rtype: list Sample response: ``["preset1", "preset2"]`` """ presets = await self.request.app.vmshepherd.preset_manager.list_presets() return list(presets.keys())
[ "async", "def", "list_presets", "(", "self", ")", ":", "presets", "=", "await", "self", ".", "request", ".", "app", ".", "vmshepherd", ".", "preset_manager", ".", "list_presets", "(", ")", "return", "list", "(", "presets", ".", "keys", "(", ")", ")" ]
23.615385
0.009404
def ConvertSupportedOSToConditions(src_object): """Turn supported_os into a condition.""" if src_object.supported_os: conditions = " OR ".join("os == '%s'" % o for o in src_object.supported_os) return conditions
[ "def", "ConvertSupportedOSToConditions", "(", "src_object", ")", ":", "if", "src_object", ".", "supported_os", ":", "conditions", "=", "\" OR \"", ".", "join", "(", "\"os == '%s'\"", "%", "o", "for", "o", "in", "src_object", ".", "supported_os", ")", "return", ...
43.8
0.013453
def pack_range(key, packing, grad_vars, rng): """Form the concatenation of a specified range of gradient tensors. Args: key: Value under which to store meta-data in packing that will be used later to restore the grad_var list structure. packing: Dict holding data describing packed ranges of small t...
[ "def", "pack_range", "(", "key", ",", "packing", ",", "grad_vars", ",", "rng", ")", ":", "to_pack", "=", "grad_vars", "[", "rng", "[", "0", "]", ":", "rng", "[", "1", "]", "+", "1", "]", "members", "=", "[", "]", "variables", "=", "[", "]", "re...
37.366667
0.00087
def _psturng(q, r, v): """scalar version of psturng""" if q < 0.: raise ValueError('q should be >= 0') opt_func = lambda p, r, v : abs(_qsturng(p, r, v) - q) if v == 1: if q < _qsturng(.9, r, 1): return .1 elif q > _qsturng(.999, r, 1): return .001 ...
[ "def", "_psturng", "(", "q", ",", "r", ",", "v", ")", ":", "if", "q", "<", "0.", ":", "raise", "ValueError", "(", "'q should be >= 0'", ")", "opt_func", "=", "lambda", "p", ",", "r", ",", "v", ":", "abs", "(", "_qsturng", "(", "p", ",", "r", ",...
28.947368
0.008803
def slug_sub(match): """Assigns id-less headers a slug that is derived from their titles. Slugs are generated by lower-casing the titles, stripping all punctuation, and converting spaces to hyphens (-). """ level = match.group(1) title = match.group(2) slug = title.lower() slug = re.sub(...
[ "def", "slug_sub", "(", "match", ")", ":", "level", "=", "match", ".", "group", "(", "1", ")", "title", "=", "match", ".", "group", "(", "2", ")", "slug", "=", "title", ".", "lower", "(", ")", "slug", "=", "re", ".", "sub", "(", "r'<.+?>|[^\\w-]'...
37.357143
0.001866
def augknt(knots, order): """Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: int, >= 0, order of spline Returns: list_of_knots: rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``k...
[ "def", "augknt", "(", "knots", ",", "order", ")", ":", "if", "isinstance", "(", "knots", ",", "np", ".", "ndarray", ")", "and", "knots", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"knots must be a list or a rank-1 array\"", ")", "knots", "="...
36.52
0.012807
def getKeySequenceCounter(self): """get current Thread Network key sequence""" print '%s call getKeySequenceCounter' % self.port keySequence = '' keySequence = self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:KeyIndex')[0] return keySequence
[ "def", "getKeySequenceCounter", "(", "self", ")", ":", "print", "'%s call getKeySequenceCounter'", "%", "self", ".", "port", "keySequence", "=", "''", "keySequence", "=", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'getprop -v Network:KeyIndex'", ")", "[...
46.666667
0.010526
def scaleY(self, canvasY): 'returns plotter y coordinate, with y-axis inverted' plotterY = super().scaleY(canvasY) return (self.plotviewBox.ymax-plotterY+4)
[ "def", "scaleY", "(", "self", ",", "canvasY", ")", ":", "plotterY", "=", "super", "(", ")", ".", "scaleY", "(", "canvasY", ")", "return", "(", "self", ".", "plotviewBox", ".", "ymax", "-", "plotterY", "+", "4", ")" ]
44.25
0.011111
def update(self, index, iterable, commit=True): """ Updates the `index` with any objects in `iterable` by adding/updating the database as needed. Required arguments: `index` -- The `SearchIndex` to process `iterable` -- An iterable of model instances to index ...
[ "def", "update", "(", "self", ",", "index", ",", "iterable", ",", "commit", "=", "True", ")", ":", "database", "=", "self", ".", "_database", "(", "writable", "=", "True", ")", "try", ":", "term_generator", "=", "xapian", ".", "TermGenerator", "(", ")"...
44.354331
0.001302
def integrations(self, **kwargs): """Retrieve all this services integrations.""" ids = [ref['id'] for ref in self['integrations']] return [Integration.fetch(id, service=self, query_params=kwargs) for id in ids]
[ "def", "integrations", "(", "self", ",", "*", "*", "kwargs", ")", ":", "ids", "=", "[", "ref", "[", "'id'", "]", "for", "ref", "in", "self", "[", "'integrations'", "]", "]", "return", "[", "Integration", ".", "fetch", "(", "id", ",", "service", "="...
57.75
0.012821
def is_country(self, text): """Check if a piece of text is in the list of countries""" ct_list = self._just_cts.keys() if text in ct_list: return True else: return False
[ "def", "is_country", "(", "self", ",", "text", ")", ":", "ct_list", "=", "self", ".", "_just_cts", ".", "keys", "(", ")", "if", "text", "in", "ct_list", ":", "return", "True", "else", ":", "return", "False" ]
31.285714
0.008889
def add_noise(data, sigma=1.0, noise_type='gauss'): r"""Add noise to data This method adds Gaussian or Poisson noise to the input data Parameters ---------- data : np.ndarray, list or tuple Input data array sigma : float or list, optional Standard deviation of the noise to be a...
[ "def", "add_noise", "(", "data", ",", "sigma", "=", "1.0", ",", "noise_type", "=", "'gauss'", ")", ":", "data", "=", "np", ".", "array", "(", "data", ")", "if", "noise_type", "not", "in", "(", "'gauss'", ",", "'poisson'", ")", ":", "raise", "ValueErr...
27.932432
0.000467
def _padding_slices_inner(lhs_arr, rhs_arr, axis, offset, pad_mode): """Return slices into the inner array part for a given ``pad_mode``. When performing padding, these slices yield the values from the inner part of a larger array that are to be assigned to the excess part of the same array. Slices for...
[ "def", "_padding_slices_inner", "(", "lhs_arr", ",", "rhs_arr", ",", "axis", ",", "offset", ",", "pad_mode", ")", ":", "# Calculate the start and stop indices for the inner part", "istart_inner", "=", "offset", "[", "axis", "]", "n_large", "=", "max", "(", "lhs_arr"...
44.276596
0.00047
def welcome_if_new(self, node): """ Given a new node, send it all the keys/values it should be storing, then add it to the routing table. @param node: A new node that just joined (or that we just found out about). Process: For each key in storage, get k closest ...
[ "def", "welcome_if_new", "(", "self", ",", "node", ")", ":", "if", "not", "self", ".", "router", ".", "is_new_node", "(", "node", ")", ":", "return", "log", ".", "info", "(", "\"never seen %s before, adding to router\"", ",", "node", ")", "for", "key", ","...
43.62069
0.001547