text
stringlengths
81
112k
Conditionally merges b into a if b's keys are contained in selection :param a: :param b: :param selection: limit merge to these top-level keys :param path: :return: def dict_selective_merge(a, b, selection, path=None): """Conditionally merges b into a if b's keys are contained in selection ...
merges b into a def dict_merge(a, b, path=None): """merges b into a""" return dict_selective_merge(a, b, b.keys(), path)
Check whether the credentials have expired. :param awsclient: :return: exit_code def are_credentials_still_valid(awsclient): """Check whether the credentials have expired. :param awsclient: :return: exit_code """ client = awsclient.get_client('lambda') try: client.list_functio...
Given a list, possibly nested to any level, return it flattened. def flatten(lis): """Given a list, possibly nested to any level, return it flattened.""" new_lis = [] for item in lis: if isinstance(item, collections.Sequence) and not isinstance(item, basestring): new_lis.extend(flatten(...
handle signals. example: 'signal.signal(signal.SIGTERM, signal_handler)' def signal_handler(signum, frame): """ handle signals. example: 'signal.signal(signal.SIGTERM, signal_handler)' """ # signals are CONSTANTS so there is no mapping from signum to description # so please add to the mappi...
This does format a dictionary into a table. Note this expects a dictionary (not a json string!) :param json: :return: def json2table(json): """This does format a dictionary into a table. Note this expects a dictionary (not a json string!) :param json: :return: """ filter_terms = [...
Create a random 6 character string. note: in case you use this function in a test during test together with an awsclient then this function is altered so you get reproducible results that will work with your recorded placebo json files (see helpers_aws.py). def random_string(length=6): """Create a ran...
Helper to process all pages using botocore service methods (exhausts NextToken). note: `cond` is optional... you can use it to make filtering more explicit if you like. Alternatively you can do the filtering in the `accessor` which is perfectly fine, too Note: lambda uses a slightly different mechanism ...
Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd :rtype: function def get_invoke(command): """ Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd ...
Get the Cmd help function from the click command :param command: The click Command object :return: the help_* method for Cmd :rtype: function def get_help(command): """ Get the Cmd help function from the click command :param command: The click Command object :return: the help_* method for C...
Get the Cmd complete function for the click command :param command: The click Command object :return: the complete_* method for Cmd :rtype: function def get_complete(command): """ Get the Cmd complete function for the click command :param command: The click Command object :return: the compl...
Bail out if template is not found. def load_template(): """Bail out if template is not found. """ cloudformation, found = load_cloudformation_template() if not found: print(colored.red('could not load cloudformation.py, bailing out...')) sys.exit(1) return cloudformation
Import public names from module into this module, like import * def _import_public_names(module): "Import public names from module into this module, like import *" self = sys.modules[__name__] for name in module.__all__: if hasattr(self, name): # don't overwrite existing names ...
Creates the argument parser for haas. def create_argument_parser(): """Creates the argument parser for haas. """ parser = argparse.ArgumentParser(prog='haas') parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(haas.__version__)) verbosity = par...
Run the haas test runner. This will load and configure the selected plugins, set up the environment and begin test discovery, loading and running. Parameters ---------- plugin_manager : haas.plugin_manager.PluginManager [Optional] Override the use of the default plu...
Crypt :new_value: if it's not crypted yet. def encrypt_password(**kwargs): """ Crypt :new_value: if it's not crypted yet. """ new_value = kwargs['new_value'] field = kwargs['field'] min_length = field.params['min_length'] if len(new_value) < min_length: raise ValueError( '`{}`: ...
Generate ApiKey model class and connect it with :user_model:. ApiKey is generated with relationship to user model class :user_model: as a One-to-One relationship with a backreference. ApiKey is set up to be auto-generated when a new :user_model: is created. Returns ApiKey document class. If ApiKey is ...
Helper function to cache currently logged in user. User is cached at `request._user`. Caching happens only only if user is not already cached or if cached user's pk does not match `user_id`. :param user_cls: User model class to use for user lookup. :param request: Pyramid Request instance. :us...
Get api token for user with username of :username: Used by Token-based auth as `credentials_callback` kwarg. def get_token_credentials(cls, username, request): """ Get api token for user with username of :username: Used by Token-based auth as `credentials_callback` kwarg. """ ...
Get user's groups if user with :username: exists and their api key token equals :token: Used by Token-based authentication as `check` kwarg. def get_groups_by_token(cls, username, token, request): """ Get user's groups if user with :username: exists and their api key token equals :toke...
Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views). def authenticate_by_password(cls, params): """ Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views). ...
Return group identifiers of user with id :userid: Used by Ticket-based auth as `callback` kwarg. def get_groups_by_userid(cls, userid, request): """ Return group identifiers of user with id :userid: Used by Ticket-based auth as `callback` kwarg. """ try: cache_requ...
Create auth user instance with data from :params:. Used by both Token and Ticket-based auths to register a user ( called from views). def create_account(cls, params): """ Create auth user instance with data from :params:. Used by both Token and Ticket-based auths to register a user ( ...
Get user by ID. Used by Ticket-based auth. Is added as request method to populate `request.user`. def get_authuser_by_userid(cls, request): """ Get user by ID. Used by Ticket-based auth. Is added as request method to populate `request.user`. """ userid = authen...
Get user by username Used by Token-based auth. Is added as request method to populate `request.user`. def get_authuser_by_name(cls, request): """ Get user by username Used by Token-based auth. Is added as request method to populate `request.user`. """ username ...
Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on the fly. def walk(self): """ Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on th...
Set up event subscribers. def includeme(config): """ Set up event subscribers. """ from .models import ( AuthUserMixin, random_uuid, lower_strip, encrypt_password, ) add_proc = config.add_field_processors add_proc( [random_uuid, lower_strip], model=Au...
Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification def _make_request(self, method, params): """Make request to API endpoint Note: Ignoring SSL cert validation due t...
channels.list This method returns a list of all channels in the team. This includes channels the caller is in, channels they are not currently in, and archived channels. The number of (non-deactivated) members in each channel is also returned. https://api.slack.com/methods/chan...
Helper name for getting a channel's id from its name def channel_name_to_id(self, channel_name, force_lookup=False): """Helper name for getting a channel's id from its name """ if force_lookup or not self.channel_name_id_map: channels = self.channels_list()['channels'] s...
chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage ...
chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default formatting rules. (e.g: "Hello world") `timestamp`: Timestamp of the me...
Connect view to route that catches all URIs like 'something,something,...' def includeme(config): """ Connect view to route that catches all URIs like 'something,something,...' """ root = config.get_root_resource() root.add('nef_polymorphic', '{collections:.+,.+}', view=Polymorphic...
Get names of collections from request matchdict. :return: Names of collections :rtype: list of str def get_collections(self): """ Get names of collections from request matchdict. :return: Names of collections :rtype: list of str """ collections = self.request.m...
Get resources that correspond to values from :collections:. :param collections: Collection names for which resources should be gathered :type collections: list of str :return: Gathered resources :rtype: list of Resource instances def get_resources(self, collections): ...
Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, user MUST have access to all of them. If this is true, ACEs are returned, that allows 'view' permissions to current request principals. Otherwise None is returned thus blocking all...
Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited. def set_collections_acl(self): """ Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inher...
Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered. def determine_types(self): """ Determine ES type names from re...
Returns a closure function that dispatches message to the WebSocket. def get_command(domain_name, command_name): """Returns a closure function that dispatches message to the WebSocket.""" def send_command(self, **kwargs): return self.ws.send_message( '{0}.{1}'.format(domain_name, command_na...
Dynamically create Domain class and set it's methods. def DomainFactory(domain_name, cmds): """Dynamically create Domain class and set it's methods.""" klass = type(str(domain_name), (BaseDomain,), {}) for c in cmds: command = get_command(domain_name, c['name']) setattr(klass, c['name'], c...
The entrypoint for the hairball command installed via setup.py. def main(): """The entrypoint for the hairball command installed via setup.py.""" description = ('PATH can be either the path to a scratch file, or a ' 'directory containing scratch files. Multiple PATH ' 'arg...
Return the sha1sum (key) belonging to the file at filepath. def path_to_key(filepath): """Return the sha1sum (key) belonging to the file at filepath.""" tmp, last = os.path.split(filepath) tmp, middle = os.path.split(tmp) return '{}{}{}'.format(os.path.basename(tmp), middle, ...
Return the fullpath to the file with sha1sum key. def key_to_path(self, key): """Return the fullpath to the file with sha1sum key.""" return os.path.join(self.cache_dir, key[:2], key[2:4], key[4:] + '.pkl')
Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it. def load(self, filename): """Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it. """ # Compute...
Yield filepath to files with the proper extension within paths. def hairball_files(self, paths, extensions): """Yield filepath to files with the proper extension within paths.""" def add_file(filename): return os.path.splitext(filename)[1] in extensions while paths: arg...
Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. def initialize_plugins(self): """Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. """ for plugin_name in self.options.plugi...
Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file. def process(self): """Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run agai...
If ``module`` is a dotted string pointing to the module, imports and returns the module object. def maybe_dotted(module, throw=True): """ If ``module`` is a dotted string pointing to the module, imports and returns the module object. """ try: return Configurator().maybe_dotted(module) e...
Return True if `arg` acts as a list and does not look like a string. def issequence(arg): """Return True if `arg` acts as a list and does not look like a string.""" string_behaviour = ( isinstance(arg, six.string_types) or isinstance(arg, six.text_type)) list_behaviour = hasattr(arg, '__get...
Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107 def merge_dicts(a, b, path=None): """ Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: if i...
Convert dotted string to dict splitting by :separator: def str2dict(dotted_str, value=None, separator='.'): """ Convert dotted string to dict splitting by :separator: """ dict_ = {} parts = dotted_str.split(separator) d, prev = dict_, None for part in parts: prev = d d = d.setdefaul...
Validate :data: contains only data allowed by privacy settings. :param request: Pyramid Request instance :param data: Dict containing request/response data which should be validated def validate_data_privacy(request, data, wrapper_kw=None): """ Validate :data: contains only data allowed by privacy...
Drops reserved params def drop_reserved_params(params): """ Drops reserved params """ from nefertari import RESERVED_PARAMS params = params.copy() for reserved_param in RESERVED_PARAMS: if reserved_param in params: params.pop(reserved_param) return params
Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns: If a value is being requested ( opt2 is "?" ), ...
Description: Returns dict of information about the TV name, model, version def info(self): """ Description: Returns dict of information about the TV name, model, version """ return {"name": self._send_command('name'), "m...
Description: Get input list Returns an ordered list of all available input keys and names def get_input_list(self): """ Description: Get input list Returns an ordered list of all available input keys and names """ inputs = [' '] * len(s...
Description: Set the input Call with no arguments to get current setting Arguments: opt: string Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1") def input(self, opt): """ Description: Set the input ...
Description: Change Channel (Digital) Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY) Arguments: opt1: integer 1-99: Major Channel opt2: integer (optional) 1-99: Minor Channel def digital_channel_air(self, opt1='?', opt2=...
Description: Change Channel (Digital) Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY) Arguments: opt1: integer 1-999: Major Channel opt2: integer (optional) 0-999: Minor Channel def digital_channel_cable(self, opt1=...
Description: Get remote button list Returns an list of all available remote buttons def get_remote_button_list(self): """ Description: Get remote button list Returns an list of all available remote buttons """ remote_buttons = [] ...
Return a 3 tuple for something. def check_results(tmp_): """Return a 3 tuple for something.""" # TODO: Fix this to work with more meaningful names if tmp_['t'] > 0: if tmp_['l'] > 0: if tmp_['rr'] > 0 or tmp_['ra'] > 1: print 1, 3, tmp_ ...
Internal helper function to check the animation. def _check_animation(self, last, last_level, gen): """Internal helper function to check the animation.""" tmp_ = Counter() results = Counter() name, level, block = last, last_level, last others = False while name in self.A...
Run and return the results from the Animation plugin. def analyze(self, scratch, **kwargs): """Run and return the results from the Animation plugin.""" results = Counter() for script in self.iter_scripts(scratch): gen = self.iter_blocks(script.blocks) name = 'start' ...
Return a list of received events contained in script_list. def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: ...
Run and return the results from the BroadcastReceive plugin. def analyze(self, scratch, **kwargs): """Run and return the results from the BroadcastReceive plugin.""" all_scripts = list(self.iter_scripts(scratch)) results = defaultdict(set) broadcast = dict((x, self.get_broadcast_events(...
Categorize instances of attempted say and sound synchronization. def analyze(self, scratch, **kwargs): """Categorize instances of attempted say and sound synchronization.""" errors = Counter() for script in self.iter_scripts(scratch): prev_name, prev_depth, prev_block = '', 0, scrip...
Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play sound until done say 'message 2' say 'message 3' play sound until done say '' def check(self, gen): """Check that th...
Converts a sys.exc_info()-style tuple of values into a string. def _format_exception(err, is_failure, stdout=None, stderr=None): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and _is_relevant_tb_level(tb): ...
Hook stdout and stderr if buffering is enabled. def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() ...
Unhook stdout and stderr if buffering is enabled. def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() ...
Register a new result handler. def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None
Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :cla...
Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tup...
Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. def addError(self, test, exception): """Register that a test ended in a...
Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. def addFailure(self, test, exception): """Register that a test ended...
Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. def addSkip(self, test, reason): """Register that a test that was skipped. Parameter...
Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. def addExpectedFailure(self, test, exception): """Re...
Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase ...
Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key def set_terminal_key(self, encrypted_key): """ Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key ...
Get PIN block in ISO 0 format, encrypted with the terminal key def get_encrypted_pin(self, clear_pin, card_number): """ Get PIN block in ISO 0 format, encrypted with the terminal key """ if not self.terminal_key: print('Terminal key is not set') return '' ...
Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool def is_url(string, allowed_schemes=None): """ Check if a string...
Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card type. :type card_type: str Can be one of these: ...
Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore (or provided separator) * it does not start with ...
Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool def is_json(string): """ Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false other...
Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the string is a palindrome (like "otto", or "i topi non aveva...
Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise. def is_pangram(string): """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param...
Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise. def is_slug(string, sign='-'): """ Checks if a given string is a slug. :param string: String to check....
Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. :rtype: str def camel_cas...
Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first letter into uppercase (default). :type upper_case_first: bool :param separ...
Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str def shuffle(string): """ Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled strin...
Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. :rtype: str def str...
Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \*, =) must have one, ...
Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugified string def slugify(string, sign='-'): ...
Initialize Sphinx extension. def setup(app): """Initialize Sphinx extension.""" app.setup_extension('nbsphinx') app.add_source_suffix('.nblink', 'linked_jupyter_notebook') app.add_source_parser(LinkedNotebookParser) app.add_config_value('nbsphinx_link_target_root', None, rebuild='env') return ...
Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the n...
Output the duplicate scripts detected. def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print('{} duplicate scripts found'.format(self.total_duplicate)) for duplicate in self.list_duplicate: print(duplicate)
Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. def analyze(self, scratch, **kwargs): """Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. """ ...
Set response content type def _set_content_type(self, system): """ Set response content type """ request = system.get('request') if request: response = request.response ct = response.content_type if ct == response.default_content_type: respons...
Render a response def _render_response(self, value, system): """ Render a response """ view = system['view'] enc_class = getattr(view, '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return json.dumps(value, cls=enc_class)
Get kwargs common for all methods. def _get_common_kwargs(self, system): """ Get kwargs common for all methods. """ enc_class = getattr(system['view'], '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return { 'request': system['request...