text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def rights_check(self, form, sub_auth, name, load, eauth=None): ''' Read in the access system to determine if the validated user has requested rights ''' if load.get('eauth'): sub_auth = sub_auth[load['eauth']] good = self.ckminions.any_auth( f...
[ "def", "rights_check", "(", "self", ",", "form", ",", "sub_auth", ",", "name", ",", "load", ",", "eauth", "=", "None", ")", ":", "if", "load", ".", "get", "(", "'eauth'", ")", ":", "sub_auth", "=", "sub_auth", "[", "load", "[", "'eauth'", "]", "]",...
40.75
0.001712
def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. ...
[ "def", "_ip_int_from_string", "(", "self", ",", "ip_str", ")", ":", "octets", "=", "ip_str", ".", "split", "(", "'.'", ")", "if", "len", "(", "octets", ")", "!=", "4", ":", "raise", "AddressValueError", "(", "ip_str", ")", "packed_ip", "=", "0", "for",...
27
0.002981
def ipblur(text): # brutalizer ;-) """ blurs IP address """ import re m = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}.*', text) if not m: return text return '%sxxx' % m.group(1)
[ "def", "ipblur", "(", "text", ")", ":", "# brutalizer ;-)", "import", "re", "m", "=", "re", ".", "match", "(", "r'^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.)\\d{1,3}.*'", ",", "text", ")", "if", "not", "m", ":", "return", "text", "return", "'%sxxx'", "%", "m", ".",...
29.285714
0.009479
def errorObject(object, cat, format, *args): """ Log a fatal error message in the given category. This will also raise a L{SystemExit}. """ doLog(ERROR, object, cat, format, args) # we do the import here because having it globally causes weird import # errors if our gstreactor also imports ...
[ "def", "errorObject", "(", "object", ",", "cat", ",", "format", ",", "*", "args", ")", ":", "doLog", "(", "ERROR", ",", "object", ",", "cat", ",", "format", ",", "args", ")", "# we do the import here because having it globally causes weird import", "# errors if ou...
32.142857
0.00216
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Creates user. Depends on get_username pipeline. """ if user: return {'user': user} if not username: return None email = details.get('email') original_email = None # email is requir...
[ "def", "create_user", "(", "backend", ",", "details", ",", "response", ",", "uid", ",", "username", ",", "user", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "user", ":", "return", "{", "'user'", ":", "user", "}", "if", ...
34.32
0.003401
def get_job( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves the specified job, whose status is OPEN or recently EXPIRED within the last 90 days. Examp...
[ "def", "get_job", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "...
39.836066
0.00241
def get_dictkey(In, k, dtype): """ returns list of given key (k) from input list of dictionaries (In) in data type dtype. uses command: get_dictkey(In,k,dtype). If dtype =="", data are strings; if "int", data are integers; if "f", data are floats. """ Out = [] for d in In: if...
[ "def", "get_dictkey", "(", "In", ",", "k", ",", "dtype", ")", ":", "Out", "=", "[", "]", "for", "d", "in", "In", ":", "if", "dtype", "==", "''", ":", "Out", ".", "append", "(", "d", "[", "k", "]", ")", "if", "dtype", "==", "'f'", ":", "if",...
30.2
0.006418
def vehicleTypes2flt(outSTRM, vtIDm): """ Currently, rather a stub than an implementation. Writes the vehicle ids stored in the given "vtIDm" map formatted as a .flt file readable by PHEM. The following may be a matter of changes: - A default map is assigned to all vehicle types with the same proba...
[ "def", "vehicleTypes2flt", "(", "outSTRM", ",", "vtIDm", ")", ":", "for", "q", "in", "sorted", "(", "vtIDm", ".", "_m", ")", ":", "print", "(", "\"%s,%s,%s\"", "%", "(", "vtIDm", ".", "g", "(", "q", ")", ",", "\"<VEHDIR>\\PC\\PC_%s.GEN\"", "%", "q", ...
41.545455
0.008565
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the DerivationParameters struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a...
[ "def", "read", "(", "self", ",", "input_stream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "DerivationParameters", ",", "self", ")", ".", "read", "(", "input_stream", ",", "kmip_version", "=", "kmip_versi...
40.333333
0.000949
def contains(self, items, pad=0): """ Test whether coordinates are contained within this tile. Parameters ---------- items : ndarray [3] or [N, 3] N coordinates to check are within the bounds of the tile pad : integer or ndarray [3] anisotropic p...
[ "def", "contains", "(", "self", ",", "items", ",", "pad", "=", "0", ")", ":", "o", "=", "(", "(", "items", ">=", "self", ".", "l", "-", "pad", ")", "&", "(", "items", "<", "self", ".", "r", "+", "pad", ")", ")", "if", "len", "(", "o", "."...
29.782609
0.002829
def encode_canonical(object, output_function=None): """ <Purpose> Encode 'object' in canonical JSON form, as specified at http://wiki.laptop.org/go/Canonical_JSON . It's a restricted dialect of JSON in which keys are always lexically sorted, there is no whitespace, floats aren't allowed, and only q...
[ "def", "encode_canonical", "(", "object", ",", "output_function", "=", "None", ")", ":", "result", "=", "None", "# If 'output_function' is unset, treat it as", "# appending to a list.", "if", "output_function", "is", "None", ":", "result", "=", "[", "]", "output_funct...
34.42029
0.004912
def __set_date(self, value): ''' Sets the date of the payment. @param value:datetime ''' if not issubclass(value.__class__, date): raise ValueError('Invalid date value') self.__date = value
[ "def", "__set_date", "(", "self", ",", "value", ")", ":", "if", "not", "issubclass", "(", "value", ".", "__class__", ",", "date", ")", ":", "raise", "ValueError", "(", "'Invalid date value'", ")", "self", ".", "__date", "=", "value" ]
26.888889
0.008
def list(context, sort, limit, where, verbose): """list(context, sort, limit. where. verbose) List all topics. >>> dcictl topic-list :param string sort: Field to apply sort :param integer limit: Max number of rows to return :param string where: An optional filter criteria :param boolean v...
[ "def", "list", "(", "context", ",", "sort", ",", "limit", ",", "where", ",", "verbose", ")", ":", "topics", "=", "topic", ".", "list", "(", "context", ",", "sort", "=", "sort", ",", "limit", "=", "limit", ",", "where", "=", "where", ")", "utils", ...
34.285714
0.002028
def get_complex(self): '''Returns the record for the complex definition to be used for database storage.''' d = dict( LName = self.lname, LShortName = self.lshortname, LHTMLName = self.lhtmlname, RName = self.rname, RShortName = self.rshortname...
[ "def", "get_complex", "(", "self", ")", ":", "d", "=", "dict", "(", "LName", "=", "self", ".", "lname", ",", "LShortName", "=", "self", ".", "lshortname", ",", "LHTMLName", "=", "self", ".", "lhtmlname", ",", "RName", "=", "self", ".", "rname", ",", ...
38.35
0.036896
def integrate(self, min, max, attr=None, info={}): """ Calculate the total number of points between [min, max). If attr is given, also calculate the sum of the weight. This is a M log(N) operation, where M is the number of min/max queries and N is number of points. ...
[ "def", "integrate", "(", "self", ",", "min", ",", "max", ",", "attr", "=", "None", ",", "info", "=", "{", "}", ")", ":", "if", "numpy", ".", "isscalar", "(", "min", ")", ":", "min", "=", "[", "min", "for", "i", "in", "range", "(", "self", "."...
39.652174
0.002141
def _fmto_groups(self): """Mapping from group to a set of formatoptions""" ret = defaultdict(set) for key in self: ret[getattr(self, key).group].add(getattr(self, key)) return dict(ret)
[ "def", "_fmto_groups", "(", "self", ")", ":", "ret", "=", "defaultdict", "(", "set", ")", "for", "key", "in", "self", ":", "ret", "[", "getattr", "(", "self", ",", "key", ")", ".", "group", "]", ".", "add", "(", "getattr", "(", "self", ",", "key"...
37.333333
0.008734
def apply_T7(word): '''If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the second and third vowels, e.g. [kau.an], [leu.an], [kiu.as].''' WORD = word offset = 0 for vvv in vvv_sequences(WORD): i = vvv.start(2) + 2 + offset ...
[ "def", "apply_T7", "(", "word", ")", ":", "WORD", "=", "word", "offset", "=", "0", "for", "vvv", "in", "vvv_sequences", "(", "WORD", ")", ":", "i", "=", "vvv", ".", "start", "(", "2", ")", "+", "2", "+", "offset", "WORD", "=", "WORD", "[", ":",...
28.266667
0.002283
def get_time_to_first_attention(self, item): """Get the first date at which a comment or reaction was made to the issue by someone other than the user who created the issue """ comment_dates = [str_to_datetime(comment['created_at']) for comment in item['comments_data'] ...
[ "def", "get_time_to_first_attention", "(", "self", ",", "item", ")", ":", "comment_dates", "=", "[", "str_to_datetime", "(", "comment", "[", "'created_at'", "]", ")", "for", "comment", "in", "item", "[", "'comments_data'", "]", "if", "item", "[", "'user'", "...
57.166667
0.008608
def forwast_autodownload(FORWAST_URL): """ Autodownloader for forwast database package for brightway. Used by `lcopt_bw2_forwast_setup` to get the database data. Not designed to be used on its own """ dirpath = tempfile.mkdtemp() r = requests.get(FORWAST_URL) z = zipfile.ZipFile(io.BytesI...
[ "def", "forwast_autodownload", "(", "FORWAST_URL", ")", ":", "dirpath", "=", "tempfile", ".", "mkdtemp", "(", ")", "r", "=", "requests", ".", "get", "(", "FORWAST_URL", ")", "z", "=", "zipfile", ".", "ZipFile", "(", "io", ".", "BytesIO", "(", "r", ".",...
40.5
0.007246
def exec(self, args): """todo: Docstring for exec :param args: arg description :type args: type description :return: :rtype: """ logger.debug("install %s, location %s", args.install, args.location) location = args.location and os.path.abspath(args.locati...
[ "def", "exec", "(", "self", ",", "args", ")", ":", "logger", ".", "debug", "(", "\"install %s, location %s\"", ",", "args", ".", "install", ",", "args", ".", "location", ")", "location", "=", "args", ".", "location", "and", "os", ".", "path", ".", "abs...
31.526316
0.006483
def set_status(self, id, status, timeout, update_time, history=None): """ Set status and update history. """ query = {'_id': {'$regex': '^' + id}} update = { '$set': {'status': status, 'timeout': timeout, 'updateTime': update_time}, '$push': { ...
[ "def", "set_status", "(", "self", ",", "id", ",", "status", ",", "timeout", ",", "update_time", ",", "history", "=", "None", ")", ":", "query", "=", "{", "'_id'", ":", "{", "'$regex'", ":", "'^'", "+", "id", "}", "}", "update", "=", "{", "'$set'", ...
32.47619
0.004274
def ip_between(ip, start, finish): """Checks to see if IP is between start and finish""" if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish): return IPAddress(ip) in IPRange(start, finish) else: return False
[ "def", "ip_between", "(", "ip", ",", "start", ",", "finish", ")", ":", "if", "is_IPv4Address", "(", "ip", ")", "and", "is_IPv4Address", "(", "start", ")", "and", "is_IPv4Address", "(", "finish", ")", ":", "return", "IPAddress", "(", "ip", ")", "in", "I...
36.142857
0.003861
def on_stop(self): """ stop requester """ LOGGER.debug("natsd.Requester.on_stop") self.is_started = False try: LOGGER.debug("natsd.Requester.on_stop - unsubscribe from " + str(self.responseQS)) next(self.nc.unsubscribe(self.responseQS)) exc...
[ "def", "on_stop", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"natsd.Requester.on_stop\"", ")", "self", ".", "is_started", "=", "False", "try", ":", "LOGGER", ".", "debug", "(", "\"natsd.Requester.on_stop - unsubscribe from \"", "+", "str", "(", "self"...
50.021277
0.005006
def update_states_geo_zone_by_id(cls, states_geo_zone_id, states_geo_zone, **kwargs): """Update StatesGeoZone Update attributes of StatesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api...
[ "def", "update_states_geo_zone_by_id", "(", "cls", ",", "states_geo_zone_id", ",", "states_geo_zone", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return"...
50.454545
0.007073
def multinterp(x, y, xquery, slow=False): """Multiple linear interpolations Parameters ---------- x : array_like, shape=(N,) sorted array of x values y : array_like, shape=(N, M) array of y values corresponding to each x value xquery : array_like, shape=(M,) array of que...
[ "def", "multinterp", "(", "x", ",", "y", ",", "xquery", ",", "slow", "=", "False", ")", ":", "x", ",", "y", ",", "xquery", "=", "map", "(", "np", ".", "asarray", ",", "(", "x", ",", "y", ",", "xquery", ")", ")", "assert", "x", ".", "ndim", ...
35.073171
0.000677
def allows_not_principal(self): """Find allowed not-principals.""" not_principals = [] for statement in self.statements: if statement.not_principal and statement.effect == "Allow": not_principals.append(statement) return not_principals
[ "def", "allows_not_principal", "(", "self", ")", ":", "not_principals", "=", "[", "]", "for", "statement", "in", "self", ".", "statements", ":", "if", "statement", ".", "not_principal", "and", "statement", ".", "effect", "==", "\"Allow\"", ":", "not_principals...
36.125
0.006757
def setUnacknowledgedPreKeyMessage(self, preKeyId, signedPreKeyId, baseKey): """ :type preKeyId: int :type signedPreKeyId: int :type baseKey: ECPublicKey """ self.sessionStructure.pendingPreKey.signedPreKeyId = signedPreKeyId self.sessionStructure.pendingPreKey.ba...
[ "def", "setUnacknowledgedPreKeyMessage", "(", "self", ",", "preKeyId", ",", "signedPreKeyId", ",", "baseKey", ")", ":", "self", ".", "sessionStructure", ".", "pendingPreKey", ".", "signedPreKeyId", "=", "signedPreKeyId", "self", ".", "sessionStructure", ".", "pendin...
39.909091
0.004454
def sparkline_value_color_map_apply_to(self, sparkline_value_color_map_apply_to): """Sets the sparkline_value_color_map_apply_to of this ChartSettings. For the single stat view, whether to apply dynamic color settings to the displayed TEXT or BACKGROUND # noqa: E501 :param sparkline_value_col...
[ "def", "sparkline_value_color_map_apply_to", "(", "self", ",", "sparkline_value_color_map_apply_to", ")", ":", "allowed_values", "=", "[", "\"TEXT\"", ",", "\"BACKGROUND\"", "]", "# noqa: E501", "if", "sparkline_value_color_map_apply_to", "not", "in", "allowed_values", ":",...
54.9375
0.004474
def _server_loop(self, client, client_addr): """Read requests from one client socket, 'client'.""" while not self._stopped and not _shutting_down: try: with self._unlock(): request = mock_server_receive_request(client, self) self._requests...
[ "def", "_server_loop", "(", "self", ",", "client", ",", "client_addr", ")", ":", "while", "not", "self", ".", "_stopped", "and", "not", "_shutting_down", ":", "try", ":", "with", "self", ".", "_unlock", "(", ")", ":", "request", "=", "mock_server_receive_r...
38.029412
0.001508
def _time_interval_operation(self, interval, operation, percentile=0): """Get a collection of a certain time interval with a given math operation.""" # retrive the function that correctly describes the operation if operation == 'average': funct = self._average elif operation ...
[ "def", "_time_interval_operation", "(", "self", ",", "interval", ",", "operation", ",", "percentile", "=", "0", ")", ":", "# retrive the function that correctly describes the operation", "if", "operation", "==", "'average'", ":", "funct", "=", "self", ".", "_average",...
44.06383
0.003307
def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha1) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1]
[ "def", "sign", "(", "self", ",", "request", ",", "consumer", ",", "token", ")", ":", "key", ",", "raw", "=", "self", ".", "signing_base", "(", "request", ",", "consumer", ",", "token", ")", "hashed", "=", "hmac", ".", "new", "(", "key", ",", "raw",...
35.75
0.006826
def deploy_lambda(awsclient, function_name, role, handler_filename, handler_function, folders, description, timeout, memory, subnet_ids=None, security_groups=None, artifact_bucket=None, zipfile=None, fail_deployment_on_unsuccessfu...
[ "def", "deploy_lambda", "(", "awsclient", ",", "function_name", ",", "role", ",", "handler_filename", ",", "handler_function", ",", "folders", ",", "description", ",", "timeout", ",", "memory", ",", "subnet_ids", "=", "None", ",", "security_groups", "=", "None",...
45.536232
0.001246
def _build_egg(egg, archive_filename, to_dir): """Build Setuptools egg.""" with archive_context(archive_filename): # building an egg log.warn('Building a Setuptools egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) # returning the result log.war...
[ "def", "_build_egg", "(", "egg", ",", "archive_filename", ",", "to_dir", ")", ":", "with", "archive_context", "(", "archive_filename", ")", ":", "# building an egg", "log", ".", "warn", "(", "'Building a Setuptools egg in %s'", ",", "to_dir", ")", "_python_cmd", "...
39.9
0.002451
def autoscale_eydata(self): """ Rescales the error so the next fit will give reduced chi squareds of 1. Each data set will be scaled independently, and you may wish to run this a few times until it converges. """ if not self.results: self._error("You must com...
[ "def", "autoscale_eydata", "(", "self", ")", ":", "if", "not", "self", ".", "results", ":", "self", ".", "_error", "(", "\"You must complete a fit first.\"", ")", "return", "r", "=", "self", ".", "reduced_chi_squareds", "(", ")", "# loop over the eydata and rescal...
29.227273
0.00753
def andor_tags(self): """Return consolidated metadata from Andor tags as dict. Remove Andor tags from self.tags. """ if not self.is_andor: return None tags = self.tags result = {'Id': tags['AndorId'].value} for tag in list(self.tags.values()): ...
[ "def", "andor_tags", "(", "self", ")", ":", "if", "not", "self", ".", "is_andor", ":", "return", "None", "tags", "=", "self", ".", "tags", "result", "=", "{", "'Id'", ":", "tags", "[", "'AndorId'", "]", ".", "value", "}", "for", "tag", "in", "list"...
30
0.003401
def throw(self, exception_class, should_throw): '''Defines if the an exception should be thrown after the request is sent Args: exception_class (class): The class of the exception to instantiate should_throw (function): The predicate that should indicate if the exception ...
[ "def", "throw", "(", "self", ",", "exception_class", ",", "should_throw", ")", ":", "return", "self", ".", "__copy_and_set", "(", "'throws'", ",", "self", ".", "_throws", "+", "[", "(", "exception_class", ",", "should_throw", ")", "]", ")" ]
48.916667
0.010033
def delete(self, model_name): """Delete a model. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. """ full_name = model_name if not model_name.startswith('projects/'): full_name = ('project...
[ "def", "delete", "(", "self", ",", "model_name", ")", ":", "full_name", "=", "model_name", "if", "not", "model_name", ".", "startswith", "(", "'projects/'", ")", ":", "full_name", "=", "(", "'projects/%s/models/%s'", "%", "(", "self", ".", "_project_id", ","...
43
0.004878
def _find_from_file(full_doc, from_file_keyword): """ Finds a line in <full_doc> like <from_file_keyword> <colon> <path> and return path """ path = None for line in full_doc.splitlines(): if from_file_keyword in line: parts = line.strip().split(':') if ...
[ "def", "_find_from_file", "(", "full_doc", ",", "from_file_keyword", ")", ":", "path", "=", "None", "for", "line", "in", "full_doc", ".", "splitlines", "(", ")", ":", "if", "from_file_keyword", "in", "line", ":", "parts", "=", "line", ".", "strip", "(", ...
24.444444
0.002188
def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFo...
[ "def", "_assert_no_error", "(", "error", ",", "exception_class", "=", "None", ")", ":", "if", "error", "==", "0", ":", "return", "cf_error_string", "=", "Security", ".", "SecCopyErrorMessageString", "(", "error", ",", "None", ")", "output", "=", "_cf_string_to...
27.631579
0.001842
def close(self, clear=True): """ Close the file open in the editor: - clear editor content - reset file attributes to their default values :param clear: True to clear the editor content. Default is True. """ Cache().set_cursor_position( self.p...
[ "def", "close", "(", "self", ",", "clear", "=", "True", ")", ":", "Cache", "(", ")", ".", "set_cursor_position", "(", "self", ".", "path", ",", "self", ".", "editor", ".", "textCursor", "(", ")", ".", "position", "(", ")", ")", "self", ".", "editor...
33.875
0.003591
def get_level_id(self): """Gets the ``Id`` of a ``Grade`` corresponding to the assessment difficulty. return: (osid.id.Id) - a grade ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_templ...
[ "def", "get_level_id", "(", "self", ")", ":", "# Implemented from template for osid.resource.Resource.get_avatar_id_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'levelId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'this Assess...
40.75
0.008
def beat_track(y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120.0, tightness=100, trim=True, bpm=None, units='frames'): r'''Dynamic programming beat tracker. Beats are detected in three stages, following the method of [1]_: 1. Measure onset strength ...
[ "def", "beat_track", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "onset_envelope", "=", "None", ",", "hop_length", "=", "512", ",", "start_bpm", "=", "120.0", ",", "tightness", "=", "100", ",", "trim", "=", "True", ",", "bpm", "=", "None", ...
30.862069
0.00018
def clean_etag(self, etag): """Cleans the ETag as returned by :func:`get_etag`. Will wrap it in quotes and append the extension for the current MIME type. """ if etag: etag = etag.replace('"', '') extension = None for ext, mime in self.EXTENSION_MAP: ...
[ "def", "clean_etag", "(", "self", ",", "etag", ")", ":", "if", "etag", ":", "etag", "=", "etag", ".", "replace", "(", "'\"'", ",", "''", ")", "extension", "=", "None", "for", "ext", ",", "mime", "in", "self", ".", "EXTENSION_MAP", ":", "if", "mime"...
36.642857
0.003802
def set_site(request): """ Put the selected site ID into the session - posted to from the "Select site" drop-down in the header of the admin. The site ID is then used in favour of the current request's domain in ``yacms.core.managers.CurrentSiteManager``. """ site_id = int(request.GET["site_...
[ "def", "set_site", "(", "request", ")", ":", "site_id", "=", "int", "(", "request", ".", "GET", "[", "\"site_id\"", "]", ")", "if", "not", "request", ".", "user", ".", "is_superuser", ":", "try", ":", "SitePermission", ".", "objects", ".", "get", "(", ...
40.73913
0.001043
def uncache(self,*items): """ Removes all, or specified items from cache Use this after reading a large amount of large objects to free up memory, when you won't be needing the objects for a while. """ if not items: self.cache = {} for it in items: ...
[ "def", "uncache", "(", "self", ",", "*", "items", ")", ":", "if", "not", "items", ":", "self", ".", "cache", "=", "{", "}", "for", "it", "in", "items", ":", "self", ".", "cache", ".", "pop", "(", "it", ",", "None", ")" ]
28.583333
0.011299
def kilometers(meters=0, miles=0, feet=0, nautical=0): """ TODO docs. """ ret = 0. if meters: ret += meters / 1000. if feet: ret += feet / ft(1.) if nautical: ret += nautical / nm(1.) ret += miles * 1.609344 return ret
[ "def", "kilometers", "(", "meters", "=", "0", ",", "miles", "=", "0", ",", "feet", "=", "0", ",", "nautical", "=", "0", ")", ":", "ret", "=", "0.", "if", "meters", ":", "ret", "+=", "meters", "/", "1000.", "if", "feet", ":", "ret", "+=", "feet"...
20.461538
0.003597
def view_call(method_name, *args, **kwargs): """ Creates an effect that will drop the current effect value, call the view's method with specified name with the specified arguments and keywords. @param method_name: the name of method belonging to the view. @type method_name: str """ def ...
[ "def", "view_call", "(", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "view_call", "(", "_value", ",", "context", ",", "*", "*", "_params", ")", ":", "method", "=", "getattr", "(", "context", "[", "\"view\"", "]", ",", ...
33.214286
0.002092
def addKerning(self, instanceLocation=None, sources=None): """ Calculate the kerning data for this location and add it to this instance. * instanceLocation: Location object * source: dict of {sourcename: (source, sourceLocation)} """ items = [] kern...
[ "def", "addKerning", "(", "self", ",", "instanceLocation", "=", "None", ",", "sources", "=", "None", ")", ":", "items", "=", "[", "]", "kerningObject", "=", "self", ".", "font", ".", "kerning", "kerningMasters", "=", "[", "]", "if", "instanceLocation", "...
42.222222
0.005788
def get_as_dataframe(worksheet, evaluate_formulas=False, **options): """ Returns the worksheet contents as a DataFrame. :param worksheet: the worksheet. :param evaluate_formulas: if True, get the value of a cell after formula evaluation; otherwise g...
[ "def", "get_as_dataframe", "(", "worksheet", ",", "evaluate_formulas", "=", "False", ",", "*", "*", "options", ")", ":", "all_values", "=", "_get_all_values", "(", "worksheet", ",", "evaluate_formulas", ")", "return", "TextParser", "(", "all_values", ",", "*", ...
42.888889
0.003802
def search_json_log(filepath, key, value): """Search json log file for a key=value pair. :param filepath: Valid path to a json file :param key: key to match :param value: value to match :returns: First matching line in json log file, parsed by :py:func:`json.loads` """ try: with ope...
[ "def", "search_json_log", "(", "filepath", ",", "key", ",", "value", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "\"r\"", ")", "as", "fh", ":", "for", "line", "in", "fh", ".", "readlines", "(", ")", ":", "log", "=", "json", ".", "...
32.470588
0.005282
def eval_formula(expr: str, dataframe=None, context=None): ''' expr: string Symbolic expression to evaluate. Example: `k(1)-delta*k(0)-i` table: (optional) pandas dataframe Each column is a time series, which can be indexed with dolo notations. context: dict or CalibrationDict ...
[ "def", "eval_formula", "(", "expr", ":", "str", ",", "dataframe", "=", "None", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "dd", "=", "{", "}", "# context dictionary", "elif", "isinstance", "(", "context", ",", "Calibration...
25.926829
0.001813
def _step7func(self, samples, force, ipyclient): """ Step 7: Filter and write output files """ ## Get sample objects from list of strings samples = _get_samples(self, samples) if self._headers: print("\n Step 7: Filter and write output files for {} Samples".\ ...
[ "def", "_step7func", "(", "self", ",", "samples", ",", "force", ",", "ipyclient", ")", ":", "## Get sample objects from list of strings", "samples", "=", "_get_samples", "(", "self", ",", "samples", ")", "if", "self", ".", "_headers", ":", "print", "(", "\"\\n...
43.977273
0.009606
def extract_words(files): ''' Extracts individual words form files and exports them to individual files. ''' output_directory = 'extracted_words' if not os.path.exists(output_directory): os.makedirs(output_directory) for f in files: file_format = None source_segment = None ...
[ "def", "extract_words", "(", "files", ")", ":", "output_directory", "=", "'extracted_words'", "if", "not", "os", ".", "path", ".", "exists", "(", "output_directory", ")", ":", "os", ".", "makedirs", "(", "output_directory", ")", "for", "f", "in", "files", ...
43.560976
0.001643
def get_inline_views_opts_from_fieldsets(fieldsets): """Returns a list of field names from an admin fieldsets structure.""" inline_views = [] for _, opts in fieldsets or (): if 'fieldsets' in opts: inline_views += get_inline_views_opts_from_fieldsets(opts.get('fieldsets')) elif '...
[ "def", "get_inline_views_opts_from_fieldsets", "(", "fieldsets", ")", ":", "inline_views", "=", "[", "]", "for", "_", ",", "opts", "in", "fieldsets", "or", "(", ")", ":", "if", "'fieldsets'", "in", "opts", ":", "inline_views", "+=", "get_inline_views_opts_from_f...
43.888889
0.004963
def db_en020(self, value=None): """ Corresponds to IDD Field `db_en020` mean coincident dry-bulb temperature to Enthalpy corresponding to 2.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `db_en020` Unit: C ...
[ "def", "db_en020", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float...
36.136364
0.003676
def set_theme(color=True): """ defines if the console messages are printed in color :param color: if True its printed in color :return: """ if color: Console.theme = Console.theme_color else: Console.theme = Console.theme_bw Consol...
[ "def", "set_theme", "(", "color", "=", "True", ")", ":", "if", "color", ":", "Console", ".", "theme", "=", "Console", ".", "theme_color", "else", ":", "Console", ".", "theme", "=", "Console", ".", "theme_bw", "Console", ".", "color", "=", "color" ]
29.545455
0.008955
def get_cluster_custom_object(self, group, version, plural, name, **kwargs): # noqa: E501 """get_cluster_custom_object # noqa: E501 Returns a cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, pleas...
[ "def", "get_cluster_custom_object", "(", "self", ",", "group", ",", "version", ",", "plural", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'as...
53.833333
0.001521
def log(db, job_id, timestamp, level, process, message): """ Write a log record in the database. :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: a job ID :param timestamp: timestamp to store in the log record :param level: logging level to...
[ "def", "log", "(", "db", ",", "job_id", ",", "timestamp", ",", "level", ",", "process", ",", "message", ")", ":", "db", "(", "'INSERT INTO log (job_id, timestamp, level, process, message) '", "'VALUES (?X)'", ",", "(", "job_id", ",", "timestamp", ",", "level", "...
31.684211
0.001613
def common_twig(self): """ The twig that is common between all items in this ParameterSet. This twig gives a single string which can point back to this ParameterSet (but may include other entries as well) see also :meth:`uniquetwig` :return: twig (full) of this Paramete...
[ "def", "common_twig", "(", "self", ")", ":", "return", "\"@\"", ".", "join", "(", "[", "getattr", "(", "self", ",", "k", ")", "for", "k", "in", "_meta_fields_twig", "if", "self", ".", "meta", ".", "get", "(", "k", ")", "is", "not", "None", "]", "...
38.727273
0.009174
def _filter_queryset(self, queryset): """Filter queryset by entity, label and position. Due to a bug in django-filter these filters have to be applied manually: https://github.com/carltongibson/django-filter/issues/883 """ entities = self.request.query_params.getlist('en...
[ "def", "_filter_queryset", "(", "self", ",", "queryset", ")", ":", "entities", "=", "self", ".", "request", ".", "query_params", ".", "getlist", "(", "'entity'", ")", "labels", "=", "self", ".", "request", ".", "query_params", ".", "getlist", "(", "'label'...
40.558824
0.002125
def reload(self): """Reload notmuch and alot config files""" self.read_notmuch_config(self._notmuchconfig.filename) self.read_config(self._config.filename)
[ "def", "reload", "(", "self", ")", ":", "self", ".", "read_notmuch_config", "(", "self", ".", "_notmuchconfig", ".", "filename", ")", "self", ".", "read_config", "(", "self", ".", "_config", ".", "filename", ")" ]
44
0.011173
def __roman_to_cyrillic(self, word): """ Transliterate a Russian word back into the Cyrillic alphabet. A Russian word formerly transliterated into the Roman alphabet in order to ease the stemming process, is transliterated back into the Cyrillic alphabet, its original form. ...
[ "def", "__roman_to_cyrillic", "(", "self", ",", "word", ")", ":", "word", "=", "(", "word", ".", "replace", "(", "\"i^u\"", ",", "\"\\u044E\"", ")", ".", "replace", "(", "\"i^a\"", ",", "\"\\u044F\"", ")", ".", "replace", "(", "\"shch\"", ",", "\"\\u0449...
48.75
0.001676
def RetrieveIP4Info(self, ip): """Retrieves information for an IP4 address.""" if ip.is_private: return (IPInfo.INTERNAL, "Internal IP address.") try: # It's an external IP, let's try to do a reverse lookup. res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD) return (IPInfo.EX...
[ "def", "RetrieveIP4Info", "(", "self", ",", "ip", ")", ":", "if", "ip", ".", "is_private", ":", "return", "(", "IPInfo", ".", "INTERNAL", ",", "\"Internal IP address.\"", ")", "try", ":", "# It's an external IP, let's try to do a reverse lookup.", "res", "=", "soc...
43.9
0.013393
def state_create_is_valid( nameop ): """ Is a nameop a valid state-preorder operation? """ assert '__state_create__' in nameop, "Not tagged with @state_create" assert nameop['__state_create__'], "BUG: tagged False by @state_create" assert '__preorder__' in nameop, "No preorder" assert '__tab...
[ "def", "state_create_is_valid", "(", "nameop", ")", ":", "assert", "'__state_create__'", "in", "nameop", ",", "\"Not tagged with @state_create\"", "assert", "nameop", "[", "'__state_create__'", "]", ",", "\"BUG: tagged False by @state_create\"", "assert", "'__preorder__'", ...
43.692308
0.005172
def session_update(self, session, *_): """Record the sqlalchemy object states in the middle of session, prepare the events for the final pub in session_commit. """ self._session_init(session) session.pending_write |= set(session.new) session.pending_update |= set(session....
[ "def", "session_update", "(", "self", ",", "session", ",", "*", "_", ")", ":", "self", ".", "_session_init", "(", "session", ")", "session", ".", "pending_write", "|=", "set", "(", "session", ".", "new", ")", "session", ".", "pending_update", "|=", "set"...
49.777778
0.004386
def delete_directory(db, user_id, api_path): """ Delete a directory. """ db_dirname = from_api_dirname(api_path) try: result = db.execute( directories.delete().where( and_( directories.c.user_id == user_id, directories.c.nam...
[ "def", "delete_directory", "(", "db", ",", "user_id", ",", "api_path", ")", ":", "db_dirname", "=", "from_api_dirname", "(", "api_path", ")", "try", ":", "result", "=", "db", ".", "execute", "(", "directories", ".", "delete", "(", ")", ".", "where", "(",...
25.04
0.001538
def set(self, name, value): """Set a variable before ``call()``.""" if not hasattr(self, 'funcs'): raise StartupError('startup cannot be called again') self.variable_values[name] = value
[ "def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'funcs'", ")", ":", "raise", "StartupError", "(", "'startup cannot be called again'", ")", "self", ".", "variable_values", "[", "name", "]", "=", "...
43.6
0.009009
def setPlainText(self, txt, mimetype='text/x-python', encoding='utf-8'): """ Extends QCodeEdit.setPlainText to allow user to setPlainText without mimetype (since the python syntax highlighter does not use it). """ try: self.syntax_highlighter.docstrings[:] = [] ...
[ "def", "setPlainText", "(", "self", ",", "txt", ",", "mimetype", "=", "'text/x-python'", ",", "encoding", "=", "'utf-8'", ")", ":", "try", ":", "self", ".", "syntax_highlighter", ".", "docstrings", "[", ":", "]", "=", "[", "]", "self", ".", "syntax_highl...
44.272727
0.004024
def chdir(path: str) -> Iterator[None]: """Context manager for changing dir and restoring previous workdir after exit. """ curdir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(curdir)
[ "def", "chdir", "(", "path", ":", "str", ")", "->", "Iterator", "[", "None", "]", ":", "curdir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "path", ")", "try", ":", "yield", "finally", ":", "os", ".", "chdir", "(", "curdir", "...
25.222222
0.008511
def percentOutputsStableOverNTimeSteps(vectors, numSamples=None): """ Returns the percent of the outputs that remain completely stable over N time steps. Parameters: ----------------------------------------------- vectors: the vectors for which the stability is calculated numSamples: the numbe...
[ "def", "percentOutputsStableOverNTimeSteps", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "# ----------------------------------------------------------------------", "# Calculate the stability", "totalSamples", "=", "len", "(", "vectors", ")", "windowSize", "=", ...
30.078947
0.010169
def subscribe(self, sr): """Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value ...
[ "def", "subscribe", "(", "self", ",", "sr", ")", ":", "if", "not", "sr", ".", "startswith", "(", "'t5_'", ")", ":", "sr", "=", "self", ".", "subreddit", "(", "sr", ")", ".", "name", "data", "=", "dict", "(", "action", "=", "'sub'", ",", "sr", "...
57.75
0.008523
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response....
[ "def", "send_message", "(", "self", ",", "request", ":", "str", ",", "response_expected", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "response", "=", "self", ".", "session", ".", "post", "(", "self", ".", "endpoint", ...
33.666667
0.007707
def make_unpublished(self, request, queryset): """ Marks selected news items as unpublished """ rows_updated = queryset.update(is_published=False) self.message_user(request, ungettext('%(count)d newsitem was unpublished', ...
[ "def", "make_unpublished", "(", "self", ",", "request", ",", "queryset", ")", ":", "rows_updated", "=", "queryset", ".", "update", "(", "is_published", "=", "False", ")", "self", ".", "message_user", "(", "request", ",", "ungettext", "(", "'%(count)d newsitem ...
48.444444
0.004505
def create_business_rules_dependencies(self): """Create business rules dependencies for hosts and services :return: None """ for item in itertools.chain(self.hosts, self.services): if not item.got_business_rule: continue bp_items = item.business...
[ "def", "create_business_rules_dependencies", "(", "self", ")", ":", "for", "item", "in", "itertools", ".", "chain", "(", "self", ".", "hosts", ",", "self", ".", "services", ")", ":", "if", "not", "item", ".", "got_business_rule", ":", "continue", "bp_items",...
42.785714
0.004898
def _get_applicable_options(self, options: Dict[str, Dict[str, Any]]): """ Returns the options that are applicable to this particular parser, from the full map of options. It first uses 'get_id_for_options()' to know the id of this parser, and then simply extracts the contents of the opt...
[ "def", "_get_applicable_options", "(", "self", ",", "options", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", ":", "return", "get_options_for_id", "(", "options", ",", "self", ".", "get_id_for_options", "(", ")", ")" ]
52.6
0.007477
def make_lambda(call): """Wrap an AST Call node to lambda expression node. call: ast.Call node """ empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]) return ast.Lambda(args=empty_args, body=call)
[ "def", "make_lambda", "(", "call", ")", ":", "empty_args", "=", "ast", ".", "arguments", "(", "args", "=", "[", "]", ",", "vararg", "=", "None", ",", "kwarg", "=", "None", ",", "defaults", "=", "[", "]", ")", "return", "ast", ".", "Lambda", "(", ...
38.833333
0.004202
def process_item(self, item, spider): """ Use the Pa11y command line tool to get an a11y report. """ config_file = write_pa11y_config(item) args = [ self.pa11y_path, item["url"], '--config={file}'.format(file=config_file.name), ] ...
[ "def", "process_item", "(", "self", ",", "item", ",", "spider", ")", ":", "config_file", "=", "write_pa11y_config", "(", "item", ")", "args", "=", "[", "self", ".", "pa11y_path", ",", "item", "[", "\"url\"", "]", ",", "'--config={file}'", ".", "format", ...
39.87037
0.000907
def encrypt(self, data, pad=True): """ DES encrypts the data based on the key it was initialised with. :param data: The bytes string to encrypt :param pad: Whether to right pad data with \x00 to a multiple of 8 :return: The encrypted bytes string """ encrypted_da...
[ "def", "encrypt", "(", "self", ",", "data", ",", "pad", "=", "True", ")", ":", "encrypted_data", "=", "b\"\"", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "8", ")", ":", "block", "=", "data", "[", "i", ":", "i", "+...
37.9
0.002574
def Serghides_1(Re, eD): r'''Calculates Darcy friction factor using the method in Serghides (1984) [2]_ as shown in [1]_. .. math:: f=\left[A-\frac{(B-A)^2}{C-2B+A}\right]^{-2} .. math:: A=-2\log_{10}\left[\frac{\epsilon/D}{3.7}+\frac{12}{Re}\right] .. math:: B=-2\log_{10}...
[ "def", "Serghides_1", "(", "Re", ",", "eD", ")", ":", "A", "=", "-", "2", "*", "log10", "(", "eD", "/", "3.7", "+", "12", "/", "Re", ")", "B", "=", "-", "2", "*", "log10", "(", "eD", "/", "3.7", "+", "2.51", "*", "A", "/", "Re", ")", "C...
26.48
0.000728
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 _flush(self): """Compresses and writes data in the cache to file.""" if self.file.closed: return cache = b"".join(self.cache) if not cache: # Nothing to write return uncompressed_data = cache[:self.MAX_CACHE_SIZE] # Save data that c...
[ "def", "_flush", "(", "self", ")", ":", "if", "self", ".", "file", ".", "closed", ":", "return", "cache", "=", "b\"\"", ".", "join", "(", "self", ".", "cache", ")", "if", "not", "cache", ":", "# Nothing to write", "return", "uncompressed_data", "=", "c...
44.714286
0.002346
def update_vm_result(self, context, msg): """Update VM's result field in the DB. The result reflects the success of failure of operation when an agent processes the vm info. """ args = jsonutils.loads(msg) agent = context.get('agent') port_id = args.get('port_uui...
[ "def", "update_vm_result", "(", "self", ",", "context", ",", "msg", ")", ":", "args", "=", "jsonutils", ".", "loads", "(", "msg", ")", "agent", "=", "context", ".", "get", "(", "'agent'", ")", "port_id", "=", "args", ".", "get", "(", "'port_uuid'", "...
40.230769
0.001867
def _get_dfs(csvs): """ LiPD Version 1.2 Create a data frame for each table for the given key :param dict csvs: LiPD metadata dictionary :return dict: paleo data data frames """ logger_dataframes.info("enter get_lipd_cols") # placeholders for the incoming data frames dfs = {"chronDat...
[ "def", "_get_dfs", "(", "csvs", ")", ":", "logger_dataframes", ".", "info", "(", "\"enter get_lipd_cols\"", ")", "# placeholders for the incoming data frames", "dfs", "=", "{", "\"chronData\"", ":", "{", "}", ",", "\"paleoData\"", ":", "{", "}", "}", "try", ":",...
37.958333
0.002141
def compare_schemas(self, db_x, db_y, show=True): """ Compare the structures of two databases. Analysis's and compares the column definitions of each table in both databases's. Identifies differences in column names, data types and keys. """ # TODO: Improve meth...
[ "def", "compare_schemas", "(", "self", ",", "db_x", ",", "db_y", ",", "show", "=", "True", ")", ":", "# TODO: Improve method", "self", ".", "_printer", "(", "\"\\tComparing database schema's {0} and {1}\"", ".", "format", "(", "db_x", ",", "db_y", ")", ")", "#...
41.019608
0.002801
def forward_state(self, sequence, state=None): """ Forward propagate a sequence through the network accounting for the state """ if state is None: state = self.zero_state(sequence.size(0)) data = self.input_block(sequence) state_outputs = [] # for layer_length, lay...
[ "def", "forward_state", "(", "self", ",", "sequence", ",", "state", "=", "None", ")", ":", "if", "state", "is", "None", ":", "state", "=", "self", ".", "zero_state", "(", "sequence", ".", "size", "(", "0", ")", ")", "data", "=", "self", ".", "input...
37.6
0.004322
def main(args): '''Function run when called from command line.''' options = { '-rfft': ['resetFFTscale',False], '-r1': ['readOneCoil',False], '-rp': ['readPhaseCorInfo',False], '-rn': ['readNavigator',False], '-skipts': ['readTimeSta...
[ "def", "main", "(", "args", ")", ":", "options", "=", "{", "'-rfft'", ":", "[", "'resetFFTscale'", ",", "False", "]", ",", "'-r1'", ":", "[", "'readOneCoil'", ",", "False", "]", ",", "'-rp'", ":", "[", "'readPhaseCorInfo'", ",", "False", "]", ",", "'...
41.6875
0.02346
def parseString( self, instring, parseAll=False ): """ Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be succe...
[ "def", "parseString", "(", "self", ",", "instring", ",", "parseAll", "=", "False", ")", ":", "ParserElement", ".", "resetCache", "(", ")", "if", "not", "self", ".", "streamlined", ":", "self", ".", "streamline", "(", ")", "#~ self.saveAsList = True", "for", ...
42.039216
0.00866
def _process_foreign_keys(cls, foreign_keys, node_data): """For each foreign key try to load the actual object so load_bulk doesn't fail trying to load an int where django expects a model instance """ for key in foreign_keys.keys(): if key in node_data: ...
[ "def", "_process_foreign_keys", "(", "cls", ",", "foreign_keys", ",", "node_data", ")", ":", "for", "key", "in", "foreign_keys", ".", "keys", "(", ")", ":", "if", "key", "in", "node_data", ":", "node_data", "[", "key", "]", "=", "foreign_keys", "[", "key...
44.444444
0.004902
def get_agent(self): """Gets the ``Agent`` who created this entry. return: (osid.authentication.Agent) - the ``Agent`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for os...
[ "def", "get_agent", "(", "self", ")", ":", "# Implemented from template for osid.resource.Resource.get_avatar_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'agentId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'this LogEntry has...
49.222222
0.005537
def _is_pod_host_networked(self, pod_uid): """ Return if the pod is on host Network Return False if the Pod isn't in the pod list :param pod_uid: str :return: bool """ for pod in self.pod_list['items']: if pod.get('metadata', {}).get('uid', '') == pod_...
[ "def", "_is_pod_host_networked", "(", "self", ",", "pod_uid", ")", ":", "for", "pod", "in", "self", ".", "pod_list", "[", "'items'", "]", ":", "if", "pod", ".", "get", "(", "'metadata'", ",", "{", "}", ")", ".", "get", "(", "'uid'", ",", "''", ")",...
36.727273
0.004831
def _prepare_wsdl_objects(self): """ This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request. """ # Default behavior is to not request transit information self.ReturnTransitAndCommit = False # T...
[ "def", "_prepare_wsdl_objects", "(", "self", ")", ":", "# Default behavior is to not request transit information", "self", ".", "ReturnTransitAndCommit", "=", "False", "# This is the primary data structure for processShipment requests.", "self", ".", "RequestedShipment", "=", "self...
45.326531
0.001763
def _get_conn(key=None, keyid=None, profile=None, region=None, **kwargs): ''' Create a boto3 client connection to EFS ''' client = None if profile: if isinstance(profile, six.string_types): if profile in __pillar__: ...
[ "def", "_get_conn", "(", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "None", "if", "profile", ":", "if", "isinstance", "(", "profile", ","...
28.775
0.00084
def exit_full_screen(self): """Change from full screen to windowed mode and remove key binding""" self.tk.attributes("-fullscreen", False) self._full_screen = False self.events.remove_event("<FullScreen.Escape>")
[ "def", "exit_full_screen", "(", "self", ")", ":", "self", ".", "tk", ".", "attributes", "(", "\"-fullscreen\"", ",", "False", ")", "self", ".", "_full_screen", "=", "False", "self", ".", "events", ".", "remove_event", "(", "\"<FullScreen.Escape>\"", ")" ]
48
0.008197
def entities(self, name_id): """ Returns all the entities of assertions for a subject, disregarding whether the assertion still is valid or not. :param name_id: The subject identifier, a NameID instance :return: A possibly empty list of entity identifiers """ cni = code(...
[ "def", "entities", "(", "self", ",", "name_id", ")", ":", "cni", "=", "code", "(", "name_id", ")", "return", "list", "(", "self", ".", "_db", "[", "cni", "]", ".", "keys", "(", ")", ")" ]
40.222222
0.005405
def get_index_from_coord(coord, base_index): """Function to return the coordinate as integer, integer array or slice If `coord` is zero-dimensional, the corresponding integer in `base_index` will be supplied. Otherwise it is first tried to return a slice, if that does not work an integer array with the...
[ "def", "get_index_from_coord", "(", "coord", ",", "base_index", ")", ":", "try", ":", "values", "=", "coord", ".", "values", "except", "AttributeError", ":", "values", "=", "coord", "if", "values", ".", "ndim", "==", "0", ":", "return", "base_index", ".", ...
34.9
0.000929
def from_validated_yaml(cls, yaml_str, selectable, **kwargs): """Create a shelf using a yaml shelf definition. :param yaml_str: A string containing yaml ingredient definitions. :param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy join to select from. :return: A shelf...
[ "def", "from_validated_yaml", "(", "cls", ",", "yaml_str", ",", "selectable", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "safe_load", "(", "yaml_str", ")", "return", "cls", ".", "from_config", "(", "obj", ",", "selectable", ",", "*", "*", "kwargs", ...
46.6
0.004211
def write (stream, items, fieldnames, tabwidth=8): """Write a typed tabular text file to the specified stream. Arguments: stream The destination stream. items An iterable of items to write. Two passes have to be made over the items (to discover the needed column widths), so thi...
[ "def", "write", "(", "stream", ",", "items", ",", "fieldnames", ",", "tabwidth", "=", "8", ")", ":", "if", "isinstance", "(", "fieldnames", ",", "six", ".", "string_types", ")", ":", "fieldnames", "=", "fieldnames", ".", "split", "(", ")", "maxlens", "...
30.068182
0.010977
def getAllViewsAsDict(self): """Return all the stats views (dict).""" return {p: self._plugins[p].get_views() for p in self._plugins}
[ "def", "getAllViewsAsDict", "(", "self", ")", ":", "return", "{", "p", ":", "self", ".", "_plugins", "[", "p", "]", ".", "get_views", "(", ")", "for", "p", "in", "self", ".", "_plugins", "}" ]
49
0.013423
def step_command_output_should_not_contain_log_records_from_categories(context): """ Verifies that the command output contains not log records from the provided log categories (in any order). .. code-block: gherkin Given I define the log record schema: | category | level | message ...
[ "def", "step_command_output_should_not_contain_log_records_from_categories", "(", "context", ")", ":", "assert", "context", ".", "table", ",", "\"REQUIRE: context.table\"", "context", ".", "table", ".", "require_column", "(", "\"category\"", ")", "record_schema", "=", "co...
41.5
0.002356
def get_reference(self, datas, name): """ Get serialized reference datas Because every reference is turned to a dict (that stands on ``keys`` variable that is a list of key names), every variables must have the same exact length of word than the key name list. A referen...
[ "def", "get_reference", "(", "self", ",", "datas", ",", "name", ")", ":", "rule_name", "=", "'-'", ".", "join", "(", "(", "RULE_REFERENCE", ",", "name", ")", ")", "structure_mode", "=", "'nested'", "if", "rule_name", "not", "in", "datas", ":", "msg", "...
38.892308
0.000772