Exemple #1
0
    def __init__(self, title, params):
        '''
        Requires params:
                - days, dataset_type, ... (type-specific, like n)

            For non-chicago:
                - time_periods, order_distr (uniform, star, centered), orders_density, number_of_cars
                    order density for star is simply number of cars. for uniform,centered - multipl. of range

        Notes:
            - Currently onoff and idle drivers are generated for one day only.
        '''

        self.params = params
        self.title = title
        self.data_path = None  # should be overwritten either by loading dataset, or by generating one
        assert (title != '')
        self.fm = FileManager(title)
        self.generators = {
            'dummy':
            lambda: self.generate_dummy(self.params['dummy_data_param']),
            'grid':
            lambda: self.generate_grid(self.params['n']),
            'hexagon':
            lambda: self.generate_hexagon(self.params['n']),
            'chicago':
            lambda: self.generate_chicago(self.params.get('sparsity', 1))
        }

        if self.params['dataset_type'] == 'chicago':
            self.params["time_periods"] = (24 * 60) // 15

        # set default values
        self.params["time_periods_per_hour"] = self.params.get(
            "time_periods_per_hour", self.params["time_periods"])  # static
Exemple #2
0
 def insert_position(self, table_name, record_length):
     #deleted list
     if len(self.deleted[table_name]) != 0:
         tmp = self.deleted[table_name][-1]
         self.deleted[table_name].pop(-1)
         return (self.fetch_block(tmp >> 11), tmp % (1 << 11))
     #last/new block
     block_num = FileManager.table_size(table_name)
     record_num = 4096 // record_length
     start = max((0, block_num - 1))
     for i in range(start, block_num):
         x = self.fetch_block_without_loading(
             (self.table_list.index(table_name) << 16) + i)
         data = x.read() if x != None else FileManager.read_block(
             table_name, i)
         for j in range(record_num):
             if struct.unpack('?',
                              data[j * record_length:j * record_length +
                                   1])[0] == False:
                 if x != None:
                     return (x, j * record_length)
                 else:
                     return (self.load_block(
                         (self.table_list.index(table_name) << 16) + i),
                             j * record_length)
     self.save_table(table_name)
     return (self.append_block(table_name), 0)
Exemple #3
0
    def __init__(self, parent, uiObj):
        #Declare Project Variables
        self.__configFile = os.path.join(
            os.path.expanduser(os.path.join('~', ".sift")), 'sf_config.ini')
        self.loadedProjName = ''
        self.loadedProjPath = ''
        self.loadedProjType = ''

        #Determine the path to sift.py
        self.baseDir = self.initBaseDir()

        #Declare all Managers
        self.uiObj = uiObj
        self.parent = parent
        self.treeViewMgr = TreeviewManager(self, self.uiObj.treeWidget_proj,
                                           self.uiObj.treeWidget_nonProj,
                                           self.uiObj.tabWidget_treeview)
        self.fileMgr = FileManager(self)
        self.viewMgr = ViewManager(self, self.uiObj.tabWidget_viewer)
        self.messageMgr = MessageManager(self, self.uiObj.statusbar)
        self.configMgr = ConfigManager(self)

        #Pass Managers to other Managers that need them
        #(Basically this simulates the Singleton pattern since python can't do it natively)
        self.viewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setViewManager(self.viewMgr)

        #Load up things needed to happen at start up, but after the managers are all loaded
        self.viewMgr.resetMainViewer()
 def __init__(self, init, end):
     self.base_url = 'http://www.chictopia.com/browse/people'
     FileManager.FileManager().create_tag_directory()
     self.tags = FileManager.get_tags_from_file()
     self.parser = LinkManager()
     self.download_page_range(init, end)
     self.parser.download_images_with_tag(self.tags)
Exemple #5
0
 def test_findFilesStarredWithRange(self):
     d = {}
     FileManager.fixupLocationWithBase(self.working, "other_[23].ext", d)
     results = FileManager.findDiskFilesMatchingStarred(d['location'])
     self.assertEqual(len(results), 2)
     self.assertTrue(os.path.join(self.working, "other_2.ext") in results)
     self.assertFalse(os.path.join(self.working, "other_1.ext") in results)
Exemple #6
0
def register():
    """注册"""
    # 1.输入用户名和密码
    user_name = input('请输入用户名:')
    pass_word = input('请输入密码:')
    # 2.判断当前用户名是否已经注册
    # ================csv文件=================
    # # 1)获取已经注册过的所有的账号信息
    # # [{'账号': 'aaa', '密码': '123456'}, {'账号': 'bbb', '密码': '123456'}]
    # all_user = FileManager.read_csv_file('files/userInfo.csv')
    # # 2)判断当前账号是否已经注册过
    # for item in all_user:
    #     if item['账号'] == user_name:
    #         print(f'注册失败! {user_name}已经注册过!')
    #         break
    # else:
    #     print('注册成功!')
    #     FileManager.write_row_csv_file('files/userInfo.csv', [user_name, pass_word])
    #     # FileManager.write_row_csv_file('files/userInfo.csv', {'账号': user_name, '密码': pass_word})

    # ========================json文件===========================
    # 1)获取已经注册过的所有的账号信息
    all_user = FileManager.read_json_file('files/userInfo.json')
    # 2)判断当前账号是否已经注册过
    if user_name in all_user:
        print(f'注册失败!{user_name}已经注册过!')
    else:
        all_user[user_name] = pass_word
        FileManager.write_json_file('files/userInfo.json', all_user)
        print('注册成功!')
Exemple #7
0
 def delete(self, table_name):
     table_index = self.table_list.index(table_name)
     for i in self.blocks:
         if i.index >> 16 == table_index:
             i.dirty = False
             self.save_block(i)
     FileManager.delete_table(table_name)
Exemple #8
0
 def test_findFilesStarredWithQuestionMark(self):
     d = {}
     FileManager.fixupLocationWithBase(self.working, "test_?.ext", d)
     results = FileManager.findDiskFilesMatchingStarred(d['location'])
     self.assertEqual(len(results), 5)
     self.assertTrue(os.path.join(self.working, "test_1.ext") in results)
     self.assertTrue(os.path.join(self.working, "test_5.ext") in results)
Exemple #9
0
def main():
    """Funcion principal, donde interactuamos con las 
       demas clases pasandoles los ficheros necesarios e 
       instanciando las clases del MapReduce"""

    num_cores = 4
    files = getArgs()

    file_manager = FileManager(files)
    lines_files = file_manager.split_in_lines()

    num_lines = len(lines_files)
    partialPart = num_lines / num_cores
    difference = num_lines - (partialPart * num_cores)

    mapper = Mapper("")
    for i in range(partialPart, (num_lines - partialPart) + 1, partialPart):
        t = threading.Thread(mapper.mapping(lines_files[i - partialPart:i]))
        t.start()

    t = threading.Thread(
        mapper.mapping(lines_files[num_lines -
                                   (partialPart + difference):num_lines]))
    t.start()

    shuffleDict = mapper.shuffle(mapper.wordsMap)

    reducer = Reducer()

    result = reducer.reduce(shuffleDict)

    dirToTxt(result)
Exemple #10
0
 def test_fileBasicREFilesRE(self):
     d = {}
     FileManager.fixupLocationWithBase(self.working, ".*[.]ext", d)
     results = FileManager.findDiskFilesMatchingRegex(d['location'])
     self.assertEqual(len(results), 8)
     self.assertTrue(os.path.join(self.working, "other_3.ext") in results)
     self.assertTrue(os.path.join(self.working, "test_4.ext") in results)
 def run(self):
     """Main"""
     global SON
     global TLP
     while not self._stopevent.isSet():
         data = input(">")
         if data == "quit":
             TLP.stop()
             self.stop()
         elif data == "Tais toi!":
             SON = False
         elif data == "Parle!":
             SON = True
         elif re.search("je.*envoie.*fichier", data):
             regex = re.search(r"[A-Za-z]*.\.[A-Za-z]*", data)
             fileName = regex.group(0)
             data2, infos = FileManager.sendFichier(0, fileName)
             if infos[1] == 0:
                 Client.sendFile(data2, fileName)
             else:
                 choix = input(data2)
                 data2, infos = FileManager.sendFichier(1, choix, infos)
         elif len(data):
             Client.sendMsg("T", str(data))
         else:
             continue
Exemple #12
0
    def __init__(self, request):
        Response.__init__(self, request)
        self.fetched = FileManager.FetchedFile(self.path)
        self.status_code = self.fetched.status_code
        self.message_body = ""

        if not FileManager.allowed_access(self.client, self.fetched.path):
            self.status_code = 403

        # Since no file takes precedence in a multi-threaded system,
        # we don't need to implement "Accept" preferences.

        if self.status_code == 404:
            self.response_header.etag = self.fetched.checksum
            self.response_header.retry = 120
            self.entity_header.c_length = 0
        elif self.status_code == 200:
            self.general_header.cach = "max-age=120"
            self.entity_header.c_type = self.fetched.type
            self.entity_header.c_length = self.fetched.size
            self.entity_header.c_encoding = "gzip"
            self.response_header.retry = 120
            self.message_body += self.fetched.encoded
            self.message_body += CRLF
        elif self.status_code == 403:
            self.entity_header.c_len = 0
Exemple #13
0
def init():
    global index_manager, catalog_manager, parser
    index_manager = IndexManager.IndexManager(FileManager.load_index())
    catalog_manager = CatalogManager.CatalogManager()
    catalog_manager.create_table_catalog(FileManager.load_catalog(0))
    catalog_manager.create_index_catalog(FileManager.load_catalog(1))
    parser = Interpreter.command(catalog_manager)
    RecordManager.init(index_manager, catalog_manager)
Exemple #14
0
 def save_table(self, table_name):
     table_index = self.table_list.index(table_name)
     for i in self.blocks:
         if i.index >> 16 == table_index:
             if i.dirty == True:
                 FileManager.write_block(self.table_list[i.index >> 16],
                                         i.index % (1 << 16), i.read())
             i.dirty = False
Exemple #15
0
 def record(self, userInput) :
     if self.newFile :
         recordEntry = self.inputTitle + self.orderedNames
         FileManager.writeData(self.fileName, recordEntry)
         self.newFile = False
     recordEntry = [userInput] + self.getCurrentValues()
     FileManager.writeData(self.fileName, recordEntry)
     self.updateLastFiveRecorded(recordEntry)
Exemple #16
0
def update_fields(fields: dict) -> None:
    """
    This should only be ran when an experiment meets required fitness levels,
    and is chosen as a schedule to be used - WIP
    """
    old_fields = fm.read_data('fields.csv', 'field')
    for key in fields:
        old_fields[key] += fields[key]
    fm.save_data(old_fields, 'fields.csv')
Exemple #17
0
 def test_fileBasicREFilesREWithDash(self):
     d = {}
     FileManager.fixupLocationWithBase(
         os.path.join(self.working, 'other-fakeworking'), '.*[.]other', d)
     results = FileManager.findDiskFilesMatchingRegex(d['location'])
     self.assertEqual(len(results), 5)
     self.assertTrue(
         os.path.join(self.working, 'other-fakeworking/my_1.other') in
         results)
Exemple #18
0
def create_table(table_name):
    attrs = catalog_manager.get_attribute(table_name)
    unique = catalog_manager.get_unique(table_name)
    FileManager.create_table(table_name)
    RecordManager.buf.update_table_list(catalog_manager.get_tables())
    index_manager.CreateTable(table_name, [(i[0], 4096 // i[2])
                                           for i in attrs if i[0] in unique])
    print('Query OK, 0 rows affected ({:.2f} sec)'.format(time.process_time() -
                                                          start_time))
Exemple #19
0
 def append_block(self, table_name):
     self.counter += 1
     block = self.first_vacancy()
     block.index = (self.table_list.index(table_name) <<
                    16) + FileManager.table_size(table_name)
     block.last_used = self.counter
     block.write(4095, b'\x00')
     FileManager.write_block(table_name, block.index % (1 << 16),
                             block.read())
     return block
Exemple #20
0
def loadJsoninGlobalVariable():
    global intrinsic
    intrinsic = objetintrinsic(FileManager.Load("json_in/intrinsics.json"))
    Counter_select.setIntrinsicParam(intrinsic)
    Geometry.setIntrinsicParam(intrinsic)
    Scene3D.setIntrinsicParam(intrinsic)
    global annotation_file
    annotation_file = FileManager.Load("json_in/annotations.json")
    InfoFromAnnotation.setJson(annotation_file)
    FileManager.setJson(annotation_file)
def show_results_fitting():
    piece = fm.load_img_piece()
    edge_img = prep.canny(piece)
    tooth = fm.load_tooth_of_piece(0)
    new_points_list, total_error = fit_measure(tooth, 25, edge_img)
    for i in range(7):
        tooth = fm.load_tooth_of_piece(i + 1)
        new_points, total_error = fit_measure(tooth, 25, edge_img)
        new_points_list = np.append(new_points_list, new_points)
    fm.show_with_points(edge_img, new_points_list.reshape(-1, 2))
 def switch_state(self):
     if self.Board.IsShow():
         self.Board.Hide()
         self.Hide()
     else:
         self.Board.Show()
         self.UpdateFileList()
         self.Show()
         self.SegiID = int(FileManager.ReadConfig("Blessing-Scroll"))
         self.MetalID = int(FileManager.ReadConfig("Magic-Stone"))
Exemple #23
0
def show_influence_ext_int():
    new_piece, new_tooth = piece, tooth 

    mean = calc_mean(new_tooth)
    ext = calc_external_img(new_piece)
    fm.show_with_points(ext, new_tooth[0:2])

    print(calc_external(new_tooth[0],ext))
    print(calc_internal(new_tooth[0], new_tooth[1], mean))
    print(calc_energy(new_tooth[0],new_tooth[1],ext,mean,10))
Exemple #24
0
 def save_block(self, block):
     if block.pinned == True:
         print('Error: block pinned')
         return
     if block.dirty == True:
         FileManager.write_block(self.table_list[block.index >> 16],
                                 block.index % (1 << 16), block.read())
     block.last_used = -1
     block.index = -1
     block.dirty = False
     block.data = io.BytesIO()
    def download_image(self, url, file_name):

        """
        Takes its given url and downloads the image from it.
        :param url: URL that contains the desired image
        :param file_name: Name of the file
        :return:
        """
        file = Requester.urlopen(url)
        FileManager.create_new_file(file, str(self.img_url)+self.file_type, "C:/Users/Volk/Pictures/5chin/")
        return None
Exemple #26
0
def clean_word_model():
    word_freq = fm.load_word_freq(path_word_frequency_tsv)
    word_to_delete = []
    for key, val in word_freq.items():
        # Remove if less than 5 due to typos
        if val < 100:
            word_to_delete.append(key)
    for word in word_to_delete:
        del word_freq[word]
    fm.save_word_freq(word_freq, path_word_frequency_tsv)
    print(sorted(word_freq.values()))
	def saveMaze(self):
		if (self.checkMaze(self.screen.MazeEditor.MazeClass)):
			name = self.getSaveName()
			FileManager.writeMaze(self.smazes,self.screen.MazeEditor.
								MazeClass.maze,name,
								self.screen.MazeEditor.MazeClass.foodBoost,
								self.screen.MazeEditor.MazeClass.timeBoost,
								self.screen.MazeEditor.MazeClass.food)
			self.initAnimation(self.christmas)
		else:
			message = "Illegal Maze! Remember no closed loops!"
			tkMessageBox.showwarning("Illegal Maze",message)
Exemple #28
0
    def __init__(self, port, root, defPages, scripts, isMaster, others):
        self.Port = port
        self.Root = root
        self.DefPages = defPages
        self.Scripts = scripts
        self.IsMaster = isMaster
        self.Others = others

        self.FileMgrFiles = fm.FileManager(
            os.path.join(os.path.dirname(__file__), self.Root))
        self.FileMgrDefaultPages = fm.FileManager(
            os.path.join(os.path.dirname(__file__), self.DefPages))
Exemple #29
0
    def Hide_UI(self):
        self.Board.Hide()
        for item in self.items_ui:
            FileManager.WriteConfig(
                str(item), str(self.items_ui[item]['item_price'].GetText()),
                FileManager.CONFIG_SHOP_CREATOR)
        FileManager.Save(FileManager.CONFIG_SHOP_CREATOR)

        FileManager.WriteConfig("ShopName",
                                str(self.ShopNameEditline.GetText()))
        FileManager.WriteConfig("Multiplication",
                                str(self.MultiplicationButton.isOn))
        FileManager.Save()
 def test_findSingleDiskFilesMatchingStarred(self):
     d = {}
     FileManager.fixupLocationWithBase(
         self.working,
         "test_1.ext",
         d )
     results = FileManager.findDiskFilesMatchingStarred(
         d['location'] )
     self.assertEqual(len(results), 1)
     self.assertEqual(os.path.join(
         self.working,
         "test_1.ext" ),
         results[0])
Exemple #31
0
def runner(m, n, alpha, b):
    s = 0
    f_name = "{0}_{1}_{2}_{3}.txt".format(str(m), str(n), str(alpha), str(b))
    for i in range(1):
        w, c, p = ks.generate_knapsack(m, n, alpha)
        for j in range(10):
            print(m, " ", n, " ", alpha, " ", b, " ", i, " ", j, end=" ")
            r = genetic.fga(n, p, w, c, m)
            pd = abs(b - r) / b
            print(pd)
            s += pd
    avg_pd = s / 10
    fm.write_to_file(f_name, avg_pd)
	def handleScoreRecord(self,score):
		newHigh = False
		for Score in self.scores:
			if int(self.scores[Score]) < score:
				newHigh = True
		if (len(self.scores) < 10):
			newHigh = True

		if (newHigh):
			if (len(self.scores) >= 10):
				self.dropSmallest()
			name = self.getName()
			FileManager.writeScores(self.scores,name,score)
def main():
    """Main function"""
    request_file = fm.get_files('Requests')
    requests = fm.read_file('Requests', request_file[0])
    requests = Request(request_file[0], requests)
    requests_sort_by_tb = requests.request_sort_by_tb

    # Outputs - Will probably be made into a separate function and saved for future use
    print("-" * 100)
    print("OVERVIEW OF REQUEST")
    print("-" * 100)

    # print(requests_sort_by_tb)
    # write_request_repeat_to_excel(requests)
    write_to_excel(requests)
Exemple #34
0
def test_module():
    piece = fm.load_img_piece()
    tooth = fm.load_tooth_of_piece(0)
    ext = calc_external_img2(piece) 
    fm.show_with_points(ext, tooth)
    
    img, stooth = fm.resolution_scale(piece, tooth, 1/6)
    ext = calc_external_img2(img) 
    fm.show_with_points(ext, stooth)
    
    new_tooth = active_contour(stooth, img, 1, 3, 1)
    fm.show_with_points(ext, new_tooth)
Exemple #35
0
    def __init__(self, parent, uiObj):
        #Declare Project Variables
        self.__configFile = os.path.join(os.path.expanduser(os.path.join('~',".sift")),'sf_config.ini')
        self.loadedProjName = ''
        self.loadedProjPath = ''
        self.loadedProjType = ''

        #Determine the path to sift.py
        self.baseDir = self.initBaseDir()

        #Declare all Managers
        self.uiObj = uiObj
        self.parent = parent
        self.treeViewMgr = TreeviewManager(self, 
                                           self.uiObj.treeWidget_proj, 
                                           self.uiObj.treeWidget_nonProj,
                                           self.uiObj.tabWidget_treeview)
        self.fileMgr = FileManager(self)
        self.viewMgr = ViewManager(self, self.uiObj.tabWidget_viewer)
        self.messageMgr = MessageManager(self, self.uiObj.statusbar)
        self.configMgr = ConfigManager(self)        

        #Pass Managers to other Managers that need them
        #(Basically this simulates the Singleton pattern since python can't do it natively)
        self.viewMgr.setFileManager(self.fileMgr) 
        self.treeViewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setViewManager(self.viewMgr)

        #Load up things needed to happen at start up, but after the managers are all loaded
        self.viewMgr.resetMainViewer()
Exemple #36
0
 def run(self):
     global son
     while not self._stopevent.isSet():
         typ,received = Client.receiveMsg()
         if typ=="N":
             Client.notify(received)
         elif typ=="F":
             r=received.split(";")
             FileManager.convertFileReceive(r[0],r[1])
             Client.notify("notif;Transfert;Fichier "+r[1]+" bien reçu;4")
         else:
             print("\n-->%s" % received)
             if son:
                 adire=received[:-14]
                 Audio.parle(adire)
         time.sleep(0.01)
	def __init__(self, reactor, peer_id, port, raw_data = None, torrent_dict = None):
		super(Torrent, self).__init__()
		if(raw_data == None and torrent_dict == None):
			Logger.error("Not Enough Information to get Torrent Data.\nCannot Ignore Error. Program will now Terminate")
		elif (torrent_dict == None and raw_data != None):
			torrent_dict = Bencoder.bdecode(raw_data)

		self.started 		= False
		self.reactor 		= reactor
		self.start_time 	= time.time()
		self.comment 		= torrent_dict['comment']
		self.info 			= torrent_dict['info']
		self.announce_list 	= torrent_dict['announce-list']
		self.announce 		= torrent_dict['announce']
		self.peer_id 		= peer_id
		self.port 			= port
		self.payload 		= self.generateBasicPayload()
		self.protocol 		= Core.BitTorrentFactory(self)
		self.fileManager 	= FileManager.FileManager(self.info)
		self.requester 		= RequestManager.RequestManager(self)
		self.payload 		= self.updatePayload()

		# The handhshake message to be sent is constant for a given torrent 
		# str() has been overloaded
		self.handshake_message = str(Messages.Handshake(self.payload['info_hash'], self.payload['peer_id'])) 
		print "Total number of pieces :", len(self.info['pieces'])
Exemple #38
0
    def record(self, userInput):
        """Collects and formats user input and data for writing to a file.

        Args:
            uerInput: User inputted value to be recorded with data.

        Returns:
            None
        """
        if self.newFile:
            recordEntry = self.inputTitle + self.orderedNames
            FileManager.writeData(self.fileName, recordEntry)
            self.newFile = False
        recordEntry = [userInput] + self.getCurrentValues()
        FileManager.writeData(self.fileName, recordEntry)
        self.updateLastFiveRecorded(recordEntry)
 def run(self):
     """main"""
     global SON
     while not self._stopevent.isSet():
         typ, received = Client.receiveMsg()
         if typ == "N":
             rec = Client.notify(received)
             if rec == "ko":
                 print("\n-->%s" % received)
         elif typ == "F":
             rec = received.split(";")
             FileManager.convertFileReceive(rec[0], rec[1])
             rec = Client.notify("notif;Transfert;Fichier "+rec[1]+" bien reçu;4")
             if rec == "ko":
                 print("\n-->Fichier "+rec[1]+" bien reçu")
         else:
             print("\n-->%s" % received)
Exemple #40
0
 def printUngradedNotes(data,param):
     returnText=""
     currentCourse = data['currentCourse']
     for i in range(1,16):
         for s in currentCourse.students:
             if FileManager.notesExist(s.gradedPath, i):
                 if s.getScoreForNotes(i)==0:
                     returnText+="Notes for %s %s credit %d need to be graded.\r\n" % (s.firstName,s.lastName, i)
     return returnText
Exemple #41
0
	def __init__(self, mainWindow, debugMode=False):
		QtCore.QObject.__init__(self)

		# Prints angry debug messages, if activated
		self.debugMode = debugMode

		# Register mainWindow object
		self.mainWindow = mainWindow

		# Create/initialize other objects
		self.fileManager      = FileManager()
		self.executionManager = ExecutionManager(self)
		self.buildManager     = BuildManager(self)
		self.dialogManager    = DialogManager(self.mainWindow)

		# Connect signals from newFileDialog and saveAsDialog to controller methods
		self.dialogManager.newFileDialog.accepted.connect(self.on_new_file_accepted)
		self.dialogManager.saveAsDialog.accepted.connect(self.on_save_As_file_accepted)

		# Connect find replace dialog button(s) to there handler method(s)
		self.dialogManager.findReplaceDialog.close_button.clicked.connect(self.dialogManager.findReplaceDialog.hide)
		self.dialogManager.findReplaceDialog.replace_all_button.clicked.connect(self.on_replace_all_button)
		self.dialogManager.findReplaceDialog.replace_button.clicked.connect(self.on_replace_button)
		self.dialogManager.findReplaceDialog.find_button.clicked.connect(self.on_find_button)

		# Connect goto line dialog buttons(s) to appropriate handler method(s)
		self.dialogManager.gotoLineDialog.accepted.connect(self.on_actionGoto_line_accepted)

		# Overriding standard exit behavior hideous hack?
		self.mainWindow.closeEvent=self.on_exit

		# Link UI elements to functions
		for item in self.mainWindow.findChildren(QtGui.QAction): # Menubar action elements
			try:
				itemName = str(item.objectName())
				if itemName != "":
					function = self.__getattribute__("on_" + itemName)
					item.triggered.connect(function)
			except AttributeError:
				if(debugMode):
					print "Controller should have a member function called '%s', but doesn't!" %("on_"+itemName)

		for item in self.mainWindow.findChildren(QtGui.QPushButton): # Buttons elements
			try:
				itemName = str(item.objectName())
				if itemName != "":
					function = self.__getattribute__("on_" + itemName)
					item.clicked.connect(function)
			except AttributeError:
				if(debugMode):
					print "Controller should have a member function called '%s', but doesn't!" %("on_"+itemName)

		inputTextBox = self.mainWindow.findChild(QtGui.QLineEdit, 'stdinTextBox');
		inputTextBox.returnPressed.connect(self.enter);
		self.disableProjectControls()
	def ejecutarAccion(self,delta):
		if(self.duracion>0):
			self.duracion-=delta

		if(self.tipo_proceso == 1 or self.tipo_proceso == 2):
			if self.tipo_proceso == 1:
				llamada = 'Llamada hecha a: '
			else:
				llamada = 'Llamada recibida de: '
			data = self.opciones[0] +'\t'+ 'Fecha: ' + str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)) +'\t'+ 'Duracion: ' + self.opciones[1] +'\n'
			if (not(self.lasth) or not(self.lasth == llamada+data)):
				# try:
				if(fm.fileExist("Historial.txt")):
					fm.editFile("Historial.txt",llamada+data,str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)))
				else:
					fm.createFile("Historial.txt",llamada+data,str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)))
					#EditFile
				# 	fh = open("Historial.txt", "a")
				# 	fh.write(llamada+data)
				# finally:
				# 	fh.close()
			self.lasth = llamada+data
		elif(self.tipo_proceso == 3 or self.tipo_proceso == 4):
			if self.tipo_proceso == 3:
				sms = 'Mensaje enviado a: ' +'\t'+ self.opciones[0] +'\t'+ 'Fecha: ' + str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)) +'\n'
			else:
				sms = 'Mensaje recibido de: ' +'\t'+ self.opciones[0] +'\t'+ 'Fecha: ' + str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)) +'\n' + self.opciones[1] + '\n'
			if(not(self.lasts) or not (self.lasts == sms)):
				if(fm.fileExist("SMS.txt")):
					fm.editFile("SMS.txt",sms,str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)))
				else:
					fm.createFile("SMS.txt",sms,str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)))
			self.lasts = sms
		elif(self.tipo_proceso >= 5 and self.tipo_proceso <= 10):
			if(self.tipo_proceso == 5):
				accion = 'Agregar Contacto: ' + self.opciones[0] +'\t'+'\t'+ 'Numero: ' + self.opciones[1] +'\n'
			elif(self.tipo_proceso == 6):
				accion = 'Proceso Cualquiera' +'\t'+'\t'+ 'Duracion: '+ self.opciones[0] +'\n'
			elif(self.tipo_proceso == 7):
				accion = 'Mandar ubicacion'+'\t'+'\t'+ 'Duracion: '+ self.opciones[0] +'\n'
			elif(self.tipo_proceso == 8):
				accion = 'Ver ubicacion'+'\t'+'\t'+ 'Duracion: '+ self.opciones[0] +'\n'
			elif(self.tipo_proceso == 9):
				accion = 'Jugar'+'\t'+'\t'+ 'Duracion: '+ self.opciones[0] +'\n'
			elif(self.tipo_proceso == 10):
				accion = 'Escuchar musica' +'\t'+'\t'+ 'Duracion: '+ self.opciones[0] +'\n'
			if(not(self.lastp) or not(self.lastp == accion)):
				if(fm.fileExist("Procesos.txt")):
					fm.editFile("Procesos.txt",accion,str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)))
				else:
					fm.createFile("Procesos.txt",accion,str(datetime.datetime.fromtimestamp(self.fecha_ejecucion)))
			self.lastp = accion
	def loadFiles(self):
		self.loadMazes()
		self.scores = FileManager.readScores()
	def loadMazes(self):
		self.mazes = ["Random Maze (Easy)","Random Maze (Medium)", 
		"Random Maze (Hard)"] 
		self.smazes = FileManager.readMaze()
		for name in self.smazes:
			self.mazes.append(name)
Exemple #45
0
def getFiles():
    global listbox
    for item in FileManager.getAllFiles("./"):
        log.debug("Add item to listbox: {0}".format(item))
        listbox.insert(END, item)
Exemple #46
0
 def sortFiles(data,param):
     courses = data['courses']
     currentCourse = data['currentCourse']
     students = currentCourse.students
     return FileManager.sortFiles(students, currentCourse)
        data.append(list(musicdata[k]))
    musicdata = data
    
    mymodel=TestModel(musicdata, log, my)
    win = TestPanel(nb, log, model=mymodel, )
    return win

#----------------------------------------------------------------------



overview = """<html><body>
<h2><center>DataViewCtrl with DataViewIndexListModel</center></h2>

This sample shows how to derive a class from PyDataViewIndexListModel and use
it to interface with a list of data items. (This model does not have any
hierarchical relationships in the data.)

<p> See the comments in the source for lots of details.

</body></html>
"""



if __name__ == '__main__':
    import FileManager
    import sys
    FileManager.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

Exemple #48
0
class SFLibManager():
    def __init__(self, parent, uiObj):
        #Declare Project Variables
        self.__configFile = os.path.join(os.path.expanduser(os.path.join('~',".sift")),'sf_config.ini')
        self.loadedProjName = ''
        self.loadedProjPath = ''
        self.loadedProjType = ''

        #Determine the path to sift.py
        self.baseDir = self.initBaseDir()

        #Declare all Managers
        self.uiObj = uiObj
        self.parent = parent
        self.treeViewMgr = TreeviewManager(self, 
                                           self.uiObj.treeWidget_proj, 
                                           self.uiObj.treeWidget_nonProj,
                                           self.uiObj.tabWidget_treeview)
        self.fileMgr = FileManager(self)
        self.viewMgr = ViewManager(self, self.uiObj.tabWidget_viewer)
        self.messageMgr = MessageManager(self, self.uiObj.statusbar)
        self.configMgr = ConfigManager(self)        

        #Pass Managers to other Managers that need them
        #(Basically this simulates the Singleton pattern since python can't do it natively)
        self.viewMgr.setFileManager(self.fileMgr) 
        self.treeViewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setViewManager(self.viewMgr)

        #Load up things needed to happen at start up, but after the managers are all loaded
        self.viewMgr.resetMainViewer()

    # - - - - - - - - - - - - - - - - 
    # - Name: loadProject()
    # - Parameters: file_dirs, projPath - provided by sift
    # - Description: Loads the project from the .all by creating a list of all .fml + paths.
    # - Lastly the treeview is populate to allow the user to navigate through the flows
    def loadProject(self, fileDirs, projPath, projName, projType):
        #Reset the main viewer back the welcome tab in case we're opening a project while already opened
        self.viewMgr.resetMainViewer()

        #Make sure fileDirs is a list
        if(not isinstance(fileDirs, list)):
            fileDirs = [fileDirs]

        #Make sure fileDirs is a correct form
        if((len(fileDirs) == 0) or
           (not isinstance(fileDirs[0], QtCore.QString) and not isinstance(fileDirs[0], str)) or
           fileDirs[0] == ''):
            self.printError("Project path is incorrect or not a string",
                                       "Project NOT loaded successfully!", 10)
            return

        #Get data from the .all
        self.loadedProjName = projName
        self.loadedProjPath = projPath
        self.loadedProjType = projType

        #Load project into file manager and populate the treeview, if they fail, tell the user
        if (self.fileMgr.loadProject(fileDirs) and self.treeViewMgr.loadTreeviewProject()):
            self.uiObj.tabWidget_treeview.setCurrentIndex(0)
            self.out("Project loaded successfully", 6) 
        else:
            msg =  "Project data incorrect, try loading project in sift using the open button.\n"
            msg +=  "\tIf this is a Lua project, loading lua files on windows is not yet implemented."
            self.printError(msg, "Project NOT loaded successfully", 10) 

    # - - - - - - - - - - - - - - - - 
    # - Name: loadFiles()
    # - Parameters: fileList
    # - Description: Loads individual files given by the user that are not associated with a .all/project
    def loadFiles(self, fileList):
        #Pass to fileMgr to load, if any are already loaded in proj, remove and warn user
        filesNotAdded = self.fileMgr.addFiles(fileList)

        #If any files were tossed, tell the user
        if(len(filesNotAdded) > 0):
            self.messageMgr.loadedFilesTossedBox(filesNotAdded)

        #If any files were actually loaded, update and switch to nonproj treeview
        if(len(filesNotAdded) < len(fileList)):
            #Populate the treeview
            self.treeViewMgr.loadTreeviewNonProject()
            self.uiObj.tabWidget_treeview.setCurrentIndex(1)

            #Tell user project is loaded
            self.out(str(len(fileList) - len(filesNotAdded)) + " of " + str(len(fileList)) + " file(s) loaded successfully", 6)
                

    # - - - - - - - - - - - - - - - - 
    # - Name: reloadFile()
    # - Parameters: path
    # - Description: Reloads a file if it is currently being viewed. If there are unsaved changes
    # - prompt the user for what they want to do
    def reloadFile(self, fileName, pathOrProj):
        #Get List of all tabs displaying something from the file
        displayedIndexs = self.viewMgr.getDisplayedFileIndexsList(fileName, pathOrProj)
        unsavedChanges = []

        #For every item being displayed that doesn't have unsaved changes, just reload them without bothering user
        #But if there are one or more with changes give the user a warning.
        for index in displayedIndexs:
            if(not self.viewMgr.doesTabHaveStatus("unsaved", index)):
                self.viewMgr.reloadTab(index)

            #If there are unsaved changes, we need to know what the user wants since just saving over
            #their changes may cause unwanted fury.
            else:
                unsavedChanges.append(index)

        #If any tab had unsaved changes, tell the user and see what they want to do
        if (len(unsavedChanges) > 0):
            result = self.messageMgr.conflictMessageBox(fileName)
            #User wants to discard their changes, and reload the viewer with the external changes
            if result == 'discard':
                for index in unsavedChanges:
                    self.viewMgr.reloadTab(index)

            #User wants to Ignore the external changes and overwrite them with whats in the viewer
            #Add the conflict status so they can see that the viewer and file are out of sync
            elif result == 'ignore':
                for index in unsavedChanges:
                    self.viewMgr.addStatus('conflict', index)

    # - - - - - - - - - - - - - - - - 
    # - Name: reloadFileTreeview()
    # - Parameters: path
    # - Description: Reloads a file entry in the treeview, if it exists
    def reloadFileTreeview(self, fileName, pathOrProj):
        self.treeViewMgr.reloadFileTreeview(fileName, pathOrProj)

    # - - - - - - - - - - - - - - - - 
    # - Name: *Update() 
    # - Parameters: None
    # - Description: update the flow that is being viewed in the main viewer. When
    # - a new selection is made in the treeview an event calls these functions, which
    # - are passed to the treeview where it then calls the view manager, giving it the 
    # - name of the flow that needs to be displayed in the view
    def tvProjUpdate(self):
        self.treeViewMgr.projUpdate()

    def tvNonProjUpdate(self):
        self.treeViewMgr.nonProjUpdate()

    # - - - - - - - - - - - - - - - - 
    # - Name: resizeTreeview() 
    # - Parameters: None
    # - Description: When something on the window is moved, resize the tree widgets
    # - so they always match the tab widgets size.
    def resizeTreeview(self):
        #First resize the tab widget to the containing frames size, then
        #use that to resize the treeviews that reside in the tab widget
        self.treeViewMgr.resizeTreeviews(self.uiObj.tabWidget_treeview.size())

    # - - - - - - - - - - - - - - - - 
    # - Name: out 
    # - Parameters: 
    # - Description: Print normal messages to the user in the appropriate fields depending on 
    # - the arguments passed in.
    # - Usage: out("Message to the output box"), out("Message to the status bar",  10 [time to show message in seconds])
    # -        out("Message to output box", "Message to status bar", 10 [time to show message in seconds])
    def out(self, text, *args):
        self.messageMgr.out(text, args)

    # - - - - - - - - - - - - - - - - 
    # - Name: printError
    # - Parameters: 
    # - Description: Similar to out, but for error messages
    def printError(self, text, *args):
        self.messageMgr.printError(text, args)

    # - - - - - - - - - - - - - - - - 
    # - Name: displayFlow
    # - Parameters: dIndex - If there are duplicate flows in an fml, the index of 
    # - which copy this is
    # - Description: Calls viewmgr to display the flow in an appropriate veiwer tab
    def displayFlow(self, fileName, pathOrProj, flowName, dIndex=None):
        self.viewMgr.displayFlow(fileName, pathOrProj, flowName, dIndex=dIndex)

    # - - - - - - - - - - - - - - - - 
    # - Name: displayFml
    # - Parameters:  
    # - Description: Calls the view manager to display the fml in an appropriate tab
    def displayFml(self, fileName, pathOrProj):
        self.viewMgr.displayFml(fileName, pathOrProj)

    # - - - - - - - - - - - - - - - - 
    # - Name: addFindHistoryEntry(combobox)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: adds the current text in the combobox to the config history
    def addFindHistoryEntry(self, combobox):
        self.configMgr.addFindHistoryEntry(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: addReplaceHistoryEntry(combobox)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: adds the current text in the combobox to the config history
    def addReplaceHistoryEntry(self, combobox):
        self.configMgr.addReplaceHistoryEntry(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: addRecentPath(flowName, fmlPath)
    # - Description: adds a flowname and fml path to the config history for the recent menu
    def addRecentPath(self, fileName, pathOrProj, flowName=None, dIndex=None):
        #Need to store both path and proj in the config file
        path = self.fileMgr.getFilePath(fileName, pathOrProj)
        proj = self.fileMgr.getFileProj(fileName, pathOrProj)
        self.configMgr.addRecentPath(fileName, path, proj, flowName, dIndex)

    def getRecentList(self):
        return self.configMgr.getRecentList()

    # - - - - - - - - - - - - - - - - 
    # - Name: updateComboHistoryEntry(text)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: moves the current text in the combobox to the top of the config history (technically bottom
    # - of the xml nodes since it can only be appended to. String list is flipped in loadCombo())
    def updateComboHistoryEntry(self, combobox):
        self.configMgr.updateComboHistoryEntry(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: updateFindOptions(text)
    # - Parameters: ops_d - a dictionary of all the options checked in the dialog
    # - Description: saves all the options in config.ini, updates if they already exist
    def updateConfigOptions(self, ops_d, comp):
        self.configMgr.updateConfigOptions(ops_d, comp)

    # - - - - - - - - - - - - - - - - 
    # - Name: loadCombo(combobox)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: Fills the combo box with the items in the config file
    def loadCombo(self, combobox):
        self.configMgr.loadCombo(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: getFindConfigDict()
    # - Description: Get the dictionary of the windows radio and check states
    def getConfigDict(self, comp):
        return self.configMgr.getConfigDict(comp)

    # - - - - - - - - - - - - - - - - 
    # - Name: findTextCurrent()
    # - Description: Get the next occurrence of text in the currently selected tab of main viewer
    def findTextCurrent(self, text, flags, flip=False):
        return self.viewMgr.findTextCurrent(text, flags, flip)

    #-- Return True if the newly found match is within the search area boundaries
    def isCursorInSearchArea(self):
        saBeg = self.viewMgr.getSearchAreaBeginning()
        saEnd = self.viewMgr.getSearchAreaEnd()
        cEnd = self.viewMgr.getCursorEnd()

        if(self.docCoordIsGreater(cEnd, saBeg) and self.docCoordIsLess(cEnd, saEnd)):
            return True
        else:
            return False

    def docCoordIsGreater(self, coord1, coord2):
        #is coord1 greater than (its position is passed) coord2
        if((coord1[0] == coord2[0] and coord1[1] > coord2[1]) or
            (coord1[0] > coord2[0])):
            return True

        return False

    def docCoordIsLess(self, coord1, coord2):
        #is coor1 less than (its position is before) coord2
        if((coord1[0] == coord2[0] and coord1[1] < coord2[1]) or
            (coord1[0] < coord2[0])):
            return True

        return False

    def setCursorToReference(self, line, pos):
        self.viewMgr.setCursorToReference(line, pos)

    def getCursorBeginning(self):
        return self.viewMgr.getCursorBeginning()

    def getCursorEnd(self):
        return self.viewMgr.getCursorEnd()

    def getSearchAreaBeginning(self):
        return self.viewMgr.getSearchAreaBeginning()

    def getSearchAreaEnd(self):
        return self.viewMgr.getSearchAreaEnd()

    def setSearchArea(self):
        return self.viewMgr.setSearchArea()

    def unsetSearchArea(self):
        self.viewMgr.unsetSearchArea()

    def reselectSearchArea(self):
        self.viewMgr.reselectSearchArea()

    def getSelectionText(self):
        return self.viewMgr.getSelectionText()

    def isDisplayed(self, fileName, pathOrProj):
        return self.viewMgr.isDisplayed(fileName, pathOrProj)

    # - - - - - - - - - - - - - - - - 
    # - Name: findAllOpenFmls()
    # - Description: Find every file with a reference of text and open them in a new tab
    def findAllOpenFmls(self, text, flags):
        #Get list of [fileNames, pathorProj] the text occurs in
        findList = self.fileMgr.findAllInFiles(text, flags)

        #Open every member of list in a new tab, if tab already exists don't create a new one
        for item in findList:
            self.viewMgr.displayFml(item[0], item[1]) #display item in tab named item

    # - - - - - - - - - - - - - - - - 
    # - Name: findReferences()
    # - Parameters: text - string - text for which to search
    # -             flags - search flags
    # -             isCurrent - bool - is the user searching the current page, False if searching selection
    # - Description: If there is a match for text then return a list of all line numbers and lines the match
    # - occurs in. Handle searching in a selection.
    def findReferences(self, text, flags, isCurrent):
        #Search all lines
        reg = text = re.escape(str(text))
        flag = re.I

        if(flags['wo']):
            reg = '^' + text + '$|'             #text by itself
            reg += '^' + text + '(?=[\s\n])|'       #text at start of line
            reg += '[\s]' + text + '(?=[\s\n])|'    #text in a line
            reg += '[\s]' + text + '$'          #text at the end

        if(flags['cs']):
            flag = 0        

        if(isCurrent):
            return self.viewMgr.getCurrentReferences(reg, flag)
        else:
            return self.viewMgr.getSelectionReferences(reg, flag)

    # - - - - - - - - - - - - - - - - 
    # - Name: findReferencesInFiles()
    # - Parameters: text - string - text for which to search
    # -             flags - search flags
    # - Description: If there is a match for text then display the line number and line in
    # - the output box. Searches all fml files.
    def findReferencesInFiles(self, text, flags):
        return self.fileMgr.findReferences(text, flags)

    # - - - - - - - - - - - - - - - - 
    # - Name: getCount()
    # - Description: Returns the number of matches for a given search
    def getCount(self, text, flags, isCurrent):
        #Search all lines
        reg = text = str(text)
        flag = re.I

        if(flags['wo']):
            reg = '^' + text + '$|'             #text by itself
            reg += '^' + text + '(?=[\s\n])|'       #text at start of line
            reg += '[\s]' + text + '(?=[\s\n])|'    #text in a line
            reg += '[\s]' + text + '$'          #text at the end
            

        if(flags['cs']):
            flag = 0        

        if(isCurrent):
            count = self.viewMgr.getCountCurrent(reg, flag)
        else:
            count = self.viewMgr.getCountSelection(reg, flag)
        return count

    def isFileLoaded(self, fileName, path):
        return self.fileMgr.isFileLoaded(fileName, path)

    def isProjLoaded(self, proj=None):
        if(proj and self.loadedProjName == proj):
            return True
        elif(not proj and self.loadedProjName != ''):
            return True

        return False

    def getDownloadFileList(self):
        return self.fileMgr.getDownloadFileList(self.loadedProjName, self.loadedProjPath)

    def tabAlreadyExists(self, tabName):
        return self.viewMgr.tabAlreadyExists(tabName)

    def tabContainsPos(self, pos):
        return self.viewMgr.tabContainsPos(pos)

    def getCurrentTabText(self):
        return self.viewMgr.getCurrentTabText()

    def isFirstSearch(self):
        #If the search tag is in the tab title, then its not the first search
        if(self.viewMgr.doesTabHaveStatus('search')):
            return False
        return True

    def finishSearch(self):
        self.viewMgr.removeStatus('search')
        self.viewMgr.unsetSearchArea()

    def finishAllSearchs(self):
        self.viewMgr.removeAllStatus('search')
        self.viewMgr.unsetAllSearchAreas()

    def startSearch(self):
        self.viewMgr.addStatus('search')

    def addStatus(self, status):
        self.viewMgr.addStatus(status)

    def selectionToFill(self, selection):
        #Determine if selection is ok to post in the find textbox when find dialog opens
        selection = selection.strip(' \n(') #strip leading/trailing spaces and new lines
        
        #If its empty, just return it
        if(selection == ''):
            return selection

        #If its a flow or keyword (ie has letters numbers or underscores uninterrupted)
        if(re.search('^(flow|cmd)?[_\w\d]+$', selection)):
            return selection

        #If what remains isn't a consecutive group of letters, numbers, underscores
        return ''

    # --- Config Save/Load Methods --- #
    def saveWindowState(self, width, height, tvWidth):
        self.configMgr.addWindowSize(width, height)
        self.configMgr.addTreeviewWidth(tvWidth)
        self.configMgr.save()

    def getWindowSize(self):
        return self.configMgr.getWindowSize()

    def getTreeviewWidth(self):
        return self.configMgr.getTreeviewWidth()
        
    def setLastOpenDir(self, path):
        self.configMgr.addLastOpenDir(path)

    def getLastOpenDir(self):
        return self.configMgr.getLastOpenDir()

    #--- Edit Related Methods ---#

    def cut(self):
        self.viewMgr.cut()

    def copy(self):
        self.viewMgr.copy()

    def paste(self):
        self.viewMgr.paste()

    def undo(self):
        self.viewMgr.undo()

    def redo(self):
        self.viewMgr.redo()

    def indent(self):
        self.viewMgr.indent()

    def unindent(self):
        self.viewMgr.unindent()

    def comment(self):
        self.viewMgr.comment()

    def uncomment(self):
        self.viewMgr.uncomment()

    def replace(self, text):
        self.viewMgr.replace(text)

    def beginUndoAction(self):
        self.viewMgr.beginUndoAction()

    def endUndoAction(self):
        self.viewMgr.endUndoAction()

    #--- Saving ---#
    def saveCurrentTab(self):
        result = self.viewMgr.saveTab()

        #If the tab failed to save, let the user know
        if (len(result) > 0):
            self.messageMgr.failedSaveBox(result)
            return False

        return True

    def saveAllTabs(self):
        #result will be the fileNames of what failed to save, if empty nothing failed
        result = self.viewMgr.saveAllTabs()

        if(len(result) > 0):
            self.messageMgr.failedSaveBox(result)
            return False

        return True

    def anyUnsavedChanges(self):
        return self.viewMgr.anyUnsavedChanges()

    def saveAnyUnsavedChanges(self):
        self.viewMgr.saveAnyUnsavedChanges()

    def getRepo(self):
        return self.fileMgr.getRepo()

    def initBaseDir(self):
        dir = sys.path[0]

        #If there is a file on the end (cause of randals windows bug) remove it
        parts = os.path.split(dir)
        if(re.search('.*\..*', parts[1])):
            dir = parts[0]

        return dir

    #--- Getters ---#
    def getFileNameFromFuncName(self, projName, funcName):
        return self.fileMgr.getFuncParent(projName, funcName)

    def getBaseDir(self):
        return self.baseDir

    def getAboutText(self):
        return self.fileMgr.getAboutText()

    def getDocDir(self):
        dir = self.getBaseDir()

        if(os.path.exists(os.path.join(dir, 'SiftFlow'))):
            return os.path.join(dir, 'SiftFlow', 'docs')

        #if all else fails, return str to avoid None type cat error
        return dir

    def getIconDir(self):
        #Find the resource path that has SiftFlow, add the images folder to it
        dir = self.getBaseDir()       

        if(os.path.exists(os.path.join(dir, 'SiftFlow'))):
            return os.path.join(dir, 'SiftFlow', 'images')

        #If all else fails, return a string to get around a None type str cat error
        return dir

    def getConfigFile(self):
        return self.__configFile

    def getLineNumberOffset(self):
        return self.viewMgr.getLineNumberOffset()

    def getLoadedProjName(self):
        return self.loadedProjName

    def getLoadedProjType(self):
        return self.loadedProjType

    def getLoadedProjPath(self):
        return self.loadedProjPath

    def getMainUiActions(self):
        #Return all the menu actions from the main window ui
        actions = {
            'cut':          self.uiObj.actionCut,
            'copy':         self.uiObj.actionCopy,
            'paste':        self.uiObj.actionPaste,
            'find':         self.uiObj.actionFind,
            'findinfiles':  self.uiObj.actionFindInFiles,
            'currentReferences': self.uiObj.actionReference,
            'referenceInFiles': self.uiObj.actionReferenceInFiles
        }
        return actions
Exemple #49
0
 def scanFiles(data,param):
     currentCourse = data['currentCourse']
     students = currentCourse.students
     returnText = ""
     for s in students:
         
         count = 0
         path = s.gradedPath
         
         files = FileManager.getPDFFiles(path)
         printCount = 1
         
         for f in files:
             sys.stdout.write("\rScanning file %d of %d for %s %s\r\n" % (printCount,len(files),s.firstName,s.lastName))
             sys.stdout.flush()
             printCount+=1
             
             filename = os.path.split(f)[1]
             num = filename.split("-")[0]
             new = True
             for a in s.assignments:
                 if a.number == num:
                     new = False
             if filename.find("packet")!=-1:
                 new=False
             if new:
                 count+=1
                 text = PDFManager.getStr(f)
                 score = PDFManager.getScore(text = text)
                 dateSubmitted = None
                 #Account for files that can't be read but grade was input manually
                 if score==0:
                     txtFile = os.path.splitext(f)[0]+".txt"
                     if os.path.exists(txtFile):
                         saveFile = open(txtFile)
                         str = saveFile.readline()
                         (score,dateSubmitted) = str.split(" - ")
                     else:
                         pass                            
                 
                 assignment = Assignment.Assignment()
                 assignment.score = score
                 assignment.number = num
                 if dateSubmitted!=None:
                     assignment.dateSubmitted = dateSubmitted
                 try:
                     assignment.credit = currentCourse.assignments[num]
                 except:
                     assignment.credit = -1
                 s.assignments.append(assignment)
                 
                 #read txt file and check if assignment has a score
                 #update txt file
                 #write text file
                 
         returnText+="Added %d grades for %s %s \r\n" % (count,s.firstName,s.lastName)
     currentCourse.students = students
     data['currentCourse'] = currentCourse
     for i in range(1,16):
         for s in students:
             path = s.gradedPath+"%d\\"%i
             destPath = s.gradedPath
             files = FileManager.getPDFFiles(path)
             for f in files:
                 filename = os.path.split(f)[1]
                 if filename.find("packet")!=-1:
                     files.remove(f)
             if (len(files)>0):
                 PDFManager.merge(files, destPath+"packet%d.pdf"%i)
     
     courses = data['courses']
     for c in courses:
         for s in c.students:
             counter=0
             for a in s.assignments:
                 if a.score=="00":
                     counter+=1
                     print("Double zero found: %s for %s %s" % (a.number,s.firstName,s.lastName))
                     input=raw_input("Should I change to 100?")
                     if input=="y" or input=="yes":
                         a.score="100"
                         print("Score changed.")
     
     
     
     return returnText
Exemple #50
0
def getCourses(url):
	html = FileManager.read(url)
	htmlSoup = BeautifulSoup(html)
	#print htmlSoup
	courses = htmlSoup.find_all("li")
	#print courses
	for course in courses:
		result = course.text.encode('utf-8')
		result = result.replace("(link)","")
		spot = result.find("(")
		if spot != -1:
			result = result[:spot]
		if "Ph.D"  not in result:
			if "M." not in result:
				if "D." not in result:
					print result
		
	'''classes = []
	for course in courses:
		#name,number,desc,pre,co,units,time
		titleNumber = course.dt.string
		number = (titleNumber[:6].strip())
		title = (titleNumber[7:].strip())
		
		#rest = course.dd.get_text("\n").splitlines()
		timeandUnits = course.dd.next_element.string.strip()
		
		if (":" in timeandUnits):
			#has units
			spot = timeandUnits.index(":")
			time = (timeandUnits)[:spot].strip()
			units = (timeandUnits)[spot+1:].strip()
		else:
			time = timeandUnits.strip()
			units = "Unknown"

		desc = list(course.dd.descendants)
		
		newDesc = []
		desc.pop(0)
		for item in desc:
			if (item != None) and ("<" not in item.encode('utf-8')):
				newDesc.append(item.strip())

		desc = ""
		for item in newDesc:
			desc += item

		desc = desc.encode('utf-8')

		if ("Course Website:" in desc):
			spot = desc.index("Course Website:")
			website = desc[spot + 15:].strip()
			desc = desc[:spot]
		else:
			website = "None"
		

		if ("Corequisites:" in desc or "Corequisite:" in desc):
			if ("Corequisites:" in desc):
				spot = desc.index("Corequisites:")
				co = desc[spot + 13:].strip()
				desc = desc[:spot]
			else:
				spot = desc.index("Corequisite:")
				co = desc[spot + 12:].strip()
				desc = desc[:spot]

		else:
			co = "None"

		if ("Prerequisites:" in desc or "Prerequisite:" in desc):
			if ("Prerequisites:" in desc):
				spot = desc.index("Prerequisites:")
				pre = desc[spot + 14:].strip()	
				desc = desc[:spot]
			else:
				spot = desc.index("Prerequisite:")
				pre = desc[spot + 13:].strip()	
				desc = desc[:spot]

		else: 
			pre = "None"


		classes.append(FileManager.Course(title,number,desc,pre,co,units,time,website))

	return classes


			
'''
		


		
		
	


	return []
Exemple #51
0
while(exitStatus==0):
	os.system('clear') 
	print "\n" + bcolors.HEADER + greetingsList[randint(0,len(greetingsList)-1)] + " " + masterName + bcolors.ENDC 
	print "\n" + bcolors.OKGREEN + serviceList[randint(0,len(serviceList)-1)] + bcolors.ENDC
	print bcolors.OKBLUE + "1)Notes\n2)Send Text\n3)Network scripts\n4)Tell Me A Joke\n5)Exit\n" + bcolors.ENDC
	response = raw_input("Response: ")
	
	if(response=="5"): # Exit 
		print bcolors.OKGREEN + goodbyeList[randint(0,len(goodbyeList)-1)] + bcolors.ENDC
		exitStatus = 1 	#sys.exit(0)
	elif(response=="1"): # notes
		print bcolors.HEADER + "Notes" + bcolors.ENDC
		path = "txt/notes"
		print "Current Files: " 
		fileNames = FileManager.displayFiles(path)
		print bcolors.OKBLUE + "\n1)Read File\n2)Write File\n3)Go Back" + bcolors.ENDC
		response1 = raw_input("Response: ")
	elif(response=="4"): #tell me a joke 
		with open("txt/alfredTalks/jokes.txt","r") as jokes_file:
			jokeList = [line.strip() for line in jokes_file]
		jokes_file.close()
		jokeCounter = 0
		while(jokeCounter<102):
			print jokeList[jokeCounter] 			
			reply = raw_input("\nWould you like to hear another?\n1)Yes\n2)No\nResponse: ")
			if(reply == "2"):
				jokeCounter = 103
			else:
				jokeCounter = jokeCounter + 1
	elif(response=="3"): # network scripts
def input(consola):
    
	global lastconsola
	#print "lastconsola " + lastconsola
	#print "consola " + consola
	if( (not(consola.value == lastconsola) or (lastconsola == "top") or (lastconsola == "agenda")  or (lastconsola == "historial") )) :
	    try :
	        variable = consola.value.split(";")
	    except :
	        pass

		global procesos
		global ejecutandose
		global tiempoMaquina

	    if(len(variable)>=5):
	        #Crear un proceso a partir de las componentes de la linea
	        print "Proceso por comando"
	        opciones = []
	        for x in range(4,len(variable)):
	            opciones.append(variable[x])
	        #Crear un proceso a partir de las componentes de la linea
	        p = Proceso(variable[0], int(variable[1])+tiempoMaquina, int(variable[2]), int(variable[3]), opciones)
	        procesos.append(p)
	        print str(p.getDuracion())
	        procesos = sorted(procesos, key=lambda Proceso: Proceso.fecha_ejecucion) 
	        variable=[]


	    elif(consola.value == "salir"):
			sys.exit(0)

	    if(consola.value == "dhistorial"):
	   		fm.deleteFile("Historial.txt")
	   		fm.deleteFile("SMS.txt")
	   		print "Historial borrado exitosamente"


	    elif(consola.value=="agenda"):
	        print "Agenda"
	        lines_bruto= fm.readFileTo("Procesos.txt")
	        # print lines_bruto
	        lines= lines_bruto.split('\n')

	        i=0
	        for l in range(0,len(lines)):

	        	if (lines[l][0:16]=="Agregar Contacto"):
	        		linea=lines[l].strip()
	        		print "call "+str(i)+": "+linea.split('\t')[0][18:]+": "+linea.split('\t')[2][8:]
	        		i+=1
	        #aqui hay que imprimir la agenda y despues agregar la llamada elegida a la clase proceso
	        variable=""
	        
	    elif(consola.value=="historial"):
	        #aqui hay que imprimir el archivo de historial de llamadas y mensajes
	        print "Historial de Mensajes"
	        lines_bruto= fm.readFileTo("SMS.txt")
	        lines= lines_bruto.split('\n')

	        for l in range(0,len(lines)):
	        	print lines[l].strip()

	        print "Historial de Llamadas"
	        lines_bruto= fm.readFileTo("Historial.txt")
	        lines= lines_bruto.split('\n')

	        for l in range(0,len(lines)):
	        	print lines[l].strip()

	        variable=""
	    elif(consola.value == "top"):
			topfunction()

	    elif(consola.value[0:4] == "copy"):
	    	opcion = consola.value[5:].strip()
	    	if(len(opcion)>0):
	    		if (os.path.isfile("./"+opcion)):
	    			f = open("./"+opcion,'rw+')
	    			text = f.read()
	    			f.close()
	    			if(fm.createFile(opcion,text,str(datetime.datetime.fromtimestamp(tiempoMaquina)))):
	    				print "Archivo copiado con éxito. Para verlo ejecute: open "+opcion
	    		else:
	    			print "La ruta del archivo que menciona no está en la carpeta raiz"

	    elif(consola.value[0:4] == "open"):
	    	opcion = consola.value[5:].strip()
	    	if(len(opcion)>0):
	    		if (fm.fileExist(opcion)):
	    			print "Archivo:"
	    			print "|--INICIO--|\n"+fm.readFileTo(opcion)+"\n|--TERMINO--|"
	    		else:
	    			print "Error 404: File not found :D"

	    elif(consola.value[0:4] == "call"):
			opcion = int(consola.value[5:].strip())

			lines_bruto= fm.readFileTo("Procesos.txt")
			lines= lines_bruto.split('\n')

			i=0
			for l in range(0,len(lines)):

				if (lines[l][0:16]=="Agregar Contacto"):
					if(opcion==i):
						linea=lines[l].strip()
						opciones = []
						opciones.append(linea.split('\t')[2][8:])
						opciones.append(str(random.randrange(1,15)))
						# opciones.append(str(10))
						p = Proceso("hacer_llamada",tiempoMaquina,1, 0,opciones)
						procesos.append(p)
						procesos = sorted(procesos, key=lambda Proceso: Proceso.fecha_ejecucion)
					i+=1
	    elif(consola.value[0:3] == "del"):
			opcion = consola.value[4:].strip()
			if(len(opcion)>0):
				if(fm.fileExist(opcion)):
					fm.deleteFile(opcion)
					print "Archivo borrado con éxito"
				else:
					print "Error 404: File not found :D"

		# elif(consola.value[0:3] == "del"):
		# 	opcion = consola.value[4:].strip()
		# 	if(len(opcion)>0):
		# 		if (fm.fileExist(opcion)):
		# 			fm.deleteFile(opcion)
		# 			print "Archivo borrado con éxito"
		# 		else:
		# 			print "Error 404: File not found :D"
	lastconsola = consola.value
class EvolutionManager(object):


    def __init__(self,
                 fitnessFunction,
                 individualsPerGeneration=100,
                 elitism=1,
                 randIndividuals=0,
                 randFitness=None,
                 mutationRate=0.2,
                 mutationSTDEV=0,
                 maxGenerations=None,
                 stopWithFitness=None,
                 stopAfterTime=None,
                 logDir=None,
                 generationsToKeep=0,
                 snapshotGenerations=None,
                 threads=1,
                 startingGeneration=None):
        """
        :param individualsPerGeneration: the size of the new generation
        :type individualsPerGeneration: int
        :param elitism: preserve the n most fit individuals without mutations or crossovers
        :type elitism: int
        :param randIndividuals: add n random chromosomes to the breeding population
        :type randIndividuals: int
        :param randFitness: random individuals may have very low fitness.  If not None, the maximum of this value and
                                the actual random fitness is used
        :type randFitness: float
        :param mutationRate: the average number of mutations each gene will undergo
        :type mutationRate: float
        :param mutationSTDEV: the standard deviation for the number of mutations each gene will undergo
        :type mutationSTDEV: float

        :param maxGenerations: stop computing after this many generations.  None means no limit
        :type maxGenerations: int
        :param stopWithFitness: stop computing if fitness meets or exceeds this value.  None means no limit
        :type stopWithFitness: float
        :param stopAfterTime: stop computing after this many seconds.  None means no limit
        :type stopAfterTime: float
        :param logDirL: if provided with a log directory then certain generations may be saved
        :type logDir: str
        :param generationsToKeep: the number of generations to save to the log directory.  For example, if set to 5
                                    then the 5 most recent generations will be saved
        :param snapshotGenerations: take a snapshot of the system very N trials
        :type snapshotGenerations: int
        :param threads: the number of threads to use for fitness tests
        :type threads: int
        :param startingGeneration: start with generation defined in YAML instead of a random generation
        :type startingGeneration: str

        """
        self.geneTypes = []
        self.startingChromosomes = []
        self.chromosomeType = None

        self.fitnessFunction = fitnessFunction
        self.individualsPerGeneration = individualsPerGeneration
        self.elitism = elitism
        self.randIndividuals  =  randIndividuals
        self.randFitness = randFitness
        self.mutationRate = mutationRate
        self.mutationSTDEV = mutationSTDEV
        self.maxGenerations = maxGenerations
        self.stopWithFitness = stopWithFitness
        self.stopAfterTime = stopAfterTime
        self.logDir = logDir
        self.generationsToKeep = generationsToKeep
        self.snapshotGenerations = snapshotGenerations
        self.threads = threads
        self.startingGenration = startingGeneration

        self.FM = FileManager()
        self.oldGenerations = []
        self.oldGenerations_perm = []

        def signal_handler(signal, frame):
            print "dumping data"
            self.dataDump()
            sys.exit(0)
        signal.signal(signal.SIGINT, signal_handler)


    def addGeneType(self, geneType):
        """
        Add a new gene type to the expiriment
        :type geneType: GeneType
        """
        if self.chromosomeType is not None:
            raise Exception("New gene types cannot be added after the chromosome template has been finalized!")
        self.geneTypes.append(geneType)

    def getChromomeTemplate(self):
        """
        Return a chromosome of the appropriate type.  Useful for creating specific chromosomes to be added
        :rtype: Chromosome
        """
        if self.chromosomeType is None:
            self.chromosomeType = ChromosomeType(self.fitnessFunction, self.geneTypes)
        return self.chromosomeType.getRandomChromosome()

    def addChromosome(self, chromsome):
        """
        Add a chomosome to the first generation.  This should not be called before adding all gene types
        :type chromsome: Chromosome
        """
        self.startingChromosomes.append(chromsome)

    def run(self):

        if self.chromosomeType is None:
            self.chromosomeType = ChromosomeType(self.fitnessFunction, self.geneTypes)

        generationType = GenerationType(self.chromosomeType)

        if self.startingGenration is None:
            currentGeneration = generationType.getRandomGeneration(max(0, self.individualsPerGeneration-len(self.startingChromosomes)))
        else:
            fobj = open(self.startingGenration)
            flist = []
            for line in fobj:
                flist.append(line)
            fline = "".join(flist)
            currentGeneration = generationType.fromYAML(fline)
            fobj.close()

        currentGeneration.population += self.startingChromosomes
        currentGeneration.doFitnessTests(threads=self.threads)

        print "The most fit individual in the starting generation is\n"
        print currentGeneration.getMostFit()

        startTime = None
        if self.stopAfterTime is not None:
            startTime = time.time()

        try:

            trials = 0
            while True:
                trials += 1

                #take a snapshot
                if self.snapshotGenerations is not None and trials % self.snapshotGenerations == 0:
                    self.oldGenerations_perm.append((trials, currentGeneration))
                #save this trial in temporary storage
                elif self.generationsToKeep > 0:
                    if len(self.oldGenerations) >= self.generationsToKeep:
                        self.oldGenerations = self.oldGenerations[1:]
                    self.oldGenerations.append((trials, currentGeneration))

                #exit conditions
                if self.maxGenerations is not None and trials > self.maxGenerations:
                    print "Maximum number of generations reached"
                    self.dataDump()
                    return currentGeneration.getMostFit()
                if self.stopWithFitness is not None and currentGeneration.getMostFit().fitness >= self.stopWithFitness:
                    print "Sufficient fitness achieved"
                    self.dataDump()
                    return currentGeneration.getMostFit()
                if self.stopAfterTime is not None and (time.time() - startTime) >= self.stopAfterTime:
                    print "Time limit reached"
                    self.dataDump()
                    return currentGeneration.getMostFit()

                print "-" * 100
                print "Begining computations for generation " + str(trials)

                nextGeneration = currentGeneration.getNextGeneration(self.individualsPerGeneration,
                                                                     self.elitism,
                                                                     self.randIndividuals,
                                                                     self.randFitness,
                                                                     self.mutationRate,
                                                                     self.mutationSTDEV)


                nextGeneration.doFitnessTests(threads=self.threads)


                print "The most fit individual in this generation is\n"
                print nextGeneration.getMostFit()

                currentGeneration = nextGeneration

        except Chromosome.PerfectMatch as e:
                print "A perfect match has been found"
                print e.message

                if self.generationsToKeep > 0:
                    if len(self.oldGenerations) >= self.generationsToKeep:
                        self.oldGenerations = self.oldGenerations[1:]
                    self.oldGenerations.append((trials, currentGeneration))
                self.dataDump()
                return e.message

    def dataDump(self):
        """
        Call this function to write all of the pending generations to disk
        """

        if self.logDir is not None:
            if not os.path.exists(self.logDir):
                os.mkdir(self.logDir)
            for trial in self.oldGenerations:
                self.FM.write(trial[1], self.logDir + "/" + str(trial[0]) + ".yaml")
            for trial in self.oldGenerations_perm:
                self.FM.write(trial[1], self.logDir + "/" + str(trial[0]) + ".yaml")
Exemple #54
0
class Controller(QtCore.QObject):

	def __init__(self, mainWindow, debugMode=False):
		QtCore.QObject.__init__(self)

		# Prints angry debug messages, if activated
		self.debugMode = debugMode

		# Register mainWindow object
		self.mainWindow = mainWindow

		# Create/initialize other objects
		self.fileManager      = FileManager()
		self.executionManager = ExecutionManager(self)
		self.buildManager     = BuildManager(self)
		self.dialogManager    = DialogManager(self.mainWindow)

		# Connect signals from newFileDialog and saveAsDialog to controller methods
		self.dialogManager.newFileDialog.accepted.connect(self.on_new_file_accepted)
		self.dialogManager.saveAsDialog.accepted.connect(self.on_save_As_file_accepted)

		# Connect find replace dialog button(s) to there handler method(s)
		self.dialogManager.findReplaceDialog.close_button.clicked.connect(self.dialogManager.findReplaceDialog.hide)
		self.dialogManager.findReplaceDialog.replace_all_button.clicked.connect(self.on_replace_all_button)
		self.dialogManager.findReplaceDialog.replace_button.clicked.connect(self.on_replace_button)
		self.dialogManager.findReplaceDialog.find_button.clicked.connect(self.on_find_button)

		# Connect goto line dialog buttons(s) to appropriate handler method(s)
		self.dialogManager.gotoLineDialog.accepted.connect(self.on_actionGoto_line_accepted)

		# Overriding standard exit behavior hideous hack?
		self.mainWindow.closeEvent=self.on_exit

		# Link UI elements to functions
		for item in self.mainWindow.findChildren(QtGui.QAction): # Menubar action elements
			try:
				itemName = str(item.objectName())
				if itemName != "":
					function = self.__getattribute__("on_" + itemName)
					item.triggered.connect(function)
			except AttributeError:
				if(debugMode):
					print "Controller should have a member function called '%s', but doesn't!" %("on_"+itemName)

		for item in self.mainWindow.findChildren(QtGui.QPushButton): # Buttons elements
			try:
				itemName = str(item.objectName())
				if itemName != "":
					function = self.__getattribute__("on_" + itemName)
					item.clicked.connect(function)
			except AttributeError:
				if(debugMode):
					print "Controller should have a member function called '%s', but doesn't!" %("on_"+itemName)

		inputTextBox = self.mainWindow.findChild(QtGui.QLineEdit, 'stdinTextBox');
		inputTextBox.returnPressed.connect(self.enter);
		self.disableProjectControls()
		
		
	# Put all basic class functions here
	def build(self):

		# before displaying the new build, clear the output text box
		outputConsole = self.mainWindow.findChild(QtGui.QTextEdit, 'outputTextBox')
		if self.executionManager.running:
			self.displayOutput("Error: A program is currently running. Press 'Stop' first, and then hit 'Build' again.",
							"<font color=red>", "</font>")
		else:

			if self.fileManager.projectOpen:
				if self.fileManager.count > 0:


					outputConsole.clear()

					# get the current tab which contains the file to be built
					tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
					currFile = tabWidget.currentWidget()

					# get the file(s) to be built
					files = currFile.file_path

					# set the name of the executable
					filename = currFile.filename
					length = len(filename)
					if (filename[length-4:length] == ".cpp"):
						executableName = filename[0:length-4]
					else:
						# This should never happen if you are trying to build a valid file...
						# If we get here it means that people are trying to compile non-.cpp
						# files...
						executableName = "SIDE.err"


					# TODO get the compilation arguments 
					compileArgs = ""

					# build with parameters defined above
					self.buildManager.build((files,), executableName, compileArgs)

				return

	def run(self):
		outputConsole = self.mainWindow.findChild(QtGui.QTextEdit, 'outputTextBox')
		if self.executionManager.running:
			self.displayOutput("Error: A program is already running. Press 'Stop' first, and then hit 'Run' again.",
							"<font color=red>", "</font>")
		else:

			if self.fileManager.projectOpen:
				if self.fileManager.count > 0:

					outputConsole.clear()

					# Find run args
					runArgsLine = self.mainWindow.findChild(QtGui.QLineEdit, 'runArgs')
					runArgs = runArgsLine.text()
					runArgsLine.clear()
			
					# Run executable
					tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
					currFile = tabWidget.currentWidget()
					filedir = os.path.dirname(str(currFile.file_path))
					executableName = str(currFile.file_path) + ""
					executableName = executableName.replace(filedir + '/', "")
					executableName = executableName.split('.')[0]
					self.executionManager.run(filedir, "./" + executableName, str(runArgs))

					return


	def stop(self):
		self.executionManager.stop()
		return

	def displayOutput(self,outBuffer,HTMLtags=None,HTMLclosingtags=None):
		if HTMLtags != None:
			outputConsole = self.mainWindow.findChild(QtGui.QTextEdit, 'outputTextBox')
			if HTMLclosingtags != None:
				outputConsole.append(HTMLtags + outBuffer + HTMLclosingtags)
			else:
				outputConsole.append(HTMLtags + outBuffer + '</font>')
		else:
			outputConsole = self.mainWindow.findChild(QtGui.QTextEdit, 'outputTextBox')
			outputConsole.append(outBuffer)
	
	def enter(self):
		if self.executionManager.process.state() == 2: # 0->not running, 1->starting, 2->running
			inputTextBox = self.mainWindow.findChild(QtGui.QLineEdit, 'stdinTextBox')
			inputLine = inputTextBox.text()
			inputTextBox.clear()

			outputConsole = self.mainWindow.findChild(QtGui.QTextEdit, 'outputTextBox')
			self.displayOutput(inputLine,'<font color="blue"><i>','</i></font>')
			#outputConsole.append('<font color="blue"><i>' + inputLine + '</i></font>')

			self.executionManager.writeDataToProcess(str(inputLine) + '\n')

	def on_button_stop(self,checked):
		self.stop()
		return
		
	def on_actionStop(self,checked):
		self.stop()
		return
		
	def on_button_enter(self,checked):
		self.enter();
		return

	def on_actionBuild(self,checked):
                tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget()
		if current_tab.isModified() == True:
                        reply = QtGui.QMessageBox.warning(self.mainWindow, 'Build Modified File?',"This file has been modified \n Would you like to save before building? " + current_tab.filename, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
                                current_tab.save()        
		self.build();
		return
	
	def on_button_build(self,checked):
                tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget()
		if current_tab.isModified() == True:
                        reply = QtGui.QMessageBox.warning(self.mainWindow, 'Build Modified File?',"This file has been modified \n Would you like to save before building? " + current_tab.filename, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
                                current_tab.save()    
		self.build();
		return
	
	def on_actionRun(self,checked):
		self.run();
		return

	def on_button_run(self,checked):
		self.run()
		return

	####################################################################
	# File Controls                                                    #
	####################################################################
	def on_actionNew_File(self,checked):
		if self.fileManager.projectPath != None and self.fileManager.projectPath != "":
			self.dialogManager.newFileDialog.open()
		return

	def on_new_file_accepted(self):
		newFileName = self.dialogManager.newFileDialog.textValue()
		if newFileName != "" and newFileName != None:
			for filename in os.listdir(self.fileManager.projectPath):
				if newFileName == filename:
					reply = QtGui.QMessageBox.warning(self.mainWindow, 'Make a New File',"The file "+filename+" already exists.\n Enter another name?", QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
					if reply == QtGui.QMessageBox.Ok:
						self.on_actionNew_File(False)
					return	
			fullname=self.fileManager.projectPath+"/"+newFileName
			newEditor=self.openFile(fullname)
			newEditor.save()
			#say created successfully
			self.displayOutput('#File, '+ str(newEditor.filename)+', was created succesfully.','<font color="green">','</font>')
			self.setFileControls()
		return	
		
	#To be changed to Import File	
	def on_actionOpen_File(self,checked):
		if self.fileManager.projectPath != None and self.fileManager.projectPath != "":
			fullname=QtGui.QFileDialog.getOpenFileName(caption='Open file',directory=self.fileManager.projectPath)
			if fullname != "" and fullname != None:
				newEditor=self.openFile(fullname)
				newEditor.setFile(newDirectory=self.fileManager.projectPath,newName=newEditor.filename)
				#say import succesful
				self.displayOutput('#File, '+ str(newEditor.filename)+', was imported succesfully.','<font color="green">','</font>')
				self.setFileControls()
		return
		
	def on_actionSave(self,checked):
		tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 
		current_tab.save()
		#say save success in output pane
		self.displayOutput('#File, '+ str(current_tab.filename)+', was saved succesfully.','<font color="green">','</font>')
		return
		
	def on_actionSave_As(self,checked):
		if self.fileManager.projectPath != None and self.fileManager.projectPath != "":
			self.dialogManager.saveAsDialog.open()
		return

	def on_save_As_file_accepted(self):
		newFileName = self.dialogManager.saveAsDialog.textValue()
		if newFileName != "" and newFileName != None:
			for filename in os.listdir(self.fileManager.projectPath):
				if newFileName == filename:
					reply = QtGui.QMessageBox.warning(self.mainWindow, 'Save as New',"The file "+filename+" already exists.\n Enter another name?", QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
					if reply == QtGui.QMessageBox.Ok:
						self.on_actionSave_As(False)
					return				
		tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 
		index = tabWidget.indexOf(current_tab)
		newTab=self.openFile(current_tab.file_path)
		newTab.save()
		current_tab.setFile(newDirectory=self.fileManager.projectPath,newName=newFileName)
		tabWidget.setTabText(index,newFileName)
		tabWidget.setCurrentIndex(tabWidget.indexOf(current_tab))
		#say created successfully
		self.displayOutput('#File, '+ str(newFileName)+', was created succesfully.','<font color="green">','</font>')
		self.setFileControls()
		return	

	def on_actionSave_All(self,checked):
		for projectFile in self.fileManager.files:
			projectFile.save()
			#say saved successfully
			self.displayOutput('#File, '+ str(projectFile.filename)+', was saved succesfully.','<font color="green">','</font>')
		return	
		
	def on_actionNewProject(self,checked):
		tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		tabWidget.clear()
		self.on_actionClose_Project(checked)
		dirPath = str(QtGui.QFileDialog.getSaveFileName(parent = self.mainWindow, caption='Create A New Project', directory='./'))
		if(dirPath != ""):
			if os.path.exists(dirPath):
				reply = QtGui.QMessageBox.warning(self.mainWindow, 'Make a New Project',"The directory "+filename+" already exists.\n Select another Directory?", QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
				if reply == QtGui.QMessageBox.Ok:
					self.on_actionNewProject(False)
				return
			else:
				os.makedirs(dirPath)
			if not os.path.exists(dirPath):
				QtGui.QMessageBox.Critical(self.mainWindow, 'ERROR',"Directory creation unsuccessful", QtGui.QMessageBox.Ok)
				#say there was an error
				self.displayOutput('#Project creation encountered an error.','<font color="red">','</font>')
				return
			self.fileManager.set(str(dirPath))
			#say success
			self.displayOutput('#Project , '+ self.fileManager.projectName+', was created succesfully.','<font color="green">','</font>')
			self.enableProjectControls()
			self.setFileControls()
		return		
		
	def on_actionOpen_Project(self,checked):

		# clear welcome tab
#		tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')

		# (check close project)
		self.on_actionClose_Project(checked)
#		tabWidget.clear()

		dirPath = str(QtGui.QFileDialog.getExistingDirectory(parent = self.mainWindow, caption='Open An Existing Project', directory='./'))
		if(dirPath != ""):
			self.fileManager.set(str(dirPath))
			for filename in os.listdir(dirPath):
				if fnmatch.fnmatch(filename, '*.c') or fnmatch.fnmatch(filename, '*.h') or fnmatch.fnmatch(filename, '*.cpp') or fnmatch.fnmatch(filename, '*.cxx') or fnmatch.fnmatch(filename, '*.txt'):
					self.openFile(dirPath +'/'+ filename)
			#say project open successfully
			self.displayOutput('#Project , '+ self.fileManager.projectName+', was opened succesfully.','<font color="green">','</font>')
			self.enableProjectControls()
			self.setFileControls()
		return	

	def on_actionDelete_File(self,checked):
		tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 
		if current_tab != 0:
			index = tabWidget.indexOf(current_tab)
			reply = QtGui.QMessageBox.warning(self.mainWindow, 'Delete this File?',
				"Are you sure you want to delete " + current_tab.filename, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:

				# get file name
				file=current_tab.filename
				deletefile=current_tab.file_path
				# remove the tab
				current_tab.setFile(newDirectory=self.fileManager.projectPath,newName=current_tab.filename+'.bak')  #THIS IS BAD
				current_tab.close()
				self.fileManager.remove(current_tab)
				
				os.remove(str(deletefile))
				print str(current_tab.file_path)
				print str(deletefile)
				tabWidget.removeTab(index)


				#deletion successful
				self.displayOutput('#File, '+ file +', was deleted succesfully.','<font color="green">','</font>')
				self.setFileControls()
		pass		
	
	def on_actionClose_Project(self,checked):

		# clear output console
		outputConsole = self.mainWindow.findChild(QtGui.QTextEdit, 'outputTextBox')
		outputConsole.clear()

		#stop any running process
		self.stop()

		#close each open file
		for projectFile in self.fileManager.files:
			self.closeFile(projectFile)

		#reset the fleManager
		self.fileManager.reset()
		self.disableProjectControls()

		# re-display the welcome tab
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		tab = self.mainWindow.findChild(QtGui.QWidget, 'welcome_tab')

		index = tabWidget.indexOf(tab)
		if index >= 0:
			tabWidget.removeTab(index)
		else:
			tabWidget.addTab(tab, QtCore.QString("Welcome to SIDE++"))		

		return		
		
	#this is called when a user press the 'X' button to quit
	def on_exit(self,event):
		self.on_actionQuit(False)
		event.ignore()

	# we don't use this...... & it is redundant
	def on_close_button(self):
		self.on_actionQuit(False)

	def on_actionQuit(self,checked):
		reply = QtGui.QMessageBox.question(self.mainWindow, 'Please Confirm',
            "Are you sure to quit?", QtGui.QMessageBox.Yes | 
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)
		if reply == QtGui.QMessageBox.Yes:
			self.on_actionClose_Project(checked)
			sys.exit(0)
		pass

	def closeFile(self,projectFile):
		#will this need to run on a seperate thread?
		if projectFile.isModified() == True:
			reply = QtGui.QMessageBox.question(self.mainWindow, 'Save this File?',
            "Would you like to save your changes to "+projectFile.filename, QtGui.QMessageBox.Yes | 
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
				projectFile.save()
				#saved successfully
		tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		tabWidget.removeTab(tabWidget.indexOf(projectFile));
		return

	def openFile(self,projectFile):
		fpath=os.path.dirname(str(projectFile))
		fname=str(projectFile)+""
		fname=fname.replace(fpath+'/',"")
		newEditorPane=ProjectFile(fname,projectFile)

		# Connect `modified` signal for new file to member-helper method
		newEditorPane.modificationStateChanged.connect(self.on_file_modification_state_changed) ##############################################################

		self.fileManager.add(newEditorPane)
		tabWidget=self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		tabWidget.addTab(newEditorPane, QtCore.QString(newEditorPane.filename))
		tabWidget.setCurrentIndex(tabWidget.indexOf(newEditorPane))
		return newEditorPane

	def disableProjectControls(self):
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionNew_File')
		Widget.setFont(QtGui.QFont("Ariel",10,5,False))
		Widget.setEnabled(False)
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionOpen_File')
		Widget.setFont(QtGui.QFont("Ariel",10,5,False))
		Widget.setEnabled(False)
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionClose_Project')
		Widget.setFont(QtGui.QFont("Ariel",10,5,False))
		Widget.setEnabled(False)
		self.setFileControls()
		self.setEditMenuControls()
		self.setActionMenuControls()
		return

	def enableProjectControls(self):
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionNew_File')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(True)
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionOpen_File')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(True)
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionClose_Project')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(True)
		self.setFileControls()
		self.setEditMenuControls()
		self.setActionMenuControls()
		return
		
	def setFileControls(self):
		if self.fileManager.projectOpen:
			if self.fileManager.count > 0:
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionDelete_File')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionSave')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionSave_All')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionSave_As')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				return
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionDelete_File')
		Widget.setFont(QtGui.QFont("Ariel",10,5,False))
		Widget.setEnabled(False)
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionSave')
		Widget.setFont(QtGui.QFont("Ariel",10,5,False))
		Widget.setEnabled(False)
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionSave_All')
		Widget.setFont(QtGui.QFont("Ariel",10,5,False))
		Widget.setEnabled(False)
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionSave_As')
		Widget.setFont(QtGui.QFont("Ariel",10,5,False))
		Widget.setEnabled(False)
		return

    # Edit Menu Controls
	def setEditMenuControls(self):
		if self.fileManager.projectOpen:
			if self.fileManager.count > 0:

				# undo
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionUndo')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# redo
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionRedo')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# redo
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionCut')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# cut
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionCopy')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# copy
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionPaste')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# paste
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionSelect_All')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# select all
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionFind_Replace')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# replace
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionGoto')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# reformat
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionReformat')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(False)

				return

		# undo
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionUndo')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# redo
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionRedo')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# redo
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionCut')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# cut
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionCopy')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# copy
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionPaste')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# paste
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionSelect_All')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# select all
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionFind_Replace')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# replace
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionGoto')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# reformat
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionReformat')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)

		return

	# Action Menu Controls
	def setActionMenuControls(self):
		if self.fileManager.projectOpen:
			if self.fileManager.count > 0:

				# build
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionBuild')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# run
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionRun')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)
				# stop
				Widget=self.mainWindow.findChild(QtGui.QAction,'actionStop')
				Widget.setFont(QtGui.QFont("Ariel",10,50,False))
				Widget.setEnabled(True)

				return

		# build
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionBuild')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# run
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionRun')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)
		# stop
		Widget=self.mainWindow.findChild(QtGui.QAction,'actionStop')
		Widget.setFont(QtGui.QFont("Ariel",10,50,False))
		Widget.setEnabled(False)

		return


	#
	# Model Signal Handlers
	#

	def on_file_modification_state_changed(self, editorPane):
		"Set whether or not a file tab indicates that the specified file is modified or not."

		# If the modified widget is found, prepend a `*` if file has been modified. 
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		

		if current_tab is not None:
			if editorPane.modified:
				tabWidget.setTabText(tabWidget.indexOf(current_tab), QtCore.QString("*" + editorPane.filename))
			else:
				tabWidget.setTabText(tabWidget.indexOf(current_tab), QtCore.QString(editorPane.filename))

	#
	# Edit Menu Features (Handlers)
	#

	# Undo
	def on_actionUndo(self,checked):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:
			current_tab.undo()

	# Redo
	def on_actionRedo(self,checked):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:
			current_tab.redo()

					########################################

	# Cut
	def on_actionCut(self,checked):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:
			current_tab.cut()

	# Copy
	def on_actionCopy(self,checked):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:
			current_tab.copy()

	# Paste
	def on_actionPaste(self,checked):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:
			current_tab.paste()

	# Select All
	def on_actionSelect_All(self,checked):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:
			current_tab.selectAll()

					########################################

	# Find & Replace (dialog will call Replace All, Replace, and/or Find)
	def on_actionFind_Replace(self,checked):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:
			self.dialogManager.findReplaceDialog.show()


	# Replace All
	def on_replace_all_button(self):

		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 
		if current_tab is not None:
			check_states=self.dialogManager.findReplaceDialog.get_check_states()
			search_for=self.dialogManager.findReplaceDialog.search_for_text.text()
			replace_with=self.dialogManager.findReplaceDialog.replace_with_text.text()
			search_description_tup = (search_for,check_states['match case'],check_states['match entire word'],check_states['wrap around'],check_states['search backward'])

			if current_tab.current_search_selection != search_description_tup:
				self.on_find_button()

			# tracking variables for replace_all loop
			start_row, start_col = current_tab.getCursorPosition()
			wrapped = False
			expression = str(replace_with)
			length = len(expression)

			# replace all occurences of search_for with replace_with
			while current_tab.current_search_selection == search_description_tup:

				# replace the found word *
				current_tab.replace(replace_with)

				selection_start_row, selection_start_col, selection_end_row, selection_end_col = current_tab.getSelection()

				# set the new cursor position
				current_tab.setCursorPosition(selection_end_row, selection_end_col)

				# find any other matches (if any) *
				self.on_find_button()

				# determine the next location of the cursor
				next_pos_row, next_pos_col = current_tab.getCursorPosition()

				if next_pos_row <= start_row:
					wrapped = True

				# check: has replace_all wrapped around to the beginning of the file?
				if wrapped:

					# check: replace_all has covered the entire file
					if next_pos_row >= start_row and next_pos_col >= start_col - 1:
						break

			# reset the cursor position
			current_tab.setCursorPosition(start_row, start_col)

	# Replace
	def on_replace_button(self):
		check_states=self.dialogManager.findReplaceDialog.get_check_states()
		search_for=self.dialogManager.findReplaceDialog.search_for_text.text()
		replace_with=self.dialogManager.findReplaceDialog.replace_with_text.text()
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget()
		if current_tab is not None:

			check_replace_with = str(replace_with).strip()

			if check_replace_with is not "":

				search_description_tup = (search_for,check_states['match case'],check_states['match entire word'],check_states['wrap around'],check_states['search backward'])

				if current_tab.current_search_selection != search_description_tup:
					self.on_find_button()

				if current_tab.current_search_selection == search_description_tup:
					current_tab.replace(replace_with)

					selection_start_row, selection_start_col, selection_end_row, selection_end_col = current_tab.getSelection()

					current_tab.setCursorPosition(selection_end_row, selection_end_col)

					self.on_find_button()

	# Find
	def on_find_button(self):
		check_states=self.dialogManager.findReplaceDialog.get_check_states()
		search_for=self.dialogManager.findReplaceDialog.search_for_text.text()
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget()
		if current_tab is not None:

			search_description_tup = (search_for,check_states['match case'],check_states['match entire word'],check_states['wrap around'],check_states['search backward'])

			if current_tab.current_search_selection == search_description_tup:
				was_found = current_tab.findNext()
			else:
				was_found = current_tab.findFirst(  search_for,
													False,
													check_states['match case'],
													check_states['match entire word'],
													check_states['wrap around'],
													not check_states['search backward']
												 )

			if was_found:
				#Set a variable indicating the the current selection is the result of a search.
				current_tab.current_search_selection = search_description_tup

	# Goto Accepted
	def on_actionGoto_line_accepted(self):

		# Get value specified in dialog
		line = self.dialogManager.gotoLineDialog.intValue() -1

		# Get the current tab
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:

			# line is unreachable
			if line > current_tab.lines():	
				return

			# Set new cursor position
			current_tab.setCursorPosition(line, 0)

	# Goto
	def on_actionGoto(self):
		tabWidget = self.mainWindow.findChild(QtGui.QTabWidget,'tabWidget')
		current_tab = tabWidget.currentWidget() 		
		if current_tab is not None:

			# Set possible range of lines in the current tab
			self.dialogManager.gotoLineDialog.setIntRange(0, current_tab.lines())

			# Open the goto line dialog
			self.dialogManager.gotoLineDialog.open()

					########################################

	# Reformat
	def on_actionReformat(self):
		print "Reformat Signalled - Not Implemented In This Version (yet...)"

	#
	# Help Menu (Handlers)
	#

	# About
	def on_actionAbout(self):
		self.dialogManager.aboutDialog.open()
    def __init__(self,
                 fitnessFunction,
                 individualsPerGeneration=100,
                 elitism=1,
                 randIndividuals=0,
                 randFitness=None,
                 mutationRate=0.2,
                 mutationSTDEV=0,
                 maxGenerations=None,
                 stopWithFitness=None,
                 stopAfterTime=None,
                 logDir=None,
                 generationsToKeep=0,
                 snapshotGenerations=None,
                 threads=1,
                 startingGeneration=None):
        """
        :param individualsPerGeneration: the size of the new generation
        :type individualsPerGeneration: int
        :param elitism: preserve the n most fit individuals without mutations or crossovers
        :type elitism: int
        :param randIndividuals: add n random chromosomes to the breeding population
        :type randIndividuals: int
        :param randFitness: random individuals may have very low fitness.  If not None, the maximum of this value and
                                the actual random fitness is used
        :type randFitness: float
        :param mutationRate: the average number of mutations each gene will undergo
        :type mutationRate: float
        :param mutationSTDEV: the standard deviation for the number of mutations each gene will undergo
        :type mutationSTDEV: float

        :param maxGenerations: stop computing after this many generations.  None means no limit
        :type maxGenerations: int
        :param stopWithFitness: stop computing if fitness meets or exceeds this value.  None means no limit
        :type stopWithFitness: float
        :param stopAfterTime: stop computing after this many seconds.  None means no limit
        :type stopAfterTime: float
        :param logDirL: if provided with a log directory then certain generations may be saved
        :type logDir: str
        :param generationsToKeep: the number of generations to save to the log directory.  For example, if set to 5
                                    then the 5 most recent generations will be saved
        :param snapshotGenerations: take a snapshot of the system very N trials
        :type snapshotGenerations: int
        :param threads: the number of threads to use for fitness tests
        :type threads: int
        :param startingGeneration: start with generation defined in YAML instead of a random generation
        :type startingGeneration: str

        """
        self.geneTypes = []
        self.startingChromosomes = []
        self.chromosomeType = None

        self.fitnessFunction = fitnessFunction
        self.individualsPerGeneration = individualsPerGeneration
        self.elitism = elitism
        self.randIndividuals  =  randIndividuals
        self.randFitness = randFitness
        self.mutationRate = mutationRate
        self.mutationSTDEV = mutationSTDEV
        self.maxGenerations = maxGenerations
        self.stopWithFitness = stopWithFitness
        self.stopAfterTime = stopAfterTime
        self.logDir = logDir
        self.generationsToKeep = generationsToKeep
        self.snapshotGenerations = snapshotGenerations
        self.threads = threads
        self.startingGenration = startingGeneration

        self.FM = FileManager()
        self.oldGenerations = []
        self.oldGenerations_perm = []

        def signal_handler(signal, frame):
            print "dumping data"
            self.dataDump()
            sys.exit(0)
        signal.signal(signal.SIGINT, signal_handler)
Exemple #56
0
    def handle(self):
        logFile = open("logs", "a")
        builtins.sendHandler = self
        builtins.init = 1
        essai = 0
        identify = 0
        while essai < 3:
            rec = self.request.recv(1024).strip()
            if len(rec) > 0:
                clair = Securite.vigenere(rec[2:].decode(), clef, "2")
                r = clair.split(";,;")
                password = r[1]
                username = r[0]
                mp = Database.searchUser(username).strip()
                if mp == "invalide":
                    self.sendMsg("L", "identify=0")
                    essai = essai + 1
                else:
                    if hashlib.sha224(password.encode("utf-8")).hexdigest() == mp:
                        identify = 1
                        self.sendMsg("L", "identify=1")
                        logFile.write(username + ";" + datetime.datetime.now().isoformat())
                        break
                    else:
                        self.sendMsg("L", "identify=0")
                        essai = essai + 1
                # print(identify)
            else:
                builtins.init = 0
                print("client deconnecte")
                break

        while 1 and identify == 1:
            suivi = open("suivi", "r")
            nbUser = 0
            for ligne in suivi:
                nbUser = int(ligne.strip())
            nbUser = nbUser + 1
            suivi = open("suivi", "w")
            suivi.write(str(nbUser))
            suivi.close()
            d = self.request.recv(1024).strip()
            if len(d) > 0:
                t = d.decode()
                temp = t.split(";")
                typ = temp[0]
                if typ == "T":
                    data = Securite.vigenere(temp[1], clef, "2")
                    cur_thread = threading.current_thread()
                    typ, answer = Cerveau.analyse(data, username)

                    if username == "florent":
                        answer += " (from" + str(cur_thread.name) + ")"
                    self.sendMsg(typ, answer)
                elif typ == "F":
                    complete = False
                    while not complete:
                        d += self.request.recv(1024).strip()
                        t = d.decode()
                        if re.search(";[A-Za-z]*.\.[A-Za-z]*", t):
                            complete = True
                    temp = t.split(";")
                    data = temp[1]
                    fileName = temp[2]
                    FileManager.convertFileReceive(data, fileName)
                    self.sendMsg("T", "Fichier " + fileName + " bien recu")
            else:
                essai = 0
                identify = 0
                builtins.init = 0
                print("client deconnecte")
                #                Cerveau.cleanHistory()
                break
Exemple #57
0
for c in courses:
    for s in c.students:
        for a in s.assignments:
            if a.credit!=-1:
                try:
                    saveFile = open(s.gradedPath+"\\%d\\%s.txt" % (int(a.credit),a.number))
                    str = saveFile.readline()
                    (score,dateSubmitted) = str.split(" - ")
                    if score!="0" and score!=a.score:
                        a.score = score
                        print("new score for %s %s credit %d would be %s instead of %s" % (s.firstName,s.lastName,int(a.credit),score,a.score))
                except:
                    s.assignments.remove(a)
        for i in range(1,16):
            files = FileManager.getTXTFiles(s.gradedPath+"%d\\" % i)
            for f in files:
                filename = os.path.split(f)[1]
                num = os.path.splitext(filename)[0]
                assignments = s.getAssignmentsDictForCredit(i)
                #print s.lastName
                #print assignments
                if num not in assignments.keys():
                    saveFile = open(f)
                    str = saveFile.readline()
                    (score,dateSubmitted) = str.split(" - ")
                    assignment = Assignment.Assignment()
                    assignment.score = score
                    assignment.number = num
                    assignment.dateSubmitted = dateSubmitted
                    try: