text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def fix_style(style='basic', ax=None, **kwargs): ''' Add an extra formatting layer to an axe, that couldn't be changed directly in matplotlib.rcParams or with styles. Apply this function to every axe you created. Parameters ---------- ax: a matplotlib axe. If None, the last ...
[ "def", "fix_style", "(", "style", "=", "'basic'", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "style", "=", "_read_style", "(", "style", ")", "# Apply all styles", "for", "s", "in", "style", ":", "if", "not", "s", "in", "style_params", ...
30.521739
0.010352
def _elem_from_descendants(children_nodes, **options): """ :param children_nodes: A list of child dict objects :param options: Keyword options, see :func:`container_to_etree` """ for child in children_nodes: # child should be a dict-like object. for ckey, cval in anyconfig.compat.iteritems(...
[ "def", "_elem_from_descendants", "(", "children_nodes", ",", "*", "*", "options", ")", ":", "for", "child", "in", "children_nodes", ":", "# child should be a dict-like object.", "for", "ckey", ",", "cval", "in", "anyconfig", ".", "compat", ".", "iteritems", "(", ...
44.1
0.002222
def count(self, query): """ If query is Select object, this function will try to get count of select """ if self.manual: return self.total if isinstance(query, Select): q = query.with_only_columns([func.count()]).order_by(None).limit(None)...
[ "def", "count", "(", "self", ",", "query", ")", ":", "if", "self", ".", "manual", ":", "return", "self", ".", "total", "if", "isinstance", "(", "query", ",", "Select", ")", ":", "q", "=", "query", ".", "with_only_columns", "(", "[", "func", ".", "c...
32.5
0.012469
def nose_selector(test): """Return the string you can pass to nose to run `test`, including argument values if the test was made by a test generator. Return "Unknown test" if it can't construct a decent path. """ address = test_address(test) if address: file, module, rest = address ...
[ "def", "nose_selector", "(", "test", ")", ":", "address", "=", "test_address", "(", "test", ")", "if", "address", ":", "file", ",", "module", ",", "rest", "=", "address", "if", "module", ":", "if", "rest", ":", "try", ":", "return", "'%s:%s%s'", "%", ...
29.95
0.001618
def _format_obj(self, item=None): """ Determines the type of the object and maps it to the correct formatter """ # Order here matters, odd behavior with tuples if item is None: return getattr(self, 'number')(item) elif isinstance(item, self.str_): ...
[ "def", "_format_obj", "(", "self", ",", "item", "=", "None", ")", ":", "# Order here matters, odd behavior with tuples", "if", "item", "is", "None", ":", "return", "getattr", "(", "self", ",", "'number'", ")", "(", "item", ")", "elif", "isinstance", "(", "it...
36.358974
0.001374
def load(self): '''获取当前的离线任务列表''' def on_list_task(info, error=None): self.loading_spin.stop() self.loading_spin.hide() if not info: self.app.toast(_('Network error, info is empty')) if error or not info: logger.error('Cloud...
[ "def", "load", "(", "self", ")", ":", "def", "on_list_task", "(", "info", ",", "error", "=", "None", ")", ":", "self", ".", "loading_spin", ".", "stop", "(", ")", "self", ".", "loading_spin", ".", "hide", "(", ")", "if", "not", "info", ":", "self",...
35.756757
0.001472
def normalize(self, expr, operation): """ Return a normalized expression transformed to its normal form in the given AND or OR operation. The new expression arguments will satisfy these conditions: - operation(*args) == expr (here mathematical equality is meant) - the op...
[ "def", "normalize", "(", "self", ",", "expr", ",", "operation", ")", ":", "# ensure that the operation is not NOT", "assert", "operation", "in", "(", "self", ".", "AND", ",", "self", ".", "OR", ",", ")", "# Move NOT inwards.", "expr", "=", "expr", ".", "lite...
41.130435
0.002066
def spherical_to_vector(spherical): """ Convert a set of (n,2) spherical vectors to (n,3) vectors Parameters ----------- spherical : (n , 2) float Angles, in radians Returns ----------- vectors : (n, 3) float Unit vectors """ spherical = np.asanyarray(spherical, dt...
[ "def", "spherical_to_vector", "(", "spherical", ")", ":", "spherical", "=", "np", ".", "asanyarray", "(", "spherical", ",", "dtype", "=", "np", ".", "float64", ")", "if", "not", "is_shape", "(", "spherical", ",", "(", "-", "1", ",", "2", ")", ")", ":...
26.52
0.001456
def get_variable_values( schema: GraphQLSchema, var_def_nodes: List[VariableDefinitionNode], inputs: Dict[str, Any], ) -> CoercedVariableValues: """Get coerced variable values based on provided definitions. Prepares a dict of variable values of the correct type based on the provided variable de...
[ "def", "get_variable_values", "(", "schema", ":", "GraphQLSchema", ",", "var_def_nodes", ":", "List", "[", "VariableDefinitionNode", "]", ",", "inputs", ":", "Dict", "[", "str", ",", "Any", "]", ",", ")", "->", "CoercedVariableValues", ":", "errors", ":", "L...
45.791667
0.002078
def hitcount(requestContext, seriesList, intervalString, alignToInterval=False): """ Estimate hit counts from a list of time series. This function assumes the values in each time series represent hits per second. It calculates hits per some larger interval such as per day or per hou...
[ "def", "hitcount", "(", "requestContext", ",", "seriesList", ",", "intervalString", ",", "alignToInterval", "=", "False", ")", ":", "results", "=", "[", "]", "delta", "=", "parseTimeOffset", "(", "intervalString", ")", "interval", "=", "to_seconds", "(", "delt...
40.663366
0.000238
def run(coro, loop=None): """ Convenient shortcut alias to ``loop.run_until_complete``. Arguments: coro (coroutine): coroutine object to schedule. loop (asyncio.BaseEventLoop): optional event loop to use. Defaults to: ``asyncio.get_event_loop()``. Returns: mixed: re...
[ "def", "run", "(", "coro", ",", "loop", "=", "None", ")", ":", "loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "return", "loop", ".", "run_until_complete", "(", "coro", ")" ]
23.130435
0.001805
def mob_suite_targets(self, database_name='mob_suite'): """ Download MOB-suite databases :param database_name: name of current database """ logging.info('Download MOB-suite databases') # NOTE: This requires mob_suite >=1.4.9.1. Versions before that don't have the -d optio...
[ "def", "mob_suite_targets", "(", "self", ",", "database_name", "=", "'mob_suite'", ")", ":", "logging", ".", "info", "(", "'Download MOB-suite databases'", ")", "# NOTE: This requires mob_suite >=1.4.9.1. Versions before that don't have the -d option.", "cmd", "=", "'mob_init -...
48.777778
0.008949
def k8s_events_handle_job_statuses(self: 'celery_app.task', payload: Dict) -> None: """Project jobs statuses""" details = payload['details'] job_uuid = details['labels']['job_uuid'] job_name = details['labels']['job_name'] project_name = details['labels'].get('project_name') logger.debug('handli...
[ "def", "k8s_events_handle_job_statuses", "(", "self", ":", "'celery_app.task'", ",", "payload", ":", "Dict", ")", "->", "None", ":", "details", "=", "payload", "[", "'details'", "]", "job_uuid", "=", "details", "[", "'labels'", "]", "[", "'job_uuid'", "]", "...
36.066667
0.0018
def get_model(app_label, model_name): """ Fetches a Django model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry...
[ "def", "get_model", "(", "app_label", ",", "model_name", ")", ":", "try", ":", "from", "django", ".", "apps", "import", "apps", "from", "django", ".", "core", ".", "exceptions", "import", "AppRegistryNotReady", "except", "ImportError", ":", "# Django < 1.7", "...
42.380952
0.000549
def simBirth(self,which_agents): ''' Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and discrete states. Calls IndShockConsumerType.simBirth, then draws from initial Markov distribution. Parameters ---------- which_agents : np.ar...
[ "def", "simBirth", "(", "self", ",", "which_agents", ")", ":", "IndShockConsumerType", ".", "simBirth", "(", "self", ",", "which_agents", ")", "# Get initial assets and permanent income", "if", "not", "self", ".", "global_markov", ":", "#Markov state is not changed if i...
45.85
0.016026
def list_keys(hive, key=None, use_32bit_registry=False): ''' Enumerates the subkeys in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU ...
[ "def", "list_keys", "(", "hive", ",", "key", "=", "None", ",", "use_32bit_registry", "=", "False", ")", ":", "return", "__utils__", "[", "'reg.list_keys'", "]", "(", "hive", "=", "hive", ",", "key", "=", "key", ",", "use_32bit_registry", "=", "use_32bit_re...
30.542857
0.000907
def _digest_auth_stage2(self, _unused): """Do the second stage (<iq type='set'/>) of legacy "digest" authentication. [client only]""" iq=Iq(stanza_type="set") q=iq.new_query("jabber:iq:auth") q.newTextChild(None,"username",to_utf8(self.my_jid.node)) q.newTextChil...
[ "def", "_digest_auth_stage2", "(", "self", ",", "_unused", ")", ":", "iq", "=", "Iq", "(", "stanza_type", "=", "\"set\"", ")", "q", "=", "iq", ".", "new_query", "(", "\"jabber:iq:auth\"", ")", "q", ".", "newTextChild", "(", "None", ",", "\"username\"", "...
37.625
0.02107
def all_jobs(self): """ Similar to jobs, but uses the default manager to return archived experiments as well. """ from db.models.jobs import Job return Job.all.filter(project=self)
[ "def", "all_jobs", "(", "self", ")", ":", "from", "db", ".", "models", ".", "jobs", "import", "Job", "return", "Job", ".", "all", ".", "filter", "(", "project", "=", "self", ")" ]
27.75
0.008734
def ReadCompletedRequests(self, session_id, timestamp=None, limit=None): """Fetches all the requests with a status message queued for them.""" subject = session_id.Add("state") requests = {} status = {} for predicate, serialized, _ in self.ResolvePrefix( subject, [self.FLOW_REQUEST_PREFIX, ...
[ "def", "ReadCompletedRequests", "(", "self", ",", "session_id", ",", "timestamp", "=", "None", ",", "limit", "=", "None", ")", ":", "subject", "=", "session_id", ".", "Add", "(", "\"state\"", ")", "requests", "=", "{", "}", "status", "=", "{", "}", "fo...
37.181818
0.008343
def dagcircuit_to_tk(dag:DAGCircuit, _BOX_UNKNOWN:bool=BOX_UNKNOWN, _DROP_CONDS:bool=DROP_CONDS) -> Circuit : """Converts a :py:class:`qiskit.DAGCircuit` into a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit`. Note that not all Qiskit operations are currently supported by pytket. Classical registers are sup...
[ "def", "dagcircuit_to_tk", "(", "dag", ":", "DAGCircuit", ",", "_BOX_UNKNOWN", ":", "bool", "=", "BOX_UNKNOWN", ",", "_DROP_CONDS", ":", "bool", "=", "DROP_CONDS", ")", "->", "Circuit", ":", "qs", "=", "dag", ".", "get_qubits", "(", ")", "qnames", "=", "...
44.204545
0.02163
def _find_relevant_nodes(query_nodes, relevance_network, relevance_node_lim): """Return a list of nodes that are relevant for the query. Parameters ---------- query_nodes : list[str] A list of node names to query for. relevance_network : str The UUID of the NDEx network to query rel...
[ "def", "_find_relevant_nodes", "(", "query_nodes", ",", "relevance_network", ",", "relevance_node_lim", ")", ":", "all_nodes", "=", "relevance_client", ".", "get_relevant_nodes", "(", "relevance_network", ",", "query_nodes", ")", "nodes", "=", "[", "n", "[", "0", ...
34.285714
0.001351
def bg_color_native_ansi(kernel32, stderr, stdout): """Get background color and if console supports ANSI colors natively for both streams. :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. :param int stderr: stderr handle. :param int stdout: stdout handle. :return: Background color...
[ "def", "bg_color_native_ansi", "(", "kernel32", ",", "stderr", ",", "stdout", ")", ":", "try", ":", "if", "stderr", "==", "INVALID_HANDLE_VALUE", ":", "raise", "OSError", "bg_color", ",", "native_ansi", "=", "get_console_info", "(", "kernel32", ",", "stderr", ...
37.272727
0.002378
def submit(self): """ Posts the form's data and returns the resulting Page Returns Page - The resulting page """ u = urlparse(self.url) if not self.action: self.action = self.url elif self.action == u.path: self.acti...
[ "def", "submit", "(", "self", ")", ":", "u", "=", "urlparse", "(", "self", ".", "url", ")", "if", "not", "self", ".", "action", ":", "self", ".", "action", "=", "self", ".", "url", "elif", "self", ".", "action", "==", "u", ".", "path", ":", "se...
34.772727
0.008906
def inspect_work_unit(self, work_spec_name, work_unit_key): '''Get the data for some work unit. Returns the data for that work unit, or `None` if it really can't be found. :param str work_spec_name: name of the work spec :param str work_unit_key: name of the work unit :...
[ "def", "inspect_work_unit", "(", "self", ",", "work_spec_name", ",", "work_unit_key", ")", ":", "with", "self", ".", "registry", ".", "lock", "(", "identifier", "=", "self", ".", "worker_id", ")", "as", "session", ":", "work_unit_data", "=", "session", ".", ...
45
0.001892
def teardown(self): '''Teardown trust domain by removing trusted devices.''' for device in self.devices: self._remove_trustee(device) self._populate_domain() self.domain = {}
[ "def", "teardown", "(", "self", ")", ":", "for", "device", "in", "self", ".", "devices", ":", "self", ".", "_remove_trustee", "(", "device", ")", "self", ".", "_populate_domain", "(", ")", "self", ".", "domain", "=", "{", "}" ]
31
0.008969
def item_details(item_id, lang="en"): """This resource returns a details about a single item. :param item_id: The item to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties de...
[ "def", "item_details", "(", "item_id", ",", "lang", "=", "\"en\"", ")", ":", "params", "=", "{", "\"item_id\"", ":", "item_id", ",", "\"lang\"", ":", "lang", "}", "cache_name", "=", "\"item_details.%(item_id)s.%(lang)s.json\"", "%", "params", "return", "get_cach...
30.580645
0.000511
def from_array(filename, data, iline=189, xline=193, format=SegySampleFormat.IBM_FLOAT_4_BYTE, dt=4000, delrt=0): """ Create a new SEGY file from an n-dimentional array. Create a structured ...
[ "def", "from_array", "(", "filename", ",", "data", ",", "iline", "=", "189", ",", "xline", "=", "193", ",", "format", "=", "SegySampleFormat", ".", "IBM_FLOAT_4_BYTE", ",", "dt", "=", "4000", ",", "delrt", "=", "0", ")", ":", "dt", "=", "int", "(", ...
35.509434
0.008012
def _del_db(self, key, branch, turn, tick): """Delete a key from the database (not the cache).""" self._set_db(key, branch, turn, tick, None)
[ "def", "_del_db", "(", "self", ",", "key", ",", "branch", ",", "turn", ",", "tick", ")", ":", "self", ".", "_set_db", "(", "key", ",", "branch", ",", "turn", ",", "tick", ",", "None", ")" ]
51.666667
0.012739
def get_nn_classifier(X, y): """ Train a neural network classifier. Parameters ---------- X : numpy array A list of feature vectors y : numpy array A list of labels Returns ------- Theano expression : The trained neural network """ assert type(X) is ...
[ "def", "get_nn_classifier", "(", "X", ",", "y", ")", ":", "assert", "type", "(", "X", ")", "is", "numpy", ".", "ndarray", "assert", "type", "(", "y", ")", "is", "numpy", ".", "ndarray", "assert", "len", "(", "X", ")", "==", "len", "(", "y", ")", ...
27.774194
0.001122
def sqrt(inputArray, scale_min=None, scale_max=None): """Performs sqrt scaling of the input numpy array. @type inputArray: numpy array @param inputArray: image data array @type scale_min: float @param scale_min: minimum data value @type scale_max: float @param scale_max: maximum data value ...
[ "def", "sqrt", "(", "inputArray", ",", "scale_min", "=", "None", ",", "scale_max", "=", "None", ")", ":", "imageData", "=", "np", ".", "array", "(", "inputArray", ",", "copy", "=", "True", ")", "if", "scale_min", "is", "None", ":", "scale_min", "=", ...
28.034483
0.001189
def one_item(self, item, detach:bool=False, denorm:bool=False, cpu:bool=False): "Get `item` into a batch. Optionally `detach` and `denorm`." ds = self.single_ds with ds.set_item(item): return self.one_batch(ds_type=DatasetType.Single, detach=detach, denorm=denorm, cpu=cpu)
[ "def", "one_item", "(", "self", ",", "item", ",", "detach", ":", "bool", "=", "False", ",", "denorm", ":", "bool", "=", "False", ",", "cpu", ":", "bool", "=", "False", ")", ":", "ds", "=", "self", ".", "single_ds", "with", "ds", ".", "set_item", ...
61
0.038835
def backward(self, grad_output): r"""Apply the adjoint of the derivative at ``grad_output``. This method is usually not called explicitly but as a part of the ``cost.backward()`` pass of a backpropagation step. Parameters ---------- grad_output : `torch.tensor._TensorBa...
[ "def", "backward", "(", "self", ",", "grad_output", ")", ":", "# TODO: implement directly for GPU data", "if", "not", "self", ".", "operator", ".", "is_linear", ":", "input_arr", "=", "self", ".", "saved_variables", "[", "0", "]", ".", "data", ".", "cpu", "(...
35.165354
0.000436
def sound_pressure(self): """ A measurement of the measured sound pressure level, as a percent. Uses a flat weighting. """ self._ensure_mode(self.MODE_DB) return self.value(0) * self._scale('DB')
[ "def", "sound_pressure", "(", "self", ")", ":", "self", ".", "_ensure_mode", "(", "self", ".", "MODE_DB", ")", "return", "self", ".", "value", "(", "0", ")", "*", "self", ".", "_scale", "(", "'DB'", ")" ]
33.857143
0.00823
def marshal_json( obj, types=JSON_TYPES, fields=None, ): """ Recursively marshal a Python object to a JSON-compatible dict that can be passed to json.{dump,dumps}, a web client, or a web server, etc... Args: obj: object, It's members can be nested Python o...
[ "def", "marshal_json", "(", "obj", ",", "types", "=", "JSON_TYPES", ",", "fields", "=", "None", ",", ")", ":", "return", "marshal_dict", "(", "obj", ",", "types", ",", "fields", "=", "fields", ",", ")" ]
27.869565
0.001508
def server_static(filepath): """Handler for serving static files.""" mimetype = "image/svg+xml" if filepath.endswith(".svg") else "auto" return bottle.static_file(filepath, root=conf.StaticPath, mimetype=mimetype)
[ "def", "server_static", "(", "filepath", ")", ":", "mimetype", "=", "\"image/svg+xml\"", "if", "filepath", ".", "endswith", "(", "\".svg\"", ")", "else", "\"auto\"", "return", "bottle", ".", "static_file", "(", "filepath", ",", "root", "=", "conf", ".", "Sta...
56.25
0.008772
def _format_multicolumn(self, row, ilevels): r""" Combine columns belonging to a group to a single multicolumn entry according to self.multicolumn_format e.g.: a & & & b & c & will become \multicolumn{3}{l}{a} & b & \multicolumn{2}{l}{c} """ row...
[ "def", "_format_multicolumn", "(", "self", ",", "row", ",", "ilevels", ")", ":", "row2", "=", "list", "(", "row", "[", ":", "ilevels", "]", ")", "ncol", "=", "1", "coltext", "=", "''", "def", "append_col", "(", ")", ":", "# write multicolumn if needed", ...
31.783784
0.00165
def compute_equiv_class(atom): """(atom)->Computes a unique integer for an atom""" try: equiv_class = atom.number + \ 1000*(atom.charge+10) + \ 100000*(atom.hcount) + \ 1000000*(atom.weight) except TypeError: raise ValueEr...
[ "def", "compute_equiv_class", "(", "atom", ")", ":", "try", ":", "equiv_class", "=", "atom", ".", "number", "+", "1000", "*", "(", "atom", ".", "charge", "+", "10", ")", "+", "100000", "*", "(", "atom", ".", "hcount", ")", "+", "1000000", "*", "(",...
42.583333
0.011494
def setBaseLocale(self, locale): """ Sets the base locale that is used with in this widget. All displayed information will be translated to this locale. :param locale | <str> """ locale = str(locale) if self._baseLocale == locale: ...
[ "def", "setBaseLocale", "(", "self", ",", "locale", ")", ":", "locale", "=", "str", "(", "locale", ")", "if", "self", ".", "_baseLocale", "==", "locale", ":", "return", "try", ":", "babel", ".", "Locale", ".", "parse", "(", "locale", ")", "except", "...
29.45
0.008224
def demo(host, port): """Basic demo of the monitoring capabilities.""" # logging.basicConfig(level=logging.DEBUG) loop = asyncio.get_event_loop() stl = AsyncSatel(host, port, loop, [1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15, 16, 17, 18, 19, ...
[ "def", "demo", "(", "host", ",", "port", ")", ":", "# logging.basicConfig(level=logging.DEBUG)", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "stl", "=", "AsyncSatel", "(", "host", ",", "port", ",", "loop", ",", "[", "1", ",", "2", ",", "3", ...
31.619048
0.001462
def is_valid_url(url): """ Check if a given string is in the correct URL format or not :param str url: :return: True or False """ regex = re.compile(r'^(?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r'localho...
[ "def", "is_valid_url", "(", "url", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'^(?:http|ftp)s?://'", "r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'", "r'localhost|'", "r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'", "r'(?::\\d+)?'",...
31.111111
0.010399
def ReadTag(buffer, pos): """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple. We return the raw bytes of the tag rather than decoding them. The raw bytes can then be used to look up the proper decoder. This effectively allows us to trade some work that would be done in pure-python (decodi...
[ "def", "ReadTag", "(", "buffer", ",", "pos", ")", ":", "start", "=", "pos", "while", "six", ".", "indexbytes", "(", "buffer", ",", "pos", ")", "&", "0x80", ":", "pos", "+=", "1", "pos", "+=", "1", "return", "(", "buffer", "[", "start", ":", "pos"...
38.9375
0.010972
def get_acf(x, axis=0, fast=False): """ Estimate the autocorrelation function of a time series using the FFT. :param x: The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. :param axi...
[ "def", "get_acf", "(", "x", ",", "axis", "=", "0", ",", "fast", "=", "False", ")", ":", "x", "=", "np", ".", "atleast_1d", "(", "x", ")", "m", "=", "[", "slice", "(", "None", ")", ",", "]", "*", "len", "(", "x", ".", "shape", ")", "# For co...
31.714286
0.000874
def run_gdb_command(message): """ Endpoint for a websocket route. Runs a gdb command. Responds only if an error occurs when trying to write the command to gdb """ controller = _state.get_controller_from_client_id(request.sid) if controller is not None: try: # the comm...
[ "def", "run_gdb_command", "(", "message", ")", ":", "controller", "=", "_state", ".", "get_controller_from_client_id", "(", "request", ".", "sid", ")", "if", "controller", "is", "not", "None", ":", "try", ":", "# the command (string) or commands (list) to run", "cmd...
33.8
0.001439
def areaBetween(requestContext, *seriesLists): """ Draws the vertical area in between the two series in seriesList. Useful for visualizing a range such as the minimum and maximum latency for a service. areaBetween expects **exactly one argument** that results in exactly two series (see example belo...
[ "def", "areaBetween", "(", "requestContext", ",", "*", "seriesLists", ")", ":", "if", "len", "(", "seriesLists", ")", "==", "1", ":", "[", "seriesLists", "]", "=", "seriesLists", "assert", "len", "(", "seriesLists", ")", "==", "2", ",", "(", "\"areaBetwe...
38
0.000641
def commit(self): """:return: Commit object the tag ref points to :raise ValueError: if the tag points to a tree or blob""" obj = self.object while obj.type != 'commit': if obj.type == "tag": # it is a tag object which carries the commit as an object ...
[ "def", "commit", "(", "self", ")", ":", "obj", "=", "self", ".", "object", "while", "obj", ".", "type", "!=", "'commit'", ":", "if", "obj", ".", "type", "==", "\"tag\"", ":", "# it is a tag object which carries the commit as an object - we can point to anything", ...
46.461538
0.00974
def extract_committees(bill): """ Returns committee associations from a bill. """ bill_id = bill.get('bill_id', None) logger.debug("Extracting Committees for {0}".format(bill_id)) committees = bill.get('committees', None) committee_map = [] for c in committees: logger.debug("Pr...
[ "def", "extract_committees", "(", "bill", ")", ":", "bill_id", "=", "bill", ".", "get", "(", "'bill_id'", ",", "None", ")", "logger", ".", "debug", "(", "\"Extracting Committees for {0}\"", ".", "format", "(", "bill_id", ")", ")", "committees", "=", "bill", ...
34.965517
0.00096
def total_variation(arr): ''' If arr is a 2D array (N X M), assumes that arr is a spectrogram with time along axis=0. Calculates the 1D total variation in time for each frequency and returns an array of size M. If arr is a 1D array, calculates total variation and returns a scalar. Sum ( Abs(arr_i+1,j - ...
[ "def", "total_variation", "(", "arr", ")", ":", "return", "np", ".", "sum", "(", "np", ".", "abs", "(", "np", ".", "diff", "(", "arr", ",", "axis", "=", "0", ")", ")", ",", "axis", "=", "0", ")" ]
32.866667
0.011834
def _display_data(self, index): """Return a data element""" return to_qvariant(self._data[index.row()][index.column()])
[ "def", "_display_data", "(", "self", ",", "index", ")", ":", "return", "to_qvariant", "(", "self", ".", "_data", "[", "index", ".", "row", "(", ")", "]", "[", "index", ".", "column", "(", ")", "]", ")" ]
45
0.014599
def hash(self): ''' :rtype: int :return: hash of the field ''' hashed = super(Dynamic, self).hash() return khash(hashed, self._key, self._length)
[ "def", "hash", "(", "self", ")", ":", "hashed", "=", "super", "(", "Dynamic", ",", "self", ")", ".", "hash", "(", ")", "return", "khash", "(", "hashed", ",", "self", ".", "_key", ",", "self", ".", "_length", ")" ]
26.714286
0.010363
def Statistics(season=None, clobber=False, model='nPLD', injection=False, compare_to='kepler', plot=True, cadence='lc', planets=False, **kwargs): ''' Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all long cadence light curves in a given ...
[ "def", "Statistics", "(", "season", "=", "None", ",", "clobber", "=", "False", ",", "model", "=", "'nPLD'", ",", "injection", "=", "False", ",", "compare_to", "=", "'kepler'", ",", "plot", "=", "True", ",", "cadence", "=", "'lc'", ",", "planets", "=", ...
46.883077
0.000257
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\xa0', ' ') string = string.replace('selten: ', '') string = string.replace('Alte Rechtschreibung', '') string = string.strip() return string
[ "def", "_normalize", "(", "self", ",", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "u'\\xb7'", ",", "''", ")", "string", "=", "string", ".", "replace", "(", "u'\\xa0'", ",", "' '", ")", "string", "=", "string", ".", "replace", "...
30.777778
0.031579
def generate_fva_warmup(self): """Generate the warmup points for the sampler. Generates warmup points by setting each flux as the sole objective and minimizing/maximizing it. Also caches the projection of the warmup points into the nullspace for non-homogeneous problems (only if...
[ "def", "generate_fva_warmup", "(", "self", ")", ":", "self", ".", "n_warmup", "=", "0", "reactions", "=", "self", ".", "model", ".", "reactions", "self", ".", "warmup", "=", "np", ".", "zeros", "(", "(", "2", "*", "len", "(", "reactions", ")", ",", ...
40.15942
0.000704
def bind_instancemethod(m, dispatcher, *accept_args, **accept_kwargs): """ Bind a function to a dispatcher. Takes accept_args, and accept_kwargs and creates and ArgSpec instance, adding that to the MNDFunction which annotates the function :param f: function to wrap :param accept_args: :p...
[ "def", "bind_instancemethod", "(", "m", ",", "dispatcher", ",", "*", "accept_args", ",", "*", "*", "accept_kwargs", ")", ":", "argspec", "=", "ArgSpec", "(", "None", ",", "*", "accept_args", ",", "*", "*", "accept_kwargs", ")", "mnd", "=", "MNDMethod", "...
28.941176
0.001969
def precision(self, precision): """ For queries that should run faster, you may specify a lower precision, and for those that need to be more precise, a higher precision: ```python # faster queries query.range('2014-01-01', '2014-01-31', precision=0) query.range(...
[ "def", "precision", "(", "self", ",", "precision", ")", ":", "if", "isinstance", "(", "precision", ",", "int", ")", ":", "precision", "=", "self", ".", "PRECISION_LEVELS", "[", "precision", "]", "if", "precision", "not", "in", "self", ".", "PRECISION_LEVEL...
39.5
0.001647
def reset(self): """ Command the PCAN driver to reset the bus after an error. """ status = self.m_objPCANBasic.Reset(self.m_PcanHandle) return status == PCAN_ERROR_OK
[ "def", "reset", "(", "self", ")", ":", "status", "=", "self", ".", "m_objPCANBasic", ".", "Reset", "(", "self", ".", "m_PcanHandle", ")", "return", "status", "==", "PCAN_ERROR_OK" ]
33.5
0.009709
def check_m(pm): ''' Shared helper function for all :ref:`tools` to check if the passed m-function is indeed :func:`photon.Photon.m` :params pm: Suspected m-function :returns: Now to be proven correct m-function, tears down whole application otherwise. ''' if not an...
[ "def", "check_m", "(", "pm", ")", ":", "if", "not", "any", "(", "[", "callable", "(", "pm", ")", ",", "pm", ".", "__name__", "!=", "Photon", ".", "m", ".", "__name__", ",", "pm", ".", "__doc__", "!=", "Photon", ".", "m", ".", "__doc__", "]", ")...
24.043478
0.001739
def get_maps(A): """Get mappings from the square array A to the flat vector of parameters alpha. Helper function for PCCA+ optimization. Parameters ---------- A : ndarray The transformation matrix A. Returns ------- flat_map : ndarray Mapping from flat indices (k) ...
[ "def", "get_maps", "(", "A", ")", ":", "N", "=", "A", ".", "shape", "[", "0", "]", "flat_map", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "N", ")", ":", "for", "j", "in", "range", "(", "1", ",", "N", ")", ":", "flat_map", "....
21.735294
0.001295
def _fillInOnTimes(vector, durations): """ Helper function used by averageOnTimePerTimestep. 'durations' is a vector which must be the same len as vector. For each "on" in vector, it fills in the corresponding element of duration with the duration of that "on" signal up until that time Parameters: ------...
[ "def", "_fillInOnTimes", "(", "vector", ",", "durations", ")", ":", "# Find where the nonzeros are", "nonzeros", "=", "numpy", ".", "array", "(", "vector", ")", ".", "nonzero", "(", ")", "[", "0", "]", "# Nothing to do if vector is empty", "if", "len", "(", "n...
27.765957
0.017765
def get_int(value, default, test_fn=None): """Convert value to integer. :param value: Integer value. :param default: Default value on failed conversion. :param test_fn: Constraint function. Use default if returns ``False``. :return: Integer value. :rtype: ``int`` """ try: conve...
[ "def", "get_int", "(", "value", ",", "default", ",", "test_fn", "=", "None", ")", ":", "try", ":", "converted", "=", "int", "(", "value", ")", "except", "ValueError", ":", "return", "default", "test_fn", "=", "test_fn", "if", "test_fn", "else", "lambda",...
29.875
0.002028
def set_max_lease(self, max_lease): """ Set the maximum lease period in months. :param max_lease: int """ self._query_params += str(QueryParam.MAX_LEASE) + str(max_lease)
[ "def", "set_max_lease", "(", "self", ",", "max_lease", ")", ":", "self", ".", "_query_params", "+=", "str", "(", "QueryParam", ".", "MAX_LEASE", ")", "+", "str", "(", "max_lease", ")" ]
34.166667
0.009524
def reset(self, reset_mutated=True): ''' Reset the state of the container and its internal fields :param reset_mutated: should reset the mutated field too (default: True) ''' super(ForEach, self).reset() if reset_mutated: self._mutated_field.reset()
[ "def", "reset", "(", "self", ",", "reset_mutated", "=", "True", ")", ":", "super", "(", "ForEach", ",", "self", ")", ".", "reset", "(", ")", "if", "reset_mutated", ":", "self", ".", "_mutated_field", ".", "reset", "(", ")" ]
33.555556
0.009677
def build_wheel_graph(num_nodes): """Builds a wheel graph with the specified number of nodes. Ref: http://mathworld.wolfram.com/WheelGraph.html""" # The easiest way to build a wheel graph is to build # C_n-1 and then add a hub node and spoke edges graph = build_cycle_graph(num_nodes - 1) cyc...
[ "def", "build_wheel_graph", "(", "num_nodes", ")", ":", "# The easiest way to build a wheel graph is to build", "# C_n-1 and then add a hub node and spoke edges", "graph", "=", "build_cycle_graph", "(", "num_nodes", "-", "1", ")", "cycle_graph_vertices", "=", "graph", ".", "g...
34.928571
0.001992
def _insert_html_configs(c, *, project_name, short_project_name): """Insert HTML theme configurations. """ # Use the lsst-sphinx-bootstrap-theme c['templates_path'] = [ '_templates', lsst_sphinx_bootstrap_theme.get_html_templates_path()] c['html_theme'] = 'lsst_sphinx_bootstrap_theme...
[ "def", "_insert_html_configs", "(", "c", ",", "*", ",", "project_name", ",", "short_project_name", ")", ":", "# Use the lsst-sphinx-bootstrap-theme", "c", "[", "'templates_path'", "]", "=", "[", "'_templates'", ",", "lsst_sphinx_bootstrap_theme", ".", "get_html_template...
37.958763
0.000265
def qos(self, prefetch_size, prefetch_count, apply_global=False): """Request specific Quality of Service.""" self.channel.basic_qos(prefetch_size, prefetch_count, apply_global)
[ "def", "qos", "(", "self", ",", "prefetch_size", ",", "prefetch_count", ",", "apply_global", "=", "False", ")", ":", "self", ".", "channel", ".", "basic_qos", "(", "prefetch_size", ",", "prefetch_count", ",", "apply_global", ")" ]
55.25
0.013393
def prepare_dispatches(): """Automatically creates dispatches for messages without them. :return: list of Dispatch :rtype: list """ dispatches = [] target_messages = Message.get_without_dispatches() cache = {} for message_model in target_messages: if message_model.cls not in ...
[ "def", "prepare_dispatches", "(", ")", ":", "dispatches", "=", "[", "]", "target_messages", "=", "Message", ".", "get_without_dispatches", "(", ")", "cache", "=", "{", "}", "for", "message_model", "in", "target_messages", ":", "if", "message_model", ".", "cls"...
29.304348
0.001437
def reduce(func): """Wrap a reduce function to Pipe object. Reduce function is a function with at least two arguments. It works like built-in reduce function. It takes first argument for accumulated result, second argument for the new data to process. A keyword-based argument named 'init...
[ "def", "reduce", "(", "func", ")", ":", "def", "wrapper", "(", "prev", ",", "*", "argv", ",", "*", "*", "kw", ")", ":", "accum_value", "=", "None", "if", "'init'", "not", "in", "kw", "else", "kw", ".", "pop", "(", "'init'", ")", "if", "prev", "...
48.653846
0.002326
def writeDrizKeywords(hdr,imgnum,drizdict): """ Write basic drizzle-related keywords out to image header as a record of the processing performed to create the image The dictionary 'drizdict' will contain the keywords and values to be written out to the header. """ _keyprefix = 'D%03...
[ "def", "writeDrizKeywords", "(", "hdr", ",", "imgnum", ",", "drizdict", ")", ":", "_keyprefix", "=", "'D%03d'", "%", "imgnum", "for", "key", "in", "drizdict", ":", "val", "=", "drizdict", "[", "key", "]", "[", "'value'", "]", "if", "val", "is", "None",...
37.133333
0.010508
def plot(name=None, fig=None, abscissa=1, iteridx=None, plot_mean=False, foffset=1e-19, x_opt=None, fontsize=9): """ plot data from files written by a `CMADataLogger`, the call ``cma.plot(name, **argsdict)`` is a shortcut for ``cma.CMADataLogger(name).plot(**argsdict)`` Arguments ...
[ "def", "plot", "(", "name", "=", "None", ",", "fig", "=", "None", ",", "abscissa", "=", "1", ",", "iteridx", "=", "None", ",", "plot_mean", "=", "False", ",", "foffset", "=", "1e-19", ",", "x_opt", "=", "None", ",", "fontsize", "=", "9", ")", ":"...
29
0.000654
def flake8_color(score): """Return flake8 badge color. Parameters ---------- score : float A flake8 score Returns ------- str Badge color """ # These are the score cutoffs for each color above. # I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orang...
[ "def", "flake8_color", "(", "score", ")", ":", "# These are the score cutoffs for each color above.", "# I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange", "score_cutoffs", "=", "(", "0", ",", "20", ",", "50", ",", "100", ",", "200", ")", "for", "i", "...
23.272727
0.001876
def samReferencesToStr(filenameOrSamfile, indent=0): """ List SAM/BAM file reference names and lengths. @param filenameOrSamfile: Either a C{str} SAM/BAM file name or an instance of C{pysam.AlignmentFile}. @param indent: An C{int} number of spaces to indent each line. @return: A C{str} desc...
[ "def", "samReferencesToStr", "(", "filenameOrSamfile", ",", "indent", "=", "0", ")", ":", "indent", "=", "' '", "*", "indent", "def", "_references", "(", "sam", ")", ":", "result", "=", "[", "]", "for", "i", "in", "range", "(", "sam", ".", "nreferences...
34.782609
0.001217
def draw_cell(self, row, col, val): """ draw a cell as position row, col containing val """ if val == 'T': self.paint_target(row,col) elif val == '#': self.paint_block(row,col) elif val == 'X': self.paint_hill(row,col) elif val ...
[ "def", "draw_cell", "(", "self", ",", "row", ",", "col", ",", "val", ")", ":", "if", "val", "==", "'T'", ":", "self", ".", "paint_target", "(", "row", ",", "col", ")", "elif", "val", "==", "'#'", ":", "self", ".", "paint_block", "(", "row", ",", ...
33.1875
0.029304
def setAttribute(values, value): """ Takes the values of an attribute value list and attempts to append attributes of the proper type, inferred from their Python type. """ if isinstance(value, int): values.add().int32_value = value elif isinstance(value, float): values.add().doub...
[ "def", "setAttribute", "(", "values", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "values", ".", "add", "(", ")", ".", "int32_value", "=", "value", "elif", "isinstance", "(", "value", ",", "float", ")", ":", "value...
36.083333
0.001125
def check_AP_raw(abf,n=10): """X""" timePoints=get_AP_timepoints(abf)[:n] #first 10 if len(timePoints)==0: return swhlab.plot.new(abf,True,title="AP shape (n=%d)"%n,xlabel="ms") Ys=abf.get_data_around(timePoints,padding=.2) Xs=(np.arange(len(Ys[0]))-len(Ys[0])/2)*1000/abf.rate for i ...
[ "def", "check_AP_raw", "(", "abf", ",", "n", "=", "10", ")", ":", "timePoints", "=", "get_AP_timepoints", "(", "abf", ")", "[", ":", "n", "]", "#first 10", "if", "len", "(", "timePoints", ")", "==", "0", ":", "return", "swhlab", ".", "plot", ".", "...
41.875
0.043796
def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128): """Transports source samples Xs onto target ones Xt Parameters ---------- Xs : array-like, shape (n_source_samples, n_features) The training input samples. ys : array-like, shape (n_source_sampl...
[ "def", "transform", "(", "self", ",", "Xs", "=", "None", ",", "ys", "=", "None", ",", "Xt", "=", "None", ",", "yt", "=", "None", ",", "batch_size", "=", "128", ")", ":", "# check the necessary inputs parameters are here", "if", "check_params", "(", "Xs", ...
35.985075
0.000807
def extract_relationtypes(urml_xml_tree): """ extracts the allowed RST relation names and relation types from an URML XML file. Parameters ---------- urml_xml_tree : lxml.etree._ElementTree lxml ElementTree representation of an URML XML file Returns ------- relations : dict...
[ "def", "extract_relationtypes", "(", "urml_xml_tree", ")", ":", "return", "{", "rel", ".", "attrib", "[", "'name'", "]", ":", "rel", ".", "attrib", "[", "'type'", "]", "for", "rel", "in", "urml_xml_tree", ".", "iterfind", "(", "'//header/reltypes/rel'", ")",...
31.25
0.001553
def recharge(self, param, must=[APIKEY, MOBILE, SN]): '''充值流量 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(仅支持大陆号码) 15205201314 sn String 是 流量包的唯一ID 点击查看 1008601 callback_url String 否 本条流量充值的状态报告推送地址 http://your...
[ "def", "recharge", "(", "self", ",", "param", ",", "must", "=", "[", "APIKEY", ",", "MOBILE", ",", "SN", "]", ")", ":", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ":", "ret...
38.666667
0.008413
def run(system, outfile='', name='', doc_string='', group='', data={}, descr={}, units={}, params=[], fnamex=[], fnamey=[], mandatory=[], zeros=[], powers=[], currents=[], voltages=[], z=[], ...
[ "def", "run", "(", "system", ",", "outfile", "=", "''", ",", "name", "=", "''", ",", "doc_string", "=", "''", ",", "group", "=", "''", ",", "data", "=", "{", "}", ",", "descr", "=", "{", "}", ",", "units", "=", "{", "}", ",", "params", "=", ...
33.0409
0.00024
def add_gauge(self, gauge): """Add `gauge` to the registry. Raises a `ValueError` if another gauge with the same name already exists in the registry. :type gauge: class:`LongGauge`, class:`DoubleGauge`, :class:`opencensus.metrics.export.cumulative.LongCumulative`, ...
[ "def", "add_gauge", "(", "self", ",", "gauge", ")", ":", "if", "gauge", "is", "None", ":", "raise", "ValueError", "name", "=", "gauge", ".", "descriptor", ".", "name", "with", "self", ".", "_gauges_lock", ":", "if", "name", "in", "self", ".", "gauges",...
42.166667
0.001932
def get_data(self, datatype, data): """ Look for an IP address or an email address in the spammer database. :param datatype: Which type of data is to be looked up. Allowed values are 'ip' or 'mail'. :param data: The value to be looked up through the API. :type d...
[ "def", "get_data", "(", "self", ",", "datatype", ",", "data", ")", ":", "result", "=", "{", "}", "params", "=", "StopforumspamClient", ".", "_set_payload", "(", "datatype", ",", "data", ")", "response", "=", "self", ".", "client", ".", "get", "(", "'ht...
38.291667
0.002123
def run(self, dag): """ Run the pass on the DAG, and write the discovered commutation relations into the property_set. """ # Initiate the commutation set self.property_set['commutation_set'] = defaultdict(list) # Build a dictionary to keep track of the gates on e...
[ "def", "run", "(", "self", ",", "dag", ")", ":", "# Initiate the commutation set", "self", ".", "property_set", "[", "'commutation_set'", "]", "=", "defaultdict", "(", "list", ")", "# Build a dictionary to keep track of the gates on each qubit", "for", "wire", "in", "...
40.282051
0.002486
def export(self, timestamp=None, info={}): """ Export the archive, directory or file. """ tval = tuple(time.localtime()) if timestamp is None else timestamp tstamp = time.strftime(self.timestamp_format, tval) info = dict(info, timestamp=tstamp) export_name = self...
[ "def", "export", "(", "self", ",", "timestamp", "=", "None", ",", "info", "=", "{", "}", ")", ":", "tval", "=", "tuple", "(", "time", ".", "localtime", "(", ")", ")", "if", "timestamp", "is", "None", "else", "timestamp", "tstamp", "=", "time", ".",...
44.869565
0.001898
def load_data(filespec, idx=None, logger=None, **kwargs): """Load data from a file. This call is used to load a data item from a filespec (path or URL) Parameters ---------- filespec : str The path of the file to load (can be a URL). idx : int or string (optional) The index or...
[ "def", "load_data", "(", "filespec", ",", "idx", "=", "None", ",", "logger", "=", "None", ",", "*", "*", "kwargs", ")", ":", "global", "loader_registry", "info", "=", "iohelper", ".", "get_fileinfo", "(", "filespec", ")", "filepath", "=", "info", ".", ...
28.526316
0.000595
def _append_slash_if_dir_path(self, relpath): """For a dir path return a path that has a trailing slash.""" if self._isdir_raw(relpath): return self._append_trailing_slash(relpath) return relpath
[ "def", "_append_slash_if_dir_path", "(", "self", ",", "relpath", ")", ":", "if", "self", ".", "_isdir_raw", "(", "relpath", ")", ":", "return", "self", ".", "_append_trailing_slash", "(", "relpath", ")", "return", "relpath" ]
34.833333
0.009346
def a_not_committed(ctx): """Provide the message that current software is not committed and reload is not possible.""" ctx.ctrl.sendline('n') ctx.msg = "Some active software packages are not yet committed. Reload may cause software rollback." ctx.device.chain.connection.emit_message(ctx.msg, log_level=l...
[ "def", "a_not_committed", "(", "ctx", ")", ":", "ctx", ".", "ctrl", ".", "sendline", "(", "'n'", ")", "ctx", ".", "msg", "=", "\"Some active software packages are not yet committed. Reload may cause software rollback.\"", "ctx", ".", "device", ".", "chain", ".", "co...
52.285714
0.008065
def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average cpu hard-coded to cpu0 (i.e. only a single CPU) """ environment = {} cpu_cmd = 'show proc cpu' mem_cmd = 'show memory s...
[ "def", "get_environment", "(", "self", ")", ":", "environment", "=", "{", "}", "cpu_cmd", "=", "'show proc cpu'", "mem_cmd", "=", "'show memory statistics'", "temp_cmd", "=", "'show env temperature status'", "output", "=", "self", ".", "_send_command", "(", "cpu_cmd...
45.467742
0.002083
def _add_new_items(self, config, seen): '''Add new (unseen) items to the config.''' for (key, value) in self.items(): if key not in seen: self._set_value(config, key, value)
[ "def", "_add_new_items", "(", "self", ",", "config", ",", "seen", ")", ":", "for", "(", "key", ",", "value", ")", "in", "self", ".", "items", "(", ")", ":", "if", "key", "not", "in", "seen", ":", "self", ".", "_set_value", "(", "config", ",", "ke...
42.6
0.009217
def connect_tcp(self, address, port): """Connect to tcp/ip `address`:`port`. Delegated to `_connect_tcp`.""" info('Connecting to TCP address: %s:%d', address, port) self._connect_tcp(address, port)
[ "def", "connect_tcp", "(", "self", ",", "address", ",", "port", ")", ":", "info", "(", "'Connecting to TCP address: %s:%d'", ",", "address", ",", "port", ")", "self", ".", "_connect_tcp", "(", "address", ",", "port", ")" ]
54.5
0.00905
def should_reduce_configs(self, iteration, bracket_iteration): """Return a boolean to indicate if we need to reschedule another bracket iteration.""" n_configs_to_keep = self.get_n_config_to_keep_for_iteration( iteration=iteration, bracket_iteration=bracket_iteration) return n_config...
[ "def", "should_reduce_configs", "(", "self", ",", "iteration", ",", "bracket_iteration", ")", ":", "n_configs_to_keep", "=", "self", ".", "get_n_config_to_keep_for_iteration", "(", "iteration", "=", "iteration", ",", "bracket_iteration", "=", "bracket_iteration", ")", ...
65.8
0.009009
def get_header(self, service_id, version_number, name): """Retrieves a Header object by name.""" content = self._fetch("/service/%s/version/%d/header/%s" % (service_id, version_number, name)) return FastlyHeader(self, content)
[ "def", "get_header", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/header/%s\"", "%", "(", "service_id", ",", "version_number", ",", "name", ")", ")", "return...
57.25
0.025862
def start(self, min_nodes=None, max_concurrent_requests=0): """ Starts up all the instances in the cloud. To speed things up, all instances are started in a seperate thread. To make sure ElastiCluster is not stopped during creation of an instance, it will overwrite the s...
[ "def", "start", "(", "self", ",", "min_nodes", "=", "None", ",", "max_concurrent_requests", "=", "0", ")", ":", "nodes", "=", "self", ".", "get_all_nodes", "(", ")", "log", ".", "info", "(", "\"Starting cluster nodes (timeout: %d seconds) ...\"", ",", "self", ...
43.661972
0.000946
def add_breathing(ch, breathing): """ Add the given breathing to the given (possibly accented) character. """ decomposed = unicodedata.normalize("NFD", ch) if len(decomposed) > 1 and decomposed[1] == LONG: return unicodedata.normalize( "NFC", decomposed[0:2] + breathing + decompo...
[ "def", "add_breathing", "(", "ch", ",", "breathing", ")", ":", "decomposed", "=", "unicodedata", ".", "normalize", "(", "\"NFD\"", ",", "ch", ")", "if", "len", "(", "decomposed", ")", ">", "1", "and", "decomposed", "[", "1", "]", "==", "LONG", ":", "...
39
0.002278
def extract_can_logging(self, dbc_files, version=None): """ extract all possible CAN signal using the provided databases. Parameters ---------- dbc_files : iterable iterable of str or pathlib.Path objects Returns ------- mdf : MDF new MDF...
[ "def", "extract_can_logging", "(", "self", ",", "dbc_files", ",", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "self", ".", "version", "else", ":", "version", "=", "validate_version_argument", "(", "version", ")", "...
35.896552
0.001335
def calcEndOfPrdvPP(self): ''' Calculates end-of-period marginal marginal value using a pre-defined array of next period market resources in self.mNrmNext. Parameters ---------- none Returns ------- EndOfPrdvPP : np.array End-of-perio...
[ "def", "calcEndOfPrdvPP", "(", "self", ")", ":", "EndOfPrdvPP", "=", "self", ".", "DiscFacEff", "*", "self", ".", "Rfree", "*", "self", ".", "Rfree", "*", "self", ".", "PermGroFac", "**", "(", "-", "self", ".", "CRRA", "-", "1.0", ")", "*", "np", "...
35.315789
0.013062
def initialize_instrument_classpath(output_dir, settings, targets, instrumentation_classpath): """Clones the existing runtime_classpath and corresponding binaries to instrumentation specific paths. :param targets: the targets for which we should create an instrumentation_classpath entry based on their ...
[ "def", "initialize_instrument_classpath", "(", "output_dir", ",", "settings", ",", "targets", ",", "instrumentation_classpath", ")", ":", "instrument_dir", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'coverage'", ",", "'classes'", ")", "settings"...
53.21875
0.010381
def index(self, value, floating=False): """Return the index of a value in the domain. Parameters ---------- value : ``self.set`` element Point whose index to find. floating : bool, optional If True, then the index should also give the position inside the ...
[ "def", "index", "(", "self", ",", "value", ",", "floating", "=", "False", ")", ":", "value", "=", "np", ".", "atleast_1d", "(", "self", ".", "set", ".", "element", "(", "value", ")", ")", "result", "=", "[", "]", "for", "val", ",", "cell_bdry_vec",...
32.725
0.000742
def format_cell(val, round_floats = False, decimal_places = 2, format_links = False, hlx = '', hxl = '', xhl = ''): """ Applys smart_round and format_hyperlink to values in a cell if desired. """ if round_floats: val = smart_round(val, decimal_places = decimal_places) if format_links: ...
[ "def", "format_cell", "(", "val", ",", "round_floats", "=", "False", ",", "decimal_places", "=", "2", ",", "format_links", "=", "False", ",", "hlx", "=", "''", ",", "hxl", "=", "''", ",", "xhl", "=", "''", ")", ":", "if", "round_floats", ":", "val", ...
34.090909
0.049351
def get_representative_chain_mapping(self, representative_id_1, representative_id_2): '''This replaces the old mapping member by constructing it from self.chain_mapping. This function returns a mapping from chain IDs in pdb_name1 to chain IDs in pdb_name2.''' d = {} for pdb1_chain_id, ma...
[ "def", "get_representative_chain_mapping", "(", "self", ",", "representative_id_1", ",", "representative_id_2", ")", ":", "d", "=", "{", "}", "for", "pdb1_chain_id", ",", "matched_chain_list", "in", "self", ".", "chain_mapping", "[", "(", "representative_id_1", ",",...
76.571429
0.01107
def exposure_summary_layer(): """Helper method for retrieving exposure summary layer. If the analysis is multi-exposure, then it will return the exposure summary layer from place exposure analysis. """ project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) ...
[ "def", "exposure_summary_layer", "(", ")", ":", "project_context_scope", "=", "QgsExpressionContextUtils", ".", "projectScope", "(", "QgsProject", ".", "instance", "(", ")", ")", "project", "=", "QgsProject", ".", "instance", "(", ")", "key", "=", "provenance_laye...
39.490196
0.000484
def _cmp_bystrlen_reverse(a, b): """A private "cmp" function to be used by the "sort" function of a list when ordering the titles found in a knowledge base by string- length - LONGEST -> SHORTEST. @param a: (string) @param b: (string) @return: (integer) - 0 if len(a) == len(b); 1 ...
[ "def", "_cmp_bystrlen_reverse", "(", "a", ",", "b", ")", ":", "if", "len", "(", "a", ")", ">", "len", "(", "b", ")", ":", "return", "-", "1", "elif", "len", "(", "a", ")", "<", "len", "(", "b", ")", ":", "return", "1", "else", ":", "return", ...
31.733333
0.002041
def name(self): """Class name.""" return ffi.string(lib.EnvGetDefclassName(self._env, self._cls)).decode()
[ "def", "name", "(", "self", ")", ":", "return", "ffi", ".", "string", "(", "lib", ".", "EnvGetDefclassName", "(", "self", ".", "_env", ",", "self", ".", "_cls", ")", ")", ".", "decode", "(", ")" ]
40
0.02459