signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def left_hash(msg, func="<STR_LIT>"):
if func == '<STR_LIT>':<EOL><INDENT>return as_unicode(b64e(sha256_digest(msg)[:<NUM_LIT:16>]))<EOL><DEDENT>elif func == '<STR_LIT>':<EOL><INDENT>return as_unicode(b64e(sha384_digest(msg)[:<NUM_LIT>]))<EOL><DEDENT>elif func == '<STR_LIT>':<EOL><INDENT>return as_unicode(b64e(sha512_digest(msg)[:<NUM_LIT:32>]))<EOL><DEDEN...
Calculate left hash as described in https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken for at_hash and in for c_hash :param msg: The message over which the hash should be calculated :param func: Which hash function that was used for the ID token
f13662:m0
def alg2keytype(alg):
if not alg or alg.lower() == "<STR_LIT:none>":<EOL><INDENT>return "<STR_LIT:none>"<EOL><DEDENT>elif alg.startswith("<STR_LIT>") or alg.startswith("<STR_LIT>"):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif alg.startswith("<STR_LIT>") or alg.startswith("<STR_LIT:A>"):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif al...
Go from algorithm name to key type. :param alg: The algorithm name :return: The key type
f13662:m1
def parse_rsa_algorithm(algorithm):
if algorithm == "<STR_LIT>":<EOL><INDENT>return hashes.SHA256(), padding.PKCS1v15()<EOL><DEDENT>elif algorithm == "<STR_LIT>":<EOL><INDENT>return hashes.SHA384(), padding.PKCS1v15()<EOL><DEDENT>elif algorithm == "<STR_LIT>":<EOL><INDENT>return hashes.SHA512(), padding.PKCS1v15()<EOL><DEDENT>elif algorithm == "<STR_LIT>...
Parses a RSA algorithm and returns tuple (hash, padding). :param algorithm: string, RSA algorithm as defined at https://tools.ietf.org/html/rfc7518#section-3.1. :raises: UnsupportedAlgorithm: if the algorithm is not supported. :returns: (hash, padding) tuple.
f13662:m2
def harmonize_usage(use):
if isinstance(use, str):<EOL><INDENT>return [MAP[use]]<EOL><DEDENT>elif isinstance(use, list):<EOL><INDENT>ul = list(MAP.keys())<EOL>return list(set([MAP[u] for u in use if u in ul]))<EOL><DEDENT>
:param use: :return: list of usage
f13664:m0
def rsa_init(spec):
try:<EOL><INDENT>size = spec['<STR_LIT:size>']<EOL><DEDENT>except KeyError:<EOL><INDENT>size = <NUM_LIT><EOL><DEDENT>kb = KeyBundle(keytype="<STR_LIT>")<EOL>if '<STR_LIT>' in spec:<EOL><INDENT>for use in harmonize_usage(spec["<STR_LIT>"]):<EOL><INDENT>_key = new_rsa_key(use=use, key_size=size)<EOL>kb.append(_key)<EOL><...
Initiates a :py:class:`oidcmsg.keybundle.KeyBundle` instance containing newly minted RSA keys according to a spec. Example of specification:: {'size':2048, 'use': ['enc', 'sig'] } Using the spec above 2 RSA keys would be minted, one for encryption and one for signing. :param spec: :return: KeyBundle
f13664:m1
def ec_init(spec):
kb = KeyBundle(keytype="<STR_LIT>")<EOL>if '<STR_LIT>' in spec:<EOL><INDENT>for use in spec["<STR_LIT>"]:<EOL><INDENT>eck = new_ec_key(crv=spec['<STR_LIT>'], use=use)<EOL>kb.append(eck)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>eck = new_ec_key(crv=spec['<STR_LIT>'])<EOL>kb.append(eck)<EOL><DEDENT>return kb<EOL>
Initiate a key bundle with an elliptic curve key. :param spec: Key specifics of the form:: {"type": "EC", "crv": "P-256", "use": ["sig"]} :return: A KeyBundle instance
f13664:m2
def keybundle_from_local_file(filename, typ, usage):
usage = harmonize_usage(usage)<EOL>if typ.lower() == "<STR_LIT>":<EOL><INDENT>kb = KeyBundle(source=filename, fileformat="<STR_LIT>", keyusage=usage)<EOL><DEDENT>elif typ.lower() == '<STR_LIT>':<EOL><INDENT>kb = KeyBundle(source=filename, fileformat="<STR_LIT>", keyusage=usage)<EOL><DEDENT>else:<EOL><INDENT>raise Unkno...
Create a KeyBundle based on the content in a local file :param filename: Name of the file :param typ: Type of content :param usage: What the key should be used for :return: The created KeyBundle
f13664:m3
def dump_jwks(kbl, target, private=False):
keys = []<EOL>for kb in kbl:<EOL><INDENT>keys.extend([k.serialize(private) for k in kb.keys() if<EOL>k.kty != '<STR_LIT>' and not k.inactive_since])<EOL><DEDENT>res = {"<STR_LIT>": keys}<EOL>try:<EOL><INDENT>f = open(target, '<STR_LIT:w>')<EOL><DEDENT>except IOError:<EOL><INDENT>(head, tail) = os.path.split(target)<EOL...
Write a JWK to a file. Will ignore symmetric keys !! :param kbl: List of KeyBundles :param target: Name of the file to which everything should be written :param private: Should also the private parts be exported
f13664:m4
def build_key_bundle(key_conf, kid_template="<STR_LIT>"):
kid = <NUM_LIT:0><EOL>tot_kb = KeyBundle()<EOL>for spec in key_conf:<EOL><INDENT>typ = spec["<STR_LIT:type>"].upper()<EOL>if typ == "<STR_LIT>":<EOL><INDENT>if "<STR_LIT:key>" in spec:<EOL><INDENT>error_to_catch = (OSError, IOError,<EOL>DeSerializationNotPossible)<EOL>try:<EOL><INDENT>kb = KeyBundle(source="<STR_LIT>" ...
Builds a :py:class:`oidcmsg.key_bundle.KeyBundle` instance based on a key specification. An example of such a specification:: keys = [ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"], "kid": "ec.1"}, {"type": "EC", "crv": "P-2...
f13664:m5
def _cmp(kd1, kd2):
if kd1 == kd2:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>elif kd1< kd2:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>elif kd1 > kd2:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>
Compare 2 keys :param kd1: First key :param kd2: Second key :return: -1,0,1 depending on whether kd1 is le,eq or gt then kd2
f13664:m6
def sort_func(kd1, kd2):
_l = _cmp(kd1['<STR_LIT:type>'], kd2['<STR_LIT:type>'])<EOL>if _l:<EOL><INDENT>return _l<EOL><DEDENT>if kd1['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>_l = _cmp(kd1['<STR_LIT>'], kd2['<STR_LIT>'])<EOL>if _l:<EOL><INDENT>return _l<EOL><DEDENT><DEDENT>_l = _cmp(kd1['<STR_LIT:type>'], kd2['<STR_LIT:type>'])<EOL>if _l:<...
Compares 2 key descriptions :param kd1: First key description :param kd2: Second key description :return: -1,0,1 depending on whether kd1 le,eq or gt then kd2
f13664:m7
def order_key_defs(key_def):
_int = []<EOL>for kd in key_def:<EOL><INDENT>if len(kd['<STR_LIT>']) > <NUM_LIT:1>:<EOL><INDENT>for _use in kd['<STR_LIT>']:<EOL><INDENT>_kd = kd.copy()<EOL>_kd['<STR_LIT>'] = _use<EOL>_int.append(_kd)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_int.append(kd)<EOL><DEDENT><DEDENT>_int.sort(key=cmp_to_key(sort_func))<EOL>ret...
Sort a set of key definitions. A key definition that defines more then one usage type are splitted into as many definitions as the number of usage types specified. One key definition per usage type. :param key_def: A set of key definitions :return: The set of definitions as a sorted list
f13664:m8
def key_diff(key_bundle, key_defs):
keys = key_bundle.get()<EOL>diff = {}<EOL>key_defs = order_key_defs(key_defs)[:]<EOL>used = []<EOL>for key in keys:<EOL><INDENT>match = False<EOL>for kd in key_defs:<EOL><INDENT>if key.use not in kd['<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>if key.kty != kd['<STR_LIT:type>']:<EOL><INDENT>continue<EOL><DEDENT>if ke...
Creates a difference dictionary with keys that should added and keys that should be deleted from a Key Bundle to get it updated to a state that mirrors What is in the key_defs specification. :param key_bundle: The original KeyBundle :param key_defs: A set of key definitions :return: A dictionary with possible keys 'ad...
f13664:m9
def update_key_bundle(key_bundle, diff):
try:<EOL><INDENT>_add = diff['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>key_bundle.extend(_add)<EOL><DEDENT>try:<EOL><INDENT>_del = diff['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>_now = time.time()<EOL>for k in _del:<EOL><INDEN...
Apply a diff specification to a KeyBundle. The keys that are to be added are added. The keys that should be deleted are marked as inactive. :param key_bundle: The original KeyBundle :param diff: The difference specification :return: An updated key_bundle
f13664:m10
def key_rollover(kb):
key_spec = []<EOL>for key in kb.get():<EOL><INDENT>_spec = {'<STR_LIT:type>': key.kty, '<STR_LIT>':[key.use]}<EOL>if key.kty == '<STR_LIT>':<EOL><INDENT>_spec['<STR_LIT>'] = key.crv<EOL><DEDENT>key_spec.append(_spec)<EOL><DEDENT>diff = {'<STR_LIT>': kb.get()}<EOL>_kb = build_key_bundle(key_spec)<EOL>diff['<STR_LIT>'] =...
A nifty function that lets you do a key rollover that encompasses creating a completely new set of keys. One new per every old one. With the same specifications as the old one. All the old ones are marked as inactive. :param kb: :return:
f13664:m11
def __init__(self, keys=None, source="<STR_LIT>", cache_time=<NUM_LIT>, verify_ssl=True,<EOL>fileformat="<STR_LIT>", keytype="<STR_LIT>", keyusage=None, kid='<STR_LIT>',<EOL>httpc=None):
self._keys = []<EOL>self.remote = False<EOL>self.cache_time = cache_time<EOL>self.time_out = <NUM_LIT:0><EOL>self.etag = "<STR_LIT>"<EOL>self.source = None<EOL>self.fileformat = fileformat.lower()<EOL>self.keytype = keytype<EOL>self.keyusage = keyusage<EOL>self.imp_jwks = None<EOL>self.last_updated = <NUM_LIT:0><EOL>if...
Contains a set of keys that have a common origin. The sources can be serveral: - A dictionary provided at the initialization, see keys below. - A list of dictionaries provided at initialization - A file containing one of: JWKS, DER encoded key - A URL pointing to a webpages from which an JWKS can be downloaded :param ...
f13664:c0:m0
def do_keys(self, keys):
for inst in keys:<EOL><INDENT>typ = inst["<STR_LIT>"]<EOL>try:<EOL><INDENT>_usage = harmonize_usage(inst['<STR_LIT>'])<EOL><DEDENT>except KeyError:<EOL><INDENT>_usage = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>del inst['<STR_LIT>']<EOL><DEDENT>flag = <NUM_LIT:0><EOL>for _use in _usage:<EOL><INDENT>for _typ in [typ, ...
Go from JWK description to binary keys :param keys: :return:
f13664:c0:m1
def do_local_jwk(self, filename):
_info = json.loads(open(filename).read())<EOL>if '<STR_LIT>' in _info:<EOL><INDENT>self.do_keys(_info["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>self.do_keys([_info])<EOL><DEDENT>self.last_updated = time.time()<EOL>
Load a JWKS from a local file :param filename:
f13664:c0:m2
def do_local_der(self, filename, keytype, keyusage=None, kid='<STR_LIT>'):
_bkey = import_private_rsa_key_from_file(filename)<EOL>if keytype.lower() != '<STR_LIT>':<EOL><INDENT>raise NotImplemented('<STR_LIT>')<EOL><DEDENT>if not keyusage:<EOL><INDENT>keyusage = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>keyusage = harmonize_usage(keyusage)<EOL><DEDENT>for use in keyusage:<EOL><...
Load a DER encoded file amd create a key from it. :param filename: :param keytype: Presently only 'rsa' supported :param keyusage: encryption ('enc') or signing ('sig') or both
f13664:c0:m3
def do_remote(self):
if self.verify_ssl:<EOL><INDENT>args = {"<STR_LIT>": self.verify_ssl}<EOL><DEDENT>else:<EOL><INDENT>args = {}<EOL><DEDENT>try:<EOL><INDENT>logging.debug('<STR_LIT>'.format(self.source))<EOL>r = self.httpc('<STR_LIT:GET>', self.source, **args)<EOL><DEDENT>except Exception as err:<EOL><INDENT>logger.error(err)<EOL>raise ...
Load a JWKS from a webpage :return: True or False if load was successful
f13664:c0:m4
def _parse_remote_response(self, response):
<EOL>try:<EOL><INDENT>if response.headers["<STR_LIT:Content-Type>"] != '<STR_LIT:application/json>':<EOL><INDENT>logger.warning('<STR_LIT>'.format(<EOL>response.headers["<STR_LIT:Content-Type>"]))<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>logger.debug("<STR_LIT>" % (response.text, self.source))<...
Parse JWKS from the HTTP response. Should be overriden by subclasses for adding support of e.g. signed JWKS. :param response: HTTP response from the 'jwks_uri' endpoint :return: response parsed as JSON
f13664:c0:m5
def update(self):
res = True <EOL>if self.source:<EOL><INDENT>_keys = self._keys <EOL>self._keys = []<EOL>try:<EOL><INDENT>if self.remote is False:<EOL><INDENT>if self.fileformat in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>self.do_local_jwk(self.source)<EOL><DEDENT>elif self.fileformat == "<STR_LIT>":<EOL><INDENT>self.do_local_der(self...
Reload the keys if necessary This is a forced update, will happen even if cache time has not elapsed. Replaced keys will be marked as inactive and not removed.
f13664:c0:m7
def get(self, typ="<STR_LIT>", only_active=True):
self._uptodate()<EOL>_typs = [typ.lower(), typ.upper()]<EOL>if typ:<EOL><INDENT>_keys = [k for k in self._keys if k.kty in _typs]<EOL><DEDENT>else:<EOL><INDENT>_keys = self._keys<EOL><DEDENT>if only_active:<EOL><INDENT>return [k for k in _keys if not k.inactive_since]<EOL><DEDENT>else:<EOL><INDENT>return _keys<EOL><DED...
Return a list of keys. Either all keys or only keys of a specific type :param typ: Type of key (rsa, ec, oct, ..) :return: If typ is undefined all the keys as a dictionary otherwise the appropriate keys in a list
f13664:c0:m8
def keys(self):
self._uptodate()<EOL>return self._keys<EOL>
Return all keys after having updated them :return: List of all keys
f13664:c0:m9
def remove_keys_by_type(self, typ):
_typs = [typ.lower(), typ.upper()]<EOL>self._keys = [k for k in self._keys if not k.kty in _typs]<EOL>
Remove keys that are of a specific type. :param typ: Type of key (rsa, ec, oct, ..)
f13664:c0:m11
def jwks(self, private=False):
self._uptodate()<EOL>keys = list()<EOL>for k in self._keys:<EOL><INDENT>if private:<EOL><INDENT>key = k.serialize(private)<EOL><DEDENT>else:<EOL><INDENT>key = k.serialize()<EOL>for k, v in key.items():<EOL><INDENT>key[k] = as_unicode(v)<EOL><DEDENT><DEDENT>keys.append(key)<EOL><DEDENT>return json.dumps({"<STR_LIT>": ke...
Create a JWKS as a JSON document :param private: Whether private key information should be included. :return: A JWKS JSON representation of the keys in this bundle
f13664:c0:m13
def append(self, key):
self._keys.append(key)<EOL>
Add a key to list of keys in this bundle :param key: Key to be added
f13664:c0:m14
def remove(self, key):
try:<EOL><INDENT>self._keys.remove(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>
Remove a specific key from this bundle :param key: The key that should be removed
f13664:c0:m16
def __len__(self):
return len(self._keys)<EOL>
The number of keys :return: The number of keys
f13664:c0:m17
def get_key_with_kid(self, kid):
for key in self._keys:<EOL><INDENT>if key.kid == kid:<EOL><INDENT>return key<EOL><DEDENT><DEDENT>self.update()<EOL>for key in self._keys:<EOL><INDENT>if key.kid == kid:<EOL><INDENT>return key<EOL><DEDENT><DEDENT>return None<EOL>
Return the key that has a specific key ID (kid) :param kid: The Key ID :return: The key or None
f13664:c0:m18
def kids(self):
self._uptodate()<EOL>return [key.kid for key in self._keys if key.kid != "<STR_LIT>"]<EOL>
Return a list of key IDs. Note that this list may be shorter then the list of keys. The reason might be that there are some keys with no key ID. :return: A list of all the key IDs that exists in this bundle
f13664:c0:m19
def mark_as_inactive(self, kid):
k = self.get_key_with_kid(kid)<EOL>k.inactive_since = time.time()<EOL>
Mark a specific key as inactive based on the keys KeyID :param kid: The Key Identifier
f13664:c0:m20
def remove_outdated(self, after, when=<NUM_LIT:0>):
if when:<EOL><INDENT>now = when<EOL><DEDENT>else:<EOL><INDENT>now = time.time()<EOL><DEDENT>if not isinstance(after, float):<EOL><INDENT>try:<EOL><INDENT>after = float(after)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>_kl = []<EOL>for k in self._keys:<EOL><INDENT>if k.inactive_since and k.inact...
Remove keys that should not be available any more. Outdated means that the key was marked as inactive at a time that was longer ago then what is given in 'after'. :param after: The length of time the key will remain in the KeyBundle before it should be removed. :param when: To make it easier to test
f13664:c0:m21
def copy(self):
kb = KeyBundle()<EOL>kb._keys = self._keys[:]<EOL>kb.cache_time = self.cache_time<EOL>kb.verify_ssl = self.verify_ssl<EOL>if self.source:<EOL><INDENT>kb.source = self.source<EOL>kb.fileformat = self.fileformat<EOL>kb.keytype = self.keytype<EOL>kb.keyusage = self.keyusage<EOL>kb.remote = self.remote<EOL><DEDENT>return k...
Make deep copy of this KeyBundle :return: The copy
f13664:c0:m23
def get_all_published_ships_basic(db_connection):
if not hasattr(get_all_published_ships_basic, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_all_published_ships_basic._results = results<EOL><DEDENT>return get_all_published_ships_basic._results<EOL>
Gets a list of all published ships and their basic information. :return: Each result has a tuple of (typeID, typeName, groupID, groupName, categoryID, and categoryName). :rtype: list
f13676:m0
def get_dogma_attribute_for_type(db_connection, type_id, dogma_attribute):
sql = '<STR_LIT>'.format(type_id, dogma_attribute)<EOL>results = execute_sql(sql, db_connection, fetch='<STR_LIT>')<EOL>if results is not None:<EOL><INDENT>results = results[<NUM_LIT:0>] <EOL><DEDENT>return results<EOL>
:param type_id: :param dogma_attribute: :return: :rtype:
f13676:m1
def get_ships_that_have_variations(db_connection):
if not hasattr(get_ships_that_have_variations, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_ships_that_have_variations._results = results<EOL><DEDENT>return get_ships_that_have_variations._results<EOL>
Gets a list of all published ship type IDs that have at least 3 variations. :return: :rtype: list
f13676:m2
def get_type_variations(db_connection, type_id):
sql = '<STR_LIT>'.format(type_id)<EOL>results = execute_sql(sql, db_connection)<EOL>return results<EOL>
:param type_id: :param dogma_attribute: :return: :rtype:
f13676:m3
def execute_sql(sql, db_connection, fetch='<STR_LIT:all>'):
cursor = db_connection.cursor()<EOL>cursor.execute(sql)<EOL>if fetch == '<STR_LIT:all>':<EOL><INDENT>results = [x for x in cursor.fetchall()]<EOL><DEDENT>elif fetch == '<STR_LIT>':<EOL><INDENT>results = cursor.fetchone()<EOL><DEDENT>else:<EOL><INDENT>results = None<EOL><DEDENT>cursor.close()<EOL>return results<EOL>
:param sql: :param db_connection: :param fetch: A string of either 'all' or 'one'. :return:
f13678:m0
def get_stored_procs(db_connection):
sql = "<STR_LIT>"<EOL>procs = execute_sql(sql, db_connection)<EOL>return [x[<NUM_LIT:1>] for x in procs]<EOL>
:param db_connection: :return:
f13678:m1
def drop_proc(proc_name, db_connection):
sql = "<STR_LIT>".format(proc_name)<EOL>execute_sql(sql, db_connection)<EOL>
:param proc_name: :param db_connection: :return:
f13678:m2
def update_sql_stored_procs(db_connection):
procs_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '<STR_LIT>')<EOL>existing_procs = get_stored_procs(db_connection)<EOL>for proc_file_name in os.listdir(procs_dir_path):<EOL><INDENT>_log.info('<STR_LIT>'.format(proc_file_name))<EOL>proc_file_path = os.path.join(procs_dir_path, proc_file_name)<E...
:param db_connection: :return:
f13678:m3
def load_tables_from_files(db_connection):
_log.info('<STR_LIT>')<EOL>sde_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '<STR_LIT>')<EOL>for sde_file_name in os.listdir(sde_dir_path):<EOL><INDENT>_log.info('<STR_LIT>'.format(sde_file_name))<EOL>sde_file_path = os.path.join(sde_dir_path, sde_file_name)<EOL>with open(sde_file_path, '<STR_LI...
Looks in the current working directory for all required tables.
f13678:m4
def get_connection(connection_details=None):
if connection_details is None:<EOL><INDENT>connection_details = get_default_connection_details()<EOL><DEDENT>return MySQLdb.connect(<EOL>connection_details['<STR_LIT:host>'],<EOL>connection_details['<STR_LIT:user>'],<EOL>connection_details['<STR_LIT:password>'],<EOL>connection_details['<STR_LIT>']<EOL>)<EOL>
Creates a connection to the MySQL DB.
f13678:m5
def get_default_connection_details():
return {<EOL>'<STR_LIT:host>': os.environ.get('<STR_LIT>', '<STR_LIT:127.0.0.1>'),<EOL>'<STR_LIT:user>': os.environ.get('<STR_LIT>', '<STR_LIT>'),<EOL>'<STR_LIT:password>': os.environ.get('<STR_LIT>', '<STR_LIT>'),<EOL>'<STR_LIT>': os.environ.get('<STR_LIT>', '<STR_LIT>'),<EOL>}<EOL>
Gets the connection details based on environment vars or Thanatos default settings. :return: Returns a dictionary of connection details. :rtype: dict
f13678:m6
def get_all_regions(db_connection):
if not hasattr(get_all_regions, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_all_regions._results = results<EOL><DEDENT>return get_all_regions._results<EOL>
Gets a list of all regions. :return: A list of all regions. Results have regionID and regionName. :rtype: list
f13679:m0
def get_all_not_wh_regions(db_connection):
if not hasattr(get_all_not_wh_regions, '<STR_LIT>'):<EOL><INDENT>sql = '<STR_LIT>'<EOL>results = execute_sql(sql, db_connection)<EOL>get_all_not_wh_regions._results = results<EOL><DEDENT>return get_all_not_wh_regions._results<EOL>
Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list
f13679:m1
def get_all_regions_connected_to_region(db_connection, region_id):
sql = '<STR_LIT>'.format(region_id)<EOL>results = execute_sql(sql, db_connection)<EOL>return results<EOL>
Gets a list of all regions connected to the region ID passed in. :param region_id: Region ID to find all regions connected to. :type region_id: int :return: A list of all regions connected to the specified region ID. Results have regionID and regionName. :rtype: list
f13679:m2
@abstractmethod<EOL><INDENT>def ask(self):<DEDENT>
pass<EOL>
ask is called whenever attempting to get a question. :return: A dictionary of answer, question, and other details. :rtype: dict
f13682:c0:m1
def format_question(self, correct_answer, possible_wrong_answers, question, add_images_to_question=False):
<EOL>wrong_answers = random.sample(possible_wrong_answers, <NUM_LIT:2>)<EOL>choices = [x for x in wrong_answers]<EOL>choices.append(correct_answer)<EOL>random.shuffle(choices)<EOL>question = {<EOL>'<STR_LIT>': correct_answer[<NUM_LIT:0>],<EOL>'<STR_LIT>': question,<EOL>'<STR_LIT>': self.convert_choices_to_dict(choices)...
Takes a set of values and converts it to the standard format expected as a return from self.ask(). :param correct_answer: A tuple of the answer key and text to be shown. :type correct_answer: tuple :param possible_wrong_answers: A list of tuples, each tuple being being (id, dis...
f13682:c0:m2
@staticmethod<EOL><INDENT>def convert_choices_to_dict(choices):<DEDENT>
formatted_choices = []<EOL>for x in choices:<EOL><INDENT>formatted_choices.append({<EOL>'<STR_LIT:value>': x[<NUM_LIT:0>],<EOL>'<STR_LIT:text>': x[<NUM_LIT:1>],<EOL>})<EOL><DEDENT>return formatted_choices<EOL>
Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type convert_choices_to_dict: list :return: ...
f13682:c0:m3
def remove_regions_with_no_gates(regions):
list_of_gateless_regions = [<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>(<NUM_LIT>, '<STR_LIT>'),<EOL>]<EOL>for gateless_region in list_of_gateless_regions:<EOL><INDENT>if gateless_region in regions:<EOL><INDENT>regions.remove(gateless_region)<EOL><DEDENT><DEDENT>return regions<EOL>
Removes all Jove regions from a list of regions. :param regions: A list of tuples (regionID, regionName) :type regions: list :return: A list of regions minus those in jove space :rtype: list
f13686:m0
def get_all_question_details():
categories = {}<EOL>subclasses = get_question_subclasses()<EOL>for subclass in subclasses:<EOL><INDENT>if subclass.category is not None and subclass.sub_category is not None:<EOL><INDENT>name = subclass.__name__.lower()<EOL>category = subclass.category['<STR_LIT:name>'].lower()<EOL>sub_category = subclass.sub_category[...
:return: A dictionary of sets representing the categories and their sub categories. :rtype: dict
f13687:m0
def get_rate_from_db(currency: str) -> Decimal:
from .models import ConversionRate<EOL>try:<EOL><INDENT>rate = ConversionRate.objects.get_rate(currency)<EOL><DEDENT>except ConversionRate.DoesNotExist: <EOL><INDENT>raise ValueError('<STR_LIT>' % (currency, ))<EOL><DEDENT>return rate.rate<EOL>
Fetch currency conversion rate from the database
f13700:m0
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal:
reverse_rate = False<EOL>if to_currency == BASE_CURRENCY:<EOL><INDENT>rate_currency = from_currency<EOL>reverse_rate = True<EOL><DEDENT>else:<EOL><INDENT>rate_currency = to_currency<EOL><DEDENT>rate = get_rate_from_db(rate_currency)<EOL>if reverse_rate:<EOL><INDENT>conversion_rate = Decimal(<NUM_LIT:1>) / rate<EOL><DED...
Get conversion rate to use in exchange
f13700:m1
def exchange_currency(<EOL>base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T:
if base.currency == to_currency:<EOL><INDENT>return base<EOL><DEDENT>if base.currency != BASE_CURRENCY and to_currency != BASE_CURRENCY:<EOL><INDENT>base = exchange_currency(base, BASE_CURRENCY)<EOL><DEDENT>if conversion_rate is None:<EOL><INDENT>conversion_rate = get_conversion_rate(base.currency, to_currency)<EOL><DE...
Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate
f13700:m2
def save(self, *args, **kwargs):
self.full_clean()<EOL>super(ConversionRate, self).save(*args, **kwargs)<EOL>
Save the model instance but only on successful validation.
f13703:c1:m0
def get_keywords():
<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full}<EOL>return keywords<EOL>
Get the keywords needed to look up the version information.
f13705:m0
def get_config():
<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT:v>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>
Create, populate and return the VersioneerConfig() object.
f13705:m1
def register_vcs_handler(vcs, method):
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
Decorator to mark a method as the handler for a particular VCS.
f13705:m2
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys...
Call the given command(s).
f13705:m3
def versions_from_parentdir(parentdir_prefix, root, verbose):
dirname = os.path.basename(root)<EOL>if not dirname.startswith(parentdir_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % (root, dirname, parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LI...
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string.
f13705:m4
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().sta...
Extract version information from the given file.
f13705:m5
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_...
Get version information from git keywords.
f13705:m6
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if not os.path.exists(os.path.join(root, "<STR_LIT>")):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>describe_out = run_comma...
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
f13705:m7
def plus_or_dot(pieces):
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
Return a + if we don't already have one, else return a .
f13705:m8
def render_pep440(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><...
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
f13705:m9
def render_pep440_pre(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
f13705:m10
def render_pep440_post(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces...
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
f13705:m11
def render_pep440_old(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<...
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
f13705:m12
def render_git_describe(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL...
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f13705:m13
def render_git_describe_long(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f13705:m14
def render(pieces, style):
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"]}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <EOL><DEDENT>if style == "<STR...
Render the given version pieces into the requested style.
f13705:m15
def get_versions():
<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>')...
Get version information or return default if unable to do so.
f13705:m16
def spinner(beep=False, disable=False, force=False):
return Spinner(beep, disable, force)<EOL>
This function creates a context manager that is used to display a spinner on stdout as long as the context has not exited. The spinner is created only if stdout is not redirected, or if the spinner is forced using the `force` parameter. Parameters ---------- beep : bool Beep when spinn...
f13706:m0
def option2tuple(opt):
if isinstance(opt[<NUM_LIT:0>], int):<EOL><INDENT>tup = opt[<NUM_LIT:1>], opt[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>tup = opt[<NUM_LIT:0>], opt[<NUM_LIT:1>:]<EOL><DEDENT>return tup<EOL>
Return a tuple of option, taking possible presence of level into account
f13708:m0
def opt_func(options, check_mandatory=True):
<EOL>def validate_arguments(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrap(*args, **kwargs):<EOL><INDENT>if args:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'.format(func, len(args)))<EOL><DEDENT>keys = set(kwargs.keys())<EOL>missing = options.mandatory_keys - keys<EOL>if missing and check_mandatory:...
Restore argument checks for functions that takes options dicts as arguments Functions that take the option dictionary produced by :meth:`Options.parse` as `kwargs` loose the argument checking usually performed by the python interpretor. They also loose the ability to take default values for their keyword arguments. Su...
f13708:m1
def __init__(self, options, args=None):
self.options = options<EOL>self._optiondict = dict([option2tuple(i) for i in options if not type(i) == str])<EOL>for opt in self._optiondict.values():<EOL><INDENT>setattr(self,opt[<NUM_LIT:0>],([] if not opt[<NUM_LIT:3>] else [opt[<NUM_LIT:3>]]) if (opt[<NUM_LIT:4>] & MULTI) else opt[<NUM_LIT:3>])<EOL><DEDENT>if args:<...
Set up options object.
f13708:c4:m0
def _default_dict(self):
options = {}<EOL>for attr, _, _, default, multi, _ in self._optiondict.values():<EOL><INDENT>if multi and default is None:<EOL><INDENT>options[attr] = []<EOL><DEDENT>else:<EOL><INDENT>options[attr] = default<EOL><DEDENT><DEDENT>return options<EOL>
Return a dictionary with the default for each option.
f13708:c4:m1
def __str__(self):
return self.help(args=self.args)<EOL>
Make a string from the option list. This method defines how the object looks like when converted to string.
f13708:c4:m4
def help(self, args=None, userlevel=<NUM_LIT:9>):
out = [main.__file__+"<STR_LIT:\n>"]<EOL>if args is not None:<EOL><INDENT>parsed = self.parse(args, ignore_help=True)<EOL><DEDENT>else:<EOL><INDENT>parsed = self._default_dict()<EOL><DEDENT>for thing in self.options:<EOL><INDENT>if type(thing) == str:<EOL><INDENT>out.append("<STR_LIT:U+0020>"+thing)<EOL><DEDENT>elif th...
Make a string from the option list
f13708:c4:m5
def parse(self, args, ignore_help=False):
options = self._default_dict()<EOL>seen = set()<EOL>args = copy.copy(args)<EOL>while args:<EOL><INDENT>opt = args.pop(<NUM_LIT:0>)<EOL>seen.add(opt)<EOL>if opt in ("<STR_LIT>","<STR_LIT>"):<EOL><INDENT>if ignore_help:<EOL><INDENT>continue<EOL><DEDENT>raise SimoptHelp<EOL><DEDENT>if not opt in self._optiondict:<EOL><IND...
Parse the (command-line) arguments.
f13708:c4:m6
def nif_nie_validation(doi, number_by_letter, special_cases):
doi = doi.upper()<EOL>if doi in special_cases:<EOL><INDENT>return False<EOL><DEDENT>table = '<STR_LIT>'<EOL>if len(doi) == <NUM_LIT:9>:<EOL><INDENT>control = doi[<NUM_LIT:8>]<EOL>numbers = number_by_letter.get(doi[<NUM_LIT:0>], doi[<NUM_LIT:0>]) + doi[<NUM_LIT:1>:<NUM_LIT:8>]<EOL>return numbers.isdigit() and control ==...
Validate if the doi is a NIF or a NIE. :param doi: DOI to validate. :return: boolean if it's valid.
f13724:m0
def is_cif(doi):
doi = doi.upper()<EOL>if len(doi) != <NUM_LIT:9>:<EOL><INDENT>return False<EOL><DEDENT>table = '<STR_LIT>'<EOL>first_chr = doi[<NUM_LIT:0>]<EOL>doi_body = doi[<NUM_LIT:1>:<NUM_LIT:8>]<EOL>control = doi[<NUM_LIT:8>]<EOL>if not doi_body.isdigit():<EOL><INDENT>return False<EOL><DEDENT>odd_result = sum(int(x) for x in '<ST...
Validate if the doi is a CIF. :param doi: DOI to validate. :return: boolean if it's valid.
f13724:m1
def is_nif(doi):
number_by_letter = {'<STR_LIT:L>': '<STR_LIT:0>', '<STR_LIT:M>': '<STR_LIT:0>', '<STR_LIT>': '<STR_LIT:0>'}<EOL>special_cases = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>return nif_nie_validation(doi, number_by_letter, special_cases)<EOL>
Validate if the doi is a NIF. :param doi: DOI to validate. :return: boolean if it's valid.
f13724:m2
def is_nie(doi):
number_by_letter = {'<STR_LIT:X>': '<STR_LIT:0>', '<STR_LIT:Y>': '<STR_LIT:1>', '<STR_LIT>': '<STR_LIT:2>'}<EOL>special_cases = ['<STR_LIT>']<EOL>if not doi or doi[<NUM_LIT:0>] not in number_by_letter.keys():<EOL><INDENT>return False<EOL><DEDENT>return nif_nie_validation(doi, number_by_letter, special_cases)<EOL>
Validate if the doi is a NIE. :param doi: DOI to validate. :return: boolean if it's valid.
f13724:m3
def __init__(self, generator):
self.generator = generator<EOL>self.max_name_len = <NUM_LIT:0><EOL>self.already_generated = []<EOL>
:param generator: a localized Generator with providers filled, for which to write the documentation :type generator: faker.Generator()
f13736:c0:m0
def execute_from_command_line(argv=None):
if sys.stdout.encoding is None:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>file=sys.stderr)<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>command = Command(argv)<EOL>command.execute()<EOL>
A simple method that runs a Command.
f13738:m2
def execute(self):
<EOL>default_locale = os.environ.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>if default_locale not in AVAILABLE_LOCALES:<EOL><INDENT>default_locale = DEFAULT_LOCALE<EOL><DEDENT>epilog =
Given the command-line arguments, this creates a parser appropriate to that command, and runs it.
f13738:c0:m1
def slugify(value, allow_dots=False, allow_unicode=False):
if allow_dots:<EOL><INDENT>pattern = _re_pattern_allow_dots<EOL><DEDENT>else:<EOL><INDENT>pattern = _re_pattern<EOL><DEDENT>value = six.text_type(value)<EOL>if allow_unicode:<EOL><INDENT>value = unicodedata.normalize('<STR_LIT>', value)<EOL>value = pattern.sub('<STR_LIT>', value).strip().lower()<EOL>return _re_spaces.s...
Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. Modified to optionally allow dots. Adapted from Django 1.9
f13740:m0
def new_date(d):
return date(d.year, d.month, d.day)<EOL>
Generate a safe date from a datetime.date object.
f13744:m0
def new_datetime(d):
kw = [d.year, d.month, d.day]<EOL>if isinstance(d, real_datetime):<EOL><INDENT>kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])<EOL><DEDENT>return datetime(*kw)<EOL>
Generate a safe datetime from a datetime.date or datetime.datetime object.
f13744:m1
def add_dicts(*args):
counters = [Counter(arg) for arg in args]<EOL>return dict(reduce(operator.add, counters))<EOL>
Adds two or more dicts together. Common keys will have their values added. For example:: >>> t1 = {'a':1, 'b':2} >>> t2 = {'b':1, 'c':3} >>> t3 = {'d':4} >>> add_dicts(t1, t2, t3) {'a': 1, 'c': 3, 'b': 3, 'd': 4}
f13746:m0
def get_providers(self):
return self.providers<EOL>
Returns added providers.
f13748:c0:m3
def seed_instance(self, seed=None):
if self.__random == random:<EOL><INDENT>self.__random = random_module.Random()<EOL><DEDENT>self.__random.seed(seed)<EOL>return self<EOL>
Calls random.seed
f13748:c0:m6
def format(self, formatter, *args, **kwargs):
<EOL>return self.get_formatter(formatter)(*args, **kwargs)<EOL>
This is a secure way to make a fake from another Provider.
f13748:c0:m8
def set_formatter(self, name, method):
setattr(self, name, method)<EOL>
This method adds a provider method to generator. Override this method to add some decoration or logging stuff.
f13748:c0:m10
def parse(self, text):
return _re_token.sub(self.__format_token, text)<EOL>
Replaces tokens (like '{{ tokenName }}' or '{{tokenName}}') with the result from the token method call.
f13748:c0:m11
def remove_accents(value):
search = '<STR_LIT>'<EOL>replace = '<STR_LIT>'<EOL>def replace_accented_character(match):<EOL><INDENT>matched = match.group(<NUM_LIT:0>)<EOL>if matched in search:<EOL><INDENT>return replace[search.find(matched)]<EOL><DEDENT>return matched<EOL><DEDENT>return re.sub(r'<STR_LIT>'.format(search), replace_accented_character...
Remove accents from characters in the given string.
f13758:m0
def latinize(value):
def replace_double_character(match):<EOL><INDENT>search = ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>').split()<EOL>replace = ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>').split()<EOL>matched = match.group(<NUM_LIT:0>)<EOL>if matched in search:<EOL><INDENT...
Converts (transliterates) greek letters to latin equivalents.
f13758:m1