text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def getIndexStripUrl(self, index): """Get comic strip URL from index.""" chapter, num = index.split('-') return self.stripUrl % (chapter, chapter, num)
[ "def", "getIndexStripUrl", "(", "self", ",", "index", ")", ":", "chapter", ",", "num", "=", "index", ".", "split", "(", "'-'", ")", "return", "self", ".", "stripUrl", "%", "(", "chapter", ",", "chapter", ",", "num", ")" ]
43
0.011429
def update_status(self): ''' Updates the status of this invoice based upon the total payments.''' old_status = self.invoice.status total_paid = self.invoice.total_payments() num_payments = commerce.PaymentBase.objects.filter( invoice=self.invoice, ).count() ...
[ "def", "update_status", "(", "self", ")", ":", "old_status", "=", "self", ".", "invoice", ".", "status", "total_paid", "=", "self", ".", "invoice", ".", "total_payments", "(", ")", "num_payments", "=", "commerce", ".", "PaymentBase", ".", "objects", ".", "...
35.854167
0.001131
def py_log_level(self, default='none'): ''' Set the log level for python Bokeh code. ''' level = self._get_str("PY_LOG_LEVEL", default, "debug") LEVELS = {'trace': logging.TRACE, 'debug': logging.DEBUG, 'info' : logging.INFO, 'warn' ...
[ "def", "py_log_level", "(", "self", ",", "default", "=", "'none'", ")", ":", "level", "=", "self", ".", "_get_str", "(", "\"PY_LOG_LEVEL\"", ",", "default", ",", "\"debug\"", ")", "LEVELS", "=", "{", "'trace'", ":", "logging", ".", "TRACE", ",", "'debug'...
36.538462
0.010267
def create(vm_): ''' Create a single VM from a data dict ''' deploy = config.get_cloud_config_value('deploy', vm_, __opts__) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.is...
[ "def", "create", "(", "vm_", ")", ":", "deploy", "=", "config", ".", "get_cloud_config_value", "(", "'deploy'", ",", "vm_", ",", "__opts__", ")", "key_filename", "=", "config", ".", "get_cloud_config_value", "(", "'ssh_key_file'", ",", "vm_", ",", "__opts__", ...
36.290909
0.001463
def symbol_leading_char(self): """Return the symbol leading char attribute of the BFD file being processed. """ if not self._ptr: raise BfdException("BFD not initialized") return _bfd.get_bfd_attribute( self._ptr, BfdAttributes.SYMBOL_LEADING_CHA...
[ "def", "symbol_leading_char", "(", "self", ")", ":", "if", "not", "self", ".", "_ptr", ":", "raise", "BfdException", "(", "\"BFD not initialized\"", ")", "return", "_bfd", ".", "get_bfd_attribute", "(", "self", ".", "_ptr", ",", "BfdAttributes", ".", "SYMBOL_L...
31.3
0.009317
def make_snapshot( cls, serialized_ops, prev_consensus_hashes ): """ Generate a consensus hash, using the tx-ordered list of serialized name operations, and a list of previous consensus hashes that contains the (k-1)th, (k-2)th; (k-3)th; ...; (k - (2**i - 1))th consensus hashes, ...
[ "def", "make_snapshot", "(", "cls", ",", "serialized_ops", ",", "prev_consensus_hashes", ")", ":", "record_root_hash", "=", "StateEngine", ".", "make_ops_snapshot", "(", "serialized_ops", ")", "log", ".", "debug", "(", "\"Snapshot('{}', {})\"", ".", "format", "(", ...
58.538462
0.019405
def get_ogr_driver(filepath): """ Get the OGR driver from the provided file extension. Args: file_extension (str): file extension Returns: osgeo.ogr.Driver Raises: ValueError: no driver is found """ filename, file_extension = os.path.splitext(filepath) EXTENSI...
[ "def", "get_ogr_driver", "(", "filepath", ")", ":", "filename", ",", "file_extension", "=", "os", ".", "path", ".", "splitext", "(", "filepath", ")", "EXTENSION", "=", "file_extension", "[", "1", ":", "]", "ogr_driver_count", "=", "ogr", ".", "GetDriverCount...
27.9
0.001155
def _get_attribute_value_of(resource, attribute_name, default=None): """Gets the value of attribute_name from the resource It catches the exception, if any, while retrieving the value of attribute_name from resource and returns default. :param resource: The resource object :attribute_name: Propert...
[ "def", "_get_attribute_value_of", "(", "resource", ",", "attribute_name", ",", "default", "=", "None", ")", ":", "try", ":", "return", "getattr", "(", "resource", ",", "attribute_name", ")", "except", "(", "sushy", ".", "exceptions", ".", "SushyError", ",", ...
42.130435
0.001009
def add(self, term, name, overwrite=False): """ Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this pipeline. Parameters ---------- column : zipline.pipeline.Term A Filter, Factor, or Class...
[ "def", "add", "(", "self", ",", "term", ",", "name", ",", "overwrite", "=", "False", ")", ":", "self", ".", "validate_column", "(", "name", ",", "term", ")", "columns", "=", "self", ".", "columns", "if", "name", "in", "columns", ":", "if", "overwrite...
31.181818
0.001885
def __load(self, redirect=True, preload=False): ''' Load basic information from Wikipedia. Confirm that page exists and is not a disambiguation/redirect. Does not need to be called manually, should be called automatically during __init__. ''' query_params = { 'prop': 'info|pageprops', ...
[ "def", "__load", "(", "self", ",", "redirect", "=", "True", ",", "preload", "=", "False", ")", ":", "query_params", "=", "{", "'prop'", ":", "'info|pageprops'", ",", "'inprop'", ":", "'url'", ",", "'ppprop'", ":", "'disambiguation'", ",", "'redirects'", ":...
30.802469
0.010485
def handle_node_change_network_state( mediator_state: MediatorTransferState, state_change: ActionChangeNodeNetworkState, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult: """ If a certain node...
[ "def", "handle_node_change_network_state", "(", "mediator_state", ":", "MediatorTransferState", ",", "state_change", ":", "ActionChangeNodeNetworkState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",...
40.45098
0.001893
def copy_region_to_clipboard(self): # () u'''Copy the text in the region to the windows clipboard.''' if self.enable_win32_clipboard: mark = min(self.mark, len(self.line_buffer)) cursor = min(self.point, len(self.line_buffer)) if self.mark == -1: ...
[ "def", "copy_region_to_clipboard", "(", "self", ")", ":", "# ()\r", "if", "self", ".", "enable_win32_clipboard", ":", "mark", "=", "min", "(", "self", ".", "mark", ",", "len", "(", "self", ".", "line_buffer", ")", ")", "cursor", "=", "min", "(", "self", ...
49.727273
0.008977
def lint(filename, options=()): """Pylint the given file. When run from emacs we will be in the directory of a file, and passed its filename. If this file is part of a package and is trying to import other modules from within its own package or another package rooted in a directory below it, pylin...
[ "def", "lint", "(", "filename", ",", "options", "=", "(", ")", ")", ":", "# traverse downwards until we are out of a python package", "full_path", "=", "osp", ".", "abspath", "(", "filename", ")", "parent_path", "=", "osp", ".", "dirname", "(", "full_path", ")",...
37.25
0.002335
def render(self, request): """ Render a request by forwarding it to the proxied server. """ # set up and evaluate a connection to the target server if self.port == 80: host = self.host else: host = "%s:%d" % (self.host, self.port) request.r...
[ "def", "render", "(", "self", ",", "request", ")", ":", "# set up and evaluate a connection to the target server", "if", "self", ".", "port", "==", "80", ":", "host", "=", "self", ".", "host", "else", ":", "host", "=", "\"%s:%d\"", "%", "(", "self", ".", "...
32.777778
0.002195
def get_svc_alias(): ''' Returns the list of service's name that are aliased and their alias path(s) ''' ret = {} for d in AVAIL_SVR_DIRS: for el in glob.glob(os.path.join(d, '*')): if not os.path.islink(el): continue psvc = os.readlink(el) ...
[ "def", "get_svc_alias", "(", ")", ":", "ret", "=", "{", "}", "for", "d", "in", "AVAIL_SVR_DIRS", ":", "for", "el", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "d", ",", "'*'", ")", ")", ":", "if", "not", "os", ".", "p...
29.444444
0.001828
def _infer_sequence_helper(node, context=None): """Infer all values based on _BaseContainer.elts""" values = [] for elt in node.elts: if isinstance(elt, nodes.Starred): starred = helpers.safe_infer(elt.value, context) if not starred: raise exceptions.Inferenc...
[ "def", "_infer_sequence_helper", "(", "node", ",", "context", "=", "None", ")", ":", "values", "=", "[", "]", "for", "elt", "in", "node", ".", "elts", ":", "if", "isinstance", "(", "elt", ",", "nodes", ".", "Starred", ")", ":", "starred", "=", "helpe...
38.866667
0.001675
def Jacobian_re_im(self, pars): r""" :math:`J` >>> import sip_models.res.cc as cc >>> import numpy as np >>> f = np.logspace(-3, 3, 20) >>> pars = [100, 0.1, 0.04, 0.8] >>> obj = cc.cc(f) >>> J = obj.Jacobian_re_im(pars) """ partials = [] ...
[ "def", "Jacobian_re_im", "(", "self", ",", "pars", ")", ":", "partials", "=", "[", "]", "# partials.append(self.dre_dlog10rho0(pars)[:, np.newaxis, :])", "partials", ".", "append", "(", "self", ".", "dre_drho0", "(", "pars", ")", "[", ":", ",", "np", ".", "new...
33.15625
0.001832
def plot_quadpole_evolution(dataobj, quadpole, cols, threshold=5, rolling=False, ax=None): """Visualize time-lapse evolution of a single quadropole. Parameters ---------- dataobj : :py:class:`pandas.DataFrame` DataFrame containing the data. Please refer to the docume...
[ "def", "plot_quadpole_evolution", "(", "dataobj", ",", "quadpole", ",", "cols", ",", "threshold", "=", "5", ",", "rolling", "=", "False", ",", "ax", "=", "None", ")", ":", "if", "isinstance", "(", "dataobj", ",", "pd", ".", "DataFrame", ")", ":", "df",...
28.929412
0.000786
def sum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): r""" Calculates a multi-dimensional sum filter. Parameters ---------- input : array-like input array to filter size : scalar or tuple, optional See footprint, below footprint :...
[ "def", "sum_filter", "(", "input", ",", "size", "=", "None", ",", "footprint", "=", "None", ",", "output", "=", "None", ",", "mode", "=", "\"reflect\"", ",", "cval", "=", "0.0", ",", "origin", "=", "0", ")", ":", "footprint", "=", "__make_footprint", ...
39.333333
0.001459
def _GetByteStreamOperation(self): """Retrieves the byte stream operation. Returns: ByteStreamOperation: byte stream operation or None if unable to determine. """ byte_order_string = self.GetStructByteOrderString() format_string = self.GetStructFormatString() # pylint: disable=assignment-fro...
[ "def", "_GetByteStreamOperation", "(", "self", ")", ":", "byte_order_string", "=", "self", ".", "GetStructByteOrderString", "(", ")", "format_string", "=", "self", ".", "GetStructFormatString", "(", ")", "# pylint: disable=assignment-from-none", "if", "not", "format_str...
37
0.008114
def parse_string(data, unquote=default_unquote): """Decode URL-encoded strings to UTF-8 containing the escaped chars. """ if data is None: return None # We'll soon need to unquote to recover our UTF-8 data. # In Python 2, unquote crashes on chars beyond ASCII. So encode functions # had ...
[ "def", "parse_string", "(", "data", ",", "unquote", "=", "default_unquote", ")", ":", "if", "data", "is", "None", ":", "return", "None", "# We'll soon need to unquote to recover our UTF-8 data.", "# In Python 2, unquote crashes on chars beyond ASCII. So encode functions", "# ha...
43.333333
0.000941
def _multi_call(function, contentkey, *args, **kwargs): ''' Retrieve full list of values for the contentkey from a boto3 ApiGateway client function that may be paged via 'position' ''' ret = function(*args, **kwargs) position = ret.get('position') while position: more = function(*ar...
[ "def", "_multi_call", "(", "function", ",", "contentkey", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "position", "=", "ret", ".", "get", "(", "'position'", ")", "whil...
35.384615
0.002119
def matthews_correl_coeff(ntp, ntn, nfp, nfn): ''' This calculates the Matthews correlation coefficent. https://en.wikipedia.org/wiki/Matthews_correlation_coefficient Parameters ---------- ntp : int The number of true positives. ntn : int The number of true negatives ...
[ "def", "matthews_correl_coeff", "(", "ntp", ",", "ntn", ",", "nfp", ",", "nfn", ")", ":", "mcc_top", "=", "(", "ntp", "*", "ntn", "-", "nfp", "*", "nfn", ")", "mcc_bot", "=", "msqrt", "(", "(", "ntp", "+", "nfp", ")", "*", "(", "ntp", "+", "nfn...
18.527778
0.001425
def _request_internal(self, command, **kwargs): """Make request parse response""" args = dict(kwargs) if self.ssid: args['ssid'] = self.ssid method = getattr(self.api, command) response = method(**args) if response and 'status' in response: if resp...
[ "def", "_request_internal", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "args", "=", "dict", "(", "kwargs", ")", "if", "self", ".", "ssid", ":", "args", "[", "'ssid'", "]", "=", "self", ".", "ssid", "method", "=", "getattr", "("...
44.666667
0.002436
def view(ctx, host, port, debug, pattern, family_file, family_type, variant_source, root, no_browser, phenomizer): """Visualize DNA variant resources. 1. Look for variant source(s) to visualize and inst. the right plugin """ main_loop = (not debug) or (os.environ.get('WERKZEUG_RUN_MAIN') == 't...
[ "def", "view", "(", "ctx", ",", "host", ",", "port", ",", "debug", ",", "pattern", ",", "family_file", ",", "family_type", ",", "variant_source", ",", "root", ",", "no_browser", ",", "phenomizer", ")", ":", "main_loop", "=", "(", "not", "debug", ")", "...
41.75
0.00234
def graph(self, as_dot=False): """Get the resolve graph. Args: as_dot: If True, get the graph as a dot-language string. Otherwise, a pygraph.digraph object is returned. Returns: A string or `pygraph.digraph` object, or None if there is no graph ...
[ "def", "graph", "(", "self", ",", "as_dot", "=", "False", ")", ":", "if", "not", "self", ".", "has_graph", ":", "return", "None", "if", "not", "as_dot", ":", "if", "self", ".", "graph_", "is", "None", ":", "# reads either dot format or our compact format", ...
35.766667
0.001815
def run(self): """ When *local_workflow_require_branches* of the task was set to *False*, starts all branch tasks via dynamic dependencies by yielding them in a list, or simply does nothing otherwise. """ if not self._has_yielded and not self.task.local_workflow_require_branches:...
[ "def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "_has_yielded", "and", "not", "self", ".", "task", ".", "local_workflow_require_branches", ":", "self", ".", "_has_yielded", "=", "True", "yield", "list", "(", "self", ".", "task", ".", "get_...
40
0.011111
def matchingfiles(self, projectpath): """Return a list of all inputfiles matching the profile (filenames)""" l = [] for inputtemplate in self.input: l += inputtemplate.matchingfiles(projectpath) return l
[ "def", "matchingfiles", "(", "self", ",", "projectpath", ")", ":", "l", "=", "[", "]", "for", "inputtemplate", "in", "self", ".", "input", ":", "l", "+=", "inputtemplate", ".", "matchingfiles", "(", "projectpath", ")", "return", "l" ]
40.333333
0.016194
def p_static_scalar_namespace_name(p): '''static_scalar : namespace_name | NS_SEPARATOR namespace_name | NAMESPACE NS_SEPARATOR namespace_name''' if len(p) == 2: p[0] = ast.Constant(p[1], lineno=p.lineno(1)) elif len(p) == 3: p[0] = ast.Constant(p[1]...
[ "def", "p_static_scalar_namespace_name", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "ast", ".", "Constant", "(", "p", "[", "1", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "el...
41.7
0.002347
def raise_not_enough_arguments(self, string): """ Raises an errors.ArgumentError if not enough arguments were supplied. Takes care of formatting for detailed error messages. Arguments: string (str): The string of the phrase for which there weren't enough arguments. Raises: errors.ArgumentErr...
[ "def", "raise_not_enough_arguments", "(", "self", ",", "string", ")", ":", "requested", "=", "errors", ".", "number", "(", "self", ".", "counter", "+", "1", ")", "number", "=", "len", "(", "self", ".", "positional", ")", "verb", "=", "\"was\"", "if", "...
23.555556
0.031722
def _create_run_config(options): """Create a `RunConfiguration` object from `options`.""" values = {opt: getattr(options, opt) for opt in RunConfiguration._fields} return RunConfiguration(**values)
[ "def", "_create_run_config", "(", "options", ")", ":", "values", "=", "{", "opt", ":", "getattr", "(", "options", ",", "opt", ")", "for", "opt", "in", "RunConfiguration", ".", "_fields", "}", "return", "RunConfiguration", "(", "*", "*", "values", ")" ]
48
0.012295
def transform(self, X, y=None): """Use the model to transform matrix to Shared Response space Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples_i] Each element in the list contains the fMRI data of one subject note that number of...
[ "def", "transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "# Check if the model exist", "if", "hasattr", "(", "self", ",", "'w_'", ")", "is", "False", ":", "raise", "NotFittedError", "(", "\"The model fit has not been run yet.\"", ")", "# Che...
34.15625
0.001779
def pov(self, color: chess.Color) -> "Score": """Get the score from the point of view of the given *color*.""" return self.relative if self.turn == color else -self.relative
[ "def", "pov", "(", "self", ",", "color", ":", "chess", ".", "Color", ")", "->", "\"Score\"", ":", "return", "self", ".", "relative", "if", "self", ".", "turn", "==", "color", "else", "-", "self", ".", "relative" ]
62.333333
0.010582
def run_console_rule(self, product, subject): """ :param product: A Goal subtype. :param subject: subject for the request. :returns: An exit_code for the given Goal. """ request = self.execution_request([product], [subject]) returns, throws = self.execute(request) if throws: _, st...
[ "def", "run_console_rule", "(", "self", ",", "product", ",", "subject", ")", ":", "request", "=", "self", ".", "execution_request", "(", "[", "product", "]", ",", "[", "subject", "]", ")", "returns", ",", "throws", "=", "self", ".", "execute", "(", "re...
30
0.010101
def _invoke_to_py_ast(ctx: GeneratorContext, node: Invoke) -> GeneratedPyAST: """Return a Python AST Node for a Basilisp function invocation.""" assert node.op == NodeOp.INVOKE fn_ast = gen_py_ast(ctx, node.fn) args_deps, args_nodes = _collection_ast(ctx, node.args) return GeneratedPyAST( ...
[ "def", "_invoke_to_py_ast", "(", "ctx", ":", "GeneratorContext", ",", "node", ":", "Invoke", ")", "->", "GeneratedPyAST", ":", "assert", "node", ".", "op", "==", "NodeOp", ".", "INVOKE", "fn_ast", "=", "gen_py_ast", "(", "ctx", ",", "node", ".", "fn", ")...
40.909091
0.002174
def is_monotonic(full_list): """ Determine whether elements in a list are monotonic. ie. unique elements are clustered together. ie. [5,5,3,4] is, [5,3,5] is not. """ prev_elements = set({full_list[0]}) prev_item = full_list[0] for item in full_list: if item != prev_item: ...
[ "def", "is_monotonic", "(", "full_list", ")", ":", "prev_elements", "=", "set", "(", "{", "full_list", "[", "0", "]", "}", ")", "prev_item", "=", "full_list", "[", "0", "]", "for", "item", "in", "full_list", ":", "if", "item", "!=", "prev_item", ":", ...
24.777778
0.00216
def majmin(reference_labels, estimated_labels): """Compare chords along major-minor rules. Chords with qualities outside Major/minor/no-chord are ignored. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_...
[ "def", "majmin", "(", "reference_labels", ",", "estimated_labels", ")", ":", "validate", "(", "reference_labels", ",", "estimated_labels", ")", "maj_semitones", "=", "np", ".", "array", "(", "QUALITIES", "[", "'maj'", "]", "[", ":", "8", "]", ")", "min_semit...
40.9375
0.000373
def delete_option_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete an RDS option group. CLI example:: salt myminion boto_rds.delete_option_group my-opt-group \ region=us-east-1 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, pr...
[ "def", "delete_option_group", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "...
34.130435
0.001239
def query(host=None, quiet=False): ''' Query the virtual machines. When called without options all hosts are detected and a full query is returned. A single host can be passed in to specify an individual host to query. ''' if quiet: log.warning("'quiet' is deprecated. Please migrate to -...
[ "def", "query", "(", "host", "=", "None", ",", "quiet", "=", "False", ")", ":", "if", "quiet", ":", "log", ".", "warning", "(", "\"'quiet' is deprecated. Please migrate to --quiet\"", ")", "ret", "=", "{", "}", "client", "=", "salt", ".", "client", ".", ...
36.428571
0.001528
def getAllViewsAsDict(self): """Return all the stats views (dict).""" return {p: self._plugins[p].get_views() for p in self._plugins}
[ "def", "getAllViewsAsDict", "(", "self", ")", ":", "return", "{", "p", ":", "self", ".", "_plugins", "[", "p", "]", ".", "get_views", "(", ")", "for", "p", "in", "self", ".", "_plugins", "}" ]
49
0.013423
def datasets(ctx): """Read and write GeoJSON from Mapbox-hosted datasets All endpoints require authentication. An access token with appropriate dataset scopes is required, see `mapbox --help`. Note that this API is currently a limited-access beta. """ access_token = (ctx.obj and ctx.obj.get('...
[ "def", "datasets", "(", "ctx", ")", ":", "access_token", "=", "(", "ctx", ".", "obj", "and", "ctx", ".", "obj", ".", "get", "(", "'access_token'", ")", ")", "or", "None", "service", "=", "mapbox", ".", "Datasets", "(", "access_token", "=", "access_toke...
35.166667
0.002309
def count_documents(self, filter, session=None, **kwargs): """Count the number of documents in this collection. The :meth:`count_documents` method is supported in a transaction. All optional parameters should be passed as keyword arguments to this method. Valid options include: ...
[ "def", "count_documents", "(", "self", ",", "filter", ",", "session", "=", "None", ",", "*", "*", "kwargs", ")", ":", "pipeline", "=", "[", "{", "'$match'", ":", "filter", "}", "]", "if", "'skip'", "in", "kwargs", ":", "pipeline", ".", "append", "(",...
48.589744
0.00181
def remove_consumer_process(self, consumer, name): """Remove all details for the specified consumer and process name. :param str consumer: The consumer name :param str name: The process name """ my_pid = os.getpid() if name in self.consumers[consumer].processes.keys(): ...
[ "def", "remove_consumer_process", "(", "self", ",", "consumer", ",", "name", ")", ":", "my_pid", "=", "os", ".", "getpid", "(", ")", "if", "name", "in", "self", ".", "consumers", "[", "consumer", "]", ".", "processes", ".", "keys", "(", ")", ":", "ch...
37.074074
0.001947
def stdformD(D, Cd, M, dimN=2): """Reshape dictionary array (`D` in :mod:`.admm.cbpdn` module, `X` in :mod:`.admm.ccmod` module) to internal standard form. Parameters ---------- D : array_like Dictionary array Cd : int Size of dictionary channel index M : int Number of fil...
[ "def", "stdformD", "(", "D", ",", "Cd", ",", "M", ",", "dimN", "=", "2", ")", ":", "return", "D", ".", "reshape", "(", "D", ".", "shape", "[", "0", ":", "dimN", "]", "+", "(", "Cd", ",", ")", "+", "(", "1", ",", ")", "+", "(", "M", ",",...
24.409091
0.001792
def _percent_selection(self, non_empty_slices): """Chooses slices at a given percentage between the first and last non-empty slice.""" return np.around(self._sampler * len(non_empty_slices) / 100).astype('int64')
[ "def", "_percent_selection", "(", "self", ",", "non_empty_slices", ")", ":", "return", "np", ".", "around", "(", "self", ".", "_sampler", "*", "len", "(", "non_empty_slices", ")", "/", "100", ")", ".", "astype", "(", "'int64'", ")" ]
56.5
0.017467
def deserialize_logical(self, node): """ Reads the logical tag from the given node, returns a Condition object. node -- the xml node (xml.dom.minidom.Node) """ term1_attrib = node.getAttribute('left-field') term1_value = node.getAttribute('left-value') op = node....
[ "def", "deserialize_logical", "(", "self", ",", "node", ")", ":", "term1_attrib", "=", "node", ".", "getAttribute", "(", "'left-field'", ")", "term1_value", "=", "node", ".", "getAttribute", "(", "'left-value'", ")", "op", "=", "node", ".", "nodeName", ".", ...
42.233333
0.001543
def set_base_prompt( self, pri_prompt_terminator=":", alt_prompt_terminator=">", delay_factor=2 ): """Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output.""" super(CoriantSSH, self).set_base_prompt( pri_prompt_terminator=pri_prompt_terminator, ...
[ "def", "set_base_prompt", "(", "self", ",", "pri_prompt_terminator", "=", "\":\"", ",", "alt_prompt_terminator", "=", "\">\"", ",", "delay_factor", "=", "2", ")", ":", "super", "(", "CoriantSSH", ",", "self", ")", ".", "set_base_prompt", "(", "pri_prompt_termina...
44.4
0.011038
def infer_table_schema(sparql_results_json): """Infer Table Schema from SPARQL results JSON SPARQL JSON Results Spec: https://www.w3.org/TR/2013/REC-sparql11-results-json-20130321 :param sparql_results_json: SPARQL JSON results of a query :returns: A schema descriptor for the inferred schema :...
[ "def", "infer_table_schema", "(", "sparql_results_json", ")", ":", "if", "(", "'results'", "in", "sparql_results_json", "and", "'bindings'", "in", "sparql_results_json", "[", "'results'", "]", "and", "len", "(", "sparql_results_json", "[", "'results'", "]", "[", "...
39
0.000397
def which(name, flags=os.X_OK): """Search PATH for executable files with the given name. ..note:: This function was taken verbatim from the twisted framework, licence available here: http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.2.0/LICENSE On newer versions of MS-Windows, the ...
[ "def", "which", "(", "name", ",", "flags", "=", "os", ".", "X_OK", ")", ":", "result", "=", "[", "]", "# pylint: disable=W0141", "extensions", "=", "[", "_f", "for", "_f", "in", "os", ".", "environ", ".", "get", "(", "'PATHEXT'", ",", "''", ")", "....
32.949153
0.0005
def main(): """ NAME watsons_f.py DESCRIPTION calculates Watson's F statistic from input files INPUT FORMAT takes dec/inc as first two columns in two space delimited files SYNTAX watsons_f.py [command line options] OPTIONS -h prints help message and qui...
[ "def", "main", "(", ")", ":", "D", ",", "D1", ",", "D2", "=", "[", "]", ",", "[", "]", ",", "[", "]", "Flip", "=", "0", "if", "'-h'", "in", "sys", ".", "argv", ":", "# check if help is needed", "print", "(", "main", ".", "__doc__", ")", "sys", ...
26.410959
0.0315
def configure(): """ Setup various global variables based on environment variables. """ global _DOWNLOADS_DIR global _CURRENT_RELEASE _CURRENT_RELEASE = None _DOWNLOADS_DIR = environ.get("MHCFLURRY_DOWNLOADS_DIR") if not _DOWNLOADS_DIR: metadata = get_downloads_metadata() ...
[ "def", "configure", "(", ")", ":", "global", "_DOWNLOADS_DIR", "global", "_CURRENT_RELEASE", "_CURRENT_RELEASE", "=", "None", "_DOWNLOADS_DIR", "=", "environ", ".", "get", "(", "\"MHCFLURRY_DOWNLOADS_DIR\"", ")", "if", "not", "_DOWNLOADS_DIR", ":", "metadata", "=", ...
44.361111
0.000613
def update(self, response): """Update session information from device response. Increment sequence number when starting stream, not when playing. If device requires authentication resend previous message with auth. """ data = response.splitlines() _LOGGER.debug('Received...
[ "def", "update", "(", "self", ",", "response", ")", ":", "data", "=", "response", ".", "splitlines", "(", ")", "_LOGGER", ".", "debug", "(", "'Received data %s from %s'", ",", "data", ",", "self", ".", "host", ")", "while", "data", ":", "line", "=", "d...
43.313433
0.001011
def strip_size(self, location='top', num_lines=None): """ Breadth of the strip background in inches Parameters ---------- location : str in ``['top', 'right']`` Location of the strip text num_lines : int Number of text lines """ dp...
[ "def", "strip_size", "(", "self", ",", "location", "=", "'top'", ",", "num_lines", "=", "None", ")", ":", "dpi", "=", "72", "theme", "=", "self", ".", "theme", "get_property", "=", "theme", ".", "themeables", ".", "property", "if", "location", "==", "'...
32.111111
0.001343
def Graetz_heat(V, D, x, rho=None, Cp=None, k=None, alpha=None): r'''Calculates Graetz number or `Gz` for a specified velocity `V`, diameter `D`, axial distance `x`, and specified properties for the given fluid. .. math:: Gz = \frac{VD^2\cdot C_p \rho}{x\cdot k} = \frac{VD^2}{x \alpha} Inp...
[ "def", "Graetz_heat", "(", "V", ",", "D", ",", "x", ",", "rho", "=", "None", ",", "Cp", "=", "None", ",", "k", "=", "None", ",", "alpha", "=", "None", ")", ":", "if", "rho", "and", "Cp", "and", "k", ":", "alpha", "=", "k", "/", "(", "rho", ...
26.892308
0.001656
def _to_json(uniq): """ Serializes a MOC to the JSON format. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result_json : {str : [int]} A dictionary of H...
[ "def", "_to_json", "(", "uniq", ")", ":", "result_json", "=", "{", "}", "depth", ",", "ipix", "=", "utils", ".", "uniq2orderipix", "(", "uniq", ")", "min_depth", "=", "np", ".", "min", "(", "depth", "[", "0", "]", ")", "max_depth", "=", "np", ".", ...
29.321429
0.002358
def link(self, link): """ Create hard link as link to this file """ if isinstance(link, File): link = link.filename os.link(self.filename, link)
[ "def", "link", "(", "self", ",", "link", ")", ":", "if", "isinstance", "(", "link", ",", "File", ")", ":", "link", "=", "link", ".", "filename", "os", ".", "link", "(", "self", ".", "filename", ",", "link", ")" ]
35.2
0.011111
def filter_debug(stream, it): """ Read line chunks from it, either yielding them directly, or building up and logging individual lines if they look like SSH debug output. This contains the mess of dealing with both line-oriented input, and partial lines such as the password prompt. Yields `(li...
[ "def", "filter_debug", "(", "stream", ",", "it", ")", ":", "# The `partial` test is unreliable, but is only problematic when verbosity", "# is enabled: it's possible for a combination of SSH banner, password", "# prompt, verbose output, timing and OS buffering specifics to create a", "# situat...
45.914894
0.000907
def canonicalize(method, resource, query_parameters, headers): """Canonicalize method, resource :type method: str :param method: The HTTP verb that will be used when requesting the URL. Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the signature will additio...
[ "def", "canonicalize", "(", "method", ",", "resource", ",", "query_parameters", ",", "headers", ")", ":", "headers", ",", "_", "=", "get_canonical_headers", "(", "headers", ")", "if", "method", "==", "\"RESUMABLE\"", ":", "method", "=", "\"POST\"", "headers", ...
41.125
0.000495
def file_iterator(filehandle, verbose=False): """Iterate over a file and yield stripped lines. Optionally show progress.""" if type(filehandle).__name__ == "str": filehandle = open(filehandle) if verbose: try: pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name), ...
[ "def", "file_iterator", "(", "filehandle", ",", "verbose", "=", "False", ")", ":", "if", "type", "(", "filehandle", ")", ".", "__name__", "==", "\"str\"", ":", "filehandle", "=", "open", "(", "filehandle", ")", "if", "verbose", ":", "try", ":", "pind", ...
36.038462
0.011435
def load_rates(freq="D"): """Load interest rates from https://fred.stlouisfed.org/. Parameters ---------- reload : bool, default True If True, download the data from source rather than loading pickled data freq : str {'D', 'W', 'M'}, default 'D' Frequency of time series; dai...
[ "def", "load_rates", "(", "freq", "=", "\"D\"", ")", ":", "months", "=", "[", "1", ",", "3", ",", "6", "]", "years", "=", "[", "1", ",", "2", ",", "3", ",", "5", ",", "7", ",", "10", ",", "20", ",", "30", "]", "# Nested dictionaries of symbols ...
29.024096
0.000401
def extent(self): """ return range of 2D data """ return [min(self.x), max(self.x), min(self.y), max(self.y)]
[ "def", "extent", "(", "self", ")", ":", "return", "[", "min", "(", "self", ".", "x", ")", ",", "max", "(", "self", ".", "x", ")", ",", "min", "(", "self", ".", "y", ")", ",", "max", "(", "self", ".", "y", ")", "]" ]
19.571429
0.013986
def dragEnterEvent(self, event): """ Reimplements the :meth:`QTabWidget.dragEnterEvent` method. :param event: QEvent. :type event: QEvent """ LOGGER.debug("> '{0}' widget drag enter event accepted!".format(self.__class__.__name__)) event.accept()
[ "def", "dragEnterEvent", "(", "self", ",", "event", ")", ":", "LOGGER", ".", "debug", "(", "\"> '{0}' widget drag enter event accepted!\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "event", ".", "accept", "(", ")" ]
29.5
0.009868
def _load_data(self, band): """From the WISE All-Sky Explanatory Supplement, IV.4.h.i.1, and Jarrett+ 2011. These are relative response per erg and so can be integrated directly against F_nu spectra. Wavelengths are in micron, uncertainties are in parts per thousand. """ ...
[ "def", "_load_data", "(", "self", ",", "band", ")", ":", "# `band` should be 1, 2, 3, or 4.", "df", "=", "bandpass_data_frame", "(", "'filter_wise_'", "+", "str", "(", "band", ")", "+", "'.dat'", ",", "'wlen resp uncert'", ")", "df", ".", "wlen", "*=", "1e4", ...
47.571429
0.010309
def get_store(self, name, workspace=None): ''' Returns a single store object. Will return None if no store is found. Will raise an error if more than one store with the same name is found. ''' stores = self.get_stores(workspaces=workspace, names=name) retur...
[ "def", "get_store", "(", "self", ",", "name", ",", "workspace", "=", "None", ")", ":", "stores", "=", "self", ".", "get_stores", "(", "workspaces", "=", "workspace", ",", "names", "=", "name", ")", "return", "self", ".", "_return_first_item", "(", "store...
38.333333
0.008499
def to_shared_lib(name): """Return library name depending on platform. Parameters ---------- name : str Name of library. Returns ------- str Name of library with extension. """ if sys.platform.startswith('linux'): return name + '.so' elif sys.platform.s...
[ "def", "to_shared_lib", "(", "name", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "return", "name", "+", "'.so'", "elif", "sys", ".", "platform", ".", "startswith", "(", "'darwin'", ")", ":", "return", "name", "+...
20.454545
0.002123
def __query_assertion(self, xpath_expr): """ Extracts nodes that match the query from the Assertion :param xpath_expr: Xpath Expresion :type xpath_expr: String :returns: The queried nodes :rtype: list """ assertion_expr = '/saml:Assertion' signa...
[ "def", "__query_assertion", "(", "self", ",", "xpath_expr", ")", ":", "assertion_expr", "=", "'/saml:Assertion'", "signature_expr", "=", "'/ds:Signature/ds:SignedInfo/ds:Reference'", "signed_assertion_query", "=", "'/samlp:Response'", "+", "assertion_expr", "+", "signature_ex...
39.529412
0.002179
def HandleForwardedIps(self, interface, forwarded_ips, interface_ip=None): """Handle changes to the forwarded IPs on a network interface. Args: interface: string, the output device to configure. forwarded_ips: list, the forwarded IP address strings desired. interface_ip: string, current inter...
[ "def", "HandleForwardedIps", "(", "self", ",", "interface", ",", "forwarded_ips", ",", "interface_ip", "=", "None", ")", ":", "desired", "=", "self", ".", "ip_forwarding_utils", ".", "ParseForwardedIps", "(", "forwarded_ips", ")", "configured", "=", "self", ".",...
46.294118
0.001245
def hour_angle(times, longitude, equation_of_time): """ Hour angle in local solar time. Zero at local solar noon. Parameters ---------- times : :class:`pandas.DatetimeIndex` Corresponding timestamps, must be localized to the timezone for the ``longitude``. longitude : numeric ...
[ "def", "hour_angle", "(", "times", ",", "longitude", ",", "equation_of_time", ")", ":", "naive_times", "=", "times", ".", "tz_localize", "(", "None", ")", "# naive but still localized", "# hours - timezone = (times - normalized_times) - (naive_times - times)", "hrs_minus_tzs"...
33.418605
0.000676
def sample_W(self, nSamples, raw_samples=False): """ Sample the loading matrix if the kernel is linear. """ assert isinstance(self.kern, kern.Linear) from ..util.linalg import pdinv N, D = self.Y.shape Q = self.X.shape[1] noise_var = self.likelihood.varian...
[ "def", "sample_W", "(", "self", ",", "nSamples", ",", "raw_samples", "=", "False", ")", ":", "assert", "isinstance", "(", "self", ".", "kern", ",", "kern", ".", "Linear", ")", "from", ".", ".", "util", ".", "linalg", "import", "pdinv", "N", ",", "D",...
43.107143
0.023501
def prewhiten_magseries(times, mags, errs, whitenperiod, whitenparams, sigclip=3.0, magsarefluxes=False, plotfit=None, plotfitphasedlconly=True, rescale...
[ "def", "prewhiten_magseries", "(", "times", ",", "mags", ",", "errs", ",", "whitenperiod", ",", "whitenparams", ",", "sigclip", "=", "3.0", ",", "magsarefluxes", "=", "False", ",", "plotfit", "=", "None", ",", "plotfitphasedlconly", "=", "True", ",", "rescal...
32.696154
0.002283
def eqtflength(b,a): """Given two list or arrays, pad with zeros the shortest array :param b: list or array :param a: list or array .. doctest:: >>> from spectrum.transfer import eqtflength >>> a = [1,2] >>> b = [1,2,3,4] >>> a, b, = eqtflength(a,b) """ d = a...
[ "def", "eqtflength", "(", "b", ",", "a", ")", ":", "d", "=", "abs", "(", "len", "(", "b", ")", "-", "len", "(", "a", ")", ")", "if", "d", "!=", "0", ":", "if", "len", "(", "a", ")", ">", "len", "(", "b", ")", ":", "try", ":", "b", "."...
21.566667
0.010355
def gridnet(np, pfile, plenfile, tlenfile, gordfile, outlet=None, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): """Run gridnet""" fname = TauDEM.func_name('gridnet') return TauDEM.run(FileClass.get_executable_fullpath(fname, exedi...
[ "def", "gridnet", "(", "np", ",", "pfile", ",", "plenfile", ",", "tlenfile", ",", "gordfile", ",", "outlet", "=", "None", ",", "workingdir", "=", "None", ",", "mpiexedir", "=", "None", ",", "exedir", "=", "None", ",", "log_file", "=", "None", ",", "r...
65.7
0.010511
def serialize_dataframe(writer, data_type_id, dataframe): """ Serialize a dataframe. Parameters ---------- writer : file File-like object to write to. Must be opened in binary mode. data_type_id : dict Serialization format to use. See the azureml.DataTypeIds class for co...
[ "def", "serialize_dataframe", "(", "writer", ",", "data_type_id", ",", "dataframe", ")", ":", "_not_none", "(", "'writer'", ",", "writer", ")", "_not_none_or_empty", "(", "'data_type_id'", ",", "data_type_id", ")", "_not_none", "(", "'dataframe'", ",", "dataframe"...
31.272727
0.00141
def make_default(self, user, group_membership): """ Set the passed GroupMembership as default for the specified user. :param user: User object or id :param group_membership: GroupMembership object or id """ return self._put(self._build_url(self.endpoint.make_default(user...
[ "def", "make_default", "(", "self", ",", "user", ",", "group_membership", ")", ":", "return", "self", ".", "_put", "(", "self", ".", "_build_url", "(", "self", ".", "endpoint", ".", "make_default", "(", "user", ",", "group_membership", ")", ")", ",", "pa...
43.25
0.008499
def p_ExtendedAttributeIdent(p): """ExtendedAttributeIdent : IDENTIFIER "=" IDENTIFIER""" p[0] = model.ExtendedAttribute( name=p[1], value=model.ExtendedAttributeValue(name=p[3]))
[ "def", "p_ExtendedAttributeIdent", "(", "p", ")", ":", "p", "[", "0", "]", "=", "model", ".", "ExtendedAttribute", "(", "name", "=", "p", "[", "1", "]", ",", "value", "=", "model", ".", "ExtendedAttributeValue", "(", "name", "=", "p", "[", "3", "]", ...
37.4
0.015707
def prettyhtml(value, autoescape=None): 'Clean (and optionally escape) passed html of unsafe tags and attributes.' value = html_cleaner(value) return escape(value) if autoescape\ and not isinstance(value, SafeData) else mark_safe(value)
[ "def", "prettyhtml", "(", "value", ",", "autoescape", "=", "None", ")", ":", "value", "=", "html_cleaner", "(", "value", ")", "return", "escape", "(", "value", ")", "if", "autoescape", "and", "not", "isinstance", "(", "value", ",", "SafeData", ")", "else...
47.4
0.020747
def _get_coord(self, coord): """ It's a hack, see fixcoord in pyreadline's console.py (revision 1289) """ x, y = coord return self.ctypes.c_int(y << 16 | x)
[ "def", "_get_coord", "(", "self", ",", "coord", ")", ":", "x", ",", "y", "=", "coord", "return", "self", ".", "ctypes", ".", "c_int", "(", "y", "<<", "16", "|", "x", ")" ]
32
0.015228
def check_recommended_files(data, vcs): """Do check for recommended files. Returns True when all is fine. """ main_files = os.listdir(data['workingdir']) if not 'setup.py' in main_files and not 'setup.cfg' in main_files: # Not a python package. We have no recommendations. return Tr...
[ "def", "check_recommended_files", "(", "data", ",", "vcs", ")", ":", "main_files", "=", "os", ".", "listdir", "(", "data", "[", "'workingdir'", "]", ")", "if", "not", "'setup.py'", "in", "main_files", "and", "not", "'setup.cfg'", "in", "main_files", ":", "...
40.030303
0.002217
def ord(x): ''' x-->char (str of length 1) Returns-->int Behaves like PY2 ord() in PY2 or PY3 if x is str of length > 1 or int > 256 raises ValueError/TypeError is not SUPPRESS_ERRORS ''' global _ord if isinstance(x, int): if x > 256: if not SUPPRESS_ERROR...
[ "def", "ord", "(", "x", ")", ":", "global", "_ord", "if", "isinstance", "(", "x", ",", "int", ")", ":", "if", "x", ">", "256", ":", "if", "not", "SUPPRESS_ERRORS", ":", "raise", "ValueError", "(", "'ord() arg not in range(256)'", ")", "return", "x", "%...
28
0.001279
def encode_waypoints(features, min_limit=None, max_limit=None, precision=6): """Given an iterable of features return a string encoded in waypoint-style used by certain mapbox APIs ("lon,lat" pairs separated by ";") """ coords = ['{lon},{lat}'.format( lon=float(round(lon, precision)...
[ "def", "encode_waypoints", "(", "features", ",", "min_limit", "=", "None", ",", "max_limit", "=", "None", ",", "precision", "=", "6", ")", ":", "coords", "=", "[", "'{lon},{lat}'", ".", "format", "(", "lon", "=", "float", "(", "round", "(", "lon", ",",...
41.95
0.001166
def get_assigned_to_user(parser, token): """ Populates a template variable with the content with WorkflowState assignd for the given criteria. Usage:: {% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %} Examples:: {% get_assigned_to_user 10 ...
[ "def", "get_assigned_to_user", "(", "parser", ",", "token", ")", ":", "tokens", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "tokens", ")", "<", "4", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"'get_assigned_to...
40.787879
0.002177
def run_bwa(job, fastqs, sample_type, univ_options, bwa_options): """ This module aligns the SAMPLE_TYPE dna fastqs to the reference ARGUMENTS -- <ST> depicts the sample type. Substitute with 'tumor'/'normal' 1. fastqs: Dict of list of input WGS/WXS fastqs fastqs +- '<ST>_dna': [...
[ "def", "run_bwa", "(", "job", ",", "fastqs", ",", "sample_type", ",", "univ_options", ",", "bwa_options", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Running bwa on %s:%s'", "%", "(", "univ_options", "[", "'patient'", "]", ",", "sample_type",...
49.078431
0.00235
def from_config( cls, obj, selectable, ingredient_constructor=ingredient_from_validated_dict, metadata=None ): """Create a shelf using a dict shelf definition. :param obj: A Python dictionary describing a Shelf. :param selectable: A SQLAlchemy Table, ...
[ "def", "from_config", "(", "cls", ",", "obj", ",", "selectable", ",", "ingredient_constructor", "=", "ingredient_from_validated_dict", ",", "metadata", "=", "None", ")", ":", "from", "recipe", "import", "Recipe", "if", "isinstance", "(", "selectable", ",", "Reci...
34.538462
0.002166
def save_block(self, data, dest): """ Save data on dest, which is file open in 'a' mode """ write_csv(dest, data, self.sep, self.fmt, 'no-header')
[ "def", "save_block", "(", "self", ",", "data", ",", "dest", ")", ":", "write_csv", "(", "dest", ",", "data", ",", "self", ".", "sep", ",", "self", ".", "fmt", ",", "'no-header'", ")" ]
34.8
0.011236
def run_script(script_path, cwd='.'): """Execute a script from a working directory. :param script_path: Absolute path to the script to run. :param cwd: The directory to run the script from. """ run_thru_shell = sys.platform.startswith('win') if script_path.endswith('.py'): script_comman...
[ "def", "run_script", "(", "script_path", ",", "cwd", "=", "'.'", ")", ":", "run_thru_shell", "=", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", "if", "script_path", ".", "endswith", "(", "'.py'", ")", ":", "script_command", "=", "[", "sys...
31.852941
0.000896
def remove_tag_from_derived_metric(self, id, tag_value, **kwargs): # noqa: E501 """Remove a tag from a specific Derived Metric # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
[ "def", "remove_tag_from_derived_metric", "(", "self", ",", "id", ",", "tag_value", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retu...
45.818182
0.001944
def Campbell_Thodos(T, Tb, Tc, Pc, M, dipole=None, hydroxyl=False): r'''Calculate saturation liquid density using the Campbell-Thodos [1]_ CSP method. An old and uncommon estimation method. .. math:: V_s = \frac{RT_c}{P_c}{Z_{RA}}^{[1+(1-T_r)^{2/7}]} Z_{RA} = \alpha + \beta(1-T_r) ...
[ "def", "Campbell_Thodos", "(", "T", ",", "Tb", ",", "Tc", ",", "Pc", ",", "M", ",", "dipole", "=", "None", ",", "hydroxyl", "=", "False", ")", ":", "Tr", "=", "T", "/", "Tc", "Tbr", "=", "Tb", "/", "Tc", "Pc", "=", "Pc", "/", "101325.", "s", ...
27.958333
0.00072
def convert_path(cls, file): """ Check to see if an extended path is given and convert appropriately """ if isinstance(file,str): return file elif isinstance(file, list) and all([isinstance(x, str) for x in file]): return "/".join(file) else: ...
[ "def", "convert_path", "(", "cls", ",", "file", ")", ":", "if", "isinstance", "(", "file", ",", "str", ")", ":", "return", "file", "elif", "isinstance", "(", "file", ",", "list", ")", "and", "all", "(", "[", "isinstance", "(", "x", ",", "str", ")",...
31
0.010444
def linstack(streams, normalize=True): """ Compute the linear stack of a series of seismic streams of \ multiplexed data. :type streams: list :param streams: List of streams to stack :type normalize: bool :param normalize: Normalize traces before stacking, normalizes by the RMS \ am...
[ "def", "linstack", "(", "streams", ",", "normalize", "=", "True", ")", ":", "stack", "=", "streams", "[", "np", ".", "argmax", "(", "[", "len", "(", "stream", ")", "for", "stream", "in", "streams", "]", ")", "]", ".", "copy", "(", ")", "if", "nor...
36.757576
0.000803
def custom(command, user=None, conf_file=None, bin_env=None): ''' Run any custom supervisord command user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI...
[ "def", "custom", "(", "command", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "_ctl_cmd", "(", "command", ",", "None", ",", "conf_file", ",", "...
23.666667
0.001692
def reverse_ip_whois(self, query=None, ip=None, country=None, server=None, include_total_count=False, page=1, **kwargs): """Pass in an IP address or a list of free text query terms.""" if (ip and query) or not (ip or query): raise ValueError('Query or IP Address (but...
[ "def", "reverse_ip_whois", "(", "self", ",", "query", "=", "None", ",", "ip", "=", "None", ",", "country", "=", "None", ",", "server", "=", "None", ",", "include_total_count", "=", "False", ",", "page", "=", "1", ",", "*", "*", "kwargs", ")", ":", ...
67.777778
0.014563
def MICECache(subsystem, parent_cache=None): """Construct a |MICE| cache. Uses either a Redis-backed cache or a local dict cache on the object. Args: subsystem (Subsystem): The subsystem that this is a cache for. Kwargs: parent_cache (MICECache): The cache generated by the uncut ...
[ "def", "MICECache", "(", "subsystem", ",", "parent_cache", "=", "None", ")", ":", "if", "config", ".", "REDIS_CACHE", ":", "cls", "=", "RedisMICECache", "else", ":", "cls", "=", "DictMICECache", "return", "cls", "(", "subsystem", ",", "parent_cache", "=", ...
33.157895
0.001543
def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.id)) cache.delete('PAGE_FIRST_ROOT_ID') self._languages = None self._complete_slug = None self._content_dict = dict() p_names = [p.name for p in get_pl...
[ "def", "invalidate", "(", "self", ")", ":", "cache", ".", "delete", "(", "self", ".", "PAGE_LANGUAGES_KEY", "%", "(", "self", ".", "id", ")", ")", "cache", ".", "delete", "(", "'PAGE_FIRST_ROOT_ID'", ")", "self", ".", "_languages", "=", "None", "self", ...
35.590909
0.002488
def org_update(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/update API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Fupdate """ return DXHTTPRequest('/%s/update' % object_id, input_para...
[ "def", "org_update", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/update'", "%", "object_id", ",", "input_params", ",", "always_retry", "=", ...
50.571429
0.008333
def _decrement_current_byte(self): """ Decrements the value of the current byte at the pointer. If the result is below 0, then it will overflow to 255 """ # If the current byte is uninitialized, then decrementing it will make it the max cell size # Otherwise, if it's alre...
[ "def", "_decrement_current_byte", "(", "self", ")", ":", "# If the current byte is uninitialized, then decrementing it will make it the max cell size", "# Otherwise, if it's already at the minimum cell size, then it will also make it the max cell size", "if", "self", ".", "tape", "[", "sel...
54.909091
0.009772
def send_reply(*types, **options): """Decorator for sending replies from request callback methods. This decorator constructs a reply from a list or tuple returned from a callback method, but unlike the return_reply decorator it also sends the reply rather than returning it. The list/tuple returned...
[ "def", "send_reply", "(", "*", "types", ",", "*", "*", "options", ")", ":", "major", "=", "options", ".", "pop", "(", "'major'", ",", "DEFAULT_KATCP_MAJOR", ")", "if", "len", "(", "options", ")", ">", "0", ":", "raise", "TypeError", "(", "'send_reply d...
32.755102
0.000605
def calc_ag_v1(self): """Sum the through flown area of the total cross section. Required flux sequences: |AM| |AV| |AVR| Calculated flux sequence: |AG| Example: >>> from hydpy.models.lstream import * >>> parameterstep() >>> fluxes.am = 1.0 >>> ...
[ "def", "calc_ag_v1", "(", "self", ")", ":", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "flu", ".", "ag", "=", "flu", ".", "am", "+", "flu", ".", "av", "[", "0", "]", "+", "flu", ".", "av", "[", "1", "]", "+", "flu...
22.208333
0.001799
def aiohttp_socket_timeout(socket_timeout_s): """ Return a aiohttp.ClientTimeout object with only socket timeouts set. """ return aiohttp.ClientTimeout(total=None, connect=None, sock_connect=socket_timeout_s, sock_read=sock...
[ "def", "aiohttp_socket_timeout", "(", "socket_timeout_s", ")", ":", "return", "aiohttp", ".", "ClientTimeout", "(", "total", "=", "None", ",", "connect", "=", "None", ",", "sock_connect", "=", "socket_timeout_s", ",", "sock_read", "=", "socket_timeout_s", ")" ]
54.666667
0.009009
def log_output(self, format_dict): """Log the output.""" if self.shell.logger.log_output: self.shell.logger.log_write(format_dict['text/plain'], 'output') self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ format_di...
[ "def", "log_output", "(", "self", ",", "format_dict", ")", ":", "if", "self", ".", "shell", ".", "logger", ".", "log_output", ":", "self", ".", "shell", ".", "logger", ".", "log_write", "(", "format_dict", "[", "'text/plain'", "]", ",", "'output'", ")", ...
55.166667
0.008929
def blobs(shape: List[int], porosity: float = 0.5, blobiness: int = 1): """ Generates an image containing amorphous blobs Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where N is the number of voxels porosity : float If specified, ...
[ "def", "blobs", "(", "shape", ":", "List", "[", "int", "]", ",", "porosity", ":", "float", "=", "0.5", ",", "blobiness", ":", "int", "=", "1", ")", ":", "blobiness", "=", "sp", ".", "array", "(", "blobiness", ")", "shape", "=", "sp", ".", "array"...
30
0.000769