Search is not available for this dataset
text
stringlengths
75
104k
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 ...
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...
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, ...
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...
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') ...
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...
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...
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: ...
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...
def _writeResponse(self, response): """ Serializes the response to JSON, and writes it to the transport. """ encoded = dumps(response, default=_default) self.transport.write(encoded)
def connectionLost(self, reason): """ Tells the box receiver to stop receiving boxes. """ self._remote.boxReceiver.stopReceivingBoxes(reason) return basic.NetstringReceiver.connectionLost(self, reason)
def buildProtocol(self, addr): """ Builds a bridge and associates it with an AMP protocol instance. """ proto = self._factory.buildProtocol(addr) return JSONAMPDialectReceiver(proto)
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...
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...
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:...
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...
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(): ...
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 """ ...
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...
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] ...
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 _
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...
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...
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...
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...
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...
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 ...
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...
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() ...
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)
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)
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
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...
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. ...
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)
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
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...
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...
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...
def init_mq(self): """Init connection and consumer with openstack mq.""" mq = self.init_connection() self.init_consumer(mq) return mq.connection
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....
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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
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...
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:]) ...
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 = ...
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...
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()...
def _atexit(self): """Invoked in the 'finally' block of Application.run.""" self.log.debug("Application._atexit") if self._atexit_func: self._atexit_func(self)
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...
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)
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...
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()
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
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 ...
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: ...
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) ...
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
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): ...
def update(self, ava): """ Implements the dict.update() method """ for key, val in ava.items(): self[key] = val
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...
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...
def hex(x): ''' x-->bytes | bytearray Returns-->bytes: hex-encoded ''' if isinstance(x, bytearray): x = bytes(x) return encode(x, 'hex')
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...
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 ...
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/...
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...
def get_rand_bytes(encoding='latin1', l=64, avoid=[]): ''' encoding-->str: one of ENCODINGS l-->int: length of unicode str avoid-->list of int: to void (unprintable chars etc) Returns-->bytes representing unicode str of the requested encoding ''' return encode( get_rand_str(encoding=...
def main(): ''' Parse argv for options and arguments, and start schema generation. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]", formatter=optparse.TitledHelpFormatter()) parser....
def scrape(ctx, url): """ Rip the events from a given rss feed, normalize the data and store. """ data = load_feed(url) feed = data['feed'] entries = data['entries'] # THIS IS SPECIFIC TO # http://konfery.cz/rss/ _type = 'community' country = 'Czech Republic' # title, title_de...
def download_image(self): """ Download the image and return the local path to the image file. """ split = urlsplit(self.url) filename = split.path.split("/")[-1] # Ensure the directory to store the image cache exists if not os.path.exists(self.cache_direc...
def has_changed(self): """ Method to check if an image has changed since it was last downloaded. By making a head request, this check can be done quicker that downloading and processing the whole file. """ request = urllib_request.Request(self.url) ...
async def api_bikes(request): """ Gets stolen bikes within a radius of a given postcode. :param request: The aiohttp request. :return: The bikes stolen with the given range from a postcode. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: radius = int(requ...
def fancy_tag_compiler(params, defaults, takes_var_args, takes_var_kwargs, takes_context, name, node_class, parser, token): "Returns a template.Node subclass." bits = token.split_contents()[1:] if takes_context: if 'context' in params[:1]: params = params[1:] else: r...
def setup_logging(log_filename=None, log_level="DEBUG", str_format=None, date_format=None, log_file_level="DEBUG", log_stdout_level=None, log_restart=False, log_history=False, formatter=None, silence_modules=None, log_filter=None): """ This will setup loggin...
def setup_stdout_logging(log_level="DEBUG", log_stdout_level="DEBUG", str_format=None, date_format=None, formatter=None, silence_modules=None, log_filter=None): """ This will setup logging for stdout and stderr :param formatter: :param log_level: ...
def setup_file_logging(log_filename, log_file_level="DEBUG", str_format=None, date_format=None, log_restart=False, log_history=False, formatter=None, silence_modules=None, log_filter=None): """ This will setup logging for a single file but can be called more than on...
def add_file_handler(log_file_level, log_filename, str_format=None, date_format=None, formatter=None, log_filter=None): """ :param log_filename: :param log_file_level str of the log level to use on this file :param str_format: str of the logging format :param date_format:...
def add_handler(log_handler_level, handler, formatter=None, log_filter=None): """ :param log_handler_level: str of the level to set for the handler :param handler: logging.Handler handler to add :param formatter: logging.Formatter instance to use :param log_filter: l...
def set_module_log_level(modules=None, log_level=logging.WARNING): """ This will raise the log level for the given modules in general this is used to silence them :param modules: list of str of module names ex. ['requests'] :param log_level: str of the new log level :return: ...
def findCaller(self, stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = logging.currentframe() # On some versions of IronPython, currentframe() returns None if # IronPython isn...
def get_defining_component(pe_pe): ''' get the C_C in which pe_pe is defined ''' if pe_pe is None: return None if pe_pe.__class__.__name__ != 'PE_PE': pe_pe = xtuml.navigate_one(pe_pe).PE_PE[8001]() ep_pkg = xtuml.navigate_one(pe_pe).EP_PKG[8000]() if ep_pkg: ...
def prebuild_action(instance): ''' Transform textual OAL actions of an *instance* to instances in the ooaofooa subsystems Value and Body. The provided *instance* must be an instance of one of the following classes: - S_SYNC - S_BRG - O_TFR - O_DBATTR - SM_ACT - SPR_RO -...
def prebuild_model(metamodel): ''' Transform textual OAL actions in a ooaofooa *metamodel* to instances in the subsystems Value and Body. Instances of the following classes are supported: - S_SYNC - S_BRG - O_TFR - O_DBATTR - SM_ACT - SPR_RO - SPR_RS - SPR_PO - SPR_P...
def main(): ''' Parse command line options and launch the prebuilder. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]", version=xtuml.version.complete_string, formatter=optparse.TitledHelp...
def find_symbol(self, name=None, kind=None): ''' Find a symbol in the symbol table by name, kind, or both. ''' for s in reversed(self.stack): for symbol_name, handle in s.symbols.items(): symbol_kind = handle.__class__.__name__ ...
def update_membership(self, contact, group): ''' input: gdata ContactEntry and GroupEntry objects ''' if not contact: log.debug('Not updating membership for EMPTY contact.') return None _uid = contact.email[0].address _gtitle = group.title.text ...
def is_contained_in(pe_pe, root): ''' Determine if a PE_PE is contained within a EP_PKG or a C_C. ''' if not pe_pe: return False if type(pe_pe).__name__ != 'PE_PE': pe_pe = one(pe_pe).PE_PE[8001]() ep_pkg = one(pe_pe).EP_PKG[8000]() c_c = one(pe_pe).C_C[8003]() ...
def is_global(pe_pe): ''' Check if a PE_PE is globally defined, i.e. not inside a C_C ''' if type(pe_pe).__name__ != 'PE_PE': pe_pe = one(pe_pe).PE_PE[8001]() if one(pe_pe).C_C[8003](): return False pe_pe = one(pe_pe).EP_PKG[8000].PE_PE[8001]() if not pe_pe: ...