def main():


    sudoku_files = {"simple": "sudokus/50_simple_sudokus.txt",
                    "easy": "sudokus/50_easy_sudokus.txt",
                    "intermediate": "sudokus/50_intermediate_sudokus.txt",
                    "expert": "sudokus/50_expert_sudokus.txt"}


    #sudoku_files = {"intermediate": "sudokus/50_intermediate_sudokus.txt",
     #               "expert": "sudokus/50_expert_sudokus.txt"}

    # UNCOMMENT FOR TEST
    #sudoku_files = {"expert": "sudokus/50_expert_sudokus.txt"}
    #sudoku_files = {"intermediate": "sudokus/50_intermediate_sudokus.txt"}


    for level, sudoku_file_path in sudoku_files.items():

        collected_data = []

        # determine number of sudokus in file (always 50 in this case)
        with open(sudoku_file_path, 'r') as sudokus_file:
            number_of_sudokus = len(sudokus_file.read().splitlines())


        # UNCOMMENT FOR TEST
        #number_of_sudokus = 5

        # go over each sudoku in the current file
        for sudoku_nr in range(number_of_sudokus):
            print(sudoku_nr, level)

            # write current sudoku from .txt file in DIMACS format
            sud2sat_experiments(sudoku_file_path, sudoku_nr)

            # run the SAT solver on the current sudoku for the give number of replicates
            replicates = []
            for i in range(NR_REPLICATES):

                # create new data storage
                globals.initialize()
                globals.experiment_data["level"] = level
                globals.experiment_data["sudoku_nr"] = sudoku_nr

                startTime = time.time()
                SATsolver("sudoku_DIMACS_format.txt", "sudoku-rules.txt")

                # store runtime
                globals.experiment_data["runtime"] = time.time() - startTime

                #print(globals.experiment_data) # DEBUG

                replicates.append(globals.experiment_data)

            collected_data.append(replicates)

        data_filename = METHOD + "_" + level

        pickle.dump(collected_data, open("data/" + data_filename + ".p", "wb"))
def run():
    globals.initialize()
    G = cargarGrafo('archivos/test1.txt', True)
    testUtils.test("Componente conexa empezando de 0: [0, 1, 2, 3, 4, 6, 5]",
                   componenteConexa(G, 0), [0, 1, 2, 3, 4, 6, 5])
    testUtils.test("Componente conexa empezando de 1: [1, 0, 3, 4, 6, 2, 5]",
                   componenteConexa(G, 1), [1, 0, 3, 4, 6, 2, 5])
    testUtils.test("Componente conexa empezando de 2: [2, 0, 4, 3, 6, 5, 1]",
                   componenteConexa(G, 2), [2, 0, 4, 3, 6, 5, 1])
    testUtils.test("Componente conexa empezando de 3: [3, 1, 4, 6, 0, 2, 5]",
                   componenteConexa(G, 3), [3, 1, 4, 6, 0, 2, 5])
    testUtils.test("Componente conexa empezando de 4: [4, 2, 3, 6, 5, 0, 1]",
                   componenteConexa(G, 4), [4, 2, 3, 6, 5, 0, 1])
    testUtils.test("Componente conexa empezando de 5: [5, 2, 0, 4, 3, 6, 1]",
                   componenteConexa(G, 5), [5, 2, 0, 4, 3, 6, 1])
    testUtils.test("Componente conexa empezando de 6: [6, 3, 4, 1, 2, 5, 0]",
                   componenteConexa(G, 6), [6, 3, 4, 1, 2, 5, 0])
    testUtils.test("Componente conexa empezando de 7: [7, 8]",
                   componenteConexa(G, 7), [7, 8])
    testUtils.test("Componente conexa empezando de 8: [8, 7]",
                   componenteConexa(G, 8), [8, 7])

    testUtils.test("Componentes conexas de G: [[0, 1, 2, 3, 4, 6, 5], [7, 8]]",
                   componentesConexas(G), [[0, 1, 2, 3, 4, 6, 5], [7, 8]])
    globals.initialize()
    G3 = cargarGrafo('archivos/test3.txt', True)
    testUtils.test(
        "Componentes conexas de G3: [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9], [10, 11, 12]]",
        componentesConexas(G3),
        [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9], [10, 11, 12]])
Beispiel #3
0
def run():
    globals.initialize()
    G = cargarGrafo('archivos/test2.txt', True)
    testUtils.test("G es dirigido", G.esDirigido(), True)
    testUtils.test("Nombres e indices", G.getNames(), {
        'A': 0,
        0: 'A',
        'C': 2,
        'B': 1,
        'D': 3,
        1: 'B',
        2: 'C',
        3: 'D'
    })
    testUtils.test("G tiene 4 nodos", G.cantidadNodos(), 4)
    testUtils.test("G tiene 4 aristas", G.cantidadAristas(), 4)
    testUtils.test("G: adyacentes a A = [B]", G.adyacenciasA(0),
                   [1])  # Indices de los nombres
    testUtils.test("G: adyacentes a B = [C]", G.adyacenciasA(1),
                   [2])  # Indices de los nombres
    testUtils.test("G: adyacentes a C = [A]", G.adyacenciasA(2),
                   [0])  # Indices de los nombres
    testUtils.test("G: adyacentes a D = [C]", G.adyacenciasA(3),
                   [2])  # Indices de los nombres
    testUtils.test("G: tiene grado de entradas", G.getGradoEntradas(),
                   [1, 1, 2, 0])
Beispiel #4
0
def smoothMove(mouseCoords, options):
    globals.initialize()
    mouseCt = 0
    # 0: not moving down, 1: started to move down or moving down

    t_start = time.time()
    t_end = time.time() + options.seconds
    lastMouseCTime = time.time()

    while time.time() < t_end:
        try:
            curMouseCTime = time.time()
            curMouseC = mouseCoords.get(True, options.seconds)
            #continue
        except queue.Empty:
            # this will be thrown when the timeout is hit
            #break
            print("mouse except")
            continue
        else:
            # mouse
            if curMouseC[2]:
                pyautogui.click(x=curMouseC[0], y=curMouseC[1])
                continue

            cursorX, cursorY = pyautogui.position()

            #print("Z: ", curMouseC[2])
            # For black spots, or setecting far off back ground object, skip

            # Mouse move
            pyautogui.move((curMouseC[0] - cursorX) / 2,
                           (curMouseC[1] - cursorY) / 2)
Beispiel #5
0
def main():
    globals.initialize()  #Initialize the globals file

    op1 = ["16S", "Ile_AUC", "Ala_GCA", "23S", "5S"]
    op2 = ["16S", "Ala_GCA", "23S", "5S"]
    op3 = ["16S", "Gln_CAA", "Ala_GCA", "23S", "5S", "16S"]

    performMultiSequenceAlignment(op1, op2, op3)
Beispiel #6
0
def main(argv):
    globals.initialize()
    buddy_manager.init_buddy()

    twitch_bot.run()

    #ws_client.stsrv()

    buddy_manager.panic(10)
Beispiel #7
0
def usr_sign_up():
    globals.initialize()
    try:
        with open(\"usrs_info.pickle\", \"rb\") as usr_file:
            usrs_info = pickle.load(usr_file)
    except FileNotFoundError:
        with open(\"usrs_info.pickle\", \"wb\") as usr_file:
            usrs_info = {\"admin\": \"admin\"}
            pickle.dump(usrs_info, usr_file)
Beispiel #8
0
def main():

    banner = """
██╗  ██╗████████╗████████╗██████╗   ██╗███████╗    ██████╗ ███████╗██╗   ██╗███████╗██╗  ██╗███████╗██╗     ██╗
██║  ██║╚══██╔══╝╚══██╔══╝██╔══██╗ ██╔╝██╔════╝    ██╔══██╗██╔════╝██║   ██║██╔════╝██║  ██║██╔════╝██║     ██║
███████║   ██║      ██║   ██████╔╝██╔╝ ███████╗    ██████╔╝█████╗  ██║   ██║███████╗███████║█████╗  ██║     ██║
██╔══██║   ██║      ██║   ██╔═══╝██╔╝  ╚════██║    ██╔══██╗██╔══╝  ╚██╗ ██╔╝╚════██║██╔══██║██╔══╝  ██║     ██║
██║  ██║   ██║      ██║   ██║   ██╔╝   ███████║    ██║  ██║███████╗ ╚████╔╝ ███████║██║  ██║███████╗███████╗███████╗
╚═╝  ╚═╝   ╚═╝      ╚═╝   ╚═╝   ╚═╝    ╚══════╝    ╚═╝  ╚═╝╚══════╝  ╚═══╝  ╚══════╝╚═╝  ╚═╝╚══════╝╚══════╝╚══════╝
                                                                                                         By: 3v4Si0N
    """
    print(Color.F_Yellow + banner + Color.reset)
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('host', help='Listen Host', type=str)
    parser.add_argument('port', help='Listen Port', type=int)
    parser.add_argument('--ssl',
                        default=False,
                        action="store_true",
                        help='Send traffic over ssl')
    parser.add_argument('--autocomplete',
                        default=False,
                        action="store_true",
                        help='Autocomplete powershell functions')
    args = parser.parse_args()

    try:
        HOST = args.host
        PORT = args.port
        server = HTTPServer((HOST, PORT), myHandler)
        print(time.asctime(), 'Server UP - %s:%s' % (HOST, PORT))
        globals.initialize()

        if (args.ssl):
            cert = certificate.Certificate()
            if ((cert.checkCertPath() == False)
                    or cert.checkCertificateExpiration()):
                cert.genCertificate()
            server.socket = ssl.wrap_socket(server.socket,
                                            certfile='certificate/cacert.pem',
                                            keyfile='certificate/private.pem',
                                            server_side=True)

        if (args.autocomplete):
            globals.AUTOCOMPLETE = True
        else:
            readline.set_completer_delims(" ")
            readline.parse_and_bind("tab: complete")

        server.serve_forever()

    except KeyboardInterrupt:
        print(' received, shutting down the web server')
        server.socket.close()
def findMotif(sequences, motifLength, iterations):
        # initialize global sequence and motif variables
        globals.initialize(sequences, motifLength)

        # choose a random motif position for each unchosen sequence
        positions = chooseMotifPositions()

        # initialize iteration variables
        currentInformationContent = 0.0
        bestInformationContent = 0.0
        profileMatrix = []
        probabilityMatrix = []
        positionWeights = []
        normalizedPositionWeights = []
        bestPositions = []
        bestProfileMatrix = []

        for iteration in range(0, iterations):
                for unchosenSequenceIndex in range(0, len(sequences)):
                        # count residue and background occurences for each position for all unchosen sequences
                        profileMatrix = profile_matrix.createProfileMatrix(positions, unchosenSequenceIndex)

                        # determine residue and background probabilities
                        probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix)

                        # calculate weight for each possible motif position in the chosen sequence
                        positionWeights = position_weights.calculatePositionWeights(probabilityMatrix)

                        # normalize position weights
                        normalizedPositionWeights = position_weights.normalizePositionWeights(positionWeights)
                        
                        # randomly choose position based on normalized probabilities
                        positions[unchosenSequenceIndex] = position_weights.choosePosition(normalizedPositionWeights)
                        
                        # recalculate profile and probability matrix
                        profileMatrix = profile_matrix.createProfileMatrix(positions, -1)
                        probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix)

                        # calculate information content of current sample
                        currentInformationContent = probability_matrix.calculateInformationContent(probabilityMatrix, positions)
                        
                        # update best sample if current has greater information content
                        if currentInformationContent > bestInformationContent:
                                bestInformationContent = currentInformationContent
                                bestPositions = list(positions)
                                bestProfileMatrix = list(profileMatrix)
        
                        # update unchosen sequence value for next iteration
                        if unchosenSequenceIndex < (len(sequences) - 1):
                                globals.unchosenSequence = sequences[unchosenSequenceIndex + 1]
        
        return [bestPositions, bestProfileMatrix, bestInformationContent]
Beispiel #10
0
async def update_stats():
    globals.initialize()
    await bot.wait_until_ready()

    while not bot.is_closed():
        try:
            if globals.err:
                with open("log/stats.txt", "a") as f:
                    f.write(
                        f"Time: {int(time.time())}, Command: {globals.last_cmd}, Error message: {globals.err_msg}\n"
                    )
                globals.err = False
            await asyncio.sleep(5)

        except Exception as e:
            print(e)
            await asyncio.sleep(5)
def main():


    # if len(sys.argv) != 2:
    #     sys.stdout.write("Usage: SAT -Sn inputfile\n " #TODO geef juiste Usage info
    #                      "*n = 1 for DP\n*n = 2 for MOM\n*n = 3 for JW *n = 4 for x-wing\n*n = 5 for y-wing")
    #     sys.exit(1)
    #TODO make code run with commandline


    globals.initialize()

    startTime = time.time()

    SATsolver("output.txt", "sudoku-rules.txt")
    print('The script took {0} seconds!'.format(time.time() - startTime))
    print(globals.experiment_data['splits'])
def beginProcessing():
    done = deleteFrames()
    globals.initialize()
    print(done)
    global filename
    filename = ""
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            processing()
    return redirect(url_for('displayResult'))
def main():

    # failsafe, to check if user inserted correct input
    if ARGS.sudoku_files == None:
        raise ImportError(
            "Please insert a .txt file that consists of a concatenation of the sudoku-rules \
                          and the sudoku in DIMACS format (in that order)")

    # check for heuristic input
    if ARGS.heuristic == "S1":
        print("Running DP algorithm.")
    elif ARGS.heuristic == "S2":
        print("Running DP algorithm with JW heuristic.")
    elif ARGS.heuristic == "S3":
        print("Running DP algorithm with MOM heuristic.")
    else:
        raise ImportError(
            "Please insert any of these options to run a heuristic: S1, S2, S3"
        )

    # check for strategy input
    if ARGS.strategy == "naked-pairs":
        print("Using naked-pairs human strategy.")
    elif ARGS.strategy == "naked-triples":
        print("Using naked-triples human strategy.")
    elif ARGS.strategy == "x-wings":
        print("Using x-wing human strategy.")
    elif ARGS.strategy == "all":
        print("Using all human strategies.")
    elif ARGS.strategy == None:
        pass
    else:
        raise ImportError(
            "Please insert any of these options to run a human-strategy: naked-pairs, naked-triples, \
                           x-wings, all")

    globals.initialize()
    SATsolver(None, ARGS.sudoku_files, ARGS)
Beispiel #14
0
    #Case 3: Only the right sibling exists so return it
    elif rightSibling != None and rightSibling.genomeFragments != None and len(
            rightSibling.genomeFragments) > 0:
        return rightSibling
    #Case 4: None of the siblings exist so return NULL
    else:
        return None


######################################################
#                       main
######################################################
print('Starting application...')
startTime = time.time()

globals.initialize()  #Initialize the globals file

if globals.printToConsole:
    print('Reading newick tree from file: %s...' % (newickFileName))
newickTree = Phylo.read(newickFileName, 'newick')

if globals.printToConsole:
    Phylo.draw(newickTree)

globals.strains = strains  #Assign pointer to the global strains array so we can access it anywhere
createFile(outputFileName, newickTree)  #Creates file where data will be output

#Traverses the newick tree recursively reconstructing ancestral genomes
if globals.printToConsole:
    print('Traversing newick tree...')
result = traverseNewickTree(newickTree.clade, None)
Beispiel #15
0
import globals
from Case import Case
from Grid import Grid
from Visual import Visual

globals.initialize()

grid = Grid([[Case() for i in range(globals.sizeOfGrid)]
             for j in range(globals.sizeOfGrid)])

visual = Visual(grid)
Beispiel #16
0
def main():
    globals.initialize()  #Initialize the globals file

    global newickFileName
    global outputFileName
    global testFileName

    if len(sys.argv) != 3:
        print "WARNING: Must provide a Newick tree and test folder name. Exiting..."
        sys.exit(0)

    newickFileName = sys.argv[1]
    if newickFileName == "tree2LeafNeighbour.dnd":
        outputFileName = sys.argv[2] + "/ApplicationNeighbourOutput.txt"
    else:
        outputFileName = sys.argv[2] + "/ApplicationOutput.txt"
    testFileName = sys.argv[2] + '/'

    print('Starting application...')
    startTime = time.time()

    if globals.printToConsole:
        print('Reading newick tree from file: %s...' % (newickFileName))
    newickTree = Phylo.read(newickFileName, 'newick')
    if globals.printToConsole:
        Phylo.draw(newickTree)

    globals.strains = strains  #Assign pointer to the global strains array so we can access it anywhere
    createFile(outputFileName,
               newickTree)  #Creates file where data will be output

    #Traverses the newick tree recursively reconstructing ancestral genomes
    if globals.printToConsole:
        print('Traversing newick tree...')
    result = traverseNewickTree(newickTree.clade, None)

    endTime = time.time()
    totalTime = endTime - startTime

    #Output ancestral genome to console
    if globals.printToConsole:
        print('This is the root ancestral genome!')

    root = newickTree.clade
    rootGenome = []
    if newickFileName == "tree2LeafNeighbour.dnd":
        if len(root.clades) == 2:
            child = root.clades[0]
            if len(child.clades) != 2:
                child = root.clades[1]
                neighbour = root.clades[0]
            else:
                neighbour = root.clades[1]
            if child.name != None and len(child.name) > 0:
                filteredList = iter(
                    filter(lambda x: x.name == child.name, strains))
                foundStrain = next(filteredList, None)
                if foundStrain != None:
                    ancestralFragments = foundStrain.genomeFragments
                    rootGenome = ', '.join(fragment.originalSequence
                                           for fragment in ancestralFragments)

            with open(testFileName + "appNeighbourRoot.txt", "w+") as f:
                f.write(rootGenome)
            neighbour.name = ''
            child.name = ''
    else:
        if root.name != None and len(root.name) > 0:
            filteredList = iter(filter(lambda x: x.name == root.name, strains))
            foundStrain = next(filteredList, None)
            if foundStrain != None:
                ancestralFragments = foundStrain.genomeFragments
                rootGenome = ', '.join(fragment.originalSequence
                                       for fragment in ancestralFragments)

        with open(testFileName + "appRoot.txt", "w+") as f:
            f.write(rootGenome)

    if globals.printToConsole:
        #Output newick tree after the ancestors have been added to it
        Phylo.draw(newickTree)

    #Need to traverse tree to ouput appropriate content to file
    newickTree.clade.name = ''  #Make sure that the output for the root is not output
    traverseNewickTreeAndOutputToFile(newickTree.clade)

    #Output the totals for the computation to console and file
    outputTotalsToFile(outputFileName, totalTime)

    #TODO compute lineage
    #target = 'NC_014019'
    #print('Computing lineage cost for: %s' % (target))
    #lineageCost = computeLineageCost(newickTree.clade, target, None)
    #if lineageCost != None:
    #print('Successfully found and computed the lineage for: %s' % (target))

    #Output Bar graphs of each event
    if globals.printToConsole:
        createBarGraph(globals.deletionSizeCounter,
                       'Distribution of Deletions')
        createBarGraph(globals.duplicationSizeCounter,
                       'Distribution of Duplications')
        createBarGraph(globals.inversionSizeDistributionCounter,
                       'Distribution of Inversions')
        createBarGraph(globals.transpositionSizeDistributionCounter,
                       'Distribution of Transpositions')
        createBarGraph(globals.invertedTranspositionSizeDistributionCounter,
                       'Distribution of Inverted Transpositions')

    print('Total time (in seconds): %s' % (totalTime))
    print('Ending application...')
Beispiel #17
0
def voice():
    excel.popen1()
    globals.initialize()
    import PyAutoGUI
    winsound.PlaySound(\"audio/vcmode.wav\", winsound.SND_FILENAME)
    while globals.var==1:
        r = sr.Recognizer()
        try:
            with sr.Microphone() as source:
                print(\"Speak:\")
                r.adjust_for_ambient_noise(source)
                audio = r.listen(source, timeout=10,phrase_time_limit=3)

            data = r.recognize_google(audio, language='zh-TW')
            print(\"您所說的話: \" + data )

            def listen():
                try:
                   with sr.Microphone() as source:
                        print(\"請說出您的帳戶名稱:\")
                        winsound.PlaySound(\"audio/username.wav\", winsound.SND_FILENAME)
                        r.adjust_for_ambient_noise(source)
                        audio = r.listen(source, timeout=20, phrase_time_limit=3)
                        speak = r.recognize_google(audio,language='zh-EN')
                        print(\"User name: \" + speak)
                        PyAutoGUI.write(speak)
                        winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
                except:
                    return listen()

            if '註冊' in data:
                PyAutoGUI.sign_up()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '錄音' in data:
                PyAutoGUI.record()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '開始' in data:
                PyAutoGUI.recording()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '波形' in data:
                PyAutoGUI.wave()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '關閉' in data:
                PyAutoGUI.close()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '寫入' in data:
                PyAutoGUI.insert()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '結束' in data:
                PyAutoGUI.record_finish()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '訓練' in data:
                PyAutoGUI.train()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '完成' in data:
                PyAutoGUI.sign_finish()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '驗證' in data:
                PyAutoGUI.user_ver()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '登入' in data:
                globals.var==0
                PyAutoGUI.log_in()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
                excel.pclose()
            elif '確定' in data:
                PyAutoGUI.confirm()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
            elif '使用者' in data:
                PyAutoGUI.user_name()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
                listen()
            elif '帳號' in data:
                PyAutoGUI.account()
                winsound.PlaySound(\"audio/dong.wav\", winsound.SND_FILENAME)
                listen()

        except sr.UnknownValueError:
                print(\"Could not understand audio\")

        except sr.RequestError as e:
            print(\"Could not request results; {0}\".format(e))

        except:
            pass
Beispiel #18
0
def procPip(frames, mouseCoords, options):

    globals.initialize()

    # Setup processing directories for pool of processes
    # Setup tmp image dir
    try:
        if (not os.path.isdir(globals.tmpDir)):
            os.mkdir(globals.tmpDir)
    except OSError as error:
        print("Could not make: " + globals.tmpDir)

    # Setup temp dir for pool of processes
    tmpImageDir = [
        globals.tmpDir + "proc_" + str(i) + "/"
        for i in range(globals.threadPoolSize)
    ]
    for i in range(globals.threadPoolSize):
        #print (tmpImageDir[i])
        try:
            if (not os.path.isdir(tmpImageDir[i])):
                os.mkdir(tmpImageDir[i])
        except OSError as error:
            print("Could not make dir: " + tmpImageDir[i])

    #pPool = multiprocessing.Pool(globals.threadPoolSize)
    backArr, backgroundZValue = getBackground(frames, options, globals.tmpDir)
    backgroundZValue -= globals.zNoiseThr

    zChangeState = 0
    zMoveDownStart = 0
    zMoveDownEnd = zMoveDownStart  # Both equal is reset state
    lx, ly, lz = (0, 0, backgroundZValue + 100)
    ct = 0

    t_end = time.time() + options.seconds
    while time.time() < t_end:
        #listOfArgs = []
        #ct += globals.threadPoolSize
        #ct += 1
        try:
            # try to retrieve an item from the queue.
            # this will block until an item can be retrieved
            # or the timeout of 1 second is hit
            item = frames.get(True)

            #for fId in range(globals.threadPoolSize):
            #    item = frames.get(True, 1)
            #    listOfArgs.append([tmpImageDir[fId], item, backArr, backgroundZValue, options.debug, ct+fId, globals.xM, globals.yM])

        except queue.Empty:
            # this will be thrown when the timeout is hit
            #print("pipeline except")
            continue
        else:

            # stTime = time.time()
            (x, y, z) = pipeline(globals.tmpDir, item, backArr,
                                 backgroundZValue, options.debug, ct,
                                 globals.xM, globals.yM)
            currX, currY = pyautogui.position()
            #print ("curMouseC, lastMouseC :", (x, y, z), (lx, ly, lz))
            #curMouseCArray = pPool.starmap(pipeline, listOfArgs)
            #print ("curMouseCArray :", curMouseCArray)
            #print("Pip time: ", (time.time() - stTime))
            #for (x, y, z) in curMouseCArray:
            # if any of x, y or z in None, skip the frame
            if x is None or y is None or z is None:
                continue

            # Got a valid frame, first check whether click is being made, if clicking, stablize x, y and do not move the cursor
            dZ = z - lz
            zMoveDiff = zMoveDownEnd - zMoveDownStart
            #print(dZ)

            if (dZ > globals.zMoveDownThr):  # mouse is moving down
                #print("Mouse moving down. frames: " + str(zChangeState) + " Z: ", str(z) + " dZ: " + str(dZ))
                if (zMoveDiff == 0):
                    zMoveDownStart = lz
                    zMoveDownEnd = z  # z - lz must be postive as dZ is positive, so this loop will not be executed next time
                    #print("Click down started. Start Z: " + str(zMoveDownStart) + " End Z: " + str(zMoveDownEnd))
                else:
                    # It is moving down, record last coordintates
                    zMoveDownEnd = z
                    #print("Click down continued. Start Z: " + str(zMoveDownStart) + " End Z: " + str(zMoveDownEnd))

                lz = z  # keep lx and ly unchanged to stabilize cursor
                continue  # click stated or in progress so check next frame without moving mouse
            elif (zMoveDiff > globals.clickZThr):
                # Mouse is not moving down now but had moved right before by click threshold
                print("Clicked. distance: " + str(zMoveDiff))
                mouseCoords.put(
                    (lx, ly,
                     True))  # Use lx, ly to keep mouse where click was started
                #lx, ly, lz = x, y, z # update to new location to keep subsequent movement smooth
                lx, ly, lz = currX, currY, z
                # Reset and tracking of downward movement
                zMoveDownEnd = zMoveDownStart
                continue

            # If control come here, mouse is not moving down and it was not a click
            # Reset and tracking of downward movement
            zMoveDownEnd = zMoveDownStart
            dX = abs(x - lx)
            dY = abs(y - ly)
            # ignore jitter and out of range
            if (dX < globals.dXMin or dX > globals.dXMax or dY < globals.dYMin
                    or dY > globals.dYMax):
                #print("dX and dY out of range or jittering")
                continue

            if (z == 0) or (z > backgroundZValue):
                #print("Put prematurely")
                # do not update z
                #lx, ly = x, y
                lx, ly = currX, currY
            else:
                #lx, ly, lz = x, y, z
                lx, ly, lz = currX, currY, z
            # no click, just move mouse
            #print("x:" + str(x) + "y: " + str(y))
            mouseCoords.put((x, y, False))
Beispiel #19
0
def main(token: str, language: str, options_path: str):
    """Main Milton subroutine.

    Loads all modules, memory, and handles incoming messages.
    Also detects and responds to changes in user and guild joining.

    Args:
        token: str
        Discord token to allow logging in.
        language: str
        Default language to use in guilds where no language setting is applied.
        options_path: str
        Path to options.json file

    Returns:
        None
    """
    print("This is Milton, and I'm initializing.")
    client = ds.Client()
    # Initialize global variables and commands
    G.initialize(options_path)
    commands.make_commands()
    achieves.make_achievements()
    idle.make_commands()
    items.make_commands()

    # Completed loading of Milton message + preliminary activity
    @client.event
    async def on_ready():
        """Preliminary activity

        Checks all guilds for all users and initializes them in memory.
        """
        print('We have logged in as {0.user}.'.format(client))
        print('I will be speaking "{0}" as default.'.format(language))
        print("Looking for new members/guilds while I was away...")
        # We search all guilds and users Milton can see and initialize them.
        i = 0
        for guild in client.guilds:
            # Add new guilds
            if str(guild.id) not in G.GLD.keys():
                default_dict = {"language": language}
                G.GLD[str(guild.id)] = mun.DefaultMunch().fromDict(default_dict, 0)
            tools.save(G.OPT.guilds_path, G.GLD)
            # Add new members
            for member in guild.members:
                if str(member.id) not in G.USR.keys():
                    i += 1
                    G.USR[str(member.id)] = mun.DefaultMunch(0)
                G.USR[str(member.id)].name = member.name
        tools.save_users()
        print(f"Found {i} new members")
        game = ds.Game("with myself.")  # Update "playing" message, for fun.
        print("Ready!")
        await client.change_presence(status=ds.Status.online, activity=game)

    # On message
    @client.event
    async def on_message(message):
        """Handles parsing and responding to all incoming messages Milton can see."""
        # Special checks on the message before parsing commands
        # Don't reply to yourself
        if message.author == client.user:
            return

        # Update locale for current guild
        G.update_loc(G.GLD[str(message.guild.id)].language)

        # Randomly throw out an insult, for fun
        if message.content.startswith(G.OPT.prefix) is False and\
                G.OPT.insult_threshold is not False and\
                message.author != client.user:
            if G.OPT.insult_threshold == random.randint(0, G.OPT.insult_threshold):
                await message.channel.send(tools.get_random_line(G.LOC.randomInsult_path))

        # Don't compute further if it isn't directed to Milton.
        if message.content.startswith(G.OPT.prefix) is False:
            return

        # Count the number of times this person typed a command.
        tools.update_user(user_id=message.author.id, stat="commandCount", increase=1)

        # Update total joules (remove in a while?):
        if G.USR[str(message.author.id)].lifetime_joules == 0 and \
                G.USR[str(message.author.id)].joules > 0:
            stats = idle.make_all_stats(str(message.author.id))
            min_joules = G.USR[str(message.author.id)].joules
            for stat in stats.values():
                min_joules += stat.recalculate_price(-1)
            tools.update_user(str(message.author.id), stat="lifetime_joules", set=min_joules)

        # Run normal commands
        for command in G.COMMANDS:
            if command.permission(message) is True:
                if command.where == "channel":
                    for string in command.logic(message):
                        await message.channel.send(string)
                elif command.where == "user":
                    if message.author.dm_channel is None:
                        await message.author.create_dm()
                    for string in command.logic(message):
                        await message.author.dm_channel.send(string)
                    await message.delete()

        # Achievements that contain strings:
        if message.content.startswith(G.OPT.prefix + "^^vv<><>ba"):
            tools.update_user(str(message.author.id), "konami", set=True)
            await message.delete()

        if message.content.startswith(G.OPT.prefix + "cheat"):
            tools.update_user(str(message.author.id), "cheat", set=True)
            await message.delete()

        # Check Achievements
        achieve_intro = True
        for achieve in G.ACHIEVES:
            if achieve.status == "legacy":
                continue
            if G.USR[str(message.author.id)].epoch < achieve.epoch:
                continue
            if achieve.check_trigger(str(message.author.id)) is True:
                out = tools.MsgBuilder()
                if achieve_intro:
                    out.add(G.LOC.msg.on_award)
                    achieve_intro = False
                out.add(achieve.award(message.author.id))
                for string in out.parse():
                    await message.channel.send(string)

    @client.event
    async def on_member_join(member):
        """Handles when new members join guilds"""
        # Update locale for current guild
        G.update_loc(G.GLD[str(member.guild.id)].language)
        if member.bot is True:
            # We don't do anything with bot accounts
            return

        for channel in member.server.channels:
            if str(channel.name).lower() in ['casa', 'general']:
                line = tools.get_random_line(G.LOC.hello_path)
                await channel.send(line.format(member.name))

        if member.id not in G.USR.keys():
            G.USR[str(member.id)] = mun.DefaultMunch(0)
            G.USR[str(member.id)].name = member.name
            tools.save_users()

    @client.event
    async def on_guild_join(guild):
        """Handles when Milton joins a guild"""
        if str(guild.id) not in G.GLD.keys():
            default_dict = {"language": language}
            G.GLD[str(guild.id)] = mun.DefaultMunch().fromDict(default_dict, 0)
        tools.save(G.OPT.guilds_path, G.GLD)
        # Add new members
        for member in guild.members:
            if str(member.id) not in G.USR.keys():
                G.USR[str(member.id)] = mun.DefaultMunch(0)
            G.USR[str(member.id)].name = member.name
        tools.save_users()

    async def generate_titan():
        """Subroutine to check when to spawn titans"""
        await client.wait_until_ready()
        while True:
            now = time.time()
            to_hour = G.OPT.titanhours * 3600 - (now % 3600)
            logger.info("I checked when to spawn titans.")
            logger.info(f"I'll check when to spawn titans again in {to_hour / 60} minutes.")

            for guild_id, guild in G.GLD.items():
                if guild.titan_status is not True:
                    G.update_loc(G.GLD[str(guild_id)].language)
                    level = idle.spawn_titan(guild_id)
                    titan = idle.Titan(level)
                    channel = client.get_channel(guild.notification_channel)
                    if guild.notification_channel != 0:
                        await channel.send(G.LOC.msg.generated_titan.format(
                            level, tools.fn(titan.hp), round((1 - titan.armor) * 100, 2)
                        ))
            await asyncio.sleep(to_hour)

    client.loop.create_task(generate_titan())
    client.run(token)
    return None
Beispiel #20
0
def deleteFrames():
    folder = 'E:/BE PROJECT/Flask/static/frames'
    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        #print(file_path)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
                #elif os.path.isdir(file_path): shutil.rmtree(file_path)
        except Exception as e:
            print(e)
    return("Frames Deleted")
    
if __name__ == '__main__':
    initialize()
    result1 = VideoToFrames('query')
    result2 = createFeatureVectors()
    result3 = AutomateDBParameters()
    result4 = generateKeyFrames()
    yoloR = yoloCall()
    print(globals.keys)
    print(globals.values2)
    result5 = DatabaseVideoIDExtraction()
    img = generateClusterImages() #list of all images to generate thumbnails
    #print(img)
    #print("generateClusterImages done")
    result7 = createThumbnail(img)
    print( globals.df_storeImageThumbnailQuery )
    result6 = findSimilarityMatrix()
    
Beispiel #21
0
from gui import GUI
from gui import print_message
from gui import InventoryMenu

from random import randint

import colors

from ressources import resources_init

#import Profile
import cProfile
import pstats

# Initialize globals
g.initialize()

# Initialize Clock
FPS = 120  # 60
g.clock = pygame.time.Clock()
"""PERFORMANCE"""
# TODO PFERFORMANCE: map blit
# TODO PFERFORMANCE: gui
# TODO PFERFORMANCE: append to list?
# Are you repeatedly adding sprites to a list without realising?
# Maybe you're creating a new font object everytime in a loop?
# Maybe you're not killing sprites that are off-screen?

#Well, you could try rendering in layers, and keeping some layers constant.
# Basically, you blit your background images onto one common surface once*
# and then just blit the common surface to the window surface;