code
stringlengths
1
18.2k
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 implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io...
See `NoneArgPolicy` for the various possibilities. Default is `NoneArgPolicy.ACCEPT_IF_OPTIONAl_ELSE_VALIDATE`. :return: a function decorator, able to transform a function into a function that will perform input validation before executing the function's code everytime it is executed. """ def decorate(f): return decora...
def decorate_cls_with_validation(cls, field_name, # type: str *validation_func, # type: ValidationFuncs **kwargs): # type: (...) -> Type[Any] """ This method is equivalent to decorating a class with the `@validate_field` decorator but can be used a posteriori. :param cls: the class to decorate :param field_name: the na...
functions to use. A validation function may be 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...
raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param none_policy: describes how None values should be handled. See `NoneArgPolicy` for the various possibi...
that may be also used to format the help message :return: the decorated function, that will perform input validation (using `_assert_input_is_valid`) before executing the function's code everytime it is executed. """ error_type, help_msg, none_policy = pop_kwargs(kwargs, [('error_type', None), ('help_msg', None), ('non...
a class') if hasattr(cls, field_name): # ** A class field with that name exist. Is it a descriptor ? var = cls.__dict__[field_name] # note: we cannot use getattr here if hasattr(var, '__set__') and callable(var.__set__): if isinstance(var, property): # *** OLD WAY which was losing type hints and default values (see var...
can not have properties # so we have to create a wrapper (sic) before sending it to the main wrapping function # def func(inst, value): # var.__set__(inst, value) # *** NEW WAY : more elegant, use directly the setter provided by the user *** func = var.fset nb_args = 2 elif ismethod(var.__set__): # bound method: normal...
var.__set__.__func__ nb_args = 3 else: # strange.. but lets try to continue func = var.__set__ nb_args = 3 # retrieve target function signature, check it and retrieve the 3d param # since signature is "def __set__(self, obj, val)" func_sig = signature(func) if len(func_sig.parameters) != nb_args: raise ValueError("Clas...
with the correct number of parameters, so it is not possible to add " "validation to it. See https://docs.python.org/3.6/howto/descriptor.html". format(field_name, cls.__name__)) # extract the correct name descriptor_arg_name = list(func_sig.parameters.items())[-1][0] # do the same than in decorate_with_validation but ...
NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE new_validator = _create_function_validator(func, func_sig, descriptor_arg_name, *validation_func, none_policy=none_policy, error_type=error_type, help_msg=help_msg, validated_class=cls, validated_class_field_name=field_name, **kw_context_args) # -- create the new setter with ...
(hasattr(var, '__delete__') and callable(var.__delete__)): # this is a descriptor but it does not have any setter method: impossible to validate raise ValueError("Class field '{}' is a valid class descriptor for class '{}' but it does not implement " "__set__ so it is not possible to add validation to it. See " "https:...
'{}.{}' is not a valid class descriptor, see " "https://docs.python.org/3.6/howto/descriptor.html".format(cls.__name__, field_name)) else: # ** No class field with that name exist # ? check for attrs ? > no specific need anymore, this is the same than annotating the constructor # if hasattr(cls, '__attrs_attrs__'): thi...
< (3, 0): try: # python 2 - we have to access the inner `im_func` init_func = cls.__init__.im_func except AttributeError: pass cls.__init__ = decorate_with_validation(init_func, field_name, *validation_func, help_msg=help_msg, _constructor_of_cls_=cls, error_type=error_type, none_policy=none_policy, **kw_context_args) ...
exception: field '{}' can not be found in class '{}', and it " "is also not an input argument of the __init__ method.".format(field_name, cls.__name__)) return cls
def decorate_several_with_validation(func, _out_=None, # type: ValidationFuncs none_policy=None, # type: int **validation_funcs # type: ValidationFuncs ): # type: (...) -> Callable """ This method is equivalent to applying `decorate_with_validation` once for each of the provided arguments of the function `func` as well...
* it does not allow to associate a custom error message or error type with each validation. * the none_policy is the same for all inputs and outputs :param func: :param _out_: :param validation_funcs: :param none_policy: :return: a function decorated with validation for all of the listed arguments and output if provide...
None: func = decorate_with_validation(func, _OUT_KEY, _out_, none_policy=none_policy) # add validation for each of the listed arguments for att_name, att_validation_funcs in validation_funcs.items(): func = decorate_with_validation(func, att_name, att_validation_funcs, none_policy=none_policy) return func
def decorate_with_validation(func, arg_name, # type: str *validation_func, # type: ValidationFuncs **kwargs): # type: (...) -> Callable """ This method is the inner method used in `@validate_io`, `@validate_arg` and `@validate_out`. It can be used if you with to perform decoration manually without a decorator. :param f...
or list of validation functions to use. A validation function may be 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_...
subclass of ValidationError to raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param none_policy: describes how None values should be handled. See `NoneArg...
in the exception, and that may be also used to format the help message :return: the decorated function, that will perform input validation (using `_assert_input_is_valid`) before executing the function's code everytime it is executed. """ error_type, help_msg, none_policy, _constructor_of_cls_ = pop_kwargs(kwargs, [('e...
= none_policy or NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE # retrieve target function signature func_sig = signature(func) # create the new validator if _constructor_of_cls_ is None: # standard method: input validator new_validator = _create_function_validator(func, func_sig, arg_name, *validation_func, none_policy=n...
decorate_with_validators(func, func_signature=func_sig, **{arg_name: new_validator})
def _get_final_none_policy_for_validator(is_nonable, # type: bool none_policy # type: NoneArgPolicy ): """ Depending on none_policy and of the fact that the target parameter is nonable or not, returns a corresponding NonePolicy :param is_nonable: :param none_policy: :return: """ if none_policy in {NonePolicy.VALIDATE, ...
is_nonable else NonePolicy.FAIL else: raise ValueError('Invalid none policy: ' + str(none_policy)) return none_policy_to_use
def decorate_with_validators(func, func_signature=None, # type: Signature **validators # type: Validator ): """ Utility method to decorate the provided function with the provided input and output Validator objects. Since this method takes Validator objects as argument, it is for advanced users. :param func: the functio...
simply adding the validators to the existing wrapper :param func_signature: the function's signature if it is already known (internal calls), otherwise it will be found again by inspection :param validators: a dictionary of arg_name (or _out_) => Validator or list of Validator :return: """ # first turn the dictionary v...
[validator] if hasattr(func, '__wrapped__') and hasattr(func.__wrapped__, '__validators__'): # ---- This function is already wrapped by our validation wrapper ---- # Update the dictionary of validators with the new validator(s) for arg_name, validator in validators.items(): for v in validator: if arg_name in func.__wra...
# ---- This function is not yet wrapped by our validator. ---- # Store the dictionary of validators as an attribute of the function if hasattr(func, '__validators__'): raise ValueError('Function ' + str(func) + ' already has a defined __validators__ attribute, valid8 ' 'decorators can not be applied on it') else: try: ...
to function '%s'" % func) # either reuse or recompute function signature func_signature = func_signature or signature(func) # create a wrapper with the same signature @wraps(func) def validating_wrapper(*args, **kwargs): """ This is the wrapper that will be called everytime the function is called """ # (a) Perform inpu...
execute the function as usual res = func(*args, **kwargs) # (c) validate output if needed if _OUT_KEY in func.__validators__: for validator in func.__validators__[_OUT_KEY]: validator.assert_valid(res) return res return validating_wrapper
def _assert_input_is_valid(input_value, # type: Any validators, # type: List[InputValidator] validated_func, # type: Callable input_name # type: str ): """ Called by the `validating_wrapper` in the first step (a) `apply_on_each_func_args` for each function input before executing the function. It simply delegates to the...
value to validate :param validator: the Validator object that will be applied on input_value_to_validate :param validated_func: the function for which this validation is performed. This is not used since the Validator knows it already, but we should not change the signature here. :param input_name: the name of the func...
def get_what_txt(self): """ Overrides the base behaviour defined in ValidationError in order to add details about the function. :return: """ return 'input [{var}] for function [{func}]'.format(var=self.get_variable_str(), func=self.validator.get_validated_func_display_name())
def get_what_txt(self): """ Overrides the base behaviour defined in ValidationError in order to add details about the class field. :return: """ return 'field [{field}] for class [{clazz}]'.format(field=self.get_variable_str(), clazz=self.validator.get_validated_class_display_name())
def generate_nonce_timestamp(): """ Generate unique nonce with counter, uuid and rng.""" global count rng = botan.rng().get(30) uuid4 = uuid.uuid4().bytes # 16 byte tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng nonce = tmpnonce[:41] # 41 byte (328 bit) count += 1 return nonce
def dict_merge(*dict_list): """recursively merges dict's. not just simple a['key'] = b['key'], if both a and bhave a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. """ result = collections.defaultdict(dict) dicts_items = itertools.chain(*[six.iterite...
dict): result[key] = dict_merge(src, value) elif isinstance(src, dict) or isinstance(src, six.text_type): result[key] = value elif hasattr(src, "__iter__") and hasattr(value, "__iter__"): result[key] += value else: result[key] = value return dict(result)
def schedule_jobs(user): """Dispatch jobs to remotecis. The remoteci can use this method to request a new job. Before a job is dispatched, the server will flag as 'killed' all the running jobs that were associated with the remoteci. This is because they will never be finished. """ values = schemas.job_schedule.post(fla...
flask.request.environ.get('HTTP_USER_AGENT'), 'client_version': flask.request.environ.get( 'HTTP_CLIENT_VERSION' ), }) topic_id = values.pop('topic_id') topic_id_secondary = values.pop('topic_id_secondary') components_ids = values.pop('components_ids') # check remoteci remoteci = v1_utils.verify_existence_and_get(user....
check secondary topic if topic_id_secondary: topic_secondary = v1_utils.verify_existence_and_get( topic_id_secondary, models.TOPICS) if topic_secondary['state'] != 'active': msg = 'Topic %s:%s not active.' % (topic_id_secondary, topic['name']) raise dci_exc.DCIException(msg, status_code=412) v1_utils.verify_team_in_top...
values['etag']}, content_type='application/json')
def create_new_update_job_from_an_existing_job(user, job_id): """Create a new job in the same topic as the job_id provided and associate the latest components of this topic.""" values = { 'id': utils.gen_uuid(), 'created_at': datetime.datetime.utcnow().isoformat(), 'updated_at': datetime.datetime.utcnow().isoformat(), ...
the associated topic topic_id = str(original_job['topic_id']) v1_utils.verify_existence_and_get(topic_id, models.TOPICS) values.update({ 'user_agent': flask.request.environ.get('HTTP_USER_AGENT'), 'client_version': flask.request.environ.get( 'HTTP_CLIENT_VERSION' ), }) values = _build_job(topic_id, remoteci, [], values...
def create_new_upgrade_job_from_an_existing_job(user): """Create a new job in the 'next topic' of the topic of the provided job_id.""" values = schemas.job_upgrade.post(flask.request.json) values.update({ 'id': utils.gen_uuid(), 'created_at': datetime.datetime.utcnow().isoformat(), 'updated_at': datetime.datetime.utcno...
str(original_job['topic_id']) topic = v1_utils.verify_existence_and_get(topic_id, models.TOPICS) values.update({ 'user_agent': flask.request.environ.get('HTTP_USER_AGENT'), 'client_version': flask.request.environ.get( 'HTTP_CLIENT_VERSION' ), }) next_topic_id = topic['next_topic_id'] if not next_topic_id: raise dci_exc...
def get_all_jobs(user, topic_id=None): """Get all jobs. If topic_id is not None, then return all the jobs with a topic pointed by topic_id. """ # get the diverse parameters args = schemas.args(flask.request.args.to_dict()) # build the query thanks to the QueryBuilder class query = v1_utils.QueryBuilder(_TABLE, args, _J...
the team if user.is_not_super_admin() and not user.is_read_only_user(): query.add_extra_condition( sql.or_( _TABLE.c.team_id.in_(user.teams_ids), _TABLE.c.team_id.in_(user.child_teams_ids))) # # If topic_id not None, then filter by topic_id if topic_id is not None: query.add_extra_condition(_TABLE.c.topic_id == topic_i...
def update_job_by_id(user, job_id): """Update a job """ # get If-Match header if_match_etag = utils.check_and_get_etag(flask.request.headers) # get the diverse parameters values = schemas.job.put(flask.request.json) job = v1_utils.verify_existence_and_get(job_id, _TABLE) job = dict(job) if not user.is_in_team(job['team...
sql.and_(_TABLE.c.etag == if_match_etag, _TABLE.c.id == job_id) values['etag'] = utils.gen_etag() query = _TABLE.update().returning(*_TABLE.columns).\ where(where_clause).values(**values) result = flask.g.db_conn.execute(query) if not result.rowcount: raise dci_exc.DCIConflict('Job', job_id) return flask.Response( json...
def get_all_results_from_jobs(user, j_id): """Get all results from job. """ job = v1_utils.verify_existence_and_get(j_id, _TABLE) if not user.is_in_team(job['team_id']) and not user.is_read_only_user(): raise dci_exc.Unauthorized() # get testscases from tests_results query = sql.select([models.TESTS_RESULTS]). \ where(...
'success': test_result['success'], 'file_id': test_result['file_id']}) return flask.jsonify({'results': results, '_meta': {'count': len(results)}})
def get_tags_from_job(user, job_id): """Retrieve all tags attached to a job.""" job = v1_utils.verify_existence_and_get(job_id, _TABLE) if not user.is_in_team(job['team_id']) and not user.is_read_only_user(): raise dci_exc.Unauthorized() JTT = models.JOIN_JOBS_TAGS query = (sql.select([models.TAGS]) .select_from(JTT.jo...
def add_tag_to_job(user, job_id): """Add a tag to a job.""" job = v1_utils.verify_existence_and_get(job_id, _TABLE) if not user.is_in_team(job['team_id']): raise dci_exc.Unauthorized() values = { 'job_id': job_id } job_tagged = tags.add_tag_to_resource(values, models.JOIN_JOBS_TAGS) return flask.Response(json.dumps(job...
def delete_tag_from_job(user, job_id, tag_id): """Delete a tag from a job.""" _JJT = models.JOIN_JOBS_TAGS job = v1_utils.verify_existence_and_get(job_id, _TABLE) if not user.is_in_team(job['team_id']): raise dci_exc.Unauthorized() v1_utils.verify_existence_and_get(tag_id, models.TAGS) query = _JJT.delete().where(sql.a...
def _lookup_node_parent(self, node): """ Return the parent of the given node, based on an internal dictionary mapping of child nodes to the child's parent required since ElementTree doesn't make info about node ancestry/parentage available. """ # Basic caching of our internal ancestry dict to help performance if not no...
dict( (c, p) for p in self._impl_document.getiterator() for c in p) self.CACHED_ANCESTRY_DICT = ancestry_dict return self.CACHED_ANCESTRY_DICT[node]
def _is_node_an_element(self, node): """ Return True if the given node is an ElementTree Element, a fact that can be tricky to determine if the cElementTree implementation is used. """ # Try the simplest approach first, works for plain old ElementTree if isinstance(node, BaseET.Element): return True # For cElementTree ...
basestring): return True
def xpath_on_node(self, node, xpath, **kwargs): """ Return result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is defined, this is converted to the prefix na...
= {} if 'namespaces' in kwargs: namespaces_dict.update(kwargs['namespaces']) # Empty namespace prefix is not supported, convert to '_' prefix if None in namespaces_dict: default_ns_uri = namespaces_dict.pop(None) namespaces_dict['_'] = default_ns_uri # If no default namespace URI defined, use root's namespace (if any) ...
namespace if it's not already defined if not 'xmlns' in namespaces_dict: namespaces_dict['xmlns'] = nodes.Node.XMLNS_URI return node.findall(xpath, namespaces_dict)
def get_to_purge_archived_resources(user, table): """List the entries to be purged from the database. """ if user.is_not_super_admin(): raise dci_exc.Unauthorized() archived_resources = get_archived_resources(table) return flask.jsonify({table.name: archived_resources, '_meta': {'count': len(archived_resources)}})
def purge_archived_resources(user, table): """Remove the entries to be purged from the database. """ if user.is_not_super_admin(): raise dci_exc.Unauthorized() where_clause = sql.and_( table.c.state == 'archived' ) query = table.delete().where(where_clause) flask.g.db_conn.execute(query) return flask.Response(None, 204...
def refresh_api_secret(user, resource, table): """Refresh the resource API Secret. """ resource_name = table.name[0:-1] where_clause = sql.and_( table.c.etag == resource['etag'], table.c.id == resource['id'], ) values = { 'api_secret': signature.gen_secret(), 'etag': utils.gen_etag() } query = table.update().where(wher...
def npm(package_json, output_file, pinned_file): """Generate a package.json file.""" amd_build_deprecation_warning() try: version = get_distribution(current_app.name).version except DistributionNotFound: version = '' output = { 'name': current_app.name, 'version': make_semver(version) if version else version, 'dependen...
folder if output file is not specified if output_file is None: if not os.path.exists(current_app.static_folder): os.makedirs(current_app.static_folder) output_file = open( os.path.join(current_app.static_folder, 'package.json'), 'w') click.echo('Writing {0}'.format(output_file.name)) json.dump(output, output_file, inde...
def getAnalyses(self, **kwargs): """Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing. (Requires limit.) Type: Integer Default: 0 * tim...
value. Format is UNIX timestamp. Type: Integer Default: 0 * time_to -- Return only results with timestamp of first test less or equal to this value. Format is UNIX timestamp. Type: Integer Default: Current Time Returned structure: [ { 'id' : <Integer> Analysis id 'timefirsttest' : <Integer> Time of test that initiated ...
perfromed the error analysis }, ... ] """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('time_to'): kwargs['to'] = kwargs.get('time_to') del kwargs['time_to'] # Warn user about unhandled kwargs for key in kwa...
kwargs) return [PingdomAnalysis(self, x) for x in response.json()['analysis']]
def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check']
def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been created. General pa...
host Type: String * paused -- Check should be paused Type: Boolean * resolution -- Check resolution time (in minutes) Type: Integer [1, 5, 15, 30, 60] * contactids -- Comma separated list of contact IDs Type: String * sendtoemail -- Send alerts as email Type: Boolean * sendtosms -- Send alerts as SMS Type: Boolean * se...
Boolean * sendtoiphone -- Send alerts to iPhone Type: Boolean * sendtoandroid -- Send alerts to Android Type: Boolean * sendnotificationwhendown -- Send notification when check is down the given number of times Type: Integer * notifyagainevery -- Set how many results to wait for in between notices Type: Integer * notif...
old notifications instead of BeepManager Type: Boolean * probe_filters -- Can be one of region: NA, region: EU, region: APAC Type: String HTTP check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target server port Type: Integer * auth -- Username and password f...
-- Target site should contain this string. Cannot be combined with 'shouldnotcontain' Type: String * shouldnotcontain -- Target site should not contain this string. Cannot be combined with 'shouldcontain' Type: String * postdata -- Data that should be posted to the web page, for example submission data for a sign-up or...
a web browser would send it to the web server Type: String * requestheader<NAME> -- Custom HTTP header, replace <NAME> with desired header name. Header in form: Header:Value Type: String HTTPCustom check options: * url -- Target path on server Type: String * encryption -- Use SSL/TLS Type: Boolean * port -- Target serv...
HTTP authentication Example: user:password Type: String * additionalurls -- Colon-separated list of additonal URLS with hostname included Type: String TCP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String...
Type: String UDP check options: * port -- Target server port Type: Integer * stringtosend -- String to send Type: String * stringtoexpect -- String to expect in response Type: String SMTP check options: * port -- Target server port Type: Integer * auth -- Username and password for target SMTP authentication. Example: u...
Type: String * encryption -- Use connection encryption Type: Boolean POP3 check options: * port -- Target server port Type: Integer * stringtoexpect -- String to expect in response Type: String * encryption -- Use connection encryption Type: Boolean IMAP check options: * port -- Target server port Type: Integer * strin...
connection encryption Type: Boolean """ # Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', 'notifywhenbackup', 'created', 'type', 'hostname', 'status',...
'<PingdomCheck>.modify()\n') # If one of the legacy parameters is used, it is required to set the legacy flag. # https://github.com/KennethWilke/PingdomLib/issues/12 if any([k for k in kwargs if k in legacy_notification_parameters]): if "use_legacy_notifications" in kwargs and kwargs["use_legacy_notifications"] != True...
def averages(self, **kwargs): """Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX timestamp Type: Integer Default: Current time * probes -...
is a comma separated list of probe identifiers Type: String Default: All probes * includeuptime -- Include uptime information Type: Boolean Default: False * bycountry -- Split response times into country groups Type: Boolean Default: False * byprobe -- Split response times into probe groups Type: Boolean Default: False...
<Integer> End time of period 'avgresponse' : <Integer> Total average response time in milliseconds }, < More can be included with optional parameters > } """ # 'from' is a reserved word, use time_from instead if kwargs.get('time_from'): kwargs['from'] = kwargs.get('time_from') del kwargs['time_from'] if kwargs.get('tim...
'to', 'probes', 'includeuptime', 'bycountry', 'byprobe']: sys.stderr.write("'%s'" % key + ' is not a valid argument of' + '<PingdomCheck.averages()\n') response = self.pingdom.request('GET', 'summary.average/%s' % self.id, kwargs) return response.json()['summary']
def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period.""" args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes']
def publishPublicReport(self): """Activate public report for this check. Returns status message""" response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message']
def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
def extract_deps(bundles, log=None): """Extract the dependencies from the bundle and its sub-bundles.""" def _flatten(bundle): deps = [] if hasattr(bundle, 'npm'): deps.append(bundle.npm) for content in bundle.contents: if isinstance(content, BundleBase): deps.extend(_flatten(content)) return deps flatten_deps = [] for...
True) if log and len(versions) > 1: log('Warn: {0} version {1} resolved to: {2}'.format( repr(package), versions, repr(deps[package]) )) return deps
def make_semver(version_str): """Make a semantic version from Python PEP440 version. Semantic versions does not handle post-releases. """ v = parse_version(version_str) major = v._version.release[0] try: minor = v._version.release[1] except IndexError: minor = 0 try: patch = v._version.release[2] except IndexError: pat...
version = '{0}.{1}.{2}'.format(major, minor, patch) if prerelease: version += '-{0}'.format(prerelease) if v.local: version += '+{0}'.format(v.local) return version
def get_max_size(pool, num_option, item_length): """ Calculate the max number of item that an option can stored in the pool at give time. This is to limit the pool size to POOL_SIZE Args: option_index (int): the index of the option to calculate the size for pool (dict): answer pool num_option (int): total number of opt...
item Returns: int: the max number of items that `option_index` can have """ max_items = POOL_SIZE / item_length # existing items plus the reserved for min size. If there is an option has 1 item, POOL_OPTION_MIN_SIZE - 1 space # is reserved. existing = POOL_OPTION_MIN_SIZE * num_option + sum([max(0, len(pool.get(i, {}))...
def offer_answer(pool, answer, rationale, student_id, algo, options): """ submit a student answer to the answer pool The answer maybe selected to stay in the pool depending on the selection algorithm Args: pool (dict): answer pool Answer pool format: { option1_index: { 'student_id': { can store algorithm specific info ...
rationale text student_id (str): student identifier algo (str): the selection algorithm options (dict): the options available in the question Raises: UnknownChooseAnswerAlgorithm: when we don't know the algorithm """ if algo['name'] == 'simple': offer_simple(pool, answer, rationale, student_id, options) elif algo['name...
def offer_simple(pool, answer, rationale, student_id, options): """ The simple selection algorithm. This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches the limit """ existing = pool.setdefault(answer, {}) if len(existing) >= get_max_size(pool, len(options), POOL_I...