text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def update_subscription(self, update_parameters, subscription_id): """UpdateSubscription. [Preview API] Update an existing subscription. Depending on the type of subscription and permissions, the caller can update the description, filter settings, channel (delivery) settings and more. :param :cl...
[ "def", "update_subscription", "(", "self", ",", "update_parameters", ",", "subscription_id", ")", ":", "route_values", "=", "{", "}", "if", "subscription_id", "is", "not", "None", ":", "route_values", "[", "'subscriptionId'", "]", "=", "self", ".", "_serialize",...
73.882353
38.647059
def _subArrayShape(self): """ Returns the shape of the sub-array. An empty tuple is returned for regular fields, which have no sub array. """ fieldName = self.nodeName fieldDtype = self._array.dtype.fields[fieldName][0] return fieldDtype.shape
[ "def", "_subArrayShape", "(", "self", ")", ":", "fieldName", "=", "self", ".", "nodeName", "fieldDtype", "=", "self", ".", "_array", ".", "dtype", ".", "fields", "[", "fieldName", "]", "[", "0", "]", "return", "fieldDtype", ".", "shape" ]
41.285714
13.285714
def get_backend_setting(cls, name, default=None): """ Reads ``name`` setting from backend settings dictionary. If `default` value is omitted, raises ``ImproperlyConfigured`` when setting ``name`` is not available. """ backend_settings = get_backend_settings(cls.BACKEND) ...
[ "def", "get_backend_setting", "(", "cls", ",", "name", ",", "default", "=", "None", ")", ":", "backend_settings", "=", "get_backend_settings", "(", "cls", ".", "BACKEND", ")", "if", "default", "is", "not", "None", ":", "return", "backend_settings", ".", "get...
40.6
19.4
def _set_route_distinguisher(self, v, load=False): """ Setter method for route_distinguisher, mapped from YANG variable /rbridge_id/evpn_instance/route_distinguisher (container) If this variable is read-only (config: false) in the source YANG file, then _set_route_distinguisher is considered as a privat...
[ "def", "_set_route_distinguisher", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",...
87.545455
41.318182
def singleton(the_class): """ Decorator for a class to make a singleton out of it. @type the_class: class @param the_class: the class that should work as a singleton @rtype: decorator @return: decorator """ class_instances = {} def get_instance(*args, **kwargs): """ ...
[ "def", "singleton", "(", "the_class", ")", ":", "class_instances", "=", "{", "}", "def", "get_instance", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Creating or just return the one and only class instance.\n\n The singleton depends on the pa...
31.068966
16.172414
def _write_function(schema): """Add a write method for named schema to a class. """ def func( data, filename=None, schema=schema, id_col='uid', sequence_col='sequence', extra_data=None, alphabet=None, **kwargs): # Use generic write clas...
[ "def", "_write_function", "(", "schema", ")", ":", "def", "func", "(", "data", ",", "filename", "=", "None", ",", "schema", "=", "schema", ",", "id_col", "=", "'uid'", ",", "sequence_col", "=", "'sequence'", ",", "extra_data", "=", "None", ",", "alphabet...
25.153846
15.192308
def contains_all(self, other): """Return ``True`` if all strings in ``other`` have size `length`.""" dtype = getattr(other, 'dtype', None) if dtype is None: dtype = np.result_type(*other) dtype_str = np.dtype('S{}'.format(self.length)) dtype_uni = np.dtype('<U{}'.form...
[ "def", "contains_all", "(", "self", ",", "other", ")", ":", "dtype", "=", "getattr", "(", "other", ",", "'dtype'", ",", "None", ")", "if", "dtype", "is", "None", ":", "dtype", "=", "np", ".", "result_type", "(", "*", "other", ")", "dtype_str", "=", ...
47
8.625
def colors_json_ids(self): """ A proxy property based access to vertices in current edge When edge is serialized to JSON object, no explicit object for its multicolor is created, but rather all colors, taking into account their multiplicity, are referenced by their json_ids. """ ...
[ "def", "colors_json_ids", "(", "self", ")", ":", "return", "[", "color", ".", "json_id", "if", "hasattr", "(", "color", ",", "\"json_id\"", ")", "else", "hash", "(", "color", ")", "for", "color", "in", "self", ".", "multicolor", ".", "multicolors", ".", ...
62.142857
37.571429
def _request(self): """ retrieve the caller frame, extract the parameters from the caller function, find the matching function, and fire the request """ caller_frame = inspect.getouterframes(inspect.currentframe())[1] args, _, _, values = inspect.getargvalues(call...
[ "def", "_request", "(", "self", ")", ":", "caller_frame", "=", "inspect", ".", "getouterframes", "(", "inspect", ".", "currentframe", "(", ")", ")", "[", "1", "]", "args", ",", "_", ",", "_", ",", "values", "=", "inspect", ".", "getargvalues", "(", "...
42.785714
16.214286
def get_context_data(self, **kwargs): """ Get the context for this view. """ #max_columns, max_rows = self.get_max_dimension() context = { 'gadgets': self._registry, 'columns': self.columns, 'rows': self.rows, 'column_ratio': 100 - ...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "#max_columns, max_rows = self.get_max_dimension()", "context", "=", "{", "'gadgets'", ":", "self", ".", "_registry", ",", "'columns'", ":", "self", ".", "columns", ",", "'rows'", ":", ...
31
9.571429
def _add_updated_at_column(self, values): """ Add the "updated_at" column to a dictionary of values. :param values: The values to update :type values: dict :return: The new dictionary of values :rtype: dict """ if not self._model.uses_timestamps(): ...
[ "def", "_add_updated_at_column", "(", "self", ",", "values", ")", ":", "if", "not", "self", ".", "_model", ".", "uses_timestamps", "(", ")", ":", "return", "values", "column", "=", "self", ".", "_model", ".", "get_updated_at_column", "(", ")", "if", "\"upd...
27
18.473684
def default_listener(col_attr, default): """Establish a default-setting listener.""" @event.listens_for(col_attr, "init_scalar", retval=True, propagate=True) def init_scalar(target, value, dict_): if default.is_callable: # the callable of ColumnDefault always accepts a context argument...
[ "def", "default_listener", "(", "col_attr", ",", "default", ")", ":", "@", "event", ".", "listens_for", "(", "col_attr", ",", "\"init_scalar\"", ",", "retval", "=", "True", ",", "propagate", "=", "True", ")", "def", "init_scalar", "(", "target", ",", "valu...
32.888889
19.611111
def check_aux_coordinates(self, ds): ''' Chapter 5 paragraph 3 The dimensions of an auxiliary coordinate variable must be a subset of the dimensions of the variable with which the coordinate is associated, with two exceptions. First, string-valued coordinates (Section 6.1, ...
[ "def", "check_aux_coordinates", "(", "self", ",", "ds", ")", ":", "ret_val", "=", "[", "]", "geophysical_variables", "=", "self", ".", "_find_geophysical_vars", "(", "ds", ")", "for", "name", "in", "geophysical_variables", ":", "variable", "=", "ds", ".", "v...
48.849057
26.924528
def get_environments(self): """ Returns the environments """ response = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False) return response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']
[ "def", "get_environments", "(", "self", ")", ":", "response", "=", "self", ".", "ebs", ".", "describe_environments", "(", "application_name", "=", "self", ".", "app_name", ",", "include_deleted", "=", "False", ")", "return", "response", "[", "'DescribeEnvironmen...
47.666667
24.333333
def _check_leading(*char_lists): """Remove any non-alphanumeric or non-~ leading characters Checks the beginning of any provided lists for non-alphanumeric or non-~ (tilde) leading characters and removes them if found. Operates on (and possibly alters) the passed list. :param list char_list: a lis...
[ "def", "_check_leading", "(", "*", "char_lists", ")", ":", "logger", ".", "debug", "(", "'_check_leading(%s)'", ",", "char_lists", ")", "for", "char_list", "in", "char_lists", ":", "while", "(", "len", "(", "char_list", ")", "!=", "0", "and", "not", "char_...
38.117647
17
def standard_backtrack(self): """Estimate step size L by computing a linesearch that guarantees that F <= Q according to the standard FISTA backtracking strategy in :cite:`beck-2009-fast`. This also updates variable Y. """ gradY = self.eval_grad() # Given Y(f), this upd...
[ "def", "standard_backtrack", "(", "self", ")", ":", "gradY", "=", "self", ".", "eval_grad", "(", ")", "# Given Y(f), this updates computes gradY(f)", "maxiter", "=", "self", ".", "L_maxiter", "iterBTrack", "=", "0", "linesearch", "=", "1", "while", "linesearch", ...
30.085714
19.485714
def drop_invalid_columns(feed: "Feed") -> "Feed": """ Drop all DataFrame columns of the given "Feed" that are not listed in the GTFS. Return the resulting new "Feed". """ feed = feed.copy() for table, group in cs.GTFS_REF.groupby("table"): f = getattr(feed, table) if f is Non...
[ "def", "drop_invalid_columns", "(", "feed", ":", "\"Feed\"", ")", "->", "\"Feed\"", ":", "feed", "=", "feed", ".", "copy", "(", ")", "for", "table", ",", "group", "in", "cs", ".", "GTFS_REF", ".", "groupby", "(", "\"table\"", ")", ":", "f", "=", "get...
30.736842
13.684211
def _check_command_response(response, msg=None, allowable_errors=None, parse_write_concern_error=False): """Check the response to a command for errors. """ if "ok" not in response: # Server didn't recognize our message as a command. raise OperationFailure(response...
[ "def", "_check_command_response", "(", "response", ",", "msg", "=", "None", ",", "allowable_errors", "=", "None", ",", "parse_write_concern_error", "=", "False", ")", ":", "if", "\"ok\"", "not", "in", "response", ":", "# Server didn't recognize our message as a comman...
42.222222
18.68254
def remove_option(self, section, option): """Remove an option.""" if not section or section == self.default_section: sectdict = self._defaults else: try: sectdict = self._sections[section] except KeyError: raise from_none(NoSect...
[ "def", "remove_option", "(", "self", ",", "section", ",", "option", ")", ":", "if", "not", "section", "or", "section", "==", "self", ".", "default_section", ":", "sectdict", "=", "self", ".", "_defaults", "else", ":", "try", ":", "sectdict", "=", "self",...
34.285714
11.642857
def get_training_image_text_data_iters(source_root: str, source: str, target: str, validation_source_root: str, validation_source: str, validation_target: str, voca...
[ "def", "get_training_image_text_data_iters", "(", "source_root", ":", "str", ",", "source", ":", "str", ",", "target", ":", "str", ",", "validation_source_root", ":", "str", ",", "validation_source", ":", "str", ",", "validation_target", ":", "str", ",", "vocab_...
57.814159
29.017699
def create_hosted_zone(self, name, caller_reference=None, comment=None): """ Creates and returns a new hosted zone. Once a hosted zone is created, its details can't be changed. :param str name: The name of the hosted zone to create. :keyword str caller_reference: A unique string...
[ "def", "create_hosted_zone", "(", "self", ",", "name", ",", "caller_reference", "=", "None", ",", "comment", "=", "None", ")", ":", "body", "=", "xml_generators", ".", "create_hosted_zone_writer", "(", "connection", "=", "self", ",", "name", "=", "name", ","...
38.916667
22.583333
def get_new(modules, min_major_version, min_minor_version): """ Get list of migrations that haven't been run yet :param modules: iterable containing module names :param min_major_version: minimum major version :param min_minor_version: minimum minor version :returns: retur...
[ "def", "get_new", "(", "modules", ",", "min_major_version", ",", "min_minor_version", ")", ":", "for", "mod_data", "in", "modules", ":", "(", "modname", ",", "mod_major_version", ",", "mod_minor_version", ")", "=", "mod_data", "if", "(", "mod_major_version", ">"...
47.2
17.133333
def i3(): '''Install and customize the tiling window manager i3.''' install_package('i3') install_file_legacy(path='~/.i3/config', username=env.user, repos_dir='repos') # setup: hide the mouse if not in use # in ~/.i3/config: 'exec /home/<USERNAME>/repos/hhpc/hhpc -i 10 &' install_packages(['ma...
[ "def", "i3", "(", ")", ":", "install_package", "(", "'i3'", ")", "install_file_legacy", "(", "path", "=", "'~/.i3/config'", ",", "username", "=", "env", ".", "user", ",", "repos_dir", "=", "'repos'", ")", "# setup: hide the mouse if not in use", "# in ~/.i3/config...
47
25
def vector_generate(start_pt, end_pt, normalize=False): """ Generates a vector from 2 input points. :param start_pt: start point of the vector :type start_pt: list, tuple :param end_pt: end point of the vector :type end_pt: list, tuple :param normalize: if True, the generated vector is normaliz...
[ "def", "vector_generate", "(", "start_pt", ",", "end_pt", ",", "normalize", "=", "False", ")", ":", "try", ":", "if", "start_pt", "is", "None", "or", "len", "(", "start_pt", ")", "==", "0", "or", "end_pt", "is", "None", "or", "len", "(", "end_pt", ")...
32.214286
18.071429
def strip_qos_cntrl(self, idx, prot_type): """strip(2 byte) wlan.qos :idx: int :prot_type: string 802.11 protocol type(.11ac, .11a, .11n, etc) :return: int number of processed bytes :return: int qos priority :return: int qos...
[ "def", "strip_qos_cntrl", "(", "self", ",", "idx", ",", "prot_type", ")", ":", "qos_cntrl", ",", "=", "struct", ".", "unpack", "(", "'H'", ",", "self", ".", "_packet", "[", "idx", ":", "idx", "+", "2", "]", ")", "qos_cntrl_bits", "=", "format", "(", ...
34.36
12.92
def Beachball(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k', alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False, zorder=100, outfile=None, format=None, fig=None): """ Draws a beach ball diagram of an earthquake focal mechanism. S1, D1, and R1, the strike, dip a...
[ "def", "Beachball", "(", "fm", ",", "linewidth", "=", "2", ",", "facecolor", "=", "'b'", ",", "bgcolor", "=", "'w'", ",", "edgecolor", "=", "'k'", ",", "alpha", "=", "1.0", ",", "xy", "=", "(", "0", ",", "0", ")", ",", "width", "=", "200", ",",...
46.321429
23.77381
def copy_ecu_with_frames(ecu_or_glob, source_db, target_db): # type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None """ Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix. This function additionally copy all relevant Frames and Defines. :param e...
[ "def", "copy_ecu_with_frames", "(", "ecu_or_glob", ",", "source_db", ",", "target_db", ")", ":", "# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None", "# check whether ecu_or_glob is object or symbolic name", "if", "isinstance", "(", "ecu_or_glob", ",", "cm", ...
43.826087
20.826087
def get_params(self, name, param_list): '''Use lctl get_param to collect a selection of parameters into a file. ''' self.add_cmd_output("lctl get_param %s" % " ".join(param_list), suggest_filename="params-%s" % name, stderr=Fal...
[ "def", "get_params", "(", "self", ",", "name", ",", "param_list", ")", ":", "self", ".", "add_cmd_output", "(", "\"lctl get_param %s\"", "%", "\" \"", ".", "join", "(", "param_list", ")", ",", "suggest_filename", "=", "\"params-%s\"", "%", "name", ",", "stde...
39.5
22.75
def osmlem(op, x, data, niter, callback=None, **kwargs): r"""Ordered Subsets Maximum Likelihood Expectation Maximation algorithm. This solver attempts to solve:: max_x L(x | data) where ``L(x, | data)`` is the likelihood of ``x`` given ``data``. The likelihood depends on the forward operators...
[ "def", "osmlem", "(", "op", ",", "x", ",", "data", ",", "niter", ",", "callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "n_ops", "=", "len", "(", "op", ")", "if", "len", "(", "data", ")", "!=", "n_ops", ":", "raise", "ValueError", "("...
32.061947
22.477876
def kill(self, sig): """Send the given signal to the child application. In keeping with UNIX tradition it has a misleading name. It does not necessarily kill the child unless you send the right signal. See the :mod:`signal` module for constants representing signal numbers. """ ...
[ "def", "kill", "(", "self", ",", "sig", ")", ":", "# Same as os.kill, but the pid is given for you.", "if", "self", ".", "isalive", "(", ")", ":", "os", ".", "kill", "(", "self", ".", "pid", ",", "sig", ")" ]
38.909091
21.727273
def init_argparser(self, argparser): """ This should not be called with an external argparser as it will corrupt tracking data if forced. """ def prepare_argparser(): if argparser in self.argparser_details: return False result = self.argpa...
[ "def", "init_argparser", "(", "self", ",", "argparser", ")", ":", "def", "prepare_argparser", "(", ")", ":", "if", "argparser", "in", "self", ".", "argparser_details", ":", "return", "False", "result", "=", "self", ".", "argparser_details", "[", "argparser", ...
46.521277
21.425532
def p_identifier_group_op(self, p): """ identifier_group : identifier_group child_selector ident_parts | identifier_group '+' ident_parts | identifier_group general_sibling_selector ident_parts ...
[ "def", "p_identifier_group_op", "(", "self", ",", "p", ")", ":", "p", "[", "1", "]", ".", "extend", "(", "[", "p", "[", "2", "]", "]", ")", "if", "len", "(", "p", ")", ">", "3", ":", "p", "[", "1", "]", ".", "extend", "(", "p", "[", "3", ...
45.1
17.3
def write(self, data): """Just quote out stuff before sending it out""" args = parse_qs(self.handler.environ.get("QUERY_STRING")) if "i" in args: i = args["i"] else: i = "0" # TODO: don't we need to quote this data in here ? super(JSONPolling, self...
[ "def", "write", "(", "self", ",", "data", ")", ":", "args", "=", "parse_qs", "(", "self", ".", "handler", ".", "environ", ".", "get", "(", "\"QUERY_STRING\"", ")", ")", "if", "\"i\"", "in", "args", ":", "i", "=", "args", "[", "\"i\"", "]", "else", ...
38.888889
18.888889
def get_regulate_amounts(self): """Extract Increase/DecreaseAmount Statements.""" pos_events = [] neg_events = [] pattern = "EVENT/[type='ONT::STIMULATE']/arg2/[type='ONT::TRANSCRIBE']/.." pos_events += self.tree.findall(pattern) pattern = "EVENT/[type='ONT::INCREASE']/ar...
[ "def", "get_regulate_amounts", "(", "self", ")", ":", "pos_events", "=", "[", "]", "neg_events", "=", "[", "]", "pattern", "=", "\"EVENT/[type='ONT::STIMULATE']/arg2/[type='ONT::TRANSCRIBE']/..\"", "pos_events", "+=", "self", ".", "tree", ".", "findall", "(", "patte...
48.52
16.133333
def c_member_funcs(self, for_struct=False): """Get the decls of the module.""" decls = [ '{} *{};'.format(self._c_type_name(name), name) for name, dummy_args in self.funcs ] if for_struct: return decls return [self._c_mod_decl()] + decls
[ "def", "c_member_funcs", "(", "self", ",", "for_struct", "=", "False", ")", ":", "decls", "=", "[", "'{} *{};'", ".", "format", "(", "self", ".", "_c_type_name", "(", "name", ")", ",", "name", ")", "for", "name", ",", "dummy_args", "in", "self", ".", ...
33.888889
13.222222
def get_component_settings(prefixes=None): """ Returns a subset of the env dictionary containing only those keys with the name prefix. """ prefixes = prefixes or [] assert isinstance(prefixes, (tuple, list)), 'Prefixes must be a sequence type, not %s.' % type(prefixes) data = {} for name...
[ "def", "get_component_settings", "(", "prefixes", "=", "None", ")", ":", "prefixes", "=", "prefixes", "or", "[", "]", "assert", "isinstance", "(", "prefixes", ",", "(", "tuple", ",", "list", ")", ")", ",", "'Prefixes must be a sequence type, not %s.'", "%", "t...
34.733333
12.333333
def residual_norm(A, x, b): """Compute ||b - A*x||.""" return norm(np.ravel(b) - A*np.ravel(x))
[ "def", "residual_norm", "(", "A", ",", "x", ",", "b", ")", ":", "return", "norm", "(", "np", ".", "ravel", "(", "b", ")", "-", "A", "*", "np", ".", "ravel", "(", "x", ")", ")" ]
33.666667
5.666667
def cns_vwl_str(self): """ Return a new IPAString, containing only: 1. the consonants, 2. the vowels, and 3. the stress diacritics in the current string. :rtype: IPAString """ return IPAString(ipa_chars=[c for c in self.ipa_chars if (c.i...
[ "def", "cns_vwl_str", "(", "self", ")", ":", "return", "IPAString", "(", "ipa_chars", "=", "[", "c", "for", "c", "in", "self", ".", "ipa_chars", "if", "(", "c", ".", "is_letter", ")", "or", "(", "c", ".", "is_suprasegmental", "and", "c", ".", "is_str...
27.692308
21.538462
def _append_funcs(target, items): """ Helper function to append functions into a given list. Arguments: target (list): receptor list to append functions. items (iterable): iterable that yields elements to append. """ [target.append(item) for item in items if isfunction(item) or...
[ "def", "_append_funcs", "(", "target", ",", "items", ")", ":", "[", "target", ".", "append", "(", "item", ")", "for", "item", "in", "items", "if", "isfunction", "(", "item", ")", "or", "ismethod", "(", "item", ")", "]" ]
32.7
13.9
def _parse_include_section(cfg, parser, section): ''' Example of include section: [include] flt: /etc/feat/flt.ini ducksboard: /etc/feat/ducksboard.ini ''' for _name, pattern in cfg.items(section): if not os.path.isabs(pattern): pattern = os.path.join(configure.confdir, p...
[ "def", "_parse_include_section", "(", "cfg", ",", "parser", ",", "section", ")", ":", "for", "_name", ",", "pattern", "in", "cfg", ".", "items", "(", "section", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "pattern", ")", ":", "patter...
31.733333
13.066667
def _handle_return(state: GlobalState) -> None: """ Adds all the annotations into the state which correspond to the locations in the memory returned by RETURN opcode. :param state: The Global State """ stack = state.mstate.stack try: offset, length = g...
[ "def", "_handle_return", "(", "state", ":", "GlobalState", ")", "->", "None", ":", "stack", "=", "state", ".", "mstate", ".", "stack", "try", ":", "offset", ",", "length", "=", "get_concrete_int", "(", "stack", "[", "-", "1", "]", ")", ",", "get_concre...
41.73913
15.391304
def execute(self, eopatch): """ Mask values of `feature` according to the `mask_values` in `mask_feature` :param eopatch: `eopatch` to be processed :return: Same `eopatch` instance with masked `feature` """ feature_type, feature_name, new_feature_name = next(self.feature(eopatch...
[ "def", "execute", "(", "self", ",", "eopatch", ")", ":", "feature_type", ",", "feature_name", ",", "new_feature_name", "=", "next", "(", "self", ".", "feature", "(", "eopatch", ")", ")", "mask_feature_type", ",", "mask_feature_name", "=", "next", "(", "self"...
39.761905
25
def aliases(self): """ Returns symbol instances corresponding to aliased vars. """ return [x for x in self[self.current_scope].values() if x.is_aliased]
[ "def", "aliases", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "is_aliased", "]" ]
43.25
14.75
def get_negation(event): """Return negation attached to an event. Example: "states": [{"@type": "State", "type": "NEGATION", "text": "n't"}] """ states = event.get('states', []) if not states: return [] negs = [state for state in ...
[ "def", "get_negation", "(", "event", ")", ":", "states", "=", "event", ".", "get", "(", "'states'", ",", "[", "]", ")", "if", "not", "states", ":", "return", "[", "]", "negs", "=", "[", "state", "for", "state", "in", "states", "if", "state", ".", ...
33.923077
12.307692
def _purge_children(self): """ Find dead children and put a response on the result queue. :return: """ for task_id, p in six.iteritems(self._running_tasks): if not p.is_alive() and p.exitcode: error_msg = 'Task {} died unexpectedly with exit code {}'....
[ "def", "_purge_children", "(", "self", ")", ":", "for", "task_id", ",", "p", "in", "six", ".", "iteritems", "(", "self", ".", "_running_tasks", ")", ":", "if", "not", "p", ".", "is_alive", "(", ")", "and", "p", ".", "exitcode", ":", "error_msg", "=",...
46.684211
28.052632
def populate_display_n(self): """Get the number of displays and populate this drop-down box with them all. Prepend the "always on primary" option. """ cb = self.get_widget('display_n') screen = self.get_widget('config-window').get_screen() cb.append_text("always on prima...
[ "def", "populate_display_n", "(", "self", ")", ":", "cb", "=", "self", ".", "get_widget", "(", "'display_n'", ")", "screen", "=", "self", ".", "get_widget", "(", "'config-window'", ")", ".", "get_screen", "(", ")", "cb", ".", "append_text", "(", "\"always ...
37.8
15
def validate_settings(settings): """ `settings` is either a dictionary or an object containing Kronos settings (e.g., the contents of conf/settings.py). This function checks that all required settings are present and valid. """ # Validate `storage` storage = _validate_and_get_value(settings, 'settings', ...
[ "def", "validate_settings", "(", "settings", ")", ":", "# Validate `storage`", "storage", "=", "_validate_and_get_value", "(", "settings", ",", "'settings'", ",", "'storage'", ",", "dict", ")", "for", "name", ",", "options", "in", "storage", ".", "iteritems", "(...
40.046154
18.692308
def __update(self, row): """Update rows in table """ expr = self.__table.update().values(row) for key in self.__update_keys: expr = expr.where(getattr(self.__table.c, key) == row[key]) if self.__autoincrement: expr = expr.returning(getattr(self.__table.c, ...
[ "def", "__update", "(", "self", ",", "row", ")", ":", "expr", "=", "self", ".", "__table", ".", "update", "(", ")", ".", "values", "(", "row", ")", "for", "key", "in", "self", ".", "__update_keys", ":", "expr", "=", "expr", ".", "where", "(", "ge...
36.0625
11.4375
def get_coverage(config: CoverageConfig) -> 'Coverage': """ Returns a Coverage instance. :param config: Coverage configuration. :return: Instance of Coverage. """ if config.type == C.COVERAGE_COUNT or config.type == C.COVERAGE_FERTILITY: utils.check_condition(config.num_hidden == 1, "Co...
[ "def", "get_coverage", "(", "config", ":", "CoverageConfig", ")", "->", "'Coverage'", ":", "if", "config", ".", "type", "==", "C", ".", "COVERAGE_COUNT", "or", "config", ".", "type", "==", "C", ".", "COVERAGE_FERTILITY", ":", "utils", ".", "check_condition",...
46.315789
20.526316
def resolve_implicit_levels(storage, debug): """Resolving implicit levels (I1, I2) See: http://unicode.org/reports/tr9/#Resolving_Implicit_Levels """ for run in storage['runs']: start, length = run['start'], run['length'] chars = storage['chars'][start:start+length] for _ch in...
[ "def", "resolve_implicit_levels", "(", "storage", ",", "debug", ")", ":", "for", "run", "in", "storage", "[", "'runs'", "]", ":", "start", ",", "length", "=", "run", "[", "'start'", "]", ",", "run", "[", "'length'", "]", "chars", "=", "storage", "[", ...
38.451613
18
def anchor(self): """int or str indicating element under which to insert this subtotal. An int anchor is the id of the dimension element (category or subvariable) under which to place this subtotal. The return value can also be one of 'top' or 'bottom'. The return value default...
[ "def", "anchor", "(", "self", ")", ":", "anchor", "=", "self", ".", "_subtotal_dict", "[", "\"anchor\"", "]", "try", ":", "anchor", "=", "int", "(", "anchor", ")", "if", "anchor", "not", "in", "self", ".", "valid_elements", ".", "element_ids", ":", "re...
39.736842
18.157895
def adjust_opts(in_opts, config): """Establish JVM opts, adjusting memory for the context if needed. This allows using less or more memory for highly parallel or multicore supporting processes, respectively. """ memory_adjust = config["algorithm"].get("memory_adjust", {}) out_opts = [] for ...
[ "def", "adjust_opts", "(", "in_opts", ",", "config", ")", ":", "memory_adjust", "=", "config", "[", "\"algorithm\"", "]", ".", "get", "(", "\"memory_adjust\"", ",", "{", "}", ")", "out_opts", "=", "[", "]", "for", "opt", "in", "in_opts", ":", "if", "op...
49.5
24.777778
def _build(self, input_modules, middle_modules, head_modules): """ TBD """ self.input_layer = self._build_input_layer(input_modules) self.middle_layers = self._build_middle_layers(middle_modules) self.heads = self._build_task_heads(head_modules) # Construct loss ...
[ "def", "_build", "(", "self", ",", "input_modules", ",", "middle_modules", ",", "head_modules", ")", ":", "self", ".", "input_layer", "=", "self", ".", "_build_input_layer", "(", "input_modules", ")", "self", ".", "middle_layers", "=", "self", ".", "_build_mid...
41
20.454545
def _compute_hanging_wall_effect(self, C, rjb, rrup, dip, mag): """ Compute hanging-wall effect (see eq. 7, 8, 9 and 10 page 319). Considers correct version of equation 8 as given in the erratum and not in the original paper. """ # eq. 8 (to be noticed that the USGS-NSHMP...
[ "def", "_compute_hanging_wall_effect", "(", "self", ",", "C", ",", "rjb", ",", "rrup", ",", "dip", ",", "mag", ")", ":", "# eq. 8 (to be noticed that the USGS-NSHMP implementation defines", "# the hanging-wall term for all rjb distances, while in the original", "# manuscript, hw ...
35.296296
21.222222
def get_annotations(self, annotation_type: type) -> Iterator[StateAnnotation]: """Filters annotations for the queried annotation type. Designed particularly for modules with annotations: worldstate.get_annotations(MySpecificModuleAnnotation) :param annotation_type: The type to filter an...
[ "def", "get_annotations", "(", "self", ",", "annotation_type", ":", "type", ")", "->", "Iterator", "[", "StateAnnotation", "]", ":", "return", "filter", "(", "lambda", "x", ":", "isinstance", "(", "x", ",", "annotation_type", ")", ",", "self", ".", "annota...
51.888889
20.444444
def dump(finished=True, profile_process='worker'): """Dump profile and stop profiler. Use this to save profile in advance in case your program cannot exit normally. Parameters ---------- finished : boolean Indicates whether to stop statistic output (dumping) after this dump. Default...
[ "def", "dump", "(", "finished", "=", "True", ",", "profile_process", "=", "'worker'", ")", ":", "fin", "=", "1", "if", "finished", "is", "True", "else", "0", "profile_process2int", "=", "{", "'worker'", ":", "0", ",", "'server'", ":", "1", "}", "check_...
42.421053
17.789474
def discovery_mdns(self): """ Installs the mDNS discovery bundles and instantiates components """ # Remove Zeroconf debug output logging.getLogger("zeroconf").setLevel(logging.WARNING) # Install the bundle self.context.install_bundle("pelix.remote.discovery.mdns"...
[ "def", "discovery_mdns", "(", "self", ")", ":", "# Remove Zeroconf debug output", "logging", ".", "getLogger", "(", "\"zeroconf\"", ")", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(...
37.923077
19.307692
def rsdl_sn(self, U): """Compute dual residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden. """ return self.rho * np.linalg.norm(self.cnst_AT(U))
[ "def", "rsdl_sn", "(", "self", ",", "U", ")", ":", "return", "self", ".", "rho", "*", "np", ".", "linalg", ".", "norm", "(", "self", ".", "cnst_AT", "(", "U", ")", ")" ]
32.888889
21.444444
def PullInstancesWithPath(self, context, MaxObjectCount, **extra): # pylint: disable=invalid-name """ Retrieve the next set of instances (with instance paths) from an open enumeration session. *New in pywbem 0.9.* This operation can only be used on enumeration sessions...
[ "def", "PullInstancesWithPath", "(", "self", ",", "context", ",", "MaxObjectCount", ",", "*", "*", "extra", ")", ":", "# pylint: disable=invalid-name", "exc", "=", "None", "result_tuple", "=", "None", "method_name", "=", "'PullInstancesWithPath'", "if", "self", "....
39.801282
23.519231
def get_first_element_index(root, tag_name): """ In order to use Element.insert() in a convenient way, this function will find the first child tag with tag_name and return its index position The index can then be used to insert an element before or after the found tag using Element.insert() ...
[ "def", "get_first_element_index", "(", "root", ",", "tag_name", ")", ":", "tag_index", "=", "1", "for", "tag", "in", "root", ":", "if", "tag", ".", "tag", "==", "tag_name", ":", "# Return the first one found if there is a match", "return", "tag_index", "tag_index"...
33.3125
14.1875
def seek(self, ofs, whence=0): """Seek in data. On uncompressed files, the seeking works by actual seeks so it's fast. On compresses files its slow - forward seeking happends by reading ahead, backwards by re-opening and decompressing from the start. """ # disa...
[ "def", "seek", "(", "self", ",", "ofs", ",", "whence", "=", "0", ")", ":", "# disable crc check when seeking", "self", ".", "_md_context", "=", "NoHashContext", "(", ")", "fsize", "=", "self", ".", "_inf", ".", "file_size", "cur_ofs", "=", "self", ".", "...
29.342105
16.578947
def query_one_table(self, table_name): """ Run all queries for the given table name (date) and update the cache. :param table_name: table name to query against :type table_name: str """ table_date = self._datetime_for_table_name(table_name) logger.info('Running a...
[ "def", "query_one_table", "(", "self", ",", "table_name", ")", ":", "table_date", "=", "self", ".", "_datetime_for_table_name", "(", "table_name", ")", "logger", ".", "info", "(", "'Running all queries for date table: %s (%s)'", ",", "table_name", ",", "table_date", ...
41.95122
17.02439
def update(self): """ Update the screens contents in every loop. """ # this is not really neccesary because the surface is black after initializing self.corners.fill(BLACK) self.corners.draw_dot((0, 0), self.colors[0]) self.corners.draw_dot((self.screen.width - 1,...
[ "def", "update", "(", "self", ")", ":", "# this is not really neccesary because the surface is black after initializing", "self", ".", "corners", ".", "fill", "(", "BLACK", ")", "self", ".", "corners", ".", "draw_dot", "(", "(", "0", ",", "0", ")", ",", "self", ...
48.441176
23.088235
def string_to_run(self, qad, executable, stdin=None, stdout=None, stderr=None, exec_args=None): """ Build and return a string with the command required to launch `executable` with the qadapter `qad`. Args qad: Qadapter instance. executable (str): Executable name or path ...
[ "def", "string_to_run", "(", "self", ",", "qad", ",", "executable", ",", "stdin", "=", "None", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ",", "exec_args", "=", "None", ")", ":", "stdin", "=", "\"< \"", "+", "stdin", "if", "stdin", "is",...
51.173913
30.173913
def _match_minimum_date_time(self, match_key, date_time_value, match=True): """Matches a minimum date time value""" if match: gtelt = '$gte' else: gtelt = '$lt' if match_key in self._query_terms: self._query_terms[match_key][gtelt] = date_time_value ...
[ "def", "_match_minimum_date_time", "(", "self", ",", "match_key", ",", "date_time_value", ",", "match", "=", "True", ")", ":", "if", "match", ":", "gtelt", "=", "'$gte'", "else", ":", "gtelt", "=", "'$lt'", "if", "match_key", "in", "self", ".", "_query_ter...
39
19.5
def verify_pattern(pattern): """Verifies if pattern for matching and finding fulfill expected structure. :param pattern: string pattern to verify :return: True if pattern has proper syntax, False otherwise """ regex = re.compile("^!?[a-zA-Z]+$|[*]{1,2}$") def __verify_pattern__(__pa...
[ "def", "verify_pattern", "(", "pattern", ")", ":", "regex", "=", "re", ".", "compile", "(", "\"^!?[a-zA-Z]+$|[*]{1,2}$\"", ")", "def", "__verify_pattern__", "(", "__pattern__", ")", ":", "if", "not", "__pattern__", ":", "return", "False", "elif", "__pattern__", ...
34.47619
20.190476
def _subset_by_support(orig_vcf, cmp_calls, data): """Subset orig_vcf to calls also present in any of the comparison callers. """ cmp_vcfs = [x["vrn_file"] for x in cmp_calls] out_file = "%s-inensemble.vcf.gz" % utils.splitext_plus(orig_vcf)[0] if not utils.file_uptodate(out_file, orig_vcf): ...
[ "def", "_subset_by_support", "(", "orig_vcf", ",", "cmp_calls", ",", "data", ")", ":", "cmp_vcfs", "=", "[", "x", "[", "\"vrn_file\"", "]", "for", "x", "in", "cmp_calls", "]", "out_file", "=", "\"%s-inensemble.vcf.gz\"", "%", "utils", ".", "splitext_plus", "...
57.769231
18
def _get_nblock_regions(in_file, min_n_size, ref_regions): """Retrieve coordinates of regions in reference genome with no mapping. These are potential breakpoints for parallelizing analysis. """ out_lines = [] called_contigs = set([]) with utils.open_gzipsafe(in_file) as in_handle: for l...
[ "def", "_get_nblock_regions", "(", "in_file", ",", "min_n_size", ",", "ref_regions", ")", ":", "out_lines", "=", "[", "]", "called_contigs", "=", "set", "(", "[", "]", ")", "with", "utils", ".", "open_gzipsafe", "(", "in_file", ")", "as", "in_handle", ":",...
50.529412
17.235294
def extrair_logs(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.extrair_logs`. :return: Uma resposta SAT especializada em ``ExtrairLogs``. :rtype: satcfe.resposta.extrairlogs.RespostaExtrairLogs """ resp = self._http_post('extrairlogs') conteudo = resp.json() ...
[ "def", "extrair_logs", "(", "self", ")", ":", "resp", "=", "self", ".", "_http_post", "(", "'extrairlogs'", ")", "conteudo", "=", "resp", ".", "json", "(", ")", "return", "RespostaExtrairLogs", ".", "analisar", "(", "conteudo", ".", "get", "(", "'retorno'"...
41.333333
16.666667
def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be c...
[ "def", "proxy_headers", "(", "self", ",", "proxy", ")", ":", "headers", "=", "{", "}", "username", ",", "password", "=", "get_auth_from_url", "(", "proxy", ")", "if", "username", "and", "password", ":", "headers", "[", "'Proxy-Authorization'", "]", "=", "_...
41.190476
23.47619
def _srm(self, data): """Expectation-Maximization algorithm for fitting the probabilistic SRM. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. Returns -...
[ "def", "_srm", "(", "self", ",", "data", ")", ":", "local_min", "=", "min", "(", "[", "d", ".", "shape", "[", "1", "]", "for", "d", "in", "data", "if", "d", "is", "not", "None", "]", ",", "default", "=", "sys", ".", "maxsize", ")", "samples", ...
42.647482
22.841727
def prove(self, file, chal, tag): """This function returns a proof calculated from the file, the challenge, and the file tag :param file: this is a file like object that supports `read()`, `tell()` and `seek()` methods. :param chal: the challenge to use for proving :para...
[ "def", "prove", "(", "self", ",", "file", ",", "chal", ",", "tag", ")", ":", "chunk_size", "=", "self", ".", "sectors", "*", "self", ".", "sectorsize", "index", "=", "KeyedPRF", "(", "chal", ".", "key", ",", "len", "(", "tag", ".", "sigma", ")", ...
32.210526
17.394737
def all(self, query=None, **kwargs): """ Gets all organizations. """ return super(OrganizationsProxy, self).all(query=query)
[ "def", "all", "(", "self", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "OrganizationsProxy", ",", "self", ")", ".", "all", "(", "query", "=", "query", ")" ]
25.333333
12.666667
def process_metadata_callbacks(aws_config): """ Iterates through each type of resource and, when callbacks have been configured in the config metadata, recurse through each resource and calls each callback. :param aws_config: The entire AWS configuration object :return: ...
[ "def", "process_metadata_callbacks", "(", "aws_config", ")", ":", "for", "service_group", "in", "aws_config", "[", "'metadata'", "]", ":", "for", "service", "in", "aws_config", "[", "'metadata'", "]", "[", "service_group", "]", ":", "if", "service", "==", "'su...
66.046154
34.2
def init_original_response(self): """Get the original response for comparing, confirm ``is_cookie_necessary``""" if 'json' in self.request: self.request['data'] = json.dumps(self.request.pop('json')).encode( self.encoding) r1 = self.req.request( retry=self...
[ "def", "init_original_response", "(", "self", ")", ":", "if", "'json'", "in", "self", ".", "request", ":", "self", ".", "request", "[", "'data'", "]", "=", "json", ".", "dumps", "(", "self", ".", "request", ".", "pop", "(", "'json'", ")", ")", ".", ...
48.461538
14.923077
def outgoing(self, node): """Returns nodes connecting out of the given node (or list of nodes).""" nodes = node if isinstance(node, list) else [node] node_ids = [self.id(n) for n in nodes] # Find edges outgoing from this group but not incoming to it outgoing = [self[e[1]] for e i...
[ "def", "outgoing", "(", "self", ",", "node", ")", ":", "nodes", "=", "node", "if", "isinstance", "(", "node", ",", "list", ")", "else", "[", "node", "]", "node_ids", "=", "[", "self", ".", "id", "(", "n", ")", "for", "n", "in", "nodes", "]", "#...
51.875
14.875
def clear_api_path_map_cache(self): """Clear out cache for api_path_map.""" self._api_path_cache = None for api_provider in self.api_providers: if six.get_method_self( api_provider.clear_api_path_map_cache, ) is not None: api_provider.clear...
[ "def", "clear_api_path_map_cache", "(", "self", ")", ":", "self", ".", "_api_path_cache", "=", "None", "for", "api_provider", "in", "self", ".", "api_providers", ":", "if", "six", ".", "get_method_self", "(", "api_provider", ".", "clear_api_path_map_cache", ",", ...
41.75
8.125
def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. Accepts full or partial FMRI. If called using pkg_resource, full FMRI is required. Partial FMRI is returned if the package is not installed. CLI Example: .. code-block:: bash salt '*' ...
[ "def", "version", "(", "*", "names", ",", "*", "*", "kwargs", ")", ":", "if", "not", "names", ":", "return", "''", "cmd", "=", "[", "'/bin/pkg'", ",", "'list'", ",", "'-Hv'", "]", "cmd", ".", "extend", "(", "names", ")", "lines", "=", "__salt__", ...
30.486486
26.108108
def stream_gzip_decompress_lines(stream): """ Uncompress a gzip stream into lines of text. Parameters ---------- Generator of chunks of gzip compressed text. Returns ------- Generator of uncompressed lines. """ dec = zlib.decompressobj(zlib.MAX_WBITS | 16) previous = "" ...
[ "def", "stream_gzip_decompress_lines", "(", "stream", ")", ":", "dec", "=", "zlib", ".", "decompressobj", "(", "zlib", ".", "MAX_WBITS", "|", "16", ")", "previous", "=", "\"\"", "for", "compressed_chunk", "in", "stream", ":", "chunk", "=", "dec", ".", "dec...
25.909091
15.909091
def prettify(root, encoding='utf-8'): """ Return a pretty-printed XML string for the Element. @see: http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/create.html """ if isinstance(root, ElementTree.Element): node = ElementTree.tostring(root, 'utf-8') else: node = root ...
[ "def", "prettify", "(", "root", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "root", ",", "ElementTree", ".", "Element", ")", ":", "node", "=", "ElementTree", ".", "tostring", "(", "root", ",", "'utf-8'", ")", "else", ":", "node"...
34.625
15.625
def register_model(self, *index_fields, **kw): """Registers a single model for fulltext search. This basically creates a simple Whoosheer for the model and calls :func:`register_whoosheer` on it. """ # construct subclass of AbstractWhoosheer for a model class ModelWhooshe...
[ "def", "register_model", "(", "self", ",", "*", "index_fields", ",", "*", "*", "kw", ")", ":", "# construct subclass of AbstractWhoosheer for a model", "class", "ModelWhoosheer", "(", "AbstractWhoosheerMeta", ")", ":", "@", "classmethod", "def", "_assign_primary", "("...
43.151899
18.822785
def _build_toc_node(docname, anchor="anchor", text="test text", bullet=False): """ Create the node structure that Sphinx expects for TOC Tree entries. The ``bullet`` argument wraps it in a ``nodes.bullet_list``, which is how you nest TOC Tree entries. """ reference = nodes.reference( ""...
[ "def", "_build_toc_node", "(", "docname", ",", "anchor", "=", "\"anchor\"", ",", "text", "=", "\"test text\"", ",", "bullet", "=", "False", ")", ":", "reference", "=", "nodes", ".", "reference", "(", "\"\"", ",", "\"\"", ",", "internal", "=", "True", ","...
33.388889
18.277778
def timeFunction(requestContext, name, step=60): """ Short Alias: time() Just returns the timestamp for each X value. T Example:: &target=time("The.time.series") This would create a series named "The.time.series" that contains in Y the same value (in seconds) as X. A second argu...
[ "def", "timeFunction", "(", "requestContext", ",", "name", ",", "step", "=", "60", ")", ":", "start", "=", "int", "(", "epoch", "(", "requestContext", "[", "\"startTime\"", "]", ")", ")", "end", "=", "int", "(", "epoch", "(", "requestContext", "[", "\"...
25.5
20.633333
def _masquerade(origin: str, orig: ServiceDefn, new: ServiceDefn, **map: str) -> str: """build an origin URL such that the orig has all of the mappings to new defined by map""" origin: ParseResult = urlparse(origin) prev_maps = {} if origin.query: prev_maps = {k: v for k, v in parse_qsl(origi...
[ "def", "_masquerade", "(", "origin", ":", "str", ",", "orig", ":", "ServiceDefn", ",", "new", ":", "ServiceDefn", ",", "*", "*", "map", ":", "str", ")", "->", "str", ":", "origin", ":", "ParseResult", "=", "urlparse", "(", "origin", ")", "prev_maps", ...
28.548387
24.612903
def register_blueprints(app): """Register Flask blueprints.""" app.register_blueprint(public.public_bp) app.register_blueprint(genes.genes_bp) app.register_blueprint(cases.cases_bp) app.register_blueprint(login.login_bp) app.register_blueprint(variants.variants_bp) app.register_blueprint(pan...
[ "def", "register_blueprints", "(", "app", ")", ":", "app", ".", "register_blueprint", "(", "public", ".", "public_bp", ")", "app", ".", "register_blueprint", "(", "genes", ".", "genes_bp", ")", "app", ".", "register_blueprint", "(", "cases", ".", "cases_bp", ...
43.307692
5.615385
def list_all_coupons(cls, **kwargs): """List Coupons Return a list of Coupons This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_coupons(async=True) >>> result = thread.get() ...
[ "def", "list_all_coupons", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_coupons_with_http_info", "(", "*", ...
35.869565
14.652174
def isloaded(self, name): """Checks if given hook module has been loaded Args: name (str): The name of the module to check Returns: bool. The return code:: True -- Loaded False -- Not Loaded """ if name is None: ...
[ "def", "isloaded", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "return", "True", "if", "isinstance", "(", "name", ",", "str", ")", ":", "return", "(", "name", "in", "[", "x", ".", "__module__", "for", "x", "in", "self", "...
24.409091
20.272727
def opt_vals_(self): """Iterator over sections, option names, and option values. This iterator is also implemented at the section level. The two loops produce the same output:: for sct, opt, val in conf.opt_vals_(): print(sct, opt, val) for sct in conf....
[ "def", "opt_vals_", "(", "self", ")", ":", "for", "sct", ",", "opt", "in", "self", ".", "options_", "(", ")", ":", "yield", "sct", ",", "opt", ",", "self", "[", "sct", "]", "[", "opt", "]" ]
32.833333
16.944444
def _split_input_from_namespace(cls, app, namespace, entity_kind, shard_count): """Helper for _split_input_from_params. If there are not enough Entities to make all of the given shards, the returned list of KeyRanges will include Nones. The returned list will contain K...
[ "def", "_split_input_from_namespace", "(", "cls", ",", "app", ",", "namespace", ",", "entity_kind", ",", "shard_count", ")", ":", "raw_entity_kind", "=", "cls", ".", "_get_raw_entity_kind", "(", "entity_kind", ")", "if", "shard_count", "==", "1", ":", "# With on...
31.949367
19.012658
def installUpdate(self): """ Install the newest version of Plex Media Server. """ # We can add this but dunno how useful this is since it sometimes # requires user action using a gui. part = '/updater/apply' release = self.check_for_update(force=True, download=True) if re...
[ "def", "installUpdate", "(", "self", ")", ":", "# We can add this but dunno how useful this is since it sometimes", "# requires user action using a gui.", "part", "=", "'/updater/apply'", "release", "=", "self", ".", "check_for_update", "(", "force", "=", "True", ",", "down...
51.444444
14.333333
def cleanup(self): """Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times fro...
[ "def", "cleanup", "(", "self", ")", ":", "for", "instance", "in", "self", ".", "context", ":", "del", "(", "instance", ")", "for", "plugin", "in", "self", ".", "plugins", ":", "del", "(", "plugin", ")" ]
32.954545
22
def deprecated(fun_name=None, msg=""): '''Issue a deprecation warning for a function''' def _deprecated(fun): '''Issue a deprecation warning for a function''' @wraps(fun) def _wrapper(*args, **kwargs): '''Issue deprecation warning and forward arguments to fun''' n...
[ "def", "deprecated", "(", "fun_name", "=", "None", ",", "msg", "=", "\"\"", ")", ":", "def", "_deprecated", "(", "fun", ")", ":", "'''Issue a deprecation warning for a function'''", "@", "wraps", "(", "fun", ")", "def", "_wrapper", "(", "*", "args", ",", "...
38.071429
20.357143
def _validate_program(self): """ Verify that selected mode is available for program and all courses in the program """ program = self.cleaned_data.get(self.Fields.PROGRAM) if not program: return course_runs = get_course_runs_from_program(program) try:...
[ "def", "_validate_program", "(", "self", ")", ":", "program", "=", "self", ".", "cleaned_data", ".", "get", "(", "self", ".", "Fields", ".", "PROGRAM", ")", "if", "not", "program", ":", "return", "course_runs", "=", "get_course_runs_from_program", "(", "prog...
45.916667
27.583333
def format_dateaxis(subplot, freq, index): """ Pretty-formats the date axis (x-axis). Major and minor ticks are automatically set for the frequency of the current underlying series. As the dynamic mode is activated by default, changing the limits of the x axis will intelligently change the pos...
[ "def", "format_dateaxis", "(", "subplot", ",", "freq", ",", "index", ")", ":", "# handle index specific formatting", "# Note: DatetimeIndex does not use this", "# interface. DatetimeIndex uses matplotlib.date directly", "if", "isinstance", "(", "index", ",", "ABCPeriodIndex", "...
42.976744
20.465116
def _define(self): """ gate sdg a { u1(-pi/2) a; } """ definition = [] q = QuantumRegister(1, "q") rule = [ (U1Gate(-pi/2), [q[0]], []) ] for inst in rule: definition.append(inst) self.definition = definition
[ "def", "_define", "(", "self", ")", ":", "definition", "=", "[", "]", "q", "=", "QuantumRegister", "(", "1", ",", "\"q\"", ")", "rule", "=", "[", "(", "U1Gate", "(", "-", "pi", "/", "2", ")", ",", "[", "q", "[", "0", "]", "]", ",", "[", "]"...
24.416667
10.75
def get_line_rules(declarations): """ Given a list of declarations, return a list of output.Rule objects. This function is wise to line-<foo>, inline-<foo>, and outline-<foo> properties, and will generate multiple LineSymbolizers if necessary. """ property_map = {'line-color': 'stro...
[ "def", "get_line_rules", "(", "declarations", ")", ":", "property_map", "=", "{", "'line-color'", ":", "'stroke'", ",", "'line-width'", ":", "'stroke-width'", ",", "'line-opacity'", ":", "'stroke-opacity'", ",", "'line-join'", ":", "'stroke-linejoin'", ",", "'line-c...
53.516667
37.583333
def insert_many(self, documents, ordered=True, bypass_document_validation=False): """Insert an iterable of documents. >>> db.test.count() 0 >>> result = db.test.insert_many([{'x': i} for i in range(2)]) >>> result.inserted_ids [ObjectId('54f...
[ "def", "insert_many", "(", "self", ",", "documents", ",", "ordered", "=", "True", ",", "bypass_document_validation", "=", "False", ")", ":", "if", "not", "isinstance", "(", "documents", ",", "collections", ".", "Iterable", ")", "or", "not", "documents", ":",...
41.981132
22.509434
def _from_dict(cls, _dict): """Initialize a Element object from a json dictionary.""" args = {} if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'types' in _dict: ...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'location'", "in", "_dict", ":", "args", "[", "'location'", "]", "=", "Location", ".", "_from_dict", "(", "_dict", ".", "get", "(", "'location'", ")", ")", "if", ...
37.8
16.75
def rename_file(self, fname): """Rename file""" path, valid = QInputDialog.getText(self, _('Rename'), _('New name:'), QLineEdit.Normal, osp.basename(fname)) if valid: path = osp.join(osp.dirname(fname), to_text_string(...
[ "def", "rename_file", "(", "self", ",", "fname", ")", ":", "path", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "_", "(", "'Rename'", ")", ",", "_", "(", "'New name:'", ")", ",", "QLineEdit", ".", "Normal", ",", "osp", ".", ...
48.642857
18.714286
def generate_table_from(data): "Output a nicely formatted ascii table" table = Texttable(max_width=120) table.add_row(["view", "method", "status", "count", "minimum", "maximum", "mean", "stdev", "queries", "querytime"]) table.set_cols_align(["l", "l", "l", "r", "r", "r", "r", "r", "r", "r"]) for i...
[ "def", "generate_table_from", "(", "data", ")", ":", "table", "=", "Texttable", "(", "max_width", "=", "120", ")", "table", ".", "add_row", "(", "[", "\"view\"", ",", "\"method\"", ",", "\"status\"", ",", "\"count\"", ",", "\"minimum\"", ",", "\"maximum\"", ...
46.565217
31.173913