示例#1
0
 def test_outputRecord(self):
     """Testing the method of converting the records into an output string.
     """
     newRecords = ['abc', 'klm']
     r = Recorder('testRecorder')
     r.addRecords(newRecords, False)
     self.assertEqual(r.outputRecord(), 'abc\nklm') # Output format correctness
示例#2
0
    def finish_initializing(self, builder):  # pylint: disable=E1002
        """Set up the main window"""
        super(CompdaysrecorderWindow, self).finish_initializing(builder)

        self.AboutDialog = AboutCompdaysrecorderDialog
        self.PreferencesDialog = PreferencesCompdaysrecorderDialog

        # The status label
        #        self.statusLabel = self.builder.get_object("statusLabel")

        # Code for other initialization actions should be added here.
        self.recorder = Recorder()

        # Date label
        self.dateLabel = self.builder.get_object("dateLabel")

        # Radio buttons
        self.aRadioButton = self.builder.get_object("aRadioButton")
        self.dRadioButton = self.builder.get_object("dRadioButton")
        self.nRadioButton = self.builder.get_object("nRadioButton")
        self.oRadioButton = self.builder.get_object("oRadioButton")
        self.hRadioButton = self.builder.get_object("hRadioButton")

        # Spin button
        self.extraSpinButton = self.builder.get_object("extraSpinButton")

        # Edit, Save and Delete buttons
        self.editButton = self.builder.get_object("editButton")
        self.saveButton = self.builder.get_object("saveButton")
        self.deleteButton = self.builder.get_object("deleteButton")

        # Calendar
        self.calendar = self.builder.get_object("calendar")
        r = self.recorder.findLastEntry()
        _ = r['date']
        self.calendar.select_month(month=_.month - 1, year=_.year)
        self.calendar.select_day(_.day)
        self.dateLabel.set_text("{0:02d}/{1:02d}/{2:04d}".format(
            _.day, _.month, _.year))
        tmp = r['shift']
        if (tmp == 'd'): self.dRadioButton.set_active(True)
        elif (tmp == 'a'): self.aRadioButton.set_active(True)
        elif (tmp == 'n'): self.nRadioButton.set_active(True)
        elif (tmp == 'o'): self.oRadioButton.set_active(True)
        else: self.hRadioButton.set_active(True)
        self.extraSpinButton.set_value(r['extra'])
        self.enableEdition(False)

        # Plot area
        self.plotArea = self.builder.get_object("plotArea")
        self.displayPlotArea = self.builder.get_object("displayPlotArea")
        self.upArrow = self.builder.get_object("upArrow")
        self.downArrow = self.builder.get_object("downArrow")
        self.plot = self.recorder.plotOffHours()
        self.plotArea.add(self.plot)

        # compDaysLabel
        self.compDaysLabel = self.builder.get_object("compDaysLabel")
        self.updateCompDays()
示例#3
0
 def test_save(self):
     """Testing the saving method.
     """
     r = Recorder('testRecorder')
     r.save()
     self.assertTrue(os.path.exists(r.path) and os.path.isfile(r.path)) # Record file existence
     with open(r.path, 'r') as fin:
         self.assertFalse(fin.read()) # Record file content emptiness
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        parent.title("HappenedOrNotRecorder")
        self.pack(fill=BOTH, expand=1)

        self.recoder = Recorder()
        self.__create_widgets()
        self.update_content()
示例#5
0
 def openRecorder(self, event):
     if self.recorderWindow == None:
         self.recorderWindow = Recorder(self.parent)
         self.recorderWindow.mainloop()
         Recorder.RecorderState = 'Running'
     else:
         self.recorderWindow.deiconify()
         Recorder.RecorderState = 'Visible'
示例#6
0
 def test_recordWithoutAutoSave(self):
     """Testing the record adding method without auto saving.
     """
     newRecord = 'abc'
     r = Recorder('testRecorder')
     r.addRecord(newRecord, False)
     self.assertEqual(r.records, [newRecord]) # Record list correctness
     with open(r.path, 'r') as fin:
         self.assertFalse(fin.read()) # Record file content correctness
示例#7
0
 def test_recordsWithoutAutoSave(self):
     """Testing the mutiple records adding method without auto saving.
     """
     newRecords = ['abc', 'klm']
     r = Recorder('testRecorder')
     r.addRecords(newRecords, False)
     self.assertEqual(r.records, newRecords) # New records were added
     with open(r.path, 'r') as fin:
         self.assertFalse(fin.read()) # Record file content correctness
示例#8
0
    def __init__(self):
        self.name = datetime.now().strftime("%Y-%m-%d.%H_%M_%S.%f")
        self.folder = os.path.abspath(os.curdir) + '\\' + self.name
        self.recorder = Recorder('')

        self.emotions = []
        self.photos = []
        self.brain_waves = []
        self.res_dataset = []
示例#9
0
 def test_record(self):
     """Testing the record adding method.
     """
     newRecord = 'abc'
     r = Recorder('testRecorder')
     r.addRecord(newRecord)
     self.assertEqual(r.records, [newRecord]) # Record list correctness
     with open(r.path, 'r') as fin:
         self.assertEqual(fin.read(), 'abc') # Record file of correct data
示例#10
0
 def test_attributes(self):
     """Testing the attribute setting after initialization.
     """
     r = Recorder('testRecorder')
     self.assertEqual(r.name, 'testRecorder') # Recorder name variable correctness
     self.assertEqual(r.path, 'tmp/testRecorder.txt') # Recorder path variable correctness
     self.assertTrue(isinstance(r.records, list)) # Record list variable datatype correctness
     self.assertTrue(os.path.exists(r.path) and os.path.isfile(r.path)) # Record file existence
     with self.assertRaises(TypeError):
         Recorder([]) # Raising error if not initialize with a string
示例#11
0
    def test_records(self):
        """Testing the mutiple record adding method.
        """
        newRecords = ['abc', 'klm']
        r = Recorder('testRecorder')
        r.addRecords(newRecords)

        self.assertEqual(r.records, newRecords) # Record list correctness
        self.assertTrue(os.path.exists(r.path) and os.path.isfile(r.path)) # Record file existence
        with open(r.path, 'r') as fin:
            self.assertEqual(fin.read(), 'abc\nklm') # Record file content correctness
def start_recording():
    global is_recording, current_audio_file
    is_recording = True
    time_stamp = datetime.now()
    filename = time_stamp.strftime('%Y_%m_%d_%H_%M_%S') + ".wav"
    print("Start recording")

    rec = Recorder(channels=2)
    current_audio_file = rec.open(filename, 'wb')
    current_audio_file.start_recording()
    threading.Timer(1, sound).start()
示例#13
0
def main():
    # TODO pass the configuration, such as sensitivity, etc.
    recorder = Recorder()
    camera = Camera()

    while camera.is_opened():

        frame, movement_area = camera.run()

        recorder.record(frame, movement_area)

    # Release cap resource
    camera.release()
    def run(self):
        '''
        record
        '''
        print("Thread start")
        micRecorder = Recorder(channels=1)

        datetime_string = datetime.now().strftime("%d%m%Y_%H%M%S")
        filename = "record_" + datetime_string + ".wav"
        with micRecorder.open("records/testing/" + filename, 'wb') as recfile:
            recfile.start_recording()
            time.sleep(10.0)
            recfile.stop_recording()
            LiveFFTWidget.stopRecord = 0

        print("Recording complete")
示例#15
0
    def __init__(self, *, debug_show=False):
        self.car_op = CarOp()
        self.auto_nav_er = AutoNav(self.car_op)
        # self.orbslam2_connect = OrbSlam2Connector()
        self.debug_show = debug_show

        self.human_detect = Yolov3HumanDetector()
        self.auto_watch_human = AutoWatchHuman(self.car_op)

        self.recorder = Recorder()
        self.notifier = Notifier(self.recorder)

        self.work_thread = Thread(target=self.work_run)
        self.work_thread.start()

        self.record_thread = Thread(target=self.record_run)
        self.record_thread.start()
    def finish_initializing(self, builder): # pylint: disable=E1002
        """Set up the main window"""
        super(CompdaysrecorderWindow, self).finish_initializing(builder)

        self.AboutDialog = AboutCompdaysrecorderDialog
        self.PreferencesDialog = PreferencesCompdaysrecorderDialog
        
        # The status label
#        self.statusLabel = self.builder.get_object("statusLabel")

        # Code for other initialization actions should be added here.
        self.recorder = Recorder()
        
        # Date label
        self.dateLabel = self.builder.get_object("dateLabel")
        
        # Radio buttons
        self.aRadioButton = self.builder.get_object("aRadioButton")
        self.dRadioButton = self.builder.get_object("dRadioButton")
        self.nRadioButton = self.builder.get_object("nRadioButton")
        self.oRadioButton = self.builder.get_object("oRadioButton")
        self.hRadioButton = self.builder.get_object("hRadioButton")
        
        # Spin button
        self.extraSpinButton = self.builder.get_object("extraSpinButton")
        
        # Edit, Save and Delete buttons
        self.editButton = self.builder.get_object("editButton")
        self.saveButton = self.builder.get_object("saveButton")
        self.deleteButton = self.builder.get_object("deleteButton")
        
        # Calendar
        self.calendar = self.builder.get_object("calendar")
        r = self.recorder.findLastEntry()
        _ = r['date']
        self.calendar.select_month(month=_.month - 1, year=_.year)
        self.calendar.select_day(_.day)
        self.dateLabel.set_text("{0:02d}/{1:02d}/{2:04d}".format(_.day, _.month, _.year))
        tmp = r['shift']
        if (tmp=='d') : self.dRadioButton.set_active(True)
        elif (tmp=='a') : self.aRadioButton.set_active(True)
        elif (tmp=='n') : self.nRadioButton.set_active(True)
        elif (tmp=='o') : self.oRadioButton.set_active(True)
        else : self.hRadioButton.set_active(True)
        self.extraSpinButton.set_value(r['extra'])
        self.enableEdition(False)
        
        # Plot area
        self.plotArea = self.builder.get_object("plotArea")
        self.displayPlotArea = self.builder.get_object("displayPlotArea")
        self.upArrow = self.builder.get_object("upArrow")
        self.downArrow = self.builder.get_object("downArrow")
        self.plot = self.recorder.plotOffHours()
        self.plotArea.add(self.plot)
        
        # compDaysLabel
        self.compDaysLabel = self.builder.get_object("compDaysLabel")
        self.updateCompDays()
示例#17
0
	def record(self):
		self.is_recording = not self.is_recording
		if self.is_recording:
			self.recorder = Recorder(self)
			self.recorder.continuer = True
			self.recorder.start()
		else:
			self.recorder.continuer = False
			self.recorder.join()
示例#18
0
class Taskbar(Frame):
    def __init__(self, parent, w=400, h=70):
        super().__init__(parent, width=w, height=h, borderwidth=2)
        self.parent = parent

        self.centerTaskbar(w=w, h=h)

        self.recorderWindow = None

        ppt = Application(self, 'Images/presentation.png',
                          'Images/presentationsel.png')
        browser = Application(self, 'Images/browser.png',
                              'Images/browsersel.png')
        self.recorder = Application(self, 'Images/recorder.png',
                                    'Images/recordersel.png')
        ppt.grid(row=0, column=0, padx=10)
        browser.grid(row=0, column=1, padx=10)
        self.recorder.grid(row=0, column=2, padx=10)

        ppt.bind('<Button-1>', self.openPowerPoint)
        self.recorder.bind('<Button-1>', self.openRecorder)

    def openPowerPoint(self, event):
        log.writeEvent('Open PPT')
        ppt = PPT(self.parent)
        ppt.mainloop()

    def openRecorder(self, event):
        if self.recorderWindow == None:
            self.recorderWindow = Recorder(self.parent)
            self.recorderWindow.mainloop()
            Recorder.RecorderState = 'Running'
        else:
            self.recorderWindow.deiconify()
            Recorder.RecorderState = 'Visible'

    def centerTaskbar(self, w, h):
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = sh - h

        self.place(x=x, y=y)
 def start_recording(self):
     recorded_videos_dir = "../recorded_videos/{}".format(int(time.time()))
     pathlib.Path(recorded_videos_dir).mkdir(parents=True, exist_ok=True)
     print(self.camera_map)
     for camera_id in self.camera_map:
         camera_OS_index = self.camera_map[camera_id]["camera_os_index"]
         self.recorder_map[camera_id] = Recorder(
             camera_OS_index, self.verboseEnabled,
             self.camera_map[camera_id]["camera_fps"])
         self.recorder_map[camera_id].start_recording(
             recorded_videos_dir + "/{}".format(str(camera_id)))
class ButtonRecorder(object):
    def __init__(self, filename=None, device=0):
        self.filename = filename
        self.rec = Recorder(channels=1, device=device)

    def set_device_index(self, index):
        self.rec.set_device(index)

    def set_file_name(self, filename):
        self.filename = filename

    def on_released(self):
        if (self.filename != None):
            self.recfile.stop_recording()
            self.recfile.close()

    def on_pressed(self):
        if (self.filename != None):
            print(self.filename)
            self.recfile = self.rec.open(self.filename, 'wb')
            self.recfile.start_recording()
示例#21
0
    def __init__(self, cam_id=0, *, debug_show=False):
        '''
        初始化函数
        :param cam_id: 当cam_id为-1时,将会使用IP摄像机,如果为其他值,例如1,将会使用本机的1号摄像头
        :param debug_show: 是否启动调试输出,为True时,将会启动debug模式,并且会显示所有子模块的处理情况的显示输出
        '''
        self.debug_show = debug_show
        print('initing cam')
        self.cam_id = cam_id
        if cam_id == -1:
            # 使用IP摄像头
            self.smart_cam = smart_cam_receiver()
        else:
            # 打开本地摄像头失败时,将会抛出异常
            self.cam = imageio.get_reader('<video%d>' % cam_id, fps=self.fps)
        print('open cam complete')

        print('load detector')
        # 载入各种检测器
        self.fire_detector = FireDetector(debug_show=debug_show)
        self.smoke_detector = SmokeDetector()
        self.diff_move_detector = DiffMoveDetector(debug_show=debug_show)
        self.human_detector = HumanDetector(const_define.yolo_net_file, const_define.yolo_weights_file, debug_show=debug_show)
        self.recoder = Recorder(const_define.record_path)
        self.notifier = Notifier(self.recoder)
        print('load detector complete')

        # 初始化第一帧为全黑图像
        self.frame = np.zeros([*self.frame_hw, 3], np.uint8)

        # 初始化各个检测器的工作线程
        self.fire_detect_thread = threading.Thread(target=self.fire_detect_run)
        self.smoke_detect_thread = threading.Thread(target=self.smoke_detect_run)
        self.human_detect_thread = threading.Thread(target=self.human_detect_run)
        self.move_detect_thread = threading.Thread(target=self.move_detect_run)

        if self.cam_id == -1:
            self.smart_cam.ctrl_framehw(self.frame_hw)
            self.smart_cam.ctrl_fps(self.fps)
示例#22
0
    def __init__(self):
        # Initialize the file
        self.__file = FileHandler()
        self.options = self.__file.getOptions()

        # Get the last player
        playerName = self.__getLastPlayer()
        self.loadPlayer(playerName)

        # Set the Game menu
        self.__status = self.IN_MENU

        self.resetTimer()

        # Points
        self.__resetModCounter()
        self.__resetPointModifier()

        # Deck
        self.__initializeDeck()

        self.__recorder = Recorder(self.__player.get('options.undo'))
    def run(self):
        '''
        record
        '''
        print("Thread start")
        micRecorder = Recorder(channels=1)

        datetime_string = datetime_to_string()
        filename = "record_" + datetime_string + ".wav"

        with micRecorder.open("records/" + filename, 'wb') as recfile:
            recfile.start_recording()
            #time.sleep(10.0)
            while (LiveFFTWidget.stopRecord != 1):
                pass
            recfile.stop_recording()
            LiveFFTWidget.stopRecord = 0

        VarManager.audioPath = "records/" + filename
        VarManager.audioUploaded = False
        print(VarManager.audioPath)

        print("Recording complete")
示例#24
0
    def test_recordExists(self):
        """Testing the method of checking the existence of record.
        """
        r = Recorder('testRecorder')
        self.assertFalse(r.recordExists()) # Record not exists at initial state

        newRecord = ['abc']
        r.addRecord(newRecord, False)
        self.assertTrue(r.recordExists()) # Record exists after adding a record
    def __init__(self):
        super().__init__()
        self.order_maker = OrderMaker()
        self.trade_history = HistoricalData()
        # self.rd = RealtimeData()    # RealtimeDataのインスタンスを生成する
        self.recorder = Recorder()

        self.df_tail = self.trade_history.df.tail(1)    # csvの最後の一行=最新データを切り取る

        # self.ewma_1day = self.df_tail['ewma1day'][0]
        # self.ewma_3days = self.df_tail['ewma3days'][0]
        # self.ewma_5days = self.df_tail['ewma5days'][0]
        # self.ewma_25days = self.df_tail['ewma25days'][0]

        # self.div_1day = self.df_tail['1dayDiv'][0]
        # self.div_5days = self.df_tail['5dayDiv'][0]
        # self.div_25days = self.df_tail['divergence'][0]

        self.ewma_1hour = self.df_tail['ewma60mins'][0]
        self.ewma_6hours = self.df_tail['ewma360mins'][0]
        # self.ewma_12hours = self.df_tail['ewma12hrs'][0]

        self.ewma_1min = self.df_tail['ewma_1min'][0]
        self.ewma_5mins = self.df_tail['ewma_5mins'][0]

        self.best_bid = 0
        self.best_ask = 0

        self.order_side = 'BUY/SELL'  # Will be BUY or SELL

        self.current_price = self.api.board(product_code=self.product)['mid_price']

        self.orders = []            # 現在の注文が入る
        self.positions = []         # 現在のポジションが入る
        self.ordering_price = 0    # 注文中の価格が入る

        self.market_flow = "SLEEP"     # 市場の流れ
        self.market_status = self.api.gethealth(product_code=self.product)['status']

        self.signal = False    # Trueならば取引GOサイン、Falseならば停止

        self.balance = self.api.getcollateral()['collateral']  # 証拠金残高、レバ1倍なのでそのまま余力

        self.order_id = None
        self.ordering = False   # 注文中か否か確認用
        self.positioning = False    # ポジションあるか否か確認用

        self.waiting_time = self.default_waiting_time      # キャンセルまでの待ち時間(sec)
示例#26
0
    def __init__(self):
        super().__init__()
        self.order_maker = OrderMaker()
        self.trade_history = HistoricalData()

        self.recorder = Recorder()

        self.df_tail = self.trade_history.ewma.tail(1)    # csvの最後の一行=最新データを切り取る
        self.ticker_tail = self.trade_history.fetchdata.tail(2)

        self.ewma_1day = self.df_tail['long'].iloc[0]
        self.ewma_6hours = self.df_tail['short'].iloc[0]

        self.order_side = 'buy/sell'  # Will be buy or sell

        self.current_price = self.bitmex.fetch_ticker(symbol=self.product)['last']
        self.current_volume = self.ticker_tail['volume'].iloc[0]
        self.current_open = self.ticker_tail['open'].iloc[0]
        self.current_close = self.ticker_tail['close'].iloc[0]

        self.orders = []                    # 現在の注文が入る
        self.positions = []                 # 現在のポジションが入る
        self.ordering_price = 0             # 注文中の価格が入る

        self.market_flow = "SLEEP"          # 市場の流れ
        self.signal = False                 # True for GO, False for STOP

        self.last_ordered_open = 0                                           # A bin's open price
        self.balance = self.bitmex.fetch_balance()['BTC']['total'] * 0.9985  # 証拠金残高

        self.order_id = None
        self.ordering = False               # 注文中か否か確認用
        self.positioning = False            # ポジションあるか否か確認用

        self.orderbook = self.bitmex.fetch_order_book('BTC/USD')
        self.bid = self.orderbook['bids'][0][0] if len(self.orderbook['bids']) > 0 else None
        self.ask = self.orderbook['asks'][0][0] if len(self.orderbook['asks']) > 0 else None
        self.spread = (self.ask - self.bid) if (self.bid and self.ask) else None

        self.waiting_time = self.default_waiting_time      # キャンセルまでの待ち時間(sec)
示例#27
0
    def test_recordAutoSaveAfterRecordWithoutAutoSave(self):
        """Testing the record adding method after exercising an adding method without auto saving.
        """
        newRecord = 'abc'
        r = Recorder('testRecorder')
        r.addRecord(newRecord, False)
        self.assertEqual(r.records, [newRecord])
        with open(r.path, 'r') as fin:
            self.assertFalse(fin.read()) # Record file content correctness

        newRecord = 'klm'
        r.addRecord(newRecord)
        with open(r.path, 'r') as fin:
            txt = fin.read()
            self.assertNotEqual(txt, 'abc')
            self.assertEqual(txt, 'abc\nklm') # Newest record was saved together with the previous unsaved record
示例#28
0
    def __init__(self,
                 what_to_grade: WhatToGrade = None,
                 who_to_grade: WhoToGrade = None,
                 getter: Getter = None,
                 tester: Tester = None,
                 recorder: Recorder = None):
        if not what_to_grade:
            what_to_grade = WhatToGrade()
        if not who_to_grade:
            who_to_grade = WhoToGrade()
        if not getter:
            getter = Getter(what_to_grade, who_to_grade)
        if not tester:
            tester = Tester(what_to_grade, who_to_grade)
        if not recorder:
            recorder = Recorder(what_to_grade, who_to_grade)

        self.what_to_grade = what_to_grade
        self.who_to_grade = who_to_grade
        self.getter = getter
        self.tester = tester
        self.recorder = recorder
示例#29
0
    def test_recordWithoutAutoSaveAfterRecordAutoSave(self):
        """Testing the record adding method without auto saving after exercising an adding method with auto saving.
        """
        newRecord = 'abc'
        r = Recorder('testRecorder')
        r.addRecord(newRecord)
        self.assertEqual(r.records, ['abc']) # Record list correctness
        with open(r.path, 'r') as fin:
            self.assertEqual(fin.read(), 'abc') # Record file content correctness

        newRecord = 'klm'
        r.addRecord(newRecord, False)
        self.assertEqual(r.records, ['abc', 'klm']) # Record list correctness
        with open(r.path, 'r') as fin:
            txt = fin.read()
            self.assertEqual(txt, 'abc') # Record file remained unchanged
            self.assertNotEqual(txt, 'abc\nklm')
示例#30
0
class Game:
    PAUSED = 0
    IN_GAME = 1
    FINISHED = 2
    IN_MENU = 3
    QUIT = 4

    def __init__(self):
        # Initialize the file
        self.__file = FileHandler()
        self.options = self.__file.getOptions()

        # Get the last player
        playerName = self.__getLastPlayer()
        self.loadPlayer(playerName)

        # Set the Game menu
        self.__status = self.IN_MENU

        self.resetTimer()

        # Points
        self.__resetModCounter()
        self.__resetPointModifier()

        # Deck
        self.__initializeDeck()

        self.__recorder = Recorder(self.__player.get('options.undo'))

    ##
    # Builds the deck and temporary deck piles
    ##
    def __initializeDeck(self):
        # Initialize discard columns
        self.__discardPiles = [
            Deck(),
            Deck(),
            Deck(),
            Deck()
        ]

        deck = Deck()
        deck.buildFullDeck()
        deck.shuffle()
        self.__deck = deck

    def undo(self):
        if self.__recorder.canUndo():
            state = self.__recorder.undo()
            if state is not None:
                self.__applyState(state)

    def __applyState(self, state):
        self.__player.set('score', state['score'])
        self.__deck = state['deck']
        self.__discardPiles = state['discardPiles']

    def __saveState(self):
        state = {
            'score': self.__player.get('score'),
            'deck': deepcopy(self.__deck),
            'discardPiles': deepcopy(self.__discardPiles)
        }
        self.__recorder.pushState(state)

    ##
    # Sets the current game status
    ##
    def __setGameStatus(self, status):
        self.__status = status

    ##
    # Returns the last recorded player or the default
    ##
    def __getLastPlayer(self):
        name = self.__file.getLatestPlayerByName()
        if name is None:
            return Player.DEFAULT_PLAYER
        return name

    def getPlayer(self):
        return self.__player

    def getPlayerStats(self):
        stats = self.__player.getAllStats(options=False)

        # Pretty print time
        stats['time'] = time.strftime("%M:%S", time.gmtime(int(stats['time'])))

        table = []
        for stat in stats:
            table.append([
                stat,
                stats[stat]
            ])
        return table

    ##
    # Sets the current game status to running
    ##
    def startGame(self):
        self.__setGameStatus(Game.IN_GAME)
        self.__initializeDeck()
        self.deal()
        # First deal of the game, reset the state
        self.__recorder.toggleUndos(self.__player.get('options.undo'))
        self.__recorder.reset()
        self.__resetModCounter()
        self.__resetPointModifier()
        self.resetTimer()
        self.__startTimer()

    def isInGame(self):
        return self.getGameStatus() == Game.IN_GAME

    def isPaued(self):
        return self.getGameStatus() == Game.PAUSED

    def isFinished(self):
        return self.getGameStatus() == Game.FINISHED

    def isInMenu(self):
        return self.getGameStatus() == Game.IN_MENU

    def quit(self):
        return self.getGameStatus() == Game.QUIT

    ##
    # Sets the current game status to paused
    ##
    def pauseGame(self):
        self.__player.addTo('time', self.__pauseTimer())
        self.__setGameStatus(Game.PAUSED)

    ##
    # Sets the current game status to finished
    ##
    def finishGame(self):
        self.__setGameStatus(Game.FINISHED)
        if self.didPlayerWin():
            self.__player.addTo('gamesWon', 1)
        else:
            self.__player.addTo('gamesLost', 1)
        self.__player.addTo('time', self.__pauseTimer())
        self.savePlayer(self.__player)

    def quitGame(self):
        self.__setGameStatus(Game.QUIT)
        self.savePlayer(self.__player)

    ##
    # Saves the active Player to file
    ##
    def savePlayer(self, player):
        self.__file.savePlayer(player)

    ##
    # Loads a Player from file
    ##
    def loadPlayer(self, playerName):
        playerInfo = self.__file.loadPlayerByName(playerName)
        if playerInfo is not None:
            self.__player = Player(playerInfo)
            self.__file.saveLatestPlayer(playerName)
        else:
            self.__player = Player(playerName)
            self.__file.savePlayer(self.__player)

    ##
    # Returns the 10 top scores from file
    ##
    def getTopScores(self):
        scores = self.__file.getScores()
        scores.sort(reverse=True)
        return scores[0, 10]

    ##
    # Returns the 10 top times from file
    ##
    def getTopTimes(self):
        times = self.__file.getTimes()
        times.sort(reverse=True)
        return times[0, 10]

    ##
    # Returns all Players from file
    ##
    def getPlayerNames(self):
        return self.__file.listAllPlayers()

    ##
    # Returns the current game status
    ##
    def getGameStatus(self):
        return self.__status

    ##
    # Returns the current facing playable Cards
    ##
    def getCurrentFacingCards(self):
        cards = []
        for deck in self.__discardPiles:
            cards.append(deck.getCardAt(-1))
        return cards

    def printCards(self):
        printableDecks = []
        for deck in self.__discardPiles:
            printableDecks.append(deck.getDeckPrint())

        output = ''
        found = True
        index = 0
        while found:
            found = False
            row = ''
            for deck in printableDecks:
                row += ' '
                try:
                    card = deck[index]
                except IndexError:
                    card = None
                if card is not None:
                    found = True
                    row += str(card)
                else:
                    row += ' ' * 7
            index += 1
            output += '\n' + row
        return output

    ##
    # Deals four Cards from the deck
    ##
    def deal(self):
        if self.__deck.cardsRemaining() > 0:
            self.__saveState()
            for el in range(len(self.__discardPiles)):
                card = self.__deck.popCard()
                self.__discardPiles[el].pushCard(card)

            self.__resetModCounter()
            self.__resetPointModifier()
            return self.getCurrentFacingCards()

        # no more cards left, game over
        self.finishGame()
        return None

    ##
    # Removes a Card from its pile
    ##
    def rmCard(self, index):
        if self.__canRemoveCardFromPile(index):
            self.__saveState()
            self.incrementModCounter()
            self.__discardPiles[index].popCard()
            self.addRemovedCardPoints()

    def mvCard(self, index):
        if index in range(0, len(self.__discardPiles)):
            cardInQuestion = self.__discardPiles[index].getFacingCard()
            if cardInQuestion is not None:
                for pile in self.__discardPiles:
                    if pile.getFacingCard() is None:
                        self.__saveState()
                        self.__discardPiles[index].popCard()
                        pile.pushCard(cardInQuestion)
                        return True
            print(str(cardInQuestion) + ' cannot be moved')
        print('Invalid column selected')

    def __canRemoveCardFromPile(self, index):
        if index in range(0, len(self.__discardPiles)):
            cardInQuestion = self.__discardPiles[index].getFacingCard()
            print('card in question: ' + str(cardInQuestion))
            if cardInQuestion is not None:
                for pile in self.__discardPiles:
                    if pile.dominatesCard(cardInQuestion):
                        return True
            print(str(cardInQuestion) + ' cannot be removed')
        print('Invalid column selected')
        return False

    ##
    # Adds points to the Player's score multiplied by the mod counter
    ##
    def addRemovedCardPoints(self):
        if self.__modCounter == 2:
            self.__resetModCounter()
            self.__modifier += 1
        updated = self.__player.get('score') + (10 * self.getModifier())
        self.__player.set('score', updated)

    ##
    # Adds one to the mod counter
    ##
    def incrementModCounter(self):
        self.__modCounter += 1

    ##
    # Resets the mod counter back to default (0)
    ##
    def __resetModCounter(self):
        self.__modCounter = 0

    ##
    # Resets the modifier back to default (1)
    ##
    def __resetPointModifier(self):
        self.__modifier = 1

    ##
    # Increases the point modifier by 1
    ##
    def increasePointModifier(self):
        self.__modifier += 1

    def getModifier(self):
        return self.__modifier

    ##
    # Adds a static number of points when winning the game
    ##
    def addGameWonPoints(self):
        self.__player.set('score', 100)

    def getCurrentTime(self):
        return time.strftime("%M:%S", time.gmtime(int(time.time() - self.__startTime)))

    def resetTimer(self):
        self.__startTime = 0
        self.__pausedTime = 0

    def __startTimer(self):
        diff = 0
        if self.__pausedTime > 0:
            diff = int(self.__pausedTime - self.__startTime)
        self.__pausedTime = 0
        self.__startTime = time.time() - diff

    def __pauseTimer(self):
        self.__pausedTime = time.time()
        return int(self.__pausedTime - self.__startTime)

    def didPlayerWin(self):
        for deck in self.__discardPiles:
            if deck.cardsRemaining() != 1 or deck.getFacingCard().getPosition() != 1:
                return False
        return True
示例#31
0
from Recorder import Recorder
from SpeechToText import speech_to_text
from TextTranslator import translate_text

recorder = Recorder('/tmp/out.wav')
recorder.start()
print ">>> Recording"
raw_input('press enter to stop ...')
recorder.stop()
print "<<< Stopped "
text = speech_to_text('es-MX', '/tmp/out.wav')
print text
translation = translate_text('en', text)
print translation
示例#32
0
class Mouvements(object):

	def __init__(self):
		IP, PORT = "127.0.0.1", 9559
		self.vx = 0.0
		self.vy = 0.0
		self.vth = 0.0
		self.dt = 0.227
		self.joints = []
		self.io_file = IO_file()
		self.is_recording = False
		self.postureProxy = ALProxy("ALRobotPosture", IP, PORT)
		self.motionProxy = ALProxy("ALMotion", IP, PORT)
		self.motionProxy.setWalkArmsEnabled(True, True)
		self.motionProxy.setMotionConfig([["ENABLE_FOOT_CONTACT_PROTECTION", False]])
		self.motionProxy.setFallManagerEnabled(False)

	def stiffness(self, go_rigide):
		parametre = 1.0 if go_rigide else 0.0
		self.motionProxy.stiffnessInterpolation("Body", parametre, 1.0)

	def go_debout(self):
		self.stiffness(True)
		self.postureProxy.goToPosture("Stand", 0.8)

	def go_assis(self):
		self.stiffness(True)
		self.postureProxy.goToPosture("Sit", 0.8)
		self.stiffness(False)

	def go_ventre(self):
		self.stiffness(True)
		self.postureProxy.goToPosture("LyingBelly", 0.8)
		self.stiffness(False)

	def go_dos(self):
		self.stiffness(True)
		self.postureProxy.goToPosture("LyingBack", 0.8)
		self.stiffness(False)

	def go_dos(self):
		self.stiffness(True)
		self.postureProxy.goToPosture("Crouch", 0.8)
		self.stiffness(False)

	def go_move(self):
		self.motionProxy.setWalkTargetVelocity(self.vx, self.vy, self.vth, 0.8)

	def set_vx(self, vx):	self.vx = vx
	def set_vy(self, vy):	self.vy = vy
	def set_vth(self, vth):	self.vth = vth

	def update_joints(self):	self.joints = self.motionProxy.getAngles("Body", False)

	def save_joints(self, write):
		self.update_joints()
		if write: fichier = self.io_file.init_write_joints()
		self.io_file.add_joints(self.joints, self.dt)
		if write: self.io_file.write_joints(fichier)

	def record(self):
		self.is_recording = not self.is_recording
		if self.is_recording:
			self.recorder = Recorder(self)
			self.recorder.continuer = True
			self.recorder.start()
		else:
			self.recorder.continuer = False
			self.recorder.join()

	def apply_joints_from_file(self, only_last):
		temps, angles = self.io_file.read_joints(only_last)
		if len(angles) == 0 : return
		self.motionProxy.angleInterpolation("Body", angles, temps, True)

	def move_head(self, vx, vy):
		self.motionProxy.angleInterpolation(["HeadYaw", "HeadPitch"], [-0.1 * float(vx), -0.1 * float(vy)], [0.2, 0.2], False)
audio_base[2] = {
    "um": audio.wavread(wav_directory + 'um.wav')[0],
    "dois": audio.wavread(wav_directory + 'dois.wav')[0],
}
audio_base[3] = {
    "matrix": audio.wavread(wav_directory + 'matrix.wav')[0],
    "braveheart": audio.wavread(wav_directory + 'braveheart.wav')[0],
    "constantine": audio.wavread(wav_directory + 'constantine.wav')[0],
}
audio_base[4] = {
    "dinheiro": audio.wavread(wav_directory + 'dinheiro.wav')[0],
    "cartao": audio.wavread(wav_directory + 'cartao.wav')[0],
}
audio_base[5] = {
    "finalizar_compra": audio.wavread(wav_directory + 'finalizar_compra.wav')[0],
    "sair": audio.wavread(wav_directory + 'sair.wav')[0],
}

if __name__ == "__main__":
    for i in range(6):
        recorder = Recorder()
        recognizer = Recognizer()

        recorder.record(time_to_run=2)
        (input_signal1, sampling_rate1, bits1) = audio.wavread('record.wav')
        Recognizer.test_audio(audio_base[i], input_signal1, wav_directory)

    fs = sampling_rate1
    lowcut = 300
    highcut = 3400
示例#34
0
        # NORMAL_NUM = category[key] if key.isdigit() else key
        print('Current Item: {}'.format(NORMAL_NUM))

        train_path = '/home/user/Documents/Public_Dataset/MVTec_AD/{}/train/'.format(
            NORMAL_NUM)
        test_root = '/home/user/Documents/Public_Dataset/MVTec_AD/{}/test/'.format(
            NORMAL_NUM)
        gt_root = '/home/user/Documents/Public_Dataset/MVTec_AD/{}/ground_truth/'.format(
            NORMAL_NUM)

        # current_ckpt = "23999"
        Experiment_name = 'No.{}_p32_IGD'.format(str(NORMAL_NUM), sig_f, rec_f,
                                                 svd_f)
        # Experiment_name = 'No.{}_vae'.format(str(NORMAL_NUM))

        recorder = Recorder(Experiment_name,
                            'MVTec_No.{}'.format(str(NORMAL_NUM)))

        save_root_path = './p32/check_points'

        create_dir(save_root_path)
        create_dir(
            os.path.join(save_root_path, "p32_SR-{}".format(args.sample_rate)))
        ckpt_path = './p32/check_points/p32_SR-{}/{}'.format(
            args.sample_rate, Experiment_name)

        if not os.path.exists(ckpt_path):
            os.mkdir(path=ckpt_path)
        auc_file = open(ckpt_path + "/auc.txt", "w")
        auc_file.close()

        generator = twoin1Generator(64, latent_dimension=latent_dimension)
示例#35
0
class GUI(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        parent.title("HappenedOrNotRecorder")
        self.pack(fill=BOTH, expand=1)

        self.recoder = Recorder()
        self.__create_widgets()
        self.update_content()

    def __create_widgets(self):
        # 選擇事件
        self.section = ttk.Combobox(self, state='readonly', )
        self.section.place(x=3, y=3)
        self.section.bind('<<ComboboxSelected>>', self.section_handler)
        self.__update_sections()

        # 發生與否的記錄按鈕
        button = Button(self)
        button["text"] = "Y"
        button["width"] = 5
        button["height"] = 2
        button.place(x=180, y=30)
        button["command"] = self.do_happened
        button = Button(self)
        button["text"] = "N"
        button["width"] = 5
        button["height"] = 2
        button.place(x=180, y=80)
        button["command"] = self.do_not_happened

        # Total, Happened, Ratio Lable
        label = Label(self)
        label["text"] = "Total :"
        label.place(x=15, y=35)
        label = Label(self)
        label["text"] = "Happened :"
        label.place(x=15, y=65)
        label = Label(self)
        label["text"] = "Ratio :"
        label.place(x=15, y=95)

        # 總次數, 發生次數, 比例
        self.total = Label(self)
        self.total.place(x=95, y=35)
        self.happened = Label(self)
        self.happened.place(x=95, y=65)
        self.ratio = Label(self)
        self.ratio.place(x=95, y=95)

        # 發生與否的記錄按鈕
        button = Button(self)
        button["text"] = "增加新事件"
        button["width"] = 10
        button.place(x=27, y=140)
        button["command"] = self.do_add_new_section
        button = Button(self)
        button["text"] = "刪除此事件"
        button["width"] = 10
        button.place(x=125, y=140)
        button["command"] = self.do_remove_section


    def __update_sections(self):
        content = []
        for e in self.recoder.get_sections():
            content.append(e.decode('utf-8'))
        self.section['values'] = content
        self.section.set(self.recoder.current_section)

    def section_handler(self, event):
        self.update_content()

    def do_happened(self):
        self.recoder.record_happened()
        self.update_context()

    def do_not_happened(self):
        self.recoder.record_not_happened()
        self.update_context()

    def do_add_new_section(self):
        popup = PopupEntry(self.master)
        self.wait_window(popup.top_window)

        self.recoder.add_section(popup.get_input_in_utf8())
        self.__update_sections()
        self.update_content()

    def do_remove_section(self):
        is_sure = tkMessageBox.askyesno("Remove Event", "Do you want to remove this event ?")
        if is_sure:
            self.recoder.remove_section(self.get_section_in_utf8())
            self.__update_sections()
            self.update_content()

    def update_content(self):
        self.recoder.change_section(self.get_section_in_utf8())
        self.update_context()

    def update_context(self):
        self.total['text'] = self.recoder.current_total
        self.happened['text'] = self.recoder.current_happened
        try:
            ratio = '%.2f%%' % (float(self.recoder.current_happened) / self.recoder.current_total * 100)
        except:
            ratio = 'N/A'
        self.ratio['text'] = ratio

    def get_section_in_utf8(self):
        return self.section.get().encode('utf-8')
class CompdaysrecorderWindow(Window):
    __gtype_name__ = "CompdaysrecorderWindow"
    
    def finish_initializing(self, builder): # pylint: disable=E1002
        """Set up the main window"""
        super(CompdaysrecorderWindow, self).finish_initializing(builder)

        self.AboutDialog = AboutCompdaysrecorderDialog
        self.PreferencesDialog = PreferencesCompdaysrecorderDialog
        
        # The status label
#        self.statusLabel = self.builder.get_object("statusLabel")

        # Code for other initialization actions should be added here.
        self.recorder = Recorder()
        
        # Date label
        self.dateLabel = self.builder.get_object("dateLabel")
        
        # Radio buttons
        self.aRadioButton = self.builder.get_object("aRadioButton")
        self.dRadioButton = self.builder.get_object("dRadioButton")
        self.nRadioButton = self.builder.get_object("nRadioButton")
        self.oRadioButton = self.builder.get_object("oRadioButton")
        self.hRadioButton = self.builder.get_object("hRadioButton")
        
        # Spin button
        self.extraSpinButton = self.builder.get_object("extraSpinButton")
        
        # Edit, Save and Delete buttons
        self.editButton = self.builder.get_object("editButton")
        self.saveButton = self.builder.get_object("saveButton")
        self.deleteButton = self.builder.get_object("deleteButton")
        
        # Calendar
        self.calendar = self.builder.get_object("calendar")
        r = self.recorder.findLastEntry()
        _ = r['date']
        self.calendar.select_month(month=_.month - 1, year=_.year)
        self.calendar.select_day(_.day)
        self.dateLabel.set_text("{0:02d}/{1:02d}/{2:04d}".format(_.day, _.month, _.year))
        tmp = r['shift']
        if (tmp=='d') : self.dRadioButton.set_active(True)
        elif (tmp=='a') : self.aRadioButton.set_active(True)
        elif (tmp=='n') : self.nRadioButton.set_active(True)
        elif (tmp=='o') : self.oRadioButton.set_active(True)
        else : self.hRadioButton.set_active(True)
        self.extraSpinButton.set_value(r['extra'])
        self.enableEdition(False)
        
        # Plot area
        self.plotArea = self.builder.get_object("plotArea")
        self.displayPlotArea = self.builder.get_object("displayPlotArea")
        self.upArrow = self.builder.get_object("upArrow")
        self.downArrow = self.builder.get_object("downArrow")
        self.plot = self.recorder.plotOffHours()
        self.plotArea.add(self.plot)
        
        # compDaysLabel
        self.compDaysLabel = self.builder.get_object("compDaysLabel")
        self.updateCompDays()
        
    def on_displayPlotArea_toggled(self, widget):
        if self.displayPlotArea.get_active() :
            self.plot = self.recorder.plotOffHours()
            self.plotArea.set_visible(True)
            self.plotArea.show()
            self.displayPlotArea.set_image(self.upArrow)
        else :
#            self.plotArea.set_visible(False)
            self.plotArea.hide()
            self.displayPlotArea.set_image(self.downArrow)
            
    def whoIsActive(self):
        if (self.dRadioButton.get_active()) : return 'd'
        elif (self.aRadioButton.get_active()) : return 'a'
        elif (self.nRadioButton.get_active()) : return 'n'
        elif (self.oRadioButton.get_active()) : return 'o'
        else : return 'h'
        
    def enableEdition(self, boolean):
        if boolean :
            self.dRadioButton.set_sensitive(True)
            self.aRadioButton.set_sensitive(True)
            self.nRadioButton.set_sensitive(True)
            self.oRadioButton.set_sensitive(True)
            self.hRadioButton.set_sensitive(True)
            self.extraSpinButton.set_sensitive(True)
            self.editButton.set_sensitive(False)
            self.saveButton.set_sensitive(True)
            self.deleteButton.set_sensitive(False)
        else :
            self.dRadioButton.set_sensitive(False)
            self.aRadioButton.set_sensitive(False)
            self.nRadioButton.set_sensitive(False)
            self.oRadioButton.set_sensitive(False)
            self.hRadioButton.set_sensitive(False)
            self.extraSpinButton.set_sensitive(False)
            self.editButton.set_sensitive(True)
            self.saveButton.set_sensitive(False)
            self.deleteButton.set_sensitive(True)
            
    def updateCompDays(self) :
        off = self.recorder.computeOffHours()
        if off< 0 :
            self.compDaysLabel.override_color(0, Gdk.RGBA(1,0,0,1))
        else :
            self.compDaysLabel.override_color(0, Gdk.RGBA(0,1,0,1))
        self.compDaysLabel.set_text(str(off/8))
        

    def on_calendar_day_selected(self, widget):
        # Parse the date selected
        year, month, day = self.calendar.get_date()
        dateObj = date(year, month+1, day)
        
        self.dateLabel.set_text("{0:02d}/{1:02d}/{2:04d}".format(day, month+1, year))
        
        # Do we already have an entry for this date ?
        r = self.recorder.findEntry(dateObj)
        if (r != -1):
            # The entry already exist.
            tmp = r['shift']
            if (tmp=='d') : self.dRadioButton.set_active(True)
            elif (tmp=='a') : self.aRadioButton.set_active(True)
            elif (tmp=='n') : self.nRadioButton.set_active(True)
            elif (tmp=='o') : self.oRadioButton.set_active(True)
            else : self.hRadioButton.set_active(True)
            
            self.extraSpinButton.set_value(r['extra'])
            # Disable editing.
            self.enableEdition(False)
        else :
            # Enable edition
            self.enableEdition(True)
            
    def on_editButton_clicked(self, widget):
        # Toggle edit mode
        self.enableEdition(True)
        
    def on_saveButton_clicked(self, widget):
        year, month, day = self.calendar.get_date()
        dateObj = date(year, month+1, day)
        
        shift = self.whoIsActive()
        
        extra = int(self.extraSpinButton.get_value())
        
        self.recorder.writeEntry(dateObj, shift, extra)
        self.enableEdition(False)
        self.updateCompDays()
        
    def on_deleteButton_clicked(self, widget):
        year, month, day = self.calendar.get_date()
        dateObj = date(year, month+1, day)
        self.recorder.removeEntry(dateObj)
        self.enableEdition(True)
        self.updateCompDays()