コード例 #1
0
ファイル: devices.py プロジェクト: jpanikulam/visar
  def __init__(self):
    '''setup the serial device handler. Once this object is created, 
          you must call destroy() before exiting.
       Updates are typles in one of three formats:   
         ('BATTERY',  <battery level>)  # system battery level
         ('SHUTDOWN', None)             # system has recieved a shutdown command
         ('CONTROL', <control update>)  # button press
    '''

    Interface.__init__(self)

    self.kill_flag = False
    self.battery = 100 # current battery level
    self.controls = None # current control state
    self.do_shutdown = True # flag for shutting down unit on destroy()

    # try to open the serial ports and handler threads
    try:
      # serial port uses long reads to block and timeouts to wake back up
      self.pwr_port = serial.Serial(PWR_NAME, timeout=TIMEOUT, writeTimeout=TIMEOUT)
      self.pwr_port.baudrate = BAUD
      thread = threading.Thread(target=self.pwr_thread)
      thread.start()
    except: print 'Could not open power device' 
    
    try:
      # conn port uses a similar structure, timeouts determine how long to block for
      self.con_port = serial.Serial(CON_NAME, timeout=TIMEOUT, writeTimeout=TIMEOUT)
      self.con_port.baudrate = BAUD
      thread = threading.Thread(target=self.con_thread)
      thread.start()
    except: print 'Could not open controller device'
コード例 #2
0
ファイル: server.py プロジェクト: zarya/OpenCTRL
def run():
    import optparse
    from cli.console import Console

    parser = optparse.OptionParser()
    parser.add_option('-d', '--debug', action='store_true', default=False,
        dest='debug',
        help='show debugging output (default: no)')
    parser.add_option('-l', '--line', default='/dev/ttyUSB1',
        dest='line',
        help='serial line device (default: /dev/ttyUSB1)')
    parser.add_option('-b', '--baud', default=9600, type='int',
        dest='baudrate',
        help='serial baud rate (default: 9600 bps)')
    parser.add_option('-t', '--timeout', default=1, type='int',
        dest='timeout',
        help='serial read timeout (default: 1 second)')
    
    options, args = parser.parse_args()

    ser = serial.Serial(options.line, options.baudrate, timeout=options.timeout)
    rcv = Receiver(ser,options).start()
    if args and args[0] == "console":
        console = Console() 
        interface = Interface(ser,console) 
        try:
            try:
                interface.loop()
                
            except KeyboardInterrupt:
                rcv.running = False
        finally:
            console.restore()
コード例 #3
0
ファイル: tc.py プロジェクト: unnch/spell-sat
 def __init__(self):
     Interface.__init__(self, "TC")
     Configurable.__init__(self)
     self.__lastStatus = None
     self.__lastElement = None
     self.__useConfig = {}
     LOG("Created")
コード例 #4
0
ファイル: sniffer.py プロジェクト: ShaneHarvey/wepcracker
def iwconfig():
    devnull = open(os.devnull, 'w')
    lst = []

    cmd = Popen(['iwconfig'], stdout=PIPE, stderr=devnull)
    for line in cmd.communicate()[0].split('\n\n'):
        tmpiface = Interface(None, None, None, None)
        line = line.strip()

        if len(line) == 0:
            continue

        ifname = re.search('^([A-Za-z0-9]+)', line)
        ifessid = re.search('ESSID:"([A-Za-z0-9]+)"', line)
        ifmode = re.search('Mode:([A-Za-z]+)', line)
        ifbssid = re.search('Access Point: ([0-9:A-F]+)', line)

        if ifname is not None:
            tmpiface.name = ifname.group(1)

            if ifessid is not None:
                tmpiface.essid = ifessid.group(1)

            if ifmode is not None:
                tmpiface.mode = ifmode.group(1)

            if ifbssid is not None:
                tmpiface.bssid = ifbssid.group(1)

            lst.append(tmpiface)

    devnull.close()
    return lst
コード例 #5
0
ファイル: aircomm.py プロジェクト: matu7151/PenguPilot
def main(name):
   sm = generate_map(name)
   
   opcd = OPCD_Interface(sm['opcd_ctrl'])
   platform = opcd.get('platform')
   device = opcd.get(platform + '.nrf_serial')
   
   global THIS_SYS_ID
   THIS_SYS_ID = opcd.get('aircomm.id')
   key = opcd.get('aircomm.psk')
   crypt.init(key)
   mhist = MessageHistory(60)

   out_socket = sm['aircomm_out']
   in_socket = sm['aircomm_in']

   aci = Interface(device)
   acr = ACIReader(aci, out_socket, mhist)
   acr.start()

   # read from SCL in socket and send data via NRF
   while True:
      data = loads(in_socket.recv())
      if len(data) == 2:
         msg = [data[0], THIS_SYS_ID, data[1]]
      elif len(data) > 2:
         msg = [data[0], THIS_SYS_ID] + data[1:]
      else:
         continue
      crypt_data = crypt.encrypt(dumps(msg))
      mhist.append(crypt_data)
      aci.send(crypt_data)
コード例 #6
0
ファイル: resources.py プロジェクト: Spacecraft-Code/SPELL
 def __init__(self):
     Interface.__init__(self, "RSC")
     Configurable.__init__(self)
     LOG("Created")
     self.toCheck = [ 'TM', 'TC' ]
     self.rscStatus = {}
     self.rscCallbacks = []
コード例 #7
0
ファイル: forbid.py プロジェクト: davinwong/forbid
def main():
    # command line arguments
    history = DATA_FILES_FOLDER_PATH + sys.argv[1]
    control_input = DATA_FILES_FOLDER_PATH + sys.argv[2]
    control_output = DATA_FILES_FOLDER_PATH + sys.argv[3]
    bid_stream_files = []
    for i in range(0, NUMBER_BID_STREAMS):
        bid_stream_files.append(DATA_FILES_FOLDER_PATH + sys.argv[4+i])

    bid_market = BidMarket()
    bid_market.import_history(history)

    interface = Interface(
        bid_market,
        control_input,
        control_output)

    bid_streams = []
    for i in range(0, NUMBER_BID_STREAMS):
        bid_streams.append(BidStream(bid_stream_files[i], bid_market))

        # make daemons so threads close with program
        bid_streams[i].daemon = True

        bid_streams[i].start()

    interface.open_control_input_stream()
コード例 #8
0
 def __init__(self, cni, mac, host_ifname, tag):
     self.pid = os.getpid()
     self.container_mac = mac
     self.host_ifname = host_ifname
     self.vlan_tag = tag
     self.vlan_ifname = CniMacVlan._make_vlan_intf_name(tag)
     CniInterface.__init__(self, cni)
     return
コード例 #9
0
ファイル: tm.py プロジェクト: Spacecraft-Code/SPELL
 def __init__(self):
     Interface.__init__(self, "TM")
     Configurable.__init__(self)
     self.__tmParameters = {}
     self.__verifiers = []
     self.__verifTable = []
     self.__verifMutex = thread.allocate_lock()
     self.__ctxName = None
     LOG("Created")
コード例 #10
0
ファイル: udpping3.py プロジェクト: AlexGiovanentti/zguide
def main():
    interface = Interface()
    while True:
        try:
            print(interface.recv())
        except KeyboardInterrupt:
            print("interrupted")
            break
    interface.stop()
コード例 #11
0
ファイル: network.py プロジェクト: nomnombtc/electrum
 def new_interface(self, server, socket):
     self.add_recent_server(server)
     interface = Interface(server, socket)
     interface.mode = 'checkpoint'
     self.interfaces[server] = interface
     self.request_header(interface, self.blockchain.checkpoint_height)
     if server == self.default_server:
         self.switch_to_interface(server)
     self.notify('interfaces')
コード例 #12
0
ファイル: curses.py プロジェクト: netixx/NetProbes
 def __init__(self, probeIp):
     Interface.__init__(self, probeIp)
     #         Thread.__init__(self)
     #         self.setName("Cli")
     self.isRunning = True
     # wins and boxes
     self.status = None
     self.commandInput = None
     self.text = None
     self.probesPanel = None
コード例 #13
0
ファイル: billiard.py プロジェクト: ixoth/billiard
class Billiard:
	def new_game(self):
		self.scores = [0, 0]
		self.sim.add_ball(0, 0.5, 0.5, 0.0, 0.0)

		#build balls triangle
		for i in range(6):
			for j in range(i):
				self.sim.add_ball((i*(i-1))/2+j+1, 1.3+i*0.06, 0.5+j*0.06-i*0.03, 0.0, 0.0)
		
	def __init__(self):
		self.gui = Interface()
		self.gui.start()
		self.sim = Simulation()
		clock = pygame.time.Clock()
		self.gui.current_player = 0

		while not self.gui.done:
			current_player = self.gui.current_player

			#start new game if requested
			if self.gui.new_game_request:
				self.gui.new_game_request = False
				self.new_game()
			self.gui.balls = {}

			#has current player changed?
			if not self.gui.stable and self.sim.is_stable():
				current_player = (current_player+1)%2
				self.gui.current_player = current_player
			self.gui.stable = self.sim.is_stable()

			#update ball positions
			for label, ball in self.sim.balls.iteritems():
				self.gui.balls[label] = ball.pos

			#read shot command from interface and execute them
			if len(self.gui.shots) != 0:
				(angle, power) = self.gui.shots.pop()
				v = Conf.VMAX*power
				angle = (angle/180.0)*math.pi
				self.sim.balls[0].x_velocity = -v*math.sin(angle)/Conf.FPS
				self.sim.balls[0].y_velocity = -v*math.cos(angle)/Conf.FPS
			
			#check if player hit any pockets and update score
			res = self.sim.next_iter()
			if 0 in [p[0] for p in res]:
				self.sim.add_ball(0, 0.5, 0.5, 0.0, 0.0)
				self.scores[current_player] -= 1
			for ball, pocket in res:
				if ball != 0:
					self.scores[current_player] += 1
			self.gui.scores = self.scores

			clock.tick(Conf.FPS)
コード例 #14
0
ファイル: network.py プロジェクト: samedjukic/electrum
 def new_interface(self, server, socket):
     # todo: get tip first, then decide which checkpoint to use.
     self.add_recent_server(server)
     interface = Interface(server, socket)
     interface.blockchain = None
     interface.tip = 0
     interface.mode = 'checkpoint'
     self.interfaces[server] = interface
     self.request_header(interface, self.get_checkpoint())
     if server == self.default_server:
         self.switch_to_interface(server)
     self.notify('interfaces')
コード例 #15
0
ファイル: Game.py プロジェクト: Anovi-Soft/Python
class Game:
    def __init__(self, size, manager=None, player_one=None,
                 player_two=None, rnd=1, online=None):
        self.size = size
        self.manager = manager
        if manager is not None:
            self.manager.load_images(size)
            self.interface = Interface(size,
                                   self.manager.img_dict,
                                   self.manager.options)
        self.person = 1
        self.online = online
        self.end = False
        self.message = None
        self.players = {1-2*rnd: player_one, -1+2*rnd: player_two}
        self.points = {-1: 2, 1: 2}
        self.active = False
        self.load = 0
        self.field = [[0] * size for i in range(size)]
        self.size = size
        if manager is not None:
            self.interface.set_information(self.points, self.person, self.players)

    def is_end(self):
        return self.end

    def the_end(self):
        self.end = True

    def descend(self, x, y):
        pass

    def get_valid_path(self):
        pass

    def start(self):
        pass

    def event(self, events):
        pass

    def update(self, dt):
        if not self.active:
            if self.load <= PASSIVE:
                self.load += dt
            else:
                self.active = True

    def draw(self, display):
        path = self.valid_path if (self.players[self.person] == Player.man) \
            else {}
        self.interface.draw(display, self.field, path)
コード例 #16
0
ファイル: main.py プロジェクト: th13f/alert_system
def main():
    pygame.init()  # Инициация PyGame, обязательная строчка
    screen = pygame.display.set_mode(DISPLAY)  # Создаем окошко
    pygame.display.set_caption("Alert system")  # Пишем в шапку
    clock = pygame.time.Clock()
    fps = 30

    interface = Interface(BACKGROUND_COLOR, DISPLAY)

    while 1:  # Основной цикл программы
        for e in pygame.event.get():  # Обрабатываем события
            keys = pygame.key.get_pressed()
            if keys[pygame.K_f]:
                interface.mode = interface.FIRE_MODE
            elif keys[pygame.K_c]:
                interface.mode = interface.CHEM_MODE
            elif keys[pygame.K_v]:
                interface.mode = interface.INACTIVE_MODE
            if True in mouse.get_pressed():
                pos = mouse.get_pos()
                if pos[0] < 1000:
                    interface.new_object(pos)
            if e.type == QUIT:
                raise SystemExit("QUIT")
        interface.update()
        screen.blit(interface.image, (0, 0))  # Каждую итерацию необходимо всё перерисовывать
        pygame.display.update()  # обновление и вывод всех изменений на экран
        clock.tick_busy_loop(fps)
コード例 #17
0
ファイル: gdbserver.py プロジェクト: wzw19890321/xnu-1
class GDBServer(object):
    """instance of gdbserver"""

    def __init__(self, backing_instance):
        super(GDBServer, self).__init__()
        self.process = backing_instance
        self.portnum = random.randint(2000, 8000)
        logging.info("Starting gdb server for localhost:%d" % self.portnum)
        self.conn = Interface("localhost", self.portnum)
        self.version_string = "name:kdbserver;version:0.1"

    def run(self):
        if not self.conn.connect():
            logging.critical("No client connected. Bailing.")
            return False

        logging.debug("Starting gdb server.")

        while True:
            # loop for running the server.
            # read command
            readBytes = ""

            while True:
                try:
                    p_bytes = self.conn.read()
                except Exception, e:
                    logging.warn("found exception in read %s" % (str(e)))
                    logging.debug("currentbytes: %s" % readBytes)
                    readBytes = ""
                    break
                readBytes += p_bytes
                p_begin = readBytes.find("$")
                p_end = readBytes.find("#")
                if p_begin >= 0 and p_end >= 0 and p_end > p_begin:
                    break
            # if empty message or acks just ignore
            if readBytes in ("", "+"):
                logging.debug("ignoring message: %s" % readBytes)
                continue
            req_msg = rsprotocol.Message.fromRSPByteData(readBytes)
            resp = self.handleMessage(req_msg)
            # in case resp is to detach
            if resp is None:
                return True
            for r_msg in resp:
                logging.debug("response: %s" % r_msg.getRSPByteData())
                self.conn.write(r_msg.getRSPByteData())
        return True
コード例 #18
0
    def computerRoll(self, diceQueue, myBoard):
        Interface.printMsg("The Computer is rolling...")
        time.sleep(1)
        if diceQueue:
            diceResults = diceQueue[0][0] + diceQueue[0][1]
            diceQueue.pop(0)
        else:
            if self.willRollSingleDie(myBoard):
                diceResults = self.rollSingleDie()
            else:
                diceResults = self.rollDice()

        message = "The Computer rolled " + repr(diceResults)
        Interface.printMsg(message)
        return diceResults
コード例 #19
0
ファイル: human.py プロジェクト: nightCapLounge/Canoga-Python
    def humanRoll(self, diceQueue, myBoard):
        Interface.printMsg("You are rolling...")
        time.sleep(1)
        if diceQueue:
            diceResults = diceQueue[0][0] + diceQueue[0][1]
            diceQueue.pop(0)
        else:
            if self.canRollSingleDie(myBoard) and Interface.validateBoolean(
                            "Would you like to roll one die? (y/n): "):
                diceResults = self.rollSingleDie()
            else:
                diceResults = self.rollDice()

        message = "You rolled " + repr(diceResults)
        Interface.printMsg(message)
        return diceResults
コード例 #20
0
ファイル: gdbserver.py プロジェクト: aglab2/darwin-xnu
 def __init__(self, backing_instance):
     super(GDBServer, self).__init__()
     self.process = backing_instance
     self.portnum = random.randint(2000, 8000)
     logging.info("Starting gdb server for localhost:%d" % self.portnum)
     self.conn = Interface('localhost', self.portnum)
     self.version_string = 'name:kdbserver;version:0.1'
コード例 #21
0
ファイル: gui.py プロジェクト: nonsns/NetProbes
    def __init__(self, ip):
        Interface.__init__(self, ip)
        self.commandHistory = []
        self.mainWin = Tk()
        self.command = StringVar(self.mainWin)
        self.status = StringVar(self.mainWin, value="Waiting for command ...")
        self.text = StringVar(self.mainWin, value="Enter a command :")
        self.result = None
        self.probesDisplay = None
        self.mainWin.title("Commander for probe with ip : " + ip)
        self.isRunning = True
        self.mainWin.protocol("WM_DELETE_WINDOW", self.quit)

        # define the threads
        self.thProbe = Thread(target=self.updateProbes, name="Probe updater", daemon=True)
        self.thResults = Thread(target=self.updateResults, name="Results Updater", daemon=True)
コード例 #22
0
ファイル: main.py プロジェクト: marcoslucca/cbr-system
def main():
    from matcher import Matcher
    from interface import Interface
    import attribute_names

    if os.path.exists(case_filename):
        with open(case_filename, "rb") as fp:
            ranges,cases = pickle.load(fp)
            for k,v in ranges.items():
                atrcls = getattr(attribute_names, k)
                atrcls._range = v
    else:
        print "Warning: No cases found (looking in '%s')." % case_filename
        cases = []
    matcher = Matcher(cases)
    interface = Interface(matcher)
    interface.cmdloop()
コード例 #23
0
def main():
    """Main function
    :returns: 0

    """
    app = Interface()
    app.draw_interface()
    app.update_interface()
    app.window_loop()
コード例 #24
0
 def applyHandicap(self, handicapSquare):
     if self.returnList[0] and self.humanIsFirstPlayer:
         Interface.printMsg("The Computer gets a handicap.")
         self.board.computerBoard[handicapSquare-1] = "*"
     if self.returnList[0] and not self.humanIsFirstPlayer:
         Interface.printMsg("You get a handicap.")
         self.board.humanBoard[handicapSquare-1] = "*"
     if not self.returnList[0] and not self.humanIsFirstPlayer:
         Interface.printMsg("You get a handicap.")
         self.board.humanBoard[handicapSquare-1] = "*"
     if not self.returnList[0] and self.humanIsFirstPlayer:
         Interface.printMsg("The Computer gets a handicap.")
         self.board.computerBoard[handicapSquare-1] = "*"
コード例 #25
0
ファイル: router.py プロジェクト: kroczi/TIR_energy_flow
 def __init__(self, hostname=None, demand=None):
     if hostname is not None:
         self._hostname = hostname
         self._demand = demand
         self._lsdb = ospf.Database()
         self._links = {}
         self._neighbors = {}
         self._seen = {}
         self._energy_flow = {}
         self._init_timers()
         self._interface = Interface(self)
コード例 #26
0
ファイル: human.py プロジェクト: nightCapLounge/Canoga-Python
    def playTurn(self, board, diceQueue, turnCount, returnList):
        board.displayBoard()
        diceResults = self.humanRoll(diceQueue, board.humanBoard)
        coverMenu = self.generateCoverMenu(board.humanBoard, diceResults)
        uncoverMenu = self.generateUncoverMenu(board.computerBoard, diceResults)

        if returnList[2] != 0:
            self.removeHandicap(returnList, uncoverMenu)

        if not self.canMove(coverMenu, uncoverMenu):
            Interface.printMsg("There are no more moves.")
            return False

        self.displayMenu(coverMenu, uncoverMenu)
        choice = Interface.validateRange("Please choose an option: ", 1, 
                                        (len(coverMenu)+len(uncoverMenu)+1))
        choice -= 1

        while(choice == (len(coverMenu)+len(uncoverMenu))):
            self.logicString =  ""
            self.getHelp(board.humanBoard, board.computerBoard, 
                                coverMenu, uncoverMenu, turnCount)
            self.displayMenu(coverMenu, uncoverMenu)
            choice = Interface.validateRange("Please choose an option: ", 1, 
                                        (len(coverMenu)+len(uncoverMenu)+1))
            choice -= 1


        if choice < len(coverMenu):
            willCover = True
        else:
            willCover = False

        self.executeChoice(board.humanBoard, board.computerBoard, 
                                        coverMenu, uncoverMenu, choice, willCover)


        if self.checkForWin(board.humanBoard, board.computerBoard, turnCount):
            return True
        else:
            return self.playTurn(board, diceQueue, turnCount, returnList)
コード例 #27
0
def main(args):
    if len(args) == 3:
        if args[1].startswith("--user="******"--pw="):
            username = args[1].split("=")[1]
            password = args[2].split("=")[1]
            backend = Databaser(u=username, pw=password)
        elif args[1].startswith("--pw=") and args[2].startswith("--user="******"=")[1]
            password = args[1].split("=")[1]
            backend = Databaser(u=username, pw=password)
        else:
            err = "The arguments you passed are not valid!"
            raise TypeError, err
    elif len(args) == 2 or len(args) > 3:
        err = "You passed timeclash.py %s argument(s), but it requires 0 or 2."
        raise TypeError, err % (len(args) - 1)
    else:
        backend = Databaser()
    methods = backend.render_functions()
    frontend = Interface(methods)
    frontend.run()
コード例 #28
0
    def playTurn(self, board, diceQueue, turnCount, returnList):
        board.displayBoard()
        diceResults = self.computerRoll(diceQueue, board.computerBoard)
        coverMenu = self.generateCoverMenu(board.computerBoard, diceResults)    
        uncoverMenu = self.generateUncoverMenu(board.humanBoard, diceResults)

        if returnList[2] != 0:
            self.removeHandicap(returnList, uncoverMenu)

        # Returns false if human is next
        if not self.canMove(coverMenu, uncoverMenu):
            Interface.printMsg("There are no more moves.")
            return False

        willCover = self.willCover(board.computerBoard, board.humanBoard, coverMenu, 
                                    uncoverMenu, turnCount)
        choice = self.chooseBestOption(board.computerBoard, board.humanBoard, 
                                            coverMenu, uncoverMenu, willCover)
        self.executeChoice(board.computerBoard, board.humanBoard, 
                                            coverMenu, uncoverMenu, choice, willCover)
        mergedMenu = coverMenu + uncoverMenu

        self.logicString = (self.getChoiceString(mergedMenu[choice]) + 
                                        self.logicString)

        prefix = "The Computer chose to "

        if willCover:
            prefix += "cover "
        else:
            prefix += "uncover "

        self.printLogic(prefix)
        self.logicString = ""

        # Returns true if the computer has won the round
        if self.checkForWin(board.computerBoard, board.humanBoard, turnCount):
            return True
        else:
            return self.playTurn(board, diceQueue, turnCount, returnList)
コード例 #29
0
ファイル: connectionmanager.py プロジェクト: mireq/pyboincgui
	def __init__(self, local, path, host, port, password, queue):
		QObject.__init__(self)
		self.__local = local
		self.__path = path
		self.__host = host
		self.__port = port
		self.__password = password
		self.__connected = 0
		self.__bInterface = Interface(host, port, password, queue)
		self.__updateTimer = None
		self.__projectState = None
		self.connect(self, SIGNAL('connectStateChanged(int)'), self.__updateConnectState)
		self.connect(self, SIGNAL('projectState(PyQt_PyObject)'), self.__startTimer)
コード例 #30
0
    def saveSequence(self):
        willSave = Interface.validateBoolean("Would you like to save and quit? (y/n): ")

        if not willSave:
            return

        saveFile = open("savedData.txt", 'w')

        Interface.printMsg("Saving data...")
        time.sleep(1)

        saveFile.write("Computer:\n")
        saveFile.write("\tSquares: " + self.getBoardString(self.board.computerBoard) + "\n")
        saveFile.write("\tScore: " + repr(self.computer.score) + "\n")
        saveFile.write("\n")
        saveFile.write("Human:\n")
        saveFile.write("\tSquares: " + self.getBoardString(self.board.humanBoard) + "\n")
        saveFile.write("\tScore: " + repr(self.human.score) + "\n")
        saveFile.write("\n")     
        firstString = "First Turn: "
        if self.humanIsFirstPlayer:
            firstString += "Human\n"
        else:
            firstString += "Computer\n"

        nextString = "Next Turn: "
        if self.humanIsNext:
            nextString += "Human\n"
        else:
            nextString += "Computer\n"

        saveFile.write(firstString)
        saveFile.write(nextString)
        saveFile.write("\n")
        saveFile.write("Dice: ")

        Interface.printMsg("Game saved.")

        self.terminate()
コード例 #31
0
 def __init__(self):
     Interface.__init__(self, "USR")
     Configurable.__init__(self)
     LOG("Created")
コード例 #32
0
class Options(object):
    """ The main wrapper for controlling a Multistrand simulation. Has an interface for returning results. """
       
    '''Constants:'''
    # FD: some could be enums, using constants instead.
    
    ZERO_C_IN_K = 273.15
        

    RateMethodToString = [ "None", "Metropolis", "Kawasaki"]

    dangleToString = [ "None", "Some", "All"]

    # Parameter type. Vienna is depreciated.
    viennaModel = 0 
    nupackModel = 1 
    parameterTypeToString = [ "Vienna", "Nupack" ]


    substrateToString = [ "Invalid", "RNA", "DNA"]    
    
    # translation
    simulationMode = {  "Normal"    :               Literals.first_passage_time,
                        "First Step":               Literals.first_step,
                        "Transition":               Literals.transition,
                        "Trajectory":               Literals.trajectory,
                        "First Passage Time":       Literals.first_passage_time}




    
    cotranscriptional_rate_default = 0.001  # 1 nt added every 1 ms
    
    activestatespace = False;
    
    def __init__(self, *args, **kargs):
        """
        Initialization of an Options object:

        Keyword Arguments:
        dangles -- Specifies the dangle terms used in the energy model.
                   Can be the strings 'None', 'Some', or 'All'.
        start_state  [type=list]     -- A list of Complexes to 
                                        use as the initial state of the system.
        simulation_time [type=float] -- Cap on the maximum simulation time.
        num_simulations [type=int]   -- Number of trajectories to run
        biscale         [type=float] -- Bimolecular scaling constant
        uniscale        [type=float] -- Unimolecular scaling constant
        parameter_type               -- Which set of energy parameters is
                                        used. Available options: 'Nupack',
                                        'Vienna'
        substrate_type               -- Whether we want 'DNA' or 'RNA' energy
                                        parameters.
        rate_method                  -- Whether we want 'Kawasaki' or 'Metropolis'
                                        or 'Arrhenius' rate method for unimolecular steps.
                                        
        If rate_method == Literals.Arrhenius, please set lnAEnd, lnALoop, lnAStack, 
                                lnAStackStack, lnALoopEnd, lnAStackEnd, lnAStackLoop, 
                                EEnd, ELoop, EStack, EStackStack, ELoopEnd, EStackEnd, 
                                EStackLoop and bimolecular_rate(double value).
        """

        ##################################################
        #                                                #
        # Data Members                                   #
        # ->Members new to the python implementation     #
        #                                                #
        #                                                #
        ##################################################
        
        
        """ Pipe to let Multistrand know the version from ../__init__.py """
        self.ms_version = float(__version__)  
        
        self.errorlog = []
        """ Keeps lines relating to possible errors or warnings that
        should be reported to the user. Usually issues relating to the
        input file or parameters with odd values.

        TODO: implement some functions to report the errors found here.
        """
        self.full_trajectory = []
        self.full_trajectory_times = []
        self.full_trajectory_arrType = []
        self.trajectory_complexes = []
        self.trajectory_state_count = 0
        self._current_end_state = []
        self._current_transition_list = []
        self.special_count = 0
        self.trajectory_current_time = 0.0
        self.current_graph = None

        self.verbosity = 1
        """ Indicates how much output will be generated for each trajectory run.
        Value = 0:  No end state reported, no warnings for timeout and nonitial steps
        Value = 1:  No end states reports, warnings active   
        Value = 2:  warnings and end states reports to stdout
        """
        
        self.print_initial_first_step = False
        """
        If True, this value will print the initial state in First Step Mode to the trajectory with a timestamp of -1.0
        """

        self.cotranscriptional = False
        """
        If True, enables the cotranscriptional simulation mode. The mode works only when a single strand is supplied.
        Starting with the initial 8 nucleotides, the simulation adds a nucleotide on the 3' end every 1 millisecond. 
        """
        
        self.cotranscriptional_rate = self.cotranscriptional_rate_default
        """
        By default, the cotranscriptional mode adds one nucleotide every 1 millisecond.
        """
        
        #############################################
        #                                           #
        # Data Members: Energy Model                #
        #                                           #
        #############################################
        # See accessors below
        self._start_state = []
        
        self.gt_enable = True
        """ Allow GT base pairs? If not, penalize by 10000 kcal/mol.
            False (0) : Do not allow GT base pairs.
        """

        self.log_ml = False
        """ Use logarithm to compute multiloop energy contributions?
        int          False (0): Do not use the logarithm.

        If True, uses log to compute one component of the multiloop energy, for loops of length > 6. Otherwise, uses the usual
        linear approximation. Using the log formula is slightly more expensive as it makes computation time for a multiloop scale
        with the number of adjoining helices.
        """
        
        self.join_concentration = 1.0
        """ concentration for V calcs
        Units are in M (molar), and represent the concentration of a single unique strand in the system. The volume simulated is
        then chosen using this parameter.
        """

        # ##
        # ## See the temperature property way below (after __init__)
        # ## for more info on accessors for these data members.
        # ##
        self._temperature_celsius = 37.0
        self._temperature_kelvin = 310.15

        self.rate_scaling = None
        """FD: This is a legacy option that sets unimolecular and bimolecular scaling automatically if set"""

        self.unimolecular_scaling = -1.0 
        """ Rate scaling factor for unimolecular reactions."""
        
        self.bimolecular_scaling = -1.0 
        """ Rate scaling factor for bimolecular reactions."""

        self.rate_method = Literals.kawasaki
        """ Choice of methods for determining forward/reverse rates. """

        self.dangles = Literals.dangles_some
        """ Dangles options for the energy model.
        
        None [0]: Do not include any dangles terms in the energy model.
        Some [1]: Some dangles terms.  (Nupack Default)
        All  [2]: Include all dangles terms, including odd overlapping ones.
        """

        self.parameter_type = self.nupackModel
        """ Which type of energy model parameter file to use.

        Vienna [0]: No longer well tested. Recommend not using.
        Nupack [1]: Includes some multi-complex parameters, otherwise
                    nearly the same as mfold style files.
        """

        self.substrate_type = Literals.substrateDNA
        """ What substrate's parameter files to use. 

        Invalid [0]: Indicates we should not auto-search for a param file.
        RNA     [1]: RNA parameters are available for Vienna and Nupack, see also
                     the comment in parameter_file_version.
        DNA     [2]: DNA parameters are publicly available via the Nupack distribution,
                     and possibly by the Vienna group upon request.
        """
        
        self.parameter_file = None
        """ Shortcut for using a very specific parameter file. Usually shouldn't be used.
        
        Type         Default
        str          None

        Should only be set to a string if it's ok to actually search
        for that parameter file. None will pass an error back to
        Multistrand if it gets used.
        """

        ####################
        #
        # BEGIN simmode
        #
        ####################
        
        self.simulation_mode = Literals.first_passage_time
        """ The simulation mode: how we want the simulation system to
        perform the main loop.
        """
        
        self.simulation_time = 600.0
        """ Maximum time (in seconds) allowed for each trajectory.
        
        Type         Default
        double       600.0
        """
        
        self.num_simulations = 1
        """ Total number of trajectories to run. 
        """
        
        self.initial_seed = None
        """ Initial random number seed to use.
        If None when simulation starts, a random seed will be chosen
        """
        
        self.name_dict = {}
        """ Dictionary from strand name to a list of unique strand objects
        having that name.
        
        Type         Default
        dict         {}
        
        Modified when start state is added. Used as a lookup when stop states 
        are added.
        """
        
        self.lnAEnd = -0.1;
        self.lnALoop = -0.1;
        self.lnAStack = -0.1;
        self.lnAStackStack = -0.1;
        self.lnALoopEnd = -0.1;
        self.lnAStackEnd = -0.1;
        self.lnAStackLoop = -0.1;        
        self.EEnd = -0.1;
        self.ELoop = -0.1;
        self.EStack = -0.1;
        self.EStackStack = -0.1;
        self.ELoopEnd = -0.1;
        self.EStackEnd = -0.1;
        self.EStackLoop = -0.1; 
         
        """ These are undocumented adjustments to the energy model """

        self.dSA = -0.0;
        self.dHA = -0.0;

        """ 
            Buffer conditions 
            Like substrate_type, temperature, and dangles,
            these follow a listener pattern to propagate settings to dangles.
            (as opposed to copying settings at the last possible moment)
        """
        self.sodium = 1.0;
        self.magnesium = 0.0;
        
        ####################
        #
        # BEGIN startstop
        #
        ####################
        

                
        # See accessors below
        self._stop_conditions = []
        self._use_stop_conditions = False
        
        self.stop_count = 0
        """ The number of stop states. Equivalent to 'len(self.stop_conditions)'.
        
        Type         Default
        int          0
        
        Incremented automatically when a stop state is added. Should not be 
        modified externally.
        """
        
        self.output_time = -1.0
        """ The amount of time (in seconds) to wait between outputs of 
        trajectory information.
        
        Type         Default
        float        -1.0
        
        A value of -1.0 corresponds to not basing outputs on output_time
        (but perhaps outputting based on some other condition). A value of 0 
        means output as often as possible.
        """
        
        self.output_interval = -1
        """ The number of states between outputs of trajectory information.
        
        Type         Default
        int          -1
        
        A value of -1 corresponds to not basing outputs on output_interval
        (but perhaps outputting based on some other condition). A value of 1 
        means output every state, 2 means every other state, and so on.
        """
        
        self.current_interval = 0
        """ Current value of output state counter.
        
        Type         Default
        int          0
        
        When current_interval is equal to output_interval, the output state is 
        True, and otherwise the output state is False. This is modified by 
        increment_output_state, and probably shouldn't be used externally."""
        
        self.output_state = False
        """ Indicates whether output should be reported.
        
        Type         Default
        boolean      False
        
        Value should be True if self.current_interval == self.output_interval 
        and False otherwise.        
        """
        
        self.interface = Interface()
        
        ##############################
        #
        # End of __init__: call the keyword hook fn. 
        #
        ##############################

        self.__init_keyword_args(self, *args, **kargs)

    def legacyRates(self):
                    
        warningmsg = "Warning! rate_scaling is set, enabling support for legacy code. Now setting rate defaults for "
                
        if (self.temperature == 298.15) & (self.rate_method == Literals.kawasaki) :
            warningmsg += "Kawasaki 25 C"
            self.JSKawasaki25()
        elif (self.temperature == 310.15) & (self.rate_method == Literals.kawasaki) :
            warningmsg += "Kawasaki 37 C"
            self.JSKawasaki37()
        elif (self.temperature == 298.15) & (self.rate_method == Literals.metropolis) :
            warningmsg += "Metropolis 25 C"
            self.JSMetropolis25()
        elif (self.temperature == 310.15) & (self.rate_method == Literals.metropolis) :
            warningmsg += "Metropolis 37 C"
            self.JSMetropolis37()
        else:
            warningmsg += "JS-Default"
            self.JSDefault()
            
        print warningmsg 
        self.rate_scaling = None       
        
    # FD, May 5th 2017
    # Supplying rate options for Metropolis and Kawasaki methods,
    # all using the dangles = some option. Also:  one general default,
    # and one setting for Metropolis rates derived for DNA23. 
    
    def JSDefault(self): 
        """ Default rates from Joseph Schaeffer's thesis  """
        
        self.unimolecular_scaling = 1.50e+08;
        self.bimolecular_scaling = 1.38e+06;
    
    def JSMetropolis25(self): 
        """ Default rates for Metropolis at 25 degree Celcius, from Joseph Schaeffer's thesis
        
        """
        
        self.unimolecular_scaling = 4.4e8;
        self.bimolecular_scaling = 1.26e6;
    
    def JSKawasaki25(self): 
        """ Default rates for Kawasaki at 25 degree Celcius, from Joseph Schaeffer's thesis
        
        """
        
        self.unimolecular_scaling = 6.1e7;
        self.bimolecular_scaling = 1.29e6;
    
    def JSKawasaki37(self):
        """ Default rates for Kawasaki at 37 degree Celcius, from Joseph Schaeffer's thesis
        """
        
        self.unimolecular_scaling = 1.5e8;
        self.bimolecular_scaling = 1.38e6;
    
    def JSMetropolis37(self): 
        """ Default rates for Metropolis at 37 degree Celcius, from Joseph Schaeffer's thesis
        """
        
        self.unimolecular_scaling = 7.3e8;
        self.bimolecular_scaling = 1.40e6;
    
    def DNA23Metropolis(self):
        """ A default rate for Metropolis at 25 degree Celcius, from the DNA23 conference
        """

        # FD march 2018: Setting these to be the 55th walker from the dna23 inference
        # previous values:
#         self.unimolecular_scaling = 5.0e6;
#         self.bimolecular_scaling = 1.4e6;
        
        self.unimolecular_scaling = 2.41686715e+06;
        self.bimolecular_scaling = 8.01171383e+05 ;
     
    def uniformRates(self):
        """ uniform rates without a source
        """
            
        self.unimolecular_scaling = 1.0e6;
        self.bimolecular_scaling = 1.0e6;

# FD: We are implementing an observer pattern. 
# FD: After temperature, substrate (RNA/DNA) or danlges is updated, we attempt to update boltzmann samples.
    def updateBoltzmannSamples(self):

        if len(self._start_state) > 0:
                        
            for c, s in self._start_state:
                c.set_boltzmann_parameters(self.dangleToString[self.dangles], self.substrateToString[self.substrate_type], self._temperature_celsius, self.sodium, self.magnesium)
    
                if c.boltzmann_sample and not self.gt_enable:
                    raise Warning("Attempting to use Boltzmann sampling but GT pairing is disabled. Energy model of Multistrand will not match that of the NUPACK sampling method.")

    
#     FD: We are using shadow variables for biscale, uniscale only because we want to 
#     flag a warning when rate_scaling is used
    @property
    def bimolecular_scaling(self):

        if self.rate_scaling != None :
            self.legacyRates()
         
        return self._bimolecular_scaling
 
    @bimolecular_scaling.setter
    def bimolecular_scaling(self, val):
                  
        self._bimolecular_scaling = float(val)
 
    @property
    def unimolecular_scaling(self):
         
        if self.rate_scaling != None :
            self.legacyRates()
         
        return self._unimolecular_scaling  
    
    @unimolecular_scaling.setter
    def unimolecular_scaling(self, val):
                  
        self._unimolecular_scaling = float(val)
        
# FD: Shadow variables for danlges only because we need to observe changes (and update boltzmann samples accordingly)
    @property
    def dangles(self):
        return self._dangles
    
    @dangles.setter
    def dangles(self, val):
        self._dangles = int(val)
        self.updateBoltzmannSamples()
        
# FD: shadow parameter so that boltzmann samples can be updated when this parameter is set
# FD: In a better control flow, complexes themselves might fetch the right constants just before evaluating their boltzmann samples 
    @property
    def substrate_type(self):
        return self._substrate_type

    @substrate_type.setter
    def substrate_type(self, value):
        self._substrate_type = int(value)
        self.updateBoltzmannSamples()

    """ FD: Following same listener pattern for sodium, magnesium, 
            so that changes are propagated to complexes."""
    @property
    def sodium(self):
        return self._sodium
    
    @sodium.setter
    def sodium(self, value):
        self._sodium = float(value)
        self.updateBoltzmannSamples()
    
    @property
    def magnesium(self):
        return self._magnesium
    
    @magnesium.setter
    def magnesium(self, value):
        self._magnesium = float(value)
        self.updateBoltzmannSamples()
        
        
    """ FD: Setting boltzmann sample in options could be used to propagate this setting to all starting states. 
            But we do not support this, and sampling is a property of each individual complex instead. """
    @property
    def boltzmann_sample(self):
        
        raise ValueError('Options.boltzmann_sample is now depreciated. Use Complex.boltzmann_sample instead.')
        
    @boltzmann_sample.setter
    def boltzmann_sample(self, val):
        
        raise ValueError('Options.boltzmann_sample is now depreciated. Use Complex.boltzmann_sample instead.')
        
            
    @property
    def start_state(self):
        """ Get the start state, i.e. a list of Complex objects.
        
        Type         Default
        list         []
        
        This should be used by ssystem.cc to get the (potentially sampled) 
        start state.
        """

        #        import pdb
        #        pdb.set_trace()
        def process_state(x):
            cmplx, rest_state = x
            if rest_state is None:
                return cmplx
            else:
                return rest_state.get_starting_complex()
            
        return [process_state(s) for s in self._start_state]
    
    @start_state.setter
    def start_state(self, *args):
        """ Set the start state, i.e. a list of Complex objects.
        
        Type         Default
        list         []
        
        The start state should be set (e.g. by the parser) so trajectories know 
        how to start.
        """
        # Error checking first
        if self._start_state != []:
            raise Exception("Start state should only be set once.")
        if len(args) == 0 or len(args[0]) == 0:
            raise ValueError("No start state given.")
        
        # deduce our input from the type of args[0].
        # Copy the input list because it's easy to do and it's safer
        
        if isinstance(args[0], Complex):
            # args is a list of complexes or resting states.
            vals = copy.deepcopy(args) 
        elif len(args) == 1 and hasattr(args[0], "__iter__"):
            vals = copy.deepcopy(args[0])
        else:
            raise ValueError("Could not comprehend the start state you gave me.")

        # vals is now an iterable over our starting configuration, be
        # it complexes or resting states.
        
        for i in vals:
            if not isinstance(i, Complex) :
                raise ValueError("Start states must be complexes. Received something of type {0}.".format(type(i)))
        
            self._add_start_complex(i)

    def _add_start_complex(self, item):
        if isinstance(item, Complex):
            self._start_state.append((item, None))
            item.set_boltzmann_parameters(self.dangleToString[self.dangles], self.substrateToString[self.substrate_type], self._temperature_celsius, self._sodium, self._magnesium)
            
            if not self.gt_enable and item.boltzmann_sample:
                raise Warning("Attempting to use Boltzmann sampling but GT pairing is disabled. Energy model of Multistrand will not match that of the NUPACK sampling method.")
            
        else:
            raise ValueError('Expected a Complex as starting state.')

    @property
    def initial_seed_flag(self):
        return self.initial_seed != None
    
    @property
    def stop_conditions(self):
        """ The stop states, i.e. a list of StopCondition objects.
        
        Type         Default
        list         []
        
        Stop states should be added to this list (e.g. by the parser) so
        trajectories know when to end.
        """
        return self._stop_conditions
    
    @stop_conditions.setter
    def stop_conditions(self, stop_list):
        """ The stop states, i.e. a list of StopCondition objects.
        
        Type         Default
        list         []
        
        Stop states should be added to this list (e.g. by the parser) so
        trajectories know when to end.
        """
        # Error checking
        if self._stop_conditions != []:
            raise Exception("Stop conditions should be set only once.")

        # Type checking
        for item in stop_list:
            if not isinstance(item, StopCondition):
                raise TypeError("All items must be 'StopCondition', not '{0}'.".format(type(item)))
        
        # Copy the input list because it's easy to do and it's safer
        stop_list = copy.deepcopy(stop_list)
        
        # Set the internal data members
        self.stop_count = len(stop_list)
        self._stop_conditions = stop_list
        self._use_stop_conditions = True

    @property
    def use_stop_conditions(self):
        """ Indicates whether trajectories should end when stop states
        are reached.
        
        Type            Default
        boolean         False: End trajectory upon reaching max time only.
        
        Defaults to ending trajectories only on the max simulation
        time, but setting any stop conditions automatically changes
        this to True, and it will stop whenever it reaches a stop
        condition, or at max time [whichever comes first].
        """
        return self._use_stop_conditions

    @use_stop_conditions.setter
    def use_stop_conditions(self, val):
        
        if val == True and len(self._stop_conditions) == 0:
             raise Warning("Options.use_stop_conditions was set to True, but no stop conditions have been defined!")

        self._use_stop_conditions = val
    
    @property
    def increment_output_state(self):
        """ Modifies self.current_interval and self.output_state as 
        necessary based on self.output_interval.
        """
        if self.output_interval == None or self.output_interval < 0:
            raise ValueError("output_interval has invalid value: %s" % self.output_interval)
        
        elif self.current_interval > self.output_interval:
            raise ValueError("current_interval has invalid value: %s" % self.current_interval)
        
        elif self.current_interval == self.output_interval:
            self.current_interval == 0
        
        else:
            self.current_interval += 1
        
        self.output_state = (self.current_interval == self.output_interval)

        return None

    @property
    def temperature(self):
        """
        Temperature, in degrees Kelvin.
        
        Arguments:
        temperature [type=float,default=310.15] -- Standard units of Kelvin.
               Default value corresponds to 37(C).
        
        This is used mostly in scaling energy model terms, and those
        scaling factors always use Kelvin. Note that when set, the
        Options object will try to make sure it's actually a 'sane'
        value, as follows:
        
        Temperatures in the range [0,100] are assumed to be Celsius,
        and are converted to Kelvin.
        
        Temperatures in the range [273,373] are assumed to be in
        Kelvin.
        
        Any temperature outside these ranges is set as the temperature
        in Kelvin, and a warning is raised. If any conversion takes
        place, a message is added to the Options object's errorlog.
        """
        return self._temperature_kelvin

    @temperature.setter
    def temperature(self, val):
        """ performs some sanity checking and provides a log error if
        perhaps the user was confused.

        Assumptions: Input should be in Kelvin, if it's not in a
        'reasonable' range for Kelvin, convert to Celsius if it's in a
        reasonable range for C [sending an output to the error log
        warning that it did so], otherwise error.

        Reasonable ranges:
            [0,100]  : Celsius
            [273,373]: Kelvin
            Others:    If you want a Fahrenheit reasonable range, I think you
                       might be unreasonable. Also, it overlaps with Celsius a bit much.

        Yes, these ranges are quite generous.
        """
        if 273.0 < val < 373.0:
            self._temperature_kelvin = val
            self._temperature_celsius = val - self.ZERO_C_IN_K
            self.updateBoltzmannSamples()

        elif 0.0 < val < 100.0:
            self._temperature_celsius = val
            self._temperature_kelvin = val + self.ZERO_C_IN_K
            self.updateBoltzmannSamples()
            self.errorlog.append("Warning: Temperature was set at the value [{0}]. We expected a value in Kelvin, or with appropriate units.\n         Temperature was automatically converted to [{1}] degrees Kelvin.\n".format(val, self._temperature_kelvin))

        else:
            self._temperature_kelvin = val
            self._temperature_celsius = val - self.ZERO_C_IN_K
            self.updateBoltzmannSamples()
            self.errorlog.append("Warning: Temperature was set at the value [{0}]. This is outside the normal range of temperatures we expect, so it was assumed to be in Kelvin.\n".format(val))
            raise Warning("Temperature did not fall in the usual expected ranges. Temperatures should be in units Kelvin, though the range [0,100] is assumed to mean units of Celsius.")
    
    def make_unique(self, strand):
        """Returns a new Strand object with a unique identifier replacing the 
        old id. Also adds the new strand to self.name_dict[strand.name].
        """
        new_strand = Strand(self.unique_id, strand.name, strand.sequence, strand.domain_list)
        self.unique_id += 1
        
        try:
            self.name_dict[strand.name].append(new_strand)
        except KeyError:
            self.name_dict[strand.name] = [new_strand]

        return new_strand

    @property
    def add_result_status_line(self):
        return None

    @add_result_status_line.setter
    def add_result_status_line(self, val):
        """ Takes a 4-tuple as the only value type, it should be:
            (random number seed, stop result flag, completion time, stop result tag)

            Prints thingies. Also sets useful values."""
        if not isinstance(val, tuple) or len(val) != 4:
            raise ValueError("Print status line needs a 4-tuple of values.")
        self.interface.add_result(val, res_type='status_line')
        if len(self._current_end_state) > 0:
            self.interface.end_states.append(self._current_end_state)
            self._current_end_state = []
    
    @property
    def add_result_status_line_firststep(self, val):
        return None

    @add_result_status_line_firststep.setter
    def add_result_status_line_firststep(self, val):
        """ Takes a 5-tuple as the only value type, it should be:
            (random number seed, stop result flag, completion time, collision rate, stop result tag)

            Prints thingies. Also sets useful values."""
        if not isinstance(val, tuple) or len(val) != 5:
            raise ValueError("Print status line needs a 5-tuple of values.")
        self.interface.add_result(val, res_type='firststep')
        if len(self._current_end_state) > 0:
            self.interface.end_states.append(self._current_end_state)
            self._current_end_state = []
            
    @property
    def add_complex_state_line(self):
        return None

    @add_complex_state_line.setter
    def add_complex_state_line(self, val):
        """ Takes a 6-tuple as only value, it should be:
            (random number seed, unique complex id, strand names, sequence, structure, energy )
            Adds this data to the interface's results object."""

        self._current_end_state.append(val)
        if self.verbosity > 1:
            print("{0[0]}: [{0[1]}] '{0[2]}': {0[5]} \n{0[3]}\n{0[4]}\n".format(val))

    @property
    def add_transition_info(self):
        return None

    @add_transition_info.setter
    def add_transition_info(self, val):
        """ Takes a 2-tuple, 1st value is current time, 2nd value is a
            list of boolean values indicating which stop conditions we
            currently meet."""
        # print( "Time: {0[0]} Membership: {0[1]}".format( val ))
        self._current_transition_list.append(val)

    @property
    def add_trajectory_complex(self):
        return None

    @add_trajectory_complex.setter
    def add_trajectory_complex(self, val):
        """ Takes a 6-tuple as only value, it should be:
            (random number seed, unique complex id, strand names, sequence, structure, energy )
            Adds this data to the interface's results object."""

        self.trajectory_complexes.append(val)
        # print "Number of complexes in current traj output:" + str(len(self.trajectory_complexes))

    @property
    def add_trajectory_current_time(self):
        return None

    @add_trajectory_current_time.setter
    def add_trajectory_current_time(self, val):
        self.trajectory_current_time = val
        self.trajectory_state_count += 1
        self.full_trajectory.append(self.trajectory_complexes)
        self.full_trajectory_times.append(self.trajectory_current_time)
        self.trajectory_complexes = []
        
    @property
    def add_trajectory_arrType(self):
        return None

    @add_trajectory_arrType.setter
    def add_trajectory_arrType(self, val):
        self.full_trajectory_arrType.append(val)
        
    @property
    def interface_current_seed(self):
        """ This is the current random number seed for the trajectory currently being
        simulated by multistrand.

        This property and its setter exist mainly for use by the
        multistrand module to provide some feedback on what seed it's
        working on, in case that trajectory crashes before completion,
        and other similar cases."""
        return self.interface.current_seed

    @interface_current_seed.setter
    def interface_current_seed(self, val):
        
        self.interface.current_seed = val
        
        def get_structure(s):
            if s.boltzmann_sample:
                return s._last_boltzmann_structure
            else:
                return s._fixed_structure
        
        def process_state(x):
            cmplx, rest_state = x
            if rest_state is None:
                return get_structure(cmplx)
            else:
                return get_structure(rest_state.get_starting_complex())
        
        structures = [process_state(s) for s in self._start_state]
        
        self.interface.start_structures[val] = structures

    @property
    def increment_trajectory_count(self):
        self.interface.increment_trajectory_count()
        if len(self._current_transition_list) > 0:
            self.interface.transition_lists.append(self._current_transition_list)
            self._current_transition_list = []

    def __init_keyword_args(self, *args, **kargs):
        """ Helper subfunction. """
        
        """ Create an options object [with default (presumably useful) values]

        Now with new and improved argument lists!

        Any default Options attribute can be set just by passing a
        keyword argument with the desired value, e.g.
        Options(simulation_time=100.0)

        Listed below are some shortcuts, for attributes that have a
        range of options, or shortened names for long attributes.
        

        Keyword Argument  |  Options
        dangles           |  'None', 'Some', 'All'
        parameter_type    |  'Nupack', 'Vienna'
        substrate_type    |  'DNA','RNA'
        
        sim_time          | [simulation_time] Max time to simulate
        num_sims          | [num_simulations] Number of trajectories to run
        biscale           | [bimolecular_scaling] Bimolecular scaling constant
        uniscale          | [unimolecular_scaling] Unimolecular scaling constant

        start_state       |  List of Complexes

        ...
        More to come!"""
        arg_lookup_table = {
            'biscale': lambda x: self.__setattr__('bimolecular_scaling', x),
            'uniscale': lambda x: self.__setattr__('unimolecular_scaling', x),
            'num_sims': lambda x: self.__setattr__('num_simulations', x),
            'sim_time': lambda x: self.__setattr__('simulation_time', x),
            'concentration': lambda x: self.__setattr__('join_concentration', x)
            }
        
        # FD: Start throwing errors if not in the right format
        # FD: This does not prevent the user to set them to ints after options 
        # FD: initialization (could use overloading via @property to prevent this).
        for key, value in kargs.items():
            
            if key == "simulation_time":
                if not isinstance(value, (float)):
                    raise Warning("Please provide simulation_time as float")
                
            if key == "bimolecular_scaling":
                if not isinstance(value, (float)):
                    raise Warning("Please provide bimolecular_scaling as float")
                
            if key == "unimolecular_scaling":
                if not isinstance(value, (float)):
                    raise Warning("Please provide unimolecular_scaling as float")
                
        
        for k in kargs.keys():
            
            if k in arg_lookup_table:
                arg_lookup_table[k](kargs[k])          
                
            # FD: Do some additional parsing for legacy support            
            # FD: This code simply translates the string calls to the numerical constants 
            elif k == 'rate_method':
                if isinstance(kargs[k], basestring):
                    self.rate_method = self.RateMethodToString.index(kargs[k])
                    
            elif k == 'dangles':
                if isinstance(kargs[k], basestring):
                    self.dangles = self.dangleToString.index(kargs[k])

            elif k == 'parameter_type':
                if isinstance(kargs[k], basestring):
                    self.parameter_type = self.parameterTypeToString.index(kargs[k])

            elif k == 'substrate_type':
                if isinstance(kargs[k], basestring):
                    self.substrate_type = self.substrateToString.index(kargs[k])
                    
            elif (k == 'simulation_mode') & (isinstance(kargs[k], basestring)):
                    self.simulation_mode = self.simulationMode[kargs[k]]

            else:
                self.__setattr__(k, kargs[k])
コード例 #33
0
from interface import Interface

Interface.setup((3000, 1600), 'GUI Editor')

from menu import Menu
#from testfile import Testfile

menu = Menu()

from editor import Editor

Interface.add_resizable_objs([Editor])

#tf = Testfile((100,100))

while Interface.running:
    pressed, events = Interface.run()
    #
    #tf.display()
    #
    menu.run(events, pressed)
    if menu.state == 'end':
        Interface.running = False
コード例 #34
0
from server import Server
from client import Client
from interface import Interface
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="%(filename)s, line:%(lineno)d # [%(asctime)s] %(message)s")
logging.info("start session")

Interface(handle_server=Server, handle_client=Client)
コード例 #35
0
width = 1080
height = 720

def toggle_turning(window):
	for shape in window.shapes:
		if not isinstance(shape, Curve):
			shape.turning = not shape.turning

l = Window(width, height)
cube1 = Cube(0, 0, 0, 200, (1, 0, 0), True)
l.add_shape(cube1)
cube2 = Cube(0, -150, 0, 100, (0, 1, 0), True)
l.add_shape(cube2)
star = Star(350, 0, 0, 100, (1, 0, 1), True)
l.add_shape(star)
interface = Interface(50, 25, 100, 50, (0, 1, 1), toggle_turning)
l.add_interface(interface)
curve1 = Curve((100, 100), (100, 200), (200, 200), (0.5, 0, 0.5))
curve2 = Curve((100, 100), (100, 200), (0, 200), (0.5, 0, 0.5))
curve3 = Curve((100, 300), (100, 200), (0, 200), (0.5, 0, 0.5))
curve4 = Curve((100, 300), (100, 200), (200, 200), (0.5, 0, 0.5))
l.add_shape(curve1)
l.add_shape(curve2)
l.add_shape(curve3)
l.add_shape(curve4)
l.draw()

#data for testing the matrix multiplier function.
#matrix_one = [[4, 0, 3], [1, -1, 7], [-3, 3, 2]]
#matrix_two = [[-2, 3, 1], [2, -3, -5], [4, 0, 7]]
#print(mult_matrix_matrix(matrix_one, matrix_two))
コード例 #36
0
 def setUp(self):
     self.interface = Interface()
コード例 #37
0
ファイル: main.py プロジェクト: sialorama/Briefs
def main():
    window = tk.Tk()
    Interface(window)
    window.mainloop()
コード例 #38
0
def main():
    """Main function."""
    game = Interface()
    game.mainloop()
コード例 #39
0
ファイル: __main__.py プロジェクト: AlexRedfield/MySpider
from parse import Parse
from webcrawler import WebCrawler
from interface import Interface

if __name__ == "__main__":
    interface = Interface()
    parse = Parse()
    args = parse.get_parse()
    parse.do_parse(args)
    webcrawler = WebCrawler(parse)
    webcrawler.get_headers(interface.header_inter())
    webcrawler.get_data(interface.data_inter())
    webcrawler.get_url(interface.url_inter())
    webcrawler.do_crawl()
コード例 #40
0
ファイル: update.py プロジェクト: Plouc314/GameClient
from interface import Interface, TextBox, Button, InputText, Cadre, C, Font, Dimension, set_screen
import pygame
import requests

pygame.init()

E = lambda x: int(x * Dimension.f)
dim = Dimension((E(3000), E(1600)))

inter = Interface()

DIM_SCREEN = (E(800), E(400))
screen = pygame.display.set_mode(DIM_SCREEN)
screen.fill(C.WHITE)
pygame.display.set_caption('Update')

set_screen(screen)

DIM_TC = (E(400), E(60))

text_conn = TextBox(DIM_TC,
                    C.WHITE, (E(200), E(100)),
                    'Connecting...',
                    font=Font.f30)

text_fail_conn = TextBox(DIM_TC,
                         C.WHITE, (E(200), E(100)),
                         'Connection failed',
                         font=Font.f30)

text_search = TextBox(DIM_TC,
コード例 #41
0
ファイル: train.py プロジェクト: xiaoli777/sedna
def main():
    tf.set_random_seed(22)

    class_names = sedna.context.get_parameters("class_names")

    # load dataset.
    train_data = sedna.load_train_dataset(data_format='txt')

    # read parameters from deployment config.
    obj_threshold = sedna.context.get_parameters("obj_threshold")
    nms_threshold = sedna.context.get_parameters("nms_threshold")
    input_shape = sedna.context.get_parameters("input_shape")
    epochs = sedna.context.get_parameters('epochs')
    batch_size = sedna.context.get_parameters('batch_size')

    tf.flags.DEFINE_string('train_url', default=MODEL_URL,
                           help='train url for model')
    tf.flags.DEFINE_string('log_url', default=None, help='log url for model')
    tf.flags.DEFINE_string('checkpoint_url', default=None,
                           help='checkpoint url for model')
    tf.flags.DEFINE_string('model_name', default=None,
                           help='url for train annotation files')
    tf.flags.DEFINE_list('class_names', default=class_names.split(','),
                         # 'helmet,helmet-on,person,helmet-off'
                         help='label names for the training datasets')
    tf.flags.DEFINE_list('input_shape',
                         default=[int(x) for x in input_shape.split(',')],
                         help='input_shape')  # [352, 640]
    tf.flags.DEFINE_integer('max_epochs', default=epochs,
                            help='training number of epochs')
    tf.flags.DEFINE_integer('batch_size', default=batch_size,
                            help='training batch size')
    tf.flags.DEFINE_boolean('load_imagenet_weights', default=False,
                            help='if load imagenet weights or not')
    tf.flags.DEFINE_string('inference_device',
                           default='GPU',
                           help='which type of device is used to do inference,'
                                ' only CPU, GPU or 310D')
    tf.flags.DEFINE_boolean('copy_to_local', default=True,
                            help='if load imagenet weights or not')
    tf.flags.DEFINE_integer('num_gpus', default=1, help='use number of gpus')
    tf.flags.DEFINE_boolean('finetuning', default=False,
                            help='use number of gpus')
    tf.flags.DEFINE_boolean('label_changed', default=False,
                            help='whether number of labels is changed or not')
    tf.flags.DEFINE_string('learning_rate', default='0.001',
                           help='label names for the training datasets')
    tf.flags.DEFINE_string('obj_threshold', default=obj_threshold,
                           help='label names for the training datasets')
    tf.flags.DEFINE_string('nms_threshold', default=nms_threshold,
                           help='label names for the training datasets')
    tf.flags.DEFINE_string('net_type', default='resnet18',
                           help='resnet18 or resnet18_nas')
    tf.flags.DEFINE_string('nas_sequence', default='64_1-2111-2-1112',
                           help='resnet18 or resnet18_nas')
    tf.flags.DEFINE_string('deploy_model_format', default=None,
                           help='the format for the converted model')
    tf.flags.DEFINE_string('result_url', default=None,
                           help='result url for training')

    model = Interface()

    sedna.incremental_learning.train(model=model,
                                     train_data=train_data,
                                     epochs=epochs,
                                     batch_size=batch_size,
                                     class_names=class_names,
                                     input_shape=input_shape,
                                     obj_threshold=obj_threshold,
                                     nms_threshold=nms_threshold)
コード例 #42
0
class Router(object):
    def __init__(self, hostname=None, demand=None):
        if hostname is not None:
            self._hostname = hostname
            self._demand = demand
            self._lsdb = ospf.Database()
            self._links = {}
            self._neighbors = {}
            self._seen = {}
            self._energy_flow = {}
            self._init_timers()
            self._interface = Interface(self)

    def __del__(self):
        self.stop()

    def init_router(self, name, demand=0):
        if not name.endswith(".cfg"):
            self.__init__(name, demand)
            return

        cfg = ConfigParser.SafeConfigParser()
        try:
            cfg.read(str(name))
        except ConfigParser.MissingSectionHeaderError:
            print('MissingSectionHeaderError')
            sys.exit(-1)

        hostname = cfg.get('Router', 'hostname')
        demand = int(cfg.get('Router', 'demand'))
        self.__init__(hostname, demand)

        links = [i for i in cfg.sections() if i.startswith('Link')]
        for link in links:
            link_id = cfg.get(link, 'link')
            cost = int(cfg.get(link, 'cost'))
            capacity = int(cfg.get(link, 'capacity'))
            self.add_link(link_id, cost, capacity)

    def _init_timers(self):
        log('Init timers.')
        self._dead_timer = None
        self._timers = {
            'lsdb': Timer(ospf.AGE_INTERVAL, self._update_lsdb),
            'refresh_lsa': Timer(ospf.LS_REFRESH_TIME, self._refresh_lsa),
            'hello': Timer(ospf.HELLO_INTERVAL, self._hello)
        }

    def _update_lsdb(self):
        log('LSDB update.')
        flushed = self._lsdb.update()
        if flushed:
            log('LSA(s) of %s reached MaxAge and was/were flushed from the LSDB'
                % (', '.join(flushed), ))

    def _refresh_lsa(self):
        if self._hostname in self._lsdb:
            log('Refreshing own LSA')
            self._advertise()

    def _hello(self):
        """Establish adjacency"""
        log('Sending HelloPacket.')
        for link, attr in self._links.iteritems():
            packet = ospf.HelloPacket(self._hostname, (link, attr[0], attr[1]))
            self.transmit(packet, link)
        for neighbor_id in self._seen:
            if neighbor_id not in self._neighbors:
                self._sync_lsdb(neighbor_id)

    def _update_energy_flow(self):
        log('Recalculating flow.')
        flow_cost, flow_dict = FlowManager.calculate_flow(self._lsdb)
        self._energy_flow = flow_dict
        log(flow_dict[self._hostname])

    def get_energy_flow(self):
        return self._energy_flow

    def get_lsdb(self):
        return self._lsdb

    def _break_adjacency(self, neighbor_id):
        log('Break adjacency.')
        # Save reference QObject errors
        self._dead_timer = self._timers[neighbor_id]
        del self._timers[neighbor_id]
        del self._neighbors[neighbor_id]
        del self._seen[neighbor_id]
        log(' '.join([neighbor_id, 'is down']))
        self._advertise()

    def _flood(self, packet, source_link=None):
        """Flood received packet to other interfaces"""
        if packet.adv_router == self._hostname:
            log('Flooding own LSA')
        else:
            log('Flooding LSA of %s' % (packet.adv_router, ))

        for data in self._neighbors.values():
            if data[0] != source_link:
                self.transmit(packet, data[0])

    def _advertise(self):
        log('Advertise.')
        networks = {}
        for neighbor_id, data in self._neighbors.iteritems():
            link, cost, capacity = data
            cost = max(cost, self._links[link][0])
            capacity = min(capacity, self._links[link][1])
            networks[link] = (neighbor_id, link, cost, capacity)
        # Create new or update existing LSA
        if self._hostname in self._lsdb:
            lsa = self._lsdb[self._hostname]
            lsa.seq_no += 1
            lsa.age = 1
            lsa.networks = networks
        else:
            lsa = ospf.LinkStatePacket(self._hostname, self._demand, 1, 1,
                                       networks)
        self._lsdb.insert(lsa)
        # Flood LSA to neighbors
        self._flood(lsa)
        self._update_energy_flow()

    def _sync_lsdb(self, neighbor_id):
        log('Sync LSDB.')
        topology_changed = (neighbor_id not in self._neighbors)
        if topology_changed:
            log('Adjacency established with %s' % (neighbor_id, ))
        self._neighbors[neighbor_id] = self._seen[neighbor_id]
        if self._hostname not in self._lsdb:
            log('Creating initial LSA')
            self._advertise()
        elif topology_changed:
            self._advertise()
            # Sync LSDB with neighbor
            for lsa in self._lsdb.values():
                self.transmit(lsa, self._neighbors[neighbor_id][0])

    def _handle_hello(self, packet):
        neighbor_id = packet.router_id
        if neighbor_id != self._hostname:
            log('Received HelloPacket.')
            log('Seen %s' % (neighbor_id, ))

            # Reset Dead timer
            if neighbor_id in self._timers:
                self._timers[neighbor_id].stop()
            t = Timer(ospf.DEAD_INTERVAL, self._break_adjacency, [neighbor_id],
                      True)
            t.start()
            self._timers[neighbor_id] = t

            self._seen[neighbor_id] = packet.seen
            if self._hostname in packet.seen:
                self._sync_lsdb(neighbor_id)

    def _handle_lsa(self, packet):
        log('Received LSA.')
        # Insert to Link State database
        if self._lsdb.insert(packet):
            if packet.adv_router == self._hostname:
                self._advertise()
            else:
                log('Received LSA of %s via %s and merged to the LSDB' %
                    (packet.adv_router, packet.link))
                self._flood(packet, packet.link)
                self._update_energy_flow()
        elif packet.adv_router == self._hostname and packet.seq_no == 1:
            self._advertise()

    def _handle_admin(self, packet):
        if packet.action == ospf.AdminPacket.ADD_LINK:
            if self._hostname == packet.router_id or self._hostname == packet.another_router_id:
                self.add_link(packet.link, packet.cost, packet.capacity)
        elif packet.action == ospf.AdminPacket.REMOVE_LINK:
            self.remove_link(packet.link)
        elif packet.action == ospf.AdminPacket.UPDATE_DEMAND:
            if self._hostname == packet.router_id:
                self.update_demand(packet.demand)
        elif packet.action == ospf.AdminPacket.GENERATE_BREAKDOWN:
            if self._hostname == packet.router_id:
                self.stop()
        elif packet.action == ospf.AdminPacket.RESET_ROUTER:
            if self._hostname == packet.router_id:
                self.reset_router(packet.filename, packet.another_router_id,
                                  packet.demand)

    def start(self):
        log('Start.')
        self._interface.handle_start()
        # Start timers
        for t in self._timers.values():
            t.start()
        self._hello()

    def stop(self):
        log('Stop.')
        for t in self._timers.values():
            t.stop()
        self._interface.handle_close()

    def transmit(self, packet, link):
        self._interface.transmit(packet, link)

    def handle_packet(self, packet):
        if isinstance(packet, ospf.AdminPacket):
            self._handle_admin(packet)
        elif packet.link in self._links:
            if isinstance(packet, ospf.HelloPacket):
                self._handle_hello(packet)
            elif isinstance(packet, ospf.LinkStatePacket):
                self._handle_lsa(packet)

    def add_link(self, link, cost, capacity):
        if link not in self._links:
            log("Added link %s." % (link, ))
            self._links[link] = (cost, capacity)

    def remove_link(self, link):
        if link in self._links:
            log("Removed link %s." % (link, ))
            del self._links[link]

    def update_demand(self, demand):
        self._demand = demand
        if self._hostname in self._lsdb:
            self._lsdb[self._hostname].demand = demand
            self._advertise()

    def reset_router(self, filename, hostname, demand):
        self.stop()
        if filename is not None:
            self.init_router(filename)
        elif hostname is None:
            self.init_router(self._hostname, self._demand)
        else:
            demand = demand if demand is not None else 0
            self.init_router(hostname, demand)
        self.start()
コード例 #43
0
 def test_get_anwer_invaldi_input_4(self, mock):
     ui = Interface()
     ui.testing = True
     self.assertEqual(ui.start_game(), "Invalid Input")
コード例 #44
0
    parser.add_argument("port", nargs="?", help="Set port to connect.")
    args = parser.parse_args()

    if args.host:
        host = args.host
    else:
        host = HOST

    if args.port:
        port = args.port
    else:
        port = PORT

    print("Connecting to %s:%s…" % (host, port))
    sock = socket.socket()
    sock.connect((host, port))
    f = sock.makefile(mode='rw')

    print("Launching interface…")
    inter = Interface()

    print("Creating channel…")
    channel = Channel(
        f.buffer,
        lambda name, args, visu=inter: callback(visu, name, args),
        proto="asserv")

    print("All done!")

    sys.exit(inter.getAppHandle().exec_())
コード例 #45
0
ファイル: __init__.py プロジェクト: TWoolhouse/WebServer
 async def timeout():
     await Interface.next(1)
     Interface.stop()
コード例 #46
0
 def __init__(self):
   self.config = self.load_config()
   self.interface = Interface(self.config['interface'])
   self.tools = Tools(self.interface, self.config['tools'])
   self.attacks = Attacks(self.tools, self.config['attacks'])
   self.tools.stop_interfaces()
コード例 #47
0
class TestSudoku(unittest.TestCase):
    def setUp(self):
        self.interface = Interface()

    @parameterized.expand([
        ('4', '2', '4'),
        ('4', '4', '5'),
        ('3', '6', '4'),
        ('8', '3', '2'),
    ])
    def test_valid_number(self, number, pos_x, pos_y):
        self.assertTrue(
            self.interface.validate_input_number(number, pos_x, pos_y))

    @parameterized.expand([
        ('0', '2', '4'),
        ('-1', '4', '5'),
        ('-2', '6', '4'),
        ('-3', '3', '2'),
    ])
    def test_input_small_number(self, number, pos_x, pos_y):
        with self.assertRaises(IncorrectNumber):
            self.interface.validate_input_number(number, pos_x, pos_y)

    @parameterized.expand([
        ('10', '2', '4'),
        ('11', '4', '5'),
        ('100', '6', '4'),
        ('15', '3', '2'),
    ])
    def test_input_big_number(self, number, pos_x, pos_y):
        with self.assertRaises(IncorrectNumber):
            self.interface.validate_input_number(number, pos_x, pos_y)

    @parameterized.expand([
        ('4', '10', '4'),
        ('4', '11', '5'),
        ('3', '12', '4'),
        ('8', '100', '2'),
    ])
    def test_input_big_number_position_x(self, number, pos_x, pos_y):
        with self.assertRaises(IncorrectNumber):
            self.interface.validate_input_number(number, pos_x, pos_y)

    @parameterized.expand([
        ('4', '-3', '4'),
        ('4', '-1', '5'),
        ('3', '-2', '4'),
        ('8', '-5', '2'),
    ])
    def test_input_small_number_position_x(self, number, pos_x, pos_y):
        with self.assertRaises(IncorrectNumber):
            self.interface.validate_input_number(number, pos_x, pos_y)

    @parameterized.expand([
        ('4', '2', '10'),
        ('4', '4', '11'),
        ('3', '6', '12'),
        ('8', '3', '15'),
    ])
    def test_input_big_number_position_y(self, number, pos_x, pos_y):
        with self.assertRaises(IncorrectNumber):
            self.interface.validate_input_number(number, pos_x, pos_y)

    @parameterized.expand([
        ('4', '2', '-1'),
        ('4', '4', '-2'),
        ('3', '6', '-3'),
        ('8', '3', '-8'),
    ])
    def test_input_small_number_position_y(self, number, pos_x, pos_y):
        with self.assertRaises(IncorrectNumber):
            self.interface.validate_input_number(number, pos_x, pos_y)

    @parameterized.expand([
        ('h', '2', '4'),
        ('o', '4', '5'),
        ('l', '6', '4'),
        ('a', '3', '2'),
    ])
    def test_input_letter(self, number, pos_x, pos_y):
        with self.assertRaises(ValueError):
            self.interface.validate_input_number(number, pos_x, pos_y)
コード例 #48
0
class Main:

  def __init__(self):
    self.config = self.load_config()
    self.interface = Interface(self.config['interface'])
    self.tools = Tools(self.interface, self.config['tools'])
    self.attacks = Attacks(self.tools, self.config['attacks'])
    self.tools.stop_interfaces()

  def load_config(self):
    with open('data/config/config.json') as f:
      return json.load(f)

  def main_interface(self):
    return self.interface.show('EVIL-ESP', [
      Voice('Options', self.options_interface),
      Voice('Attacks', self.attacks_interface),
      Voice('Logs', self.logs_interface)
    ])

  def options_interface(self):
    return self.interface.show('OPTIONS', [
      Voice('Back', self.main_interface),
      Voice('Config Mode', self.tools.start_config_mode),
      Voice('Sleep', self.device_sleep)
    ])

  def attacks_interface(self):
    return self.interface.show('ATTACKS', [
      Voice('Back', self.main_interface),
      Voice('Beacon Spammer', self.attacks.start_beacon_spammer),
      Voice('Captive Portal', self.attacks.start_captive_portal),
      Voice('Evil Twin', self.evil_twin_interface)
    ])

  def create_lambda(self, essid):
    return lambda: self.attacks.start_evil_twin(essid)

  def evil_twin_interface(self):
    self.interface.show_single(['Scanning'])
    voices = [Voice('No networks', self.attacks_interface)]
    networks = self.tools.scan_networks()
    if len(networks) > 0:
      voices[0].name = 'Back'
      for net in networks:
        if net[4] > 0:
          essid = str(net[0], 'utf-8')
          callback = self.create_lambda(essid)
          voices.append(Voice(essid, callback))
    return self.interface.show('TWIN', voices)

  def logs_interface(self):
    return self.interface.show('LOGS', [
      Voice('Back', self.main_interface),
      Voice('Captive Portal', self.captive_portal_logs_interface),
      Voice('Evil Twin', self.evil_twin_logs_interface)
    ])

  def captive_portal_logs_interface(self):
    voices = [Voice('No credentials', self.logs_interface)]
    logs = self.attacks.get_captive_portal_logs()
    if len(logs) > 0:
      voices = []
      for log in logs:
        log = log.replace('\n', '')
        voices.append(Voice(log, self.logs_interface))
    return self.interface.show('PORTAL', voices)

  def evil_twin_logs_interface(self):
    voices = [Voice('No credentials', self.logs_interface)]
    logs = self.attacks.get_evil_twin_logs()
    if len(logs) > 0:
      voices = []
      for log in logs:
        log = log.replace('\n', '')
        voices.append(Voice(log, self.logs_interface))
    return self.interface.show('TWIN', voices)


  def device_sleep(self):
    self.interface.sleep_screen()
    machine.deepsleep()

  def start(self):
    display_enabled = self.config['interface']['display']['enabled']
    button_enabled = self.config['interface']['button']['enabled']
    default_attack = self.config['attacks']['default']
    if display_enabled and button_enabled:
      self.loop()
    elif default_attack == 'beacon_spammer':
      self.attacks.start_beacon_spammer()
    elif default_attack == 'captive_portal':
      self.attacks.start_captive_portal()
    elif default_attack == 'evil_twin':
      target_essid = self.config['attacks']['evil_twin']['default_essid']
      self.attacks.start_evil_twin(target_essid)

  def loop(self, callback = None):
    while True:
      if not callback:
        callback = self.main_interface
      callback = callback()
コード例 #49
0
app = Flask(__name__)
app.config[
    'SECRET_KEY'] = b'\xb2t\x9e\xb0\xab\x17g\xc1\x82\xe7\xaep\xe8\xbe+0\xf2\x0e\xaa\xc6\x8e9\xeds'
cache = Cache(config=redisconfig.config)
cache.init_app(app)


@app.errorhandler(404)
def page_not_found(error):
    return render_template('404error.html')


@app.route('/robots.txt')
def robots():
    root = os.path.dirname(os.path.abspath(__file__))
    return send_from_directory(root, 'robots.txt')


if __name__ == '__main__':
    index = Index(app)
    search = Search(app)
    articles_detail = ArticlesDetail(app, cache)
    archives = Archives(app)
    about = About(app)
    manager = Manager(app)
    publish = Publish(app)
    login = Login(app)
    interface = Interface(app)
    app.run()
コード例 #50
0
ファイル: dqn_env.py プロジェクト: xingchen1106/tensor48
class T48Env(py_environment.PyEnvironment):
    def __init__(self, do_record):
        self._do_record = do_record
        if self._do_record:
            self._step_counter = 0
            self._record_name = "dqn_eval_logs/{}.log".format(time())
            self._file = open(self._record_name, "w")
            self._file.write("Agent Game Log\n\r")
            self._file.write(
                "======================================================\n\r")
            self._file.close()

        self._game = Interface()
        self._state = self._game.get_flat_board()
        self._episode_ended = False

        self._action_spec = array_spec.BoundedArraySpec(shape=(),
                                                        dtype=np.int32,
                                                        minimum=0,
                                                        maximum=3,
                                                        name='action')
        self._observation_spec = array_spec.BoundedArraySpec(
            shape=self._state.shape,
            dtype=np.uint8,
            minimum=0,
            name='observation')
        # Define Actions
        self._UP = 0
        self._DOWN = 1
        self._LEFT = 2
        self._RIGHT = 3

    def action_spec(self):
        return self._action_spec

    def observation_spec(self):
        return self._observation_spec

    def _reset(self):
        self._game.restart()
        self._state = self._game.get_flat_board()
        self._episode_ended = False

        return ts.restart(self._state)

    def _write_log_entry(self, action):
        full_board = self._game.get_board()
        score = self._game.get_score()
        current_step = self._step_counter
        self._step_counter += 1

        log_string = '''Current Move: {}\r\n
Current Score: {}\r\n
{}\r\n
Next Move: {}\r\n
======================================================\n\r'''.format(
            current_step, score, full_board, action)

        f = open(self._record_name, "a")
        f.write(log_string)
        f.close()

    def _step(self, action):

        if self._do_record:
            self._write_log_entry(action)

        if self._episode_ended:
            # The last action ended the episode. Ignore the current action and start
            # a new episode.
            return self.reset()

        iscore = self._game.get_score()

        # Input agent action
        if action == self._UP:
            self._game.move_up()
        elif action == self._DOWN:
            self._game.move_down()
        elif action == self._LEFT:
            self._game.move_left()
        elif action == self._RIGHT:
            self._game.move_right()
        else:
            raise ValueError('`action` should be between 0 and 3 (inclusive).')

        # Get state after the agent action is taken
        state_buffer = self._state
        self._state = self._game.get_flat_board()
        if self._game.is_game_over() or np.array_equal(state_buffer,
                                                       self._state):
            self._episode_ended = True
        reward = self._game.get_score() - iscore

        # Set rewards
        if self._episode_ended:
            # return with a reward of 0
            return ts.termination(self._state, 0.0)
        else:
            return ts.transition(self._state, reward=reward, discount=1.0)
コード例 #51
0
ファイル: main.py プロジェクト: janEntikan/Unseen-Adventure
class GameApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        pman.shim.init(self)
        info = self.pipe.getDisplayInformation()
        for idx in range(info.getTotalDisplayModes()):
            width = info.getDisplayModeWidth(idx)
            height = info.getDisplayModeHeight(idx)
            bits = info.getDisplayModeBitsPerPixel(idx)
        wp = WindowProperties()
        wp.set_size(width, height)
        base.win.requestProperties(wp)
        self.win.set_clear_color((0.03,0.03,0.03,1))
        add_device_listener(
            config_file='keybindings.toml',
            assigner=SinglePlayerAssigner(),
        )
        base.disableMouse() 
        self.dt = globalClock.get_dt()
        self.transition = Transitions(loader)
        self.font = loader.load_font("probe.ttf")
        self.load_sounds()
        self.base_fov = 35
        base.camLens.set_fov(self.base_fov)
        self.interface = Interface()
        self.sequence = None
        self.sequence_end = Func(self.end_sequence)
        #self.interface.test()
        taskMgr.add(self.update)

    def load_sounds(self):
        self.playing = None
        self.sounds = {}
        self.music = {}
        sounds = (
            "accept", "back", "error", 
            "rotate", "select", "move",
            "hit0", "hit1", "hit2", "hit3",
            "down", "upup", "money", "equip",
            "door_open", "door_close", "youdie",
            "quest_found", "quest_success",
        )
        musics = (
            "home", "town", "shop", "tension",
            "forrest", "battlesong", "strange",
            "tower", "mine", "ending", "title",
        )
        for sound in sounds:
            self.sounds[sound] = loader.load_sfx("sound/{}.wav".format(sound))
        for music in musics:
            self.music[music] = loader.load_sfx("music/{}.ogg".format(music))
            self.music[music].set_volume(0.25)

    def play_music(self, music=None):
        if not music == self.playing:
            for song in self.music:
                self.music[song].stop()
            if music:
                self.music[music].set_loop(True)
                self.music[music].play()
            self.playing = music

    def start_sequence(self, *kwargs):
        if not self.sequence:
            self.sequence = Sequence()
        while self.sequence_end in self.sequence:
            self.sequence.remove(self.sequence_end)
        for item in kwargs:
            self.sequence.append(item)
        self.sequence.append(self.sequence_end)
        self.sequence.start()

    def end_sequence(self):
        if self.sequence:
            self.sequence.finish()
            self.sequence = None

    def update(self, task):
        self.interface.said_this_frame = []
        self.dt = globalClock.get_dt()
        if not self.sequence:
            self.interface.update()
        return task.cont
コード例 #52
0
l = 200
w = 800

feedr += [rs.rect(l, w, x1r, ycentr - 400)]

for i in range(0, len(feedr)):
    infeedr = gdspy.Polygon(feedr[i], rem_layer)
    dots = gdspy.fast_boolean(dots,
                              infeedr,
                              'not',
                              precision=1e-9,
                              max_points=1000,
                              layer=dot_layer)
    # poly_cell.add(infeedr)

circuit = gdspy.fast_boolean(dots,
                             conductor,
                             'or',
                             precision=1e-9,
                             max_points=1000,
                             layer=sub_layer)

# poly_cell.add(dots)
# poly_cell.add(conductor)
poly_cell.add(circuit)

###########################################################################
# Make gds file and open up klayout
inter = Interface()
inter.klayout(layout_file)
コード例 #53
0
class Simulator(object):
    def __init__(self):
        self.wind_speed = 5.0  # default wind speed
        self.coherent_pow_flg = True  # add coherent power
        self.coh_integrate_time = 0.001  # coherent integrateed time
        self.num_angles = 360  # integrated angle resolution
        self.interface_flg = 1  # curvature surface
        self.ddm_cov_factor = 5  # cov mode factor for ddm
        # # atmosphere loss for signal propagation 0.5 dB
        self.atmospheric_loss = pow(10.0, (0.5 / 10.0))
        # # members
        self.geometry = Geometry()
        self.nadir_RF = Antenna()
        self.zenith_RF = Antenna()
        self.signal = Signal()
        self.power_waveform = Waveform(True, 1000)
        self.interface = Interface()

    def plot_delay_waveform(self, flg=False):
        """ plot delay simulated waveform """
        if flg:
            waveform = self.integrate_waveform
            title = "Integrated waveform"
        else:
            waveform = self.waveform
            title = "Delay waveform"
        noise_level = waveform[0]
        plt.figure()
        plt.plot(self.wave_range / 1000.0,
                 10.0 * np.log10(waveform / noise_level), '*-')
        plt.grid()
        plt.title(title)
        plt.xlabel("Range from specular [km]")
        plt.ylabel("SNR [dB]")
        plt.ylim(0, 5)
        plt.xlim(-1.0, 5.0)
        plt.tight_layout()
        plt.show()

    def plot_power_ddm(self):
        """ plot scattered power DDM """
        plt.figure(figsize=(4, 3))
        noise_level = self.ddm.min()
        extent = [
            self.wave_range[0] / 1000.0, self.wave_range[-1] / 1000.0,
            -self.dopp_bin * self.center_dopp / 1000.0,
            self.dopp_bin * self.center_dopp / 1000.0
        ]
        plt.imshow(self.ddm,
                   extent=extent,
                   vmin=noise_level,
                   vmax=max(self.ddm[self.center_dopp, :]),
                   cmap='jet',
                   aspect='auto')
        plt.title("Scattered power DDM")
        plt.xlabel("Range from specular [km]")
        plt.ylabel("Doppler [kHz]")
        plt.colorbar()
        plt.tight_layout()
        plt.show()

    def plot_scattered_area(self, flg=True):
        """ plot scattered area """
        if flg:
            sca_area = self.eff_area
            title = "Effective scatter area"
        else:
            sca_area = self.phy_area
            title = "Physical scatter area"
        plt.figure(figsize=(4, 3))
        noise_level = sca_area.min()
        max_pow = max(sca_area[self.center_dopp, :])
        extent = [
            self.wave_range[0] / 1000.0, self.wave_range[-1] / 1000.0,
            -self.dopp_bin * self.center_dopp / 1000.0,
            self.dopp_bin * self.center_dopp / 1000.0
        ]
        plt.imshow(sca_area,
                   extent=extent,
                   vmin=noise_level,
                   vmax=max_pow,
                   cmap='jet',
                   aspect='auto')
        plt.title(title)
        plt.xlabel("Range from specular [km]")
        plt.ylabel("Doppler [kHz]")
        plt.colorbar()
        plt.tight_layout()
        plt.show()

    ###########################################################################
    def compute_direct_power(self, transmit_pow):
        """ compute direct signal power """
        # # receiver body frame
        bf_e, bf_h, bf_k = self.zenith_RF.get_antenna_bf()
        # # receiver body frame to specular
        self.geometry.BF2spfs(bf_e, bf_h, bf_k)
        scat_vec, rang = self.geometry.compute_r2t_vector()
        angles = self.geometry.compute_antenna_gain_pos(scat_vec)
        directivity = pow(10.0,
                          (self.nadir_RF.get_receiver_gain(angles)) / 10.0)
        tmp = const.C_LIGHT / (self.signal.freq * 4.0 * const.PI * rang)
        self.direct_pow = pow(tmp, 2)
        self.direct_pow *= transmit_pow * directivity / self.atmospheric_loss

    def correlate_direct_signal(self):
        sin_arg = 2 * self.zenith_RF.filter_bb_bw / self.sampling_rate
        sin_arg *= np.arange(0, self.range_samples_len)
        sin_arg[sin_arg == 0.0] = 1.0
        sin_arg = np.sinc(sin_arg)
        self.nd_nr_cov = abs(sin_arg)
        self.sd_nr_cov = np.convolve(sin_arg,
                                     self.signal.lambda_fun,
                                     mode="same")
        self.sd_nr_cov = np.abs(self.sd_nr_cov)
        max_value = self.sd_nr_cov.max()
        if max_value > 0.0:
            self.sd_nr_cov = self.sd_nr_cov / max_value
        for i in range(self.dopps):
            power = self.power[:, i]
            pass

    ###########################################################################
    def compute_coherent_power(self, scat_vec):
        """
        compute coherent power at scat_vec diretion, commonly coherent
        relection accur at specular point
        """
        # # compute receiver antenna gain at scat_vec diretion
        # # receiver body frame
        bf_e, bf_h, bf_k = self.nadir_RF.get_antenna_bf()
        # # receiver body frame to specular
        self.geometry.BF2spfs(bf_e, bf_h, bf_k)
        angles = self.geometry.compute_antenna_gain_pos(scat_vec)
        directivity = pow(10.0,
                          (self.nadir_RF.get_receiver_gain(angles)) / 10.0)
        # # specular point sinc function
        self.cosi = cos(self.geometry.tx_inc)
        self.tani = tan(self.geometry.tx_inc)
        self.sinc_dopps = np.zeros(self.dopps)
        sinc_arg = self.dopp_bin * self.coh_integrate_time
        if sinc_arg == 0.0:
            self.sinc_dopps[self.center_dopp] = 1.0
        else:
            self.sinc_dopps[self.center_dopp] = pow(np.sinc(sinc_arg), 2)
        # # compute fresnel coefficients
        self.interface.compute_fresnel(self.geometry.tx_inc)
        # # get corherent power
        tmp = 4.0 * const.PI * self.interface.sigma_z * self.cosi
        coherent_pow = self.signal.trans_pow * self.interface.fresnel
        coherent_pow *= exp(-1.0 * pow(tmp / self.signal.wavelen, 2))
        tmp = const.C_LIGHT * self.coh_integrate_time
        tmp /= (4.0 * const.PI * self.signal.freq)
        tmp /= (norm(self.geometry.tx_spf) + norm(self.geometry.rx_spf))
        coherent_pow *= directivity * self.sinc_dopps[self.center_dopp]
        coherent_pow *= pow(tmp, 2) / self.atmospheric_loss
        self.coherent_pow = coherent_pow

    def set_pow_waveform(self, init_range, sampling_rate):
        """ set power waveform for delays computation """
        self.power_waveform.sampling_rate = sampling_rate
        self.power_waveform.set_init_range(init_range)

    def set_nadir_antenna(self,
                          gain,
                          temp,
                          figure,
                          filter_bb_bw,
                          antenna_flg=True):
        """
        set antenna attitude information for receiver antenna gain
        computation
        """
        self.nadir_RF.set_receiver(gain, temp, figure, filter_bb_bw,
                                   antenna_flg)

    def set_radar_signal(self, sampling_rate, filter_bb_bw, exponent):
        """ initailze the bistatic radar signal """
        self.signal.set_radar_signal(sampling_rate, filter_bb_bw)
        # # compute corelation function of WAF
        self.signal.compute_lambda()
        self.isotropic_factor = (self.signal.wavelen**2) / (4.0 * const.PI)**3
        self.dt = const.C_LIGHT / sampling_rate  # just for computation later
        # # compute the transmit power
        ele = const.PI / 2 - self.geometry.tx_inc
        self.signal.compute_transmit_power(self.signal, ele)

    def set_interface(self, wind_speed):
        self.interface.ws = wind_speed
        self.interface.set_polarization(self.polar_mode)

    def configure_radar_geometry(self, tx, tv, rx, rv, undulation_flg=True):
        """
        set bistatic radar configuration, need the ecef postion and velocity
        of transimiter and receiver, compute specular point postion. function
        can also account for the undualtion of geoid
        """
        self.geometry.tx_pos = np.asarray(tx)
        self.geometry.tx_vel = np.asarray(tv)
        self.geometry.rx_pos = np.asarray(rx)
        self.geometry.rx_vel = np.asarray(rv)
        # # compute the specular point
        self.geometry.compute_sp_pos(undulation_flg)

    def earth_curvature_appro(self, tau, x):
        """ modified surface glisten zone coordinations for earth curvature """
        rad = norm(x[:2])
        az = atan2(x[1], x[0])
        x[2] = sqrt(const.RE_WGS84**2 - rad**2) - const.RE_WGS84
        rr = norm(self.geometry.rx_spf - x)
        rt = norm(self.geometry.tx_spf - x)
        delay = rr + rt - self.geometry.rrt - self.sp_delay
        rad *= sqrt(tau / delay)
        x[0] = rad * cos(az)
        x[1] = rad * sin(az)
        x[2] = sqrt(const.RE_WGS84**2 - rad**2) - const.RE_WGS84

    def compute_sinc(self, dopp):
        """ compute doppler sinc function """
        sinc_arg = (np.arange(self.dopps) - self.center_dopp) * self.dopp_bin
        sinc_arg = (dopp - sinc_arg) * self.coh_integrate_time
        ind = sinc_arg != 0.0
        self.sinc_dopps[ind] = pow(np.sinc(sinc_arg[ind]), 2)
        self.sinc_dopps[~ind] = 1.0

    def delay_integration(self, tau, a, c, delta):
        """
        integration points over the surface ellipse for each range sample
        """
        x = np.zeros(3)
        pow_tau = np.zeros(self.dopps)
        phy_area = np.zeros(self.dopps)
        eff_area = np.zeros(self.dopps)
        left_side = -1.0 * (self.center_dopp + 0.5) * self.dopp_bin
        for i in range(self.num_angles):
            # # surface point calculation
            theta = i * delta
            x[0] = a * self.cosi * cos(theta)
            x[1] = a * sin(theta) + c
            # # surface point earth curvature modified
            if self.interface_flg == 1:
                self.earth_curvature_appro(tau, x)
            # # surface point scatter vector and scatter area
            inc_vec, sca_vec, jacob, coeff = self.geometry.compute_scattering_vector(
                x)
            # # surface point relative doppler shift to the specular point
            dopp = self.geometry.doppler_shift(inc_vec, sca_vec,
                                               self.signal.freq) - self.sp_dopp
            # if self.dopps % 2 == 0:
            #     dopp -= self.dopp_bin
            # # sinc function
            self.compute_sinc(dopp)
            # # reflected coeffcient
            simga0 = self.interface.compute_scattered_coeff(
                inc_vec, sca_vec, self.geometry.tx_az)
            # # receicer antenna gain at the surface point direction
            angles = self.geometry.compute_antenna_gain_pos(inc_vec)
            rev_gain_db = self.nadir_RF.get_receiver_gain(angles)
            directivity = pow(10.0, rev_gain_db / 10.0)
            # # a factor for correlation calculation
            factor = directivity * self.isotropic_factor * simga0 * jacob * coeff
            if i == 0:
                # # restore the first surface point
                fx = np.copy(x[:2])
                px = np.copy(x[:2])  # the former point relative to current one
                fst_dopp = pre_dopp = dopp
                fst_jac = pre_jac = jacob
                fst_ft = factor * self.sinc_dopps
                pre_ft = fst_ft.copy()
                fst_area = jacob * self.sinc_dopps
                pre_area = fst_area.copy()
                continue
            diff_ang = abs(atan2(x[1], x[0]) - atan2(px[1], px[0]))
            new_theta = min(diff_ang, 2.0 * const.PI - diff_ang)
            px = np.copy(x[:2])
            tmp = factor * self.sinc_dopps
            area = jacob * self.sinc_dopps
            pow_tau += new_theta * (tmp + pre_ft) / 2.0  # accumulate the power
            ind = int(((dopp + pre_dopp) / 2.0 - left_side) // self.dopp_bin)
            if (ind >= 0) and (ind < self.dopps):
                phy_area[ind] += (jacob + pre_jac) / 2.0 * new_theta
            eff_area += new_theta * (area + pre_area) / 2.0
            pre_dopp = dopp
            pre_jac = jacob
            pre_ft = tmp.copy()
            pre_area = area.copy()
            if i == self.num_angles - 1:
                # # intergration to finish the whole ellipse, connect
                # # the last point to the first point
                diff_ang = abs(atan2(fx[1], fx[0]) - atan2(x[1], x[0]))
                new_theta = min(diff_ang, 2.0 * const.PI - diff_ang)
                pow_tau += new_theta * (fst_ft +
                                        tmp) / 2.0  # accumulate the power
                ind = int(
                    ((dopp + fst_dopp) / 2.0 - left_side) // self.dopp_bin)
                if (ind >= 0) and (ind < self.dopps):
                    phy_area[ind] += (jacob + fst_jac) / 2.0 * new_theta
                eff_area += new_theta * (fst_area + area) / 2.0
        return pow_tau, phy_area, eff_area

    def compute_noise_floor(self):
        """ compute noise floor """
        eta_factor = 1.0
        self.noise_floor = eta_factor * pow(10.0,
                                            self.nadir_RF.noise_power / 10.0)
        self.noise_floor /= self.nadir_RF.filter_bb_bw * self.coh_integrate_time

    def compute_power_waveform(self, ind):
        """ get lambda function """
        lam_len = self.signal.lambda_size
        half_lam = lam_len // 2
        waveform_conv = np.convolve(self.power[:, ind],
                                    self.signal.lambda_fun,
                                    mode="same")
        area_conv = np.convolve(self.dis_eff_area[:, ind],
                                self.signal.lambda_fun,
                                mode="same")
        # # compute delay power waveform
        tmp = waveform_conv[half_lam:half_lam + self.delays]
        tmp *= self.signal.trans_pow * self.dt / self.atmospheric_loss
        tmp += self.noise_floor
        if lam_len > self.delays:
            lam_len = self.delays
        tmp[:lam_len] += self.coherent_pow * self.signal.lambda_fun[:lam_len]
        return abs(tmp), area_conv[half_lam:half_lam + self.delays]

    def compute_ddm(self):
        """ compute ddm of scattered surface """
        half_lam = self.signal.lambda_size // 2
        self.ddm = np.zeros((self.dopps, self.delays))
        self.eff_area = np.zeros((self.dopps, self.delays))
        self.phy_area = self.dis_phy_area[half_lam:half_lam + self.delays,
                                          range(self.dopps)].T
        # # zero doppler shift delay waveform
        for i in range(self.dopps):
            sca_pow, eff_area = self.compute_power_waveform(i)
            self.ddm[i, :] = sca_pow
            self.eff_area[i, :] = eff_area
        # # integrated waveform
        self.integrate_waveform = self.ddm.sum(axis=0)
        if not hasattr(self, "wave_range"):
            self.power_waveform.set_waveform(self.ddm[self.center_dopp, :])
            self.power_waveform.compute_waveform_delays()
            self.wave_range = self.power_waveform.get_range_waveform()
            self.wave_range -= self.geometry.geometric_delay

    def compute_center_waveform(self):
        """ compute delay power waveform  """
        self.compute_noise_floor()
        self.waveform, _ = self.compute_power_waveform(self.center_dopp)
        # # compute spatical delays of delay waveform in meters
        self.power_waveform.set_waveform(self.waveform)
        self.power_waveform.compute_waveform_delays()
        self.wave_range = self.power_waveform.get_range_waveform()
        self.wave_range -= self.geometry.geometric_delay

    def compute_power_distribution(self):
        """
        Computation power distribution over reflecting surface
        origin located at sample = gnss_signal.lambda_size
        """
        # # signal correlation starting postion
        lam_len = self.signal.lambda_size
        end = self.range_samples_len - lam_len
        self.power = np.zeros((self.range_samples_len, self.dopps))
        self.dis_phy_area = np.zeros((self.range_samples_len, self.dopps))
        self.dis_eff_area = np.zeros((self.range_samples_len, self.dopps))
        for i in range(lam_len, end):
            # # compute relative delay
            tau = (i - lam_len) * self.dt
            tau = 1.0e-6 if i == lam_len else tau
            # # compute absolute delay
            tau_abs = tau + self.sp_delay
            a = tau_abs / self.cosi**2 * sqrt(1.0 - self.sp_delay / tau_abs)
            c = self.tani / self.cosi * tau
            delta = 2.0 * const.PI / self.num_angles
            sca_pow, phy_area, eff_area = self.delay_integration(
                tau, a, c, delta)
            self.power[i, :] = sca_pow
            self.dis_phy_area[i, :] = phy_area
            self.dis_eff_area[i, :] = eff_area

    def compute_sp_info(self):
        """
        compute the delay/dopper on the specular point, also calculate the
        coherent power on the specular point for the coherent reflection
        """
        # # compute scattering vector
        inc_vec = -1.0 * self.geometry.tx_spf / norm(self.geometry.tx_spf)
        scat_vec = self.geometry.rx_spf / norm(self.geometry.rx_spf)
        # # delay and dopper at specular point
        self.sp_dopp = self.geometry.doppler_shift(inc_vec, scat_vec,
                                                   self.signal.freq)
        self.sp_delay = self.geometry.geometric_delay
        # # coherent power
        if self.coherent_pow_flg:
            self.compute_coherent_power(scat_vec)

    def set_model(self, rx_pos, rx_vel, tx_pos, tx_vel, cov_mode=False):
        """ set model for simulator initalization"""
        self.ddm_cov_mode = cov_mode
        # # equal 244ns( 1/(1/1023000/4)), it is ddm delay sampling rate,
        self.sampling_rate = 4091750.0  # 4092000
        self.range_len_exponent = 8
        self.delays = 17  # DDM delay chips
        self.dopps = 11  # DDM doppler bins
        self.dopp_bin = 500.0  # doppler resolution unit in Hz
        self.filter_bb_bw = 5000000.0  # receiver baseband bandwidth in Hz
        self.polar_mode = "RL"  # poliariztion of reflected signal
        # # variable initialize
        if self.ddm_cov_mode:
            self.dopps = (self.dopps - 1) * 2 * self.ddm_cov_factor
        self.center_dopp = self.dopps // 2
        self.range_samples_len = 2**self.range_len_exponent
        # # set bistatic radar geometry
        self.configure_radar_geometry(tx_pos, tx_vel, rx_pos, rx_vel, True)
        # # set interface
        self.set_interface(self.wind_speed)
        # # set radar signal
        self.set_radar_signal(self.sampling_rate, self.filter_bb_bw,
                              self.range_len_exponent)
        # # set intrument information
        self.gain = 0.0
        self.antenna_temperature = 200
        self.noise_figure = 3.0
        self.set_nadir_antenna(self.gain, self.antenna_temperature,
                               self.noise_figure, self.filter_bb_bw, False)
        # # set power waveform information
        init_range = self.geometry.geometric_delay
        init_range -= (self.signal.lambda_size // 2 + 1) * self.dt
        self.set_pow_waveform(init_range, self.sampling_rate)

    def simulate(self, rx_pos, rx_vel, tx_pos, tx_vel):
        self.set_model(rx_pos, rx_vel, tx_pos, tx_vel)
        self.compute_sp_info()
        self.compute_power_distribution()
        self.compute_center_waveform()
        self.compute_ddm()
        # self.output_subddm()
        return self.waveform, self.integrate_waveform, self.wave_range
コード例 #54
0
ファイル: main.py プロジェクト: arturmen/PE2020
from interface import Interface
from config_manager import ConfigManager
from db_connector import DBConnector
from logger_connector import LoggerConnector
from file_connector import LoggerFileConnector
from file_connector import DbFileConnector
import i18n

config_manager = ConfigManager("config.json")

# i18n setup
i18n.load_path.append('./translations')
i18n.set('filename_format', '{locale}.{format}')
i18n.set('fallback', 'en')
i18n.set('file_format', 'json')
i18n.set('locale', config_manager.language)

logger_file_connector = LoggerFileConnector(config_manager)
db_file_connector = DbFileConnector(config_manager)

logger_connector = LoggerConnector(logger_file_connector)
db_connector = DBConnector(db_file_connector)

application = Interface(db_connector, logger_connector, config_manager)
application.menu()
コード例 #55
0
    def __init__(self, *args, **kargs):
        """
        Initialization of an Options object:

        Keyword Arguments:
        dangles -- Specifies the dangle terms used in the energy model.
                   Can be the strings 'None', 'Some', or 'All'.
        start_state  [type=list]     -- A list of Complexes to 
                                        use as the initial state of the system.
        simulation_time [type=float] -- Cap on the maximum simulation time.
        num_simulations [type=int]   -- Number of trajectories to run
        biscale         [type=float] -- Bimolecular scaling constant
        uniscale        [type=float] -- Unimolecular scaling constant
        parameter_type               -- Which set of energy parameters is
                                        used. Available options: 'Nupack',
                                        'Vienna'
        substrate_type               -- Whether we want 'DNA' or 'RNA' energy
                                        parameters.
        rate_method                  -- Whether we want 'Kawasaki' or 'Metropolis'
                                        or 'Arrhenius' rate method for unimolecular steps.
                                        
        If rate_method == Literals.Arrhenius, please set lnAEnd, lnALoop, lnAStack, 
                                lnAStackStack, lnALoopEnd, lnAStackEnd, lnAStackLoop, 
                                EEnd, ELoop, EStack, EStackStack, ELoopEnd, EStackEnd, 
                                EStackLoop and bimolecular_rate(double value).
        """

        ##################################################
        #                                                #
        # Data Members                                   #
        # ->Members new to the python implementation     #
        #                                                #
        #                                                #
        ##################################################
        
        
        """ Pipe to let Multistrand know the version from ../__init__.py """
        self.ms_version = float(__version__)  
        
        self.errorlog = []
        """ Keeps lines relating to possible errors or warnings that
        should be reported to the user. Usually issues relating to the
        input file or parameters with odd values.

        TODO: implement some functions to report the errors found here.
        """
        self.full_trajectory = []
        self.full_trajectory_times = []
        self.full_trajectory_arrType = []
        self.trajectory_complexes = []
        self.trajectory_state_count = 0
        self._current_end_state = []
        self._current_transition_list = []
        self.special_count = 0
        self.trajectory_current_time = 0.0
        self.current_graph = None

        self.verbosity = 1
        """ Indicates how much output will be generated for each trajectory run.
        Value = 0:  No end state reported, no warnings for timeout and nonitial steps
        Value = 1:  No end states reports, warnings active   
        Value = 2:  warnings and end states reports to stdout
        """
        
        self.print_initial_first_step = False
        """
        If True, this value will print the initial state in First Step Mode to the trajectory with a timestamp of -1.0
        """

        self.cotranscriptional = False
        """
        If True, enables the cotranscriptional simulation mode. The mode works only when a single strand is supplied.
        Starting with the initial 8 nucleotides, the simulation adds a nucleotide on the 3' end every 1 millisecond. 
        """
        
        self.cotranscriptional_rate = self.cotranscriptional_rate_default
        """
        By default, the cotranscriptional mode adds one nucleotide every 1 millisecond.
        """
        
        #############################################
        #                                           #
        # Data Members: Energy Model                #
        #                                           #
        #############################################
        # See accessors below
        self._start_state = []
        
        self.gt_enable = True
        """ Allow GT base pairs? If not, penalize by 10000 kcal/mol.
            False (0) : Do not allow GT base pairs.
        """

        self.log_ml = False
        """ Use logarithm to compute multiloop energy contributions?
        int          False (0): Do not use the logarithm.

        If True, uses log to compute one component of the multiloop energy, for loops of length > 6. Otherwise, uses the usual
        linear approximation. Using the log formula is slightly more expensive as it makes computation time for a multiloop scale
        with the number of adjoining helices.
        """
        
        self.join_concentration = 1.0
        """ concentration for V calcs
        Units are in M (molar), and represent the concentration of a single unique strand in the system. The volume simulated is
        then chosen using this parameter.
        """

        # ##
        # ## See the temperature property way below (after __init__)
        # ## for more info on accessors for these data members.
        # ##
        self._temperature_celsius = 37.0
        self._temperature_kelvin = 310.15

        self.rate_scaling = None
        """FD: This is a legacy option that sets unimolecular and bimolecular scaling automatically if set"""

        self.unimolecular_scaling = -1.0 
        """ Rate scaling factor for unimolecular reactions."""
        
        self.bimolecular_scaling = -1.0 
        """ Rate scaling factor for bimolecular reactions."""

        self.rate_method = Literals.kawasaki
        """ Choice of methods for determining forward/reverse rates. """

        self.dangles = Literals.dangles_some
        """ Dangles options for the energy model.
        
        None [0]: Do not include any dangles terms in the energy model.
        Some [1]: Some dangles terms.  (Nupack Default)
        All  [2]: Include all dangles terms, including odd overlapping ones.
        """

        self.parameter_type = self.nupackModel
        """ Which type of energy model parameter file to use.

        Vienna [0]: No longer well tested. Recommend not using.
        Nupack [1]: Includes some multi-complex parameters, otherwise
                    nearly the same as mfold style files.
        """

        self.substrate_type = Literals.substrateDNA
        """ What substrate's parameter files to use. 

        Invalid [0]: Indicates we should not auto-search for a param file.
        RNA     [1]: RNA parameters are available for Vienna and Nupack, see also
                     the comment in parameter_file_version.
        DNA     [2]: DNA parameters are publicly available via the Nupack distribution,
                     and possibly by the Vienna group upon request.
        """
        
        self.parameter_file = None
        """ Shortcut for using a very specific parameter file. Usually shouldn't be used.
        
        Type         Default
        str          None

        Should only be set to a string if it's ok to actually search
        for that parameter file. None will pass an error back to
        Multistrand if it gets used.
        """

        ####################
        #
        # BEGIN simmode
        #
        ####################
        
        self.simulation_mode = Literals.first_passage_time
        """ The simulation mode: how we want the simulation system to
        perform the main loop.
        """
        
        self.simulation_time = 600.0
        """ Maximum time (in seconds) allowed for each trajectory.
        
        Type         Default
        double       600.0
        """
        
        self.num_simulations = 1
        """ Total number of trajectories to run. 
        """
        
        self.initial_seed = None
        """ Initial random number seed to use.
        If None when simulation starts, a random seed will be chosen
        """
        
        self.name_dict = {}
        """ Dictionary from strand name to a list of unique strand objects
        having that name.
        
        Type         Default
        dict         {}
        
        Modified when start state is added. Used as a lookup when stop states 
        are added.
        """
        
        self.lnAEnd = -0.1;
        self.lnALoop = -0.1;
        self.lnAStack = -0.1;
        self.lnAStackStack = -0.1;
        self.lnALoopEnd = -0.1;
        self.lnAStackEnd = -0.1;
        self.lnAStackLoop = -0.1;        
        self.EEnd = -0.1;
        self.ELoop = -0.1;
        self.EStack = -0.1;
        self.EStackStack = -0.1;
        self.ELoopEnd = -0.1;
        self.EStackEnd = -0.1;
        self.EStackLoop = -0.1; 
         
        """ These are undocumented adjustments to the energy model """

        self.dSA = -0.0;
        self.dHA = -0.0;

        """ 
            Buffer conditions 
            Like substrate_type, temperature, and dangles,
            these follow a listener pattern to propagate settings to dangles.
            (as opposed to copying settings at the last possible moment)
        """
        self.sodium = 1.0;
        self.magnesium = 0.0;
        
        ####################
        #
        # BEGIN startstop
        #
        ####################
        

                
        # See accessors below
        self._stop_conditions = []
        self._use_stop_conditions = False
        
        self.stop_count = 0
        """ The number of stop states. Equivalent to 'len(self.stop_conditions)'.
        
        Type         Default
        int          0
        
        Incremented automatically when a stop state is added. Should not be 
        modified externally.
        """
        
        self.output_time = -1.0
        """ The amount of time (in seconds) to wait between outputs of 
        trajectory information.
        
        Type         Default
        float        -1.0
        
        A value of -1.0 corresponds to not basing outputs on output_time
        (but perhaps outputting based on some other condition). A value of 0 
        means output as often as possible.
        """
        
        self.output_interval = -1
        """ The number of states between outputs of trajectory information.
        
        Type         Default
        int          -1
        
        A value of -1 corresponds to not basing outputs on output_interval
        (but perhaps outputting based on some other condition). A value of 1 
        means output every state, 2 means every other state, and so on.
        """
        
        self.current_interval = 0
        """ Current value of output state counter.
        
        Type         Default
        int          0
        
        When current_interval is equal to output_interval, the output state is 
        True, and otherwise the output state is False. This is modified by 
        increment_output_state, and probably shouldn't be used externally."""
        
        self.output_state = False
        """ Indicates whether output should be reported.
        
        Type         Default
        boolean      False
        
        Value should be True if self.current_interval == self.output_interval 
        and False otherwise.        
        """
        
        self.interface = Interface()
        
        ##############################
        #
        # End of __init__: call the keyword hook fn. 
        #
        ##############################

        self.__init_keyword_args(self, *args, **kargs)
コード例 #56
0
 def __init__(self):
     Interface.__init__(self, "EV")
     Configurable.__init__(self)
     self.__ctxName = None
     LOG("Created")
コード例 #57
0
ファイル: main.py プロジェクト: jiachin1995/CZ3004
class Main:
    interface = None

    listen_rate = 1

    android = None
    arduino = None

    def __init__(self):
        threading.Thread.__init__(self)

        #self.pc = PC(tcp_ip="192.168.1.1")
        self.android = Android()
        self.arduino = Arduino()

        #self.pc.connect()
        self.android.connect()
        self.arduino.connect()

        time.sleep(1)

        self.interface = Interface(arduino=self.arduino,
                                   fakeRun=False,
                                   android=self.android)

    def write_to_pc(self, msg):
        self.pc.write(msg)
        print("[@] Sent to PC: {}".format(msg))

    def read_from_pc(self):
        msg = self.pc.read()
        if msg == None:
            return print("[#] nothing to read [read_from_pc]")

    def start_listening(self):
        self.android.write('{"canExplore": true}')

        while True:
            msg = self.android.read()
            if msg == None:
                continue

            try:
                results = self.interface.readinstructions(msg)

                if results is None:
                    print("Instruction Done")
                else:
                    self.android.write(results)

            except Exception as e:
                print("[@] Error reading instructions")
                print(e)
                time.sleep(self.listen_rate)

                import sys, os

                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                print(exc_type, fname, exc_tb.tb_lineno)

    def close_all_connections(self):
        #self.pc.close()
        self.android.close()
        self.arduino.close()
コード例 #58
0
	def construct(name, label, top_left_x, top_left_y, width, height, h_bezel, v_bezel, TOUCHBAR_OPTION=1):
		touch_screen_device_builder = TouchScreenDeviceBuilder(name, label, top_left_x, top_left_y, width, height)
		
		# Place a screen on the device.
		screen = touch_screen_device_builder.device.create_screen('touchscreen', 'touchscreen', top_left_x + h_bezel, top_left_y + v_bezel, width - 2*h_bezel, height - 2*v_bezel)

		default_textbox_margin = 10
		default_textbox_width = screen.width - 2*default_textbox_margin
		default_textbox_height = ((screen.width - 10) / 30) + 20
		default_textbox_character_width = (screen.width - 10) / 30
		default_textbox_character_height = (screen.width - 10) / 30

		# Place a textbox with transciprion phrase at the top of the screen.
		phrase_textbox = TextBox('phrase_textbox', '', default_textbox_margin, default_textbox_margin, 0, 0, 0, 0)
		screen.add_child(phrase_textbox, default_textbox_margin, default_textbox_margin)

		# Place a textbox with transciprion phrase at the top of the screen.
		transcript_textbox = None
		# transcript_textbox = TextBox('transcription_textbox', '', default_textbox_margin, default_textbox_margin + phrase_textbox.top_left_y + phrase_textbox.height, default_textbox_width, default_textbox_height, default_textbox_character_width, default_textbox_character_height)
		# screen.add_child(transcript_textbox, default_textbox_margin, default_textbox_margin + phrase_textbox.top_left_y + phrase_textbox.height)

		# Place a keyboard at the bottom third of the device.
		keyboard = Interface('keyboard', 'keyboard', 0, 0, screen.width, screen.height)
		screen.add_child(keyboard, 0, 0)

		# Add keys.
		default_key_width = 170
		default_key_height = 170
		default_touchbar_height = 70
		if TOUCHBAR_OPTION == 1:
			touchbar = ['esc','<','light','volumn','mute','siri']
		elif TOUCHBAR_OPTION == 2:
			touchbar = ['vol-', 'slide', 'vol+', 'out']
		elif TOUCHBAR_OPTION == 3:
			touchbar = ['out', 'light-', 'light+', 'layout', 'launchpad', 'keylight-', 'keylight+', '<<', '>||', '>>', 'mute', 'vol-', 'vol+', 'siri']
		elif TOUCHBAR_OPTION == 4:
			touchbar = ['esc',"<-","->","refresh","search","bookmark","newtag","<",'light','volumn','mute','siri']

		key_rows = [touchbar,\
		["~\n`",'1','2','3','4','5','6','7','8','9','0',"_\n-","+\n=",'del'],\
		['tab','q','w','e','r','t','y','u','i','o','p',"{\n[","}\n]","|\n\\"],\
		['cap','a','s','d','f','g','h','j','k','l',":\n;","\"\n\'",'return'],\
		['shift1','z','x','c','v','b','n','m',"<\n,",">\n.","?\n/",'shift2'],\
		['fn','ctrl','opt1','cmd1',' ','cmd2','opt2','left',"up\ndown",'right']]

		# Starting key positions.
		key_top_left_x = 0
		key_top_left_y = 0

		for key_row, idx in zip(key_rows, range(len(key_rows))):
			key_width = default_key_width
			key_height = default_key_height

			key_top_left_x = 0
			if idx == 0 and TOUCHBAR_OPTION == 1:
				key_height = default_touchbar_height
				# esc
				key_top_left_x = 110
				key_button = KeyboardKey(key_row[0], key_row[0], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# <
				key_top_left_x += 140 + 1550
				key_button = KeyboardKey(key_row[1], key_row[1], key_top_left_x, 0, 30, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				key_top_left_x += 30
				for i in range(4):
					key_button = KeyboardKey(key_row[i+2], key_row[i+2], key_top_left_x, 0, 160, key_height, transcript_textbox)
					keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
					key_top_left_x += 160
			elif idx == 0 and TOUCHBAR_OPTION == 2:
				key_height = default_touchbar_height
				# vol-
				key_top_left_x = 1250
				key_button = KeyboardKey(key_row[0], key_row[0], key_top_left_x, 0, 150, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# slide
				key_top_left_x += 150
				key_button = KeyboardKey(key_row[1], key_row[1], key_top_left_x, 0, 520, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# vol-
				key_top_left_x += 520
				key_button = KeyboardKey(key_row[2], key_row[2], key_top_left_x, 0, 150, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# out
				key_top_left_x += 150
				key_button = KeyboardKey(key_row[3], key_row[3], key_top_left_x, 0, 100, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
			elif idx == 0 and TOUCHBAR_OPTION == 3:
				key_height = default_touchbar_height
				# out
				key_top_left_x = 110
				key_button = KeyboardKey(key_row[0], key_row[0], key_top_left_x, 0, 120, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# light-
				key_top_left_x += 120 + 60
				key_button = KeyboardKey(key_row[1], key_row[1], key_top_left_x, 0, 165, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# light+
				key_top_left_x += 165
				key_button = KeyboardKey(key_row[2], key_row[2], key_top_left_x, 0, 165, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# layout
				key_top_left_x += 165 + 35
				key_button = KeyboardKey(key_row[3], key_row[3], key_top_left_x, 0, 165, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# launchpad
				key_top_left_x += 165 + 35
				key_button = KeyboardKey(key_row[4], key_row[4], key_top_left_x, 0, 165, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# keylight-
				key_top_left_x += 165 + 35
				key_button = KeyboardKey(key_row[5], key_row[5], key_top_left_x, 0, 165, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# keylight+
				key_top_left_x += 165
				key_button = KeyboardKey(key_row[6], key_row[6], key_top_left_x, 0, 165, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# <<
				key_top_left_x += 165 + 35
				key_button = KeyboardKey(key_row[7], key_row[7], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# >||
				key_top_left_x += 140
				key_button = KeyboardKey(key_row[8], key_row[8], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# >>
				key_top_left_x += 140
				key_button = KeyboardKey(key_row[9], key_row[9], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# mute
				key_top_left_x += 140 + 35
				key_button = KeyboardKey(key_row[10], key_row[10], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# vol-
				key_top_left_x += 140
				key_button = KeyboardKey(key_row[11], key_row[11], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# vol+
				key_top_left_x += 140
				key_button = KeyboardKey(key_row[12], key_row[12], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# siri
				key_top_left_x += 140 + 35
				key_button = KeyboardKey(key_row[13], key_row[13], key_top_left_x, 0, 165, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
			elif idx == 0 and TOUCHBAR_OPTION == 4:
				key_height = default_touchbar_height
				# out
				key_top_left_x += 110
				key_button = KeyboardKey(key_row[0], key_row[0], key_top_left_x, 0, 140, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# <-
				key_top_left_x += 140 + 35
				key_button = KeyboardKey(key_row[1], key_row[1], key_top_left_x, 0, 160, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# ->
				key_top_left_x += 160 + 15
				key_button = KeyboardKey(key_row[2], key_row[2], key_top_left_x, 0, 160, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# refresh
				key_top_left_x += 160 + 15
				key_button = KeyboardKey(key_row[3], key_row[3], key_top_left_x, 0, 160, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# search
				key_top_left_x += 160 + 15
				key_button = KeyboardKey(key_row[4], key_row[4], key_top_left_x, 0, 620, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# bookmark
				key_top_left_x += 620 + 15
				key_button = KeyboardKey(key_row[5], key_row[5], key_top_left_x, 0, 160, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# newtag
				key_top_left_x += 160 + 15
				key_button = KeyboardKey(key_row[6], key_row[6], key_top_left_x, 0, 160, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				# <
				key_top_left_x += 160 + 35
				key_button = KeyboardKey(key_row[7], key_row[7], key_top_left_x, 0, 30, key_height, transcript_textbox)
				keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
				key_top_left_x += 30
				for i in range(4):
					key_button = KeyboardKey(key_row[i+8], key_row[i+8], key_top_left_x, 0, 160, key_height, transcript_textbox)
					keyboard.add_child(key_button, key_top_left_x, key_top_left_y)
					key_top_left_x += 160




			else:
				for key in key_row:
					if key in ['del','tab']:
						key_width = 260
					elif key in ['cap','return']:
						key_width = 305
					elif key in ['shift1',"shift2"]:
						key_width = 395
					elif key in ['cmd1','cmd2']:
						key_width = 215
					elif key in [' ']:
						key_width = 890
					else:
						key_width = 170
					key_button = KeyboardKey(key, key, key_top_left_x, key_top_left_y, key_width, key_height, transcript_textbox)

					keyboard.add_child(key_button, key_top_left_x, key_top_left_y)

					key_top_left_x += key_width + 10

			if idx == 0:
				key_top_left_y += key_height + 40
			else:
				key_top_left_y += key_height + 10

		return touch_screen_device_builder.set_screen(screen, screen.top_left_x, screen.top_left_y).get_result()
コード例 #59
0
ファイル: Main.py プロジェクト: TheTimebike/Scheduled-Diary
from interface import Interface
from tkinter import Tk

if __name__ == "__main__":
    root = Tk()
    root.geometry("300x120")
    interface = Interface(root)
    root.resizable(False, False)
    root.mainloop()
コード例 #60
0
        """
        if self.__debug:
            print(msg)


if __name__ == "__main__":
    SERVER_HOST = "localhost"
    SERVER_PORT = 502

    c = ModbusClient()

    # define modbus server host, port
    c.host(SERVER_HOST)
    c.port(SERVER_PORT)
    root = Tk()
    root.geometry("1080x650")
    root.resizable(0, 0)
    while True:
        # open or reconnect TCP to server
        if not c.is_open():
            if not c.open():
                print("unable to connect to " + SERVER_HOST + ":" +
                      str(SERVER_PORT))

        s = Interface(root, c).init_windows()
        # root.mainloop()
        try:
            root.destroy()
        except:
            pass