INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a dictionary of all the files under a path.
def _get_local_files(self, path): """Returns a dictionary of all the files under a path.""" if not path: raise ValueError("No path specified") files = defaultdict(lambda: None) path_len = len(path) + 1 for root, dirs, filenames in os.walk(path): for name i...
Syncs a local directory with an S3 bucket. Currently does not delete files from S3 that are not in the local directory.
def sync_folder(self, path, bucket): """Syncs a local directory with an S3 bucket. Currently does not delete files from S3 that are not in the local directory. path: The path to the directory to sync to S3 bucket: The name of the bucket on S3 """ bucket = self.conn...
Syncs a list of folders to their assicated buckets. folders: A list of 2 - tuples in the form ( folder bucket )
def sync(self, folders): """Syncs a list of folders to their assicated buckets. folders: A list of 2-tuples in the form (folder, bucket) """ if not folders: raise ValueError("No folders to sync given") for folder in folders: self.sync_folder(*fold...
Decorator for views that checks that the user is logged in redirecting to the log - in page if necessary.
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = request_passes_test( lambda r: r.session.get('use...
Decorator for views that checks that the user is logged in redirecting to the log - in page if necessary.
def permission_required(function=None, permission=None, object_id=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_de...
Ensure the user has the necessary tokens for the specified services
def tokens_required(service_list): """ Ensure the user has the necessary tokens for the specified services """ def decorator(func): @wraps(func) def inner(request, *args, **kwargs): for service in service_list: if service not in request.session["user_tokens"]:...
Displays the login form and handles the login action.
def login(request, template_name='ci/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(redirect_field_name, req...
Build CLI dynamically based on the package structure.
def build(cli, path, package): """Build CLI dynamically based on the package structure. """ for _, name, ispkg in iter_modules(path): module = import_module(f'.{name}', package) if ispkg: build(cli.group(name)(module.group), module.__path__, mo...
Return an already closed read - only instance of Fridge. Arguments are the same as for the constructor.
def readonly(cls, *args, **kwargs): """ Return an already closed read-only instance of Fridge. Arguments are the same as for the constructor. """ fridge = cls(*args, **kwargs) fridge.close() return fridge
Force reloading the data from the file. All data in the in - memory dictionary is discarded. This method is called automatically by the constructor normally you don t need to call it.
def load(self): """ Force reloading the data from the file. All data in the in-memory dictionary is discarded. This method is called automatically by the constructor, normally you don't need to call it. """ self._check_open() try: data = json.l...
Force saving the dictionary to the file. All data in the file is discarded. This method is called automatically by: meth: close.
def save(self): """ Force saving the dictionary to the file. All data in the file is discarded. This method is called automatically by :meth:`close`. """ self._check_open() self.file.truncate(0) self.file.seek(0) json.dump(self, self.file, **self.d...
Close the fridge. Calls: meth: save and closes the underlying file object unless an already open file was passed to the constructor. This method has no effect if the object is already closed.
def close(self): """ Close the fridge. Calls :meth:`save` and closes the underlying file object unless an already open file was passed to the constructor. This method has no effect if the object is already closed. After the fridge is closed :meth:`save` and :meth:`load` ...
Create a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS.
def self_sign_jwks(keyjar, iss, kid='', lifetime=3600): """ Create a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. :param keyjar: A KeyJar instance with at least one private signing key :param iss: issuer of the JWT, should be the owner of the keys :param kid: ...
Verify the signature of a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. In the JWT the JWKS is stored using this format:: jwks: { keys: [ ] }
def verify_self_signed_jwks(sjwt): """ Verify the signature of a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. In the JWT the JWKS is stored using this format :: 'jwks': { 'keys': [ ] } :param sjwt: Signed Jason Web Token :retu...
A metadata statement signing request with signing_keys signed by one of the keys in signing_keys.
def request_signed_by_signing_keys(keyjar, msreq, iss, lifetime, kid=''): """ A metadata statement signing request with 'signing_keys' signed by one of the keys in 'signing_keys'. :param keyjar: A KeyJar instance with the private signing key :param msreq: Metadata statement signing request. A Metad...
Verify that a JWT is signed with a key that is inside the JWT.: param smsreq: Signed Metadata Statement signing request: return: Dictionary containing ms ( the signed request ) and iss ( the issuer of the JWT ).
def verify_request_signed_by_signing_keys(smsreq): """ Verify that a JWT is signed with a key that is inside the JWT. :param smsreq: Signed Metadata Statement signing request :return: Dictionary containing 'ms' (the signed request) and 'iss' (the issuer of the JWT). """ _jws = fact...
A decorator for providing a unittesting function/ method with every card in a librarian card library database when it is called.
def card(func): """ A decorator for providing a unittesting function/method with every card in a librarian card library database when it is called. """ @wraps(func) def wrapped(*args, **kwargs): """Transparent wrapper.""" return func(*args, **kwargs) TESTS.append(wrapped) ...
A decorator for providing a unittest with a library and have it called only once.
def library(func): """ A decorator for providing a unittest with a library and have it called only once. """ @wraps(func) def wrapped(*args, **kwargs): """Transparent wrapper.""" return func(*args, **kwargs) SINGLES.append(wrapped) return wrapped
Descover and load greencard tests.
def descovery(testdir): """Descover and load greencard tests.""" from os.path import join, exists, isdir, splitext, basename, sep if not testdir or not exists(testdir) or not isdir(testdir): return None from os import walk import fnmatch import imp for root, _, filenames in walk(te...
Command line entry point.
def main(clargs=None): """Command line entry point.""" from argparse import ArgumentParser from librarian.library import Library import sys parser = ArgumentParser( description="A test runner for each card in a librarian library.") parser.add_argument("library", help="Library database")...
Returns the Scrabble score of a letter.
def letter_score(letter): """Returns the Scrabble score of a letter. Args: letter: a single character string Raises: TypeError if a non-Scrabble character is supplied """ score_map = { 1: ["a", "e", "i", "o", "u", "l", "n", "r", "s", "t"], 2: ["d", "g"], 3:...
Checks the Scrabble score of a single word.
def word_score(word, input_letters, questions=0): """Checks the Scrabble score of a single word. Args: word: a string to check the Scrabble score of input_letters: the letters in our rack questions: integer of the tiles already on the board to build on Returns: an integer S...
Searches a string for blank tile characters ( ? and _ ).
def blank_tiles(input_word): """Searches a string for blank tile characters ("?" and "_"). Args: input_word: the user supplied string to search through Returns: a tuple of: input_word without blanks integer number of blanks (no points) integer number of ...
Opens the word list file.
def word_list(sowpods=False, start="", end=""): """Opens the word list file. Args: sowpods: a boolean to declare using the sowpods list or TWL (default) start: a string of starting characters to find anagrams based on end: a string of ending characters to find anagrams based on Yei...
Checks if the input word could be played with a full bag of tiles.
def valid_scrabble_word(word): """Checks if the input word could be played with a full bag of tiles. Returns: True or false """ letters_in_bag = { "a": 9, "b": 2, "c": 2, "d": 4, "e": 12, "f": 2, "g": 3, "h": 2, "i": 9, ...
docstring for main
def main(args): """docstring for main""" try: args.query = ' '.join(args.query).replace('?', '') so = SOSearch(args.query, args.tags) result = so.first_q().best_answer.code if result != None: print result else: print("Sorry I can't find your answe...
docstring for argparse
def cli_run(): """docstring for argparse""" parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow') parser.add_argument('query', help="What's the problem ?", type=str, nargs='+') parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda') ...
Handle a JSON AMP dialect request.
def stringReceived(self, string): """Handle a JSON AMP dialect request. First, the JSON is parsed. Then, all JSON dialect specific values in the request are turned into the correct objects. Then, finds the correct responder function, calls it, and serializes the result (or error...
Gets the command class and matching responder function for the given command name.
def _getCommandAndResponder(self, commandName): """Gets the command class and matching responder function for the given command name. """ # DISGUSTING IMPLEMENTATION DETAIL EXPLOITING HACK locator = self._remote.boxReceiver.locator responder = locator.locateResponder(com...
Parses all the values in the request that are in a form specific to the JSON AMP dialect.
def _parseRequestValues(self, request, command): """Parses all the values in the request that are in a form specific to the JSON AMP dialect. """ for key, ampType in command.arguments: ampClass = ampType.__class__ if ampClass is exposed.ExposedResponderLocator: ...
Run the responser function. If it succeeds add the _answer key. If it fails with an error known to the command serialize the error.
def _runResponder(self, responder, request, command, identifier): """Run the responser function. If it succeeds, add the _answer key. If it fails with an error known to the command, serialize the error. """ d = defer.maybeDeferred(responder, **request) def _addIdentifie...
Serializes the response to JSON and writes it to the transport.
def _writeResponse(self, response): """ Serializes the response to JSON, and writes it to the transport. """ encoded = dumps(response, default=_default) self.transport.write(encoded)
Tells the box receiver to stop receiving boxes.
def connectionLost(self, reason): """ Tells the box receiver to stop receiving boxes. """ self._remote.boxReceiver.stopReceivingBoxes(reason) return basic.NetstringReceiver.connectionLost(self, reason)
Builds a bridge and associates it with an AMP protocol instance.
def buildProtocol(self, addr): """ Builds a bridge and associates it with an AMP protocol instance. """ proto = self._factory.buildProtocol(addr) return JSONAMPDialectReceiver(proto)
Read a signed JWKS bundle from disc verify the signature and instantiate a JWKSBundle instance with the information from the file.: param iss:: param ver_keys:: param bundle_file:: return:
def get_bundle(iss, ver_keys, bundle_file): """ Read a signed JWKS bundle from disc, verify the signature and instantiate a JWKSBundle instance with the information from the file. :param iss: :param ver_keys: :param bundle_file: :return: """ fp = open(bundle_file, 'r') signe...
If the * key_file * file exists then read the keys from there otherwise create the keys and store them a file with the name * key_file *.
def get_signing_keys(eid, keydef, key_file): """ If the *key_file* file exists then read the keys from there, otherwise create the keys and store them a file with the name *key_file*. :param eid: The ID of the entity that the keys belongs to :param keydef: What keys to create :param key_file: A...
Convert a JWKS to a KeyJar instance.
def jwks_to_keyjar(jwks, iss=''): """ Convert a JWKS to a KeyJar instance. :param jwks: String representation of a JWKS :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance """ if not isinstance(jwks, dict): try: jwks = json.loads(jwks) except json.JSONDecodeError:...
Create a signed JWT containing a dictionary with Issuer IDs as keys and JWKSs as values. If iss_list is empty then all available issuers are included.: param sign_alg: Which algorithm to use when signing the JWT: param iss_list: A list of issuer IDs who s keys should be included in the signed bundle.: return: A signed ...
def create_signed_bundle(self, sign_alg='RS256', iss_list=None): """ Create a signed JWT containing a dictionary with Issuer IDs as keys and JWKSs as values. If iss_list is empty then all available issuers are included. :param sign_alg: Which algorithm to use when signin...
Upload a bundle from an unsigned JSON document
def loads(self, jstr): """ Upload a bundle from an unsigned JSON document :param jstr: A bundle as a dictionary or a JSON document """ if isinstance(jstr, dict): _info = jstr else: _info = json.loads(jstr) for iss, jwks in _info.items(): ...
Return the bundle of keys as a dictionary with the issuer IDs as the keys and the key sets represented as JWKS instances.: param iss_list: List of Issuer IDs that should be part of the output: rtype: Dictionary
def dict(self, iss_list=None): """ Return the bundle of keys as a dictionary with the issuer IDs as the keys and the key sets represented as JWKS instances. :param iss_list: List of Issuer IDs that should be part of the output :rtype: Dictionary """ ...
Input is a signed JWT with a JSON document representing the key bundle as body. This method verifies the signature and the updates the instance bundle with whatever was in the received package. Note that as with dictionary update if an Issuer ID already exists in the instance bundle that will be overwritten with the ne...
def upload_signed_bundle(self, sign_bundle, ver_keys): """ Input is a signed JWT with a JSON document representing the key bundle as body. This method verifies the signature and the updates the instance bundle with whatever was in the received package. Note, that as with dictio...
Convert a key bundle into a KeyJar instance.: return: An: py: class: oidcmsg. key_jar. KeyJar instance
def as_keyjar(self): """ Convert a key bundle into a KeyJar instance. :return: An :py:class:`oidcmsg.key_jar.KeyJar` instance """ kj = KeyJar() for iss, k in self.bundle.items(): try: kj.issuer_keys[iss] = k.issuer_keys[iss] ...
return a function which runs the given cmd make_shortcut ( ls ) returns a function which executes envoy. run ( ls + arguments )
def make_shortcut(cmd): """return a function which runs the given cmd make_shortcut('ls') returns a function which executes envoy.run('ls ' + arguments)""" def _(cmd_arguments, *args, **kwargs): return run("%s %s" % (cmd, cmd_arguments), *args, **kwargs) return _
This function deal with the nova notification.
def nova_process(body, message): """ This function deal with the nova notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use ternya d...
This function deal with the cinder notification.
def cinder_process(body, message): """ This function deal with the cinder notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use tern...
This function deal with the neutron notification.
def neutron_process(body, message): """ This function deal with the neutron notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use te...
This function deal with the glance notification.
def glance_process(body, message): """ This function deal with the glance notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use tern...
This function deal with the swift notification.
def swift_process(body, message): """ This function deal with the swift notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use ternya...
This function deal with the keystone notification.
def keystone_process(body, message): """ This function deal with the keystone notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use ...
This function deal with the heat notification.
def heat_process(body, message): """ This function deal with the heat notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use ternya d...
Serve app using wsgiref or provided server.
def serve(self, server=None): """Serve app using wsgiref or provided server. Args: - server (callable): An callable """ if server is None: from wsgiref.simple_server import make_server server = lambda app: make_server('', 8000, app).serve_forever() ...
Print msg to stdout and option log at info level.
def pout(msg, log=None): """Print 'msg' to stdout, and option 'log' at info level.""" _print(msg, sys.stdout, log_func=log.info if log else None)
Print msg to stderr and option log at info level.
def perr(msg, log=None): """Print 'msg' to stderr, and option 'log' at info level.""" _print(msg, sys.stderr, log_func=log.error if log else None)
A class decorator for Command classes to register in the default set.
def register(CommandSubClass): """A class decorator for Command classes to register in the default set.""" name = CommandSubClass.name() if name in Command._all_commands: raise ValueError("Command already exists: " + name) Command._all_commands[name] = CommandSubClass return CommandSubClass
A class decorator for Command classes to register.
def register(Class, CommandSubClass): """A class decorator for Command classes to register.""" for name in [CommandSubClass.name()] + CommandSubClass.aliases(): if name in Class._registered_commands[Class]: raise ValueError("Command already exists: " + name) Class...
Instantiate each registered command to a dict mapping name/ alias to instance.
def loadCommandMap(Class, subparsers=None, instantiate=True, **cmd_kwargs): """Instantiate each registered command to a dict mapping name/alias to instance. Due to aliases, the returned length may be greater there the number of commands, but the unique instance count will match. ...
If all of the constraints are satisfied with the given value defers to the composed AMP argument s toString method.
def toString(self, value): """ If all of the constraints are satisfied with the given value, defers to the composed AMP argument's ``toString`` method. """ self._checkConstraints(value) return self.baseArgument.toString(value)
Converts the string to a value using the composed AMP argument then checks all the constraints against that value.
def fromString(self, string): """ Converts the string to a value using the composed AMP argument, then checks all the constraints against that value. """ value = self.baseArgument.fromString(string) self._checkConstraints(value) return value
Merges cdict into completers. In the event that a key in cdict already exists in the completers dict a ValueError is raised iff regex false y. If a regex str is provided it and the duplicate key are updated to be unique and the updated regex is returned.
def _updateCompleterDict(completers, cdict, regex=None): """Merges ``cdict`` into ``completers``. In the event that a key in cdict already exists in the completers dict a ValueError is raised iff ``regex`` false'y. If a regex str is provided it and the duplicate key are updated to be uni...
log. debug ( ------------------------------------------------------ ) log. debug ( f ** WORD { self. WORD } ) log. debug ( f ** words { self. words } ) log. debug ( f ** word_before_cursor { word_before_cursor } )
def get_completions(self, document, complete_event): # Get word/text before cursor. if self.sentence: word_before_cursor = document.text_before_cursor else: word_before_cursor = document.get_word_before_cursor(WORD=self.WORD) if self.ignore_case: word...
Start ternya work.
def work(self): """ Start ternya work. First, import customer's service modules. Second, init openstack mq. Third, keep a ternya connection that can auto-reconnect. """ self.init_modules() connection = self.init_mq() TernyaConnection(self, connect...
Init connection and consumer with openstack mq.
def init_mq(self): """Init connection and consumer with openstack mq.""" mq = self.init_connection() self.init_consumer(mq) return mq.connection
Import customer s service modules.
def init_modules(self): """Import customer's service modules.""" if not self.config: raise ValueError("please read your config file.") log.debug("begin to import customer's service modules.") modules = ServiceModules(self.config) modules.import_modules() log....
Init openstack nova mq
def init_nova_consumer(self, mq): """ Init openstack nova mq 1. Check if enable listening nova notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Nova): log.debug("disable listening n...
Init openstack cinder mq
def init_cinder_consumer(self, mq): """ Init openstack cinder mq 1. Check if enable listening cinder notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Cinder): log.debug("disable lis...
Init openstack neutron mq
def init_neutron_consumer(self, mq): """ Init openstack neutron mq 1. Check if enable listening neutron notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Neutron): log.debug("disable...
Init openstack glance mq
def init_glance_consumer(self, mq): """ Init openstack glance mq 1. Check if enable listening glance notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Glance): log.debug("disable lis...
Init openstack swift mq
def init_swift_consumer(self, mq): """ Init openstack swift mq 1. Check if enable listening swift notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Swift): log.debug("disable listeni...
Init openstack swift mq
def init_keystone_consumer(self, mq): """ Init openstack swift mq 1. Check if enable listening keystone notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Keystone): log.debug("disabl...
Init openstack heat mq
def init_heat_consumer(self, mq): """ Init openstack heat mq 1. Check if enable listening heat notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Heat): log.debug("disable listening h...
Check if customer enable openstack component notification.
def enable_component_notification(self, openstack_component): """ Check if customer enable openstack component notification. :param openstack_component: Openstack component type. """ openstack_component_mapping = { Openstack.Nova: self.config.listen_nova_notification...
Get music info from baidu music api
def music_info(songid): """ Get music info from baidu music api """ if isinstance(songid, list): songid = ','.join(songid) data = { "hq": 1, "songIds": songid } res = requests.post(MUSIC_INFO_URL, data=data) info = res.json() music_data = info["data"] son...
process for downing music with multiple threads
def download_music(song, thread_num=4): """ process for downing music with multiple threads """ filename = "{}.mp3".format(song["name"]) if os.path.exists(filename): os.remove(filename) part = int(song["size"] / thread_num) if part <= 1024: thread_num = 1 _id = uuid.uu...
Execute a code object The inputs and behavior of this function should match those of eval_ and exec_.
def execute(self, globals_=None, _locals=None): """ Execute a code object The inputs and behavior of this function should match those of eval_ and exec_. .. _eval: https://docs.python.org/3/library/functions.html?highlight=eval#eval .. _exec: https://docs.python...
Implementation of the LOAD_NAME operation
def load_name(self, name): """ Implementation of the LOAD_NAME operation """ if name in self.globals_: return self.globals_[name] b = self.globals_['__builtins__'] if isinstance(b, dict): return b[name] else: return get...
Pop the ** n ** topmost items from the stack and return them as a list.
def pop(self, n): """ Pop the **n** topmost items from the stack and return them as a ``list``. """ poped = self.__stack[len(self.__stack) - n:] del self.__stack[len(self.__stack) - n:] return poped
Implement builtins. __build_class__. We must wrap all class member functions using: py: func: function_wrapper. This requires using a: py: class: Machine to execute the class source code and then recreating the class source code using an: py: class: Assembler.
def build_class(self, callable_, args): """ Implement ``builtins.__build_class__``. We must wrap all class member functions using :py:func:`function_wrapper`. This requires using a :py:class:`Machine` to execute the class source code and then recreating the class source code usin...
Implement the CALL_FUNCTION_ operation.
def call_function(self, c, i): """ Implement the CALL_FUNCTION_ operation. .. _CALL_FUNCTION: https://docs.python.org/3/library/dis.html#opcode-CALL_FUNCTION """ callable_ = self.__stack[-1-i.arg] args = tuple(self.__stack[len(self.__stack) - i.arg:]) ...
Perfoms a mysqldump backup. Create a database dump for the given database. returns statuscode and shelloutput
def dump(filename, dbname, username=None, password=None, host=None, port=None, tempdir='/tmp', mysqldump_path='mysqldump'): """Perfoms a mysqldump backup. Create a database dump for the given database. returns statuscode and shelloutput """ filepath = os.path.join(tempdir, filename) cmd = ...
returns a connected cursor to the database - server.
def _connection(username=None, password=None, host=None, port=None): "returns a connected cursor to the database-server." c_opts = {} if username: c_opts['user'] = username if password: c_opts['passwd'] = password if host: c_opts['host'] = host if port: c_opts['port'] = port dbc = MySQLdb...
Render ditaa code into a PNG output file.
def render_ditaa(self, code, options, prefix='ditaa'): """Render ditaa code into a PNG output file.""" hashkey = code.encode('utf-8') + str(options) + \ str(self.builder.config.ditaa) + \ str(self.builder.config.ditaa_args) infname = '%s-%s.%s' % (prefix, sha(hashkey).hexdigest()...
Invoked in the finally block of Application. run.
def _atexit(self): """Invoked in the 'finally' block of Application.run.""" self.log.debug("Application._atexit") if self._atexit_func: self._atexit_func(self)
Run Application. main and exits with the return value.
def run(self, args_list=None): """Run Application.main and exits with the return value.""" self.log.debug("Application.run: {args_list}".format(**locals())) retval = None try: retval = self._run(args_list=args_list) except KeyboardInterrupt: self.log.verbo...
Context manager that changes to directory path and return to CWD when exited.
def cd(path): """Context manager that changes to directory `path` and return to CWD when exited. """ old_path = os.getcwd() os.chdir(path) try: yield finally: os.chdir(old_path)
Modified from shutil. copytree docs code sample merges files rather than requiring dst to not exist.
def copytree(src, dst, symlinks=True): """ Modified from shutil.copytree docs code sample, merges files rather than requiring dst to not exist. """ from shutil import copy2, Error, copystat names = os.listdir(src) if not Path(dst).exists(): os.makedirs(dst) errors = [] for...
If called in the context of an exception calls post_mortem ; otherwise set_trace. ipdb is preferred over pdb if installed.
def debugger(): """If called in the context of an exception, calls post_mortem; otherwise set_trace. ``ipdb`` is preferred over ``pdb`` if installed. """ e, m, tb = sys.exc_info() if tb is not None: _debugger.post_mortem(tb) else: _debugger.set_trace()
Implements the dict. keys () method
def keys(self): """ Implements the dict.keys() method """ self.sync() for k in self.db.keys(): try: yield self.key_conv['from'](k) except KeyError: yield k
Find the time this file was last modified.
def get_mtime(fname): """ Find the time this file was last modified. :param fname: File name :return: The last time the file was modified. """ try: mtime = os.stat(fname).st_mtime_ns except OSError: # The file might be right in the middle ...
Find out if this item has been modified since last
def is_changed(self, item): """ Find out if this item has been modified since last :param item: A key :return: True/False """ fname = os.path.join(self.fdir, item) if os.path.isfile(fname): mtime = self.get_mtime(fname) try: ...
Goes through the directory and builds a local cache based on the content of the directory.
def sync(self): """ Goes through the directory and builds a local cache based on the content of the directory. """ if not os.path.isdir(self.fdir): os.makedirs(self.fdir) for f in os.listdir(self.fdir): fname = os.path.join(self.fdir, f) ...
Implements the dict. items () method
def items(self): """ Implements the dict.items() method """ self.sync() for k, v in self.db.items(): try: yield self.key_conv['from'](k), v except KeyError: yield k, v
Completely resets the database. This means that all information in the local cache and on disc will be erased.
def clear(self): """ Completely resets the database. This means that all information in the local cache and on disc will be erased. """ if not os.path.isdir(self.fdir): os.makedirs(self.fdir, exist_ok=True) return for f in os.listdir(self.fdir): ...
Implements the dict. update () method
def update(self, ava): """ Implements the dict.update() method """ for key, val in ava.items(): self[key] = val
x -- > int/ byte Returns -- > BYTE ( not str in python3 ) Behaves like PY2 chr () in PY2 or PY3 if x is str of length > 1 or int > 256 raises ValueError/ TypeError is not SUPPRESS_ERRORS
def chr(x): ''' x-->int / byte Returns-->BYTE (not str in python3) Behaves like PY2 chr() in PY2 or PY3 if x is str of length > 1 or int > 256 raises ValueError/TypeError is not SUPPRESS_ERRORS ''' global _chr if isinstance(x, int): if x > 256: if SUPPRESS...
x -- > char ( str of length 1 ) Returns -- > int Behaves like PY2 ord () in PY2 or PY3 if x is str of length > 1 or int > 256 raises ValueError/ TypeError is not SUPPRESS_ERRORS
def ord(x): ''' x-->char (str of length 1) Returns-->int Behaves like PY2 ord() in PY2 or PY3 if x is str of length > 1 or int > 256 raises ValueError/TypeError is not SUPPRESS_ERRORS ''' global _ord if isinstance(x, int): if x > 256: if not SUPPRESS_ERROR...
x -- > bytes | bytearray Returns -- > bytes: hex - encoded
def hex(x): ''' x-->bytes | bytearray Returns-->bytes: hex-encoded ''' if isinstance(x, bytearray): x = bytes(x) return encode(x, 'hex')
x -- > unicode string | bytearray | bytes Returns -- > unicode string with encoding = latin1
def fromBytes(x): ''' x-->unicode string | bytearray | bytes Returns-->unicode string, with encoding=latin1 ''' if isinstance(x, unicode): return x if isinstance(x, bytearray): x = bytes(x) elif isinstance(x, bytes): pass else: return x # unchanged (int e...
x -- > unicode string | bytearray | bytes Returns -- > bytes If x is unicode MUST have encoding = latin1
def toBytes(x): ''' x-->unicode string | bytearray | bytes Returns-->bytes If x is unicode, MUST have encoding=latin1 ''' if isinstance(x, bytes): return x elif isinstance(x, bytearray): return bytes(x) elif isinstance(x, unicode): pass else: return x ...
encoding -- > str: one of ENCODINGS avoid -- > list of int: to void ( unprintable chars etc ) Returns -- > int that can be converted to requested encoding which is NOT in avoid
def get_rand_int(encoding='latin1', avoid=[]): ''' encoding-->str: one of ENCODINGS avoid-->list of int: to void (unprintable chars etc) Returns-->int that can be converted to requested encoding which is NOT in avoid ''' UNICODE_LIMIT = 0x10ffff # See: https://en.wikipedia.org/...
encoding -- > str: one of ENCODINGS l -- > int: length of returned str avoid -- > list of int: to void ( unprintable chars etc ) Returns -- > unicode str of the requested encoding
def get_rand_str(encoding='latin1', l=64, avoid=[]): ''' encoding-->str: one of ENCODINGS l-->int: length of returned str avoid-->list of int: to void (unprintable chars etc) Returns-->unicode str of the requested encoding ''' ret = unicode('') while len(ret) < l: rndint = get_ra...