text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_notes(self, folderid="", offset=0, limit=10): """Fetch notes :param folderid: The UUID of the folder to fetch notes from :param offset: the pagination offset :param limit: the pagination limit """ if self.standard_grant_type is not "authorization_code": ...
[ "def", "get_notes", "(", "self", ",", "folderid", "=", "\"\"", ",", "offset", "=", "0", ",", "limit", "=", "10", ")", ":", "if", "self", ".", "standard_grant_type", "is", "not", "\"authorization_code\"", ":", "raise", "DeviantartError", "(", "\"Authenticatio...
30.212766
0.006139
def _replace(_self, **kwds): 'Return a new SplitResult object replacing specified fields with new values' result = _self._make(map(kwds.pop, ('scheme', 'netloc', 'path', 'query', 'fragment'), _self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) re...
[ "def", "_replace", "(", "_self", ",", "*", "*", "kwds", ")", ":", "result", "=", "_self", ".", "_make", "(", "map", "(", "kwds", ".", "pop", ",", "(", "'scheme'", ",", "'netloc'", ",", "'path'", ",", "'query'", ",", "'fragment'", ")", ",", "_self",...
54.333333
0.012085
def plot_coupling_matrix(self, lmax, nwin=None, weights=None, mode='full', axes_labelsize=None, tick_labelsize=None, show=True, ax=None, fname=None): """ Plot the multitaper coupling matrix. This matrix relates the global power spectrum ...
[ "def", "plot_coupling_matrix", "(", "self", ",", "lmax", ",", "nwin", "=", "None", ",", "weights", "=", "None", ",", "mode", "=", "'full'", ",", "axes_labelsize", "=", "None", ",", "tick_labelsize", "=", "None", ",", "show", "=", "True", ",", "ax", "="...
43.471429
0.001285
def create_index(self, attr, unique=False, accept_none=False): """Create a new index on a given attribute. If C{unique} is True and records are found in the table with duplicate attribute values, the index is deleted and C{KeyError} is raised. If the table already has an index ...
[ "def", "create_index", "(", "self", ",", "attr", ",", "unique", "=", "False", ",", "accept_none", "=", "False", ")", ":", "if", "attr", "in", "self", ".", "_indexes", ":", "raise", "ValueError", "(", "'index %r already defined for table'", "%", "attr", ")", ...
44.725
0.003829
def _get_transport(self): """ Return the SSH transport to the remote gateway """ if self.ssh_proxy: if isinstance(self.ssh_proxy, paramiko.proxy.ProxyCommand): proxy_repr = repr(self.ssh_proxy.cmd[1]) else: proxy_repr = repr(self.ssh_proxy) ...
[ "def", "_get_transport", "(", "self", ")", ":", "if", "self", ".", "ssh_proxy", ":", "if", "isinstance", "(", "self", ".", "ssh_proxy", ",", "paramiko", ".", "proxy", ".", "ProxyCommand", ")", ":", "proxy_repr", "=", "repr", "(", "self", ".", "ssh_proxy"...
44.05
0.002222
def _prepare_reserved_tokens(reserved_tokens): """Prepare reserved tokens and a regex for splitting them out of strings.""" reserved_tokens = [tf.compat.as_text(tok) for tok in reserved_tokens or []] dups = _find_duplicates(reserved_tokens) if dups: raise ValueError("Duplicates found in tokens: %s" % dups) ...
[ "def", "_prepare_reserved_tokens", "(", "reserved_tokens", ")", ":", "reserved_tokens", "=", "[", "tf", ".", "compat", ".", "as_text", "(", "tok", ")", "for", "tok", "in", "reserved_tokens", "or", "[", "]", "]", "dups", "=", "_find_duplicates", "(", "reserve...
52.75
0.016317
def _set_router_isis_config(self, v, load=False): """ Setter method for router_isis_config, mapped from YANG variable /isis_state/router_isis_config (container) If this variable is read-only (config: false) in the source YANG file, then _set_router_isis_config is considered as a private method. Back...
[ "def", "_set_router_isis_config", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ","...
78.333333
0.005255
def cluster_setup(nodes, pcsclustername='pcscluster', extra_args=None): ''' Setup pacemaker cluster via pcs command nodes a list of nodes which should be set up pcsclustername Name of the Pacemaker cluster (default: pcscluster) extra_args list of extra option for the \'pcs c...
[ "def", "cluster_setup", "(", "nodes", ",", "pcsclustername", "=", "'pcscluster'", ",", "extra_args", "=", "None", ")", ":", "cmd", "=", "[", "'pcs'", ",", "'cluster'", ",", "'setup'", "]", "cmd", "+=", "[", "'--name'", ",", "pcsclustername", "]", "cmd", ...
28.153846
0.003963
def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_nets = [IPv6Network(u'::/8'), IPv6Network(u'100::/8'), IPv6...
[ "def", "is_reserved", "(", "self", ")", ":", "reserved_nets", "=", "[", "IPv6Network", "(", "u'::/8'", ")", ",", "IPv6Network", "(", "u'100::/8'", ")", ",", "IPv6Network", "(", "u'200::/7'", ")", ",", "IPv6Network", "(", "u'400::/6'", ")", ",", "IPv6Network"...
46.5
0.002342
def isCollapsed( self ): """ Returns whether or not this group box is collapsed. :return <bool> """ if not self.isCollapsible(): return False if self._inverted: return self.isChecked() return not self.isChec...
[ "def", "isCollapsed", "(", "self", ")", ":", "if", "not", "self", ".", "isCollapsible", "(", ")", ":", "return", "False", "if", "self", ".", "_inverted", ":", "return", "self", ".", "isChecked", "(", ")", "return", "not", "self", ".", "isChecked", "(",...
26.166667
0.018462
def RLS(anchors, W, r, print_out=False, grid=None, num_points=10): """ Range least squares (RLS) using grid search. Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems". :param anchors: anchor points :param r2: squared distances from anchors to poi...
[ "def", "RLS", "(", "anchors", ",", "W", ",", "r", ",", "print_out", "=", "False", ",", "grid", "=", "None", ",", "num_points", "=", "10", ")", ":", "def", "cost_function", "(", "arr", ")", ":", "X", "=", "np", ".", "c_", "[", "arr", "]", "r_mea...
41.392157
0.002776
def change_node_subscriptions(self, jid, node, subscriptions_to_set): """ Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscr...
[ "def", "change_node_subscriptions", "(", "self", ",", "jid", ",", "node", ",", "subscriptions_to_set", ")", ":", "iq", "=", "aioxmpp", ".", "stanza", ".", "IQ", "(", "type_", "=", "aioxmpp", ".", "structs", ".", "IQType", ".", "SET", ",", "to", "=", "j...
37.722222
0.001436
def quad_tree(self): """Gets the tile in the Microsoft QuadTree format, converted from TMS""" value = '' tms_x, tms_y = self.tms tms_y = (2 ** self.zoom - 1) - tms_y for i in range(self.zoom, 0, -1): digit = 0 mask = 1 << (i - 1) if (tms_x & ma...
[ "def", "quad_tree", "(", "self", ")", ":", "value", "=", "''", "tms_x", ",", "tms_y", "=", "self", ".", "tms", "tms_y", "=", "(", "2", "**", "self", ".", "zoom", "-", "1", ")", "-", "tms_y", "for", "i", "in", "range", "(", "self", ".", "zoom", ...
32.785714
0.006356
def process_firmware_image(compact_firmware_file, ilo_object): """Processes the firmware file. Processing the firmware file entails extracting the firmware file from its compact format. Along with the raw (extracted) firmware file, this method also sends out information of whether or not the extracted ...
[ "def", "process_firmware_image", "(", "compact_firmware_file", ",", "ilo_object", ")", ":", "fw_img_extractor", "=", "firmware_controller", ".", "get_fw_extractor", "(", "compact_firmware_file", ")", "LOG", ".", "debug", "(", "'Extracting firmware file: %s ...'", ",", "co...
50.02439
0.000956
def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]: '''Extend base by updating with the extension. **Arguments** :``base``: dictionary to have keys updated or added :``extension``: dictionary to update base with **Return Value(s)** Resulting dictionary from up...
[ "def", "extend", "(", "base", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "extension", ":", "Dict", "[", "Any", ",", "Any", "]", ")", "->", "Dict", "[", "Any", ",", "Any", "]", ":", "_", "=", "copy", ".", "deepcopy", "(", "base", ")", "_",...
22.555556
0.002364
def managed(name, template_name=None, template_source=None, template_hash=None, template_hash_name=None, saltenv='base', template_engine='jinja', skip_verify=False, context=None, defaults=None, test=F...
[ "def", "managed", "(", "name", ",", "template_name", "=", "None", ",", "template_source", "=", "None", ",", "template_hash", "=", "None", ",", "template_hash_name", "=", "None", ",", "saltenv", "=", "'base'", ",", "template_engine", "=", "'jinja'", ",", "ski...
42.035443
0.002412
def module_function(string): """ Load a function from a python module using a file name, function name specification of format: /path/to/x.py:function_name[:parameter] """ parts = string.split(':', 2) if len(parts) < 2: raise ValueError( "Illegal specification. Should...
[ "def", "module_function", "(", "string", ")", ":", "parts", "=", "string", ".", "split", "(", "':'", ",", "2", ")", "if", "len", "(", "parts", ")", "<", "2", ":", "raise", "ValueError", "(", "\"Illegal specification. Should be module:function[:parameter]\"", "...
30.481481
0.002356
def list_worksheets(self): """ List what worksheet keys exist Returns a list of tuples of the form: (WORKSHEET_ID, WORKSHEET_NAME) You can then retrieve the specific WORKSHEET_ID in the future by constructing a new GSpreadsheet(worksheet=WORKSHEET_ID, ...) ""...
[ "def", "list_worksheets", "(", "self", ")", ":", "worksheets", "=", "self", ".", "get_worksheets", "(", ")", "return", "[", "(", "x", ".", "link", "[", "3", "]", ".", "href", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ",", "x", ".", "ti...
37.833333
0.006452
def offset(self, offset_value): """Return a copy of self, shifted a constant offset. Parameters ---------- offset_value : float Number of pixels to shift the CCDLine. """ new_instance = deepcopy(self) new_instance.poly_funct.coef[0] += offset_value ...
[ "def", "offset", "(", "self", ",", "offset_value", ")", ":", "new_instance", "=", "deepcopy", "(", "self", ")", "new_instance", ".", "poly_funct", ".", "coef", "[", "0", "]", "+=", "offset_value", "return", "new_instance" ]
25.769231
0.005764
def constant_tuple_dict(self): """ Returns ------- constant_tuple_dict: {Constant: ConstantTuple} The set of all constants associated with this mapper """ return {constant_tuple.constant: constant_tuple for name, prior_model in self.prior_model...
[ "def", "constant_tuple_dict", "(", "self", ")", ":", "return", "{", "constant_tuple", ".", "constant", ":", "constant_tuple", "for", "name", ",", "prior_model", "in", "self", ".", "prior_model_tuples", "for", "constant_tuple", "in", "prior_model", ".", "constant_t...
39.4
0.004963
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begi...
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "def", "_int2hex", "(", "number", ")", ":", "return", "\"{0:0{1}x}\"", ".", "format", "(", "number", ",", "2", ")", "try", ":", "unpacked_data", "=", "struct", ".", "unpack...
34.72
0.002242
def add_license( self, url=None, license=None, material=None, imposing=None ): """Add license. :param url: url for the description of the license :type url: string :param license: license type :type license: string :param mat...
[ "def", "add_license", "(", "self", ",", "url", "=", "None", ",", "license", "=", "None", ",", "material", "=", "None", ",", "imposing", "=", "None", ")", ":", "hep_license", "=", "{", "}", "try", ":", "license_from_url", "=", "get_license_from_url", "(",...
24.342857
0.003386
def _coord2offset(self, coord): """Convert a normalized coordinate to an item offset.""" size = self.size offset = 0 for dim, index in enumerate(coord): size //= self._normshape[dim] offset += size * index return offset
[ "def", "_coord2offset", "(", "self", ",", "coord", ")", ":", "size", "=", "self", ".", "size", "offset", "=", "0", "for", "dim", ",", "index", "in", "enumerate", "(", "coord", ")", ":", "size", "//=", "self", ".", "_normshape", "[", "dim", "]", "of...
34.5
0.007067
def dispatch_queue(self): """ Dispatch any queued requests. Called by the debugger when it stops. """ self.queue_lock.acquire() q = list(self.queue) self.queue = [] self.queue_lock.release() log.debug("Dispatching requests: {}".format(q)) ...
[ "def", "dispatch_queue", "(", "self", ")", ":", "self", ".", "queue_lock", ".", "acquire", "(", ")", "q", "=", "list", "(", "self", ".", "queue", ")", "self", ".", "queue", "=", "[", "]", "self", ".", "queue_lock", ".", "release", "(", ")", "log", ...
28
0.004608
def K(self, X, X2=None): """Compute the covariance matrix between X and X2.""" if X2 is None: X2 = X base = np.pi * (X[:, None, :] - X2[None, :, :]) / self.period exp_dist = np.exp( -0.5* np.sum( np.square( np.sin( base ) / self.lengthscale ), axis = -1 ) ) return ...
[ "def", "K", "(", "self", ",", "X", ",", "X2", "=", "None", ")", ":", "if", "X2", "is", "None", ":", "X2", "=", "X", "base", "=", "np", ".", "pi", "*", "(", "X", "[", ":", ",", "None", ",", ":", "]", "-", "X2", "[", "None", ",", ":", "...
37.333333
0.040698
def _construct_opf_model(self, case): """ Returns an OPF model. """ # Zero the case result attributes. self.case.reset() base_mva = case.base_mva # Check for one reference bus. oneref, refs = self._ref_check(case) if not oneref: #return {"status": "error...
[ "def", "_construct_opf_model", "(", "self", ",", "case", ")", ":", "# Zero the case result attributes.", "self", ".", "case", ".", "reset", "(", ")", "base_mva", "=", "case", ".", "base_mva", "# Check for one reference bus.", "oneref", ",", "refs", "=", "self", ...
31.386667
0.003295
def model(method): """Use this to decorate methods that expect a model.""" def wrapper(self, *args, **kwargs): if self.__model__ is None: raise ValidationError( 'You cannot perform CRUD operations without selecting a ' 'model first.', ...
[ "def", "model", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "__model__", "is", "None", ":", "raise", "ValidationError", "(", "'You cannot perform CRUD operations without sele...
39.9
0.004902
def add_headers(self, **headers): """packing dicts into typecode pyclass, may fail if typecodes are used in the body (when asdict=True) """ class _holder: pass def _remap(pyobj, **d): pyobj.__dict__ = d for k,v in pyobj.__dict__.items(): if...
[ "def", "add_headers", "(", "self", ",", "*", "*", "headers", ")", ":", "class", "_holder", ":", "pass", "def", "_remap", "(", "pyobj", ",", "*", "*", "d", ")", ":", "pyobj", ".", "__dict__", "=", "d", "for", "k", ",", "v", "in", "pyobj", ".", "...
34.65625
0.014035
def generate_base_grid(self, vtk_filename=None): """ Run first step of algorithm. Next step is split_voxels :param vtk_filename: :return: """ nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize) self.add_nodes(nd) self.add_edges(ed, ed_dir, ...
[ "def", "generate_base_grid", "(", "self", ",", "vtk_filename", "=", "None", ")", ":", "nd", ",", "ed", ",", "ed_dir", "=", "self", ".", "gen_grid_fcn", "(", "self", ".", "data", ".", "shape", ",", "self", ".", "voxelsize", ")", "self", ".", "add_nodes"...
33.916667
0.004785
def check_class(self, id_, class_, lineno, scope=None, show_error=True): """ Check the id is either undefined or defined with the given class. - If the identifier (e.g. variable) does not exists means it's undeclared, and returns True (OK). - If the identifier exists, but its cl...
[ "def", "check_class", "(", "self", ",", "id_", ",", "class_", ",", "lineno", ",", "scope", "=", "None", ",", "show_error", "=", "True", ")", ":", "assert", "CLASS", ".", "is_valid", "(", "class_", ")", "entry", "=", "self", ".", "get_entry", "(", "id...
36.8125
0.001654
def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname
[ "def", "ip_to_host", "(", "ip", ")", ":", "try", ":", "hostname", ",", "aliaslist", ",", "ipaddrlist", "=", "socket", ".", "gethostbyaddr", "(", "ip", ")", "except", "Exception", "as", "exc", ":", "log", ".", "debug", "(", "'salt.utils.network.ip_to_host(%r)...
28.9
0.003356
def notification( self, topic_name, topic_project=None, custom_attributes=None, event_types=None, blob_name_prefix=None, payload_format=NONE_PAYLOAD_FORMAT, ): """Factory: create a notification resource for the bucket. See: :class:`.BucketNot...
[ "def", "notification", "(", "self", ",", "topic_name", ",", "topic_project", "=", "None", ",", "custom_attributes", "=", "None", ",", "event_types", "=", "None", ",", "blob_name_prefix", "=", "None", ",", "payload_format", "=", "NONE_PAYLOAD_FORMAT", ",", ")", ...
28.541667
0.004237
def default_storable(python_type, exposes=None, version=None, storable_type=None, peek=default_peek): """ Default mechanics for building the storable instance for a type. Arguments: python_type (type): type. exposes (iterable): attributes exposed by the type. version (tuple): ver...
[ "def", "default_storable", "(", "python_type", ",", "exposes", "=", "None", ",", "version", "=", "None", ",", "storable_type", "=", "None", ",", "peek", "=", "default_peek", ")", ":", "if", "not", "exposes", ":", "for", "extension", "in", "expose_extensions"...
29.405405
0.007117
def _norm(self, x): """Compute the safe norm.""" return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)
[ "def", "_norm", "(", "self", ",", "x", ")", ":", "return", "tf", ".", "sqrt", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "x", ")", ",", "keepdims", "=", "True", ",", "axis", "=", "-", "1", ")", "+", "1e-7", ")" ]
43
0.007634
def recommend(self, limit=10): ''' Listup arms and expected value. Args: limit: Length of the list. Returns: [Tuple(`Arms master id`, `expected value`)] ''' expected_list = [(arm_id, beta_dist.expected_value()) for arm_id, beta_dist in self....
[ "def", "recommend", "(", "self", ",", "limit", "=", "10", ")", ":", "expected_list", "=", "[", "(", "arm_id", ",", "beta_dist", ".", "expected_value", "(", ")", ")", "for", "arm_id", ",", "beta_dist", "in", "self", ".", "__beta_dist_dict", ".", "items", ...
34.615385
0.006494
def copy_style(shapefile_path): """Copy style from the OSM resource directory to the output path. .. versionadded: 3.3 :param shapefile_path: Path to the shapefile that should get the path added. :type shapefile_path: basestring """ source_qml_path = resourc...
[ "def", "copy_style", "(", "shapefile_path", ")", ":", "source_qml_path", "=", "resources_path", "(", "'petabencana'", ",", "'flood-style.qml'", ")", "output_qml_path", "=", "shapefile_path", ".", "replace", "(", "'shp'", ",", "'qml'", ")", "LOGGER", ".", "info", ...
39.923077
0.003766
def optimize(self, to_buy, to_sell): ''' Buy sid * parameters['buy_amount'] * parameters['scale'][sid] Sell sid * parameters['sell_amount'] * parameters['scale'][sid] ''' allocations = {} # Process every stock the same way for s in to_buy: quantity = ...
[ "def", "optimize", "(", "self", ",", "to_buy", ",", "to_sell", ")", ":", "allocations", "=", "{", "}", "# Process every stock the same way", "for", "s", "in", "to_buy", ":", "quantity", "=", "self", ".", "properties", ".", "get", "(", "'buy_amount'", ",", ...
37.035714
0.00188
def handle_job_exception(self, exception, variables=None): """ Makes and returns a last-ditch error response. :param exception: The exception that happened :type exception: Exception :param variables: A dictionary of context-relevant variables to include in the error response ...
[ "def", "handle_job_exception", "(", "self", ",", "exception", ",", "variables", "=", "None", ")", ":", "# Get the error and traceback if we can", "# noinspection PyBroadException", "try", ":", "error_str", ",", "traceback_str", "=", "six", ".", "text_type", "(", "exce...
41.581395
0.004918
def local(self): """ Access the local :returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalList :rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalList """ if self._local is None: self._local = LocalList( ...
[ "def", "local", "(", "self", ")", ":", "if", "self", ".", "_local", "is", "None", ":", "self", ".", "_local", "=", "LocalList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "country_co...
34.714286
0.008016
def process_species(self, limit): """ Loop through the xml file and process the species. We add elements to the graph, and store the id-to-label in the label_hash dict. :param limit: :return: """ myfile = '/'.join((self.rawdir, self.files['data']['file']))...
[ "def", "process_species", "(", "self", ",", "limit", ")", ":", "myfile", "=", "'/'", ".", "join", "(", "(", "self", ".", "rawdir", ",", "self", ".", "files", "[", "'data'", "]", "[", "'file'", "]", ")", ")", "fh", "=", "gzip", ".", "open", "(", ...
40.888889
0.003984
async def delete(self, *names): """ "Delete one or more keys specified by ``names``" Cluster impl: Iterate all keys and send DELETE for each key. This will go a lot slower than a normal delete call in StrictRedis. Operation is no longer atomic. """ ...
[ "async", "def", "delete", "(", "self", ",", "*", "names", ")", ":", "count", "=", "0", "for", "arg", "in", "names", ":", "count", "+=", "await", "self", ".", "execute_command", "(", "'DEL'", ",", "arg", ")", "return", "count" ]
26.875
0.004494
def convert_cifar100(directory, output_directory, output_filename='cifar100.hdf5'): """Converts the CIFAR-100 dataset to HDF5. Converts the CIFAR-100 dataset to an HDF5 dataset compatible with :class:`fuel.datasets.CIFAR100`. The converted dataset is saved as 'cifar100.hdf5'. ...
[ "def", "convert_cifar100", "(", "directory", ",", "output_directory", ",", "output_filename", "=", "'cifar100.hdf5'", ")", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "output_directory", ",", "output_filename", ")", "h5file", "=", "h5py", ".", ...
36.716049
0.000327
def tfpdef(self, ident_tok, annotation_opt): """(3.0-) tfpdef: NAME [':' test]""" if annotation_opt: colon_loc, annotation = annotation_opt return self._arg(ident_tok, colon_loc, annotation) return self._arg(ident_tok)
[ "def", "tfpdef", "(", "self", ",", "ident_tok", ",", "annotation_opt", ")", ":", "if", "annotation_opt", ":", "colon_loc", ",", "annotation", "=", "annotation_opt", "return", "self", ".", "_arg", "(", "ident_tok", ",", "colon_loc", ",", "annotation", ")", "r...
43.5
0.007519
def get_root_object(models): """ Read list of models and returns a Root object with the proper models added. """ root = napalm_yang.base.Root() for model in models: current = napalm_yang for p in model.split("."): current = getattr(current, p) root.add_model(curr...
[ "def", "get_root_object", "(", "models", ")", ":", "root", "=", "napalm_yang", ".", "base", ".", "Root", "(", ")", "for", "model", "in", "models", ":", "current", "=", "napalm_yang", "for", "p", "in", "model", ".", "split", "(", "\".\"", ")", ":", "c...
25.307692
0.002933
def verify_sauce_connect_is_running(self, options): """ Start Sauce Connect, if it isn't already running. Returns a tuple of two elements: * A boolean which is True if Sauce Connect is now running * The Popen object representing the process so it can be terminated lat...
[ "def", "verify_sauce_connect_is_running", "(", "self", ",", "options", ")", ":", "sc_path", "=", "settings", ".", "SELENIUM_SAUCE_CONNECT_PATH", "if", "len", "(", "sc_path", ")", "<", "2", ":", "self", ".", "stdout", ".", "write", "(", "'You need to configure SE...
45.170213
0.001383
def move_pos(line=1, column=1, file=sys.stdout): """ Move the cursor to a new position. Values are 1-based, and default to 1. Esc[<line>;<column>H or Esc[<line>;<column>f """ move.pos(line=line, col=column).write(file=file)
[ "def", "move_pos", "(", "line", "=", "1", ",", "column", "=", "1", ",", "file", "=", "sys", ".", "stdout", ")", ":", "move", ".", "pos", "(", "line", "=", "line", ",", "col", "=", "column", ")", ".", "write", "(", "file", "=", "file", ")" ]
28.888889
0.003731
async def deaths(self, root): """Causes of death in the nation, as percentages. Returns ------- an :class:`ApiQuery` of dict with keys of str and values of float """ return { elem.get('type'): float(elem.text) for elem in root.find('DEATHS') ...
[ "async", "def", "deaths", "(", "self", ",", "root", ")", ":", "return", "{", "elem", ".", "get", "(", "'type'", ")", ":", "float", "(", "elem", ".", "text", ")", "for", "elem", "in", "root", ".", "find", "(", "'DEATHS'", ")", "}" ]
28.545455
0.006173
def func_globals_inject(func, **overrides): ''' Override specific variables within a function's global context. ''' # recognize methods if hasattr(func, 'im_func'): func = func.__func__ # Get a reference to the function globals dictionary func_globals = func.__globals__ # Save t...
[ "def", "func_globals_inject", "(", "func", ",", "*", "*", "overrides", ")", ":", "# recognize methods", "if", "hasattr", "(", "func", ",", "'im_func'", ")", ":", "func", "=", "func", ".", "__func__", "# Get a reference to the function globals dictionary", "func_glob...
31.676471
0.000901
def smart_convert(original, colorkey, pixelalpha): """ this method does several tests on a surface to determine the optimal flags and pixel format for each tile surface. this is done for the best rendering speeds and removes the need to convert() the images on your own """ tile_size = origi...
[ "def", "smart_convert", "(", "original", ",", "colorkey", ",", "pixelalpha", ")", ":", "tile_size", "=", "original", ".", "get_size", "(", ")", "threshold", "=", "127", "# the default", "try", ":", "# count the number of pixels in the tile that are not transparent", "...
32.675676
0.001606
async def get_current_directory(self): """ :py:func:`asyncio.coroutine` Getting current working directory. :rtype: :py:class:`pathlib.PurePosixPath` """ code, info = await self.command("PWD", "257") directory = self.parse_directory_response(info[-1]) ret...
[ "async", "def", "get_current_directory", "(", "self", ")", ":", "code", ",", "info", "=", "await", "self", ".", "command", "(", "\"PWD\"", ",", "\"257\"", ")", "directory", "=", "self", ".", "parse_directory_response", "(", "info", "[", "-", "1", "]", ")...
29.363636
0.006006
def get_format_implementation(ext, format_name=None): """Return the implementation for the desired format""" # remove pre-extension if any ext = '.' + ext.split('.')[-1] formats_for_extension = [] for fmt in JUPYTEXT_FORMATS: if fmt.extension == ext: if fmt.format_name == format...
[ "def", "get_format_implementation", "(", "ext", ",", "format_name", "=", "None", ")", ":", "# remove pre-extension if any", "ext", "=", "'.'", "+", "ext", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "formats_for_extension", "=", "[", "]", "for", "fm...
46.35
0.005285
def register_data(self, typename, value): """Registers a data product, raising if a product was already registered. :API: public :param typename: The type of product to register a value for. :param value: The data product to register under `typename`. :returns: The registered `value`. :raises:...
[ "def", "register_data", "(", "self", ",", "typename", ",", "value", ")", ":", "if", "typename", "in", "self", ".", "data_products", ":", "raise", "ProductError", "(", "'Already have a product registered for {}, cannot over-write with {}'", ".", "format", "(", "typenam...
43.933333
0.005944
def getcolor(spec): """ Turn optional color string spec into an array. """ if isinstance(spec, str): from matplotlib import colors return asarray(colors.hex2color(colors.cnames[spec])) else: return spec
[ "def", "getcolor", "(", "spec", ")", ":", "if", "isinstance", "(", "spec", ",", "str", ")", ":", "from", "matplotlib", "import", "colors", "return", "asarray", "(", "colors", ".", "hex2color", "(", "colors", ".", "cnames", "[", "spec", "]", ")", ")", ...
26.444444
0.004065
def propagateFrom(self, startLayer, **args): """ Propagates activation through the network. Optionally, takes input layer names as keywords, and their associated activations. If input layer(s) are given, then propagate() will return the output layer's activation. If there is more than ...
[ "def", "propagateFrom", "(", "self", ",", "startLayer", ",", "*", "*", "args", ")", ":", "for", "layerName", "in", "args", ":", "self", "[", "layerName", "]", ".", "copyActivations", "(", "args", "[", "layerName", "]", ")", "# initialize netinput:", "start...
43.555556
0.007069
def apply_same_chip_constraints(vertices_resources, nets, constraints): """Modify a set of vertices_resources, nets and constraints to account for all SameChipConstraints. To allow placement algorithms to handle SameChipConstraints without any special cases, Vertices identified in a SameChipConstraint ...
[ "def", "apply_same_chip_constraints", "(", "vertices_resources", ",", "nets", ",", "constraints", ")", ":", "# Make a copy of the basic structures to be modified by this function", "vertices_resources", "=", "vertices_resources", ".", "copy", "(", ")", "nets", "=", "nets", ...
43.081301
0.000184
def _RunAction(self, rule, client_id): """Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started. """ actions_count = 0 try: if ...
[ "def", "_RunAction", "(", "self", ",", "rule", ",", "client_id", ")", ":", "actions_count", "=", "0", "try", ":", "if", "self", ".", "_CheckIfHuntTaskWasAssigned", "(", "client_id", ",", "rule", ".", "hunt_id", ")", ":", "logging", ".", "info", "(", "\"F...
34.526316
0.00593
def is_newer_than(pth1, pth2): """ Return true if either file pth1 or file pth2 don't exist, or if pth1 has been modified more recently than pth2 """ return not os.path.exists(pth1) or not os.path.exists(pth2) or \ os.stat(pth1).st_mtime > os.stat(pth2).st_mtime
[ "def", "is_newer_than", "(", "pth1", ",", "pth2", ")", ":", "return", "not", "os", ".", "path", ".", "exists", "(", "pth1", ")", "or", "not", "os", ".", "path", ".", "exists", "(", "pth2", ")", "or", "os", ".", "stat", "(", "pth1", ")", ".", "s...
35.375
0.006897
def app(session_id, app, bind, port): """ Run a local proxy to a service provided by Backend.AI compute sessions. The type of proxy depends on the app definition: plain TCP or HTTP. \b SESSID: The compute session ID. APP: The name of service provided by the given session. """ api_sessi...
[ "def", "app", "(", "session_id", ",", "app", ",", "bind", ",", "port", ")", ":", "api_session", "=", "None", "runner", "=", "None", "async", "def", "app_setup", "(", ")", ":", "nonlocal", "api_session", ",", "runner", "loop", "=", "current_loop", "(", ...
33.9
0.000717
def date(self) -> Optional[DateHeader]: """The ``Date`` header.""" try: return cast(DateHeader, self[b'date'][0]) except (KeyError, IndexError): return None
[ "def", "date", "(", "self", ")", "->", "Optional", "[", "DateHeader", "]", ":", "try", ":", "return", "cast", "(", "DateHeader", ",", "self", "[", "b'date'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "IndexError", ")", ":", "return", ...
33.166667
0.009804
def on(self): """Send an ON message to device group.""" on_command = ExtendedSend(self._address, COMMAND_LIGHT_ON_0X11_NONE, self._udata, cmd2=0xff) on_command.set_checksum() self._send_...
[ "def", "on", "(", "self", ")", ":", "on_command", "=", "ExtendedSend", "(", "self", ".", "_address", ",", "COMMAND_LIGHT_ON_0X11_NONE", ",", "self", ".", "_udata", ",", "cmd2", "=", "0xff", ")", "on_command", ".", "set_checksum", "(", ")", "self", ".", "...
44.75
0.005479
def get_compression_type(self, file_name): """ Determine compression type for a given file using its extension. :param file_name: a given file name :type file_name: str """ ext = os.path.splitext(file_name)[1] if ext == '.gz': self.ctype...
[ "def", "get_compression_type", "(", "self", ",", "file_name", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "[", "1", "]", "if", "ext", "==", "'.gz'", ":", "self", ".", "ctype", "=", "'gzip'", "elif", "ext", "==", ...
27.055556
0.003968
def restricted_cover(l, succsOf): """ Returns a restricted <succsOf> which only takes and yields values from <l> """ fzl = frozenset(l) lut = dict() for i in l: lut[i] = fzl.intersection(succsOf(i)) return lambda x: lut[x]
[ "def", "restricted_cover", "(", "l", ",", "succsOf", ")", ":", "fzl", "=", "frozenset", "(", "l", ")", "lut", "=", "dict", "(", ")", "for", "i", "in", "l", ":", "lut", "[", "i", "]", "=", "fzl", ".", "intersection", "(", "succsOf", "(", "i", ")...
31.375
0.007752
def _spelling_pipeline(self, sources, options, personal_dict): """Check spelling pipeline.""" for source in self._pipeline_step(sources, options, personal_dict): # Don't waste time on empty strings if source._has_error(): yield Results([], source.context, source....
[ "def", "_spelling_pipeline", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ")", ":", "for", "source", "in", "self", ".", "_pipeline_step", "(", "sources", ",", "options", ",", "personal_dict", ")", ":", "# Don't waste time on empty strings", ...
46.764706
0.003697
def dict_fields(obj, parent=[]): """ reads a dictionary and returns a list of fields cojoined with a dot notation args: obj: the dictionary to parse parent: name for a parent key. used with a recursive call """ rtn_obj = {} for key, value in obj.items(): n...
[ "def", "dict_fields", "(", "obj", ",", "parent", "=", "[", "]", ")", ":", "rtn_obj", "=", "{", "}", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "new_key", "=", "parent", "+", "[", "key", "]", "new_key", "=", "\".\"", "...
30.047619
0.001536
def binary_cross_entropy_loss_with_logits(x, target, name=None): """Calculates the binary cross entropy between sigmoid(x) and target. Expects unscaled logits. Do not pass in results of sigmoid operation. Args: x: the calculated pre-sigmoid values target: the desired values. name: the name for this ...
[ "def", "binary_cross_entropy_loss_with_logits", "(", "x", ",", "target", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "'binary_cross_entropy_with_logits'", ",", "[", "x", ",", "target", "]", ")", "as", "scope", ":", ...
40.095238
0.00348
def depends_on_helper(obj): """ Handles using .title if the given object is a troposphere resource. If the given object is a troposphere resource, use the `.title` attribute of that resource. If it's a string, just use the string. This should allow more pythonic use of DependsOn. """ if isinsta...
[ "def", "depends_on_helper", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "AWSObject", ")", ":", "return", "obj", ".", "title", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "list", "(", "map", "(", "depends_on_helper", ...
37.5
0.002169
def from_spec(cls, spec): """ Load a Custodian instance where the jobs are specified from a structure and a spec dict. This allows simple custom job sequences to be constructed quickly via a YAML file. Args: spec (dict): A dict specifying job. A sample of the dict in...
[ "def", "from_spec", "(", "cls", ",", "spec", ")", ":", "dec", "=", "MontyDecoder", "(", ")", "def", "load_class", "(", "dotpath", ")", ":", "modname", ",", "classname", "=", "dotpath", ".", "rsplit", "(", "\".\"", ",", "1", ")", "mod", "=", "__import...
37.089888
0.00118
def download_files(fapi, file_name, conf, use_cache, cache_dir=None): """ Downloads translated versions of the files """ retrieval_type = conf.get('retrieval-type', 'published') include_original_strings = 'true' if conf.get('include-original-strings', False) else 'false' save_pattern...
[ "def", "download_files", "(", "fapi", ",", "file_name", ",", "conf", ",", "use_cache", ",", "cache_dir", "=", "None", ")", ":", "retrieval_type", "=", "conf", ".", "get", "(", "'retrieval-type'", ",", "'published'", ")", "include_original_strings", "=", "'true...
48.715909
0.006401
def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent': """Return a new schedule with `schedule` inserted within `self` at `start_time`. Args: start_time: time to be inserted schedule: schedule to be inserted """ return ops.insert(s...
[ "def", "insert", "(", "self", ",", "start_time", ":", "int", ",", "schedule", ":", "ScheduleComponent", ")", "->", "'ScheduleComponent'", ":", "return", "ops", ".", "insert", "(", "self", ",", "start_time", ",", "schedule", ")" ]
42.375
0.011561
def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size): """Gather top beams from nested structure.""" _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size) return _gather_beams(nested, topk_indexes, batch_size, beam_size)
[ "def", "_gather_topk_beams", "(", "nested", ",", "score_or_log_prob", ",", "batch_size", ",", "beam_size", ")", ":", "_", ",", "topk_indexes", "=", "tf", ".", "nn", ".", "top_k", "(", "score_or_log_prob", ",", "k", "=", "beam_size", ")", "return", "_gather_b...
62.5
0.01581
def slice_plot(netin, ax, nodelabels=None, timelabels=None, communities=None, plotedgeweights=False, edgeweightscalar=1, timeunit='', linestyle='k-', cmap=None, nodesize=100, nodekwargs=None, edgekwargs=None): r''' Fuction draws "slice graph" and exports axis handles Parameters ---------- netin ...
[ "def", "slice_plot", "(", "netin", ",", "ax", ",", "nodelabels", "=", "None", ",", "timelabels", "=", "None", ",", "communities", "=", "None", ",", "plotedgeweights", "=", "False", ",", "edgeweightscalar", "=", "1", ",", "timeunit", "=", "''", ",", "line...
34.159091
0.00194
def PreparePairedSequenceBatch(source, target_in, pad=0): """Build masks for this batch. Args: source: (batch, source_len) array of integer-coded symbols for inputs target_in: (batch, batch_len) array of integer-coded symbols for targets pad: int: the padding symbol used to pad the above Returns: ...
[ "def", "PreparePairedSequenceBatch", "(", "source", ",", "target_in", ",", "pad", "=", "0", ")", ":", "target", "=", "target_in", "[", ":", ",", ":", "-", "1", "]", "target_y", "=", "target_in", "[", ":", ",", "1", ":", "]", "source_mask", "=", "np",...
40.818182
0.010881
def remove(name=None, index=None): """ remove the specified configuration """ removed = False count = 1 for configuration in _CONFIG.sections(): if index != None: if count == index: _CONFIG.remove_section(configuration) removed = True ...
[ "def", "remove", "(", "name", "=", "None", ",", "index", "=", "None", ")", ":", "removed", "=", "False", "count", "=", "1", "for", "configuration", "in", "_CONFIG", ".", "sections", "(", ")", ":", "if", "index", "!=", "None", ":", "if", "count", "=...
24.107143
0.004274
def _dataset_concat(datasets, dim, data_vars, coords, compat, positions): """ Concatenate a sequence of datasets along a new or existing dimension """ from .dataset import Dataset if compat not in ['equals', 'identical']: raise ValueError("compat=%r invalid: must be 'equals' " ...
[ "def", "_dataset_concat", "(", "datasets", ",", "dim", ",", "data_vars", ",", "coords", ",", "compat", ",", "positions", ")", ":", "from", ".", "dataset", "import", "Dataset", "if", "compat", "not", "in", "[", "'equals'", ",", "'identical'", "]", ":", "r...
41.45098
0.000231
def begin_subsegment(self, name, namespace='local'): """ Begin a new subsegment. If there is open subsegment, the newly created subsegment will be the child of latest opened subsegment. If not, it will be the child of the current open segment. :param str name: the name o...
[ "def", "begin_subsegment", "(", "self", ",", "name", ",", "namespace", "=", "'local'", ")", ":", "segment", "=", "self", ".", "current_segment", "(", ")", "if", "not", "segment", ":", "log", ".", "warning", "(", "\"No segment found, cannot begin subsegment %s.\"...
33.958333
0.002387
def relabel(self, mapping): """ Rename ConfusionMatrix classes. :param mapping: mapping dictionary :type mapping : dict :return: None """ if not isinstance(mapping, dict): raise pycmMatrixError(MAPPING_FORMAT_ERROR) if self.classes != list(map...
[ "def", "relabel", "(", "self", ",", "mapping", ")", ":", "if", "not", "isinstance", "(", "mapping", ",", "dict", ")", ":", "raise", "pycmMatrixError", "(", "MAPPING_FORMAT_ERROR", ")", "if", "self", ".", "classes", "!=", "list", "(", "mapping", ".", "key...
39.783784
0.001326
def input_size(self): '''Size of layer input (for layers with one input).''' shape = self.input_shape if shape is None: raise util.ConfigurationError( 'undefined input size for layer "{}"'.format(self.name)) return shape[-1]
[ "def", "input_size", "(", "self", ")", ":", "shape", "=", "self", ".", "input_shape", "if", "shape", "is", "None", ":", "raise", "util", ".", "ConfigurationError", "(", "'undefined input size for layer \"{}\"'", ".", "format", "(", "self", ".", "name", ")", ...
39.714286
0.007042
def check_pending_target(self, scan_id, multiscan_proc): """ Check if a scan process is still alive. In case the process finished or is stopped, removes the process from the multiscan _process list. Processes dead and with progress < 100% are considered stopped or with failures. ...
[ "def", "check_pending_target", "(", "self", ",", "scan_id", ",", "multiscan_proc", ")", ":", "for", "running_target_proc", ",", "running_target_id", "in", "multiscan_proc", ":", "if", "not", "running_target_proc", ".", "is_alive", "(", ")", ":", "target_prog", "="...
48.304348
0.001765
def ImportFile(store, filename, start): """Import hashes from 'filename' into 'store'.""" with io.open(filename, "r") as fp: reader = csv.Reader(fp.read()) i = 0 current_row = None product_code_list = [] op_system_code_list = [] for row in reader: # Skip first row. i += 1 i...
[ "def", "ImportFile", "(", "store", ",", "filename", ",", "start", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "\"r\"", ")", "as", "fp", ":", "reader", "=", "csv", ".", "Reader", "(", "fp", ".", "read", "(", ")", ")", "i", "=", "0...
32.363636
0.01636
def _pkl_periodogram(lspinfo, plotdpi=100, override_pfmethod=None): '''This returns the periodogram plot PNG as base64, plus info as a dict. Parameters ---------- lspinfo : dict This is an lspinfo dict containing results from a period-finding f...
[ "def", "_pkl_periodogram", "(", "lspinfo", ",", "plotdpi", "=", "100", ",", "override_pfmethod", "=", "None", ")", ":", "# get the appropriate plot ylabel", "pgramylabel", "=", "PLOTYLABELS", "[", "lspinfo", "[", "'method'", "]", "]", "# get the periods and lspvals fr...
37.275168
0.003858
def create(vm_): ''' get the system build going ''' creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) cloud_profile = config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('token',) ) group = config.get...
[ "def", "create", "(", "vm_", ")", ":", "creds", "=", "get_creds", "(", ")", "clc", ".", "v1", ".", "SetCredentials", "(", "creds", "[", "\"token\"", "]", ",", "creds", "[", "\"token_pass\"", "]", ")", "cloud_profile", "=", "config", ".", "is_provider_con...
37.266667
0.000871
async def _handle_conversation_delta(self, conversation): """Receive Conversation delta and create or update the conversation. Args: conversation: hangouts_pb2.Conversation instance Raises: NetworkError: A request to fetch the complete conversation failed. """ ...
[ "async", "def", "_handle_conversation_delta", "(", "self", ",", "conversation", ")", ":", "conv_id", "=", "conversation", ".", "conversation_id", ".", "id", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", ...
39.411765
0.002915
def validate_manifest_against_schema(manifest: Dict[str, Any]) -> None: """ Load and validate manifest against schema located at MANIFEST_SCHEMA_PATH. """ schema_data = _load_schema_data() try: validate(manifest, schema_data) except jsonValidationError as e: raise ValidationE...
[ "def", "validate_manifest_against_schema", "(", "manifest", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "schema_data", "=", "_load_schema_data", "(", ")", "try", ":", "validate", "(", "manifest", ",", "schema_data", ")", "except", "json...
33.538462
0.002232
def decode(self, encoded_payload): """Decode a transmitted payload.""" self.packets = [] while encoded_payload: if six.byte2int(encoded_payload[0:1]) <= 1: packet_len = 0 i = 1 while six.byte2int(encoded_payload[i:i + 1]) != 255: ...
[ "def", "decode", "(", "self", ",", "encoded_payload", ")", ":", "self", ".", "packets", "=", "[", "]", "while", "encoded_payload", ":", "if", "six", ".", "byte2int", "(", "encoded_payload", "[", "0", ":", "1", "]", ")", "<=", "1", ":", "packet_len", ...
49.117647
0.001174
def reset_actions(self): """ Clears actions that are already stored locally and on the remote end """ if self._driver.w3c: self.w3c_actions.clear_actions() self._actions = []
[ "def", "reset_actions", "(", "self", ")", ":", "if", "self", ".", "_driver", ".", "w3c", ":", "self", ".", "w3c_actions", ".", "clear_actions", "(", ")", "self", ".", "_actions", "=", "[", "]" ]
32
0.013043
def from_dict(self, document): """Create a prediction image set resource from a dictionary serialization. Parameters ---------- document : dict Dictionary serialization of the resource Returns ------- PredictionImageSetHandle Hand...
[ "def", "from_dict", "(", "self", ",", "document", ")", ":", "return", "PredictionImageSetHandle", "(", "str", "(", "document", "[", "'_id'", "]", ")", ",", "document", "[", "'properties'", "]", ",", "[", "PredictionImageSet", ".", "from_dict", "(", "img", ...
30.041667
0.002688
def update_single_grading_period(self, id, course_id, grading_periods_end_date, grading_periods_start_date, grading_periods_weight=None): """ Update a single grading period. Update an existing grading period. """ path = {} data = {} params = {} ...
[ "def", "update_single_grading_period", "(", "self", ",", "id", ",", "course_id", ",", "grading_periods_end_date", ",", "grading_periods_start_date", ",", "grading_periods_weight", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "="...
44.181818
0.004027
def finish(): """Print warning about interrupt and empty the job queue.""" out.warn("Interrupted!") for t in threads: t.stop() jobs.clear() out.warn("Waiting for download threads to finish.")
[ "def", "finish", "(", ")", ":", "out", ".", "warn", "(", "\"Interrupted!\"", ")", "for", "t", "in", "threads", ":", "t", ".", "stop", "(", ")", "jobs", ".", "clear", "(", ")", "out", ".", "warn", "(", "\"Waiting for download threads to finish.\"", ")" ]
30.428571
0.004566
def update_or_create(cls, external_gateway, name, with_status=False, **kw): """ Update or create external endpoints for the specified external gateway. An ExternalEndpoint is considered unique based on the IP address for the endpoint (you cannot add two external endpoints with the same I...
[ "def", "update_or_create", "(", "cls", ",", "external_gateway", ",", "name", ",", "with_status", "=", "False", ",", "*", "*", "kw", ")", ":", "if", "'address'", "in", "kw", ":", "external_endpoint", "=", "external_gateway", ".", "external_endpoint", ".", "ge...
50.911111
0.005567
def not_empty(message=None) -> Filter_T: """ Validate any object to ensure it's not empty (is None or has no elements). """ def validate(value): if value is None: _raise_failure(message) if hasattr(value, '__len__') and value.__len__() == 0: _raise_failure(messag...
[ "def", "not_empty", "(", "message", "=", "None", ")", "->", "Filter_T", ":", "def", "validate", "(", "value", ")", ":", "if", "value", "is", "None", ":", "_raise_failure", "(", "message", ")", "if", "hasattr", "(", "value", ",", "'__len__'", ")", "and"...
27.076923
0.002747
def _compute(self): """ Compute parameters necessary for later steps within the rendering process """ for serie in self.series: serie.points, serie.outliers = \ self._box_points(serie.values, self.box_mode) self._x_pos = [(i + .5) / self._orde...
[ "def", "_compute", "(", "self", ")", ":", "for", "serie", "in", "self", ".", "series", ":", "serie", ".", "points", ",", "serie", ".", "outliers", "=", "self", ".", "_box_points", "(", "serie", ".", "values", ",", "self", ".", "box_mode", ")", "self"...
32.733333
0.00396
def _maybe_convert_usecols(usecols): """ Convert `usecols` into a compatible format for parsing in `parsers.py`. Parameters ---------- usecols : object The use-columns object to potentially convert. Returns ------- converted : object The compatible format of `usecols`. ...
[ "def", "_maybe_convert_usecols", "(", "usecols", ")", ":", "if", "usecols", "is", "None", ":", "return", "usecols", "if", "is_integer", "(", "usecols", ")", ":", "warnings", ".", "warn", "(", "(", "\"Passing in an integer for `usecols` has been \"", "\"deprecated. P...
27
0.001277
def load(self, reload=False, require_load=False): # type: (bool, bool) -> None """ Searches for an appropriate config file. If found, loads the file into the current instance. This method can also be used to reload a configuration. Note that you may want to set ``reload`` to ``Tr...
[ "def", "load", "(", "self", ",", "reload", "=", "False", ",", "require_load", "=", "False", ")", ":", "# type: (bool, bool) -> None", "if", "reload", ":", "# pragma: no cover", "self", ".", "config", "=", "None", "# only load the config if necessary (or explicitly req...
48.737705
0.001319
def parse_sargasso_logs(self, f): """ Parse the sargasso log file. """ species_name = list() items = list() header = list() is_first_line = True for l in f['f'].splitlines(): s = l.split(",") # Check that this actually is a Sargasso file ...
[ "def", "parse_sargasso_logs", "(", "self", ",", "f", ")", ":", "species_name", "=", "list", "(", ")", "items", "=", "list", "(", ")", "header", "=", "list", "(", ")", "is_first_line", "=", "True", "for", "l", "in", "f", "[", "'f'", "]", ".", "split...
39.253731
0.008531
def _make_record(self, parent, gline): """Process next record. This method created new record from the line read from file if needed and/or updates its parent record. If the parent record tag is ``BLOB`` and new record tag is ``CONT`` then record is skipped entirely and None is ...
[ "def", "_make_record", "(", "self", ",", "parent", ",", "gline", ")", ":", "if", "parent", "and", "gline", ".", "tag", "in", "(", "\"CONT\"", ",", "\"CONC\"", ")", ":", "# concatenate, only for non-BLOBs", "if", "parent", ".", "tag", "!=", "\"BLOB\"", ":",...
37.595745
0.001103
def fetch_by_refresh_token(self, refresh_token): """ Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNo...
[ "def", "fetch_by_refresh_token", "(", "self", ",", "refresh_token", ")", ":", "row", "=", "self", ".", "fetchone", "(", "self", ".", "fetch_by_refresh_token_query", ",", "refresh_token", ")", "if", "row", "is", "None", ":", "raise", "AccessTokenNotFound", "scope...
33.571429
0.002759
def do_class(self, element, decl, pseudo): """Implement class declaration - pre-match.""" step = self.state[self.state['current_step']] actions = step['actions'] strval = self.eval_string_value(element, decl.value) actions.append(('attrib', ('class', strval)))
[ "def", "do_class", "(", "self", ",", "element", ",", "decl", ",", "pseudo", ")", ":", "step", "=", "self", ".", "state", "[", "self", ".", "state", "[", "'current_step'", "]", "]", "actions", "=", "step", "[", "'actions'", "]", "strval", "=", "self",...
49.166667
0.006667
def beagle(args): """ %prog beagle input.vcf 1 Use BEAGLE4.1 to impute vcf on chromosome 1. """ p = OptionParser(beagle.__doc__) p.set_home("beagle") p.set_ref() p.set_cpus() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) vcffile, c...
[ "def", "beagle", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "beagle", ".", "__doc__", ")", "p", ".", "set_home", "(", "\"beagle\"", ")", "p", ".", "set_ref", "(", ")", "p", ".", "set_cpus", "(", ")", "opts", ",", "args", "=", "p", ".",...
25.645161
0.001212
def handle(self, type: str, *, kwargs: dict = None) -> Callable: """ Register an event handler with the :obj:`Layabout` instance. Args: type: The name of a Slack RTM API event to be handled. As a special case, although it is not a proper RTM event, ``*`` may ...
[ "def", "handle", "(", "self", ",", "type", ":", "str", ",", "*", ",", "kwargs", ":", "dict", "=", "None", ")", "->", "Callable", ":", "def", "decorator", "(", "fn", ":", "Callable", ")", "->", "Callable", ":", "# Validate that the wrapped callable is a sui...
41.484848
0.001428
def _sconnect(host=None, port=None, password=None): ''' Returns an instance of the redis client ''' if host is None: host = __salt__['config.option']('redis_sentinel.host', 'localhost') if port is None: port = __salt__['config.option']('redis_sentinel.port', 26379) if password is...
[ "def", "_sconnect", "(", "host", "=", "None", ",", "port", "=", "None", ",", "password", "=", "None", ")", ":", "if", "host", "is", "None", ":", "host", "=", "__salt__", "[", "'config.option'", "]", "(", "'redis_sentinel.host'", ",", "'localhost'", ")", ...
39.25
0.004149