text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the Rekey request payload to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStrea...
[ "def", "write", "(", "self", ",", "output_stream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "local_stream", "=", "utils", ".", "BytearrayStream", "(", ")", "if", "self", ".", "_unique_identifier", "is", "not", "None",...
35.789474
0.001432
def CreateServiceProto(job): """Create the Service protobuf. Args: job: Launchdjobdict from servicemanagement framework. Returns: sysinfo_pb2.OSXServiceInformation proto """ service = rdf_client.OSXServiceInformation( label=job.get("Label"), program=job.get("Program"), sessiontype=...
[ "def", "CreateServiceProto", "(", "job", ")", ":", "service", "=", "rdf_client", ".", "OSXServiceInformation", "(", "label", "=", "job", ".", "get", "(", "\"Label\"", ")", ",", "program", "=", "job", ".", "get", "(", "\"Program\"", ")", ",", "sessiontype",...
29.818182
0.009843
def _waitFor(self, timeout, notification, **kwargs): """Wait for a particular UI event to occur; this can be built upon in NativeUIElement for specific convenience methods. """ callback = self._matchOther retelem = None callbackArgs = None callbackKwargs = None ...
[ "def", "_waitFor", "(", "self", ",", "timeout", ",", "notification", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "self", ".", "_matchOther", "retelem", "=", "None", "callbackArgs", "=", "None", "callbackKwargs", "=", "None", "# Allow customization of t...
39.836735
0.0015
def __parse_child(self, node): '''for rpc-style map each message part to a class in typesmodule ''' try: tc = self.gettypecode(self.typesmodule, node) except: self.logger.debug('didnt find typecode for "%s" in typesmodule: %s', node.localName, sel...
[ "def", "__parse_child", "(", "self", ",", "node", ")", ":", "try", ":", "tc", "=", "self", ".", "gettypecode", "(", "self", ".", "typesmodule", ",", "node", ")", "except", ":", "self", ".", "logger", ".", "debug", "(", "'didnt find typecode for \"%s\" in t...
35.421053
0.008683
def unpacktar(tarfile, destdir): """ Unpack given tarball into the specified dir """ nullfd = open(os.devnull, "w") tarfile = cygpath(os.path.abspath(tarfile)) log.debug("unpack tar %s into %s", tarfile, destdir) try: check_call([TAR, '-xzf', tarfile], cwd=destdir, stdout=...
[ "def", "unpacktar", "(", "tarfile", ",", "destdir", ")", ":", "nullfd", "=", "open", "(", "os", ".", "devnull", ",", "\"w\"", ")", "tarfile", "=", "cygpath", "(", "os", ".", "path", ".", "abspath", "(", "tarfile", ")", ")", "log", ".", "debug", "("...
39.083333
0.002083
def right_click_specimen_equalarea(self, event): """ toggles between zoom and pan effects for the specimen equal area on right click Parameters ---------- event : the wx.MouseEvent that triggered the call of this function Alters ------ specimen_E...
[ "def", "right_click_specimen_equalarea", "(", "self", ",", "event", ")", ":", "if", "event", ".", "LeftIsDown", "(", ")", "or", "event", ".", "ButtonDClick", "(", ")", ":", "return", "elif", "self", ".", "specimen_EA_setting", "==", "\"Zoom\"", ":", "self", ...
29.962963
0.002395
def from_span(cls, inputs, window_length, span, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -----...
[ "def", "from_span", "(", "cls", ",", "inputs", ",", "window_length", ",", "span", ",", "*", "*", "kwargs", ")", ":", "if", "span", "<=", "1", ":", "raise", "ValueError", "(", "\"`span` must be a positive number. %s was passed.\"", "%", "span", ")", "decay_rate...
29.209302
0.001541
def get_json_field(self, field, **kwargs): """ Perform a GET request and get the contents of the JSON response. Marathon's JSON responses tend to contain an object with a single key which points to the actual data of the response. For example /v2/apps returns something like {"ap...
[ "def", "get_json_field", "(", "self", ",", "field", ",", "*", "*", "kwargs", ")", ":", "d", "=", "self", ".", "request", "(", "'GET'", ",", "headers", "=", "{", "'Accept'", ":", "'application/json'", "}", ",", "*", "*", "kwargs", ")", "d", ".", "ad...
42.6
0.002296
def get_proxy(self, proxystr=''): """ Get the proxy given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable. """ if not proxystr: proxystr = os.environ.get('HTTP_PROXY', '') if proxystr:...
[ "def", "get_proxy", "(", "self", ",", "proxystr", "=", "''", ")", ":", "if", "not", "proxystr", ":", "proxystr", "=", "os", ".", "environ", ".", "get", "(", "'HTTP_PROXY'", ",", "''", ")", "if", "proxystr", ":", "if", "'@'", "in", "proxystr", ":", ...
39.318182
0.002257
def convert_sqla_type_for_dialect( coltype: TypeEngine, dialect: Dialect, strip_collation: bool = True, convert_mssql_timestamp: bool = True, expand_for_scrubbing: bool = False) -> TypeEngine: """ Converts an SQLAlchemy column type from one SQL dialect to another. Ar...
[ "def", "convert_sqla_type_for_dialect", "(", "coltype", ":", "TypeEngine", ",", "dialect", ":", "Dialect", ",", "strip_collation", ":", "bool", "=", "True", ",", "convert_mssql_timestamp", ":", "bool", "=", "True", ",", "expand_for_scrubbing", ":", "bool", "=", ...
45.868687
0.000216
def _clone(self, deepcopy=True, base=None): """Internal clone helper.""" if not base: if self.__explicit_session: base = self._clone_base(self.__session) else: base = self._clone_base(None) values_to_clone = ("spec", "projection", "skip", ...
[ "def", "_clone", "(", "self", ",", "deepcopy", "=", "True", ",", "base", "=", "None", ")", ":", "if", "not", "base", ":", "if", "self", ".", "__explicit_session", ":", "base", "=", "self", ".", "_clone_base", "(", "self", ".", "__session", ")", "else...
44.736842
0.002304
def render_response(self, **kwargs): """Render the graph, and return a Flask response""" from flask import Response return Response(self.render(**kwargs), mimetype='image/svg+xml')
[ "def", "render_response", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "flask", "import", "Response", "return", "Response", "(", "self", ".", "render", "(", "*", "*", "kwargs", ")", ",", "mimetype", "=", "'image/svg+xml'", ")" ]
50.25
0.009804
def get_whitespace(txt): """ Returns a list containing the whitespace to the left and right of a string as its two elements """ # if the entire parameter is whitespace rall = re.search(r'^([\s])+$', txt) if rall: tmp = txt.split('\n', 1) if len(tmp) == 2: return ...
[ "def", "get_whitespace", "(", "txt", ")", ":", "# if the entire parameter is whitespace", "rall", "=", "re", ".", "search", "(", "r'^([\\s])+$'", ",", "txt", ")", "if", "rall", ":", "tmp", "=", "txt", ".", "split", "(", "'\\n'", ",", "1", ")", "if", "len...
28.36
0.001364
def handle(self, connection_id, message_content): """ A connection must use one of the supported authorization types to prove their identity. If a requester deviates from the procedure in any way, the requester will be rejected and the connection will be closed. The same is true ...
[ "def", "handle", "(", "self", ",", "connection_id", ",", "message_content", ")", ":", "message", "=", "ConnectionRequest", "(", ")", "message", ".", "ParseFromString", "(", "message_content", ")", "LOGGER", ".", "debug", "(", "\"got connect message from %s. sending ...
49.326923
0.000382
def getoutput(cmd): """Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- stdout : str """ with AvoidUNCPath() as path: if p...
[ "def", "getoutput", "(", "cmd", ")", ":", "with", "AvoidUNCPath", "(", ")", "as", "path", ":", "if", "path", "is", "not", "None", ":", "cmd", "=", "'\"pushd %s &&\"%s'", "%", "(", "path", ",", "cmd", ")", "out", "=", "process_handler", "(", "cmd", ",...
22.391304
0.001862
def Decode(self, attribute, value): """Decode the value to the required type.""" required_type = self._attribute_types.get(attribute, "bytes") if required_type == "integer": return rdf_structs.SignedVarintReader(value, 0)[0] elif required_type == "unsigned_integer": return rdf_structs.Varint...
[ "def", "Decode", "(", "self", ",", "attribute", ",", "value", ")", ":", "required_type", "=", "self", ".", "_attribute_types", ".", "get", "(", "attribute", ",", "\"bytes\"", ")", "if", "required_type", "==", "\"integer\"", ":", "return", "rdf_structs", ".",...
36.857143
0.011342
def print_terminal_table(headers, data_list, parse_row_fn): """Uses a set of headers, raw data, and a row parsing function, to print data to the terminal in a table of rows and columns. Args: headers (tuple of strings): The headers for each column of data data_list (list of dicts): Raw resp...
[ "def", "print_terminal_table", "(", "headers", ",", "data_list", ",", "parse_row_fn", ")", ":", "data_iter", "=", "iter", "(", "data_list", ")", "try", ":", "example", "=", "next", "(", "data_iter", ")", "example_row", "=", "parse_row_fn", "(", "example", ")...
41.185185
0.000879
def h5ToDict(h5, readH5pyDataset=True): """ Read a hdf5 file into a dictionary """ h = h5py.File(h5, "r") ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset) if readH5pyDataset: h.close() return ret
[ "def", "h5ToDict", "(", "h5", ",", "readH5pyDataset", "=", "True", ")", ":", "h", "=", "h5py", ".", "File", "(", "h5", ",", "\"r\"", ")", "ret", "=", "unwrapArray", "(", "h", ",", "recursive", "=", "True", ",", "readH5pyDataset", "=", "readH5pyDataset"...
38.5
0.008475
def get_sha(path=None, log=None, short=False, timeout=None): """Use `git rev-parse HEAD <REPO>` to get current SHA. """ # git_command = "git rev-parse HEAD {}".format(repo_name).split() # git_command = "git rev-parse HEAD".split() git_command = ["git", "rev-parse"] if short: git_command....
[ "def", "get_sha", "(", "path", "=", "None", ",", "log", "=", "None", ",", "short", "=", "False", ",", "timeout", "=", "None", ")", ":", "# git_command = \"git rev-parse HEAD {}\".format(repo_name).split()", "# git_command = \"git rev-parse HEAD\".split()", "git_command", ...
29.111111
0.002463
def remove_all_containers(self, **kwargs): """ Identical to :meth:`dockermap.client.docker_util.DockerUtilityMixin.remove_all_containers` with additional logging. """ self.push_log("Fetching container list.") set_raise_on_error(kwargs) super(DockerFabricClient, se...
[ "def", "remove_all_containers", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "push_log", "(", "\"Fetching container list.\"", ")", "set_raise_on_error", "(", "kwargs", ")", "super", "(", "DockerFabricClient", ",", "self", ")", ".", "remove_all_co...
43.5
0.008451
def get_service_framework_id( service_name, inactive=False, completed=False ): """ Get the framework ID for a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool ...
[ "def", "get_service_framework_id", "(", "service_name", ",", "inactive", "=", "False", ",", "completed", "=", "False", ")", ":", "service", "=", "get_service", "(", "service_name", ",", "inactive", ",", "completed", ")", "if", "service", "is", "not", "None", ...
26.565217
0.00158
def encode(cls, public_key, scalar, precision=None, max_exponent=None): """Return an encoding of an int or float. This encoding is carefully chosen so that it supports the same operations as the Paillier cryptosystem. If *scalar* is a float, first approximate it as an int, `int_rep`: ...
[ "def", "encode", "(", "cls", ",", "public_key", ",", "scalar", ",", "precision", "=", "None", ",", "max_exponent", "=", "None", ")", ":", "# Calculate the maximum exponent for desired precision", "if", "precision", "is", "None", ":", "if", "isinstance", "(", "sc...
45.47191
0.000484
def get(self, object_type, cache_key): """ Query the cache for a Zenpy object """ if object_type not in self.mapping or self.disabled: return None cache = self.mapping[object_type] if cache_key in cache: log.debug("Cache HIT: [%s %s]" % (object_type.capitalize(), ...
[ "def", "get", "(", "self", ",", "object_type", ",", "cache_key", ")", ":", "if", "object_type", "not", "in", "self", ".", "mapping", "or", "self", ".", "disabled", ":", "return", "None", "cache", "=", "self", ".", "mapping", "[", "object_type", "]", "i...
45.7
0.008584
def vgg11_bn(pretrained=False, **kwargs): """VGG 11-layer model (configuration "A") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['A'], batch_norm=True)...
[ "def", "vgg11_bn", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "pretrained", ":", "kwargs", "[", "'init_weights'", "]", "=", "False", "model", "=", "VGG", "(", "make_layers", "(", "cfg", "[", "'A'", "]", ",", "batch_norm",...
35.833333
0.002268
def path(self): "Returns the path up to the root for the current node." if self.parent: return '.'.join([self.parent.path, str(self.identifier)]) else: return self.identifier if self.identifier else self.__class__.__name__
[ "def", "path", "(", "self", ")", ":", "if", "self", ".", "parent", ":", "return", "'.'", ".", "join", "(", "[", "self", ".", "parent", ".", "path", ",", "str", "(", "self", ".", "identifier", ")", "]", ")", "else", ":", "return", "self", ".", "...
44.166667
0.011111
def set(self, item_name, item_value): """ Sets the value of an option in the configuration. :param str item_name: The name of the option to set. :param item_value: The value of the option to set. """ if self.prefix: item_name = self.prefix + self.seperator + item_name item_names = item_name.split(self...
[ "def", "set", "(", "self", ",", "item_name", ",", "item_value", ")", ":", "if", "self", ".", "prefix", ":", "item_name", "=", "self", ".", "prefix", "+", "self", ".", "seperator", "+", "item_name", "item_names", "=", "item_name", ".", "split", "(", "se...
28.833333
0.035448
def _set_precision(self, precision): ''' function that sets precision to an (hopfully) reasonable guess based on the length of the sequence if not explicitly set ''' # if precision is explicitly specified, use it. if self.one_mutation: self.min_width = 10*sel...
[ "def", "_set_precision", "(", "self", ",", "precision", ")", ":", "# if precision is explicitly specified, use it.", "if", "self", ".", "one_mutation", ":", "self", ".", "min_width", "=", "10", "*", "self", ".", "one_mutation", "else", ":", "self", ".", "min_wid...
45.093023
0.010601
def _atoms(atoms_string): """Parse the atom string. Args: atoms_string (str): The atoms to plot, in the form ``"C.1.2.3,"``. Returns: dict: The atomic indices over which to sum the DOS. Formatted as:: {Element: [atom_indices]}. Indices are zero indexed for each atomic...
[ "def", "_atoms", "(", "atoms_string", ")", ":", "atoms", "=", "{", "}", "for", "split", "in", "atoms_string", ".", "split", "(", "','", ")", ":", "sites", "=", "split", ".", "split", "(", "'.'", ")", "el", "=", "sites", ".", "pop", "(", "0", ")",...
29.272727
0.001504
def _prepare_record(record, index, doc_type): """Prepare record data for indexing. :param record: The record to prepare. :param index: The Elasticsearch index. :param doc_type: The Elasticsearch document type. :returns: The record metadata. """ if current_app.con...
[ "def", "_prepare_record", "(", "record", ",", "index", ",", "doc_type", ")", ":", "if", "current_app", ".", "config", "[", "'INDEXER_REPLACE_REFS'", "]", ":", "data", "=", "copy", ".", "deepcopy", "(", "record", ".", "replace_refs", "(", ")", ")", "else", ...
33.821429
0.002053
def delete(self, **args): ''' Delete a gist by gistname/gistID ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Provide GistName to delete') url = 'gists' if self.gist_id: ...
[ "def", "delete", "(", "self", ",", "*", "*", "args", ")", ":", "if", "'name'", "in", "args", ":", "self", ".", "gist_name", "=", "args", "[", "'name'", "]", "self", ".", "gist_id", "=", "self", ".", "getMyID", "(", "self", ".", "gist_name", ")", ...
20.576923
0.048214
def split_extension(file_name, special=['tar.bz2', 'tar.gz']): """ Find the file extension of a file name, including support for special case multipart file extensions (like .tar.gz) Parameters ---------- file_name: str, file name special: list of str, multipart extensions ...
[ "def", "split_extension", "(", "file_name", ",", "special", "=", "[", "'tar.bz2'", ",", "'tar.gz'", "]", ")", ":", "file_name", "=", "str", "(", "file_name", ")", "if", "file_name", ".", "endswith", "(", "tuple", "(", "special", ")", ")", ":", "for", "...
28.608696
0.001471
def associate_keys(user_dict, client): """ This whole function is black magic, had to however cause of the way we keep key-machine association """ added_keys = user_dict['keypairs'] print ">>>Updating Keys-Machines association" for key in added_keys: machines = added_keys[key]['machines...
[ "def", "associate_keys", "(", "user_dict", ",", "client", ")", ":", "added_keys", "=", "user_dict", "[", "'keypairs'", "]", "print", "\">>>Updating Keys-Machines association\"", "for", "key", "in", "added_keys", ":", "machines", "=", "added_keys", "[", "key", "]",...
39.151515
0.002266
def hash(self): """Returns the SHA256 of the pipfile's data.""" content = json.dumps(self.data, sort_keys=True, separators=(",", ":")) return hashlib.sha256(content.encode("utf8")).hexdigest()
[ "def", "hash", "(", "self", ")", ":", "content", "=", "json", ".", "dumps", "(", "self", ".", "data", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "\",\"", ",", "\":\"", ")", ")", "return", "hashlib", ".", "sha256", "(", "content", "...
53.25
0.009259
def _legacy_status(stat): """Legacy status method from the 'qsmobile.js' library. Pass in the 'val' from &devices or the 'data' received after calling a specific ID. """ # 2d0c00002a0000 if stat[:2] == '30' or stat[:2] == '47': # RX1 CT ooo = stat[4:5] # console.log("legstat. "...
[ "def", "_legacy_status", "(", "stat", ")", ":", "# 2d0c00002a0000", "if", "stat", "[", ":", "2", "]", "==", "'30'", "or", "stat", "[", ":", "2", "]", "==", "'47'", ":", "# RX1 CT", "ooo", "=", "stat", "[", "4", ":", "5", "]", "# console.log(\"legstat...
30.340909
0.000726
def title_prefix_json(soup): "titlePrefix with capitalisation changed" prefix = title_prefix(soup) prefix_rewritten = elifetools.json_rewrite.rewrite_json("title_prefix_json", soup, prefix) return prefix_rewritten
[ "def", "title_prefix_json", "(", "soup", ")", ":", "prefix", "=", "title_prefix", "(", "soup", ")", "prefix_rewritten", "=", "elifetools", ".", "json_rewrite", ".", "rewrite_json", "(", "\"title_prefix_json\"", ",", "soup", ",", "prefix", ")", "return", "prefix_...
45
0.008734
def variational_dropout(units, keep_prob, fixed_mask_dims=(1,)): """ Dropout with the same drop mask for all fixed_mask_dims Args: units: a tensor, usually with shapes [B x T x F], where B - batch size T - tokens dimension F - feature dimension keep_prob: kee...
[ "def", "variational_dropout", "(", "units", ",", "keep_prob", ",", "fixed_mask_dims", "=", "(", "1", ",", ")", ")", ":", "units_shape", "=", "tf", ".", "shape", "(", "units", ")", "noise_shape", "=", "[", "units_shape", "[", "n", "]", "for", "n", "in",...
34.526316
0.001484
def addApplicationManifest(self, pchApplicationManifestFullPath, bTemporary): """ Adds an application manifest to the list to load when building the list of installed applications. Temporary manifests are not automatically loaded """ fn = self.function_table.addApplicationManif...
[ "def", "addApplicationManifest", "(", "self", ",", "pchApplicationManifestFullPath", ",", "bTemporary", ")", ":", "fn", "=", "self", ".", "function_table", ".", "addApplicationManifest", "result", "=", "fn", "(", "pchApplicationManifestFullPath", ",", "bTemporary", ")...
44.555556
0.00978
def get_include_fields(request): """Retrieve include_fields values from the request """ include_fields = [] rif = request.get("include_fields", "") if "include_fields" in request: include_fields = [x.strip() for x in rif.split(",") if x.str...
[ "def", "get_include_fields", "(", "request", ")", ":", "include_fields", "=", "[", "]", "rif", "=", "request", ".", "get", "(", "\"include_fields\"", ",", "\"\"", ")", "if", "\"include_fields\"", "in", "request", ":", "include_fields", "=", "[", "x", ".", ...
35.916667
0.002262
def _create_kvstore(kvstore, num_device, arg_params): """Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to ...
[ "def", "_create_kvstore", "(", "kvstore", ",", "num_device", ",", "arg_params", ")", ":", "update_on_kvstore", "=", "bool", "(", "int", "(", "os", ".", "getenv", "(", "'MXNET_UPDATE_ON_KVSTORE'", ",", "\"1\"", ")", ")", ")", "if", "kvstore", "is", "None", ...
33.973684
0.001506
def synthetic_source(self, value): """The synthetic_source property. Args: value (string). the property value. """ if value == self._defaults['ai.operation.syntheticSource'] and 'ai.operation.syntheticSource' in self._values: del self._values['ai.operatio...
[ "def", "synthetic_source", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'ai.operation.syntheticSource'", "]", "and", "'ai.operation.syntheticSource'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", ...
40.9
0.009569
def clean(self): """ Validates the topic instance. """ super().clean() if self.forum.is_category or self.forum.is_link: raise ValidationError( _('A topic can not be associated with a category or a link forum') )
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "if", "self", ".", "forum", ".", "is_category", "or", "self", ".", "forum", ".", "is_link", ":", "raise", "ValidationError", "(", "_", "(", "'A topic can not be associated ...
38.428571
0.010909
def processAbf(abfFname,saveAs=False,dpi=100,show=True): """ automatically generate a single representative image for an ABF. If saveAs is given (full path of a jpg of png file), the image will be saved. Otherwise, the image will pop up in a matplotlib window. """ if not type(abfFname) is str or...
[ "def", "processAbf", "(", "abfFname", ",", "saveAs", "=", "False", ",", "dpi", "=", "100", ",", "show", "=", "True", ")", ":", "if", "not", "type", "(", "abfFname", ")", "is", "str", "or", "not", "len", "(", "abfFname", ")", ">", "3", ":", "retur...
37.984848
0.018663
def generate_s3_bucket(): """Create the blockade bucket if not already there.""" logger.debug("[#] Setting up S3 bucket") client = boto3.client("s3", region_name=PRIMARY_REGION) buckets = client.list_buckets() matches = [x for x in buckets.get('Buckets', list()) if x['Name'].startswit...
[ "def", "generate_s3_bucket", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Setting up S3 bucket\"", ")", "client", "=", "boto3", ".", "client", "(", "\"s3\"", ",", "region_name", "=", "PRIMARY_REGION", ")", "buckets", "=", "client", ".", "list_buckets", "...
33
0.001473
def verify_oauth2_token(id_token, request, audience=None): """Verifies an ID Token issued by Google's OAuth 2.0 authorization server. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audien...
[ "def", "verify_oauth2_token", "(", "id_token", ",", "request", ",", "audience", "=", "None", ")", ":", "return", "verify_token", "(", "id_token", ",", "request", ",", "audience", "=", "audience", ",", "certs_url", "=", "_GOOGLE_OAUTH2_CERTS_URL", ")" ]
39.235294
0.001464
def compute_actor_handle_id_non_forked(actor_handle_id, current_task_id): """Deterministically compute an actor handle ID in the non-forked case. This code path is used whenever an actor handle is pickled and unpickled (for example, if a remote function closes over an actor handle). Then, whenever the ...
[ "def", "compute_actor_handle_id_non_forked", "(", "actor_handle_id", ",", "current_task_id", ")", ":", "assert", "isinstance", "(", "actor_handle_id", ",", "ActorHandleID", ")", "assert", "isinstance", "(", "current_task_id", ",", "TaskID", ")", "handle_id_hash", "=", ...
43.851852
0.000826
def init_duts(self, args): # pylint: disable=too-many-locals,too-many-branches """ Initializes duts of different types based on configuration provided by AllocationContext. Able to do the initialization of duts in parallel, if --parallel_flash was provided. :param args: Argument Namesp...
[ "def", "init_duts", "(", "self", ",", "args", ")", ":", "# pylint: disable=too-many-locals,too-many-branches", "# TODO: Split into smaller chunks to reduce complexity.", "threads", "=", "[", "]", "abort_queue", "=", "Queue", "(", ")", "def", "thread_wrapper", "(", "*", ...
39.622222
0.001915
def print_big_dir_and_big_file(self, top_n=5): """Print ``top_n`` big dir and ``top_n`` big file in each dir. """ self.assert_is_dir_and_exists() size_table1 = sorted( [(p, p.dirsize) for p in self.select_dir(recursive=False)], key=lambda x: x[1], rev...
[ "def", "print_big_dir_and_big_file", "(", "self", ",", "top_n", "=", "5", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "size_table1", "=", "sorted", "(", "[", "(", "p", ",", "p", ".", "dirsize", ")", "for", "p", "in", "self", ".", "sele...
39.35
0.002481
def adam(f, x, learning_rate=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, maxiter=1000, tol=1e-16, callback=None): r"""ADAM method to minimize an objective function. General implementation of ADAM for solving .. math:: \min f(x) where :math:`f` is a differentiable functional. The alg...
[ "def", "adam", "(", "f", ",", "x", ",", "learning_rate", "=", "1e-3", ",", "beta1", "=", "0.9", ",", "beta2", "=", "0.999", ",", "eps", "=", "1e-8", ",", "maxiter", "=", "1000", ",", "tol", "=", "1e-16", ",", "callback", "=", "None", ")", ":", ...
32.136986
0.000414
def inspect(self): """Inspect device requests and sensors, update model Returns ------- Tornado future that resolves with: model_changes : Nested AttrDict or None Contains sets of added/removed request/sensor names Example structure: {'req...
[ "def", "inspect", "(", "self", ")", ":", "timeout_manager", "=", "future_timeout_manager", "(", "self", ".", "sync_timeout", ")", "sensor_index_before", "=", "copy", ".", "copy", "(", "self", ".", "_sensors_index", ")", "request_index_before", "=", "copy", ".", ...
35.9
0.001085
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs): """ Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step. Args: resource (intern.resource.Resource): Resource compatible with cutout opera...
[ "def", "get_neuroglancer_link", "(", "self", ",", "resource", ",", "resolution", ",", "x_range", ",", "y_range", ",", "z_range", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "service", ".", "get_neuroglancer_link", "(", "resource", ",", "resolut...
52.368421
0.010859
def newDocNode(self, ns, name, content): """Creation of a new node element within a document. @ns and @content are optional (None). NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities references, but XML special chars need to be escaped first by using ...
[ "def", "newDocNode", "(", "self", ",", "ns", ",", "name", ",", "content", ")", ":", "if", "ns", "is", "None", ":", "ns__o", "=", "None", "else", ":", "ns__o", "=", "ns", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlNewDocNode", "(", "self", ".", ...
51.461538
0.008811
def update_ld_api(project: str, environment: str, feature: str, state: str): """ Execute command against the LaunchDarkly API. This command is generally not used directly, instead it is called as a part of running the ``playback()`` function. :param project: LaunchDarkly project key. :param en...
[ "def", "update_ld_api", "(", "project", ":", "str", ",", "environment", ":", "str", ",", "feature", ":", "str", ",", "state", ":", "str", ")", ":", "ld_api", "=", "LaunchDarklyApi", "(", "os", ".", "environ", ".", "get", "(", "'LD_API_KEY'", ")", ",", ...
31.296296
0.001148
def _generate_docstring(self, doc_type, quote): """Generate docstring.""" docstring = None self.quote3 = quote * 3 if quote == '"': self.quote3_other = "'''" else: self.quote3_other = '"""' result = self.get_function_definition_from_bel...
[ "def", "_generate_docstring", "(", "self", ",", "doc_type", ",", "quote", ")", ":", "docstring", "=", "None", "self", ".", "quote3", "=", "quote", "*", "3", "if", "quote", "==", "'\"'", ":", "self", ".", "quote3_other", "=", "\"'''\"", "else", ":", "se...
32.285714
0.002148
def _to_json(self, sort_keys=False, indent=4): """Convert :class:`~ctfile.ctfile.CTfile` into JSON string. :return: ``JSON`` formatted string. :rtype: :py:class:`str`. """ return json.dumps(self, sort_keys=sort_keys, indent=indent, cls=CtabAtomBondEncoder)
[ "def", "_to_json", "(", "self", ",", "sort_keys", "=", "False", ",", "indent", "=", "4", ")", ":", "return", "json", ".", "dumps", "(", "self", ",", "sort_keys", "=", "sort_keys", ",", "indent", "=", "indent", ",", "cls", "=", "CtabAtomBondEncoder", ")...
41.571429
0.010101
def make_remote_view(data, settings, more_excluded_names=None): """ Make a remote view of dictionary *data* -> globals explorer """ data = get_remote_data(data, settings, mode='editable', more_excluded_names=more_excluded_names) remote = {} for key, value in list(d...
[ "def", "make_remote_view", "(", "data", ",", "settings", ",", "more_excluded_names", "=", "None", ")", ":", "data", "=", "get_remote_data", "(", "data", ",", "settings", ",", "mode", "=", "'editable'", ",", "more_excluded_names", "=", "more_excluded_names", ")",...
40.6
0.001605
def itemChange( self, change, value ): """ Overloads the base QGraphicsItem itemChange method to block user ability to move along the y-axis. :param change <int> :param value <variant> :return <variant> """ # onl...
[ "def", "itemChange", "(", "self", ",", "change", ",", "value", ")", ":", "# only operate when it is a visible, geometric change", "if", "not", "(", "self", ".", "isVisible", "(", ")", "and", "change", "==", "self", ".", "ItemPositionChange", ")", ":", "return", ...
35.733333
0.014532
def get_placement_solver(service_instance): ''' Returns a placement solver service_instance Service instance to the host or vCenter ''' stub = salt.utils.vmware.get_new_service_instance_stub( service_instance, ns='pbm/2.0', path='/pbm/sdk') pbm_si = pbm.ServiceInstance('ServiceI...
[ "def", "get_placement_solver", "(", "service_instance", ")", ":", "stub", "=", "salt", ".", "utils", ".", "vmware", ".", "get_new_service_instance_stub", "(", "service_instance", ",", "ns", "=", "'pbm/2.0'", ",", "path", "=", "'/pbm/sdk'", ")", "pbm_si", "=", ...
36.130435
0.001172
def update(collection_name, upsert, multi, spec, doc, safe, last_error_args, check_keys, opts): """Get an **update** message. """ options = 0 if upsert: options += 1 if multi: options += 2 data = _ZERO_32 data += bson._make_c_string(collection_name) data += st...
[ "def", "update", "(", "collection_name", ",", "upsert", ",", "multi", ",", "spec", ",", "doc", ",", "safe", ",", "last_error_args", ",", "check_keys", ",", "opts", ")", ":", "options", "=", "0", "if", "upsert", ":", "options", "+=", "1", "if", "multi",...
35.958333
0.001129
def bg_color(self, value): """Sets the color to a new value (tuple). Renders the text if needed.""" if value != self.bg_color: self._bg_color = value self._render()
[ "def", "bg_color", "(", "self", ",", "value", ")", ":", "if", "value", "!=", "self", ".", "bg_color", ":", "self", ".", "_bg_color", "=", "value", "self", ".", "_render", "(", ")" ]
33.333333
0.014634
def proximal_convex_conj_l1_l2(space, lam=1, g=None): r"""Proximal operator factory of the L1-L2 norm/distance convex conjugate. Implements the proximal operator of the convex conjugate of the functional :: F(x) = lam || |x - g|_2 ||_1 with ``x`` and ``g`` elements in ``space``, and scaling f...
[ "def", "proximal_convex_conj_l1_l2", "(", "space", ",", "lam", "=", "1", ",", "g", "=", "None", ")", ":", "# Fix for rounding errors", "dtype", "=", "getattr", "(", "space", ",", "'dtype'", ",", "float", ")", "eps", "=", "np", ".", "finfo", "(", "dtype",...
30.137255
0.000315
def str_to_datetime(ts): """Format a string to a datetime object. This functions supports several date formats like YYYY-MM-DD, MM-DD-YYYY, YY-MM-DD, YYYY-MM-DD HH:mm:SS +HH:MM, among others. When the timezone is not provided, UTC+0 will be set as default (using `dateutil.tz.tzutc` object). :p...
[ "def", "str_to_datetime", "(", "ts", ")", ":", "def", "parse_datetime", "(", "ts", ")", ":", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "ts", ")", "if", "not", "dt", ".", "tzinfo", ":", "dt", "=", "dt", ".", "replace", "(", "tzinfo", ...
30.519231
0.001221
def module_return(self, return_code, timeperiods): """Module the exit code if necessary :: * modulation_period is legit * exit_code_modulation * return_code in exit_codes_match :param return_code: actual code returned by the check :type return_code: int :return:...
[ "def", "module_return", "(", "self", ",", "return_code", ",", "timeperiods", ")", ":", "# Only if in modulation_period of modulation_period == None", "if", "self", ".", "is_active", "(", "timeperiods", ")", ":", "# Try to change the exit code only if a new one is defined", "i...
38.904762
0.002389
def sde(self): """ Return the state space representation of the standard periodic covariance. ! Note: one must constrain lengthscale not to drop below 0.2. (independently of approximation order) After this Bessel functions of the first becomes NaN. Rescaling t...
[ "def", "sde", "(", "self", ")", ":", "#import pdb; pdb.set_trace()", "# Params to use: (in that order)", "#self.variance", "#self.period", "#self.lengthscale", "if", "self", ".", "approx_order", "is", "not", "None", ":", "N", "=", "int", "(", "self", ".", "approx_or...
42.75641
0.029015
def list_branches(cwd, remote=False, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Return a list of branches cwd The path to the git checkout r...
[ "def", "list_branches", "(", "cwd", ",", "remote", "=", "False", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "u...
30.985294
0.00046
def _process_features(features): """ Generate the `Features String` from an iterable of features. :param features: The features to generate the features string from. :type features: :class:`~collections.abc.Iterable` of :class:`str` :return: The `Features String` :rtype: :class:`bytes` Gen...
[ "def", "_process_features", "(", "features", ")", ":", "parts", "=", "[", "feature", ".", "encode", "(", "\"utf-8\"", ")", "+", "b\"\\x1f\"", "for", "feature", "in", "features", "]", "parts", ".", "sort", "(", ")", "return", "b\"\"", ".", "join", "(", ...
30
0.001795
def _CreateLineStringForShape(self, parent, shape): """Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is ...
[ "def", "_CreateLineStringForShape", "(", "self", ",", "parent", ",", "shape", ")", ":", "coordinate_list", "=", "[", "(", "longitude", ",", "latitude", ")", "for", "(", "latitude", ",", "longitude", ",", "distance", ")", "in", "shape", ".", "points", "]", ...
36.214286
0.001923
def itemStyle(self): """ Returns the item style information for this item. :return <XGanttWidgetItem.ItemStyle> """ if ( self.useGroupStyleWithChildren() and self.childCount() ): return XGanttWidgetItem.ItemStyle.Group return sel...
[ "def", "itemStyle", "(", "self", ")", ":", "if", "(", "self", ".", "useGroupStyleWithChildren", "(", ")", "and", "self", ".", "childCount", "(", ")", ")", ":", "return", "XGanttWidgetItem", ".", "ItemStyle", ".", "Group", "return", "self", ".", "_itemStyle...
32.3
0.018072
def imp_print(self, text, end): """Catch UnicodeEncodeError""" try: PRINT(text, end=end) except UnicodeEncodeError: for i in text: try: PRINT(i, end="") except UnicodeEncodeError: PRINT("?", end="") PRINT("", end=end)
[ "def", "imp_print", "(", "self", ",", "text", ",", "end", ")", ":", "try", ":", "PRINT", "(", "text", ",", "end", "=", "end", ")", "except", "UnicodeEncodeError", ":", "for", "i", "in", "text", ":", "try", ":", "PRINT", "(", "i", ",", "end", "=",...
21.818182
0.048
def ssh_accept_sec_context(self, hostname, username, recv_token): """ Accept a SSPI context (server mode). :param str hostname: The servers FQDN :param str username: The name of the user who attempts to login :param str recv_token: The SSPI Token received from the server, ...
[ "def", "ssh_accept_sec_context", "(", "self", ",", "hostname", ",", "username", ",", "recv_token", ")", ":", "self", ".", "_gss_host", "=", "hostname", "self", ".", "_username", "=", "username", "targ_name", "=", "\"host/\"", "+", "self", ".", "_gss_host", "...
41.809524
0.002227
def p_l_expression(self, p): ''' l : expression ''' _LOGGER.debug("l -> expresion") l = TypedList( [ p[1] ] ) p[0] = l
[ "def", "p_l_expression", "(", "self", ",", "p", ")", ":", "_LOGGER", ".", "debug", "(", "\"l -> expresion\"", ")", "l", "=", "TypedList", "(", "[", "p", "[", "1", "]", "]", ")", "p", "[", "0", "]", "=", "l" ]
23.571429
0.046784
def _generate_annotation_type_class(self, ns, annotation_type): # type: (ApiNamespace, AnnotationType) -> None """Defines a Python class that represents an annotation type in Stone.""" self.emit('class {}(object):'.format(class_name_for_annotation_type(annotation_type, ns))) with self.in...
[ "def", "_generate_annotation_type_class", "(", "self", ",", "ns", ",", "annotation_type", ")", ":", "# type: (ApiNamespace, AnnotationType) -> None", "self", ".", "emit", "(", "'class {}(object):'", ".", "format", "(", "class_name_for_annotation_type", "(", "annotation_type...
62
0.011928
def visit_FunctionCall(self, node): """Visitor for `FunctionCall` AST node.""" function_name = node.identifier.name call = self.table[function_name] if call is None: raise SementicError(f"Function `{function_name}` not declared.") else: call = call._node ...
[ "def", "visit_FunctionCall", "(", "self", ",", "node", ")", ":", "function_name", "=", "node", ".", "identifier", ".", "name", "call", "=", "self", ".", "table", "[", "function_name", "]", "if", "call", "is", "None", ":", "raise", "SementicError", "(", "...
35.551724
0.001889
def offline(name, path): ''' Mark a cache storage device as offline. The storage is identified by a path which must match exactly a path specified in storage.config. This removes the storage from the cache and redirects requests that would have used this storage to other storage. This has exactly th...
[ "def", "offline", "(", "name", ",", "path", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "__opts__", "[", "'test'", "]", ":", "ret", "[", ...
31.034483
0.001078
def add_custom_options(parser): """Adds custom options to a parser. :param parser: the parser to which to add options. :type parser: argparse.ArgumentParser """ parser.add_argument("--outliers-of", type=str, metavar="POP", default="CEU", choices=["CEU", "YRI", "JPT-CHB"], ...
[ "def", "add_custom_options", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "\"--outliers-of\"", ",", "type", "=", "str", ",", "metavar", "=", "\"POP\"", ",", "default", "=", "\"CEU\"", ",", "choices", "=", "[", "\"CEU\"", ",", "\"YRI\"", ","...
52.04
0.000755
def load_env(print_vars=False): """Load environment variables from a .env file, if present. If an .env file is found in the working directory, and the listed environment variables are not already set, they will be set according to the values listed in the file. """ env_file = os.environ.get('EN...
[ "def", "load_env", "(", "print_vars", "=", "False", ")", ":", "env_file", "=", "os", ".", "environ", ".", "get", "(", "'ENV_FILE'", ",", "'.env'", ")", "try", ":", "variables", "=", "open", "(", "env_file", ")", ".", "read", "(", ")", ".", "splitline...
40.08
0.001949
def blksize(self): """The test blksize.""" self._blksize = self.lib.iperf_get_test_blksize(self._test) return self._blksize
[ "def", "blksize", "(", "self", ")", ":", "self", ".", "_blksize", "=", "self", ".", "lib", ".", "iperf_get_test_blksize", "(", "self", ".", "_test", ")", "return", "self", ".", "_blksize" ]
36
0.013605
def bss_eval_images(reference_sources, estimated_sources, compute_permutation=True): """Implementation of the bss_eval_images function from the BSS_EVAL Matlab toolbox. Ordering and measurement of the separation quality for estimated source signals in terms of filtered true source, ...
[ "def", "bss_eval_images", "(", "reference_sources", ",", "estimated_sources", ",", "compute_permutation", "=", "True", ")", ":", "# make sure the input has 3 dimensions", "# assuming input is in shape (nsampl) or (nsrc, nsampl)", "estimated_sources", "=", "np", ".", "atleast_3d",...
42.2
0.000171
def write(self, offset, value): """ .. _write: Writes the memory word at ``offset`` to ``value``. Might raise ReadOnlyError_, if the device is read-only. Might raise AddressError_, if the offset exceeds the size of the device. """ if(not self.mode & 0b10): raise ReadOnlyError("Device is Read-Only") ...
[ "def", "write", "(", "self", ",", "offset", ",", "value", ")", ":", "if", "(", "not", "self", ".", "mode", "&", "0b10", ")", ":", "raise", "ReadOnlyError", "(", "\"Device is Read-Only\"", ")", "if", "(", "offset", ">=", "self", ".", "size", ")", ":",...
32.571429
0.029851
def q(self, q, inputs=None, limit='', offset='', history=False): """ query """ if not q.strip().startswith("["): q = "[ {0} ]".format(q) args = u'[ {:db/alias "%(store)s/%(db)s" %(hist)s} %(inputs)s ]' % dict( store = self.store, db = self.db, hist = ':history true' if histo...
[ "def", "q", "(", "self", ",", "q", ",", "inputs", "=", "None", ",", "limit", "=", "''", ",", "offset", "=", "''", ",", "history", "=", "False", ")", ":", "if", "not", "q", ".", "strip", "(", ")", ".", "startswith", "(", "\"[\"", ")", ":", "q"...
37.733333
0.034483
def dot(a, b, axis=-2): """ Compute the matrix product of `a` and the specified axes of `b`, with broadcasting over the remaining axes of `b`. This function is a generalisation of :func:`numpy.dot`, supporting sum product over an arbitrary axis instead of just over the last axis. If `a` and `b`...
[ "def", "dot", "(", "a", ",", "b", ",", "axis", "=", "-", "2", ")", ":", "# Ensure axis specification is positive", "if", "axis", "<", "0", ":", "axis", "=", "b", ".", "ndim", "+", "axis", "# Insert singleton axis into b", "bx", "=", "np", ".", "expand_di...
37.901961
0.000504
def from_bs_date(cls, year, month, day): """ Create and update an NepDate object for bikram sambat date """ return NepDate(year, month, day).update()
[ "def", "from_bs_date", "(", "cls", ",", "year", ",", "month", ",", "day", ")", ":", "return", "NepDate", "(", "year", ",", "month", ",", "day", ")", ".", "update", "(", ")" ]
54.333333
0.012121
def draw(self, startpoint=(0, 0), mode='plain', showfig=False): """ lattice visualization :param startpoint: start drawing point coords, default: (0, 0) :param showfig: show figure or not, default: False :param mode: artist mode, 'plain' or 'fancy', 'plain' by de...
[ "def", "draw", "(", "self", ",", "startpoint", "=", "(", "0", ",", "0", ")", ",", "mode", "=", "'plain'", ",", "showfig", "=", "False", ")", ":", "p0", "=", "startpoint", "angle", "=", "0.0", "patchlist", "=", "[", "]", "anotelist", "=", "[", "]"...
40.018868
0.001841
def _render_bundle(bundle_name): """ Renders the HTML for a bundle in place - one HTML tag or many depending on settings.USE_BUNDLES """ try: bundle = get_bundles()[bundle_name] except KeyError: raise ImproperlyConfigured("Bundle '%s' is not defined" % bundle_name) if bundle.use...
[ "def", "_render_bundle", "(", "bundle_name", ")", ":", "try", ":", "bundle", "=", "get_bundles", "(", ")", "[", "bundle_name", "]", "except", "KeyError", ":", "raise", "ImproperlyConfigured", "(", "\"Bundle '%s' is not defined\"", "%", "bundle_name", ")", "if", ...
42.181818
0.00843
def add_app_template_global(self, func: Callable, name: Optional[str]=None) -> None: """Add an application wide template global. This is designed to be used on the blueprint directly, and has the same arguments as :meth:`~quart.Quart.add_template_global`. An example usage, .. c...
[ "def", "add_app_template_global", "(", "self", ",", "func", ":", "Callable", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "self", ".", "record_once", "(", "lambda", "state", ":", "state", ".", "register_template_globa...
35.25
0.010363
def suppress_unifurcations(self): '''Remove all nodes with only one child and directly attach child to parent''' q = deque(); q.append(self.root) while len(q) != 0: node = q.popleft() if len(node.children) != 1: q.extend(node.children); continue ...
[ "def", "suppress_unifurcations", "(", "self", ")", ":", "q", "=", "deque", "(", ")", "q", ".", "append", "(", "self", ".", "root", ")", "while", "len", "(", "q", ")", "!=", "0", ":", "node", "=", "q", ".", "popleft", "(", ")", "if", "len", "(",...
44.368421
0.010453
def parse_favorites(self, favorites_page): """Parses the DOM and returns character favorites attributes. :type favorites_page: :class:`bs4.BeautifulSoup` :param favorites_page: MAL character favorites page's DOM :rtype: dict :return: Character favorites attributes. """ character_info = se...
[ "def", "parse_favorites", "(", "self", ",", "favorites_page", ")", ":", "character_info", "=", "self", ".", "parse_sidebar", "(", "favorites_page", ")", "second_col", "=", "favorites_page", ".", "find", "(", "u'div'", ",", "{", "'id'", ":", "'content'", "}", ...
34.875
0.009302
def unset_access_cookies(response): """ takes a flask response object, and configures it to unset (delete) the access token from the response cookies. if `jwt_csrf_in_cookies` (see :ref:`configuration options`) is `true`, this will also remove the access csrf double submit value from the response co...
[ "def", "unset_access_cookies", "(", "response", ")", ":", "if", "not", "config", ".", "jwt_in_cookies", ":", "raise", "RuntimeWarning", "(", "\"unset_refresh_cookies() called without \"", "\"'JWT_TOKEN_LOCATION' configured to use cookies\"", ")", "response", ".", "set_cookie"...
46.129032
0.000685
def get_pattern_formatter(cls, location): """ Fragment from aiohttp.web_urldispatcher.UrlDispatcher#add_resource :param location: :return: """ pattern = '' formatter = '' canon = '' for part in cls.ROUTE_RE.split(location): match = cls....
[ "def", "get_pattern_formatter", "(", "cls", ",", "location", ")", ":", "pattern", "=", "''", "formatter", "=", "''", "canon", "=", "''", "for", "part", "in", "cls", ".", "ROUTE_RE", ".", "split", "(", "location", ")", ":", "match", "=", "cls", ".", "...
33.444444
0.001614
def dispatch(self, *args, **kwargs) -> Awaitable[bool]: """ Create and dispatch an event. This method constructs an event object and then passes it to :meth:`dispatch_event` for the actual dispatching. :param args: positional arguments to the constructor of the associated event...
[ "def", "dispatch", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Awaitable", "[", "bool", "]", ":", "event", "=", "self", ".", "event_class", "(", "self", ".", "source", "(", ")", ",", "cast", "(", "str", ",", "self", ".", ...
48.8125
0.01005
def getNetworkName(self): """get Thread Network name""" print '%s call getNetworkname' % self.port networkName = self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:Name')[0] return self.__stripValue(networkName)
[ "def", "getNetworkName", "(", "self", ")", ":", "print", "'%s call getNetworkname'", "%", "self", ".", "port", "networkName", "=", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'getprop -v Network:Name'", ")", "[", "0", "]", "return", "self", ".", "_...
48.2
0.012245
def init(self, sys_clock, swo_clock, console): """! @brief Configures trace graph and starts thread. This method performs all steps required to start up SWV. It first calls the target's trace_start() method, which allows for target-specific trace initialization. Then it configur...
[ "def", "init", "(", "self", ",", "sys_clock", ",", "swo_clock", ",", "console", ")", ":", "self", ".", "_swo_clock", "=", "swo_clock", "if", "not", "self", ".", "_session", ".", "probe", ".", "has_swo", "(", ")", ":", "LOG", ".", "warning", "(", "\"P...
36.902439
0.009659
def attention_bias_ignore_padding(memory_padding): """Create an bias tensor to be added to attention logits. Args: memory_padding: a float `Tensor` with shape [batch, memory_length]. Returns: a `Tensor` with shape [batch, 1, 1, memory_length]. """ ret = memory_padding * large_compatible_negative(mem...
[ "def", "attention_bias_ignore_padding", "(", "memory_padding", ")", ":", "ret", "=", "memory_padding", "*", "large_compatible_negative", "(", "memory_padding", ".", "dtype", ")", "return", "tf", ".", "expand_dims", "(", "tf", ".", "expand_dims", "(", "ret", ",", ...
35.363636
0.010025
def load_child_articles_for_section( context, section, featured_in_section=None, count=5): """ Returns all child articles If the `locale_code` in the context is not the main language, it will return the translations of the live articles. """ request = context.get('request') locale = ...
[ "def", "load_child_articles_for_section", "(", "context", ",", "section", ",", "featured_in_section", "=", "None", ",", "count", "=", "5", ")", ":", "request", "=", "context", ".", "get", "(", "'request'", ")", "locale", "=", "context", ".", "get", "(", "'...
35.694915
0.000462
def create_client(self) -> "google.cloud.storage.Client": """ Construct GCS API client. """ # Client should be imported here because grpc starts threads during import # and if you call fork after that, a child process will be hang during exit from google.cloud.storage imp...
[ "def", "create_client", "(", "self", ")", "->", "\"google.cloud.storage.Client\"", ":", "# Client should be imported here because grpc starts threads during import", "# and if you call fork after that, a child process will be hang during exit", "from", "google", ".", "cloud", ".", "sto...
40.5
0.008048
def determine_reach_subtype(event_name): """Returns the category of reach rule from the reach rule instance. Looks at a list of regular expressions corresponding to reach rule types, and returns the longest regexp that matches, or None if none of them match. Parameters ---------- evidence ...
[ "def", "determine_reach_subtype", "(", "event_name", ")", ":", "best_match_length", "=", "None", "best_match", "=", "None", "for", "ss", "in", "reach_rule_regexps", ":", "if", "re", ".", "search", "(", "ss", ",", "event_name", ")", ":", "if", "best_match", "...
29.071429
0.001189
def getHomoloGene(taxfile="build_inputs/taxid_taxname",\ genefile="homologene.data",\ proteinsfile="build_inputs/all_proteins.data",\ proteinsclusterfile="build_inputs/proteins_for_clustering.data",\ baseURL="http://ftp.ncbi.nih.gov/pub/HomoloGene/...
[ "def", "getHomoloGene", "(", "taxfile", "=", "\"build_inputs/taxid_taxname\"", ",", "genefile", "=", "\"homologene.data\"", ",", "proteinsfile", "=", "\"build_inputs/all_proteins.data\"", ",", "proteinsclusterfile", "=", "\"build_inputs/proteins_for_clustering.data\"", ",", "ba...
54.295082
0.022835
def _callable_contents(obj): """Return the signature contents of a callable Python object. """ try: # Test if obj is a method. return _function_contents(obj.__func__) except AttributeError: try: # Test if obj is a callable object. return _function_content...
[ "def", "_callable_contents", "(", "obj", ")", ":", "try", ":", "# Test if obj is a method.", "return", "_function_contents", "(", "obj", ".", "__func__", ")", "except", "AttributeError", ":", "try", ":", "# Test if obj is a callable object.", "return", "_function_conten...
30
0.001616
def client(self, id): """Returns the client object in the database given a certain id. Raises an error if that does not exist.""" return self.query(Client).filter(Client.id==id).one()
[ "def", "client", "(", "self", ",", "id", ")", ":", "return", "self", ".", "query", "(", "Client", ")", ".", "filter", "(", "Client", ".", "id", "==", "id", ")", ".", "one", "(", ")" ]
38.4
0.010204
def encodeEvent(self, event): """Adapts an Event object to a Riemann protobuf event Event""" pbevent = proto_pb2.Event( time=int(event.time), state=event.state, service=event.service, host=event.hostname, description=event.description, ...
[ "def", "encodeEvent", "(", "self", ",", "event", ")", ":", "pbevent", "=", "proto_pb2", ".", "Event", "(", "time", "=", "int", "(", "event", ".", "time", ")", ",", "state", "=", "event", ".", "state", ",", "service", "=", "event", ".", "service", "...
36.538462
0.002051
def install_dir(self): """Returns application installation path. .. note:: If fails this falls back to a restricted interface, which can only be used by approved apps. :rtype: str """ max_len = 500 directory = self._get_str(self._iface.get_install_dir, [se...
[ "def", "install_dir", "(", "self", ")", ":", "max_len", "=", "500", "directory", "=", "self", ".", "_get_str", "(", "self", ".", "_iface", ".", "get_install_dir", ",", "[", "self", ".", "app_id", "]", ",", "max_len", "=", "max_len", ")", "if", "not", ...
31.777778
0.010187