Create unique barcode IDs assigned to sequences
359302
def _generate_barcode_ids(info_iter):
    
    bc_type = "SampleSheet"
    barcodes = list(set([x[-1] for x in info_iter]))
    barcodes.sort()
    barcode_ids = {}
    for i, bc in enumerate(barcodes):
        barcode_ids[bc] = (bc_type, i+1)
    return barcode_ids
26922
def _ids(self):
        """"""
        for pk in self._pks:
            yield getattr(self, pk)

        for pk in self._pks:

            try:
                yield str(getattr(self, pk))
            except ValueError:
                pass
185218
def generateUniqueId(context, **kw):
    

    # get the config for this portal type from the system setup
    config = get_config(context, **kw)

    # get the variables map for later string interpolation
    variables = get_variables(context, **kw)

    # The new generate sequence number
    number = 0

    # get the sequence type from the global config
    sequence_type = config.get("sequence_type", "generated")

    # Sequence Type is "Counter", so we use the length of the backreferences or
    # contained objects of the evaluated "context" defined in the config
    if sequence_type in ["counter"]:
        number = get_counted_number(context, config, variables, **kw)

    # Sequence Type is "Generated", so the ID is constructed according to the
    # configured split length
    if sequence_type in ["generated"]:
        number = get_generated_number(context, config, variables, **kw)

    # store the new sequence number to the variables map for str interpolation
    if isinstance(number, Alphanumber):
        variables["alpha"] = number
    variables["seq"] = to_int(number)

    # The ID formatting template from user config, e.g. {sampleId}-R{seq:02d}
    id_template = config.get("form", "")

    # Interpolate the ID template
    try:
        new_id = id_template.format(**variables)
    except KeyError, e:
        logger.error('KeyError: {} not in id_template {}'.format(
            e, id_template))
        raise
    normalized_id = api.normalize_filename(new_id)
    logger.info("generateUniqueId: {}".format(normalized_id))

    return normalized_id
1254471
function GenID2012($seq='adodbseq',$start=1)
	{

		/*
		 * First time in create an array of sequence names that we
		 * can use in later requests to see if the sequence exists
		 * the overhead is creating a list of sequences every time
		 * we need access to at least 1. If we really care about
		 * performance, we could maybe flag a 'nocheck' class variable
		 */
		if (!$this->sequences){
			$sql = "SELECT name FROM sys.sequences";
			$this->sequences = $this->GetCol($sql);
		}
		if (!is_array($this->sequences)
		|| is_array($this->sequences) && !in_array($seq,$this->sequences)){
			$this->CreateSequence2012($seq, $start);

		}
		$num = $this->GetOne("SELECT NEXT VALUE FOR $seq");
		return $num;
	}
646025
private synchronized long nextId(boolean isPadding, long busId) {

        long timestamp = timeGen();
        long paddingnum = regionId;

        if (isPadding) {
            paddingnum = busId;
        }

        if (timestamp < lastTimestamp) {
            try {
                throw new Exception("Clock moved backwards.  Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //如果上次生成时间和当前时间相同,在同一毫秒内
        if (lastTimestamp == timestamp) {
            //sequence自增，因为sequence只有10bit，所以和sequenceMask相与一下，去掉高位
            sequence = (sequence + 1) & sequenceMask;
            //判断是否溢出,也就是每毫秒内超过1024，当为1024时，与sequenceMask相与，sequence就等于0
            if (sequence == 0) {
                //自旋等待到下一毫秒
                timestamp = tailNextMillis(lastTimestamp);
            }
        } else {
            // 如果和上次生成时间不同,重置sequence，就是下一毫秒开始，sequence计数重新从0开始累加,
            // 为了保证尾数随机性更大一些,最后一位设置一个随机数
            sequence = new SecureRandom().nextInt(10);
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) | (paddingnum << regionIdShift) | (workerId << workerIdShift) | sequence;
    }
1160232
function initializeUnique() {
  uniquecoll = db.addCollection('uniquecoll', {
    unique: ['customId']
  });

  for (var idx = 0; idx < arraySize; idx++) {
    var v1 = genRandomVal();
    var v2 = genRandomVal();

    uniquecoll.insert({
      customId: (arraySize - idx),
      val: v1,
      val2: v2,
      val3: "more data 1234567890"
    });
  }
}
845891
private static String generateUniqueId(Set<String> ids, String idBase) {
		String id = idBase;
		int counter = 1;
		while (ids.contains(id)) {
			id = idBase + String.valueOf(counter++);
		}
		
		// put the newly generated one into the set
		ids.add(id);
		return id;
	}
832831
def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements):
    """"""
    # Create additional container-list without "map".
    containersWithoutMap = containers[:]
    try:
        containersWithoutMap.remove('map')
    except ValueError:
        # We can safely ignore if "map" is not contained in 'containers'!
        pass
    # Create header/source-files.
    create_more_container_files(headerDir, ".hpp", maxElements, containers, containersWithoutMap)
    create_more_container_files(sourceDir, ".cpp", maxElements, containers, containersWithoutMap)
572684
public static Map<String,Set<Writable>> getUniqueSequence(List<String> columnNames, Schema schema,
                                                               SequenceRecordReader sequenceData) {
        Map<String,Set<Writable>> m = new HashMap<>();
        for(String s : columnNames){
            m.put(s, new HashSet<>());
        }
        while(sequenceData.hasNext()){
            List<List<Writable>> next = sequenceData.sequenceRecord();
            for(List<Writable> step : next) {
                for (String s : columnNames) {
                    int idx = schema.getIndexOfColumn(s);
                    m.get(s).add(step.get(idx));
                }
            }
        }
        return m;
    }
1005149
def update_id(self, sequence_id=None, force=True):
        """"""
        from ..identity import ObjectNumber

        if sequence_id:
            self.sequence_id = sequence_id

        assert self.d_vid

        if self.id is None or force:
            dataset_id = ObjectNumber.parse(self.d_vid).rev(None)
            self.d_id = str(dataset_id)
            self.id = str(TableNumber(dataset_id, self.sequence_id))

        if self.vid is None or force:
            dataset_vid = ObjectNumber.parse(self.d_vid)
            self.vid = str(TableNumber(dataset_vid, self.sequence_id))
735214
def id_generator(size=15, random_state=None):
    """"""
    chars = list(string.ascii_uppercase + string.digits)
    return ''.join(random_state.choice(chars, size, replace=True))
52227
def unique(seq):
    """"""
    seen = {}
    result = []
    for item in seq:
        marker = item
        if marker in seen:
            continue
        seen[marker] = 1
        result.append(item)
    return result
707156
def replace_sequence(self, pdb_ID, chain_id, replacement_sequence):
        ''''''
        old_sequences = self.sequences
        old_unique_sequences = self.unique_sequences
        self.sequences = []
        self.unique_sequences = {}
        for s in old_sequences:
            if s[0] == pdb_ID and s[1] == chain_id:
                self._add_sequence(pdb_ID, chain_id, replacement_sequence)
            else:
                self._add_sequence(s[0], s[1], s[2])

        self._find_identical_sequences()
1072240
def update_id(self, sequence_id=None):
        """"""
        from ..identity import GeneralNumber1

        if sequence_id:
            self.sequence_id = sequence_id

        self.vid = str(GeneralNumber1('T', self.d_vid, self.sequence_id))
474358
public static Set<Writable> getUniqueSequence(String columnName, Schema schema,
                                                   SequenceRecordReader sequenceData) {
        int colIdx = schema.getIndexOfColumn(columnName);
        Set<Writable> unique = new HashSet<>();
        while(sequenceData.hasNext()){
            List<List<Writable>> next = sequenceData.sequenceRecord();
            for(List<Writable> step : next){
                unique.add(step.get(colIdx));
            }
        }
        return unique;
    }
1266263
def insert_many(self, it):
        """"""
        unique_indexes = self._uniqueIndexes  # [ind for ind in self._indexes.values() if ind.is_unique]
        NO_SUCH_ATTR = object()
        new_objs = list(it)
        if unique_indexes:
            for ind in unique_indexes:
                ind_attr = ind.attr
                new_keys = dict((getattr(obj, ind_attr, NO_SUCH_ATTR), obj) for obj in new_objs)
                if not ind.accept_none and (None in new_keys or NO_SUCH_ATTR in new_keys):
                    raise KeyError("unique key cannot be None or blank for index %s" % ind_attr, 
                                    [ob for ob in new_objs if getattr(ob, ind_attr, NO_SUCH_ATTR) is None])
                if len(new_keys) < len(new_objs):
                    raise KeyError("given sequence contains duplicate keys for index %s" % ind_attr)
                for key in new_keys:
                    if key in ind:
                        obj = new_keys[key]
                        raise KeyError("duplicate unique key value '%s' for index %s" % (getattr(obj, ind_attr), ind_attr), 
                                       new_keys[key])
                    
        for obj in new_objs:
            self.obs.append(obj)
            for attr, ind in self._indexes.items():
                obval = getattr(obj, attr)
                ind[obval] = obj

        return self
230011
def dePrefixAndSuffixFasta(sequences):
    
    sequences = sorted(sequences, key=lambda s: len(s.seq), reverse=True)
    seen = set()
    for s in sequences:
        thisSeq = str(s.seq)
        thisHash = md5(thisSeq.encode('UTF-8')).digest()
        if thisHash not in seen:
            # Add prefixes.
            newHash = md5()
            for nucl in thisSeq:
                newHash.update(nucl.encode('UTF-8'))
                seen.add(newHash.digest())
            # Add suffixes.
            for start in range(len(thisSeq) - 1):
                seen.add(md5(thisSeq[start + 1:].encode('UTF-8')).digest())
            yield s