コード例 #1
0
 def VerifyEmail(self, string):
     fm = FileManager()
     match = re.match(r'\b[\w.-]+@[\w.-]+.\w{2,4}\b', string)
     if match and fm.isUnique(string,2):
         return True
     else:
         return False
コード例 #2
0
    def __init__(self, automaton):
        # Valores definidos por el usuario
        self.automaton = Automaton2D()
        self.automaton = automaton
        self.cells_y = automaton.iterations  # Numero de filas
        self.cells_x = automaton.size  # NUmero de columnas (iteraciones)
        self.state = []

        # Tamaño de las celdas del lienzo
        self.cell_width = 1000
        self.cell_height = 600

        # Colores
        self.background_color = 25, 25, 25
        self.cell_color = 255, 255, 255
        self.death_cell_color = 128, 128, 128

        # Otros valores por defecto
        self.max_width = 50  # Tamaño maximo de las filas
        self.current_row = 0  # Fila que estamos pintando actualmente
        self.file_manager = FileManager()

        # tamaño de celdas en el eje x
        self.sizeX = self.cell_width / self.cells_x
        self.sizeY = self.cell_height / self.cells_y

        # Desplegar la pantalla de pygame
        pygame.init()
        pygame.display.set_caption('Automata celular ' +
                                   str(self.automaton.rule))
        self.screen = pygame.display.set_mode(
            (self.cell_width, self.cell_height))
        self.screen.fill(self.background_color)  # pintar fondo
コード例 #3
0
    def test_getScrambles(self):
        file = open('testing.txt', 'w')
        sessionData1 = [
            [[0,
              28563], "U2 F2 L2 D2 L' U2 L' F2 L F2 U L' D B' F' L' U2 F' L'",
             "", 1563232395],
            [[0, 32727], "R F U F' L' D' B L B2 D2 R2 F' D2 R2 F' B2 D2 F D",
             "", 1563232454],
            [[0, 28053],
             "D F2 R2 U R2 F2 L2 U2 B2 D' L2 U L' R' F' D2 U B F2 U2 R'", "",
             1563232519]
        ]

        sessionDict = {"session1": sessionData1}
        json.dump(sessionDict, file)
        file.close()

        fileManager = FileManager('testing.txt')
        sessionData = fileManager.getSessionData('session1')

        sessionResults = SessionResults(sessionData)

        self.assertEqual(sessionResults.getScrambles(), [
            "U2 F2 L2 D2 L' U2 L' F2 L F2 U L' D B' F' L' U2 F' L'",
            "R F U F' L' D' B L B2 D2 R2 F' D2 R2 F' B2 D2 F D",
            "D F2 R2 U R2 F2 L2 U2 B2 D' L2 U L' R' F' D2 U B F2 U2 R'"
        ])
コード例 #4
0
def main():

    args = parseArguments()
    fileManager = FileManager(args=args)
    demoPathAttributes = fileManager.getAttributes()
    uploader = Uploader(demoPathAttributes)
    uploader.upload()
コード例 #5
0
    def login(self, username, password):
        """Calls the user manager to generate the Login request. Then initializes the FileManager for loggedIn user

        Parameters:
        ------------------------------------------
        username : string
            username for the user
        password: stirng
            password for the user
        Return : string
            response from the UserManager class method login
        """
        data = ""
        status = self.checkLogin(username)
        if status == 1:
            data = "Some other user is already logged in. Open another client to user a new login."
            return data
        elif status == 2:
            data = "This user is already logged in."
            return data
        else:
            data = f"Welcome {username}. Use help command to show available commands"
        data = self.usermanager.logIn(username, password)
        self.user = self.usermanager.getUserCredentials(username)
        self.fileManager = FileManager(self.absolutePath +
                                       self.user.rootDirectory)
        self.fileManager.createUserDirectory()
        return data
コード例 #6
0
 def manager(self,rule, ruledef):
     from MatchManager import Matching
     from SearchManager import SearchManager
     from Trigger import Trigger
     from FileManager import FileManager
        
     Matching = Matching(rule, ruledef)
     Trigger = Trigger()
     FileManager = FileManager()
        
     log_location = self.log_check(rule)
     log = FileManager.read_logfile(log_location)
     logfile = log
     endPoint = len(logfile)
     
     while True:
         if endPoint > self.startAt:     
             Searching = SearchManager(Matching.matchlist, rule, logfile)
             Trigger.perform_action(Searching.action, rule)
         
         print 'start at begin: ' ,  self.startAt
         self.startAt = endPoint
         print 'startat = ', self.startAt
         print 'endpoint = ', endPoint
         interval = self.interval_check(rule)
         print 'Sleeping for ' + str(interval) + ' seconds'
         time.sleep(interval)
         print 'Searching in the new rule file'
         
         log_location = self.log_check(rule)
         log = FileManager.read_logfile(log_location)
         del logfile[:]
         for line in range (self.startAt, len(log)):
             logfile.append(log[line])
         endPoint = len(log)
コード例 #7
0
    def manager(self, rule, ruledef):
        from MatchManager import Matching
        from SearchManager import SearchManager
        from Trigger import Trigger
        from FileManager import FileManager

        Matching = Matching(rule, ruledef)
        Trigger = Trigger()
        FileManager = FileManager()

        log_location = self.log_check(rule)
        log = FileManager.read_logfile(log_location)
        logfile = log
        endPoint = len(logfile)

        while True:
            if endPoint > self.startAt:
                Searching = SearchManager(Matching.matchlist, rule, logfile)
                Trigger.perform_action(Searching.action, rule)

            print 'start at begin: ', self.startAt
            self.startAt = endPoint
            print 'startat = ', self.startAt
            print 'endpoint = ', endPoint
            interval = self.interval_check(rule)
            print 'Sleeping for ' + str(interval) + ' seconds'
            time.sleep(interval)
            print 'Searching in the new rule file'

            log_location = self.log_check(rule)
            log = FileManager.read_logfile(log_location)
            del logfile[:]
            for line in range(self.startAt, len(log)):
                logfile.append(log[line])
            endPoint = len(log)
コード例 #8
0
	def build(self):
		fileManager = FileManager()
		
		cities = [dir for dir in os.listdir(self.source) if os.path.isdir(os.path.join(self.source, dir))]
		for city in cities:
			city_path = os.path.join(self.source, city)
			self.logger.info("%s ..."% city)
			files = [os.path.splitext(os.path.normcase(file))[0] for file in os.listdir(city_path) if os.path.splitext(file)[1] == '.json']
			for file in files:
				json_file = os.path.join(city_path, "%s.json"% file)
				geojson_file = os.path.join(city_path, "%s.geojson"% file)
				js_geojson_file = os.path.join(city_path, "%s.js"% file)
				self.logger.info("%s.json"% file)
				if not os.path.isfile(geojson_file) or not os.path.isfile(js_geojson_file):
					f = open(json_file, 'r')
					loaded_json = json.load(f)
					f.close()
					
					loaded_geojson = self.builder.build_geojson(loaded_json)

					fileManager.write_geojson(loaded_geojson, self.source, city, file)
					self.logger.info(" => %s.geojson"% file)
					
					fileManager.write_js_geojson(loaded_geojson, self.source, city, file)
					self.logger.info(" => %s.js"% file)
コード例 #9
0
class SinNombreOntologia():
    def suceso(self):
        return {u"Dia": "", u"Mes": "", u"A\u00f1o": ""}

    def lugar(self):
        return {u"Nivel": u"Departamento", u"Nombre": u""}

    def __init__(self, jsonLine):
        self.jsonLine = jsonLine
        self.fileManager = FileManager()
        self.structure = {}
        try:
            with self.fileManager.readFile("structure.json") as z:
                self.structure = json.loads(z.read().replace('\n', ''))
        except Exception as e:
            self.fileManager.recordError("Couldn't load the structures file ")
        self.clear()

    def clear(self):
        self.suc = self.suceso()
        self.depto = self.lugar()
        self.municipio = self.lugar()

    def process(self, case, value):
        if case == "Dia":
            self.suc = Charmer.addValue(self.suc, "Dia", value)
        elif case == "Mes":
            self.suc = Charmer.addValue(self.suc, "Mes", value)
        elif case == u"A\u00f1o":
            self.suc = Charmer.addValue(self.suc, u"A\u00f1o", value)
        elif case == "Departamento":
            self.depto = Charmer.addValue(self.depto, "Nombre", value)
コード例 #10
0
def concatenate_directory_of_npz_files(path):
    file_manager = FileManager()

    file_paths = file_manager.get_file_paths_from_directory(
        directory_path=path)

    training_sets = list()

    shapes = set()
    for path in file_paths:
        if path.endswith(".npz"):
            array = numpy.load(path)['a']

            # ignore empty arrays
            if len(array[0]) > 0:
                training_sets.append(numpy.load(path)['a'])
            else:
                print("omitted because empty: ", path)

            shape = '-'.join(list(map(str, array.shape)))
            shapes.add(shape)

    training_data = numpy.concatenate(training_sets, axis=0)

    return training_data
コード例 #11
0
 def test_get_datetime(self):
     f = FileManager()
     year, month, day, hour, minute, second = f._get_datetime()
     # TODO: Should I mock the python now function to test for specific
     # values?
     # Checks that the year is between 2016 and 2099.  2099 is somewhat
     # arbitrary - the test will work for many years ... probably more
     # than is necessary.
     self.assertIn(
         year, range(2016, 2100),
         "FileManger get_datetime returns a valid year")
     self.assertIn(
         month, range(1, 13),
         "FileManger get_datetime returns a valid month")
     self.assertIn(
         day, range(1, 32),
         "FileManger get_datetime returns a valid day")
     self.assertIn(
         hour, range(1, 25),
         "FileManger get_datetime returns a valid hour")
     self.assertIn(
         minute, range(0, 60),
         "FileManger get_datetime returns a valid minute")
     self.assertIn(
         second, range(0, 60),
         "FileManger get_datetime returns a valid second")
コード例 #12
0
ファイル: ViPRLogManager.py プロジェクト: pperias/LogManager
    def __init__(self):
        self.lmLogger = logging.getLogger("ViPRLogManager")
        self.analysisDir = "."
        self.lmLogger.setLevel(logging.DEBUG)
        logManagerFileName = "ViPRLogManager.log"
        logFileLocation = os.path.join(self.analysisDir, logManagerFileName)
        # create file handler which logs even debug messages
        fileHandler = logging.FileHandler(logFileLocation, mode='a')
        fileHandler.setLevel(logging.DEBUG)
        # create console handler with a higher log level
        consoleHandler = logging.StreamHandler()
        consoleHandler.setLevel(logging.INFO)
        # create formatter and add it to the handlers
        FORMAT = "%(asctime)s - %(name)s:%(module)s - %(levelname)s - %(message)s"
        formatter = logging.Formatter(FORMAT)
        fileHandler.setFormatter(formatter)
        consoleHandler.setFormatter(formatter)
        # add the handlers to the logger
        self.lmLogger.addHandler(fileHandler)
        self.lmLogger.propagate = False
        self.lmLogger.addHandler(consoleHandler)

        self.lmLogger.info("ViPR Log Manager 1.2")
        self.appConfig = self.readFile("applicationConfig.json")

        self.exclusion_list = self.readFile("exclusionList.json")
        self.regexManager = RegExManager(self.appConfig, self.lmLogger)
        self.fileManager = FileManager(self.appConfig, self.regexManager,
                                       self.lmLogger)
        self.dataManager = DataManager(self.appConfig, self.fileManager,
                                       self.regexManager, self.lmLogger)
        self.logInquirer = LogInquirer(self.appConfig, self.fileManager,
                                       self.dataManager, self.lmLogger)

        self.userConfig = None
コード例 #13
0
 def VerifyCedula(self, string):
     match = re.match(r'\d{4}-\d{4}-\d{5}', string)
     fm = FileManager()
     if match and  fm.isUnique(string,3):
         return  True
     else:
         return  False
コード例 #14
0
ファイル: take_photo.py プロジェクト: tomhotch/timelapse
def take_photo():
    file_settings = FileSettings()

    logging.basicConfig(
        filename=file_settings.log_file(),
        format='%(asctime)s %(levelname)s: %(message)s',
        level=logging.INFO)
    logging.debug('Starting take_photo')
    try:
        logging.debug('Creating FileManager')
        file_mgr = FileManager(file_settings.project_dir)
        logging.debug('Getting file path')
        file_name_path = file_mgr.get_file_path()
        logging.debug('Photo file path name: %s', file_name_path)
    except:
        # Got an error trying to create the directory.
        # NEXT file_name_path isn't set on an exception.  What exception
        #      message is raised?  Print that?  Yes, need to debug the error.
        # NEXT Create a unit (or behavioral test) to check this logic - does
        #      it need to be put into a separate module?
        logging.error('Failed to create: %s', os.path.dirname(file_name_path))
        return

    logging.info('Taking photo with file path: %s', file_name_path)

    camera_settings = CameraSettings()
    # Camera is mounted upside down in the weatherproof housing
    # Need to rotate 180 degrees so photo is right side up
    camera_settings.rotation = 180

    take_and_save_photo(camera_settings, file_name_path)
コード例 #15
0
ファイル: WebWrapper.py プロジェクト: Dmium/lvc
 def get_commits_for_path(self, path):
     file_manager = FileManager()
     print(file_manager.path_lists)
     if file_manager.check(path):
         json_data = TrackedFile.load_file(path).get_json()
         return json_data
     return json.dumps([])
コード例 #16
0
    def _prepare(self):
        # ファイルを取得する準備
        FileManager.BASE_DIR = self.input_base_dir
        self.file_manager = FileManager()

        # 保存先ディレクトリを作成
        self.target_key = datetime.now().strftime("%Y%m%d_%H%M%S")
コード例 #17
0
    def test_getMultipleSessionData(self):
        file = open('testing.txt', 'w')
        sessionData1 = [
            [[0,
              28563], "U2 F2 L2 D2 L' U2 L' F2 L F2 U L' D B' F' L' U2 F' L'",
             "", 1563232395],
            [[0, 32727], "R F U F' L' D' B L B2 D2 R2 F' D2 R2 F' B2 D2 F D",
             "", 1563232454],
            [[0, 28053],
             "D F2 R2 U R2 F2 L2 U2 B2 D' L2 U L' R' F' D2 U B F2 U2 R'", "",
             1563232519]
        ]
        sessionData2 = [
            [[0, 73228], "L' U B2 L B R D2 F' U2 F2 U B2 R2 U2 B2 R2 U' R2 F",
             "", 1563233503],
            [[0, 30163],
             "D2 R2 F' U2 B R2 D2 U2 B' L2 R2 D' B U R2 F L B' R' F R'", "",
             1563233644],
            [[0, 28436],
             "U' L2 D2 R2 B' D2 B R2 B' F2 U2 B' U' L D B' D L2 B F R'", "",
             1563233713]
        ]
        sessionDataList = [sessionData1, sessionData2]
        sessionDict = {"session1": sessionData1, "session2": sessionData2}
        json.dump(sessionDict, file)
        file.close()

        fileManager = FileManager('testing.txt')

        for i in range(2):
            sessionName = 'session' + str(i + 1)
            self.assertEqual(fileManager.getSessionData(sessionName),
                             sessionDataList[i])

        os.remove('testing.txt')
コード例 #18
0
ファイル: app.py プロジェクト: pony1487/Guitaro
def get_lesson_notation(topic, lesson):
    print("Test notation")
    topic_path = "topics/"
    topic += "/"
    file_manager = FileManager(topic_path + topic)

    bpm = file_manager.get_tempo_from_file_name(lesson)

    lesson_file_path = file_manager.get_lesson_path("/" + lesson)

    lesson_analysis = AudioAnalysis(lesson_file_path)

    lesson_note_list, lesson_freq_list = lesson_analysis.analyse_notes()
    lesson_timing_list = lesson_analysis.analyse_timing()

    if int(bpm) < 0:
        return "Error: No tempo present in filename"
    else:

        lesson_notation_creator = Notation(lesson_freq_list, lesson_timing_list, bpm)

        lesson_string_list = lesson_notation_creator.get_strings_to_be_played()
        lesson_fret_list = lesson_notation_creator.get_frets_to_be_played()
        padded_duration_list = lesson_notation_creator.get_padded_duration_list()

        total_beats = lesson_notation_creator.calculate_total_beats(padded_duration_list)

        d = app_utils.create_dictionary(lesson_string_list=lesson_string_list, lesson_fret_list=lesson_fret_list,
                                        padded_duration_list=padded_duration_list, total_beats=total_beats, bpm=bpm)
        return jsonify(d)
コード例 #19
0
    def analysis(id, string, file_options_path):

        result = None

        options = FileManager.read_data_from_json(file_options_path)

        if string == "/op":
            if options['operators'] and id not in options['operators']:
                options['operators'].append(id)
                result = "Операция успешно выполнена. Вы оператор"
            elif id not in options['operators']:
                options['operators'] = [id]
                result = "Операция успешно выполнена. Вы оператор"
            else:
                result = "Операция не выполнена, так как вы уже оператор"
            FileManager.write_data_to_json(file_options_path, options)
        if string == "/deop":
            if options['operators'] and id in options['operators']:
                for i in range(0, options['operators'].count(id)):
                    options['operators'].remove(id)
                result = "Операция успешно выполнена. Терерь вы не оператор"
            else:
                result = "Операция не выполнена, так как вы не были оператором"
            FileManager.write_data_to_json(file_options_path, options)

        return result
コード例 #20
0
def extract(filename, tmp_dir):
    fm = FileManager()
    fm.GoInsideDirectory(tmp_dir)
    if fm.DirectoryExists(pyserver_path):
        fm.DeleteDirectory(pyserver_path)

    unpack_archive(filename, path__to_server)
コード例 #21
0
ファイル: app.py プロジェクト: pony1487/Guitaro
def analyse_user_chords(dirone, dirtwo, lesson):
    if request.method == 'POST':
        if 'file' not in request.files:
            print("no file uploaded")
            return "Error: No File uploaded"

        # Users attempt
        file = request.files['file']

        # Path to where the lesson the user attempted is stored
        lesson_path = "{}/{}".format(dirone, dirtwo)

        file_manager = FileManager(lesson_path)
        lesson_file_path = file_manager.get_lesson_path("/" + lesson)

        if file and app_utils.allowed_file(file.filename):
            filename = secure_filename(file.filename)
            # Save user file to be analysed
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            uploaded_file_path = app.config['UPLOAD_FOLDER'] + "/" + filename

            user_chord_analyser = ChordAnalyser(uploaded_file_path)
            user_chroma_list = user_chord_analyser.compute_chromagram()
            user_note_list = user_chord_analyser.get_notes_of_chord(user_chroma_list)

            lesson_chord_analyser = ChordAnalyser(lesson_file_path)
            lesson_chroma_list = lesson_chord_analyser.compute_chromagram()
            lesson_note_list = lesson_chord_analyser.get_notes_of_chord(lesson_chroma_list)

            chord_comparision = ChordComparison(lesson, user_note_list, lesson_note_list)
            return jsonify(chord_comparision.get_comparision_dict())
        else:
            return "Wrong File type: Must be wav"
コード例 #22
0
ファイル: app.py プロジェクト: pony1487/Guitaro
def list_files_in_plan(plan):
    plan_path = "plans/"

    if plan not in valid_plans:
        return "Error: Not a valid plan"
    file_manager = FileManager(plan_path + plan)
    return jsonify(file_manager.list_files_in_directory())
コード例 #23
0
def HistoryGraph():
    readRecord = FileManager(todayWeather)
    hmm = readRecord.read()
    tempToShow = []
    humidToShow = []
    timeToShow = []
    for temp, humid, time in hmm:
        tempToShow.append(temp)
        humidToShow.append(humid)
        timeToShow.append(time)
    print(tempToShow)   
    # plt.ion()
    tempGraphStart = plt.figure()
    tempGraph = tempGraphStart.add_subplot(1,1,1)
    tempGraph.plot(timeToShow,[float(i) for i in tempToShow])
    tempGraph.set_title("temperature")
    tempGraph.legend(["temperature"])

    humiGraphStart = plt.figure()
    humiGraph = humiGraphStart.add_subplot(1,1,1)
    humiGraph.plot([float(x) for x in humidToShow])
    humiGraph.set_title("humidity")
    humiGraph.legend(["humidity"])
    # plt.xlabel('temp')
    # plt.ylabel('timeElapsed')

    #likelihood to rain according to data
    averageTemp = (sum([int(i) for i in tempToShow])/len(tempToShow))
    averageHumid = (sum([int(i) for i in humidToShow])/len(humidToShow))
    title = likelinessToRain(averageHumid, averageTemp)
    print(f"title in historical graph {title}")
    # plt.legend(["Temperature","Humidity"])
    # plt.figure()
    plt.show()
コード例 #24
0
ファイル: main.py プロジェクト: damr-/tiss
    def __init__(self):
        super().__init__()

        self.timeout = 30
        self.fetchIncrement = 20
        self.height = 600
        self.width = 1200

        self.tissCataloguesRows = 12
        self.tissCataloguesCols = 4
        self.personalCatalogueRowsFirst = 4
        self.personalCatalogueRowsSecond = 8
        self.personalCatalogueCols = 1

        self.tissCatalogues = []
        self.personalCatalogues = []
        self.personalCataloguesTitles = []

        self.initUI()
        self.setupWorkerThread()
        self.loadCatalogues()
        settings = FileManager.loadSettings()
        if len(settings) > 0:
            self.lastFetchDateTime.setText(settings[0])
            self.toggleCourseNumbers.setChecked(FileManager.str2bool(settings[1]))
            self.toggleCourseHours.setChecked(FileManager.str2bool(settings[2]))
            self.exactSemester.setChecked(FileManager.str2bool(settings[3]))
コード例 #25
0
 def test9_change_directory_root(self):
     """Checks folder navigation outside root"""
     absolutepath = os.path.dirname(
         os.path.abspath(inspect.getfile(inspect.currentframe())))
     absolutepath += "/User/" + self.username + "/"
     fmanager = FileManager(absolutepath)
     response = fmanager.changeDirectory("..")
     self.assertEqual(response, "You are at root directory")
コード例 #26
0
ファイル: test_file_manager.py プロジェクト: pony1487/Guitaro
    def test_list_directories(self):
        directory = "topics"
        file_manager = FileManager(directory)

        dir_list = file_manager.list_directories()

        expected_output = {'directories': ['fingerIndependence', 'strumming', 'picking']}
        assert dir_list == expected_output
コード例 #27
0
 def OnSize(self, message):
     d = FileManager().CurrentFile().data
     w = d.GetWidth()
     h = d.GetHeight()
     self.SetSize(size=(w * self.scale, h * self.scale))
     self.parent.SetScrollbars(1, 1, w * self.scale, h * self.scale)
     logging.info("DrawPanel.OnZoom()")
     self.Refresh()
コード例 #28
0
ファイル: Data.py プロジェクト: towqsz/TextMining
class Data:
    def __init__(self):
        self.file = FileManager()
        self._text = self.file.file

    def set_data(self, file):
        self._text = file
        self.file.set_file(self._text)
コード例 #29
0
 def OnOK(self, event):
     fm = FileManager()
     fm.New( 'image',
             self.add_w.GetValue(), 
             self.add_h.GetValue()
             )
     pub.sendMessage("UpdateBitmap")
     self.Destroy()
コード例 #30
0
 def test1_create_user_directory(self):
     """Checks if a user directory is created, checking for a user folder called TestUser"""
     absolutepath = os.path.dirname(
         os.path.abspath(inspect.getfile(inspect.currentframe())))
     userRoot = absolutepath + "/User/" + self.username
     fmanager = FileManager(userRoot)
     fmanager.createUserDirectory()
     self.assertTrue(os.path.exists(userRoot))
コード例 #31
0
 def catchPics(self, html):
     bs = BeautifulSoup(html, 'lxml')
     photoNum = 0
     for picsboxContent in bs.find_all('div', {"class": "picsbox"})[0]:
         imgSrc = picsboxContent.contents[0]['src']
         photoNum += 1
         self.downloadPic(imgSrc, photoNum)
         FileManager.writeToFile('PhotoSrc', imgSrc)
コード例 #32
0
ファイル: test_file_manager.py プロジェクト: pony1487/Guitaro
    def test_get_tempo_from_file_name_bad_input(self):
        directory = "topics"
        lesson_name = "A_minor_pentatonic_ascending_quarter_notes95.wav"

        file_manager = FileManager(directory)

        bpm = file_manager.get_tempo_from_file_name(lesson_name)

        assert not bpm
コード例 #33
0
def buildlevel1(data):

    seed = 23
    modellst = []

    filename = "level1Ensemble.pkl"

    fObject = FileManager(filename)

    if not fObject.isExist():

        X, y = data['type1']['x'], data['type1']['y']

        ###add catboost here

        model = CatBoostClassifier(loss_function='Logloss')
        model.fit(X, y)
        modellst.append(model)

        model = CatBoostClassifier(loss_function='CrossEntropy')
        model.fit(X, y)
        modellst.append(model)

        model = CatBoostClassifier(eval_metric=HingelossMetric())
        model.fit(X, y)
        modellst.append(model)

        model = CatBoostClassifier(eval_metric=SquaredlossMetric())
        model.fit(X, y)
        modellst.append(model)

        model = CatBoostClassifier(eval_metric=LogisticMetric())
        model.fit(X, y)
        modellst.append(model)

        model = CatBoostClassifier(eval_metric=AUClossMetric())
        model.fit(X, y)
        modellst.append(model)

        model = CatBoostClassifier(eval_metric=GiniMetric())
        model.fit(X, y)
        modellst.append(model)

        X, y = data['type2']['x'], data['type2']['y']

        aucModel = lgbmodel(X, y, metric='auc')
        modellst.append(aucModel)

        lambdaModel = lgbmodel(X, y, metric='xentlambda')
        modellst.append(lambdaModel)

        binaryerrModel = lgbmodel(X, y, metric='binary_error')
        modellst.append(binaryerrModel)

        #save model to disk
        fObject.save(modellst)
コード例 #34
0
 def __init__(self):
     """Initialize the server manager object.
     The parameters are passed on to the init function of server manager
     """
     self.user = User("")
     self.usermanager = UserManager()
     self.absolutePath = os.path.dirname(
         os.path.abspath(inspect.getfile(inspect.currentframe())))
     self.fileManager = FileManager(self.absolutePath)
     super().__init__()
コード例 #35
0
    def Monitor(self):
        from FileManager import FileManager
        FileManager = FileManager()
        rules = FileManager.get_rules()
        ruledef = FileManager.get_ruledef()

        for rule in range(len(rules)):
            print rules[rule]
            thread = Thread(target=self.manager, args=(rules[rule], ruledef))
            thread.start()
コード例 #36
0
 def __init__(self, jsonLine):
     self.jsonLine = jsonLine
     self.fileManager = FileManager()
     self.structure = {}
     try:
         with self.fileManager.readFile("structure.json") as z:
             self.structure = json.loads(z.read().replace('\n', ''))
     except Exception as e:
         self.fileManager.recordError("Couldn't load the structures file ")
     self.clear()
コード例 #37
0
 def Monitor(self):
     from FileManager import FileManager
     FileManager = FileManager()
     rules = FileManager.get_rules()
     ruledef = FileManager.get_ruledef()
             
     for rule in range (len(rules)):
         print rules[rule]
         thread = Thread( target=self.manager, args=(rules[rule], ruledef))
         thread.start() 
コード例 #38
0
	def negativeFeaturesSingleCat(self,category):
		## PREPROCESSING PERCORSI IMMAGINI
		fm = FileManager()

		X_negative = []
		#for i in range(0,len(listDir)):
		file_negative = self.root+category+"/"+category+"_" + self.detector + "_" + self.extractor + ".csv"
		if not os.path.isfile(file_negative):
			self.creaFileFeatures(category)
		else:
			X = fm.csvToArray(file_negative)
			X_negative = X_negative + X
		return X_negative		
コード例 #39
0
ファイル: BossEnemy.py プロジェクト: elanas/TheCrazySix
 def loadResources(self):
     loader = AssetLoader('images')
     if BossEnemy.walking_images[Enemy.INDEX_DOWN] is None:
         path = os.path.join(
             BossEnemy.WALKING_PATH, BossEnemy.WALKING_DOWN_PATH)
         prefix_path = os.path.join(
             BossEnemy.PREFIX_PATH, BossEnemy.WALKING_DOWN_PATH)
         fM = FileManager(path, file_ext='.png', create_dir=False)
         BossEnemy.walking_images[Enemy.INDEX_DOWN] = \
             loader.load_images(fM.get_files(prefix_path=prefix_path))
     if BossEnemy.walking_images[Enemy.INDEX_UP] is None:
         path = os.path.join(
             BossEnemy.WALKING_PATH, BossEnemy.WALKING_UP_PATH)
         prefix_path = os.path.join(
             BossEnemy.PREFIX_PATH, BossEnemy.WALKING_UP_PATH)
         fM = FileManager(path, file_ext='.png', create_dir=False)
         BossEnemy.walking_images[Enemy.INDEX_UP] = \
             loader.load_images(fM.get_files(prefix_path=prefix_path))
     if BossEnemy.walking_images[Enemy.INDEX_LEFT] is None:
         path = os.path.join(
             BossEnemy.WALKING_PATH, BossEnemy.WALKING_LEFT_PATH)
         prefix_path = os.path.join(
             BossEnemy.PREFIX_PATH, BossEnemy.WALKING_LEFT_PATH)
         fM = FileManager(path, file_ext='.png', create_dir=False)
         BossEnemy.walking_images[Enemy.INDEX_LEFT] = \
             loader.load_images(fM.get_files(prefix_path=prefix_path))
     if BossEnemy.walking_images[Enemy.INDEX_RIGHT] is None:
         path = os.path.join(
             BossEnemy.WALKING_PATH, BossEnemy.WALKING_RIGHT_PATH)
         prefix_path = os.path.join(
             BossEnemy.PREFIX_PATH, BossEnemy.WALKING_RIGHT_PATH)
         fM = FileManager(path, file_ext='.png', create_dir=False)
         BossEnemy.walking_images[Enemy.INDEX_RIGHT] = \
             loader.load_images(fM.get_files(prefix_path=prefix_path))
コード例 #40
0
ファイル: AqiCapture.py プロジェクト: ComplexCity/capture
def main():
	captor = AqiCaptor(logger)
	file_manager = FileManager()

	try:
		try:
			locations = file_manager.get_locations(source)
		except IOError:
			raise InitError("File %s is missing"% file_manager.get_locations_path(source))
		except ValueError:
			raise InitError("The %s file does not contain any correct JSON object"% file_manager.get_locations_path(source))
			
		for city, location in locations.iteritems():
			logger.warning("- Capting for %s"% city)
			my_date = datetime.now().strftime('%y-%m-%d-%H')
			loaded_json = captor.get_data(location)
			try:
				file_manager.write_json(loaded_json, source, city, my_date)
			except IOError:
				raise InitError("Folder %s is missing"% file_manager.get_folder_path(source, city))
		
		return 0

	except InitError as e:
		logger.critical("%s: %s"% (type(e).__name__, e))
		return 1
	except requests.exceptions.RequestException as e:
		logger.critical("%s: %s"% (type(e).__name__, e))
		return 2
	except Exception as e:
		logger.critical(e, exc_info=True)
		return 3
コード例 #41
0
	def featuresCategories(self):
		#recupera tutte le categorie, senza distinzione fra positive e negative
		#usando un numero incrementale per l'assegnazione delle categorie
		fm = FileManager()
		X_train = []
		y_train = []
		assoc = dict()
		listCategories = fm.listNoHiddenDir(self.root)
		index = 1
		for cat in listCategories:
			file_positive = self.root+cat+"/"+cat+"_" + self.detector + "_" + self.extractor + ".csv"
			X_cat = fm.csvToArray(file_positive)
			X_train = X_train + X_cat
			y_train = y_train + [index]*len(X_cat)
			assoc[cat] = index
			index = index + 1

		return X_train,y_train,assoc
コード例 #42
0
ファイル: PymageMain.py プロジェクト: edson-gonzales/PymageC
 def read_all_values_to_rotate(self):
     """
     This method read all the data required by the final user to rotate an image
     Return:
     input_values.- List with all the inputs inserted by the user
                    [Image path,  degrees, New name of the image]
                    If some value inserted is invalid, the method returns a empty list
     """
     file_manager = FileManager()
     input_values = []
     image_path = self.read_image_path()
     if (file_manager.validate_type_of_image(image_path) == True):
         degrees = self.read_degrees_to_rotate_image()
         if (degrees != 9999):
             new_image_name = self.read_name_to_save_image_rotate()
             input_values = [image_path, degrees, new_image_name]
             return input_values
         else:
             return input_values
     else:
         return input_values
コード例 #43
0
def main():
	try:
		logger.warning("Capting Archdaily...")
		
		now = datetime.now().strftime('%y-%m-%d')
		loaded_json = ArchdailyCaptor().get_data()
		
		logger.info("Building the GeoJSON...")
		loaded_geojson = ArchdailyGeojsonBuilder().build_geojson(loaded_json)
		
		logger.info("Writing GeoJSON...")
		file_manager = FileManager()
		try:
			file_manager.write_geojson(loaded_geojson, source, None, now)
			file_manager.write_js_geojson(loaded_geojson, source, None, now)
		except IOError:
			raise InitError("The folder %s is missing"% file_manager.get_folder_path(source))
		
		logger.warning("New GeoJSON written for Archdaily: %d locations"% len(loaded_json))
		return 0
	
	except InitError as e:
		logger.critical("%s: %s"% (type(e).__name__, e))
		return 1
	except requests.exceptions.RequestException as e:
		logger.critical(e, exc_info=True)
		return 2
	except Exception as e:
		logger.critical(e, exc_info=True)
		return 3
コード例 #44
0
    def test_get_file_path(self):

        # Successful cases
        root_dir = os.path.join("temp")
        try:
            f = FileManager(root_dir)
            file_path = f.get_file_path()

            # TODO: The regex path check is unix specific.  Is there
            # a way to have a regexp check for os path separator?
            path, basename = os.path.split(file_path)
            self.assertRegexpMatches(
                path, "\d\d\d\d/\d\d/\d\d", "Verify path format is yyyy/mm/dd")

            self.assertRegexpMatches(
                basename, "\d\d\d\d-\d\d-\d\d_\d\d-\d\d-\d\d.jpg",
                "Verify file name format is year-month-day_hour-minute-second.jpg")

        finally:
            # Clean up - remove directories created just for this test
            os.removedirs(os.path.dirname(file_path))
            self.assertFalse(
                os.path.isdir(root_dir),
                "Verify test directory does not exist after clean up")

        # Error Cases
        # Create a directory that can't be written to
        unwritable_dir = "unwritable"
        TEST_UMASK = 0o222
        orig_umask = os.umask(TEST_UMASK)
        os.makedirs(unwritable_dir)

        try:
            # Make sure we get an exception if creating the directory fails
            f = FileManager(unwritable_dir)
            self.assertRaises(OSError, f.get_file_path )

        finally:
            os.umask(orig_umask)
            os.removedirs(unwritable_dir)
コード例 #45
0
ファイル: PymageMain.py プロジェクト: edson-gonzales/PymageC
    def read_all_values_to_export_an_image_file_to_another_format(self):
        """
        This method read all the data required by the final user to export an image
        to another format.
        The formats that are supported by the application are: jpg, bmp and png

        Return: List with all the inputs inserted by the user
                [Image path,  new format]
                If some value inserted is invalid, the method returns a empty list
        """
        file_manager = FileManager()
        input_values = []
        image_path = self.read_image_path()
        if (file_manager.validate_type_of_image(image_path) == True):
            new_format = self.read_format_to_export_an_image()
            if (new_format != "Incorrect format"):
                input_values = [image_path, new_format]
                return input_values
            else:
                return input_values
        else:
            return input_values
コード例 #46
0
	def negativeFeatures(self):
		## PREPROCESSING PERCORSI IMMAGINI
		fm = FileManager()
		#file_negative = self.root+self.keywords+"/"+self.keywords+"_" + self.detector + "_" + self.extractor + "_negative.csv"

		# List dir contiene tutte le cartelle della root img
		listDir = fm.listNoHiddenDir(self.root)

		# Cerco l'indice della cartella della Keywords
		indexKeywords = listDir.index(self.keywords)
		# Vado ad eliminare nella lista cartelle quella della keywords
		listDir.pop(indexKeywords)

		X_negative = []
		for i in range(0,len(listDir)):
			file_negative = self.root+listDir[i]+"/"+listDir[i]+"_" + self.detector + "_" + self.extractor + ".csv"
			if not os.path.isfile(file_negative):
				self.creaFileFeatures(listDir[i])
			else:
				X = fm.csvToArray(file_negative)
				X_negative = X_negative + X
		return X_negative
コード例 #47
0
class FileManagerTest(unittest.TestCase):
    
    
    def setUp(self):
        
        self.file_manager= FileManager()
        self.current_path = os.getcwd()
        
    def test_aget_current_path_return_the_current_path(self):
    
        self.assertEquals(self.current_path, self.file_manager.get_current_path())

    def test_blist_image_from_path_return_a_list_with_images(self):
        
        self.assertEquals(['apple.bmp', 'pregoneroOficial.jpg', 'tank.png', 'apple.bmp', 'bmp.bmp', 'linux.png', 'pregoneroOficial.jpg', 'programmer.jpg', 'test.jpg'], self.file_manager.list_image_from_path(self.current_path))

    def test_clist_image_from_path_return_a_list_with_images_with_three_matching_files_and_one_different(self):
        
        folder = "/input/moreimages"
        path = self.current_path + folder
        self.assertEquals(['apple.bmp', 'bmp.bmp', 'linux.png', 'pregoneroOficial.jpg', 'programmer.jpg', 'test.jpg'], self.file_manager.list_image_from_path(path))
    
    def test_dlist_image_from_path_return_a_empty_list_when_no_images_exist(self):
        
        folder="/input/empty"
        path = self.current_path + folder
        self.assertEquals([], self.file_manager.list_image_from_path(path))    

    def test_everify_path_directory_exists_when_user_insert_a_valid_path(self):
        
        self.assertEquals(self.current_path, self.file_manager.directory_exists(self.current_path))

    def test_fverify_path_directory_exists_when_user_insert_an_invalid_path(self):
        
        self.assertEquals("This is an invalid path", self.file_manager.directory_exists("InvalidPath"))

    def test_gverify_image_exist_when_user_insert_an_existing_image(self):
        
        folder = "/input/tank.png"
        path_image = self.current_path + folder
        self.assertTrue(self.file_manager.validate_type_of_image(path_image))	

    def test_hverify_image_exist_when_user_insert_an_unexisting_image(self):
        
        image = "/input/92.jpg"
        path_image = self.current_path + image
        self.assertFalse(self.file_manager.validate_type_of_image(image))
    
    def test_iverify_image_exist_when_user_insert_an_unexisting_image(self):
        
        txt_file = "/input/moreimages/readme.txt"
        path_file = self.current_path + txt_file
        self.assertFalse(self.file_manager.validate_type_of_image(path_file))
コード例 #48
0
 def __init__(self):
     self.init_images()
     self.file_manager = FileManager(
         path=CustomLevelPicker.CUSTOM_MAP_PATH,
         file_ext=CustomLevelPicker.MAP_FILE_EXT)
     self.file_names = self.file_manager.get_files(strip_ext=True)
     self.current_selection = 0
     self.text_surf = None
     self.text_rect = None
     self.highlight_surf = None
     self.highlight_rect = None
     self.build_text()
     self.build_subtitles()
     Globals.play_menu_sound()
コード例 #49
0
ファイル: PicThing.py プロジェクト: splitbrain/picthing
    def action_switchlibrary(self, widget):
        """ Load a new library """
        library = self.libs[widget.get_active()]
        print "loading library '"+library[0]+"' in '"+library[1]+"'"
        self.meta     = None
        self.builder.get_object('notebook').set_current_page(0)
        if(self.filemgr != None):
            self.filemgr.index.close();
        self.filemgr  = FileManager(library[1])
        self.iconview = self.builder.get_object("iconview")
        self.iconview.set_model(self.filemgr.store)
        self.iconview.set_text_column(self.filemgr.COL_TITLE)
        self.iconview.set_pixbuf_column(self.filemgr.COL_PIXBUF)
        self.iconview.set_tooltip_column(self.filemgr.COL_PATH)
        self.new_query('')

        self.filemgr.index.tagcloud()
コード例 #50
0
def main():
	captor = YahooWeatherCaptor()
	file_manager = FileManager()

	try:
		try:
			woe_ids = file_manager.get_locations(source)
		except IOError:
			raise InitError("File %s is missing"% file_manager.get_locations_path(source))
		except ValueError:
			raise InitError("The %s file does not contain any correct JSON object"% file_manager.get_locations_path(source))
		
		for city, woe_id in woe_ids.iteritems():
			logger.warning("Capting for %s" % city)
			loaded_json = captor.get_data(woe_id)
			
			last_build_date = dateutil.parser.parse(loaded_json['lastBuildDate'])
			date_for_path = last_build_date.strftime('%y-%m-%d-%H-%M')
			
			if os.path.isfile(file_manager.get_path(source, city, date_for_path)):
				logger.warning("Same build date for %s (%s)" % (city, last_build_date))
			else:
				try:
					file_manager.write_json(loaded_json, source, city, date_for_path)
				except IOError:
					raise InitError("Folder %s is missing"% file_manager.get_folder_path(source, city))
				logger.warning("New JSON written for %s %s" % (city, last_build_date))
		return 0

	except InitError as e:
		logger.critical("%s: %s"% (type(e).__name__, e))
		return 1
	except requests.exceptions.RequestException as e:
		logger.critical("%s: %s"% (type(e).__name__, e))
		return 2
	except Exception as e:
		logger.critical(e, exc_info=True)
		return 3
コード例 #51
0
	def creaCsv(self):
		fm = FileManager()
		listCategories = fm.listNoHiddenDir(self.root)
		for cat in listCategories:
			file_positive = self.root+cat+"/"+cat+"_" + self.detector + "_" + self.extractor + ".csv"
			if not os.path.isfile(file_positive):
				#se il file non esiste viene creato
				print "Nuovo File Features Positive " + self.detector + " + " + self.extractor + " creato."
				X_positive = []
				#elaborazione immagini
				listArrayPositive = fm.listNoHiddenFiles(self.root+cat,self.estension)
				for k in range(0,len(listArrayPositive)): # Da eliminare file csv ed altri
					base_name = self.root+cat+"/"+cat+fm.correggi(k)+ self.estension
					print "Immagini " + str(k) + " -> " + base_name 
					ret = (self.obj.elabora(base_name)) #[0:cut_features]
					X_positive.append(ret)
				fm.arrayToCsv(X_positive,file_positive)	
			else:
				print "File Features Positive " + self.detector + " + " + self.extractor + " esiste gia."			
コード例 #52
0
ファイル: main.py プロジェクト: massi92/DIP-Project_MGFF
from FileManager import FileManager
from detectAndExtract import detectAndExtract


n_folds = input("Insert the number of folds: ")

detectors_descriptors = [
    ["MSER", "SIFT"],
    ["HARRIS", "SIFT"],
    ["SIFT", "SIFT"],
    ["ORB", "ORB"],
    ["FAST", "SURF"],
    ["FAST", "BRIEF"],
]

fm = FileManager()

categories = fm.listNoHiddenDir(os.path.dirname(__file__) + os.path.sep + "\\Project_OVA\\imm")

for i in range(0, len(categories)):

    currentCategories = categories[i]

    print "\n######################################"
    print "CURRENT CATEGORY: " + currentCategories

    for x in range(0, len(detectors_descriptors)):

        print "###########################"

        print currentCategories
コード例 #53
0
class TileWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="TileMapEditor")
        self.iconTheme = Gtk.IconTheme.get_default()
        self.iconTheme.append_search_path("Ressources/Icons")
        self.fileManager = FileManager(self)
        self.newContents = CreateMenu(self)
        self.tileBox = TileBox()
        self.traceManager = TraceManager()
        self.objectManager = ObjectManager()
        self.sfmlTilePaned = Gtk.Paned()
        self.sfmlTilePaned.pack1(self.tileBox)

        self.toolNotebook = Gtk.Notebook()
        self.toolNotebook.append_page(self.traceManager, Gtk.Label("Trace Manager"))
        self.toolNotebook.set_size_request(200,200)
        self.miniMap = MiniMap(self.toolNotebook)

        self.toolPaned = Gtk.Paned(orientation = Gtk.Orientation.VERTICAL)
        self.toolPaned.add1(self.toolNotebook)
        self.toolPaned.pack2(self.objectManager)
        self.toolPaned.connect('notify::position', self.handleToolPanedMoving)
        self.toolPaned.set_property('position-set', True)
        self.toolPaned.set_position(300)

        self.sfmlBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.sfmlTilePaned.add2(self.sfmlBox)
        self.sfmlTilePaned.set_size_request(500, 300)

        globalVar.sfmlArea = None

        self.panedSFML_toolPaned = Gtk.Paned()
        self.panedSFML_toolPaned.add1(self.sfmlTilePaned)
        self.panedSFML_toolPaned.pack2(self.toolPaned, False, False)
        self.panedSFML_toolPaned.connect('notify::position', self.handleToolPanedMoving)
        self.panedSFML_toolPaned.set_property('position-set', True)
        self.panedSFML_toolPaned.set_position(600)
        self.set_default_size(800, 600)

        self.actionGroup = Gtk.ActionGroup("Actions")
        self.makeSFMLMenuAction(self.actionGroup)
        self.makeFileMenuAction(self.actionGroup)
        self.makeEditionMenuAction(self.actionGroup)
        self.makeToolMenuAction(self.actionGroup)
        self.tileBox.makeActionMenu(self.actionGroup)

        self.uiManager = self.createUIManager()
        self.uiManager.insert_action_group(self.actionGroup)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.add(vbox)
        vbox.pack_start(self.uiManager.get_widget("/MenuBar"), False, False, 0)
        vbox.pack_start(self.uiManager.get_widget("/ToolBar"), False, False, 0)

        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox.pack_start(self.panedSFML_toolPaned, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        self.traceManager.connectToolButton(self)
        self.tileBox.makePopupMenu(self.uiManager)

        self.mode = None

        self.show_all()

    def buildSFMLArea(self, numberCase, size):
        if globalVar.sfmlArea:
            self.traceManager.clearAll()
            self.tileBox.clearAll()
            self.objectManager.clearAll()
            for child in self.sfmlBox:
                self.sfmlBox.remove(child)

        vSlide = Gtk.VScrollbar()
        hSlide = Gtk.HScrollbar()

        globalVar.sfmlArea = SFMLArea(hSlide, vSlide, \
                        numberCase, size, self.miniMap)

        hBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        self.eventSFMLBox = Gtk.EventBox()
        self.eventSFMLBox.add(globalVar.sfmlArea)
        hBox.pack_start(self.eventSFMLBox, True, True, 0)
        hBox.pack_start(vSlide, False, False, 0)
        self.sfmlBox.pack_start(hBox, True, True, 0)
        self.sfmlBox.pack_start(hSlide, False, False, 0)

        globalVar.sfmlArea.makePopupAction(self.actionGroup)
        globalVar.sfmlArea.makePopup(self.uiManager, self.eventSFMLBox)
        
        self.show_all()
        if platform.system() == "Linux":
            globalVar.sfmlArea.render.create(globalVar.sfmlArea.get_window().get_xid())
        elif platform.system() == "Windows":
            globalVar.sfmlArea.render.create(GdkWin32.Win32Window.get_handle(globalVar.sfmlArea.get_window()))
        self.zoomPlus.connect("activate", globalVar.sfmlArea.zoom, "in")
        self.zoomOut.connect("activate", globalVar.sfmlArea.zoom, "out")
        for mode in ["Print", "Eraser"]:
            if self.actionGroup.get_action(mode).get_active():
                globalVar.sfmlArea.mode = mode
                self.mode = mode
                break

    def makeFileMenuAction(self, actionGroup):
        fileMenuAction = Gtk.Action("FileMenu", "_File", None, None)
        actionGroup.add_action(fileMenuAction)

        newFileAction = Gtk.Action("NewFile", None, None, Gtk.STOCK_NEW)
        actionGroup.add_action_with_accel(newFileAction, None)
        newFileAction.connect("activate", self.newFile)

        openFileAction = Gtk.Action("OpenFile", None, None, Gtk.STOCK_OPEN)
        openFileAction.connect("activate", self.manageFile, "open", "xml")
        actionGroup.add_action_with_accel(openFileAction, None)

        saveAction = Gtk.Action("Save", None, None, Gtk.STOCK_SAVE)
        actionGroup.add_action_with_accel(saveAction, None)
        saveAction.connect("activate", self.manageFile, "save", "xml")

        saveAsAction = Gtk.Action("SaveAs", None, None, Gtk.STOCK_SAVE_AS)
        actionGroup.add_action_with_accel(saveAsAction, "<Ctrl><Shift>s")
        saveAsAction.connect("activate", self.manageFile, "saveAs", "xml")

    def makeEditionMenuAction(self, actionGroup):
        editionMenuAction = Gtk.Action("EditionMenu", "_Edition", None, None)
        actionGroup.add_action(editionMenuAction)

        newTraceAction = Gtk.Action("NewTrace", "New _Trace", None, None)
        actionGroup.add_action_with_accel(newTraceAction, "<Ctrl><Shift>t")
        newTraceAction.connect("activate", self.newContents.newTrace, self.traceManager)

        newImageAction = Gtk.Action("NewImage", "New _Image", None, None)
        actionGroup.add_action_with_accel(newImageAction, "<Ctrl><Shift>i")
        newImageAction.connect("activate", self.manageFile, "open", "image")

        newObjectAction = Gtk.Action("NewObject", "New _Object", None, None)
        actionGroup.add_action_with_accel(newObjectAction, "<Ctrl><Shift>o")
        newObjectAction.connect("activate", self.objectManager.promptAddObject)

        changeSizeAction = Gtk.Action("ChangeSize", "Chan_ge size", None, None)
        changeSizeAction.connect("activate", self.promptSetSize)

    def makeToolMenuAction(self, actionGroup):
        toolsMenuAction = Gtk.Action("ToolsMenu", "_Tools", None, None)
        actionGroup.add_action(toolsMenuAction)

        changeSizeAction = Gtk.Action("ChangeSize", "Change size", None, None)
        actionGroup.add_action(changeSizeAction)
        self.zoomPlus = Gtk.Action("Zoom+", None, None, Gtk.STOCK_ZOOM_IN)
        actionGroup.add_action_with_accel(self.zoomPlus, None)
        self.zoomOut = Gtk.Action("Zoom-", None, None, Gtk.STOCK_ZOOM_OUT)
        actionGroup.add_action_with_accel(self.zoomOut, None)

        actionGroup.add_radio_actions([("Print", None, None, "p", None, 0), \
                ("Eraser", None, None, "e", None, 0)], "active", self.radioActionManager)

        actionGroup.get_action("Print").set_icon_name("pencil")
        actionGroup.get_action("Eraser").set_icon_name("eraser")

    def makeSFMLMenuAction(self, actionGroup):
        delCase = Gtk.Action("DelCase", "Delete", None, None)
        setTileProperties = Gtk.Action("SetTileProperties", "Set tile properties", None, None)
        actionGroup.add_action(delCase)
        actionGroup.add_action(setTileProperties)
        
    def createUIManager(self):
        with open("Ressources/UI_INFO.xml", 'r') as info:
            ui = Gtk.UIManager()
            ui.add_ui_from_string(info.read())
            self.add_accel_group(ui.get_accel_group())
            return ui

    def manageFile(self, widget, action, mime=""):
        if action=="open":
            if mime=="image":
                self.newContents.createNewImage(self.fileManager, self.tileBox)
            elif mime=="xml":
                self.fileManager.openFileXML(self.tileBox, self.traceManager, self.objectManager)

        elif action=="saveAs":
            self.fileManager.saveAsFile(self.tileBox, self.traceManager, self.objectManager)
        elif action=="save":
            self.fileManager.saveFile(self.tileBox, self.traceManager, self.objectManager)

    def handleToolPanedMoving(self, widget, paramSpec):
        self.miniMap.scalePixbuf()
    
    def newFile(self, widget):
        self.newContents.newFile(self.fileManager)

    def promptSetSize(self, widget):
        self.newContents.setSize()

    def getSaveFileElem(self):
        windowElem = ET.Element('Window')
        windowElem.set('numberCases', str(globalVar.sfmlArea.numberCases.x)+'x'+str(globalVar.sfmlArea.numberCases.y))
        windowElem.set('tileSize', str(globalVar.sfmlArea.sizeCase.x)+'x'+str(globalVar.sfmlArea.sizeCase.y))
        windowElem.set('title', str(self.get_title()))

        return windowElem

    def decodeXML(self, windowElement):
        windowValuesElement = dict()
        for item in windowElement.items():
            windowValuesElement[item[0]]=item[1]

        tileSizeSplit = windowValuesElement['tileSize'].split('x')
        windowValuesElement['tileSize'] = sf.Vector2(float(tileSizeSplit[0]), float(tileSizeSplit[1]))

        numberCasesSplit = windowValuesElement['numberCases'].split('x')
        windowValuesElement['numberCases'] = sf.Vector2(float(numberCasesSplit[0]), float(numberCasesSplit[1]))
        self.buildSFMLArea(windowValuesElement['numberCases'], windowValuesElement['tileSize'])

        self.set_title(windowValuesElement['title'])

    def radioActionManager(self, radioAction, current):
        if globalVar.sfmlArea:
            globalVar.sfmlArea.setMode(current.get_name())
        self.mode = current.get_name()
コード例 #54
0
    def __init__(self):
        Gtk.Window.__init__(self, title="TileMapEditor")
        self.iconTheme = Gtk.IconTheme.get_default()
        self.iconTheme.append_search_path("Ressources/Icons")
        self.fileManager = FileManager(self)
        self.newContents = CreateMenu(self)
        self.tileBox = TileBox()
        self.traceManager = TraceManager()
        self.objectManager = ObjectManager()
        self.sfmlTilePaned = Gtk.Paned()
        self.sfmlTilePaned.pack1(self.tileBox)

        self.toolNotebook = Gtk.Notebook()
        self.toolNotebook.append_page(self.traceManager, Gtk.Label("Trace Manager"))
        self.toolNotebook.set_size_request(200,200)
        self.miniMap = MiniMap(self.toolNotebook)

        self.toolPaned = Gtk.Paned(orientation = Gtk.Orientation.VERTICAL)
        self.toolPaned.add1(self.toolNotebook)
        self.toolPaned.pack2(self.objectManager)
        self.toolPaned.connect('notify::position', self.handleToolPanedMoving)
        self.toolPaned.set_property('position-set', True)
        self.toolPaned.set_position(300)

        self.sfmlBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.sfmlTilePaned.add2(self.sfmlBox)
        self.sfmlTilePaned.set_size_request(500, 300)

        globalVar.sfmlArea = None

        self.panedSFML_toolPaned = Gtk.Paned()
        self.panedSFML_toolPaned.add1(self.sfmlTilePaned)
        self.panedSFML_toolPaned.pack2(self.toolPaned, False, False)
        self.panedSFML_toolPaned.connect('notify::position', self.handleToolPanedMoving)
        self.panedSFML_toolPaned.set_property('position-set', True)
        self.panedSFML_toolPaned.set_position(600)
        self.set_default_size(800, 600)

        self.actionGroup = Gtk.ActionGroup("Actions")
        self.makeSFMLMenuAction(self.actionGroup)
        self.makeFileMenuAction(self.actionGroup)
        self.makeEditionMenuAction(self.actionGroup)
        self.makeToolMenuAction(self.actionGroup)
        self.tileBox.makeActionMenu(self.actionGroup)

        self.uiManager = self.createUIManager()
        self.uiManager.insert_action_group(self.actionGroup)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.add(vbox)
        vbox.pack_start(self.uiManager.get_widget("/MenuBar"), False, False, 0)
        vbox.pack_start(self.uiManager.get_widget("/ToolBar"), False, False, 0)

        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox.pack_start(self.panedSFML_toolPaned, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        self.traceManager.connectToolButton(self)
        self.tileBox.makePopupMenu(self.uiManager)

        self.mode = None

        self.show_all()
コード例 #55
0
    def test_create_direcotry(self):

        # Successful cases
        root_dir = os.path.join("test")
        test_dirs = []

        # TODO: Test fails if root_dir was not deleted from a previous failing
        #       test run.  I thought I fixed that, but I missed something.
        try:
            # Pick some specific values to verify the right directories get created
            year, month, day = '2001', '09', '11'
            year_dir = os.path.join(root_dir, year)
            expected_dir = os.path.join(root_dir, year, month, day)
            test_dirs.append(expected_dir)

            self.assertFalse(
                os.path.isdir(root_dir),
                "Verify year directory does not exist before creating it")

            f = FileManager(root_dir)
            f._create_directories(root_dir, year, month, day)
            self.assertTrue(
                os.path.isdir(expected_dir),
                "Verify directories created successfully")

            # Make sure the top level directory created has owner, group,
            # and world read/write/execute permission.  I didn't set up
            # proper usernames on different systems, so I want to be able
            # to read, write and delete files from different computers
            # (including from Windows) as different users.
            #
            # Assume Linux since the script is designed to run on
            # Raspberry Pi

            mode = os.stat(year_dir).st_mode & 0o777
            self.assertEqual(
                mode, 0o777,
                "Verity year directory is user, group, world read/write/execute")

            f._create_directories(root_dir, year, month, day)
            self.assertTrue(
                os.path.isdir(expected_dir),
                "Verify create_directories works if the directory already exists")

            # Try making just a day directory (year and month exist)
            day = '12'
            expected_dir = os.path.join(root_dir, year, month, day)
            test_dirs.append(expected_dir)
            self.assertFalse(
                os.path.isdir(expected_dir),
                "Verify day directory does not exist before creating it")

            f._create_directories(root_dir, year, month, day)
            self.assertTrue(
                os.path.isdir(expected_dir),
                "Verify a new day directory was created successfully")


        finally:
            # Clean up - remove directories created just for this test
            for dir in test_dirs:
                os.removedirs(dir)
                self.assertFalse(
                    os.path.isdir(dir),
                    "Verify test directory does not exist after clean up")

            self.assertFalse(
                os.path.isdir(root_dir),
                "Verify root test directory does not exist after clean up")
コード例 #56
0
from DatabaseManager import DatabaseManager
from FileManager import FileManager
from functools import wraps
from shutil import rmtree
import traceback
import re
from urllib import quote
import time

app = Flask("__main__") # This is not used correctly as of now.

# Database Manager
db_man = DatabaseManager(app)

# File Manager
file_man = FileManager(app)


# Base 36 encode/decode used in the subdomains
convert = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

# encode challenge_ids for use in subdomains, just makes them grow a bit slower
def encode(challenge_id):
	if challenge_id == 0:
		return('0')
	challenge_id36 = ''
	while challenge_id > 0:
		challenge_id36 = convert[challenge_id%36]+challenge_id36
		challenge_id = challenge_id / 36
	return challenge_id36
コード例 #57
0
ファイル: Player.py プロジェクト: elanas/TheCrazySix
    def loadResources(self):
        if Player.still_images[Player.INDEX_UP] is None:
            Player.still_images[Player.INDEX_UP] = \
                Player.loader.load_spritesheet_alpha("main_still_up.png", 1, 2)
        if Player.still_images[Player.INDEX_DOWN] is None:
            Player.still_images[Player.INDEX_DOWN] = \
                Player.loader.load_spritesheet_alpha(
                    "main_still_down.png", 1, 2)
        if Player.still_images[Player.INDEX_LEFT] is None:
            Player.still_images[Player.INDEX_LEFT] = \
                Player.loader.load_spritesheet_alpha(
                    "main_still_left.png", 2, 1)
        if Player.still_images[Player.INDEX_RIGHT] is None:
            Player.still_images[Player.INDEX_RIGHT] = \
                Player.loader.load_spritesheet_alpha(
                    "main_still_right.png", 2, 1)

        if Player.walking_images[Player.INDEX_DOWN] is None:
            path = os.path.join(Player.WALKING_PATH, Player.WALKING_DOWN_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.WALKING_DOWN_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.walking_images[Player.INDEX_DOWN] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))
        if Player.walking_images[Player.INDEX_UP] is None:
            path = os.path.join(Player.WALKING_PATH, Player.WALKING_UP_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.WALKING_UP_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.walking_images[Player.INDEX_UP] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))
        if Player.walking_images[Player.INDEX_LEFT] is None:
            path = os.path.join(Player.WALKING_PATH, Player.WALKING_LEFT_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.WALKING_LEFT_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.walking_images[Player.INDEX_LEFT] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))
        if Player.walking_images[Player.INDEX_RIGHT] is None:
            path = os.path.join(Player.WALKING_PATH, Player.WALKING_RIGHT_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.WALKING_RIGHT_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.walking_images[Player.INDEX_RIGHT] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))

        if Player.punching_images[Player.INDEX_DOWN] is None:
            path = os.path.join(Player.WALKING_PATH, Player.PUNCHING_DOWN_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.PUNCHING_DOWN_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.punching_images[Player.INDEX_DOWN] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))
        if Player.punching_images[Player.INDEX_UP] is None:
            path = os.path.join(Player.WALKING_PATH, Player.PUNCHING_UP_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.PUNCHING_UP_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.punching_images[Player.INDEX_UP] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))
        if Player.punching_images[Player.INDEX_LEFT] is None:
            path = os.path.join(Player.WALKING_PATH, Player.PUNCHING_LEFT_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.PUNCHING_LEFT_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.punching_images[Player.INDEX_LEFT] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))
        if Player.punching_images[Player.INDEX_RIGHT] is None:
            path = os.path.join(
                Player.WALKING_PATH, Player.PUNCHING_RIGHT_PATH)
            prefix_path = os.path.join(
                Player.PREFIX_PATH, Player.PUNCHING_RIGHT_PATH)
            fM = FileManager(path, file_ext='.png', create_dir=False)
            Player.punching_images[Player.INDEX_RIGHT] = \
                Player.loader.load_images(
                    fM.get_files(prefix_path=prefix_path))
        if Player.hitSound is None:
            Player.hitSound = Player.loader.load_sound(Player.SOUND_PATH)
        if Player.attackSound is None:
            Player.attackSound = Player.loader.load_sound(
                Player.ATTACK_SOUND_PATH)
コード例 #58
0
 def setUp(self):
     
     self.file_manager= FileManager()
     self.current_path = os.getcwd()
コード例 #59
0
ファイル: try-again.py プロジェクト: iangmhill/CrashCourse
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.scrollview import ScrollView
from kivy.base import runTouchApp
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import ScreenManager, Screen, WipeTransition
from kivy.clock import Clock
from FileManager import FileManager
from Course_Item import Course_Item
from kivy.uix.dropdown import DropDown
from Proto3_5 import DragTab
#from dashNoKv import Dashboard



fm = FileManager()
catalog = fm.load_courses()
user = fm.load_user('ihill','crashcourse')


favorite_courses = []
search_temp_list = [] 


class TabTextInput(TextInput):

    def __init__(self, *args, **kwargs):
        self.next = kwargs.pop('next', None)
        super(TabTextInput, self).__init__(*args, **kwargs)

    def set_next(self, next):
コード例 #60
0
ファイル: step2_1.py プロジェクト: yamh/Python_study_group
    #"必要な要素のインデックス取得"
    id_num = attr.index('_N')
    title_num = attr.index('TI')
    abst_num = attr.index('AB')
    doc = []

    #"各行での結合"
    for line in input_data[1:]:
        tmp = line[id_num] + '\t' + line[title_num] + '\t' + line[abst_num]
        doc.append(tmp)
    return doc


#"メイン関数"
if __name__ == "__main__":

    tsvfile = TSVDIR + "mission.facet.2.tsv"
    
    fm = FileManager()
    f = fm.readFile(tsvfile, '\t')

    #"関数の呼び出し、結合した情報の取得"
    texts = merge_doc(f)

    #"作成したtextsの中身確認"
    print texts[0]
    print texts[1]