Validate and save this JSON. Ensure (and return) a unique amendment id
553044
def add_new_amendment(self,
                          json_repr,
                          auth_info,
                          commit_msg=''):
        """"""
        amendment = self._coerce_json_to_amendment(json_repr)
        if amendment is None:
            msg = "File failed to parse as JSON:\n{j}".format(j=json_repr)
            raise ValueError(msg)
        if not self._is_valid_amendment_json(amendment):
            msg = "JSON is not a valid amendment:\n{j}".format(j=json_repr)
            raise ValueError(msg)

        # Mint any needed ottids, update the document accordingly, and
        # prepare a response with
        #  - per-taxon mapping of tag to ottid
        #  - resulting id (or URL) to the stored amendment
        # To ensure synchronization of ottids and amendments, this should be an
        # atomic operation!

        # check for tags and confirm count of new ottids required (if provided)
        num_taxa_eligible_for_ids = 0
        for taxon in amendment.get("taxa"):
            # N.B. We don't require 'tag' in amendment validation; check for it now!
            if "tag" not in taxon:
                raise KeyError('Requested Taxon is missing "tag" property!')
            # allow for taxa that have already been assigned (use cases?)
            if "ott_id" not in taxon:
                num_taxa_eligible_for_ids += 1
        if 'new_ottids_required' in amendment:
            requested_ids = amendment['new_ottids_required']
            try:
                assert (requested_ids == num_taxa_eligible_for_ids)
            except:
                m = 'Number of OTT ids requested ({r}) does not match eligible taxa ({t})'
                m = m.format(r=requested_ids, t=num_taxa_eligible_for_ids)
                raise ValueError(m)

        # mint new ids and assign each to an eligible taxon
        with self._growing_shard._doc_counter_lock:
            # build a map of tags to ottids, to return to the caller
            tag_to_id = {}
            first_new_id = self._growing_shard.next_ott_id
            last_new_id = first_new_id + num_taxa_eligible_for_ids - 1
            if last_new_id < first_new_id:
                # This can happen if ther are no eligible taxa! In this case,
                # repeat and "burn" the next ottid (ie, it will be used to
                # identify this amendment, but it won't be assigned)
                last_new_id = first_new_id
            new_id = first_new_id
            for taxon in amendment.get("taxa"):
                if "ott_id" not in taxon:
                    taxon["ott_id"] = new_id
                    ttag = taxon["tag"]
                    tag_to_id[ttag] = new_id
                    new_id += 1
                    ptag = taxon.get("parent_tag")
                    if ptag is not None:
                        taxon["parent"] = tag_to_id[ptag]
            if num_taxa_eligible_for_ids > 0:
                try:
                    assert (new_id == (last_new_id + 1))
                except:
                    applied = last_new_id - first_new_id + 1
                    raise ValueError(
                        'Number of OTT ids requested ({r}) does not match ids actually applied ({a})'.format(
                            r=requested_ids, a=applied))

            # Build a proper amendment id, in the format '{subtype}-{first ottid}-{last-ottid}'
            amendment_subtype = 'additions'
            # TODO: Handle other subtypes (beyond additions) by examining JSON?
            amendment_id = "{s}-{f}-{l}".format(s=amendment_subtype, f=first_new_id, l=last_new_id)

            # Check the proposed id for uniqueness (just to be safe), then
            # "reserve" it using a placeholder value.
            with self._index_lock:
                if amendment_id in self._doc2shard_map:
                    # this should never happen!
                    raise KeyError('Amendment "{i}" already exists!'.format(i=amendment_id))
                self._doc2shard_map[amendment_id] = None

            # Set the amendment's top-level "id" property to match
            amendment["id"] = amendment_id

            # pass the id and amendment JSON to a proper git action
            new_amendment_id = None
            r = None
            try:
                # assign the new id to a shard (important prep for commit_and_try_merge2master)
                gd_id_pair = self.create_git_action_for_new_amendment(new_amendment_id=amendment_id)
                new_amendment_id = gd_id_pair[1]
                # For amendments, the id should not have changed!
                try:
                    assert new_amendment_id == amendment_id
                except:
                    raise KeyError('Amendment id unexpectedly changed from "{o}" to "{n}"!'.format(
                        o=amendment_id, n=new_amendment_id))
                try:
                    # it's already been validated, so keep it simple
                    r = self.commit_and_try_merge2master(file_content=amendment,
                                                         doc_id=new_amendment_id,
                                                         auth_info=auth_info,
                                                         parent_sha=None,
                                                         commit_msg=commit_msg,
                                                         merged_sha=None)
                except:
                    self._growing_shard.delete_doc_from_index(new_amendment_id)
                    raise

                # amendment is now in the repo, so we can safely reserve the ottids
                first_minted_id, last_minted_id = self._growing_shard._mint_new_ott_ids(
                    how_many=max(num_taxa_eligible_for_ids, 1))
                # do a final check for errors!
                try:
                    assert first_minted_id == first_new_id
                except:
                    raise ValueError('First minted ottid is "{m}", expected "{e}"!'.format(
                        m=first_minted_id, e=first_new_id))
                try:
                    assert last_minted_id == last_new_id
                except:
                    raise ValueError('Last minted ottid is "{m}", expected "{e}"!'.format(
                        m=last_minted_id, e=last_new_id))
                # Add the tag-to-ottid mapping to the response, so a caller
                # (e.g. the curation webapp) can provisionally assign them
                r['tag_to_ottid'] = tag_to_id
            except:
                with self._index_lock:
                    if new_amendment_id in self._doc2shard_map:
                        del self._doc2shard_map[new_amendment_id]
                raise

        with self._index_lock:
            self._doc2shard_map[new_amendment_id] = self._growing_shard
        return new_amendment_id, r
326971
def modified_created(instance):
    
    if 'modified' in instance and 'created' in instance and \
            instance['modified'] < instance['created']:
        msg = "'modified' (%s) must be later or equal to 'created' (%s)"
        return JSONError(msg % (instance['modified'], instance['created']),
                         instance['id'])
909901
def update(self, id, data):
        
        id = self.as_id(id)
        response = self.http.patch(
            '%s/%s' % (self, id), json=data, auth=self.auth
        )
        response.raise_for_status()
        return response.json()
470187
def to_json(self, incl_uniqueid=False):
        
        def _parse(k, v):
            
            if k=='value':
                if isinstance(self._value, nparray.ndarray):
                    if self._value.unit is not None and hasattr(self, 'default_unit'):
                        v = self._value.to(self.default_unit).to_dict()
                    else:
                        v = self._value.to_dict()
                if isinstance(v, u.Quantity):
                    v = self.get_value() # force to be in default units
                if isinstance(v, np.ndarray):
                    v = v.tolist()
                return v
            elif k=='limits':
                return [vi.value if hasattr(vi, 'value') else vi for vi in v]
            elif v is None:
                return v
            elif isinstance(v, str):
                return v
            elif isinstance(v, dict):
                return v
            elif isinstance(v, float) or isinstance(v, int) or isinstance(v, list):
                return v
            elif _is_unit(v):
                return str(v.to_string())
            else:
                try:
                    return str(v)
                except:
                    raise NotImplementedError("could not parse {} of '{}' to json".format(k, self.uniquetwig))

        return {k: _parse(k, v) for k,v in self.to_dict().items() if (v is not None and k not in ['twig', 'uniquetwig', 'quantity'] and (k!='uniqueid' or incl_uniqueid or self.qualifier=='detached_job'))}
164425
def check_unique(self):
        """"""
        errors = []
        service_id = getattr(self, 'id', None)
        fields = [('location', views.service_location),
                  ('name', views.service_name)]

        for field, view in fields:
            value = getattr(self, field, None)
            if not value:
                continue

            result = yield view.values(key=value)
            matched = {x['id'] for x in result if x['id'] != service_id}
            if matched:
                errors.append("Service with {} '{}' already exists"
                              .format(field, value))

        if errors:
            raise exceptions.ValidationError(errors)
936010
def save(self, obj, run_id):
        
        id_code = self.generate_save_identifier(obj, run_id)
        self.store.save(obj, id_code)
312399
public void ensureValidity(long oid) {
		if (oids == null) {
			return;
		}
		if (oid >= oids[oids.length-1]) {
			nextValidOidPos = -1;
			return;
		}
		while (oid >= oids[nextValidOidPos]) {
			nextValidOidPos++;
		}
	}
960211
def save(self):
        
        resp = self.r_session.put(
            self.document_url,
            data=self.json(),
            headers={'Content-Type': 'application/json'}
        )
        resp.raise_for_status()
304414
def json(self):
        
        self.pendingvalidation()

        jsondoc = {'id': self.id, 'children': [], 'declarations': self.jsondeclarations() }
        if self.version:
            jsondoc['version'] = self.version
        else:
            jsondoc['version'] = FOLIAVERSION
        jsondoc['generator'] = 'pynlpl.formats.folia-v' + LIBVERSION

        for text in self.data:
            jsondoc['children'].append(text.json())
        return jsondoc
454879
public void validateVerification(int id, String code) {
		getResourceFactory().getApiResource("/hook/" + id + "/verify/validate")
				.entity(new HookValidate(code), MediaType.APPLICATION_JSON)
				.post();
	}
520567
def _validate(self):
        
        probably_good_to_go = True
        sheet = self.table
        identity = self.db_sheet_cols.id

        # check if you have unique srnos
        id_col = sheet.loc[:, identity]
        if any(id_col.duplicated()):
            warnings.warn(
                "your database is corrupt: duplicates"
                " encountered in the srno-column")
            logger.debug("srno duplicates:\n" + str(
                id_col.duplicated()))
            probably_good_to_go = False
        return probably_good_to_go
886043
def save
      response = service.send(:"#{method_prefix}_update", self.attrs)

      if response.at_xpath('//status').attr('code') == 'ok'
        # Load the ID if this was a creation
        self.id = response.at_xpath("//#{ac_obj_node_name}").attr("#{ac_obj_type}-id") if self.id.nil?
        true
      else
        save_errors(response)
        false
      end
    end
715043
def safe_json_response(method):
    

    def _safe_document(document):
        """ function modifies the document in place
            it iterates over the json document and stringify all non-string types
            :return: modified document """
        assert isinstance(document, dict), 'Error: provided document is not of DICT type: {0}' \
            .format(document.__class__.__name__)

        for key, value in document.items():
            if isinstance(value, dict):
                document[key] = {k: str(v) for k, v in value.items()}
            elif isinstance(value, list):
                document[key] = [str(v) for v in value]
            else:
                document[key] = str(document[key])
        return document

    @functools.wraps(method)
    def _wrapper(self, *args, **kwargs):
        try:
            document = method(self, *args, **kwargs)
            return _safe_document(document)
        except Exception as e:
            return self.reply_server_error(e)

    return _wrapper
648154
def _validate_unique(self, unique, field, value):
        
        if unique:
            root_key = self.schema_path[0]
            data = (doc[field] for doc in self.root_document[root_key])
            for key, count in collections.Counter(data).items():
                if count > 1:
                    msg = "'{}' is not unique".format(key)
                    self._error(field, msg)
650614
def to_json(self, incl_uniqueid=False):
        
        lst = []
        for context in _contexts:
            lst += [v.to_json(incl_uniqueid=incl_uniqueid)
                    for v in self.filter(context=context,
                                         check_visible=False,
                                         check_default=False).to_list()]
        return lst
820049
def build_json(self, guid):
        """"""
        upserts = []
        for value in self.upserts:
            upserts.append({"value": value, "criteria": self.upserts[value]})
        return json.dumps({'replace_all': self.replace_all, 'guid': guid,
                           'complete': self.complete, 'upserts': upserts, 'deletes': self.deletes})
237341
function uniqueId() {
  var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'id_';
  var id = prefix + strRand();
  if (!store.uniqueId) store.uniqueId = {};
  var generatedIds = store.uniqueId;

  if (document.getElementById(id) || generatedIds[id]) {
    return uniqueId(prefix);
  } else {
    generatedIds[id] = true;
    return id;
  }
}