code
stringlengths 1
18.2k
|
|---|
FIXME: This needs a better description. Parameters ---------- start : str The directory, package, module, class or test to load. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ logger.debug('Starting test discovery') if os.path.isdir(start):
|
start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(start): start_filepath = start return self.discover_by_file( start_filepath, top_level_directory=top_level_directory) else: package_or_module = start return self.discover_by_module( package_or_module, top_level_directory=top_level_directory, pattern=pattern)
|
def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of
|
the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ # If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module: module_name=%r, ' 'top_level_directory=%r, pattern=%r', module_name, top_level_directory,
|
pattern) try: module, case_attributes = find_module_by_name(module_name) except ImportError: return self.discover_filtered_tests( module_name, top_level_directory=top_level_directory, pattern=pattern) dirname, basename = os.path.split(module.__file__) basename = os.path.splitext(basename)[0] if len(case_attributes) == 0 and basename == '__init__': # Discover in a package return self.discover_by_directory( dirname, top_level_directory, pattern=pattern) elif len(case_attributes) == 0: # Discover all in a module return self._loader.load_module(module) return self.discover_single_case(module, case_attributes)
|
def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be the name of a TestCase subclass. The second component must be the name of a method in
|
the TestCase. """ # Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): rest = case_attributes[index + 1:] if len(rest) > 1: raise ValueError('Too many components in module path') elif len(rest) == 1: return loader.create_suite( [loader.load_test(case, *rest)]) return loader.load_case(case) # No cases matched, return empty suite
|
return loader.create_suite()
|
def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """
|
start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r', start_directory, top_level_directory, pattern) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._discover_tests( start_directory, top_level_directory, pattern) return self._loader.create_suite(list(tests))
|
def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. """ start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests
|
in file: start_filepath=%r, ' 'top_level_directory=', start_filepath, top_level_directory) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._load_from_file( start_filepath, top_level_directory) return self._loader.create_suite(list(tests))
|
def _set_options_headers(self, methods): """ Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Arguments: :methods: Sequence of HTTP method names that are value for requested URI """ request = self.request response = request.response response.headers['Allow'] = ', '.join(sorted(methods)) if 'Access-Control-Request-Method' in request.headers: response.headers['Access-Control-Allow-Methods'] = \ ', '.join(sorted(methods)) if 'Access-Control-Request-Headers' in request.headers: response.headers['Access-Control-Allow-Headers'] = \ 'origin, x-requested-with, content-type' return response
|
def _get_handled_methods(self, actions_map): """ Get names of HTTP methods that can be used at requested URI. Arguments: :actions_map: Map of actions. Must have the same structure as self._item_actions and self._collection_actions """ methods = ('OPTIONS',) defined_actions = [] for action_name in actions_map.keys(): view_method = getattr(self, action_name, None) method_exists = view_method is not None method_defined = view_method != self.not_allowed_action if method_exists and method_defined: defined_actions.append(action_name) for action
|
in defined_actions: methods += actions_map[action] return methods
|
def item_options(self, **kwargs): """ Handle collection OPTIONS request. Singular route requests are handled a bit differently because singular views may handle POST requests despite being registered as item routes. """ actions = self._item_actions.copy() if self._resource.is_singular: actions['create'] = ('POST',) methods = self._get_handled_methods(actions) return self._set_options_headers(methods)
|
def collection_options(self, **kwargs): """ Handle collection item OPTIONS request. """ methods = self._get_handled_methods(self._collection_actions) return self._set_options_headers(methods)
|
def wrap(self, func): """ Wrap :func: to perform aggregation on :func: call. Should be called with view instance methods. """ @six.wraps(func) def wrapper(*args, **kwargs): try: return self.aggregate() except KeyError: return func(*args, **kwargs) return wrapper
|
def pop_aggregations_params(self): """ Pop and return aggregation params from query string params. Aggregation params are expected to be prefixed(nested under) by any of `self._aggregations_keys`. """ from nefertari.view import BaseView self._query_params = BaseView.convert_dotted(self.view._query_params) for key in self._aggregations_keys: if key in self._query_params: return self._query_params.pop(key) else: raise KeyError('Missing aggregation params')
|
def get_aggregations_fields(cls, params): """ Recursively get values under the 'field' key. Is used to get names of fields on which aggregations should be performed. """ fields = [] for key, val in params.items(): if isinstance(val, dict): fields += cls.get_aggregations_fields(val) if key == 'field': fields.append(val) return fields
|
def check_aggregations_privacy(self, aggregations_params): """ Check per-field privacy rules in aggregations. Privacy is checked by making sure user has access to the fields used in aggregations. """ fields = self.get_aggregations_fields(aggregations_params) fields_dict = dictset.fromkeys(fields) fields_dict['_type'] = self.view.Model.__name__ try: validate_data_privacy(self.view.request, fields_dict) except wrappers.ValidationError as ex: raise JHTTPForbidden( 'Not enough permissions to aggregate on ' 'fields: {}'.format(ex))
|
def aggregate(self): """ Perform aggregation and return response. """ from nefertari.elasticsearch import ES aggregations_params = self.pop_aggregations_params() if self.view._auth_enabled: self.check_aggregations_privacy(aggregations_params) self.stub_wrappers() return ES(self.view.Model.__name__).aggregate( _aggregations_params=aggregations_params, **self._query_params)
|
def asdict(self, name, _type=None, _set=False): """ Turn this 'a:2,b:blabla,c:True,a:'d' to {a:[2, 'd'], b:'blabla', c:True} """ if _type is None: _type = lambda t: t dict_str = self.pop(name, None) if not dict_str: return {} _dict = {} for item in split_strip(dict_str): key, _, val = item.partition(':') val = _type(val) if key in _dict: if isinstance(_dict[key], list): _dict[key].append(val) else: _dict[key] = [_dict[key], val] else: _dict[key] =
|
val if _set: self[name] = _dict return _dict
|
def get_random_hex(length): """ Return random hex string of a given length """ if length <= 0: return '' return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
|
def get_response(_code): """ Return xx1x response for xx0x codes (e.g. 0810 for 0800) """ if _code: code = str(_code) return code[:-2] + str(int(code[-2:-1]) + 1) + code[-1] else: return None
|
def load_case(self, testcase): """Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. Parameters ---------- testcase : type A subclass of :class:`unittest.TestCase` """ tests = [self.load_test(testcase, name) for name in self.find_test_method_names(testcase)] return self.create_suite(tests)
|
def load_module(self, module): """Create and return a test suite containing all cases loaded from the provided module. Parameters ---------- module : module A module object containing ``TestCases`` """ cases = self.get_test_cases_from_module(module) suites = [self.load_case(case) for case in cases] return self.create_suite(suites)
|
def Field(self, field, Value = None): ''' Add field to bitmap ''' if Value == None: try: return self.__Bitmap[field] except KeyError: return None elif Value == 1 or Value == 0: self.__Bitmap[field] = Value else: raise ValueError
|
def FieldData(self, field, Value = None): ''' Add field data ''' if Value == None: try: return self.__FieldData[field] except KeyError: return None else: if len(str(Value)) > self.__IsoSpec.MaxLength(field): raise ValueError('Value length larger than field maximum ({0})'.format(self.__IsoSpec.MaxLength(field))) self.Field(field, Value=1) self.__FieldData[field] = Value
|
def authenticated_userid(request): """Helper function that can be used in ``db_key`` to support `self` as a collection key. """ user = getattr(request, 'user', None) key = user.pk_field() return getattr(user, key)
|
def iter_blocks(block_list): """A generator for blocks contained in a block list. Yields tuples containing the block name, the depth that the block was found at, and finally a handle to the block itself. """ # queue the block and the depth of the block queue = [(block, 0) for block in block_list if isinstance(block, kurt.Block)] while queue: block, depth = queue.pop(0) assert block.type.text yield
|
block.type.text, depth, block for arg in block.args: if hasattr(arg, '__iter__'): queue[0:0] = [(x, depth + 1) for x in arg if isinstance(x, kurt.Block)] elif isinstance(arg, kurt.Block): queue.append((arg, depth))
|
def iter_scripts(scratch): """A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite """ for script in scratch.stage.scripts: if not isinstance(script, kurt.Comment): yield script for sprite in scratch.sprites: for script in sprite.scripts: if not isinstance(script, kurt.Comment): yield script
|
def iter_sprite_scripts(scratch): """A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite """ for script in scratch.stage.scripts: if not isinstance(script, kurt.Comment): yield ('Stage', script) for sprite in scratch.sprites: for script in sprite.scripts: if not isinstance(script, kurt.Comment): yield (sprite.name, script)
|
def script_start_type(script): """Return the type of block the script begins with.""" if script[0].type.text == 'when @greenFlag clicked': return HairballPlugin.HAT_GREEN_FLAG elif script[0].type.text == 'when I receive %s': return HairballPlugin.HAT_WHEN_I_RECEIVE elif script[0].type.text == 'when this sprite clicked': return HairballPlugin.HAT_MOUSE elif script[0].type.text == 'when %s key pressed': return HairballPlugin.HAT_KEY else: return HairballPlugin.NO_HAT
|
def get_broadcast_events(cls, script): """Return a Counter of event-names that were broadcast. The Count will contain the key True if any of the broadcast blocks contain a parameter that is a variable. """ events = Counter() for name, _, block in cls.iter_blocks(script): if 'broadcast %s' in name: if isinstance(block.args[0], kurt.Block): events[True] += 1 else: events[block.args[0].lower()] += 1 return events
|
def tag_reachable_scripts(cls, scratch): """Tag each script with attribute reachable. The reachable attribute will be set false for any script that does not begin with a hat block. Additionally, any script that begins with a 'when I receive' block whose event-name doesn't appear in a corresponding broadcast block is marked as unreachable. """ if getattr(scratch, 'hairball_prepared', False): # Only process once return reachable = set()
|
untriggered_events = {} # Initial pass to find reachable and potentially reachable scripts for script in cls.iter_scripts(scratch): if not isinstance(script, kurt.Comment): starting_type = cls.script_start_type(script) if starting_type == cls.NO_HAT: script.reachable = False elif starting_type == cls.HAT_WHEN_I_RECEIVE: # Value will be updated if reachable script.reachable = False message = script[0].args[0].lower() untriggered_events.setdefault(message, set()).add(script) else: script.reachable = True reachable.add(script) # Expand reachable states based on broadcast events while
|
reachable: for event in cls.get_broadcast_events(reachable.pop()): if event in untriggered_events: for script in untriggered_events.pop(event): script.reachable = True reachable.add(script) scratch.hairball_prepared = True
|
def description(self): """Attribute that returns the plugin description from its docstring.""" lines = [] for line in self.__doc__.split('\n')[2:]: line = line.strip() if line: lines.append(line) return ' '.join(lines)
|
def _process(self, scratch, filename, **kwargs): """Internal hook that marks reachable scripts before calling analyze. Returns data exactly as returned by the analyze method. """ self.tag_reachable_scripts(scratch) return self.analyze(scratch, filename=filename, **kwargs)
|
def close(self): """ Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement, you must call this manually, it is not triggered automatically like on a file object. :return: Nothing. """ self.zipf.writestr("content.xml", self.dom.toxml().encode("utf-8")) self.zipf.close()
|
def writerow(self, cells): """ Write a row of cells into the default sheet of the spreadsheet. :param cells: A list of cells (most basic Python types supported). :return: Nothing. """ if self.default_sheet is None: self.default_sheet = self.new_sheet() self.default_sheet.writerow(cells)
|
def new_sheet(self, name=None, cols=None): """ Create a new sheet in the spreadsheet and return it so content can be added. :param name: Optional name for the sheet. :param cols: Specify the number of columns, needed for compatibility in some cases :return: Sheet object """ sheet = Sheet(self.dom, name, cols) self.sheets.append(sheet) return sheet
|
def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld']
|
= ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.keys(): for v in formats[k]: if v in kwargs: kwargs[k] = kwargs[v] kwargs.pop(v) return func(*args, **kwargs) return inner
|
def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start. iend = limit # Index of group end. dft = kwargs.pop('dft', None) if type(dft) == int: dft = str(dft) while
|
True: if iend > len(entries): iend = len(entries) istart = iend - limit if istart < 0: istart = 0 iend = limit unext = len(entries) - iend # Number of next entries. uprev = istart # Number of previous entries. nnext = "" # Name of 'next' menu entry. nprev = "" # Name of 'prev' menu entry. dnext = "" # Description
|
of 'next' menu entry. dprev = "" # Description of 'prev' menu entry. group = copy.deepcopy(entries[istart:iend]) names = [i.name for i in group] if unext > 0: for i in ["n", "N", "next", "NEXT", "->", ">>", ">>>"]: if i not in names: nnext = i dnext = "Next %u of %u entries" % (unext, len(entries)) group.append(MenuEntry(nnext, dnext, None, None, None)) names.append("n") break if uprev
|
> 0: for i in ["p", "P", "prev", "PREV", "<-", "<<", "<<<"]: if i not in names: nprev = i dprev = "Previous %u of %u entries" % (uprev, len(entries)) group.append(MenuEntry(nprev, dprev, None, None, None)) names.append("p") break tmpdft = None if dft != None: if dft not in names: if "n" in names: tmpdft = "n" else: tmpdft = dft result = show_menu(group, dft=tmpdft,
|
**kwargs) if result == nnext or result == dnext: istart += limit iend += limit elif result == nprev or result == dprev: istart -= limit iend -= limit else: return result
|
def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items
|
will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr =
|
kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries:
|
msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg,
|
vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return
|
getattr(entry, "name")
|
def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func()
|
def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu
|
def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|str|func]) - Valid input
|
entries. - shw (bool) - If true, show the user's input as typed. - blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input. """ global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if
|
int == v: lst.append("<int>") elif float == v: lst.append("<float>") elif str == v: lst.append("<str>") else: lst.append("(" + v.__name__ + ")") if lst: echo("[HELP] Valid input: %s" % (" | ".join([str(l) for l in lst]))) if hlp: echo("[HELP] Extra notes: " + hlp) if blk: echo("[HELP] Input may be blank.") vld = vld or [] hlp = hlp or "" if not hasattr(vld, "__iter__"): vld
|
= [vld] if not hasattr(fmt, "__call__"): fmt = lambda x: x # NOTE: Defaults to function that does nothing. msg = "%s%s" % (QSTR if qstr else "", msg) dft = fmt(dft) if dft != None else None # Prevents showing [None] default. if dft != None: msg += " [%s]" % (dft if type(dft) is str else repr(dft)) vld.append(dft) blk = False if
|
vld: # Sanitize valid inputs. vld = list(set([fmt(v) if fmt(v) else v for v in vld])) if blk and "" not in vld: vld.append("") # NOTE: The following fixes a Py3 related bug found in `0.8.1`. try: vld = sorted(vld) except: pass msg += ISTR ans = None while ans is None: get_input = _input if shw else getpass ans = get_input(msg) if _AUTO:
|
echo(ans) if "?" == ans: print_help() ans = None continue if "" == ans: if dft != None: ans = dft if not fmt else fmt(dft) break if "" not in vld: ans = None continue try: ans = ans if not fmt else fmt(ans) except: ans = None if vld: for v in vld: if type(v) is type and cast(ans, v) is not
|
None: ans = cast(ans, v) break elif hasattr(v, "__call__"): try: if v(ans): break except: pass elif ans in vld: break else: ans = None return ans
|
def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes
|
def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
|
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
|
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
|
def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
|
def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
|
def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to print at start of `func`. The following parameters are available when
|
used as a function: - msg (str) [args] - Message to print at start of `func`. - func (func) - Function to call. First `args` if using `status()` as a function. Automatically provided if using `status()` as a decorator. - fargs (list) - List of `args` passed to `func`. - fkrgs (dict) - Dictionary of `kwargs` passed to `func`. - fin (str) [kwargs] -
|
Message to print when `func` finishes. **Examples**: :: @qprompt.status("Something is happening...") def do_something(a): time.sleep(a) do_something() # [!] Something is happening... DONE. qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv}) # [!] Doing a thing... DONE. """ def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args =
|
list(args) if len(args) > 1 and callable(args[1]): msg = args.pop(0) func = args.pop(0) try: fargs = args.pop(0) except: fargs = [] try: fkrgs = args.pop(0) except: fkrgs = {} return decor(func)(*fargs, **fkrgs) msg = args.pop(0) return decor
|
def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode)
|
def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width))
|
def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
|
def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. """ with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item)
|
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a number postfix.
|
count = 2 while name in taken: name = name + str(count) count += 1 return name
|
def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
|
def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
|
def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs)
|
def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break
|
def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. - loop (bool) - If true, the menu
|
will loop until quit. - quit ((str,str)) - If provided, adds a quit option to the menu. """ def _main(): global _AUTO if quit: if self.entries[-1][:2] != quit: self.add(*quit, func=lambda: quit[0]) if stdin_auto.auto: _AUTO = True result = None if loop: note = "Menu loops until quit." try: while True: mresult = self.show(note=note, **kwargs) if mresult in quit: break result = mresult except EOFError:
|
pass return result else: note = "Menu does not loop, single entry." result = self.show(note=note, **kwargs) return result global _AUTO if _AUTO: return _main() else: with stdin_auto: return _main()
|
def partition_scripts(scripts, start_type1, start_type2): """Return two lists of scripts out of the original `scripts` list. Scripts that begin with a `start_type1` or `start_type2` blocks are returned first. All other scripts are returned second. """ match, other = [], [] for script in scripts: if (HairballPlugin.script_start_type(script) == start_type1 or HairballPlugin.script_start_type(script) == start_type2): match.append(script) else: other.append(script) return match, other
|
def attribute_result(cls, sprites): """Return mapping of attributes to if they were initialized or not.""" retval = dict((x, True) for x in cls.ATTRIBUTES) for properties in sprites.values(): for attribute, state in properties.items(): retval[attribute] &= state != cls.STATE_MODIFIED return retval
|
def attribute_state(cls, scripts, attribute): """Return the state of the scripts for the given attribute. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be initialized. """ green_flag, other = partition_scripts(scripts, cls.HAT_GREEN_FLAG, cls.HAT_CLONE) block_set = cls.BLOCKMAPPING[attribute] state = cls.STATE_NOT_MODIFIED # TODO: Any regular broadcast blocks encountered in the initialization #
|
zone should be added to this loop for conflict checking. for script in green_flag: in_zone = True for name, level, _ in cls.iter_blocks(script.blocks): if name == 'broadcast %s and wait': # TODO: Follow the broadcast and wait scripts that occur in # the initialization zone in_zone = False if (name, 'absolute') in block_set: if in_zone and level == 0: # Success! if state ==
|
cls.STATE_NOT_MODIFIED: state = cls.STATE_INITIALIZED else: # Multiple when green flag clicked conflict state = cls.STATE_MODIFIED elif in_zone: continue # Conservative ignore for nested absolutes else: state = cls.STATE_MODIFIED break # The state of the script has been determined elif (name, 'relative') in block_set: state = cls.STATE_MODIFIED break if state != cls.STATE_NOT_MODIFIED: return state # Check the other scripts to see if the attribute was
|
ever modified for script in other: for name, _, _ in cls.iter_blocks(script.blocks): if name in [x[0] for x in block_set]: return cls.STATE_MODIFIED return cls.STATE_NOT_MODIFIED
|
def output_results(cls, sprites): """Output whether or not each attribute was correctly initialized. Attributes that were not modified at all are considered to be properly initialized. """ print(' '.join(cls.ATTRIBUTES)) format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) for x in cls.ATTRIBUTES] print(' '.join(format_strs).format(**cls.attribute_result(sprites)))
|
def sprite_changes(cls, sprite): """Return a mapping of attributes to their initilization state.""" retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in (x for x in cls.ATTRIBUTES if x != 'background')) return retval
|
def analyze(self, scratch, **kwargs): """Run and return the results of the AttributeInitialization plugin.""" changes = dict((x.name, self.sprite_changes(x)) for x in scratch.sprites) changes['stage'] = { 'background': self.attribute_state(scratch.stage.scripts, 'costume')} # self.output_results(changes) return {'initialized': changes}
|
def variable_state(cls, scripts, variables): """Return the initialization state for each variable in variables. The state is determined based on the scripts passed in via the scripts parameter. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be initialized. """ def conditionally_set_not_modified(): """Set the variable to modified if it hasn't
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.