Exemplo n.º 1
0
    def reportSorted(self, sortedSignatureIDs):

        filteredSignatures = (
            Signature.readSignatures(self.filteredLocation))    # The output.

        # REPORT SORTED SIGNATURES
        outputFile = open(self.sortedLocation, 'w')

        for ID in sortedSignatureIDs:

            if ID in filteredSignatures:

                signature = filteredSignatures[ID]

                # -- Score Signature -- #
                if ID in self.overallScore:
                    signature.score = self.overallScore[ID]
                else:
                    signature.score = 0.0

                if ID in self.inclusionScore:
                    signature.inscore = self.inclusionScore[ID]
                else:
                    signature.inscore = 0.0

                if ID in self.exclusionScore:
                    signature.exscore = self.exclusionScore[ID]
                else:
                    signature.exscore = 0.0

                Signature.writeSignature(signature, outputFile)

        outputFile.close()
Exemplo n.º 2
0
    def is_valid(self):
        total_in = 0
        total_out = 0
        message = self.__gather()
        # Self.inputs -> List[Tuples(addr, amount)]
        for addr, amount, index in self.inputs:
            found = False
            for s in self.sigs:
                if Signature.verify(message, s, addr):
                    found = True
            if not found:
                return False
            if amount < 0:
                return False
            total_in = total_out + amount

        for addr in self.reqd:
            found = False
            for s in self.sigs:
                if Signature.verify(message, s, addr):
                    found = True
            if not found:
                return False

        for addr, amount in self.outputs:
            if amount < 0:
                return False
            total_out = total_out + amount
        ''' 
        # Remove as Miners best interest to have transactions where outputs > inputs.
        # Miners will be performing these checks.
        if total_out > total_in:
            return False
        '''
        return True
Exemplo n.º 3
0
def get_similar_signs(smallsign, bigsign, diffPercentage=12, minSimilarity=75):
    start = timer()
    curs.execute("SELECT datestamp,smallsign,bigsign FROM people")
    data = curs.fetchall()

    nbSmallCorres = 0
    nbBigCorres = 0

    similarSmallSign = []
    similarBigSign = []
    for row in data:
        if sign.compare_signs(smallsign, convertItem(row[1]),
                              diffPercentage)[1] >= minSimilarity:
            nbSmallCorres += 1
            similarSmallSign.append((row[0], row[1]))
        if sign.compare_signs(bigsign, convertItem(row[2]),
                              diffPercentage)[1] >= minSimilarity:
            nbBigCorres += 1
            similarBigSign.append((row[0], row[2]))

    print("{} similar small sign in DB // {} similare big sign in DB".format(
        nbSmallCorres, nbBigCorres))

    #print("getSimilarSign: " + str(timer() - start))
    return similarSmallSign, similarBigSign
Exemplo n.º 4
0
    def reportSorted(self, sortedSignatureIDs):

        filteredSignatures = (
            Signature.readSignatures(self.filteredLocation))    # The output.

        # REPORT SORTED SIGNATURES
        outputFile = open(self.sortedLocation, 'w')

        for ID in sortedSignatureIDs:

            if ID in filteredSignatures:

                signature = filteredSignatures[ID]

                # -- Score Signature -- #
                if ID in self.overallScore:
                    signature.score = self.overallScore[ID]
                else:
                    signature.score = 0.0

                if ID in self.inclusionScore:
                    signature.inscore = self.inclusionScore[ID]
                else:
                    signature.inscore = 0.0

                if ID in self.exclusionScore:
                    signature.exscore = self.exclusionScore[ID]
                else:
                    signature.exscore = 0.0

                Signature.writeSignature(signature, outputFile)

        outputFile.close()
Exemplo n.º 5
0
def post():
    message = request.form.get('message')
    author = request.form.get('author')
    if not message or not author:
        flash("You must fill in both a message and an author")
    else:
        signature = Signature(message=message, author=author)
        signature.store()
        flash("Signature stored")
    return redirect(url_for('display'))
Exemplo n.º 6
0
def consolidateSignatures(
        signatureLocations, seedSize, outputDirectoryLocation):

    # --- Compile Signatures --- #
    compiledSignatures = {}
    compileSignatures(compiledSignatures, signatureLocations)

    # -- Sort Signatures -- #
    sortedSignatures = Signature.sortSignatures(compiledSignatures)

    # -- Write Signatures -- #
    compiledSignatureLocation = os.path.join(
        outputDirectoryLocation, COMPILED_SIGNATURES)

    compiledSignatureFile = open(compiledSignatureLocation, 'w')
    Signature.writeSignatures(sortedSignatures, compiledSignatureFile)
    compiledSignatureFile.close()

    # --- Build and Query Database --- #
    databaseLocation = os.path.join(
        outputDirectoryLocation, COMPILED_DATABASE)
    queryLocation = os.path.join(
        outputDirectoryLocation, COMPILED_DATABASE_QUERY)

    Database.createDatabaseJob(compiledSignatureLocation, databaseLocation)
    Database.queryDatabase(
        databaseLocation, compiledSignatureLocation,
        queryLocation, 0.50, seedSize)

    # --- Produce Signatures --- #
    outputLocation = os.path.join(
        outputDirectoryLocation, CONSOLIDATED_SIGNATURES)
    outputFile = open(outputLocation, 'w')
    queryFile = open(queryLocation, 'r')

    produceSignatures(sortedSignatures, queryFile, outputFile)

    outputFile.close()
    queryFile.close()

    # --- Clean Output --- #
    filelist = [f for f in os.listdir(outputDirectoryLocation)
                if f.startswith(COMPILED_DATABASE)]

    for f in filelist:
        os.remove(os.path.join(outputDirectoryLocation, f))

    os.remove(os.path.join(outputDirectoryLocation, COMPILED_SIGNATURES))

    print "\n==== Exiting ====\n"
Exemplo n.º 7
0
def consolidateSignatures(
        signatureLocations, seedSize, outputDirectoryLocation):

    # --- Compile Signatures --- #
    compiledSignatures = {}
    compileSignatures(compiledSignatures, signatureLocations)

    # -- Sort Signatures -- #
    sortedSignatures = Signature.sortSignatures(compiledSignatures)

    # -- Write Signatures -- #
    compiledSignatureLocation = os.path.join(
        outputDirectoryLocation, COMPILED_SIGNATURES)

    compiledSignatureFile = open(compiledSignatureLocation, 'w')
    Signature.writeSignatures(sortedSignatures, compiledSignatureFile)
    compiledSignatureFile.close()

    # --- Build and Query Database --- #
    databaseLocation = os.path.join(
        outputDirectoryLocation, COMPILED_DATABASE)
    queryLocation = os.path.join(
        outputDirectoryLocation, COMPILED_DATABASE_QUERY)

    Database.createDatabaseJob(compiledSignatureLocation, databaseLocation)
    Database.queryDatabase(
        databaseLocation, compiledSignatureLocation,
        queryLocation, 0.50, seedSize)

    # --- Produce Signatures --- #
    outputLocation = os.path.join(
        outputDirectoryLocation, CONSOLIDATED_SIGNATURES)
    outputFile = open(outputLocation, 'w')
    queryFile = open(queryLocation, 'r')

    produceSignatures(sortedSignatures, queryFile, outputFile)

    outputFile.close()
    queryFile.close()

    # --- Clean Output --- #
    filelist = [f for f in os.listdir(outputDirectoryLocation)
                if f.startswith(COMPILED_DATABASE)]

    for f in filelist:
        os.remove(os.path.join(outputDirectoryLocation, f))

    os.remove(os.path.join(outputDirectoryLocation, COMPILED_SIGNATURES))
Exemplo n.º 8
0
 def sign(self, z):
     k = self.deterministic_k(z)
     r = (k*G).x.num
     k_inv = pow(k, N-2, N)
     s = (z + r*self.secret) * k_inv % N
     if s > N/2:
         s = N - s
     return Signature(r, s)
Exemplo n.º 9
0
def get_tests(config={}):
    tests = []
    import Cipher; tests += Cipher.get_tests(config=config)
    import Hash;   tests += Hash.get_tests(config=config)
    import Protocol; tests += Protocol.get_tests(config=config)
    import PublicKey; tests += PublicKey.get_tests(config=config)
    import Random; tests += Random.get_tests(config=config)
    import Util;   tests += Util.get_tests(config=config)
    import Signature;   tests += Signature.get_tests(config=config)
    return tests
Exemplo n.º 10
0
def startWallet():
    global tWS

    # Load public and private keys
    Wallet.my_private, Wallet.my_public = Signature.loadKeys(
        ("private.key", "public.key"))

    # Start WalletServer
    tWS = threading.Thread(target=Wallet.walletServer, args=((my_ip, 5006), ))
    tWS.start()

    return True
Exemplo n.º 11
0
def produceSignatures(sortedSignatures, blastOutputFile, destination):

    hits = {}  # [SIGNATURE ID] -> [(SIGNATURE ID) LIST] // (alignments)
    outputSignatures = {}  # Collection of already-output signatures.

    # Build a list of all query hits.
    # This creates a dictionary mapping signatures that align to each other.
    # [SIGNATURE ID] -> [(SIGNATURE ID) LIST]
    for line in blastOutputFile:

        hit = Database.Hit(line)

        # We only keep the hit if the ratio of the signature-to-alignment
        # length is sufficiently long.
        if (float(hit.alignmentLength) / float(hit.length) < float(0.50)):
            continue

        # Append the signature ID to the existing list of IDs.
        if hit.ID in hits:
            hits[hit.ID].append(hit.reference)

        # Create a new list of signature IDs associated with specific
        # signature ID.
        else:
            hits[hit.ID] = [hit.reference]

    # Write the signatures to output, while maintaining a dictionary of
    # signatures that were previously written to output. This attempts to
    # avoid writing signatures appear to be duplicates or appear to overlap
    # significantly.
    for signature in sortedSignatures:

        # Is the signature close to anything already written to output?
        if(all((ID not in outputSignatures) for ID in hits[signature.ID])):

            # The signature appears to be sufficiently unique.
            # Write the signature to output and update outputed signatures.
            outputSignatures[signature.ID] = signature
            Signature.writeSignature(signature, destination)
Exemplo n.º 12
0
def produceSignatures(sortedSignatures, blastOutputFile, destination):

    hits = {}  # [SIGNATURE ID] -> [(SIGNATURE ID) LIST] // (alignments)
    outputSignatures = {}  # Collection of already-output signatures.

    # Build a list of all query hits.
    # This creates a dictionary mapping signatures that align to each other.
    # [SIGNATURE ID] -> [(SIGNATURE ID) LIST]
    for line in blastOutputFile:

        hit = Database.Hit(line)

        # We only keep the hit if the ratio of the signature-to-alignment
        # length is sufficiently long.
        if (float(hit.alignmentLength) / float(hit.length) < float(0.50)):
            continue

        # Append the signature ID to the existing list of IDs.
        if hit.ID in hits:
            hits[hit.ID].append(hit.reference)

        # Create a new list of signature IDs associated with specific
        # signature ID.
        else:
            hits[hit.ID] = [hit.reference]

    # Write the signatures to output, while maintaining a dictionary of
    # signatures that were previously written to output. This attempts to
    # avoid writing signatures appear to be duplicates or appear to overlap
    # significantly.
    for signature in sortedSignatures:

        # Is the signature close to anything already written to output?
        if(all((ID not in outputSignatures) for ID in hits[signature.ID])):

            # The signature appears to be sufficiently unique.
            # Write the signature to output and update outputed signatures.
            outputSignatures[signature.ID] = signature
            Signature.writeSignature(signature, destination)
Exemplo n.º 13
0
    def reportFilteredCandidates(self):

        outputFile = open(self.filteredLocation, 'w')   # The output.
        candidateSignatures = Signature.readSignatures(
            self.candidatesLocation)                    # The input.
        dictionary = self.exclusionOverallDictionary    # Overall dictionary.

        for ID in candidateSignatures:

            signature = candidateSignatures[ID]

            if ID in dictionary:

                hit = dictionary[ID]

                if (float(hit.alignmentLength) / float(signature.length) <
                        float(self.filterLength)):
                    Signature.writeSignature(signature, outputFile)

            else:
                Signature.writeSignature(signature, outputFile)

        outputFile.close()
Exemplo n.º 14
0
def createJsonLog(signlist):
    data = []
    cpt = 1
    for s in signList:
        data.append({'id': cpt, 'sign': []})
        signat = sign.createSign(s, 100)
        for val in signat:

            data[-1]['sign'].append(val.tolist())
        cpt = cpt + 1
    filename = "session_" + time.strftime("%d-%m-%Y") + '-' + time.strftime(
        "%H-%M-%S") + ".txt"
    with open('Log/' + filename, 'w') as outfile:
        json.dump(data, outfile)
Exemplo n.º 15
0
    def reportFilteredCandidates(self):

        outputFile = open(self.filteredLocation, 'w')   # The output.
        candidateSignatures = Signature.readSignatures(
            self.candidatesLocation)                    # The input.
        dictionary = self.exclusionOverallDictionary    # Overall dictionary.

        for ID in candidateSignatures:

            signature = candidateSignatures[ID]

            if ID in dictionary:

                hit = dictionary[ID]

                if (float(hit.alignmentLength) / float(signature.length) <
                        float(self.filterLength)):
                    Signature.writeSignature(signature, outputFile)

            else:
                Signature.writeSignature(signature, outputFile)

        outputFile.close()
Exemplo n.º 16
0
def compileSignatures(compiledSignatures, signatureLocations):

    fileID = 0

    # -- Read Files -- #
    for location in signatureLocations:

        signatures = Signature.readSignatures(location)

        for signatureID in signatures:

            compileID = str(fileID) + "." + signatureID
            compiledSignatures[compileID] = signatures[signatureID]
            compiledSignatures[compileID].ID = compileID

        fileID += 1

    return compiledSignatures
Exemplo n.º 17
0
def startMiner():
    global tMS, tNF

    # Load public_key
    try:
        my_pu = Signature.loadPublic("public.key")
    except:
        print("No public.key, need to generate?")
        pass

    # Start nonceFinder
    # Start minerServer
    tMS = threading.Thread(target=Miner.minerServer, args=((my_ip, 5005), ))
    tNF = threading.Thread(target=Miner.nonceFinder, args=(wallets, my_pu))
    tMS.start()
    tNF.start()

    return True
Exemplo n.º 18
0
def compileSignatures(compiledSignatures, signatureLocations):

    fileID = 0

    # -- Read Files -- #
    for location in signatureLocations:

        signatures = Signature.readSignatures(location)

        for signatureID in signatures:

            compileID = str(fileID) + "." + signatureID
            compiledSignatures[compileID] = signatures[signatureID]
            compiledSignatures[compileID].ID = compileID

        fileID += 1

    return compiledSignatures
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Custom functions
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=





print "Test creating default signature"
a = Signature()
print "a is ", a.data

print "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="

print "Test setting default signatures with new data."
x = Signature()
print "x is ", x.data
x.data = [0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0]
print "now, x is ", x.data
y = Signature()
print "y is ", y.data
y.data = [0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0]
print "now, y is ", y.data

print "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="

print "Testing signature.weigh()"
print "x is", x.data,"and x.weigh() is", x.weigh()
print "y is", y.data,"and y.weigh() is", y.weigh()

print "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="
Exemplo n.º 20
0
# -*-coding=utf-8
import json
import requests
from Signature import *
import sys
sys.path.append('..')
import log
import logging
log.initLogging('/data/rx/log')
sign = Signature('2', '123', '5321e33f2819487e99a6d52f92dc7cd7',
                 str(int(time.time())))
token = sign.create_token_base64()
decode = sign.decode_base64(token)
contentType = 'application/x-www-form-urlencoded'  # form数据封装到http body中,然后发送到server  name=test&gender=male&[email protected]
header = {'Content-Type': contentType, 'Authorization': 'Bearer %s' % token}


def delete_yidian_ad(feedyidianId):
    boby = {
        "biz": 2,
        "ownerId": 1000001603,
        "adId": feedyidianId,
    }
    try:
        url = 'http://183.131.22.111/v1/ad/delete'
        resp = requests.post(url, data=boby, headers=header)
        resp.close()
        if resp.status_code != 200:
            logging.error('delete_yidian_ad_fail')
            logging.info('delete_yidian_ad_code:' + str(resp.status_code))
            logging.info(resp.content)
Exemplo n.º 21
0
##
def saveTxList(the_list, filename):
    fp = open(filename, "wb")
    pickle.dump(the_list, fp)
    fp.close

    return True



if __name__ == "__main__":
    import threading
    import time
    import Signature

    my_pr, my_pu = Signature.loadKeys("private.key", "public_key")

    # args need to be passed as a TUPLE, in t1
    t1 = threading.Thread(target=minerServer, args=(('localhost', 5005),))
    t2 = threading.Thread(target=nonceFinder, args=(wallets, my_pu))
    
    server = SocketUtils.newServerConnect('localhost', 5006)

    t1.start()
    t2.start()

    pr1, pu1 = Signature.generate_keys()
    pr2, pu2 = Signature.generate_keys()
    pr3, pu3 = Signature.generate_keys()

    Tx1 = Transaction.Tx()
Exemplo n.º 22
0
# -*-coding=utf-8
import json
import requests
from Signature import *
import sys
sys.path.append('..')
import log
import logging
# log.initLogging('/data/rx/log')

sign = Signature('19', '1113', '9798384b2ccb4f2aa372520758b5b8f8',str(int(time.time())))
token = sign.create_token_base64()
decode = sign.decode_base64(token)
contentType = 'application/x-www-form-urlencoded'  # form数据封装到http body中,然后发送到server  name=test&gender=male&[email protected]
header = {
    'Content-Type': contentType,
    'Authorization': 'Bearer %s' % token
}
boby = {
    "biz":2,
    "name":"自动化内部广告",
    "specId":2,
    "adType":12,
    "brandName":"自动化内部广告",
    "copywriter":"aaa",
    "tags":"自动化内部广告",
    "targetUrl":"http://www.baidu.com",
    'materialUrls':'["http://www.vivibride.cn/uploads/allimg/130306/16-130306161552619.jpg"]',
    "price":1000,
    "billingType":2,
    "ownerId":137,
Exemplo n.º 23
0
#SecondMiner

import threading
import Miner
import Signature
import time

my_ip = 'localhost'
wallets = [(my_ip, 5005), (my_ip, 5006)]


my_pr, my_pu = Signature.loadKeys("private.key", "public_key")
# args need to be passed as a TUPLE, in t1
t1 = threading.Thread(target=Miner.minerServer, args=(('localhost', 5007),))
t2 = threading.Thread(target=Miner.nonceFinder, args=(wallets, my_pu))


t1.start()
t2.start()
time.sleep(20)
Miner.StopAll()

t1.join()
t2.join()

print(ord(TxBlock.findLongestBlockchain(Miner.head_blocks).previousBlock.previousBlock.nonce[0]))
print(ord(TxBlock.findLongestBlockchain(Miner.head_blocks).previousBlock.nonce[0]))
print(ord(TxBlock.findLongestBlockchain(Miner.head_blocks).nonce[0]))
Exemplo n.º 24
0
###
###
def sendBlock(ip_addr, blk):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip_addr, TCP_PORT))

    data = pickle.dumps(blk)
    s.send(data)

    s.close()

    return False


if __name__ == "__main__":
    pr1, pu1 = Signature.generate_keys()
    pr2, pu2 = Signature.generate_keys()
    pr3, pu3 = Signature.generate_keys()

    Tx1 = Transaction.Tx()
    Tx1.add_input(pu1, 2.3)
    Tx1.add_output(pu2, 1.0)
    Tx1.add_output(pu3, 1.1)
    Tx1.sign(pr1)

    Tx2 = Transaction.Tx()
    Tx2.add_input(pu3, 2.3)
    Tx2.add_input(pu2, 1.0)
    Tx2.add_output(pu1, 3.1)
    Tx2.sign(pr2)
    Tx2.sign(pr3)
Exemplo n.º 25
0
import WechatLogin
import Portrait
import Signature
import GetLocation
import Gender
WechatLogin.weChatLogin()
Portrait.getPortrait()
Signature.getSignature()
GetLocation.getLocation()
Gender.getGender()
Exemplo n.º 26
0
def loadKeys(pr_file, pu_file):
    return Signature.loadPrivate(pr_file), Signature.loadPublic(pu_file)
Exemplo n.º 27
0
        reprstr = reprstr + "REQD:\n"
        for r in self.reqd:
            reprstr = reprstr + str(r) + "\n"

        reprstr = reprstr + "SIGS:\n"
        for s in self.sigs:
            reprstr = reprstr + str(s) + "\n"

        reprstr = reprstr + "END\n"

        return reprstr


# Testing
if __name__ == "__main__":
    pr1, pul1 = Signature.generate_keys()
    pr2, pul2 = Signature.generate_keys()
    pr3, pul3 = Signature.generate_keys()
    pr4, pul4 = Signature.generate_keys()

    # Correct Transactions
    #Single Transaction between 2 Parties
    Tx1 = Tx()
    Tx1.add_input(pul1, 1)
    Tx1.add_output(pul2, 1)
    Tx1.sign(pr1)
    #Multiple Transaction between 3 Parties
    Tx2 = Tx()
    Tx2.add_input(pul1, 2)
    Tx2.add_output(pul2, 1)
    Tx2.add_output(pul3, 1)
Exemplo n.º 28
0
 def sign(self, private):
     message = self.__gather()
     newSig = Signature.sign(message, private)
     self.sigs.append(newSig)
Exemplo n.º 29
0
def display():
    page = paginate(Signature.all(), 5, request.args.get('start'))
    return render_template('display.html', page=page)
Exemplo n.º 30
0
                type=bool,
                default=False,
                help="if true, will save detected sign on DB")
args = vars(ap.parse_args())

feed = args["feed_db"]
b = False
hasTarget = False

signList = []

if IsDbEmpty():
    feed = True
else:
    targetSign = get_sign_from_db(3, 1)
    targetPattern = sign.create_pattern_from_sign(targetSign)
    hasTarget = True
    """
	User Interface
	Show the sign and its pattern
	"""
    createSignPreview(targetSign)
    createSignPreview(targetPattern, "Pattern")

# if the video argument is None, then we are reading from webcam
if args.get("video", None) is None:
    camera = cv.VideoCapture(0)
    time.sleep(0.25)

# otherwise, we are reading from a video file
else:
Exemplo n.º 31
0
def extract(references, k, inmers, exmers, size, gap, outputFile):

    # references
    if references is None or len(references) < 1:
        raise RuntimeError("There are no references.")

    # 1 <= kmerSize
    if k < 1:
        raise RuntimeError("The k-mer size is out of range.")

    # inclusion k-mers
    if inmers is None or len(inmers) < 1:
        raise RuntimeError("There are no inclusion k-mers.")

    # exclusion k-mers
    if exmers is None:
        raise RuntimeError("There are no exclusion k-mers.")

    # 1 <= size
    if size < 1:
        raise RuntimeError("The signature size is out of range.")

    # 1 <= gap
    if gap < 1:
        raise RuntimeError("The gap size is out of range.")

    # output
    if outputFile is None:
        raise RuntimeError("The output location is not specified.")

    regions = []

    # iterate all references
    for key in references:

        # next reference
        ref = references[key]

        # initialize positions
        start = -1
        end = -1

        # every kmer in reference
        for i in range(len(ref.strip()) - k + 1):

            # k-mer and reverse complement
            kmer = ref[i:i + k]
            reverse = reverseComplement(kmer)

            # kmer is in exclusion sufficiently -- break chain
            if kmer in exmers or reverse in exmers:

                # close the region if started:
                if (end - start) >= size:
                    region = Region(ref[start:end], key, start)
                    regions.append(region)

                # end the region regardless:
                start = -1
                end = -1

            # k-mer is in inclusion sufficiently -- build chain
            # (else -- don't both break and build)
            elif kmer in inmers or reverse in inmers:

                # new chain
                if start < 0 and end < 0:
                    start = i + k - 1
                    end = i + 1

                # hit with something else started
                if start >= 0 and end >= 0:

                    # gap within size? -- yes
                    if (i - (end + 1)) <= gap:
                        end = i + 1

                    # gap within size? -- no
                    else:
                        if (end - start) >= size:
                            region = Region(ref[start:end], key, start)
                            regions.append(region)

                        start = i + k - 1
                        end = i + 1

        if start >= 0 and end > 0 and (end - start) >= size:
            region = Region(ref[start:end], key, start)
            regions.append(region)

    for i in range(len(regions)):

        signature = Signature.Signature(
            i, 0.0, 0.0, 0.0, regions[i].sequence,
            regions[i].reference, regions[i].position)

        Signature.writeSignature(signature, outputFile)
Exemplo n.º 32
0
import SocketUtils
import Transaction
import TxBlock
import pickle
import Signature

break_now = False
head_blocks = [None]
wallets = [('localhost', 5006)]
miners = [('localhost', 5005)]
#miners = [('localhost', 5005), ('localhost', 5007)]
#Transaction Index
tx_index = {}

my_private, my_public = Signature.generate_keys()


def StopAll():
    break_now = True


##
def walletServer(my_addr):
    global head_blocks
    global tx_index

    # Load head_blocks
    try:
        # Save Wallet blocks to different file to Miner: AllBlocks.dat.
        # Otherwise dangerous to read at the same time if you were writing to the same file.
Exemplo n.º 33
0
def extract(references, k, inmers, exmers, size, gap, outputFile):

    # references
    if references is None or len(references) < 1:
        raise RuntimeError("There are no references.")

    # 1 <= kmerSize
    if k < 1:
        raise RuntimeError("The k-mer size is out of range.")

    # inclusion k-mers
    if inmers is None or len(inmers) < 1:
        raise RuntimeError("There are no inclusion k-mers.")

    # exclusion k-mers
    if exmers is None:
        raise RuntimeError("There are no exclusion k-mers.")

    # 1 <= size
    if size < 1:
        raise RuntimeError("The signature size is out of range.")

    # 1 <= gap
    if gap < 1:
        raise RuntimeError("The gap size is out of range.")

    # output
    if outputFile is None:
        raise RuntimeError("The output location is not specified.")

    regions = []

    # iterate all references
    for key in references:

        # next reference
        ref = references[key]

        # initialize positions
        start = -1
        end = -1

        # every kmer in reference
        for i in range(len(ref.strip()) - k + 1):

            # k-mer and reverse complement
            kmer = ref[i:i + k]
            reverse = reverseComplement(kmer)

            # kmer is in exclusion sufficiently -- break chain
            if kmer in exmers or reverse in exmers:

                # close the region if started:
                if (end - start) >= size:
                    region = Region(ref[start:end], key, start)
                    regions.append(region)

                # end the region regardless:
                start = -1
                end = -1

            # k-mer is in inclusion sufficiently -- build chain
            # (else -- don't both break and build)
            elif kmer in inmers or reverse in inmers:

                # new chain
                if start < 0 and end < 0:
                    start = i + k - 1
                    end = i + 1

                # hit with something else started
                if start >= 0 and end >= 0:

                    # gap within size? -- yes
                    if (i - (end + 1)) <= gap:
                        end = i + 1

                    # gap within size? -- no
                    else:
                        if (end - start) >= size:
                            region = Region(ref[start:end], key, start)
                            regions.append(region)

                        start = i + k - 1
                        end = i + 1

        if start >= 0 and end > 0 and (end - start) >= size:
            region = Region(ref[start:end], key, start)
            regions.append(region)

    for i in range(len(regions)):

        signature = Signature.Signature(
            i, 0.0, 0.0, 0.0, regions[i].sequence,
            regions[i].reference, regions[i].position)

        Signature.writeSignature(signature, outputFile)