code stringlengths 1 18.2k |
|---|
def create(**data): """ Create a Payment request. :param data: data required to create the payment :return: The payment resource :rtype resources.Payment """ http_client = HttpClient() response, _ = http_client.post(routes.url(routes.PAYMENT_RESOURCE), data) return resources.Payment(**response) |
def list(per_page=None, page=None): """ List of payments. You have to handle pagination manually :param page: the page number :type page: int|None :param per_page: number of payment per page. It's a good practice to increase this number if you know that you will need a lot of payments. :type per_page: int|None :return ... |
def retrieve(payment, refund_id): """ Retrieve a refund from a payment and the refund id. :param payment: The payment id or the payment object :type payment: resources.Payment|string :param refund_id: The refund id :type refund_id: string :return: The refund resource :rtype: resources.Refund """ if isinstance(payment, ... |
def create(payment, **data): """ Create a refund on a payment. :param payment: Either the payment object or the payment id you want to refund. :type payment: resources.Payment|string :param data: data required to create the refund :return: The refund resource :rtype resources.Refund """ if isinstance(payment, resources... |
def list(payment): """ List all the refunds for a payment. :param payment: The payment object or the payment id :type payment: resources.Payment|string :return: A collection of refunds :rtype resources.APIResourceCollection """ if isinstance(payment, resources.Payment): payment = payment.id http_client = HttpClient() r... |
def retrieve(customer_id): """ Retrieve a customer from its id. :param customer_id: The customer id :type customer_id: string :return: The customer resource :rtype: resources.Customer """ http_client = HttpClient() response, __ = http_client.get(routes.url(routes.CUSTOMER_RESOURCE, resource_id=customer_id)) return reso... |
def delete(customer): """ Delete a customer from its id. :param customer: The customer id or object :type customer: string|Customer """ if isinstance(customer, resources.Customer): customer = customer.id http_client = HttpClient() http_client.delete(routes.url(routes.CUSTOMER_RESOURCE, resource_id=customer)) |
def update(customer, **data): """ Update a customer from its id. :param customer: The customer id or object :type customer: string|Customer :param data: The data you want to update :return: The customer resource :rtype resources.Customer """ if isinstance(customer, resources.Customer): customer = customer.id http_clien... |
def create(**data): """ Create a customer. :param data: data required to create the customer :return: The customer resource :rtype resources.Customer """ http_client = HttpClient() response, _ = http_client.post(routes.url(routes.CUSTOMER_RESOURCE), data) return resources.Customer(**response) |
def retrieve(customer, card_id): """ Retrieve a card from its id. :param customer: The customer id or object :type customer: string|Customer :param card_id: The card id :type card_id: string :return: The customer resource :rtype: resources.Card """ if isinstance(customer, resources.Customer): customer = customer.id htt... |
def delete(customer, card): """ Delete a card from its id. :param customer: The customer id or object :type customer: string|Customer :param card: The card id or object :type card: string|Card """ if isinstance(customer, resources.Customer): customer = customer.id if isinstance(card, resources.Card): card = card.id htt... |
def create(customer, **data): """ Create a card instance. :param customer: the customer id or object :type customer: string|Customer :param data: data required to create the card :return: The card resource :rtype resources.Card """ if isinstance(customer, resources.Customer): customer = customer.id http_client = HttpCl... |
def list(customer, per_page=None, page=None): """ List of cards. You have to handle pagination manually for the moment. :param customer: the customer id or object :type customer: string|Customer :param page: the page number :type page: int|None :param per_page: number of customers per page. It's a good practice to incr... |
in [('page', page), ('per_page', per_page)] if value) http_client = HttpClient() response, _ = http_client.get(routes.url(routes.CARD_RESOURCE, customer_id=customer, pagination=pagination)) return resources.APIResourceCollection(resources.Card, **response) |
def strptime(self, value, format): """ By default, parse datetime with TZ. If TZ is False, convert datetime to local time and disable TZ """ value = force_str(value) if format == ISO_8601: try: parsed = parse_datetime(value) if not settings.USE_TZ: fr_tz = pytz.timezone(settings.TIME_ZONE) parsed = parsed.astimezone(fr... |
def find_data_files(source, target, patterns): """ Locates the specified data-files and returns the matches in a data_files compatible format. source is the root of the source data tree. Use '' or '.' for current directory. target is the root of the target data tree. Use '' or '.' for the distribution directory. patter... |
def cache(self): """Query or return the Graph API representation of this resource.""" if not self._cache: self._cache = self.graph.get('%s' % self.id) return self._cache |
def capakey_rest_gateway_request(url, headers={}, params={}): ''' Utility function that helps making requests to the CAPAKEY REST service. :param string url: URL to request. :param dict headers: Headers to send with the URL. :param dict params: Parameters to send with the URL. :returns: Result of the call. ''' try: res... |
def check_lazy_load_gemeente(f): ''' Decorator function to lazy load a :class:`Gemeente`. ''' def wrapper(self): gemeente = self if (getattr(gemeente, '_%s' % f.__name__, None) is None): log.debug('Lazy loading Gemeente %d', gemeente.id) gemeente.check_gateway() g = gemeente.gateway.get_gemeente_by_id(gemeente.id) geme... |
def check_lazy_load_afdeling(f): ''' Decorator function to lazy load a :class:`Afdeling`. ''' def wrapper(self): afdeling = self if (getattr(afdeling, '_%s' % f.__name__, None) is None): log.debug('Lazy loading Afdeling %d', afdeling.id) afdeling.check_gateway() a = afdeling.gateway.get_kadastrale_afdeling_by_id(afdeli... |
def check_lazy_load_sectie(f): ''' Decorator function to lazy load a :class:`Sectie`. ''' def wrapper(self): sectie = self if (getattr(sectie, '_%s' % f.__name__, None) is None): log.debug('Lazy loading Sectie %s in Afdeling %d', sectie.id, sectie.afdeling.id) sectie.check_gateway() s = sectie.gateway.get_sectie_by_id_... |
def check_lazy_load_perceel(f): ''' Decorator function to lazy load a :class:`Perceel`. ''' def wrapper(self): perceel = self if (getattr(perceel, '_%s' % f.__name__, None) is None): log.debug( 'Lazy loading Perceel %s in Sectie %s in Afdeling %d', perceel.id, perceel.sectie.id, perceel.sectie.afdeling.id ) perceel.che... |
def _parse_bounding_box(bounding_box): ''' Parse response bounding box from the CapakeyRestGateway to (MinimumX, MinimumY, MaximumX, MaximumY) :param bounding_box: response bounding box from the CapakeyRestGateway :return: (MinimumX, MinimumY, MaximumX, MaximumY) ''' coordinates = json.loads(bounding_box)["coordinates"... |
def list_gemeenten(self, sort=1): ''' List all `gemeenten` in Vlaanderen. :param integer sort: What field to sort on. :rtype: A :class:`list` of :class:`Gemeente`. ''' def creator(): url = self.base_url + '/municipality' h = self.base_headers p = { 'orderbyCode': sort == 1 } res = capakey_rest_gateway_request(url, h, p... |
def get_gemeente_by_id(self, id): ''' Retrieve a `gemeente` by id (the NIScode). :rtype: :class:`Gemeente` ''' def creator(): url = self.base_url + '/municipality/%s' % id h = self.base_headers p = { 'geometry': 'full', 'srs': '31370' } res = capakey_rest_gateway_request(url, h, p).json() return Gemeente( res['municipa... |
def list_kadastrale_afdelingen(self): ''' List all `kadastrale afdelingen` in Flanders. :param integer sort: Field to sort on. :rtype: A :class:`list` of :class:`Afdeling`. ''' def creator(): gemeentes = self.list_gemeenten() res = [] for g in gemeentes: res += self.list_kadastrale_afdelingen_by_gemeente(g) return res ... |
def list_kadastrale_afdelingen_by_gemeente(self, gemeente, sort=1): ''' List all `kadastrale afdelingen` in a `gemeente`. :param gemeente: The :class:`Gemeente` for which the \ `afdelingen` are wanted. :param integer sort: Field to sort on. :rtype: A :class:`list` of :class:`Afdeling`. ''' try: gid = gemeente.id except... |
def get_kadastrale_afdeling_by_id(self, aid): ''' Retrieve a 'kadastrale afdeling' by id. :param aid: An id of a `kadastrale afdeling`. :rtype: A :class:`Afdeling`. ''' def creator(): url = self.base_url + '/department/%s' % (aid) h = self.base_headers p = { 'geometry': 'full', 'srs': '31370' } res = capakey_rest_gatew... |
def list_secties_by_afdeling(self, afdeling): ''' List all `secties` in a `kadastrale afdeling`. :param afdeling: The :class:`Afdeling` for which the `secties` are \ wanted. Can also be the id of and `afdeling`. :rtype: A :class:`list` of `Sectie`. ''' try: aid = afdeling.id gid = afdeling.gemeente.id except AttributeE... |
def get_sectie_by_id_and_afdeling(self, id, afdeling): ''' Get a `sectie`. :param id: An id of a sectie. eg. "A" :param afdeling: The :class:`Afdeling` for in which the `sectie` can \ be found. Can also be the id of and `afdeling`. :rtype: A :class:`Sectie`. ''' try: aid = afdeling.id except AttributeError: aid = afdel... |
def list_percelen_by_sectie(self, sectie): ''' List all percelen in a `sectie`. :param sectie: The :class:`Sectie` for which the percelen are wanted. :param integer sort: Field to sort on. :rtype: A :class:`list` of :class:`Perceel`. ''' sid = sectie.id aid = sectie.afdeling.id gid = sectie.afdeling.gemeente.id sectie.... |
def get_perceel_by_id_and_sectie(self, id, sectie): ''' Get a `perceel`. :param id: An id for a `perceel`. :param sectie: The :class:`Sectie` that contains the perceel. :rtype: :class:`Perceel` ''' sid = sectie.id aid = sectie.afdeling.id gid = sectie.afdeling.gemeente.id sectie.clear_gateway() def creator(): url = sel... |
def get_perceel_by_capakey(self, capakey): ''' Get a `perceel`. :param capakey: An capakey for a `perceel`. :rtype: :class:`Perceel` ''' def creator(): url = self.base_url + '/parcel/%s' % capakey h = self.base_headers p = { 'geometry': 'full', 'srs': '31370', 'data': 'adp' } res = capakey_rest_gateway_request(url, h, ... |
def set_gateway(self, gateway): ''' :param crabpy.gateway.capakey.CapakeyGateway gateway: Gateway to use. ''' self.gateway = gateway if (self._gemeente is not None): self._gemeente.set_gateway(gateway) |
def set_gateway(self, gateway): ''' :param crabpy.gateway.capakey.CapakeyGateway gateway: Gateway to use. ''' self.gateway = gateway self.afdeling.set_gateway(gateway) |
def set_gateway(self, gateway): ''' :param crabpy.gateway.capakey.CapakeyGateway gateway: Gateway to use. ''' self.gateway = gateway self.sectie.set_gateway(gateway) |
def _split_capakey(self): ''' Split a capakey into more readable elements. Splits a capakey into it's grondnummer, bisnummer, exponent and macht. ''' import re match = re.match( r"^[0-9]{5}[A-Z]{1}([0-9]{4})\/([0-9]{2})([A-Z\_]{1})([0-9]{3})$", self.capakey ) if match: self.grondnummer = match.group(1) self.bisnummer =... |
def requires_libsodium(func): """ Mark a function as requiring libsodium. If no libsodium support is detected, a `RuntimeError` is thrown. """ @wraps(func) def wrapper(*args, **kwargs): libsodium_check() return func(*args, **kwargs) return wrapper |
def has_delete_permission(self, request, obj=None): """ Default namespaces cannot be deleted. """ if obj is not None and obj.fixed: return False return super(NamespaceAdmin, self).has_delete_permission(request, obj) |
def get_install_requires(): """Add conditional dependencies (when creating source distributions).""" install_requires = get_requirements('requirements.txt') if 'bdist_wheel' not in sys.argv: if sys.version_info[0] == 2: # On Python 2.6 and 2.7 we pull in Bazaar. install_requires.append('bzr >= 2.6.0') if sys.version_in... |
def get_urls(self): """ Overload the admin's urls for WYMEditor. """ entry_admin_urls = super(EntryAdminWYMEditorMixin, self).get_urls() urls = [ url(r'^wymeditor/$', self.admin_site.admin_view(self.wymeditor), name='zinnia_entry_wymeditor'), ] return urls + entry_admin_urls |
def _media(self): """ The medias needed to enhance the admin page. """ def static_url(url): return staticfiles_storage.url('zinnia_wymeditor/%s' % url) media = super(EntryAdminWYMEditorMixin, self).media media += Media( js=(static_url('js/jquery.min.js'), static_url('js/wymeditor/jquery.wymeditor.pack.js'), static_url(... |
def launchEditor(mapObj): """ PURPOSE: launch the editor using a specific map object INPUT: mapObj (sc2maptool.mapRecord.MapRecord) """ cfg = Config() if cfg.is64bit: selectedArchitecture = c.SUPPORT_64_BIT_TERMS else: selectedArchitecture = c.SUPPORT_32_BIT_TERMS editorCmd = "%s -run %s -testMod %s -displayMode 1" ful... |
def initScenario(controller, scenario, thisPlayerID, debug=False): """once in the in_game state, use the controller to set up the scenario""" ############################################################################ def createUnitsWithTags(unitList, existingUnits={}, maxTries=25): """create each unit of unitList in ... |
match a unit of a different type if liveUnit.owner != unit.owner: continue # can't match units with different owners if liveUnit.tag in existingUnits: continue # don't match against previously existing or new units unit.tag = liveUnit.tag # found a match; sync tags + decalre this unit matched existingUnits[unit.tag] = ... |
continue foundNewUnit = False for u in obs.observation.raw_data.units: # identify existing units (requieres no fog to be disabled?) if u.tag in detectedUnits: continue foundNewUnit = True detectedUnits[u.tag] = u if foundNewUnit: continue # ensure that two consecutive gameloops have identical units if detectedUnits: br... |
(noNeutral or ownedOnly): return unitDict # must select filters to get something different return {unit.tag : unit for unit in unitDict.values() if allow(unit)} ############################################################################ def removeUnitsByKey(originalUnits=None, keepTags=[], **filters): """remove all de... |
and messaging around delayed timing""" if debug: print(msg) while True: time.sleep(1) delay -= 1 if delay > 0: if debug: print("%d..."%delay) continue break ############################################################################ knownUnits = detectCurrentUnits(noNeutral=True) # all initial units, including misc un... |
rmTags wait(1, "idle for unit kills (keep %d)"%len(knownUnits)) removeUnitsByKey(keepTags=knownUnits.keys(), noNeutral=True) # attempt again because zerg building deaths produce broodlings if debug: print("%d remaining initial, known units"%len(knownUnits)) initialUnits = dict(knownUnits) if thisPlayerID == 1: # this i... |
convert ability into requisite upgrade protocol action while len(actionLists) <= i: actionLists.append([]) nonActionLists.append([]) action = Action() uCmd = action.action_raw.unit_command uCmd.unit_tags.append(unit.tag) uCmd.queue_command = True uCmd.ability_id, ignoreTargetType = ability.getGameCmd() # upgrade abilit... |
upgrades") if thisPlayerID == 1: # this is the host (disable cheats for all players) controller.debug(debugCmds.disableAllCosts(), # disable cheats debugCmds.allowEnemyControl(), debugCmds.fastProduction()) wait(0.5, "wait to disable cheats before proceeding") if thisPlayerID == 1: removeUnitsByKey(keepTags=initialUnit... |
controller wait(0.1, "allow modifications to finish") controller.debug(debugCmds.revealMap()) # reenable fog of war if debug: print("scenario setup is finished") |
def set_properties(self, path, mode): """Set file's properties (name and mode). This function is also in charge of swapping between textual and binary streams. """ self.name = path self.mode = mode if 'b' in self.mode: if not isinstance(self.read_data, bytes): self.read_data = bytes(self.read_data, encoding='utf8') els... |
def reset_mock(self, visited=None): """Reset the default tell/read/write/etc side effects.""" # In some versions of the mock library, `reset_mock` takes an argument # and in some it doesn't. We try to handle all situations. if visited is not None: super(FileLikeMock, self).reset_mock(visited) else: super(FileLikeMock, ... |
def _get_child_mock(self, **kws): """Create a new FileLikeMock instance. The new mock will inherit the parent's side_effect and read_data attributes. """ kws.update({ '_new_parent': self, 'side_effect': self._mock_side_effect, 'read_data': self.__read_data, }) return FileLikeMock(**kws) |
def allow(self, ip): """ Allow the specified IP to connect. :param ip: The IPv4 or IPv6 address to allow. """ self.whitelist.append(ip) self.blacklist.clear() |
def deny(self, ip): """ Allow the specified IP to connect. :param ip: The IPv4 or IPv6 address to allow. """ self.blacklist.append(ip) self.whitelist.clear() |
async def on_request( self, domain, address, identity, mechanism, credentials, ): """ Handle a ZAP request. """ logger.debug( "Request in domain %s for %s (%r): %r (%r)", domain, address, identity, mechanism, credentials, ) user_id = None metadata = {} if self.whitelist: if address not in self.whitelist: raise ZAPAuthe... |
metadata |
def factory(data): """ Try to reconstruct the APIResource from its data. :param data: The APIResource data :type data: dict :return: The guessed APIResource :raise exceptions.UnkownAPIResource when it's impossible to reconstruct the APIResource from its data. """ if 'object' not in data: raise exceptions.UnknownAPIReso... |
def _initialize(self, **resource_attributes): """ Initialize a resource. Default behavior is just to set all the attributes. You may want to override this. :param resource_attributes: The resource attributes """ self._set_attributes(**resource_attributes) for attribute, attribute_type in list(self._mapper.items()): if ... |
def _mapper(self): """ Maps payment attributes to their specific types. :see :func:`~APIResource._mapper` """ return { 'card': Payment.Card, 'customer': Payment.Customer, 'hosted_payment': Payment.HostedPayment, 'notification': Payment.Notification, 'failure': Payment.Failure, } |
def get_consistent_resource(self): """ :return a payment that you can trust. :rtype Payment """ http_client = HttpClient() response, _ = http_client.get(routes.url(routes.PAYMENT_RESOURCE, resource_id=self.id)) return Payment(**response) |
def get_consistent_resource(self): """ :return a refund that you can trust. :rtype Refund """ http_client = HttpClient() response, _ = http_client.get( routes.url(routes.REFUND_RESOURCE, resource_id=self.id, payment_id=self.payment_id) ) return Refund(**response) |
def list_cards(self, *args, **kwargs): """ List the cards of the customer. :param page: the page number :type page: int|None :param per_page: number of customers per page. It's a good practice to increase this number if you know that you will need a lot of payments. :type per_page: int|None :return: The cards of the cu... |
def _initialize(self, **resource_attributes): """ Initialize the collection. :param resource_attributes: API resource parameters """ super(APIResourceCollection, self)._initialize(**resource_attributes) dict_list = self.data self.data = [] for resource in dict_list: self.data.append(self._expected_api_resource(**resour... |
def main(): """The command line interface of the ``vcs-tool`` program.""" # Initialize logging to the terminal. coloredlogs.install() # Command line option defaults. repository = None revision = None actions = [] # Parse the command line arguments. try: options, arguments = getopt.gnu_getopt(sys.argv[1:], 'r:dnisume:vq... |
global # revision id which is immutable. If release objects had # something like an optional `mutable_revision_id' it # should be possible to support the combination of # --release and --merge-up. assert repository, "Please specify a repository first!" release_id = value.strip() assert release_id in repository.releases... |
specify a nonempty release identifier!" actions.append(functools.partial(print_selected_release, repository, release_id)) elif option in ('-s', '--sum-revisions'): assert len(arguments) >= 2, "Please specify one or more repository/revision pairs!" actions.append(functools.partial(print_summed_revisions, arguments)) arg... |
actions: usage(__doc__) return except Exception as e: warning("Error: %s", e) sys.exit(1) # Execute the requested action(s). try: for action in actions: action() except Exception: logger.exception("Failed to execute requested action(s)!") sys.exit(1) |
def retry(retries=10, wait=5, catch=None): """ Decorator to retry on exceptions raised """ catch = catch or (Exception,) def real_retry(function): def wrapper(*args, **kwargs): for _ in range(retries): try: ret = function(*args, **kwargs) return ret except catch: time.sleep(wait) except Exception as e: raise e else: ra... |
def replace_all(filepath, searchExp, replaceExp): """ Replace all the ocurrences (in a file) of a string with another value. """ for line in fileinput.input(filepath, inplace=1): if searchExp in line: line = line.replace(searchExp, replaceExp) sys.stdout.write(line) |
def discard_incoming_messages(self): """ Discard all incoming messages for the time of the context manager. """ # Flush any received message so far. self.inbox.clear() # This allows nesting of discard_incoming_messages() calls. previous = self._discard_incoming_messages self._discard_incoming_messages = True try: yield... |
def provides(self, imt): """ Returns True iff the self is at least as specific as other. Examples: application/xhtml+xml provides application/xml, application/*, */* text/html provides text/*, but not application/xhtml+xml or application/html """ return self.type[:imt.specifity] == imt.type[:imt.specifity] |
def resolve(cls, accept, available_renderers): """ Resolves a list of accepted MediaTypes and available renderers to the preferred renderer. Call as MediaType.resolve([MediaType], [renderer]). """ assert isinstance(available_renderers, tuple) accept = sorted(accept) renderers, seen = [], set() accept_groups = [[accept.... |
def get_available_name(self, name): """ Deletes the given file if it exists. """ if self.exists(name): self.delete(name) return name |
def delete(self, name): """ Handle deletion race condition present in Django prior to 1.4 https://code.djangoproject.com/ticket/16108 """ try: super(StaticCompilerFileStorage, self).delete(name) except OSError, e: if e.errno != errno.ENOENT: raise |
def add_socket(self, socket): """ Add a socket to the multiplexer. :param socket: The socket. If it was added already, it won't be added a second time. """ if socket not in self._sockets: self._sockets.add(socket) socket.on_closed.connect(self.remove_socket) |
def remove_socket(self, socket): """ Remove a socket from the multiplexer. :param socket: The socket. If it was removed already or if it wasn't added, the call does nothing. """ if socket in self._sockets: socket.on_closed.disconnect(self.remove_socket) self._sockets.remove(socket) |
async def recv_multipart(self): """ Read from all the associated sockets. :returns: A list of tuples (socket, frames) for each socket that returned a result. """ if not self._sockets: return [] results = [] async def recv_and_store(socket): frames = await socket.recv_multipart() results.append((socket, frames)) tasks =... |
def as_dict(self): """ Serializes the object necessary data in a dictionary. :returns: Serialized data in a dictionary. :rtype: dict """ result_dict = super(Group, self).as_dict() statuses = list() version = None titles = list() descriptions = list() platforms = list() groups = list() rules = list() for child in self.c... |
rules return result_dict |
def modified_data_decorator(function): """ Decorator to initialise the modified_data if necessary. To be used in list functions to modify the list """ @wraps(function) def func(self, *args, **kwargs): """Decorator function""" if not self.get_read_only() or not self.is_locked(): self.initialise_modified_data() return fu... |
def initialise_modified_data(self): """ Initialise the modified_data if necessary """ if self.__modified_data__ is None: if self.__original_data__: self.__modified_data__ = list(self.__original_data__) else: self.__modified_data__ = [] |
def append(self, item): """ Appending elements to our list """ validated_value = self.get_validated_object(item) if validated_value is not None: self.__modified_data__.append(validated_value) |
def insert(self, index, p_object): """ Insert an element to a list """ validated_value = self.get_validated_object(p_object) if validated_value is not None: self.__modified_data__.insert(index, validated_value) |
def index(self, value): """ Gets the index in the list for a value """ if self.__modified_data__ is not None: return self.__modified_data__.index(value) return self.__original_data__.index(value) |
def count(self, value): """ Gives the number of occurrencies of a value in the list """ if self.__modified_data__ is not None: return self.__modified_data__.count(value) return self.__original_data__.count(value) |
def flat_data(self): """ Function to pass our modified values to the original ones """ def flat_field(value): """ Flat item """ try: value.flat_data() return value except AttributeError: return value modified_data = self.__modified_data__ if self.__modified_data__ is not None else self.__original_data__ if modified_dat... |
def export_data(self): """ Retrieves the data in a jsoned form """ def export_field(value): """ Export item """ try: return value.export_data() except AttributeError: return value if self.__modified_data__ is not None: return [export_field(value) for value in self.__modified_data__] return [export_field(value) for valu... |
def export_modified_data(self): """ Retrieves the modified data in a jsoned form """ def export_modfield(value, is_modified_seq=True): """ Export modified item """ try: return value.export_modified_data() except AttributeError: if is_modified_seq: return value if self.__modified_data__ is not None: return [export_modfi... |
def export_modifications(self): """ Returns list modifications. """ if self.__modified_data__ is not None: return self.export_data() result = {} for key, value in enumerate(self.__original_data__): try: if not value.is_modified(): continue modifications = value.export_modifications() except AttributeError: continue try... |
def export_original_data(self): """ Retrieves the original_data """ def export_field(value): """ Export item """ try: return value.export_original_data() except AttributeError: return value return [export_field(val) for val in self.__original_data__] |
def import_deleted_fields(self, data): """ Set data fields to deleted """ def child_delete_from_str(data_str): """ Inner function to set children fields to deleted """ parts = data_str.split('.', 1) if parts[0].isnumeric: self[int(parts[0])].import_deleted_fields(parts[1]) if not self.get_read_only() or not self.is_loc... |
def export_deleted_fields(self): """ Returns a list with any deleted fields form original data. In tree models, deleted fields on children will be appended. """ result = [] if self.__modified_data__ is not None: return result for index, item in enumerate(self): try: deleted_fields = item.export_deleted_fields() result.... |
def is_modified(self): """ Returns whether list is modified or not """ if self.__modified_data__ is not None: return True for value in self.__original_data__: try: if value.is_modified(): return True except AttributeError: pass return False |
def clear_modified_data(self): """ Clears only the modified data """ self.__modified_data__ = None for value in self.__original_data__: try: value.clear_modified_data() except AttributeError: pass |
def get_attrs_by_path(self, field_path, stop_first=False): """ It returns list of values looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: list or None. :param stop_first: Stop iteration on first ... |
def delete_attr_by_path(self, field): """ Function for deleting a field specifying the path in the whole model as described in :func:`dirty:models.models.BaseModel.perform_function_by_path` """ index_list, next_field = self._get_indexes_by_path(field) if index_list: for index in reversed(index_list): if next_field: sel... |
def reset_attr_by_path(self, field): """ Function for restoring a field specifying the path in the whole model as described in :func:`dirty:models.models.BaseModel.perform_function_by_path` """ index_list, next_field = self._get_indexes_by_path(field) if index_list: if next_field: for index in index_list: self[index].r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.