Takes a list of SeqRecordExpanded objects corresponding to a gene_code
        and produces the gene_block as string.

        :param block:
        :return: str.
197611
def convert_to_string(self, block):
        
        if self.aminoacids:
            molecule_type = "protein"
        else:
            molecule_type = "dna"

        out = None
        for seq_record in block:
            if not out:
                out = '&[{0}]\n'.format(molecule_type, seq_record.gene_code)
            taxon_id = '{0}_{1}_{2}'.format(seq_record.voucher_code,
                                            seq_record.taxonomy['genus'],
                                            seq_record.taxonomy['species'],
                                            )
            sequence = get_seq(seq_record, self.codon_positions, self.aminoacids,
                               self.degenerate)
            seq = sequence.seq
            if sequence.warning:
                self.warnings.append(sequence.warning)

            out += '{0}{1}\n'.format(taxon_id.ljust(55), seq)
        return out
1073340
def from_str(cls: Type[BlockUIDType], blockid: str) -> BlockUIDType:
        
        data = BlockUID.re_block_uid.match(blockid)
        if data is None:
            raise MalformedDocumentError("BlockUID")
        try:
            number = int(data.group(1))
        except AttributeError:
            raise MalformedDocumentError("BlockUID")

        try:
            sha_hash = data.group(2)
        except AttributeError:
            raise MalformedDocumentError("BlockHash")

        return cls(number, sha_hash)
770262
def getobjectref(blocklst, commdct):
    
    objlst_dct = {}
    for eli in commdct:
        for elj in eli:
            if 'object-list' in elj:
                objlist = elj['object-list'][0]
                objlst_dct[objlist] = []

    for objlist in list(objlst_dct.keys()):
        for i in range(len(commdct)):
            for j in range(len(commdct[i])):
                if 'reference' in commdct[i][j]:
                    for ref in commdct[i][j]['reference']:
                        if ref == objlist:
                            objlst_dct[objlist].append((blocklst[i][0], j))
    return objlst_dct
851998
def processDatasetBlocks(self, url, conn, inputdataset, order_counter):
        
        ordered_dict = {}
        srcblks = self.getSrcBlocks(url, dataset=inputdataset)
        if len(srcblks) < 0:
            e = "DBSMigration: No blocks in the required dataset %s found at source %s."%(inputdataset, url)
            dbsExceptionHandler('dbsException-invalid-input2', e, self.logger.exception, e)
        dstblks = self.blocklist.execute(conn, dataset=inputdataset)
	self.logger.debug("******* dstblks for dataset %s ***********" %inputdataset)
	self.logger.debug(dstblks)
        blocksInSrcNames = [ y['block_name'] for y in srcblks]
	blocksInDstNames = []
	for item in dstblks:
	    blocksInDstNames.append(item['block_name'])
        ordered_dict[order_counter] = []
        for ablk in blocksInSrcNames:
            if not ablk in blocksInDstNames:
                ordered_dict[order_counter].append(ablk)
        if ordered_dict[order_counter] != []:
	    self.logger.debug("**** ordered_dict dict length ****")
	    self.logger.debug(len(ordered_dict)) 	
            return ordered_dict
        else:
            return {}
525283
def _convert(self, block_node):
        

        if not type(block_node) is BlockNode:
            return block_node

        block = self.project.factory.block(block_node.addr, block_node.size)

        ail_block = ailment.IRSBConverter.convert(block.vex, self._ail_manager)
        return ail_block
1074166
def make_degenerate_regex( motif_seq, molecule='dna' ):
	
	
	if not isinstance( motif_seq, six.string_types ):
		raise TypeError( "motif_seq must be a string!" )
		
	if molecule == 'dna':
		degenerate_code = { "A":"A", "B":"[CGT]", "C":"C", "D":"[AGT]", "G":"G", "H":"[ACT]", "K":"[GT]", "M":"[AC]", "N":"[ACGT]", "R":"[AG]", "S":"[GC]", "T":"T", "V":"[ACG]", "W":"[AT]", "Y":"[CT]" }
	elif molecule == 'rna':
		degenerate_code = { "A":"A", "B":"[CGU]", "C":"C", "D":"[AGU]", "G":"G", "H":"[ACU]", "K":"[GU]", "M":"[AC]", "N":"[ACGU]", "R":"[AG]", "S":"[GC]", "U":"U", "V":"[ACG]", "W":"[AU]", "Y":"[CU]" }
	else:
		raise ValueError( "make_degenerate_regex requires molecule to be dna or rna" )
	
	regex_string = ''
	
	idx = 0
	
	while idx < len( motif_seq ):
		curr = motif_seq[idx]
		
		count = 1
		
		for next_idx in range( idx+1, len( motif_seq ) ):
			next = motif_seq[next_idx]
			
			if next == curr:
				count += 1
			else:
				break
		
		regex_string += degenerate_code[curr]
		
		if count > 1:
			idx = idx + count - 1
			regex_string += "{%s}" % ( count )
		
		idx += 1
	
	return regex_string
404939
def parse_block(self, block, lineno, indent):
        
        tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
        tree.future_features = frozenset()
        return tree
1182723
def gen_blocks(output, ascii_props=False, append=False, prefix=""):
    """"""

    with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
        if not append:
            f.write(HEADER)
        f.write('%s_blocks = {' % prefix)
        no_block = []
        last = -1

        max_range = MAXASCII if ascii_props else MAXUNICODE
        formatter = bytesformat if ascii_props else uniformat

        with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, 'Blocks.txt'), 'r', 'utf-8') as uf:
            for line in uf:
                if not line.startswith('#'):
                    data = line.split(';')
                    if len(data) < 2:
                        continue
                    block = [int(i, 16) for i in data[0].strip().split('..')]
                    if block[0] > last + 1:
                        if (last + 1) <= max_range:
                            endval = block[0] - 1 if (block[0] - 1) < max_range else max_range
                            no_block.append((last + 1, endval))
                    last = block[1]
                    name = format_name(data[1])
                    inverse_range = []
                    if block[0] > max_range:
                        if ascii_props:
                            f.write('\n    "%s": "",' % name)
                            f.write('\n    "^%s": "%s-%s",' % (name, formatter(0), formatter(max_range)))
                        continue
                    if block[0] > 0:
                        inverse_range.append("%s-%s" % (formatter(0), formatter(block[0] - 1)))
                    if block[1] < max_range:
                        inverse_range.append("%s-%s" % (formatter(block[1] + 1), formatter(max_range)))
                    f.write('\n    "%s": "%s-%s",' % (name, formatter(block[0]), formatter(block[1])))
                    f.write('\n    "^%s": "%s",' % (name, ''.join(inverse_range)))
            if last < max_range:
                if (last + 1) <= max_range:
                    no_block.append((last + 1, max_range))
            last = -1
            no_block_inverse = []
            if not no_block:
                no_block_inverse.append((0, max_range))
            else:
                for piece in no_block:
                    if piece[0] > last + 1:
                        no_block_inverse.append((last + 1, piece[0] - 1))
                    last = piece[1]
            for block, name in ((no_block, 'noblock'), (no_block_inverse, '^noblock')):
                f.write('\n    "%s": "' % name)
                for piece in block:
                    if piece[0] == piece[1]:
                        f.write(formatter(piece[0]))
                    else:
                        f.write("%s-%s" % (formatter(piece[0]), formatter(piece[1])))
                f.write('",')
            f.write('\n}\n')
1138847
def atlasdb_get_zonefiles_by_block( from_block, to_block, offset, count, name=None, con=None, path=None ):
    
    ret = None

    if count > 100:
        return {'error' : 'Count must be less than 100'}

    with AtlasDBOpen(con=con, path=path) as dbcon:

        sql = 'SELECT name,zonefile_hash,txid,block_height,inv_index FROM zonefiles WHERE block_height >= ? AND block_height <= ?'
        args = (from_block, to_block)

        if name:
            sql += ' AND name = ?'
            args += (name,)

        sql += 'ORDER BY inv_index LIMIT ? OFFSET ?;'
        args += (count, offset)

        cur = dbcon.cursor()
        res = atlasdb_query_execute( cur, sql, args )

        ret = []

        for zfinfo in res:
            ret.append({
                'name' : zfinfo['name'],
                'zonefile_hash' : zfinfo['zonefile_hash'],
                'block_height' : zfinfo['block_height'],
                'txid' : zfinfo['txid'],
                'inv_index': zfinfo['inv_index'],
            })

    return ret
629574
def getSrcBlockParents(self, url, block):
        
        #blockname = block.replace("#", urllib.quote_plus('#'))
        #resturl = "%s/blockparents?block_name=%s" % (url, blockname)
        params={'block_name':block}
        return cjson.decode(self.callDBSService(url, 'blockparents', params, {}))
309871
def get_annotated_chain_sequence_string(self, chain_id, use_seqres_sequences_if_possible, raise_Exception_if_not_found = True):
        ''''''
        if use_seqres_sequences_if_possible and self.seqres_sequences and self.seqres_sequences.get(chain_id):
            return ('SEQRES', self.seqres_sequences[chain_id])
        elif self.atom_sequences.get(chain_id):
            return ('ATOM', self.atom_sequences[chain_id])
        elif raise_Exception_if_not_found:
            raise Exception('Error: Chain %s expected but not found.' % (str(chain_id)))
        else:
            return None
1017656
def _build_trees_by_chrom(blocks, verbose=False):
  
  if verbose:
    sys.stderr.write("separating blocks by chromosome... ")
  by_chrom = {}
  for b in blocks:
    if b.chrom not in by_chrom:
      by_chrom[b.chrom] = []
    by_chrom[b.chrom].append(b)
  if verbose:
    sys.stderr.write("done\n")

  if verbose:
    sys.stderr.write("building interval trees by chromosome... ")
  res = {}
  for c in by_chrom:
    res[c] = IntervalTree(by_chrom[c], openEnded=True)
  if verbose:
    sys.stderr.write("done\n")

  return res
698394
def parse_blocks(lines):  # type: (List[str]) -> List[List[str]]
    
    blocks = []

    while lines:
        if lines[0] == '':
            lines.pop(0)
        else:
            blocks.append(parse_block(lines))

    return blocks
1029032
def bmap_btree_record_to_block_pointers(record, block_pointers_length)
      block_pointers = []
      # Fill in the missing blocks with 0-blocks
      block_pointers << 0 while (block_pointers_length + block_pointers.length) < record.start_offset
      1.upto(record.block_count) { |i| block_pointers << record.start_block + i - 1 }
      @block_offset += record.block_count
      block_pointers
    end
1284551
def genbank_to_gene_coords(infile, genes):
    ''''''
    coords = {}

    for seq_record in SeqIO.parse(infile, "genbank"):
        for feature in seq_record.features:
            if feature.type == 'gene':
                gene_name = feature.qualifiers.get('gene', [None])[0]
                if gene_name not in genes:
                    continue

                if feature.location.strand == 1:
                    coords[gene_name] = {'start': int(feature.location.start), 'end': int(feature.location.end) - 1}
                else:
                    coords[gene_name] = {'end': int(feature.location.start), 'start': int(feature.location.end) - 1}

    return coords
1276336
def _identify_heterogeneity_blocks_seg(in_file, seg_file, params, work_dir, somatic_info):
    
    def _segment_by_cns(target_chrom, freqs, coords):
        with open(seg_file) as in_handle:
            reader = csv.reader(in_handle, dialect="excel-tab")
            next(reader)  # header
            for cur_chrom, start, end in (xs[:3] for xs in reader):
                if cur_chrom == target_chrom:
                    block_freqs = []
                    for i, (freq, coord) in enumerate(zip(freqs, coords)):
                        if coord >= int(start) and coord < int(end):
                            block_freqs.append(freq)
                        elif coord >= int(end):
                            break
                    coords = coords[max(0, i - 1):]
                    freqs = freqs[max(0, i - 1):]
                    if len(block_freqs) > params["hetblock"]["min_alleles"]:
                        yield start, end
    return _identify_heterogeneity_blocks_shared(in_file, _segment_by_cns, params, work_dir, somatic_info)
1314715
def _docstring_parse(self, blocks):
        """"""
        result = {}
        for block, docline, doclength, key in blocks:
            doctext = "<doc>{}</doc>".format(" ".join(block))
            try:
                docs = ET.XML(doctext)
                docstart = self.parser.charindex(docline, 0, self.context)
                if not key in result:
                    result[key] = [list(docs), docstart, docstart + doclength]
                else:
                    #If there are docblocks separated by whitespace in the
                    #same element we can't easily keep track of the start and
                    #end character indices anymore.
                    result[key][0].extend(list(docs))
            except ET.ParseError:
                msg.warn(doctext)

        return result