text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _did_receive_response(self, response): """ Called when a response is received """
try: data = response.json() except: data = None self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason) level = logging.WARNING if self._response.status_code >= 300 else logging.DEBUG ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _did_timeout(self): """ Called when a resquest has timeout """
bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout)) self._has_timeouted = True if self.async: self._callback(self) else: return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_request(self, session=None): """ Make a synchronous request """
if session is None: session = NURESTSession.get_current_session() self._has_timeouted = False # Add specific headers controller = session.login_controller enterprise = controller.enterprise user_name = controller.user api_key = controller.api_key ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __make_request(self, requests_session, method, url, params, data, headers, certificate): """ Encapsulate requests call """
verify = False timeout = self.timeout try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-546 response = requests_session.request(method=method, url=url, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Make an HTTP request with a specific method """
# TODO : Use Timeout here and _ignore_request_idle from .nurest_session import NURESTSession session = NURESTSession.get_current_session() if self.async: thread = threading.Thread(target=self._make_request, kwargs={'session': session}) thread.is_daemon = False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Reset the connection """
self._request = None self._response = None self._transaction_id = uuid.uuid4().hex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, price_estimate): """ Take configuration from previous month, it it exists. Set last_update_time equals to the beginning of the month. """
kwargs = {} try: previous_price_estimate = price_estimate.get_previous() except ObjectDoesNotExist: pass else: configuration = previous_price_estimate.consumption_details.configuration kwargs['configuration'] = configuration month_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fields(self): """ When static declaration is used, event type choices are fetched too early - even before all apps are initialized. As a result, some eve...
fields = super(BaseHookSerializer, self).get_fields() fields['event_types'] = serializers.MultipleChoiceField( choices=loggers.get_valid_events(), required=False) fields['event_groups'] = serializers.MultipleChoiceField( choices=loggers.get_event_groups_keys(), required=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_nested_field(self, field_name, relation_info, nested_depth): """ Use PriceEstimateSerializer to serialize estimate children """
if field_name != 'children': return super(PriceEstimateSerializer, self).build_nested_field(field_name, relation_info, nested_depth) field_class = self.__class__ field_kwargs = {'read_only': True, 'many': True, 'context': {'depth': nested_depth - 1}} return field_class, fiel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the ...
if not hasattr(error, "_type_"): if exc_info is None: exc_info = sys.exc_info() error._type_ = exc_info[0] error._traceback = exc_info[2] return error
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reraise(error): """Re-raises the error that was processed by prepare_for_reraise earlier."""
if hasattr(error, "_type_"): six.reraise(type(error), error, error._traceback) raise error
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rest_name(cls): """ Represents a singular REST name """
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__rest_name__ is None: raise NotImplementedError('%s has no defined name. Implement rest_name property first.' % cls) return cls.__rest_name__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_name(cls): """ Represents the resource name """
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__resource_name__ is None: raise NotImplementedError('%s has no defined resource name. Implement resource_name property first.' % cls) return cls.__resource_name__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_args(self, data=dict(), **kwargs): """ Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a d...
for name, remote_attribute in self._attributes.items(): default_value = BambouConfig.get_default_attribute_value(self.__class__, name, remote_attribute.attribute_type) setattr(self, name, default_value) if len(data) > 0: self.from_dict(data) for key, value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def children_rest_names(self): """ Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: [...
names = [] for fetcher in self.fetchers: names.append(fetcher.__class__.managed_object_rest_name()) return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self): """ Validate the current object attributes. Check all attributes and store errors Returns: Returns True if all attibutes of the object respec...
self._attribute_errors = dict() # Reset validation errors for local_name, attribute in self._attributes.items(): value = getattr(self, local_name, None) if attribute.is_required and (value is None or value == ""): self._attribute_errors[local_name] = {'title'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None...
if remote_name is None: remote_name = local_name if display_name is None: display_name = local_name attribute = NURemoteAttribute(local_name=local_name, remote_name=remote_name, attribute_type=attribute_type) attribute.display_name = display_name attrib...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_owned_by_current_user(self): """ Check if the current user owns the object """
from bambou.nurest_root_object import NURESTRootObject root_object = NURESTRootObject.get_default_root_object() return self._owner == root_object.id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent_for_matching_rest_name(self, rest_names): """ Return parent that matches a rest name """
parent = self while parent: if parent.rest_name in rest_names: return parent parent = parent.parent_object return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genealogic_types(self): """ Get genealogic types Returns: Returns a list of all parent types """
types = [] parent = self while parent: types.append(parent.rest_name) parent = parent.parent_object return types
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genealogic_ids(self): """ Get all genealogic ids Returns: A list of all parent ids """
ids = [] parent = self while parent: ids.append(parent.id) parent = parent.parent_object return ids
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_child(self, child): """ Add a child """
rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) if children is None: raise InternalConsitencyError('Could not find fetcher with name %s while adding %s in parent %s' % (rest_name, child, self)) if child not in children: child.paren...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_child(self, child): """ Remove a child """
rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) target_child = None for local_child in children: if local_child.id == child.id: target_child = local_child break if target_child: target_child...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Converts the current object into a Dictionary using all exposed ReST attributes. Returns: dict: the dictionary containing all the exposed ...
dictionary = dict() for local_name, attribute in self._attributes.items(): remote_name = attribute.remote_name if hasattr(self, local_name): value = getattr(self, local_name) # Removed to resolve issue http://mvjira.mv.usa.alcatel.com/browse/V...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(self, dictionary): """ Sets all the exposed ReST attribues from the given dictionary Args: dictionary (dict): dictionnary containing the raw objec...
for remote_name, remote_value in dictionary.items(): # Check if a local attribute is exposed with the remote_name # if no attribute is exposed, return None local_name = next((name for name, attribute in self._attributes.items() if attribute.remote_name == remote_name), None...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, response_choice=1, async=False, callback=None): """ Delete object and call given callback in case of call. Args: response_choice (int): Automat...
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_DELETE, async=async, callback=callback, response_choice=response_choice)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, response_choice=None, async=False, callback=None): """ Update object and call given callback in case of async call Args: async (bool): Boolean to...
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_PUT, async=async, callback=callback, response_choice=response_choice)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(self, request, async=False, local_callback=None, remote_callback=None, user_info=None): """ Sends a request, calls the local callback, then the ...
callbacks = dict() if local_callback: callbacks['local'] = local_callback if remote_callback: callbacks['remote'] = remote_callback connection = NURESTConnection(request=request, async=async, callback=self._did_receive_response, callbacks=callbacks) c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False): """ Low leve...
url = None if method == HTTP_METHOD_POST: url = self.get_resource_url_for_child_type(nurest_object.__class__) else: url = self.get_resource_url() if response_choice is not None: url += '?responseChoice=%s' % response_choice request = NUREST...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _did_receive_response(self, connection): """ Receive a response from the connection """
if connection.has_timeouted: bambou_logger.info("NURESTConnection has timeout.") return has_callbacks = connection.has_callbacks() should_post = not has_callbacks if connection.handle_response_for_connection(should_post=should_post) and has_callbacks: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _did_retrieve(self, connection): """ Callback called after fetching the object """
response = connection.response try: self.from_dict(response.data[0]) except: pass return self._did_perform_standard_operation(connection)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _did_perform_standard_operation(self, connection): """ Performs standard opertions """
if connection.async: callback = connection.callbacks['remote'] if connection.user_info and 'nurest_object' in connection.user_info: callback(connection.user_info['nurest_object'], connection) else: callback(self, connection) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_child(self, nurest_object, response_choice=None, async=False, callback=None, commit=True): """ Add given nurest_object to the current object For examp...
# if nurest_object.id: # raise InternalConsitencyError("Cannot create a child that already has an ID: %s." % nurest_object) return self._manage_child_object(nurest_object=nurest_object, async=async, method=H...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instantiate_child(self, nurest_object, from_template, response_choice=None, async=False, callback=None, commit=True): """ Instantiate an nurest_object from a...
# if nurest_object.id: # raise InternalConsitencyError("Cannot instantiate a child that already has an ID: %s." % nurest_object) if not from_template.id: raise InternalConsitencyError("Cannot instantiate a child from a template with no ID: %s." % from_template) nurest...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _did_create_child(self, connection): """ Callback called after adding a new child nurest_object """
response = connection.response try: connection.user_info['nurest_object'].from_dict(response.data[0]) except Exception: pass return self._did_perform_standard_operation(connection)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign(self, objects, nurest_object_type, async=False, callback=None, commit=True): """ Reference a list of objects into the current resource Args: objects (...
ids = list() for nurest_object in objects: ids.append(nurest_object.id) url = self.get_resource_url_for_child_type(nurest_object_type) request = NURESTRequest(method=HTTP_METHOD_PUT, url=url, data=ids) user_info = {'nurest_objects': objects, 'commit': commit} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rest_equals(self, rest_object): """ Compare objects REST attributes """
if not self.equals(rest_object): return False return self.to_dict() == rest_object.to_dict()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equals(self, rest_object): """ Compare with another object """
if self._is_dirty: return False if rest_object is None: return False if not isinstance(rest_object, NURESTObject): raise TypeError('The object is not a NURESTObject %s' % rest_object) if self.rest_name != rest_object.rest_name: return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ip_address(request): """ Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR """
if 'HTTP_X_FORWARDED_FOR' in request.META: return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() else: return request.META['REMOTE_ADDR']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_estimates_without_scope_in_month(self, customer): """ It is expected that valid row for each month contains at least one price estimate for customer, ser...
estimates = self.get_price_estimates_for_customer(customer) if not estimates: return [] tables = {model: collections.defaultdict(list) for model in self.get_estimated_models()} dates = set() for estimate in estimates: date = (estimate....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_default_value(self): """ Get a default value of the attribute_type """
if self.choices: return self.choices[0] value = self.attribute_type() if self.attribute_type is time: value = int(value) elif self.attribute_type is str: value = "A" if self.min_length: if self.attribute_type is str: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_min_value(self): """ Get the minimum value """
value = self.get_default_value() if self.attribute_type is str: min_value = value[:self.min_length - 1] elif self.attribute_type is int: min_value = self.min_length - 1 else: raise TypeError('Attribute %s can not have a minimum value' % self.local...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_max_value(self): """ Get the maximum value """
value = self.get_default_value() if self.attribute_type is str: max_value = value.ljust(self.max_length + 1, 'a') elif self.attribute_type is int: max_value = self.max_length + 1 else: raise TypeError('Attribute %s can not have a maximum value' % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_api_root_view(self, api_urls=None): """ Return a basic root view. """
api_root_dict = OrderedDict() list_name = self.routes[0].name for prefix, viewset, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) class APIRootView(views.APIView): _ignore_model_permissions = True exclude_from_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_default_base_name(self, viewset): """ Attempt to automatically determine base name using `get_url_name`. """
queryset = getattr(viewset, 'queryset', None) if queryset is not None: get_url_name = getattr(queryset.model, 'get_url_name', None) if get_url_name is not None: return get_url_name() return super(SortedDefaultRouter, self).get_default_base_name(viewset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_customer_nc_users_quota(sender, structure, user, role, signal, **kwargs): """ Modify nc_user_count quota usage on structure role grant or revoke """
assert signal in (signals.structure_role_granted, signals.structure_role_revoked), \ 'Handler "change_customer_nc_users_quota" has to be used only with structure_role signals' assert sender in (Customer, Project), \ 'Handler "change_customer_nc_users_quota" works only with Project and Customer ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_service_settings_on_service_delete(sender, instance, **kwargs): """ Delete not shared service settings without services """
service = instance try: service_settings = service.settings except ServiceSettings.DoesNotExist: # If this handler works together with delete_service_settings_on_scope_delete # it tries to delete service settings that are already deleted. return if not service_settings.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_service_settings_on_scope_delete(sender, instance, **kwargs): """ If VM that contains service settings were deleted - all settings resources could be ...
for service_settings in ServiceSettings.objects.filter(scope=instance): service_settings.unlink_descendants() service_settings.delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url(self, url): """ Set API URL endpoint Args: url: the url of the API endpoint """
if url and url.endswith('/'): url = url[:-1] self._url = url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_authentication_header(self, user=None, api_key=None, password=None, certificate=None): """ Return authenication string to place in Authorization Header I...
if not user: user = self.user if not api_key: api_key = self.api_key if not password: password = self.password if not password: password = self.password if not certificate: certificate = self._certificate ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def impersonate(self, user, enterprise): """ Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enter...
if not user or not enterprise: raise ValueError('You must set a user name and an enterprise name to begin impersonification') self._is_impersonating = True self._impersonation = "%s@%s" % (user, enterprise)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equals(self, controller): """ Verify if the controller corresponds to the current one. """
if controller is None: return False return self.user == controller.user and self.enterprise == controller.enterprise and self.url == controller.url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(self, conn): """Revert back connection to pool."""
if conn.in_transaction: raise InvalidRequestError( "Cannot release a connection with " "not finished transaction" ) raw = conn.connection res = yield from self._pool.release(raw) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_configuration(cls, resource): """ Return how much consumables are used by resource with current configuration. Output example: { <ConsumableItem instance...
strategy = cls._get_strategy(resource.__class__) return strategy.get_configuration(resource)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_version(): """Obtain the version number"""
import imp import os mod = imp.load_source( 'version', os.path.join('skdata', '__init__.py') ) return mod.__version__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self, request, uuid=None): """ Accept invitation for current user. To replace user's email with email from invitation - add parameter 'replace_email' ...
invitation = self.get_object() if invitation.state != models.Invitation.State.PENDING: raise ValidationError(_('Only pending invitation can be accepted.')) elif invitation.civil_number and invitation.civil_number != request.user.civil_number: raise ValidationError(_('Us...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scope_deletion(sender, instance, **kwargs): """ Run different actions on price estimate scope deletion. If scope is a customer - delete all customer estimate...
is_resource = isinstance(instance, structure_models.ResourceMixin) if is_resource and getattr(instance, 'PERFORM_UNLINK', False): _resource_unlink(resource=instance) elif is_resource and not getattr(instance, 'PERFORM_UNLINK', False): _resource_deletion(resource=instance) elif isinstan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resource_deletion(resource): """ Recalculate consumption details and save resource details """
if resource.__class__ not in CostTrackingRegister.registered_resources: return new_configuration = {} price_estimate = models.PriceEstimate.update_resource_estimate(resource, new_configuration) price_estimate.init_details()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_update(sender, instance, created=False, **kwargs): """ Update resource consumption details and price estimate if its configuration has changed. Crea...
resource = instance try: new_configuration = CostTrackingRegister.get_configuration(resource) except ResourceNotRegisteredError: return models.PriceEstimate.update_resource_estimate( resource, new_configuration, raise_exception=not _is_in_celery_task()) # Try to create histo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_quota_update(sender, instance, **kwargs): """ Update resource consumption details and price estimate if its configuration has changed """
quota = instance resource = quota.scope try: new_configuration = CostTrackingRegister.get_configuration(resource) except ResourceNotRegisteredError: return models.PriceEstimate.update_resource_estimate( resource, new_configuration, raise_exception=not _is_in_celery_task())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_historical_estimates(resource, configuration): """ Create consumption details and price estimates for past months. Usually we need to update historic...
today = timezone.now() month_start = core_utils.month_start(today) while month_start > resource.created: month_start -= relativedelta(months=1) models.PriceEstimate.create_historical(resource, configuration, max(month_start, resource.created))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def IPYTHON_MAIN(): """Decide if the Ipython command line is running code."""
import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__ )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_model(cls, model): """ Register a model class according to its remote name Args: model: the model to register """
rest_name = model.rest_name resource_name = model.resource_name if rest_name not in cls._model_rest_name_registry: cls._model_rest_name_registry[rest_name] = [model] cls._model_resource_name_registry[resource_name] = [model] elif model not in cls._model_rest_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_first_model_with_rest_name(cls, rest_name): """ Get the first model corresponding to a rest_name Args: rest_name: the rest name """
models = cls.get_models_with_rest_name(rest_name) if len(models) > 0: return models[0] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_first_model_with_resource_name(cls, resource_name): """ Get the first model corresponding to a resource_name Args: resource_name: the resource name """
models = cls.get_models_with_resource_name(resource_name) if len(models) > 0: return models[0] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_spec(self, fullname, target=None): """Try to finder the spec and if it cannot be found, use the underscore starring syntax to identify potential matches...
spec = super().find_spec(fullname, target=target) if spec is None: original = fullname if "." in fullname: original, fullname = fullname.rsplit(".", 1) else: original, fullname = "", original if "_" in fullname: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, async=False, callback=None, encrypted=True): """ Updates the user and perform the callback method """
if self._new_password and encrypted: self.password = Sha1.encrypt(self._new_password) controller = NURESTSession.get_current_session().login_controller controller.password = self._new_password controller.api_key = None data = json.dumps(self.to_dict()) req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _did_save(self, connection): """ Launched when save has been successfully executed """
self._new_password = None controller = NURESTSession.get_current_session().login_controller controller.password = None controller.api_key = self.api_key if connection.async: callback = connection.callbacks['remote'] if connection.user_info: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch(self, async=False, callback=None): """ Fetch all information about the current object Args: async (bool): Boolean to make an asynchronous call. Defaul...
request = NURESTRequest(method=HTTP_METHOD_GET, url=self.get_resource_url()) if async: return self.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback) else: connection = self.send_request(request=request) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fabtabular(): """ This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists. """
import csv import sys from pkg_resources import resource_filename data = resource_filename(__package__, 'iso-639-3.tab') inverted = resource_filename(__package__, 'iso-639-3_Name_Index.tab') macro = resource_filename(__package__, 'iso-639-3-macrolanguages.tab') part5 = resource_filename(__...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def users(self, request, uuid=None): """ A list of users connected to the project """
project = self.get_object() queryset = project.get_users() # we need to handle filtration manually because we want to filter only project users, not projects. filter_backend = filters.UserConcatenatedNameOrderingBackend() queryset = filter_backend.filter_queryset(request, querys...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_user_update_settings(request, view, obj=None): """ Only staff can update shared settings, otherwise user has to be an owner of the settings."""
if obj is None: return # TODO [TM:3/21/17] clean it up after WAL-634. Clean up service settings update tests as well. if obj.customer and not obj.shared: return permissions.is_owner(request, view, obj) else: return permissions.is_staff(request, view,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, request, *args, **kwargs): """ Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^ It is possible to filter services by their types. Example: /api/ser...
return super(ServicesViewSet, self).list(request, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _require_staff_for_shared_settings(request, view, obj=None): """ Allow to execute action only if service settings are not shared or user is staff """
if obj is None: return if obj.settings.shared and not request.user.is_staff: raise PermissionDenied(_('Only staff users are allowed to import resources from shared services.'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unlink(self, request, uuid=None): """ Unlink all related resources, service project link and service itself. """
service = self.get_object() service.unlink_descendants() self.perform_destroy(service) return Response(status=status.HTTP_204_NO_CONTENT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_aggregator_quotas(self, quota): """ Fetch ancestors quotas that have the same name and are registered as aggregator quotas. """
ancestors = quota.scope.get_quota_ancestors() aggregator_quotas = [] for ancestor in ancestors: for ancestor_quota_field in ancestor.get_quotas_fields(field_class=AggregatorQuotaField): if ancestor_quota_field.get_child_quota_name() == quota.name: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscribe(self, handler): """Adds a new event handler."""
assert callable(handler), "Invalid handler %s" % handler self.handlers.append(handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on(self, event, handler): """Attaches the handler to the specified event. @param event: event to attach the handler to. Any object can be passed as event, bu...
event_hook = self.get_or_create(event) event_hook.subscribe(handler) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def off(self, event, handler): """Detaches the handler from the specified event. @param event: event to detach the handler to. Any object can be passed as event,...
event_hook = self.get_or_create(event) event_hook.unsubscribe(handler) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trigger(self, event, *args): """Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be ...
event_hook = self.get_or_create(event) event_hook.trigger(*args) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_trigger(self, event, *args): """Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. A...
event_hook = self.get_or_create(event) event_hook.safe_trigger(*args) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel_expired_invitations(invitations=None): """ Invitation lifetime must be specified in Waldur Core settings with parameter "INVITATION_LIFETIME". If invi...
expiration_date = timezone.now() - settings.WALDUR_CORE['INVITATION_LIFETIME'] if not invitations: invitations = models.Invitation.objects.filter(state=models.Invitation.State.PENDING) invitations = invitations.filter(created__lte=expiration_date) invitations.update(state=models.Invitation.Stat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_abi(self, jsonabi): """ Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :return: """
self.signatures = {} for element_description in jsonabi: abi_e = AbiMethod(element_description) if abi_e["type"] == "constructor": self.signatures[b"__constructor__"] = abi_e elif abi_e["type"] == "fallback": abi_e.setdefault("inputs",...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_input(self, s): """ Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return: AbiMethod instance ...
signatures = self.signatures.items() for sighash, method in signatures: if sighash is None or sighash.startswith(b"__"): continue # skip constructor if s.startswith(sighash): s = s[len(sighash):] types_def = self.signatures.get...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_is(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is not actual."""
assert expected is actual, _assert_fail_message( message, expected, actual, "is not", extra )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_is_not(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is actual."""
assert expected is not actual, _assert_fail_message( message, expected, actual, "is", extra )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_eq(expected, actual, message=None, tolerance=None, extra=None): """Raises an AssertionError if expected != actual. If tolerance is specified, raises a...
if tolerance is None: assert expected == actual, _assert_fail_message( message, expected, actual, "!=", extra ) else: assert isinstance(tolerance, _number_types), ( "tolerance parameter to assert_eq must be a number: %r" % tolerance ) assert isins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): """Asserts that two dictionaries are equal, producing a custom message if they are not...
assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys <= actual_keys, "Actual dict at %s is missing keys: %r" % ( _dict_path_string(dict_path), expected_keys - actual_keys, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_gt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand <= right_hand."""
assert left > right, _assert_fail_message(message, left, right, "<=", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_ge(left, right, message=None, extra=None): """Raises an AssertionError if left_hand < right_hand."""
assert left >= right, _assert_fail_message(message, left, right, "<", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_lt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand >= right_hand."""
assert left < right, _assert_fail_message(message, left, right, ">=", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_le(left, right, message=None, extra=None): """Raises an AssertionError if left_hand > right_hand."""
assert left <= right, _assert_fail_message(message, left, right, ">", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is not in seq."""
assert obj in seq, _assert_fail_message(message, obj, seq, "is not in", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_not_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is in iter."""
# for very long strings, provide a truncated error if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200: index = seq.find(obj) start_index = index - 50 if start_index > 0: truncated = "(truncated) ..." else: truncated = "" st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): """Raises an AssertionError if obj is not in seq using assert_eq cmp."""
for i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except AssertionError: pass assert False, _assert_fail_message(message, obj, seq, "is not in", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_is_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is not a substring of subject."""
assert ( (subject is not None) and (substring is not None) and (subject.find(substring) != -1) ), _assert_fail_message(message, substring, subject, "is not in", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_is_not_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is a substring of subject."""
assert ( (subject is not None) and (substring is not None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject, "is in", extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_unordered_list_eq(expected, actual, message=None): """Raises an AssertionError if the objects contained in expected are not equal to the objects conta...
missing_in_actual = [] missing_in_expected = list(actual) for x in expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if not message: message = ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _execute_if_not_empty(func): """ Execute function only if one of input parameters is not empty """
def wrapper(*args, **kwargs): if any(args[1:]) or any(kwargs.items()): return func(*args, **kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_search_body(self, should_terms=None, must_terms=None, must_not_terms=None, search_text='', start=None, end=None): """ Prepare body for elasticsearch ...
self.body = self.SearchBody() self.body.set_should_terms(should_terms) self.body.set_must_terms(must_terms) self.body.set_must_not_terms(must_not_terms) self.body.set_search_text(search_text) self.body.set_timestamp_filter(start, end) self.body.prepare()