sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def gt(min_value, # type: Any strict=False # type: bool ): """ 'Greater than' validation_function generator. Returns a validation_function to check that x >= min_value (strict=False, default) or x > min_value (strict=True) :param min_value: minimum value for x :param strict: Boole...
'Greater than' validation_function generator. Returns a validation_function to check that x >= min_value (strict=False, default) or x > min_value (strict=True) :param min_value: minimum value for x :param strict: Boolean flag to switch between x >= min_value (strict=False) and x > min_value (strict=True) ...
entailment
def lt(max_value, # type: Any strict=False # type: bool ): """ 'Lesser than' validation_function generator. Returns a validation_function to check that x <= max_value (strict=False, default) or x < max_value (strict=True) :param max_value: maximum value for x :param strict: Boolea...
'Lesser than' validation_function generator. Returns a validation_function to check that x <= max_value (strict=False, default) or x < max_value (strict=True) :param max_value: maximum value for x :param strict: Boolean flag to switch between x <= max_value (strict=False) and x < max_value (strict=True) ...
entailment
def between(min_val, # type: Any max_val, # type: Any open_left=False, # type: bool open_right=False # type: bool ): """ 'Is between' validation_function generator. Returns a validation_function to check that min_val <= x <= max_val (defaul...
'Is between' validation_function generator. Returns a validation_function to check that min_val <= x <= max_val (default). open_right and open_left flags allow to transform each side into strict mode. For example setting open_left=True will enforce min_val < x <= max_val :param min_val: minimum value for x...
entailment
def _sub_process_main(started_event: Event, channel_name: str, connection: Connection, consumer_configuration: BrightsideConsumerConfiguration, consumer_factory: Callable[[Connection, BrightsideConsumerConfiguration, logging.Logger]...
This is the main method for the sub=process, everything we need to create the message pump and channel it needs to be passed in as parameters that can be pickled as when we run they will be serialized into this process. The data should be value types, not reference types as we will receive a copy of the origina...
entailment
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
entailment
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ app_conf = dci_config.generate_conf() connectable = dci_config.get_engine(app_conf) with connectable.connect() as connection: ...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
entailment
def reject(): """Sends a 401 reject response that enables basic auth.""" auth_message = ('Could not verify your access level for that URL.' 'Please login with proper credentials.') auth_message = json.dumps({'_status': 'Unauthorized', 'message': auth_messa...
Sends a 401 reject response that enables basic auth.
entailment
def modify(self, **kwargs): """Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without...
Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In ...
entailment
def _establish_connection(self, conn: BrokerConnection) -> None: """ We don't use a pool here. We only have one consumer connection per process, so we get no value from a pool, and we want to use a heartbeat to keep the consumer collection alive, which does not work with a pool :...
We don't use a pool here. We only have one consumer connection per process, so we get no value from a pool, and we want to use a heartbeat to keep the consumer collection alive, which does not work with a pool :return: the connection to the transport
entailment
def run_heartbeat_continuously(self) -> threading.Event: """ For a long runing handler, there is a danger that we do not send a heartbeat message or activity on the connection whilst we are running the handler. With a default heartbeat of 30s, for example, there is a risk that a handler ...
For a long runing handler, there is a danger that we do not send a heartbeat message or activity on the connection whilst we are running the handler. With a default heartbeat of 30s, for example, there is a risk that a handler which takes more than 15s will fail to send the heartbeat in time and then th...
entailment
def _check(user, topic): """If the topic has it's export_control set to True then all the teams under the product team can access to the topic's resources. :param user: :param topic: :return: True if check is ok, False otherwise """ # if export_control then check the team is associated to t...
If the topic has it's export_control set to True then all the teams under the product team can access to the topic's resources. :param user: :param topic: :return: True if check is ok, False otherwise
entailment
def get_stream_or_content_from_request(request): """Ensure the proper content is uploaded. Stream might be already consumed by authentication process. Hence flask.request.stream might not be readable and return improper value. This methods checks if the stream has already been consumed and if so r...
Ensure the proper content is uploaded. Stream might be already consumed by authentication process. Hence flask.request.stream might not be readable and return improper value. This methods checks if the stream has already been consumed and if so retrieve the data from flask.request.data where it has be...
entailment
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 d...
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 name '_' so it can b...
entailment
def _is_ns_in_ancestor(self, node, name, value): """ Return True if the given namespace name/value is defined in an ancestor of the given node, meaning that the given node need not have its own attributes to apply that namespacing. """ curr_node = self.get_node_parent(nod...
Return True if the given namespace name/value is defined in an ancestor of the given node, meaning that the given node need not have its own attributes to apply that namespacing.
entailment
def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.sco...
Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__ratin...
entailment
def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_f...
Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating,...
entailment
def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as...
Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public...
entailment
def gen_etag(): """Generate random etag based on MD5.""" my_salt = gen_uuid() if six.PY2: my_salt = my_salt.decode('utf-8') elif six.PY3: my_salt = my_salt.encode('utf-8') md5 = hashlib.md5() md5.update(my_salt) return md5.hexdigest()
Generate random etag based on MD5.
entailment
def delete(self): """Delete this email report""" response = self.pingdom.request('DELETE', 'reports.shared/%s' % self.id) return response.json()['message']
Delete this email report
entailment
def is_multiple_of(ref): """ Validates that x is a multiple of the reference (`x % ref == 0`) """ def is_multiple_of_ref(x): if x % ref == 0: return True else: raise IsNotMultipleOf(wrong_value=x, ref=ref) # raise Failure('x % {ref} == 0 does not hold for x={v...
Validates that x is a multiple of the reference (`x % ref == 0`)
entailment
def get_all_components(user, topic_id): """Get all components of a topic.""" args = schemas.args(flask.request.args.to_dict()) query = v1_utils.QueryBuilder(_TABLE, args, _C_COLUMNS) query.add_extra_condition(sql.and_( _TABLE.c.topic_id == topic_id, _TABLE.c.state != 'archived')) ...
Get all components of a topic.
entailment
def get_component_types_from_topic(topic_id, db_conn=None): """Returns the component types of a topic.""" db_conn = db_conn or flask.g.db_conn query = sql.select([models.TOPICS]).\ where(models.TOPICS.c.id == topic_id) topic = db_conn.execute(query).fetchone() topic = dict(topic) return ...
Returns the component types of a topic.
entailment
def get_component_types(topic_id, remoteci_id, db_conn=None): """Returns either the topic component types or the rconfigration's component types.""" db_conn = db_conn or flask.g.db_conn rconfiguration = remotecis.get_remoteci_configuration(topic_id, ...
Returns either the topic component types or the rconfigration's component types.
entailment
def get_last_components_by_type(component_types, topic_id, db_conn=None): """For each component type of a topic, get the last one.""" db_conn = db_conn or flask.g.db_conn schedule_components_ids = [] for ct in component_types: where_clause = sql.and_(models.COMPONENTS.c.type == ct, ...
For each component type of a topic, get the last one.
entailment
def verify_and_get_components_ids(topic_id, components_ids, component_types, db_conn=None): """Process some verifications of the provided components ids.""" db_conn = db_conn or flask.g.db_conn if len(components_ids) != len(component_types): msg = 'The number of com...
Process some verifications of the provided components ids.
entailment
def retrieve_tags_from_component(user, c_id): """Retrieve all tags attached to a component.""" JCT = models.JOIN_COMPONENTS_TAGS query = (sql.select([models.TAGS]) .select_from(JCT.join(models.TAGS)) .where(JCT.c.component_id == c_id)) rows = flask.g.db_conn.execute(query) ...
Retrieve all tags attached to a component.
entailment
def add_tag_for_component(user, c_id): """Add a tag on a specific component.""" v1_utils.verify_existence_and_get(c_id, _TABLE) values = { 'component_id': c_id } component_tagged = tags.add_tag_to_resource(values, models.JOIN_COMPONENTS_TAGS...
Add a tag on a specific component.
entailment
def delete_tag_for_component(user, c_id, tag_id): """Delete a tag on a specific component.""" # Todo : check c_id and tag_id exist in db query = _TABLE_TAGS.delete().where(_TABLE_TAGS.c.tag_id == tag_id and _TABLE_TAGS.c.component_id == c_id) try: flask.g...
Delete a tag on a specific component.
entailment
def should_be_hidden_as_cause(exc): """ Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error """ # reduced traceback in case of HasWrongType (instance_of checks) from valid8.validation_lib.types import HasWrongType, IsWrongType return isinstance(exc, (H...
Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error
entailment
def is_error_of_type(exc, ref_type): """ Helper function to determine if some exception is of some type, by also looking at its declared __cause__ :param exc: :param ref_type: :return: """ if isinstance(exc, ref_type): return True elif hasattr(exc, '__cause__') and exc.__cause__...
Helper function to determine if some exception is of some type, by also looking at its declared __cause__ :param exc: :param ref_type: :return:
entailment
def _failure_raiser(validation_callable, # type: Callable failure_type=None, # type: Type[WrappingFailure] help_msg=None, # type: str **kw_context_args): # type: (...) -> Callable """ Wraps the provided validation function so that in ...
Wraps the provided validation function so that in case of failure it raises the given failure_type or a WrappingFailure with the given help message. :param validation_callable: :param failure_type: an optional subclass of `WrappingFailure` that should be raised in case of failure, instead of `WrappingF...
entailment
def _none_accepter(validation_callable # type: Callable ): # type: (...) -> Callable """ Wraps the given validation callable to accept None values silently. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will return...
Wraps the given validation callable to accept None values silently. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will return True. When any other value is received the validation_callable is called as usual. Note: the created wrapper ha...
entailment
def _none_rejecter(validation_callable # type: Callable ): # type: (...) -> Callable """ Wraps the given validation callable to reject None values. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will raise a Wrappin...
Wraps the given validation callable to reject None values. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will raise a WrappingFailure. When any other value is received the validation_callable is called as usual. :param validation_callabl...
entailment
def get_help_msg(self, dotspace_ending=False, # type: bool **kwargs): # type: (...) -> str """ The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg' attribute, whether it is defined at the in...
The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg' attribute, whether it is defined at the instance level or at the class level. The help message is formatted according to help_msg.format(**kwargs), and may be terminated with a dot and a ...
entailment
def get_details(self): """ The function called to get the details appended to the help message when self.append_details is True """ strval = str(self.wrong_value) if len(strval) > self.__max_str_length_displayed__: return '(Actual value is too big to be printed in this message)' ...
The function called to get the details appended to the help message when self.append_details is True
entailment
def get_details(self): """ Overrides the method in Failure so as to add a few details about the wrapped function and outcome """ if isinstance(self.validation_outcome, Exception): if isinstance(self.validation_outcome, Failure): # do not say again what was the value, it is a...
Overrides the method in Failure so as to add a few details about the wrapped function and outcome
entailment
def get_context_for_help_msgs(self, context_dict): """ We override this method from HelpMsgMixIn to replace wrapped_func with its name """ context_dict = copy(context_dict) context_dict['wrapped_func'] = get_callable_name(context_dict['wrapped_func']) return context_dict
We override this method from HelpMsgMixIn to replace wrapped_func with its name
entailment
def validate_field(cls, field_name, *validation_func, # type: ValidationFuncs **kwargs): # type: (...) -> Callable """ A class decorator. It goes through all class variables and for all of those that are descriptors with a __set__, it wraps the d...
A class decorator. It goes through all class variables and for all of those that are descriptors with a __set__, it wraps the descriptors' setter function with a `validate_arg` annotation :param field_name: :param validation_func: :param help_msg: :param error_type: :param none_policy: :par...
entailment
def validate_io(f=DECORATED, none_policy=None, # type: int _out_=None, # type: ValidationFuncs **kw_validation_funcs # type: ValidationFuncs ): """ A function decorator to add input validation prior to the function execution. It sh...
A function decorator to add input validation prior to the function execution. It should be called with named arguments: for each function arg name, provide a single validation function or a list of validation functions to apply. If validation fails, it will raise an InputValidationError with details about the f...
entailment
def validate_arg(f, arg_name, *validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ A decorator to apply function input validation for the given argument name, with the provided base validation function(s)...
A decorator to apply function input validation for the given argument name, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked on top of each other (no external decorator in the middle) :param arg_name: :param validation_fu...
entailment
def validate_out(*validation_func, # type: ValidationFuncs **kwargs): # type: (...) -> Callable """ A decorator to apply function output validation to this function's output, with the provided base validation function(s). You may use several such decorators on a given function as long ...
A decorator to apply function output validation to this function's output, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked on top of each other (no external decorator in the middle) :param validation_func: the base validatio...
entailment
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 th...
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 name of the argument to validate or _OUT_KEY for output validation :param validation_func: the validation function or list of v...
entailment
def decorate_several_with_validation(func, _out_=None, # type: ValidationFuncs none_policy=None, # type: int **validation_funcs # type: ValidationFuncs ): # ...
This method is equivalent to applying `decorate_with_validation` once for each of the provided arguments of the function `func` as well as output `_out_`. validation_funcs keyword arguments are validation functions for each arg name. Note that this method is less flexible than decorate_with_validation sinc...
entailment
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`...
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 func: :param arg_name: the name of the argument to validate or _OUT_KEY for output validation :param validation_func: the va...
entailment
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 NoneP...
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:
entailment
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. ...
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 function to decorate. It might already be decorated, this method will check it and wont create another wra...
entailment
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_wrappe...
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 validator. The signature of this function is hardcoded to correspond to `apply_on_each_func_args`'s behaviour and should therefore not be changed. ...
entailment
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(), ...
Overrides the base behaviour defined in ValidationError in order to add details about the function. :return:
entailment
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(), ...
Overrides the base behaviour defined in ValidationError in order to add details about the class field. :return:
entailment
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 ...
Generate unique nonce with counter, uuid and rng.
entailment
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 = itert...
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.
entailment
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 ...
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.
entailment
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': dat...
Create a new job in the same topic as the job_id provided and associate the latest components of this topic.
entailment
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(), ...
Create a new job in the 'next topic' of the topic of the provided job_id.
entailment
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_u...
Get all jobs. If topic_id is not None, then return all the jobs with a topic pointed by topic_id.
entailment
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...
Update a job
entailment
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.selec...
Get all results from job.
entailment
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([mod...
Retrieve all tags attached to a job.
entailment
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...
Add a tag to a job.
entailment
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) ...
Delete a tag from a job.
entailment
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 inte...
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.
entailment
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 isinstanc...
Return True if the given node is an ElementTree Element, a fact that can be tricky to determine if the cElementTree implementation is used.
entailment
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 d...
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 name '_' so it can b...
entailment
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, ...
List the entries to be purged from the database.
entailment
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.exec...
Remove the entries to be purged from the database.
entailment
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...
Refresh the resource API Secret.
entailment
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': ma...
Generate a package.json file.
entailment
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 ...
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 -- O...
entailment
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']
Update check details, returns dictionary of details
entailment
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 ...
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 cr...
entailment
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...
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 ti...
entailment
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.i...
Get a list of probes that performed tests for a specified check during a specified period.
entailment
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']
Activate public report for this check. Returns status message
entailment
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']
Deactivate public report for this check. Returns status message
entailment
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): ...
Extract the dependencies from the bundle and its sub-bundles.
entailment
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: ...
Make a semantic version from Python PEP440 version. Semantic versions does not handle post-releases.
entailment
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 ...
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 options available for ...
entailment
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: { o...
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 i...
entailment
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_si...
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
entailment
def offer_random(pool, answer, rationale, student_id, options): """ The random selection algorithm. The same as simple algorithm """ offer_simple(pool, answer, rationale, student_id, options)
The random selection algorithm. The same as simple algorithm
entailment
def validate_seeded_answers_simple(answers, options, algo): """ This validator checks if the answers includes all possible options Args: answers (str): the answers to be checked options (dict): all options that should exist in the answers algo (str): selection algorithm Returns...
This validator checks if the answers includes all possible options Args: answers (str): the answers to be checked options (dict): all options that should exist in the answers algo (str): selection algorithm Returns: None if everything is good. Otherwise, the missing option erro...
entailment
def validate_seeded_answers(answers, options, algo): """ Validate answers based on selection algorithm This is called when instructor setup the tool and providing seeded answers to the question. This function is trying to validate if instructor provided enough seeds for a give algorithm. e.g. we re...
Validate answers based on selection algorithm This is called when instructor setup the tool and providing seeded answers to the question. This function is trying to validate if instructor provided enough seeds for a give algorithm. e.g. we require 1 seed for each option in simple algorithm and at least 1 s...
entailment
def get_other_answers(pool, seeded_answers, get_student_item_dict, algo, options): """ Select other student's answers from answer pool or seeded answers based on the selection algorithm Args: pool (dict): answer pool, format: { option1_index: { studen...
Select other student's answers from answer pool or seeded answers based on the selection algorithm Args: pool (dict): answer pool, format: { option1_index: { student_id: { can store algorithm specific info here } }, option2_ind...
entailment
def get_other_answers_simple(pool, seeded_answers, get_student_item_dict, num_responses): """ Get answers from others with simple algorithm, which picks one answer for each option. Args: see `get_other_answers` num_responses (int): the number of responses to be returned. This value may not ...
Get answers from others with simple algorithm, which picks one answer for each option. Args: see `get_other_answers` num_responses (int): the number of responses to be returned. This value may not be respected if there is not enough answers to return Returns: dict: answers ...
entailment
def get_other_answers_random(pool, seeded_answers, get_student_item_dict, num_responses): """ Get answers from others with random algorithm, which randomly select answer from the pool. Student may get three answers for option 1 or one answer for option 1 and two answers for option 2. Args: see...
Get answers from others with random algorithm, which randomly select answer from the pool. Student may get three answers for option 1 or one answer for option 1 and two answers for option 2. Args: see `get_other_answers` num_responses (int): the number of responses to be returned. This value m...
entailment
def convert_seeded_answers(answers): """ Convert seeded answers into the format that can be merged into student answers. Args: answers (list): seeded answers Returns: dict: seeded answers with student answers format: { 0: { 'seeded0': 'ra...
Convert seeded answers into the format that can be merged into student answers. Args: answers (list): seeded answers Returns: dict: seeded answers with student answers format: { 0: { 'seeded0': 'rationaleA' } 1: { ...
entailment
def upgradeProcessor1to2(oldProcessor): """ Batch processors stopped polling at version 2, so they no longer needed the idleInterval attribute. They also gained a scheduled attribute which tracks their interaction with the scheduler. Since they stopped polling, we also set them up as a timed event...
Batch processors stopped polling at version 2, so they no longer needed the idleInterval attribute. They also gained a scheduled attribute which tracks their interaction with the scheduler. Since they stopped polling, we also set them up as a timed event here to make sure that they don't silently disa...
entailment
def processor(forType): """ Create an Axiom Item type which is suitable to use as a batch processor for the given Axiom Item type. Processors created this way depend on a L{iaxiom.IScheduler} powerup on the on which store they are installed. @type forType: L{item.MetaItem} @param forType: ...
Create an Axiom Item type which is suitable to use as a batch processor for the given Axiom Item type. Processors created this way depend on a L{iaxiom.IScheduler} powerup on the on which store they are installed. @type forType: L{item.MetaItem} @param forType: The Axiom Item type for which to cre...
entailment
def storeBatchServiceSpecialCase(st, pups): """ Adapt a L{Store} to L{IBatchService}. If C{st} is a substore, return a simple wrapper that delegates to the site store's L{IBatchService} powerup. Return C{None} if C{st} has no L{BatchProcessingControllerService}. """ if st.parent is not Non...
Adapt a L{Store} to L{IBatchService}. If C{st} is a substore, return a simple wrapper that delegates to the site store's L{IBatchService} powerup. Return C{None} if C{st} has no L{BatchProcessingControllerService}.
entailment
def mark(self): """ Mark the unit of work as failed in the database and update the listener so as to skip it next time. """ self.reliableListener.lastRun = extime.Time() BatchProcessingError( store=self.reliableListener.store, processor=self.reliab...
Mark the unit of work as failed in the database and update the listener so as to skip it next time.
entailment
def run(self): """ Try to run one unit of work through one listener. If there are more listeners or more work, reschedule this item to be run again in C{self.busyInterval} milliseconds, otherwise unschedule it. @rtype: L{extime.Time} or C{None} @return: The next time at...
Try to run one unit of work through one listener. If there are more listeners or more work, reschedule this item to be run again in C{self.busyInterval} milliseconds, otherwise unschedule it. @rtype: L{extime.Time} or C{None} @return: The next time at which to run this item, used by th...
entailment
def addReliableListener(self, listener, style=iaxiom.LOCAL): """ Add the given Item to the set which will be notified of Items available for processing. Note: Each Item is processed synchronously. Adding too many listeners to a single batch processor will cause the L{step} ...
Add the given Item to the set which will be notified of Items available for processing. Note: Each Item is processed synchronously. Adding too many listeners to a single batch processor will cause the L{step} method to block while it sends notification to each listener. @param...
entailment
def removeReliableListener(self, listener): """ Remove a previously added listener. """ self.store.query(_ReliableListener, attributes.AND(_ReliableListener.processor == self, _ReliableListener.listener == listener)).delete...
Remove a previously added listener.
entailment
def getReliableListeners(self): """ Return an iterable of the listeners which have been added to this batch processor. """ for rellist in self.store.query(_ReliableListener, _ReliableListener.processor == self): yield rellist.listener
Return an iterable of the listeners which have been added to this batch processor.
entailment
def getFailedItems(self): """ Return an iterable of two-tuples of listeners which raised an exception from C{processItem} and the item which was passed as the argument to that method. """ for failed in self.store.query(BatchProcessingError, BatchProcessingError.processor ...
Return an iterable of two-tuples of listeners which raised an exception from C{processItem} and the item which was passed as the argument to that method.
entailment
def itemAdded(self): """ Called to indicate that a new item of the type monitored by this batch processor is being added to the database. If this processor is not already scheduled to run, this will schedule it. It will also start the batch process if it is not yet running and ...
Called to indicate that a new item of the type monitored by this batch processor is being added to the database. If this processor is not already scheduled to run, this will schedule it. It will also start the batch process if it is not yet running and there are any registered remote l...
entailment
def call(self, itemMethod): """ Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked. """ item = itemMethod.im_self method = itemMethod.im_func.func_name return self.batchController.getProcess().a...
Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked.
entailment
def processWhileRunning(self): """ Run tasks until stopService is called. """ work = self.step() for result, more in work: yield result if not self.running: break if more: delay = 0.1 else: ...
Run tasks until stopService is called.
entailment
def getcols(sheetMatch=None,colMatch="Decay"): """find every column in every sheet and put it in a new sheet or book.""" book=BOOK() if sheetMatch is None: matchingSheets=book.sheetNames print('all %d sheets selected '%(len(matchingSheets))) else: matchingSheets=[x for x in book....
find every column in every sheet and put it in a new sheet or book.
entailment
def upgradeStore(self, store): """ Recursively upgrade C{store}. """ self.upgradeEverything(store) upgradeExplicitOid(store) for substore in store.query(SubStore): print 'Upgrading: {!r}'.format(substore) self.upgradeStore(substore.open())
Recursively upgrade C{store}.
entailment