code stringlengths 1 18.2k |
|---|
row id in seen set then it means the row has been completely processed seen = set() for row in rows: if row['id'] in seen: continue seen.add(row['id']) new_row = {} # adds level 1 fields for field in row: if field not in list_embeds: new_row[field] = row[field] # adds all level 2 fields # list() for py34 row_ids_to_emb... |
adds the nested fields if there is somes for embd in list_embeds: if embd in row_ids_to_embed_values_keys: if '.' in embd: prefix, suffix = embd.split('.', 1) new_row[prefix][suffix] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new_row[embd] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new... |
complete ! result.append(new_row) return result |
def common_values_dict(): """Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. """ now = datetime.datetime.utcnow().isoformat() etag = utils.gen_etag() values = { 'id': util... |
def execute(self, fetchall=False, fetchone=False, use_labels=True): """ :param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return: """ query = self.get_query(use_labels=use_labels) if fetchall: return flask.g.db_conn.execute(query).fetchall() e... |
def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( json.dumps( { 'identity': { 'id': identity.id, 'etag': identity.etag, 'name': identity.name, 'fullname': identity.fullname, 'email': identity.email, 'timezone': identity.timezone, 'teams': _encod... |
def get_issues_by_resource(resource_id, table): """Get all issues for a specific job.""" v1_utils.verify_existence_and_get(resource_id, table) # When retrieving the issues for a job, we actually retrieve # the issues attach to the job itself + the issues attached to # the components the job has been run with. if table.... |
to all the components attach to a job j1 = sql.join( _TABLE, sql.join( JCI, JJC, sql.and_( JCI.c.component_id == JJC.c.component_id, JJC.c.job_id == resource_id, ), ), _TABLE.c.id == JCI.c.issue_id, ) query = sql.select([_TABLE]).select_from(j1) rows = flask.g.db_conn.execute(query) rows = [dict(row) for row in rows] #... |
query2 = sql.select([_TABLE]).select_from(j2) rows2 = flask.g.db_conn.execute(query2) rows += [dict(row) for row in rows2] # When retrieving the issues for a component, we only retrieve the # issues attached to the specified component. else: JCI = models.JOIN_COMPONENTS_ISSUES query = (sql.select([_TABLE]) .select_from... |
elif row['tracker'] == 'bugzilla': l_tracker = bugzilla.Bugzilla(row['url']) row.update(l_tracker.dump()) return flask.jsonify({'issues': rows, '_meta': {'count': len(rows)}}) |
def unattach_issue(resource_id, issue_id, table): """Unattach an issue from a specific job.""" v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_id == resource_id, join_table.c.issue_id == issue_id) else: join_table... |
def attach_issue(resource_id, table, user_id): """Attach an issue to a specific job.""" data = schemas.issue.post(flask.request.json) issue = _get_or_create_issue(data) # Second, insert a join record in the JOIN_JOBS_ISSUES or # JOIN_COMPONENTS_ISSUES database. if table.name == 'jobs': join_table = models.JOIN_JOBS_ISS... |
% key) result = json.dumps({'issue': dict(issue)}) return flask.Response(result, 201, content_type='application/json') |
def collect_staticroot_removal(app, blueprints): """Remove collect's static root folder from list.""" collect_root = app.extensions['collect'].static_root return [bp for bp in blueprints if ( bp.has_static_folder and bp.static_folder != collect_root)] |
def get_all_jobstates(user, job_id): """Get all jobstates. """ args = schemas.args(flask.request.args.to_dict()) job = v1_utils.verify_existence_and_get(job_id, models.JOBS) if user.is_not_super_admin() and user.is_not_read_only_user(): if (job['team_id'] not in user.teams_ids and job['team_id'] not in user.child_teams... |
{'count': nb_rows}}) |
def create_client(access_token): """Create the dci client in the master realm.""" url = 'http://keycloak:8080/auth/admin/realms/dci-test/clients' r = requests.post(url, data=json.dumps(client_data), headers=get_auth_headers(access_token)) if r.status_code in (201, 409): print('Keycloak client dci created successfully.'... |
def create_user_dci(access_token): """Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io""" user_data = {'username': 'dci', 'email': 'dci@distributed-ci.io', 'enabled': True, 'emailVerified': True, 'credentials': [{'type': 'password', 'value': 'dci'}]} r = requests.post('http://keycloak:8080... |
def initialize(self, name=None, dbname=None, base=None, generator=None, case=None, namespaces=None): self.name = none_or(name, str) """ The name of the site. : str | `None` """ self.dbname = none_or(dbname, str) """ The dbname of the site. : str | `None` """ self.base = none_or(base, str) """ TODO: ??? : str | `None` "... |
none_or(case, str) """ TODO: ??? : str | `None` """ self.namespaces = none_or(namespaces, list) """ A list of :class:`mwtypes.Namespace` | `None` """ |
def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lowe... |
def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self.accountemail: headers.update({'Account-Em... |
method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid meth... |
%s\n' % response.json()) response.raise_for_status() return response |
def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None * to -- Only include actions generated prior to this timestamp. Form... |
results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identi... |
Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android']... |
contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short descri... |
was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) re... |
def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: S... |
key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']] |
def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check |
def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False ... |
Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about... |
in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes'] |
def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ ... |
def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identi... |
: <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> andr... |
% key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']] |
def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to... |
and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direc... |
for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()[... |
def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message'] |
def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports |
def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma sep... |
String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value ... |
def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports |
def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * from... |
Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stder... |
= {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message'] |
def encry_decry_cascade(data, masterkey, bool_encry, assoc_data): """ When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 by... |
will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data. """ engine1 = botan.cipher(algo="Serpent/GCM", encrypt=bool_encry) engine2 = botan.cipher(algo="AES-256/GCM", encrypt=bool_encry) engine3 = b... |
generate_nonce_timestamp() nonce2 = generate_nonce_timestamp() nonce3 = generate_nonce_timestamp() engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) cipher1 = engine1.finish(data) cipher2 = engine2.finish(cipher1) cipher3 = engine3.finish(cipher2) return nonce1 + nonce2 + nonce3 + ciph... |
corrupted data") decrypteddata2 = engine2.finish(decrypteddata1) if decrypteddata2 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata3 = engine1.finish(decrypteddata2) if decrypteddata3 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") else:... |
def register(self, request_class: Request, handler_factory: Callable[[], Handler]) -> None: """ Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispatch to :return: """ key = request... |
this request has already been registered") elif is_event and is_present: self._registry[key].append(handler_factory) elif is_command or is_event: self._registry[key] = [handler_factory] |
def lookup(self, request: Request) -> List[Callable[[], Handler]]: """ Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return: """ key = request.__class__.__name__ if key not in self._registry: if request.... |
type: Callable[[] Handler] return self._registry[key] |
def register(self, request_class: Request, mapper_func: Callable[[Request], BrightsideMessage]) -> None: """Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type """ key = request_class.__name__ if k... |
one") |
def lookup(self, request_class: Request) -> Callable[[Request], BrightsideMessage]: """ Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_class: :return: """ key = request_... |
return self._registry[key] |
def instance_of(*args): """ This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument ... |
function to check that `instance_of(x, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode value, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if isinstance(value, ref_type): return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type) else: # ref_type... |
match = True break if match: return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): # ref_type is a single type def instance_of_ref(x): if ... |
# test against each of the provided types for ref in ref_type: if isinstance(x, ref): match = True break if match: return True else: raise HasWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') instance_of_ref.__name__ = 'instance_of_{}'.format(ref_type) return insta... |
def subclass_of(*args): """ This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (... |
function to check that `subclass_of(c, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode typ, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if issubclass(typ, ref_type): return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type) else: # ref_type is a s... |
match = True break if match: return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): def subclass_of_ref(x): if issubclass(x, ref_type): return ... |
provided types for ref in ref_type: if issubclass(x, ref): match = True break if match: return True else: raise IsWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') subclass_of_ref.__name__ = 'subclass_of_{}'.format(ref_type) return subclass_of_ref else: raise TypeEr... |
def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'. """ director... |
hash. if method and key: key = key[1:] filename = '{}-{}.pickle'.format(basename, hash(key)) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): with open(filepath, 'rb') as handle: return pickle.load(handle) result = func(*args, **kwargs) with open(filepath, 'wb') as handle: pickle.dump(result, h... |
def download(url, directory, filename=None): """ Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. """ if not filename: _, filename = os.path.split(url) directory = o... |
with urlopen(url) as response, open(filepath, 'wb') as file_: shutil.copyfileobj(response, file_) return filepath |
def ensure_directory(directory): """ Create the directories along the provided directory path that do not exist. """ directory = os.path.expanduser(directory) try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise e |
def _process_validation_function_s(validation_func, # type: ValidationFuncs auto_and_wrapper=True # type: bool ): # type: (...) -> Union[Callable, List[Callable]] """ This function handles the various ways that users may enter 'validation functions', so as to output a single callable method. Setting "auto_and_wrapper" ... |
must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be... |
this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, h... |
are supported and indicate an implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param auto_and_wrapper: if True (default), this function returns a... |
is empty or none if validation_func is None: raise ValueError('mandatory validation_func is None') elif not isinstance(validation_func, list): # so not use list() because we do not want to convert tuples here. validation_func = [validation_func] elif len(validation_func) == 0: raise ValueError('provided validation_func... |
automatically convert to a function # note: we have to do it before anything else (such as .index) otherwise we may get failures v = as_function(v) if isinstance(v, tuple): # convert all the tuples to failure raisers if len(v) == 2: if isinstance(v[1], str): final_list.append(_failure_raiser(v[0], help_msg=v[1])) elif ... |
syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) elif callable(v): # use the validator direct... |
syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) # return what is required: if auto_and_wrapper: # a single callable doing the 'and' return and_(*final_list) else: # or the list (typically for use inside or_(), xor_()...) return final_list |
def and_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_` is performed if you provide a... |
...) :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an ... |
:return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case: no wrapper else: def and_v_(x): for validator in validation_func: try: res = validator(x) except Exception as e... |
return and_v_ |
def not_(validation_func, # type: ValidationFuncs catch_all=False # type: bool ): # type: (...) -> Callable """ Generates the inverse of the provided validation functions: when the validator returns `False` or raises a `Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure. By default, exce... |
you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. A callable, a tuple(cal... |
main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned in... |
try: res = validation_func(x) if not result_is_success(res): # inverse the result return True except Failure: return True # caught failure: always return True except Exception as e: if not catch_all: raise e else: return True # caught exception in 'catch_all' mode: return True # if we're here that's a failure raise Did... |
def or_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details about al... |
use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expression... |
for single validator case else: def or_v_(x): for validator in validation_func: # noinspection PyBroadException try: res = validator(x) if result_is_success(res): # we can return : one validator was happy return True except Exception: # catch all silently pass # no validator accepted: gather details and raise raise All... |
def xor_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised, toget... |
functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda... |
# simplification for single validation function case else: def xor_v_(x): ok_validators = [] for val_func in validation_func: # noinspection PyBroadException try: res = val_func(x) if result_is_success(res): ok_validators.append(val_func) except Exception: pass # return if were happy or not if len(ok_validators) == 1: ... |
# no validation function happy, fail raise AllValidatorsFailed(validation_func, x) xor_v_.__name__ = 'xor({})'.format(get_callable_names(validation_func)) return xor_v_ |
def not_all(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ An alias for not_(and_(validators)). :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list o... |
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.