Esempio n. 1
0
def main():
    quantum = int(input("Digite el quantum: \n"))
    OS.opSystem.setQuantum(quantum)
    print('Set quantum to {}\n'.format(OS.opSystem.getQuantum()))
    p1PHilos = getPosiblesHilos('p0')
    p2PHilos= getPosiblesHilos('p1')
    hilosP1 = [int(i) for i in input('Digite el id (numero) de los hilos que desea ejecutar para procesador 0, separados por un espacio.\nHilos: {}\n'.format(p1PHilos)).strip().split()]
    dir1 = [p1PHilos[i] for i in hilosP1]
    hilosP2 = [int(i) for i in input('Digite el id (numero) de los hilos que desea ejecutar para procesador 0, separados por un espacio.\nHilos: {}\n'.format(p2PHilos)).strip().split()]
    dir2 = [p2PHilos[i] for i in hilosP2]
    p1 = Processor.Processor(2, 24, 24, 4, 0, 0)
    p2 = Processor.Processor(1, 16, 24, 4, 0, 1)
    getHilos(dir1, p1)
    getHilos(dir2, p2)
    
    # getHilos(dir1, p1)
    # getHilos(dir2, p2)
    procs = [p1, p2]
    #procs = [p2]
    cores = []
    for proc in procs:
        for core in proc.cores:
            cores.append(core)
    cores[0].setNeighborProcessors(p2)
    cores[1].setNeighborProcessors(p2)
    cores[2].setNeighborProcessors(p1)
    for core in cores:
        core.start()
    for core in cores:
        core.join()
    #for p in procs:
    #    for d in p.directory.directory:
    #        print(d)
    #for core in cores:
    #    for c in core.dataCache.cache:
    #        print(c)
    print('Gathering contexts for printing...')
    print('Formatting registers for output...')
    print('Done!\n')

    ppSharedMem = formatSharedMemForOutput(p1.sharedMemory.memory)
    print('SharedMem: {} \n'.format(ppSharedMem))
    ppCacheCore0P0 = formatCacheForOutput(p1.cores[0].dataCache)
    ppCacheCore1P0 = formatCacheForOutput(p1.cores[1].dataCache)
    ppCacheCore0P1 = formatCacheForOutput(p2.cores[0].dataCache)
    print('Data Cache for Core 0 in P0: {}\n'.format(ppCacheCore0P0))
    print('Data Cache for Core 1 in P0: {}\n'.format(ppCacheCore1P0))
    print('Data Cache for Core 0 in P1: {}\n'.format(ppCacheCore0P1))
    print('Directory: {}\n'.format(p1.directory.directory))
    for proc in procs:
        
        for context in proc.finished:
            
            registers = context['registers']
            ppRegisters = {}
            for i in range(len(registers)):
                if registers[i] != 0:
                    ppRegisters['R{}'.format(i)] = registers[i]
            print('Thread ID: {0}\n finalPC: {1}\n registers: {2}\n totalCicles: {3}\n totalTime: {4}\n'
                    .format(context['id'], context['pc'], ppRegisters, context['cicles'], context['elapsedTime']))
Esempio n. 2
0
def data_testsave(input_dir, output_dir):
    filename = 'TestSet.tfrecord'
    writer = tf.python_io.TFRecordWriter(os.path.join(output_dir + filename))
    for folder in os.listdir(input_dir):
        print('****************' + folder + '***********************')
        img_path = input_dir + '/' + folder + '/Image/'
        lbl_path = input_dir + '/' + folder + '/Label/'
        for imgname in os.listdir(img_path):
            lblname = imgname[:-3] + 'bmp'
            print(imgname + "," + lblname)
            img = cv2.imread(img_path + imgname)
            lbl = cv2.imread(lbl_path + lblname)
            #imgs =  np.dot(img[...,:3], [0.299, 0.587, 0.114])
            imgs = pr.Intensity(img)
            lbls = np.dot(lbl[..., :3], [0.299, 0.587, 0.114]) // 255
            lbls = lbls.astype('uint8')

            img_batch = pr.down_sample(imgs).astype('float64')
            lbl_batch = pr.down_sample(lbls)
            img_batch_norm = pr.contrast_normalization(img_batch)

            example = tf.train.Example(features=tf.train.Features(
                feature={
                    'img_raw': _bytes_feature(img_batch_norm.tostring()),
                    'gt_raw': _bytes_feature(lbl_batch.tostring())
                }))
            writer.write(example.SerializeToString())
    writer.close()
Esempio n. 3
0
def system_init():
    processor_temp = Processor()
    resource_temp = Resource()
    processor_temp.create_process('init', 0)
    for x in processor_temp.get_running_list():
        print(x + " ", end='')
    return processor_temp, resource_temp
Esempio n. 4
0
 def test_Response(self):
     questions, responses = Preprocessor.load_corpus()
     question_list = Processor.vectorizer(questions)
     self.assertEqual(
         Processor.process("what is a star?", question_list, responses),
         "Stars are mostly made of hydrogen and helium\n")
     self.assertEqual(Processor.process("Hello", question_list, responses),
                      "Hello! I am Nova.\n")
     self.assertEqual(
         Processor.process("What is your job?", question_list, responses),
         "I teach you about astronomy and geography!\n")
Esempio n. 5
0
 def __init__(self, database):
     self.root = Tk()
     self.root.attributes("-zoomed", True)
     self.root.title("Physik-Formelsammlung")
     guiSetup.set_up(self.root, self)
     self.database = database
     self.processor = Processor()
     self.listbox_items = list()
     self.update_solution()
     self.standard_dict = {"Name": [1, 50], "Definition": [10, 50], "Weiteres": [3, 50]}
     self.size_mapping = {**self.standard_dict, **{"Formelzeichen (mathtext)": [1, 50], "Formelzeichen (sympy)":
                                                   [1, 50], "Einheit": [1, 50], "Gleichung": [2, 50]}}
Esempio n. 6
0
def getInfo():
    try:
        response = vk.method(
            'users.get', {
                'user_ids':
                Fixer.UserID,
                'fields':
                'about,activities,bdate,books,career,city,connections,contacts,counters,country,domain,education,exports,home_town,interests'
            })
        if response:
            user = response[0]
            Fixer.Name = user['first_name']
            Fixer.Family = user['last_name']
            if 'about' in user:
                Fixer.About = user['about']
            if 'activities' in user:
                Fixer.Interests.append(user['activities'])
            Fixer.BirthDay = user['bdate']
            if 'books' in user:
                Fixer.Interests.append(user['books'])
            if 'career' in user:
                if 'company' in user['career']:
                    Fixer.Contacts['компания'] = user['career']['company']
                if 'position' in user['career']:
                    Fixer.Contacts['вакансия'] = user['career']['position']
            if 'city' in user:
                Fixer.Contacts['город'] = user['city']['title']
                Processor.coordinates(user['city']['title'])
                Fixer.X = Fixer.Coords[0]
                Fixer.Y = Fixer.Coords[1]
            if 'connections' in user:
                for connect in user['connections']:
                    Fixer.Contacts[connect] = user['connections'][connect]
            if 'contacts' in user:
                if 'mobile_phone' in user['contacts']:
                    Fixer.Phone = user['contacts']['mobile_phone']
                if 'home_phone' in user['contacts']:
                    Fixer.Contacts['телефон'] = user['contacts']['home_phone']
            Fixer.Things.append('Друзья: ' + str(user['counters']['friends']))
            Fixer.Things.append('Группы: ' + str(user['counters']['pages']))
            Fixer.Contacts['страна'] = user['country']['title']
            Fixer.Contacts['VK'] = user['domain']
            if 'interests' in user:
                m = Fixer.getparams(user['interests'], ', ')
                for im in m:
                    Fixer.Interests.append(im)
            return True
    except Exception as e:
        print('Ошибка доступа к информации пользователя ' + str(Fixer.UserID) +
              ': ' + str(e))
        return False
Esempio n. 7
0
def main():
    level = '3-4'
    times = 20
    # 点击出征
    processor.expedition()
    # 进入关卡
    processor.first_enter_level(level)
    # 切换为自律模式
    processor.switch_to_auto()
    for i in range(times):
        # 作战中
        processor.fighting()
        #
        processor.enter_level(level)
    def test_operand_forwarding_to_MEM(self):
        # Expected output:
        # R4 = 8
        # R1 <- 8
        # R2 <- (R1) = 999
        # (R1) <- R2 = 999
        instruction_list = [
            'I ADDI R5 R5 1234',
            'I ADDI R2 R2 3',
            'I ADDI R3 R3 5',
            'I ADDI R4 R4 8',
            'I ADDI R6 R6 9',
            'R ADD  R2 R3 R1',
            'I LW  R1 R2 0',
            'I SW  R1 R2 0',
        ]
        instruction_list = [
            instruction_string.split()
            for instruction_string in instruction_list
        ]
        memory = Memory.Memory(instruction_list)
        processor = Processor.Processor(memory, 0)

        processor.data_memory[8] = 999

        processor.start()
        print 'CPI: ', processor.getCPI()
        self.assertEqual(processor.decode_stage.num_stalls, 0)
        self.assertEqual(processor.execute_stage.num_stalls, 0)
        self.assertEqual(processor.memory_stage.num_stalls, 0)

        self.assertEqual(processor.register_file[1], 8)
        self.assertEqual(processor.register_file[4], 8)
        self.assertEqual(processor.register_file[2], 999)
        self.assertEqual(processor.data_memory[8], 999)
Esempio n. 9
0
def maxThreshold(process_list, N, p, time_max):
    # N - number of processors (50-100)
    # p - threshold of processor utilization (process will be send there if utilization in smaller than p)
    # z - maximum amount of queries for processor utilization
    # time_max - maximum number of ticks
    sum_of_means = 0
    sum_of_requests = 0
    sum_of_process_migrations = 0
    processor_list = []
    for i in range(N):
        processor_list.append(pr.CProcessor())  # create a list of N processors

    for i in range(time_max):  # simulate the passing of time
        for process in process_list:
            process.starting_time -= 1  # decrease starting time of all processes in queue
            if process.starting_time == 0:  # if a process starting time reaches 0, it's added to a random processor
                p_temp = p  # keep track of how many times you've asked for other processes utilization
                times_repeated = 0
                if processor_list[process.starting_proc].utilization > p:
                    while p_temp:
                        times_repeated += 1
                        random_processor = np.random.randint(
                            0, N)  # randomly choose a processor
                        sum_of_requests += 1
                        if processor_list[random_processor].calc_util(
                        ) < p_temp:  # ask for its utilization, and if it's lower than p
                            processor_list[
                                random_processor].processes_running.append(
                                    process)  # give it that process
                            sum_of_process_migrations += 1
                            break
                        else:
                            if times_repeated == N:
                                p_temp += 1  # if you've asked N times, increase the acceptable load
                                times_repeated = 0
                else:
                    processor_list[
                        process.starting_proc].processes_running.append(
                            process)

        for processor in processor_list:  # update running time of all processes on all processors
            for process_running in processor.processes_running:
                process_running.time_required -= 1
                if process_running.time_required == 0:
                    processor.processes_running.remove(process_running)
            processor.update_mean_util(
            )  # update mean processor load of each processor

    print(
        "Maximum Threshold processor request, average utilization of each processor:"
    )
    for temp in range(len(processor_list)):
        # print("Processor {0}: {1:3.2f}%".format(temp, processor_list[temp].get_mean_util()))
        sum_of_means += processor_list[temp].get_mean_util()
    print("Mean utilization of all processes: {0:3.2f}%".format(sum_of_means /
                                                                N))
    print("Number of requests sent: {0}".format(sum_of_requests))
    print(
        "Number of processes migrated: {0}".format(sum_of_process_migrations))
    return
Esempio n. 10
0
    def __init__(self, master, file_name, input_info, output_info,
                 duration_estimate):
        self.master = master
        border_width = 15
        self.canvas_width = master.winfo_width()
        self.canvas_height = master.winfo_height()
        self.output_info = output_info
        arrow_width = self.canvas_height / 200
        border = 0

        #processor must be initialized first
        OutTop.OutTop(master, self.canvas_width, self.canvas_height, border,
                      border_width)
        OutBottom.OutBottom(master, self.canvas_width, self.canvas_height,
                            border, border_width)
        OutLeft.OutLeft(master, self.canvas_width, self.canvas_height, border,
                        border_width)
        OutRight.OutRight(master, self.canvas_width, self.canvas_height,
                          border, border_width)
        self.processor = Processor.Processor(master, self.canvas_width,
                                             self.canvas_height, arrow_width,
                                             border)
        self.wheel = Wheel.Wheel(master, self.canvas_width, self.canvas_height,
                                 border, arrow_width)
        self.register = Register.Register(master, self.canvas_width,
                                          self.canvas_height, border,
                                          self.processor.exit_height,
                                          arrow_width)
        self.memory = Memory.Memory(master, self.canvas_width,
                                    self.canvas_height, border)
        self.memory_op = MemoryOp.MemoryOp(master, self.canvas_width,
                                           self.canvas_height, arrow_width,
                                           border)
        self.cable = Cable.Cable(master, self.canvas_width, self.canvas_height,
                                 arrow_width, border,
                                 self.processor.entry_width,
                                 self.memory_op.entry_width,
                                 self.wheel.exit_height, self)
        self.controls = Controls.Controls(master, self.canvas_width,
                                          self.canvas_height, self, input_info,
                                          duration_estimate)

        ## TODO : MEANINGFUL EXCEPTIONS
        #        file_name = sys.argv[1]
        self.command_sequence = []
        memory_preset = []
        input_file = open(file_name, 'r')
        for line in input_file:
            line = line.strip()
            if line.strip().startswith('#') or line == '':
                continue
            elif line.strip().startswith('['):
                memory_preset = line[1:-1].split(',')
            else:
                self.command_sequence.append(line.strip().upper())

        self.memory.init(memory_preset, self.command_sequence)
        self.wheel.init(self.command_sequence)

        input_file.close()
def main():
    with open("pascalCode.pas", "r", encoding='utf-8') as fileReader:
        for line_number, line in enumerate(fileReader):
            lp = Processor.LineProcessor(line_number + 1, line)
            lp.process()
    print("token_list.csv File Generated")
    print("symboltable.csv File Genearated")
Esempio n. 12
0
def Enter_pressed():

    input_get = You.get()
    if input_get.lower() in bye_synonyms:
        quit()
    if input_get.lower() in translate_synonyms:
        f = open('Corpus.txt', 'r')
        contents = f.read()
        result = translator.translate(contents, dest='fr')
        print(result.text)
    if input_get.startswith("direct"):
        addressArr = input_get.replace("direct ", "").split(" and ")
        addressStart = addressArr[0].replace("from ", "").replace(" ", "")
        addressEnd = addressArr[1].replace(" ", "")
        print(addressStart)
        print(addressEnd)
        print(map.getdirect(addressStart, addressEnd))
    else:
        messages.insert(END, "You: " + '%s\n' % input_get)
        # this gets the response from the Processor.py file and then prints them out
        get_response = Processor.process(input_get, question_list, responses)
        messages.insert(INSERT, "Nova: " + '%s\n' % get_response)
        You.set('')
        messages.see(END)
        return "break"
Esempio n. 13
0
def Enter_pressed():

    input_get = You.get()
    if input_get.lower() in bye_synonyms:
        quit()

    if input_get.lower() in translate_synonyms:
        i = open('Corpus.txt', 'r')
        content = i.read()
        final = translator.translate(content, dest='ch')
        print(final.text)

    if input_get.startswith("navigation"):
        address = input_get.replace("navigation ", "").split(" and ")
        begin = address[0].replace("from ", "").replace(" ", "")
        end = address[1].replace(" ", "")
        print(begin)
        print(end)
        print(map.getdirect(begin, end))

    else:
        messages.insert(END, "You: " + '%s\n' % input_get)
        # this gets the response from the Processor.py file and then prints them out
        get_response = Processor.process(input_get, question_list, responses)
        messages.insert(INSERT, "Nova: " + '%s\n' % get_response)
        You.set('')
        messages.see(END)
        return "break"
Esempio n. 14
0
def Enter_pressed():
    input_get = You.get()
    if input_get.lower() in bye_synonyms:
        quit()
    elif input_get.lower() == 'picture of the day':
        messages.insert(END, "You: " + '%s\n' % input_get)
        nasa_response = NASA_Api.apod()
        messages.insert(INSERT, "Nova: " + '%s\n' % nasa_response)
        You.set('')
        messages.see(END)
        return "break"
    elif input_get.lower().split()[0] == 'wikipedia:':
        messages.insert(END, "You: " + '%s\n' % input_get)
        wiki_response = Wikipedia_Api.wikiSearch(input_get)
        messages.insert(INSERT, "Nova: " + '%s\n' % wiki_response)
        You.set('')
        messages.see(END)
        return "break"
    elif input_get.lower().split()[0] == 'wolfram:':
        messages.insert(END, "You: " + '%s\n' % input_get)
        # this gets the response from the Processor.py file and then prints them out
        wolfram_response = Wolfram_Api.wolframSearch(input_get)
        messages.insert(INSERT, "Nova: " + '%s\n' % wolfram_response)
        You.set('')
        messages.see(END)
        return "break"
    else:
        messages.insert(END, "You: " + '%s\n' % input_get)
        # this gets the response from the Processor.py file and then prints them out
        get_response = Processor.process(input_get, question_list, responses)
        messages.insert(INSERT, "Nova: " + '%s\n' % get_response)
        You.set('')
        messages.see(END)
        return "break"
Esempio n. 15
0
    def generateProcessor(this):
        handler = None
        if (this.isRequestValid):
            aggregate = this.factDatabase.getFactAggregation()
            currentSymbolNumber = 0
            numSymbolsToEliminate = len(this.eliminatedSymbols)
            while (currentSymbolNumber < numSymbolsToEliminate):
                aggregate.eliminateSymbol(
                    this.eliminatedSymbols[currentSymbolNumber])
                currentSymbolNumber += 1

            this.eliminatedSymbols = []

            request = this.getRequest()
            requestSymbolList = request.getSymbolList()
            totalWork = 2**len(requestSymbolList)
            coefficientMap = QuantumCounter.QuantumCounter()
            coefficientMap.createCoefficientMap(requestSymbolList)
            this.processor = Processor.Processor(aggregate, request,
                                                 coefficientMap, totalWork)
            handler = this.processor.go
        else:
            this.errorOutputMethod("Failed to declare environment: "
                                   "request is not defined.")
        return handler
Esempio n. 16
0
 def _clean(self, fragments):
     try:
         model = BlockModelBuilder.build(fragments)
         return Processor.process(model, self.keys)
     except BlockModelBuilder.SyntaxException:
         return CleanResult(None, "Syntax Error", 0, 0)
     except:
         return CleanResult(None, "Undefined Error", 0, 0)
Esempio n. 17
0
    def pre_process(self):
        G.debug(''.join(
            ['Doing post upgrade when globalvars = ',
             str(self.globalvars)]))
        filename = getkey(self.arguments, 'primary', False)
        if not filename:
            G.error('No filename specified, skipping Input')
            return
        G.info(''.join(['Inserting ', filename]))
        p = None
        if os.path.isfile(getkey(self.globalvars, 'root') + filename):
            p = Processor.Processor(getkey(self.globalvars, 'root'),
                                    filename,
                                    _is_main_file=False)
        if os.path.isfile(
                getkey(self.globalvars, 'root') + 'templates/' + filename):
            p = Processor.Processor(getkey(self.globalvars, 'root') +
                                    'templates/',
                                    filename,
                                    _is_main_file=False)
        elif os.path.isfile(getkey(self.globalvars, 'templatedir') + filename):
            p = Processor.Processor(getkey(self.globalvars, 'templatedir'),
                                    filename,
                                    _is_main_file=False)
        elif os.path.isfile(G.template_dir + filename):
            p = Processor.Processor(G.template_dir,
                                    filename,
                                    _is_main_file=False)
        else:
            G.error('Could not find file requested by Input: ' + filename)
            return

        # Use the uppermost globalvars dictionary
        p.globalvars = self.globalvars

        # Load the objects
        if p.init_file():
            p.load_objects()
            p.close_file()

        # Copy objects from the processor to the object
        self.sub_objects = p.objects
        G.debug(''.join(['Input objects are: ', p.get_objects_as_string()]))

        self.removed = True
Esempio n. 18
0
def run_program():
    log_path = "/Users/zhangmengfeifei/Desktop/self_learning/test_files/log.txt"
    parameters = dict()
    print("Welcome to Image Process Master!")
    parameters["content_type"], parameters["content"] = set_content()
    operation = set_operation()
    set_operation_para(parameters, operation)
    output_path = set_output_path()
    processor = Processor.Processor(parameters, output_path, log_path)
    # processor.__test_parameters__()
    processor.process()
Esempio n. 19
0
def main():
    '''Server main loop'''

    host = 'localhost'
    port = 5000

    try:
        server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                    socket.IPPROTO_TCP)
        server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_sock.bind((host, port))
        server_sock.listen(1)
        print 'Server start listen at:\n', str(host) + ':' + str(port)
    except socket.error as msg:
        print 'Oops! we have an error here...\n', msg
        main()

    while True:
        client_sock, cliet_addr = server_sock.accept()

        Processor.get_request_data(client_sock)
        Processor.parse_data()

        print '##STEP_5-----sending_response--------------'
        print 'response to connection: HI! how are you?\n'
        client_sock.send('HI! how are you?\n')

        Processor.set_flow_free()

        client_sock.close()
Esempio n. 20
0
def run():
    Processor.init()
    try:
        while True:
            pc = Processor.read_pc()
            content = Memory.read(pc)
            assert content[
                'type'] == 2, 'Following content %s is unexpected.' % str(
                    content)
            inst = content['inst']

            Profiler.count(pc)

            if JIT.is_acceleratable(pc):
                JIT.accelerate(pc)
            else:
                """
                print 'Current PC is 0x%08X.' % Processor.read_pc()
                print inst
                """
                Processor.execute(inst)
                JIT.snapshot(pc)
    except KeyboardInterrupt:
        pass
    except:
        print traceback.print_exc()
        print 'Current PC is 0x%08X.' % Processor.read_pc()
        print 'Current instruction is %s.' % str(inst)
Esempio n. 21
0
def main():
    '''Server main loop'''

    host = 'localhost'
    port = 5000

    try:
        server_sock = socket.socket(socket.AF_INET,
                                    socket.SOCK_STREAM,
                                    socket.IPPROTO_TCP)
        server_sock.setsockopt(socket.SOL_SOCKET,
                               socket.SO_REUSEADDR, 1)
        server_sock.bind((host, port))
        server_sock.listen(1)
        print 'Server start listen at:\n', str(host) + ':' + str(port)
    except socket.error as msg:
        print 'Oops! we have an error here...\n', msg
        main()

    while True:
        client_sock, cliet_addr = server_sock.accept()

        Processor.get_request_data(client_sock)
        Processor.parse_data()

        print '##STEP_5-----sending_response--------------'
        print 'response to connection: HI! how are you?\n'
        client_sock.send('HI! how are you?\n')

        Processor.set_flow_free()

        client_sock.close()
Esempio n. 22
0
def Enter_pressed():

    input_get = You.get()
    if input_get.lower() in bye_synonyms:
        quit()
    else:
        messages.insert(END, "You: " + '%s\n' % input_get)
        # this gets the response from the Processor.py file and then prints them out
        get_response = Processor.process(input_get, question_list, responses)
        messages.insert(INSERT, "Nova: " + '%s\n' % get_response)
        You.set('')
        messages.see(END)
        return "break"
def run(j):
    #for j in xrange(7):
    for i in xrange(10):
        featureName = None
        channels = None
        if j in range(5):
            featureName = "Dog_" + str(j + 1)
            if j == 4:
                channels = 15
            else:
                channels = 16
        else:
            if j == 6:
                channels = 24
            else:
                channels = 15
            featureName = "Patient_" + str(j - 4)
        feature = Feature(featureName)
        processor = Processor()
        basePath = "/home/xiaobin/raw_data/" + feature.subjectName
        print basePath
        X_train, y_train = processor.processDataPerSubject(basePath,
                                                           trainOrTest="train",
                                                           splitNum=10,
                                                           sequence=i)
        X_train, y_train = feature.pca(X_train, y_train)
        #X_train, y_train = feature.fft(X_train, y_train)
        print "X_train shape" + str(X_train.shape)
        feature.saveToDisk(trainOrTest="train", name=str(i))

        X_test, y_test = processor.processDataPerSubject(basePath,
                                                         trainOrTest="test",
                                                         splitNum=10,
                                                         sequence=i)
        #X_test, y_test = feature.fft(X_test, y_test )
        X_train, y_train = feature.pca(X_test, y_test)

        feature.saveToDisk(trainOrTest="test", name=str(i))
Esempio n. 24
0
def test_file(filename):
    print '=' * 60
    print filename
    f = file(filename, 'rb')
    xparser = Parser(f)
    xprocessor = Processor()
    xprocessor.appendCommandList(xparser.commandList())
    xprocessor.run()
    f.close()
    def setUp(self):
        old_pickle_file_name = 'old-cycle-data.pickle'
        new_pickle_file_name = 'new-cycle-data.pickle'

        self.memory = Memory.Memory()
        self.memory.loadProgramDebug('fibo.txt')
        self.processor = Processor.Processor(self.memory, 0)
        self.processor.start(new_pickle_file_name)

        print
        print 'Processor Regression Testing...'
        self.old_data_list = Processor.Processor.read_saved_data(
            old_pickle_file_name)
        self.new_data_list = Processor.Processor.read_saved_data(
            new_pickle_file_name)
 def test_operand_forwarding_R_and_R_instruction(self):
     instruction_list = [
         'R ADD  R2 R3 R2',
         'R ADD  R2 R3 R1',
     ]
     instruction_list = [
         instruction_string.split()
         for instruction_string in instruction_list
     ]
     memory = Memory.Memory(instruction_list)
     processor = Processor.Processor(memory, 0)
     processor.start()
     print 'CPI: ', processor.getCPI()
     self.assertEqual(processor.decode_stage.num_stalls, 0)
     self.assertEqual(processor.execute_stage.num_stalls, 0)
     self.assertEqual(processor.memory_stage.num_stalls, 0)
Esempio n. 27
0
def Enter_pressed():

    input_get = You.get()
    input_test = input_get.lower()
    if (translate.detect_language(input_test) != "en"):
        input_test = translate.translate_text("EN", input_test)
    if input_test in bye_synonyms:
        quit()
    else:
        messages.insert(END, "You: " + '%s\n' % input_get)
        # this gets the response from the Processor.py file and then prints them out
        get_response = Processor.process(input_get, question_list, responses)
        messages.insert(INSERT, "Nova: " + '%s\n' % get_response)
        You.set('')
        messages.see(END)
        return "break"
 def test_all_intermediate_buffers_are_shared(self):
     for i in xrange(1, 10):
         processor = Processor.Processor(self.memory, 0)
         processor.execute_cycles(i)
         pairs = [
             (processor.fetch_stage.fetcher_buffer,
              processor.decode_stage.fetcher_buffer),
             (processor.decode_stage.decoder_buffer,
              processor.execute_stage.decoder_buffer),
             (processor.execute_stage.executer_buffer,
              processor.memory_stage.executer_buffer),
             (processor.memory_stage.memory_buffer,
              processor.write_back_stage.memory_buffer),
         ]
         for i, pair in enumerate(pairs):
             self.assertEqual(
                 pair[0], pair[1],
                 '{0} != {1} index: {2}'.format(pair[0], pair[1], i))
 def setUp(self):
     instruction_list = [
         'I ADDI R1 R1 1',
         'I ADDI R2 R2 2',
         'I ADDI R5 R5 89',
         'I BEQ  R2 R5 4',
         'R ADD  R1 R2 R3',
         'R ADD  R2 R0 R1',
         'R ADD  R3 R0 R2',
         'J J    3',
         'I ADDI R9 R9 999',
     ]
     instruction_list = [
         instruction_string.split()
         for instruction_string in instruction_list
     ]
     self.memory = Memory.Memory(instruction_list)
     self.register_file = RegisterFile()
     self.processor = Processor.Processor(self.memory, 0)
Esempio n. 30
0
def openfile() -> None:
    filePath = str(filedialog.askopenfilename(filetypes=[("No Extend", "*.*")]))
    if filePath is None or filePath == '':
        return

    if len(filePath.split('.')) != 1:
        tk.messagebox.askquestion(title='提示', message='这个格式不行!')
        return

    filename = filePath.split('/')[-1]
    operate_bat = False
    if re.fullmatch(r'.*\d', filename) is None:
        print(filename)
        if re.fullmatch(r'.*\dbak', filename) is not None:
            filePath = filePath[:-3]
            operate_bat = True
        else:
            tk.messagebox.askquestion(title='提示', message='文件名称应该全是数字!,或者是*bak')
            return

    print(filePath)
    # do transform
    job = Processor.Processor(v.get())
    if operate_bat is False:
        result = job.process(filePath)
    else:
        result = job.process(filePath+'bak')

    if result == '':
        tk.messagebox.askquestion(title='提示', message='Unicode 解码失败, 请确认是否为歌词文件')

    if operate_bat is False and os.path.isfile(filePath+'bak'):
        tk.messagebox.askquestion(title='提示', message='已存在bak,请对bak操作')
        return

    if operate_bat is False:
        os.rename(filePath, filePath+"bak")

    f = open(filePath, encoding='utf-8', mode='w+')
    f.write(result)

    tk.messagebox.askquestion(title='提示', message='完成替换!')
Esempio n. 31
0
def run(filename):
    # recursion to inner dir
    ext = os.path.splitext(filename)[1]
    if not os.path.isdir(filename) and \
        ext.lower() not in ('.m4v', '.wmv', '.avi', '.mkv', '.mp4', '.vob'):
        return

    if os.path.isdir(filename):
        if options.recur:
            if options.verbose:
                print 'REC enter %s' % filename
            for f in os.listdir(filename):
                ff = os.path.join(filename, f)
                run(ff)
            if options.verbose:
                print 'REC leave %s' % filename
        else:
            print '%s is a directory' % filename
        return 0

    proc = Processor.Processor(filename, overwrite=options.overwrite)
    proc.run()
Esempio n. 32
0
def run():
    Processor.init()
    try:
        while True:
            content = Memory.read(Processor.read_pc())
            assert content['type'] == 2, 'Following content %s is unexpected.' % str(content)
            inst = content['inst']

            """
            print 'Current PC is 0x%08X.' % Processor.read_pc()
            print inst
            """

            Processor.execute(inst)
    except KeyboardInterrupt:
        pass
    except:
        print traceback.print_exc()
        print 'Current PC is 0x%08X.' % Processor.read_pc()
        print 'Current instruction is %s.' % str(inst)
Esempio n. 33
0
 def __init__(self):
     self.processor = Processor()
Esempio n. 34
0
class CmdFunction(object):

    def __init__(self):
        self.processor = Processor()

    def load_file(self, file_path):
        self.processor.validator.empty_bad_data()
        if file_path == "":
            return "No file/path entered"
        else:
            try:
                self.processor.add_data(file_path)
                return "File loaded\nGood data: " + str(self.processor.database.get_length()) + "\nBad data: " + str(self.processor.validator.get_bad_data_len())
            except IOError as not_found_err:
                return "File/path not found"
            except UnicodeDecodeError as bad_format_err:
                return "Not a valid File type"

    def pickle_load_file(self, file_path):
        self.processor.validator.empty_bad_data()
        if file_path == "":
            return "No file/path entered"
        else:
            try:
                self.processor.add_data(file_path)
                return "File loaded\nGood data: " + str(self.processor.database.get_length()) + "\nBad data: " + str(self.processor.validator.get_bad_data_len())
            except IOError as not_found_err:
                return "File/path not found"
            except UnicodeDecodeError as bad_format_err:
                return "Not a valid File type"

    def display_good(self, theMessage):
        if self.processor.filer.get_file_path() == None and self.processor.database.get_length() == 0:
            print("No data to display. Please load a file or run deserialize")
        else:
            self.processor.database.print_all()

    def display_bad(self, msg):
        if self.processor.filer.get_file_path() == None and self.processor.database.get_length() == 0:
            print("No data to display. Please load a file")
        elif len(self.processor.validator.export_bad_data()) == 0:
            print("No bad data to display.")
        else:
            self.processor.validator.print_bad_data()

    def edit_bad(self, value):
        if self.processor.filer.get_file_path() == None and self.processor.database.get_length() == 0:
            return "No data to edit. Please load a file"
        elif len(self.processor.validator.export_bad_data()) == 0:
            return "No bad data to edit."
        else:
            self.processor.process_bad()

    def display_graphs(self, input):
        if self.processor.database.get_length() != 0:
            if input == "1":
                self.processor.pie_bmi()
            elif input == "2":
                self.processor.pie_gender()
            elif input == "3":
                self.processor.scatter_sales()
            elif input == "4":
                self.processor.bar_bmi_vs_gender()
        else:
            print("No data has been loaded")

    def serialize(self, option):
        if option == 0:
            o = 0
        elif option == 1:
            self.processor.set_file_path(input("Please enter the directory you wish to save to:\n"))
            o = 1
        try:
            self.processor.serialize(o)
        except OSError as no_dir_err:
            print("Directory not found")

    def deserialize(self, option):
        if option == 0:
            self.processor.deserialize(0)
        elif option == 1:
            self.processor.set_file_path(input("Please enter the directory you wish to load from:\n"))
            self.processor.deserialize(1)
Esempio n. 35
0
#! /usr/bin/env python

import os, os.path, sys
sys.path.insert(0, os.getcwd())

import PTree
import Processor

class Walker(PTree.Visitor):

    def visit_atom(self, a):
        print a
    def visit_list(self, l):
        if l.car():
            l.car().accept(self)
        if l.cdr():
            l.cdr().accept(self)

test = os.path.join(os.path.dirname(__file__), 'test.cc')
buffer = Processor.Buffer(test)
ptree = Processor.parse(buffer)
walker = Walker()
ptree.accept(walker)
Esempio n. 36
0
documentNum=0
for line in open(filelist):
    filename = line.strip()
    print "processing %s" % filename
    documentNum += 1
    clip = path.basename(filename).split('.')[0]
    fin = open(filename, 'r')
    while True:
        l = fin.readline()
        if not l:
            break
        #print Tparse.GetText(l.strip())
        text = Tparse.GetText(l.strip())
        tokens = re.split("\s+|_", text)
        for token in tokens:
            word = Processor.process_word(token, 1)
            word_clip_dict[word][clip] += 1

#calculate dictionary
IDF_dict = {}
for word in word_clip_dict.keys():
        if len(word_clip_dict[word].keys())<cut:
                continue
        IDF_dict[word] = math.log(documentNum) - math.log(len(word_clip_dict[word].keys()))

fout = open(output, 'w')
idx=1
for word, idf in sorted(IDF_dict.items(), key=lambda item:item[1]):
        fout.write("%d %s %.3f\n" % (idx, word, idf))
        idx += 1
fout.close()