code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if isinstance(cls.__executor, ThreadPoolExecutor): if cls.__executor.max_workers == max_workers: return cls.__executor.shutdown() cls.__executor = ThreadPoolExecutor(max_workers=max_workers)
def configure(cls: typing.Type["ThreadPooled"], max_workers: typing.Optional[int] = None) -> None
Pool executor create and configure. :param max_workers: Maximum workers :type max_workers: typing.Optional[int]
3.280167
3.124168
1.049933
if not isinstance(self.__executor, ThreadPoolExecutor) or self.__executor.is_shutdown: self.configure() return self.__executor
def executor(self) -> "ThreadPoolExecutor"
Executor instance. :rtype: ThreadPoolExecutor
4.629697
5.718728
0.809568
return self.__loop_getter
def loop_getter( self ) -> typing.Optional[typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]]
Loop getter. :rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]
19.358479
16.481094
1.174587
if callable(self.loop_getter): if self.loop_getter_need_context: return self.loop_getter(*args, **kwargs) # pylint: disable=not-callable return self.loop_getter() # pylint: disable=not-callable return self.loop_getter
def _get_loop(self, *args: typing.Any, **kwargs: typing.Any) -> typing.Optional[asyncio.AbstractEventLoop]
Get event loop in decorator class.
2.683879
2.475434
1.084205
prepared = self._await_if_required(func) # noinspection PyMissingOrEmptyDocstring @functools.wraps(prepared) # pylint: disable=missing-docstring def wrapper( *args: typing.Any, **kwargs: typing.Any ) -> typing.Union[ "concurrent.futures.Future[t...
def _get_function_wrapper( self, func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]] ) -> typing.Callable[..., "typing.Union[concurrent.futures.Future[typing.Any], typing.Awaitable[typing.Any]]"]
Here should be constructed and returned real decorator. :param func: Wrapped function :type func: typing.Callable :return: wrapped coroutine or function :rtype: typing.Callable[..., typing.Union[typing.Awaitable, concurrent.futures.Future]]
2.017782
2.200444
0.916989
if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']: return False _socket = _socket or socket fqdn = _socket.getfqdn() if hostname == fqdn: return False local_hostname = _socket.gethostname() local_short_hostname = local_hostname.split('.')[0] if local_hostnam...
def needs_ssh(hostname, _socket=None)
Obtains remote hostname of the socket and cuts off the domain part of its FQDN.
2.262104
2.158124
1.048181
# executables in order of preference: executables = ['python3', 'python', 'python2.7'] for executable in executables: conn.logger.debug('trying to determine remote python executable with %s' % executable) out, err, code = check(conn, ['which', executable]) if code: c...
def get_python_executable(conn)
Try to determine the remote Python version so that it can be used when executing. Avoids the problem of different Python versions, or distros that do not use ``python`` but do ``python3``
4.382631
4.069884
1.076844
exc = _execnet or execnet gw = exc.makegateway( self._make_connection_string(self.hostname, use_sudo=False) ) channel = gw.remote_exec( 'import getpass; channel.send(getpass.getuser())' ) result = channel.receive() gw.exit() ...
def _detect_sudo(self, _execnet=None)
``sudo`` detection has to create a different connection to the remote host so that we can reliably ensure that ``getuser()`` will return the right information. After getting the user info it closes the connection and returns a boolean
5.772691
6.847384
0.843051
if self.remote_import_system is not None: if self.remote_import_system == 'json': self.remote_module = JsonModuleExecute(self, module, self.logger) else: self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger) else: ...
def import_module(self, module)
Allows remote execution of a local module. Depending on the ``remote_import_system`` attribute it may use execnet's implementation or remoto's own based on JSON. .. note:: It is not possible to use execnet's remote execution model on connections that aren't SSH or Local.
3.204123
2.700855
1.186337
mapping = { 'ssh': ssh.SshConnection, 'oc': openshift.OpenshiftConnection, 'openshift': openshift.OpenshiftConnection, 'kubernetes': kubernetes.KubernetesConnection, 'k8s': kubernetes.KubernetesConnection, 'local': local.LocalConnection, 'popen': local.Lo...
def get(name, fallback='ssh')
Retrieve the matching backend class from a string. If no backend can be matched, it raises an error. >>> get('ssh') <class 'remoto.backends.BaseConnection'> >>> get() <class 'remoto.backends.BaseConnection'> >>> get('non-existent') <class 'remoto.backends.BaseConnection'> >>> get('non-e...
3.140676
3.138053
1.000836
r, g, b = hsv_to_rgb(hue, saturation, value) write_led_value(self.device_unique_name, 'red', r * 255.0) write_led_value(self.device_unique_name, 'green', g * 255.0) write_led_value(self.device_unique_name, 'blue', b * 255.0)
def set_leds(self, hue: float = 0.0, saturation: float = 1.0, value: float = 1.0)
The DualShock4 has an LED bar on the front of the controller. This function allows you to set the value of this bar. Note that the controller must be connected for this to work, if it's not the call will just be ignored. :param hue: The hue of the colour, defaults to 0, specified as a float...
2.171965
2.379267
0.912871
config = {} s = os.environ.get(env, default) if s: config = parse(s) return config
def config(env=DEFAULT_ENV, default='locmem://')
Returns configured CACHES dictionary from CACHE_URL
4.647054
4.931818
0.94226
config = {} url = urlparse.urlparse(url) # Handle python 2.6 broken url parsing path, query = url.path, url.query if '?' in path and query == '': path, query = path.split('?', 1) cache_args = dict([(key.upper(), ';'.join(val)) for key, val in urlparse.parse_...
def parse(url)
Parses a cache URL.
3.00565
2.96163
1.014863
response = _get(Operation.memory_changed, url) try: return int(response.text) == 1 except ValueError: raise IOError("Likely no FlashAir connection, " "memory changed CGI command failed")
def memory_changed(url=URL)
Returns True if memory has been written to, False otherwise
15.426307
14.791296
1.042931
prepped_request = _prep_get(operation, url=url, **params) return cgi.send(prepped_request)
def _get(operation: Operation, url=URL, **params)
HTTP GET of the FlashAir command.cgi entrypoint
7.682002
5.006049
1.534544
bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0]) message_string = parser.compile_filter(bits[1]) remaining = bits[2:] noop = False asvar = None message_context = None seen = set() invalid_context = {...
def do_translate(parser, token)
This will mark a string for translation and will translate the string for the current language. Usage:: {% trans "this is a test" %} This will mark the string for translation so it will be pulled out by mark-messages.py into the .po files and will run the string through the translation engin...
2.191859
2.248936
0.97462
def asynciotask( func: None = None, *, loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] = asyncio.get_event_loop, loop_getter_need_context: bool = False, ) -> AsyncIOTask
Overload: no function.
2,489,269.75
34,462.929688
72.230358
if func is None: return AsyncIOTask(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context) return AsyncIOTask( # type: ignore func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context )(func)
def asynciotask( # noqa: F811 func: typing.Optional[typing.Callable[..., "typing.Awaitable[typing.Any]"]] = None, *, loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop ] = asyncio.get_event_loop, loop_getter_need_context: bool = False, ) ->...
Wrap function in future and return. :param func: Function to wrap :type func: typing.Optional[typing.Callable[..., typing.Awaitable]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ typing.Callable[..., asyncio.AbstractEv...
1.693291
1.922615
0.880723
if self.loop_getter_need_context: return self.loop_getter(*args, **kwargs) # pylint: disable=not-callable return self.loop_getter() # pylint: disable=not-callable return self.loop_getter
def get_loop(self, *args, **kwargs): # type: (typing.Any, typing.Any) -> asyncio.AbstractEventLoop if callable(self.loop_getter)
Get event loop in decorator class.
3.698773
2.8817
1.283538
# noinspection PyMissingOrEmptyDocstring @functools.wraps(func) # pylint: disable=missing-docstring def wrapper(*args, **kwargs): # type: (typing.Any, typing.Any) -> asyncio.Task[typing.Any] loop = self.get_loop(*args, **kwargs) return loop.create_task(func(*ar...
def _get_function_wrapper( self, func: typing.Callable[..., "typing.Awaitable[typing.Any]"] ) -> typing.Callable[..., "asyncio.Task[typing.Any]"]
Here should be constructed and returned real decorator. :param func: Wrapped function :type func: typing.Callable[..., typing.Awaitable] :return: wrapper, which will produce asyncio.Task on call with function called inside it :rtype: typing.Callable[..., asyncio.Task]
2.244366
2.181047
1.029031
def threaded( name: typing.Callable[..., typing.Any], daemon: bool = False, started: bool = False ) -> typing.Callable[..., threading.Thread]
Overload: Call decorator without arguments.
86,454.085938
10,695.193359
8.083452
if callable(name): func, name = (name, "Threaded: " + getattr(name, "__name__", str(hash(name)))) return Threaded(name=name, daemon=daemon, started=started)(func) # type: ignore return Threaded(name=name, daemon=daemon, started=started)
def threaded( # noqa: F811 name: typing.Optional[typing.Union[str, typing.Callable[..., typing.Any]]] = None, daemon: bool = False, started: bool = False, ) -> typing.Union[Threaded, typing.Callable[..., threading.Thread]]
Run function in separate thread. :param name: New thread name. If callable: use as wrapped function. If none: use wrapped function name. :type name: typing.Union[None, str, typing.Callable] :param daemon: Daemonize thread. :type daemon: bool :param started: Return ...
3.286955
3.508591
0.93683
prepared: typing.Callable[..., typing.Any] = self._await_if_required(func) name: typing.Optional[str] = self.name if name is None: name = "Threaded: " + getattr(func, "__name__", str(hash(func))) # noinspection PyMissingOrEmptyDocstring @functools.wraps(prep...
def _get_function_wrapper( self, func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]] ) -> typing.Callable[..., threading.Thread]
Here should be constructed and returned real decorator. :param func: Wrapped function :type func: typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]] :return: wrapped function :rtype: typing.Callable[..., threading.Thread]
2.715411
2.920047
0.92992
is_oscrypto = isinstance(value, asymmetric.Certificate) if not is_oscrypto and not isinstance(value, x509.Certificate): raise TypeError(_pretty_message( ''' issuer must be an instance of asn1crypto.x509.Certificate or oscrypto.asymmet...
def issuer(self, value)
An asn1crypto.x509.Certificate or oscrypto.asymmetric.Certificate object of the issuer.
2.993986
2.202689
1.359242
if value not in set(['sha1', 'sha256']): raise ValueError(_pretty_message( ''' hash_algo must be one of "sha1", "sha256", not %s ''', repr(value) )) self._key_hash_algo = value
def key_hash_algo(self, value)
A unicode string of the hash algorithm to use when creating the certificate identifier - "sha1" (default), or "sha256".
3.132668
2.861567
1.094738
if not isinstance(value, bool): raise TypeError(_pretty_message( ''' nonce must be a boolean, not %s ''', _type_name(value) )) self._nonce = value
def nonce(self, value)
A bool - if the nonce extension should be used to prevent replay attacks.
3.287585
3.036181
1.082803
if isinstance(name, str_cls): request_extension_oids = set([ 'service_locator', '1.3.6.1.5.5.7.48.1.7' ]) tbs_request_extension_oids = set([ 'nonce', 'acceptable_responses', 'preferred_s...
def set_extension(self, name, value)
Sets the value for an extension using a fully constructed asn1crypto.core.Asn1Value object. Normally this should not be needed, and the convenience attributes should be sufficient. See the definition of asn1crypto.ocsp.TBSRequestExtension and asn1crypto.ocsp.RequestExtension to determin...
2.296189
1.97218
1.164289
if not isinstance(value, str_cls): raise TypeError(_pretty_message( ''' response_status must be a unicode string, not %s ''', _type_name(value) )) valid_response_statuses = set([ 'successful', ...
def response_status(self, value)
The overall status of the response. Only a "successful" response will include information about the certificate. Other response types are for signaling info about the OCSP responder. Valid values include: - "successful" - when the response includes information about the certificate - ...
2.280063
1.950531
1.168945
if value is not None: is_oscrypto = isinstance(value, asymmetric.Certificate) if not is_oscrypto and not isinstance(value, x509.Certificate): raise TypeError(_pretty_message( ''' certificate must be an instance of asn1cryp...
def certificate(self, value)
An asn1crypto.x509.Certificate or oscrypto.asymmetric.Certificate object of the certificate the response is about.
2.900902
2.235498
1.297653
if value is not None: if not isinstance(value, str_cls): raise TypeError(_pretty_message( ''' certificate_status must be a unicode string, not %s ''', _type_name(value) )) ...
def certificate_status(self, value)
A unicode string of the status of the certificate. Valid values include: - "good" - when the certificate is in good standing - "revoked" - when the certificate is revoked without a reason code - "key_compromise" - when a private key is compromised - "ca_compromise" - when the CA iss...
1.739471
1.571951
1.106568
if value is not None and not isinstance(value, datetime): raise TypeError(_pretty_message( ''' revocation_date must be an instance of datetime.datetime, not %s ''', _type_name(value) )) self._revocation_da...
def revocation_date(self, value)
A datetime.datetime object of when the certificate was revoked, if the status is not "good" or "unknown".
2.737097
2.769821
0.988186
if value is not None: is_oscrypto = isinstance(value, asymmetric.Certificate) if not is_oscrypto and not isinstance(value, x509.Certificate): raise TypeError(_pretty_message( ''' certificate_issuer must be an instance of ...
def certificate_issuer(self, value)
An asn1crypto.x509.Certificate object of the issuer of the certificate. This should only be set if the OCSP responder is not the issuer of the certificate, but instead a special certificate only for OCSP responses.
2.675514
2.490021
1.074494
if not isinstance(value, datetime): raise TypeError(_pretty_message( ''' this_update must be an instance of datetime.datetime, not %s ''', _type_name(value) )) self._this_update = value
def this_update(self, value)
A datetime.datetime object of when the response was generated.
3.287552
2.803661
1.172593
if not isinstance(value, datetime): raise TypeError(_pretty_message( ''' next_update must be an instance of datetime.datetime, not %s ''', _type_name(value) )) self._next_update = value
def next_update(self, value)
A datetime.datetime object of when the response may next change. This should only be set if responses are cached. If responses are generated fresh on every request, this should not be set.
3.066037
2.743847
1.117423
if isinstance(name, str_cls): response_data_extension_oids = set([ 'nonce', 'extended_revoke', '1.3.6.1.5.5.7.48.1.2', '1.3.6.1.5.5.7.48.1.9' ]) single_response_extension_oids = set([ '...
def set_extension(self, name, value)
Sets the value for an extension using a fully constructed asn1crypto.core.Asn1Value object. Normally this should not be needed, and the convenience attributes should be sufficient. See the definition of asn1crypto.ocsp.SingleResponseExtension and asn1crypto.ocsp.ResponseDataExtension to...
2.222961
1.989323
1.117446
_jwt = JWT(key_jar=keys, iss=issuer, sign_alg=request_object_signing_alg) return _jwt.pack(arq.to_dict(), owner=issuer, recv=recv)
def make_openid_request(arq, keys, issuer, request_object_signing_alg, recv)
Construct the JWT to be passed by value (the request parameter) or by reference (request_uri). The request will be signed :param arq: The Authorization request :param keys: Keys to use for signing/encrypting. A KeyJar instance :param issuer: Who is signing this JSON Web Token :param request_obj...
4.436312
4.076106
1.08837
super(AuthorizationRequest, self).verify(**kwargs) clear_verified_claims(self) args = {} for arg in ["keyjar", "opponent_id", "sender", "alg", "encalg", "encenc"]: try: args[arg] = kwargs[arg] except KeyError: ...
def verify(self, **kwargs)
Authorization Request parameters that are OPTIONAL in the OAuth 2.0 specification MAY be included in the OpenID Request Object without also passing them as OAuth 2.0 Authorization Request parameters, with one exception: The scope parameter MUST always be present in OAuth 2.0 Authorizatio...
3.24966
3.238816
1.003348
super(RegistrationResponse, self).verify(**kwargs) has_reg_uri = "registration_client_uri" in self has_reg_at = "registration_access_token" in self if has_reg_uri != has_reg_at: raise VerificationError(( "Only one of registration_client_uri" ...
def verify(self, **kwargs)
Implementations MUST either return both a Client Configuration Endpoint and a Registration Access Token or neither of them. :param kwargs: :return: True if the message is OK otherwise False
4.375388
3.805544
1.14974
if not time_format: time_format = TIME_FORMAT return time_in_a_while(days, seconds, microseconds, milliseconds, minutes, hours, weeks).strftime(time_format)
def in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0, time_format=TIME_FORMAT)
:param days: :param seconds: :param microseconds: :param milliseconds: :param minutes: :param hours: :param weeks: :param time_format: :return: Formatet string
2.62975
3.178546
0.827344
if not point: return True if isinstance(point, str): point = str_to_time(point) elif isinstance(point, int): point = time.gmtime(point) return time.gmtime() < point
def before(point)
True if point datetime specification is before now
3.532499
2.996751
1.178776
if isinstance(after, str): after = str_to_time(after) elif isinstance(after, int): after = time.gmtime(after) if isinstance(before, str): before = str_to_time(before) elif isinstance(before, int): before = time.gmtime(before) return after >= before
def later_than(after, before)
True if then is later or equal to that
1.871065
1.843382
1.015017
dt = time_in_a_while(days, seconds, microseconds, milliseconds, minutes, hours, weeks) return int((dt - datetime(1970, 1, 1)).total_seconds())
def epoch_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Return the number of seconds since epoch a while from now. :param days: :param seconds: :param microseconds: :param milliseconds: :param minutes: :param hours: :param weeks: :return: Seconds since epoch (1970-01-01)
2.76073
3.036562
0.909163
for key, val in self.c_default.items(): self._dict[key] = val
def set_defaults(self)
Based on specification set a parameters value to the default value.
7.246212
5.79149
1.251183
_spec = self.c_param if not self.lax: for attribute, (_, req, _ser, _, na) in _spec.items(): if req and attribute not in self._dict: raise MissingRequiredAttribute("%s" % attribute, "%s" % self) ...
def to_urlencoded(self, lev=0)
Creates a string using the application/x-www-form-urlencoded format :return: A string of the application/x-www-form-urlencoded format
3.116485
3.160757
0.985993
return getattr(self, "to_%s" % method)(lev=lev, **kwargs)
def serialize(self, method="urlencoded", lev=0, **kwargs)
Convert this instance to another representation. Which representation is given by the choice of serialization method. :param method: A serialization method. Presently 'urlencoded', 'json', 'jwt' and 'dict' is supported. :param lev: :param kwargs: Extra key word arg...
4.497497
7.05064
0.637885
try: func = getattr(self, "from_%s" % method) except AttributeError: raise FormatError("Unknown serialization method (%s)" % method) else: return func(info, **kwargs)
def deserialize(self, info, method="urlencoded", **kwargs)
Convert from an external representation to an internal. :param info: The input :param method: The method used to deserialize the info :param kwargs: extra Keyword arguments :return: In the normal case the Message instance
3.395271
3.588821
0.946069
# parse_qs returns a dictionary with keys and values. The values are # always lists even if there is only one value in the list. # keys only appears once. if isinstance(urlencoded, str): pass elif isinstance(urlencoded, list): urlencoded = urlen...
def from_urlencoded(self, urlencoded, **kwargs)
Starting with a string of the application/x-www-form-urlencoded format this method creates a class instance :param urlencoded: The string :return: A class instance or raise an exception on error
3.220997
3.30491
0.974609
_spec = self.c_param _res = {} lev += 1 for key, val in self._dict.items(): try: (_, req, _ser, _, null_allowed) = _spec[str(key)] except KeyError: try: _key, lang = key.split("#") ...
def to_dict(self, lev=0)
Return a dictionary representation of the class :return: A dict
3.514742
3.514699
1.000012
_spec = self.c_param for key, val in dictionary.items(): # Earlier versions of python don't like unicode strings as # variable names if val == "" or val == [""]: continue skey = str(key) try: (vtyp, r...
def from_dict(self, dictionary, **kwargs)
Direct translation, so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error
3.517131
3.570552
0.985039
if isinstance(val, list): if (len(val) == 0 or val[0] is None) and null_allowed is False: return if isinstance(vtyp, tuple): vtyp = vtyp[0] if isinstance(vtyp, list): vtype = vtyp[0] if isinstance(val, vtype): ...
def _add_value(self, skey, vtyp, key, val, _deser, null_allowed)
Main method for adding a value to the instance. Does all the checking on type of value and if among allowed values. :param skey: string version of the key :param vtyp: Type of value :param key: original representation of the key :param val: The value to add :par...
2.009361
2.004174
1.002588
if lev: return self.to_dict(lev + 1) else: return json.dumps(self.to_dict(1), indent=indent)
def to_json(self, lev=0, indent=None)
Serialize the content of this instance into a JSON string. :param lev: :param indent: Number of spaces that should be used for indentation :return:
3.093522
3.469584
0.891612
_dict = json.loads(txt) return self.from_dict(_dict)
def from_json(self, txt, **kwargs)
Convert from a JSON string to an instance of this class. :param txt: The JSON string (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) :param kwargs: extra keyword arguments :return: The instantiated instance
4.312598
6.153385
0.70085
_jws = JWS(self.to_json(lev), alg=algorithm) return _jws.sign_compact(key)
def to_jwt(self, key=None, algorithm="", lev=0, lifetime=0)
Create a signed JWT representation of the class instance :param key: The signing key :param algorithm: The signature algorithm to use :param lev: :param lifetime: The lifetime of the JWS :return: A signed JWT
5.152683
5.582131
0.923067
algarg = {} if 'encalg' in kwargs: algarg['alg'] = kwargs['encalg'] if 'encenc' in kwargs: algarg['enc'] = kwargs['encenc'] _decryptor = jwe_factory(txt, **algarg) if _decryptor: logger.debug("JWE headers: {}".format(_decryptor.jwt.h...
def from_jwt(self, txt, keyjar, verify=True, **kwargs)
Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature of the JWT :param verify: Whether the signature should be verified or...
3.191631
3.228393
0.988613
_spec = self.c_param try: _allowed = self.c_allowed_values except KeyError: _allowed = {} for (attribute, (typ, required, _, _, na)) in _spec.items(): if attribute == "*": continue try: val = self....
def verify(self, **kwargs)
Make sure all the required values are there and that the values are of the correct type
4.04208
3.89828
1.036888
_l = as_unicode(location) _qp = as_unicode(self.to_urlencoded()) if fragment_enc: return "%s#%s" % (_l, _qp) else: if "?" in location: return "%s&%s" % (_l, _qp) else: return "%s?%s" % (_l, _qp)
def request(self, location, fragment_enc=False)
Given a URL this method will add a fragment, a query part or extend a query part if it already exists with the information in this instance. :param location: A URL :param fragment_enc: Whether the information should be placed in a fragment (True) or in a query part (False) ...
2.949229
2.682857
1.099287
return dict([(key, val) for key, val in self._dict.items() if key not in self.c_param])
def extra(self)
Return the extra parameters that this instance. Extra meaning those that are not listed in the c_params specification. :return: The key,value pairs for keys that are not in the c_params specification,
8.755971
8.74645
1.001089
known = [key for key in self._dict.keys() if key in self.c_param] if not known: return True else: return False
def only_extras(self)
Return True if this instance only has key,value pairs for keys that are not defined in c_params. :return: True/False
8.121752
4.979781
1.630946
if isinstance(item, dict): self._dict.update(item) elif isinstance(item, Message): for key, val in item.items(): self._dict[key] = val else: raise ValueError("Can't update message using: '%s'" % (item,))
def update(self, item, **kwargs)
Update the information in this instance. :param item: a dictionary or a Message instance
3.427073
3.056452
1.121259
_jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(keys)
def to_jwe(self, keys, enc, alg, lev=0)
Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: list or KeyJar instance :param enc: Content Encryption Algorithm :par...
4.279854
4.299331
0.99547
jwe = JWE() _res = jwe.decrypt(msg, keys) return self.from_json(_res.decode())
def from_jwe(self, msg, keys)
Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object. :param msg: An encrypted JWT :param keys: Possibly usable keys. :type keys: list or KeyJar instance :return: The decrypted message. If decryption failed an exception will...
4.947351
5.951344
0.8313
_ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
def weed(self)
Get rid of key value pairs that are not standard
6.32045
4.769373
1.325216
_blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key]
def rm_blanks(self)
Get rid of parameters that has no value.
3.244879
2.622122
1.237501
if path.startswith("./"): pass elif path.startswith("/"): path = ".%s" % path elif path.startswith("."): while path.startswith("."): path = path[1:] if path.startswith("/"): path = ".%s" % path else: path = "./%s" % path if not pa...
def proper_path(path)
Clean up the path specification so it looks like something I could use. "./" <path> "/"
2.245459
2.121079
1.05864
code = COLOR_CODES[color] return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)
def ansi(color, text)
Wrap text in an ansi escape sequence
4.872012
4.753458
1.024941
@wraps(fun) def ensure_flushed(service, *args, **kwargs): if service.app_state.needs_db_flush: session = db.session() if not session._flushing and any( isinstance(m, (RoleAssignment, SecurityAudit)) for models in (session.new, session.dirty, ...
def require_flush(fun)
Decorator for methods that need to query security. It ensures all security related operations are flushed to DB, but avoids unneeded flushes.
4.149084
3.832222
1.082684
to_visit = [session.deleted, session.dirty, session.new] with session.no_autoflush: # no_autoflush is required to visit PERMISSIONS_ATTR without emitting a # flush() if obj: to_visit.append(getattr(obj, PERMISSIONS_ATTR)) permissions = ( p for p in c...
def query_pa_no_flush(session, permission, role, obj)
Query for a :class:`PermissionAssignment` using `session` without any `flush()`. It works by looking in session `new`, `dirty` and `deleted`, and issuing a query with no autoflush. .. note:: This function is used by `add_permission` and `delete_permission` to allow to add/remove the s...
4.638169
4.506171
1.029293
if session is None: session = db.session() try: user = g.user except Exception: return session.query(User).get(0) if sa.orm.object_session(user) is not session: # this can happen when called from a celery task during development ...
def _current_user_manager(self, session=None)
Return the current user, or SYSTEM user.
6.773956
6.600857
1.026224
assert principal if hasattr(principal, "is_anonymous") and principal.is_anonymous: return [AnonymousRole] query = db.session.query(RoleAssignment.role) if isinstance(principal, Group): filter_principal = RoleAssignment.group == principal else: ...
def get_roles(self, principal, object=None, no_group_roles=False)
Get all the roles attached to given `principal`, on a given `object`. :param principal: a :class:`User` or :class:`Group` :param object: an :class:`Entity` :param no_group_roles: If `True`, return only direct roles, not roles acquired through group membership.
2.723798
2.835226
0.960699
if not isinstance(role, Role): role = Role(role) assert role assert users or groups query = RoleAssignment.query.filter_by(role=role) if not anonymous: query = query.filter(RoleAssignment.anonymous == False) if not users: quer...
def get_principals( self, role, anonymous=True, users=True, groups=True, object=None, as_list=True )
Return all users which are assigned given role.
2.605448
2.548075
1.022516
if not self.app_state.use_cache: return None if not self._has_role_cache(principal) or overwrite: self._set_role_cache(principal, self._all_roles(principal)) return self._role_cache(principal)
def _fill_role_cache(self, principal, overwrite=False)
Fill role cache for `principal` (User or Group), in order to avoid too many queries when checking role access with 'has_role'. Return role_cache of `principal`
3.860786
3.684152
1.047944
if not self.app_state.use_cache: return query = db.session.query(RoleAssignment) users = {u for u in principals if isinstance(u, User)} groups = {g for g in principals if isinstance(g, Group)} groups |= {g for u in users for g in u.groups} if not ov...
def _fill_role_cache_batch(self, principals, overwrite=False)
Fill role cache for `principals` (Users and/or Groups), in order to avoid too many queries when checking role access with 'has_role'.
2.653594
2.617803
1.013672
if not principal: return False principal = unwrap(principal) if not self.running: return True if isinstance(role, (Role, (str,))): role = (role,) # admin & manager always have role valid_roles = frozenset((Admin, Manager) + ...
def has_role(self, principal, role, object=None)
True if `principal` has `role` (either globally, if `object` is None, or on the specific `object`). :param:role: can be a list or tuple of strings or a :class:`Role` instance `object` can be an :class:`Entity`, a string, or `None`. Note: we're using a cache for efficiency ...
4.090961
4.016741
1.018478
assert principal principal = unwrap(principal) session = object_session(obj) if obj is not None else db.session manager = self._current_user_manager(session=session) args = { "role": role, "object": obj, "anonymous": False, ...
def grant_role(self, principal, role, obj=None)
Grant `role` to `user` (either globally, if `obj` is None, or on the specific `obj`).
4.408276
4.413095
0.998908
assert principal principal = unwrap(principal) session = object_session(object) if object is not None else db.session manager = self._current_user_manager(session=session) args = { "role": role, "object": object, "anonymous": False, ...
def ungrant_role(self, principal, role, object=None)
Ungrant `role` to `user` (either globally, if `object` is None, or on the specific `object`).
3.112459
3.084963
1.008913
if not isinstance(permission, Permission): assert permission in PERMISSIONS permission = Permission(permission) user = unwrap(user) if not self.running: return True session = None if obj is not None: session = object_sess...
def has_permission(self, user, permission, obj=None, inherit=False, roles=None)
:param obj: target object to check permissions. :param inherit: check with permission inheritance. By default, check only local roles. :param roles: additional valid role or iterable of roles having `permission`.
5.019049
5.070933
0.989768
assert isinstance(permission, Permission) assert issubclass(Model, Entity) RA = sa.orm.aliased(RoleAssignment) PA = sa.orm.aliased(PermissionAssignment) # id column from entity table. Model.id would refer to 'model' table. # this allows the DB to use indexes / fo...
def query_entity_with_permission(self, permission, user=None, Model=Entity)
Filter a query on an :class:`Entity` or on of its subclasses. Usage:: read_q = security.query_entity_with_permission(READ, Model=MyModel) MyModel.query.filter(read_q) It should always be placed before any `.join()` happens in the query; else sqlalchemy might join to th...
4.021169
4.067416
0.98863
session = None if obj is not None: assert isinstance(obj, Entity) session = object_session(obj) if obj.id is None: obj = None if session is None: session = db.session() pa = session.query( PermissionA...
def get_permissions_assignments(self, obj=None, permission=None)
:param permission: return only roles having this permission :returns: an dict where keys are `permissions` and values `roles` iterable.
2.958171
2.770729
1.067651
supported = list(self._assets_bundles.keys()) if type_ not in supported: msg = "Invalid type: {}. Valid types: {}".format( repr(type_), ", ".join(sorted(supported)) ) raise KeyError(msg) for asset in assets: if not isinsta...
def register_asset(self, type_, *assets)
Register webassets bundle to be served on all pages. :param type_: `"css"`, `"js-top"` or `"js""`. :param assets: a path to file, a :ref:`webassets.Bundle <webassets:bundles>` instance or a callable that returns a :ref:`webassets.Bundle <webassets:bundles>` instance...
3.633274
3.113708
1.166864
languages = self.config["BABEL_ACCEPT_LANGUAGES"] assets = self.extensions["webassets"] for path in paths: for lang in languages: filename = path.format(lang=lang) try: assets.resolver.search_for_source(assets, filename) ...
def register_i18n_js(self, *paths)
Register templates path translations files, like `select2/select2_locale_{lang}.js`. Only existing files are registered.
5.533181
5.23966
1.056019
from abilian.web import assets as bundles self.register_asset("css", bundles.LESS) self.register_asset("js-top", bundles.TOP_JS) self.register_asset("js", bundles.JS) self.register_i18n_js(*bundles.JS_I18N)
def register_base_assets(self)
Register assets needed by Abilian. This is done in a separate method in order to allow applications to redefine it at will.
5.752809
4.848316
1.186558
endpoint, kwargs = user_url_args(user, size) return url_for(endpoint, **kwargs)
def user_photo_url(user, size)
Return url to use for this user.
6.555194
6.373806
1.028458
try: fmt = get_format(image) except IOError: # not a known image file raise NotFound() self.content_type = "image/png" if fmt == "PNG" else "image/jpeg" ext = "." + str(fmt.lower()) if not filename: filename = "image" ...
def make_response(self, image, size, mode, filename=None, *args, **kwargs)
:param image: image as bytes :param size: requested maximum width/height size :param mode: one of 'scale', 'fit' or 'crop' :param filename: filename
3.840436
3.942243
0.974175
if not sessions: return [], [] users = {} dates = {} for session in sessions: user = session.user # time value is discarded to aggregate on days only date = session.started_at.strftime("%Y/%m/%d") # keep the info only it's the first time we encounter a user ...
def newlogins(sessions)
Brand new logins each day, and total of users each day. :return: data, total 2 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
3.444916
3.320231
1.037553
# sessions = LoginSession.query.order_by(LoginSession.started_at.asc()).all() if not sessions: return [], [], [] dates = {} for session in sessions: user = session.user # time value is discarded to aggregate on days only date = session.started_at.strftime("%Y/%m/%d")...
def uniquelogins(sessions)
Unique logins per days/weeks/months. :return: daily, weekly, monthly 3 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
2.873143
2.821566
1.01828
if isinstance(roles, Role): roles = (roles,) valid_roles = frozenset(roles) if Anonymous in valid_roles: return allow_anonymous def check_role(user, roles, **kwargs): from abilian.services import get_service security = get_service("security") return securi...
def allow_access_for_roles(roles)
Access control helper to check user's roles against a list of valid roles.
4.99191
5.423291
0.920458
from abilian.core.models.blob import Blob delete_value = self.allow_delete and self.delete_files_index if not self.has_file() and not delete_value: # nothing uploaded, and nothing to delete return state = sa.inspect(obj) mapper = state.mapper ...
def populate_obj(self, obj, name)
Store file.
5.795342
5.673152
1.021538
from sqlalchemy.orm.util import identity_key cls, key = identity_key(instance=obj)[0:2] return ":".join(text_type(x) for x in key)
def _get_pk_from_identity(obj)
Copied / pasted, and fixed, from WTForms_sqlalchemy due to issue w/ SQLAlchemy >= 1.2.
8.164268
7.011675
1.164382
query = Setting.query if prefix: query = query.filter(Setting.key.startswith(prefix)) # don't use iteritems: 'value' require little processing whereas we only # want 'key' return [i[0] for i in query.yield_per(1000).values(Setting.key)]
def keys(self, prefix=None)
List all keys, with optional prefix filtering.
8.706611
8.415018
1.034651
query = Setting.query if prefix: query = query.filter(Setting.key.startswith(prefix)) for s in query.yield_per(1000): yield (s.key, s.value)
def iteritems(self, prefix=None)
Like dict.iteritems.
3.170215
3.272974
0.968604
if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abilian.core.entities.Entity") Commentable.register(cls) return cls
def register(cls)
Register an :class:`Entity` as a commentable class. Can be used as a class decorator: .. code-block:: python @comment.register class MyContent(Entity): ...
7.205674
10.119339
0.71207
if isinstance(obj_or_class, type): return issubclass(obj_or_class, Commentable) if not isinstance(obj_or_class, Commentable): return False if obj_or_class.id is None: return False return True
def is_commentable(obj_or_class)
:param obj_or_class: a class or instance
2.097141
1.90771
1.099297
if check_commentable and not is_commentable(obj): return [] return getattr(obj, ATTRIBUTE)
def for_entity(obj, check_commentable=False)
Return comments on an entity.
6.086952
4.994977
1.218615
if not self._enabled: return False try: return self.pre_condition(context) and self._check_condition(context) except Exception: return False
def available(self, context)
Determine if this actions is available in this `context`. :param context: a dict whose content is left to application needs; if :attr:`.condition` is a callable it receives `context` in parameter.
5.015635
4.791218
1.046839
if app is None: app = current_app return self.__EXTENSION_NAME in app.extensions
def installed(self, app=None)
Return `True` if the registry has been installed in current applications.
11.993053
11.312538
1.060156
assert self.installed(), "Actions not enabled on this application" assert all(isinstance(a, Action) for a in actions) for action in actions: cat = action.category reg = self._state["categories"].setdefault(cat, []) reg.append(action)
def register(self, *actions)
Register `actions` in the current application. All `actions` must be an instance of :class:`.Action` or one of its subclasses. If `overwrite` is `True`, then it is allowed to overwrite an existing action with same name and category; else `ValueError` is raised.
6.715353
6.360275
1.055827
assert self.installed(), "Actions not enabled on this application" result = {} if context is None: context = self.context for cat, actions in self._state["categories"].items(): result[cat] = [a for a in actions if a.available(context)] return res...
def actions(self, context=None)
Return a mapping of category => actions list. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`).
6.254829
4.684414
1.335242
assert self.installed(), "Actions not enabled on this application" actions = self._state["categories"].get(category, []) if context is None: context = self.context return [a for a in actions if a.available(context)]
def for_category(self, category, context=None)
Returns actions list for this category in current application. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`)
7.441759
5.301618
1.403677
if not isinstance(pattern, DateTimePattern): pattern = parse_pattern(pattern) map_fmt = { # days "d": "%d", "dd": "%d", "EEE": "%a", "EEEE": "%A", "EEEEE": "%a", # narrow name => short name # months "M": "%m", "MM": "%m", ...
def babel2datetime(pattern)
Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by datetime.strptime.
2.23764
2.28455
0.979466
conditions = [LoginSession.user == user] if user_agent is not _MARK: if user_agent is None: user_agent = request.environ.get("HTTP_USER_AGENT", "") conditions.append(LoginSession.user_agent == user_agent) if ip_address is not _MARK: ...
def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK)
Return last known session for given user. :param user: user session :type user: `abilian.core.models.subjects.User` :param user_agent: *exact* user agent string to lookup, or `None` to have user_agent extracted from request object. If not provided at all, no filtering on user_a...
1.923036
1.829618
1.051059