コード例 #1
0
def game_main_loop(col, row, k, g, ai_1, ai_2, debug=False):
    board = Board(col, row, k, g)
    AI_com_list = [Communicator(ai_1, TIME_OUT), Communicator(ai_2, TIME_OUT)]
    player = 1
    win_flag = 0
    already_time = [0.0, 0.0]
    try:
        AI_com_list[player - 1].send("-1 -1".encode())
    except BrokenPipeError:
        print("Player 2 wins!")
        return

    while True:
        try:
            ai_move, std_error, at = AI_com_list[player - 1].recv()
        except TimeoutError:
            player = player_switch(player)
            if (debug):
                print("Time Out!")
            player = player_switch(player)
            break
        already_time[player - 1] += at
        ai_move = ai_move.decode().split("\n")[-1].rstrip()
        if (debug):
            print("Player", player, "says:", ai_move)

        try:
            board = board.make_move(Move(0, 0, ai_move), player)
        except InvalidMoveError:
            if (debug):
                print("Invalid Move!")
            player = player_switch(player)
            break
        except Exception as msg:
            if (debug):
                print("Unknown Error with the stderr:")
                print(std_error.decode())
                print("Shell raised the following exception:")
                print(msg)
            player = player_switch(player)
            break
        if (debug):
            board.show_board()
        win_flag = board.is_win()
        if (win_flag != 0):
            break

        player = player_switch(player)
        try:
            AI_com_list[player - 1].send(ai_move.encode())
        except BrokenPipeError:
            if (debug):
                print("Player", player, "crashed!")
            player = player_switch(player)
            break

    if win_flag != 0:
        return win_flag
    else:
        return player
コード例 #2
0
ファイル: Main.py プロジェクト: Torrib/NTNU
class Main():

    def __init__(self):


        self.messageHandler = MessageHandler()
        self.communicator = Communicator(self.messageHandler)
        self.controller = Controller(self.communicator)
        self.messageHandler.setController(self.controller)

        print "MAIN initialize"



        ## test code.
        print "--------------"
        sleep(2)
        print "testing start"

        peer = Peer("78.91.5.10")
        message = Message("stillAlive", peer.IP, "", "", "", "")

        self.communicator.broadcast(message)

        #self.communicator.sendToOne(peer, message)

        print "testing complete"
        print "--------------"
コード例 #3
0
def game_main_loop(col, row, k, g, ai_1, ai_2, debug=False):
    board = Board(col, row, k, g)
    AI_com_list = [Communicator(ai_1, 1000), Communicator(ai_2, 1000)]
    player = 1
    win_flag = 0
    try:
        AI_com_list[player - 1].send("-1 -1".encode())
    except BrokenPipeError:
        print("Player 2 wins!")
        return

    while True:
        try:
            ai_move = AI_com_list[player - 1].recv()
        except TimeoutError:
            player = player_switch(player)
            if (debug):
                print("Time Out!")
            break
        ai_move = ai_move.decode().split("\n")[-1].rstrip()
        if (debug):
            print("Player", player, "says:", ai_move)

        try:
            board = board.make_move(Move(0, 0, ai_move), player)
        except InvalidMoveError:
            if (debug):
                print("Invalid Move!")
            player = player_switch(player)
            break
        except Exception as msg:
            if (debug):
                print("Unknown Error!")
                print(msg)
            player = player_switch(player)
            break
        if (debug):
            board.show_board()
        win_flag = board.is_win()
        if (win_flag != 0):
            break

        player = player_switch(player)
        try:
            AI_com_list[player - 1].send(ai_move.encode())
        except BrokenPipeError:
            if (debug):
                print("Player", player, "crashed!")
            player = player_switch(player)
            break

    if win_flag != 0:
        return win_flag
    else:
        return player
コード例 #4
0
ファイル: Gui.py プロジェクト: bogini/Brickalicious
    def Printing_Screen(self):
        self.scrollbar = Scrollbar(self.frame)
        self.scrollbar.grid(row=0, column=2, sticky=N+S)
        
        self.printing_l = Text(self.frame)
        self.printing_l.grid(row=0, column = 0)
        self.scrollbar.config(command=self.printing_l.yview)

        self.pause_b = Button(self.frame, text="Pause Printing", font=("Helvetica", 14),command= self.Pause_Screen)
        self.pause_b.grid(row=1, column = 0, pady=10)
        
        self.quit_b = Button(self.frame, text= "Quit Printing", font=("Helvetica", 14),command= self.to_quit)
        self.quit_b.grid(row=2, column = 0, pady=10)
        
        # Interpreter
        self.display_message("Reading file...")
        bricks = Interpreter.parsing(self.file.name)
        Interpreter.translation(bricks)
        self.display_message("Parsing file...")
        build_order = Interpreter.generate_build_order(bricks)
        self.display_message("Generating build order...")
        #build_list = Interpreter.generate_build_list(build_order)
        
        # Communication
        self.display_message("Opening communication channel...")
        com = Communicator()
        com.setup_connection()
        self.display_message("Communication established.")
        self.display_message("Printing...")
        bricks = com.print_bricks(build_order)
        for instruction in bricks:
    		  com.send_message(instruction[0], instruction[1])
        com.close_connection()
コード例 #5
0
    def __init__(self, handle, axes, periods, reorder):
        import _mpi
        # create the handle
        cartesian = _mpi.communicatorCreateCartesian(handle, reorder, axes, periods)

        # create the python wrapper
        Communicator.__init__(self, cartesian)

        # cache attributes
        self._axes = axes
        self._periods = periods
        self._coordinates = _mpi.communicatorCartesianCoordinates(
            self._handle, self.rank, len(axes))

        return
コード例 #6
0
    def __init__(self, handle, axes, periods, reorder):
        import _mpi
        # create the handle
        cartesian = _mpi.communicatorCreateCartesian(handle, reorder, axes, periods)

        # create the python wrapper
        Communicator.__init__(self, cartesian)

        # cache attributes
        self._axes = axes
        self._periods = periods
        self._coordinates = _mpi.communicatorCartesianCoordinates(
            self._handle, self.rank, len(axes))

        return
コード例 #7
0
    def __init__(self, args=None):
        threading.Thread.__init__(self)
        self.obs = {'result' : None, 'azimuth': None ,'recogtime': None}
        self.running = True
        self.args = args
        self.pause = False
                # setup PocketSphinx
        hmm= 'model/en-us'
        lm = 'model/en-us.lm'
        dic = 'model/cmu07a.dic'

        config = Decoder.default_config()
        config.set_string('-logfn', '/dev/null') #comment for debug information
        config.set_string('-hmm', hmm)
        config.set_string('-lm', lm)
        config.set_string('-dict', dic)
        #config.set_string('-fsgusefiller', 'no') #removes filler words
        #config.set_string('-rawlogdir', 'logs') #uncomment to log the raw stream data
        print "[SpeechRecognizer] loading language model ..."
        self.decoder = Decoder(config)
        print "[SpeechRecognizer] done."

        if not args.gram:
            raise Exception("Please provde a closed grammar file")
        self.decoderAnalyzer = DecoderAnalyzer(args.gram)
        self.Communicator = Communicator(args.gram)
コード例 #8
0
    def login(self) -> bool:
        """
        Login in to obtain authentication token
        :return: bool
        """
        try:
            body = [{
                "cmd": "Login",
                "action": 0,
                "param": {
                    "User": {
                        "userName": self.username,
                        "password": self.password
                    }
                }
            }]
            param = {"cmd": "Login", "token": "null"}
            response = Communicator.send(self.url, data=body, params=param)
            if response is not None:
                data = json.loads(response.text)[0]
                code = data["code"]

                if int(code) == 0:
                    self.token = data["value"]["Token"]["name"]
                    print("Login OK")
                    return True
                return False
            else:
                print("Failed to login\nStatus Code:", response.status_code)
                return False
        except Exception as e:
            print("Login Error\n", e)
            raise
コード例 #9
0
ファイル: server.py プロジェクト: akshittyagi/Tak-sim
	def BuildServer(self,port_no,num_clients):
		"""Builds The server on the port_number port_no for num_clients
		Args:
			port_no: (int) The port number
			num_clients: (int) The number of clients who would join (>= 2 for all practical purposes)
		Returns: 
			None		
		"""
		s = socket.socket()
		s.settimeout(self.NETWORK_TIMER)
		host = socket.gethostname()
		self.port = port_no		
		s.bind((host,port_no))
		s.listen(5)
		self.client_count = 0
		self.CLOSE_NETWORK = False						
		while self.client_count < num_clients and (not self.CLOSE_NETWORK):
			try:			
				c,addr = s.accept()
			except:				
				self.CLOSE_NETWORK = True			
			if(not self.CLOSE_NETWORK):
				self.client_count += 1
				self.communicator_list.append(Communicator())
				self.communicator_list[-1].setSocket(c,self.NETWORK_TIMER)
		s.close()
コード例 #10
0
ファイル: TempTaker.py プロジェクト: HaeffnerLab/sqip
 def initServer( self ):
     #setting up necessary objects
     self.daq = Communicator()
     self.channels = self.daq.channels
     self.channelDict = self.daq.channelDict
     self.averager = RunningAverage(self.channels, averageNumber = 12)
     self.emailer = self.client.emailer
     yield self.emailer.set_recipients(['*****@*****.**']) #### set this later
     self.alarmChecker = AlarmChecker(self.emailer, self.channelDict)
     #stting up constants
     self.PIDparams =([0,0,0],..)####get from registry
     self.daqErrors = 0
     #
     self.responseCalc = ResponseCalculator()
     #begin control
     self.inControl = LoopingCall(self.control)
     self.inControl.start(self.updateRate)
コード例 #11
0
ファイル: IOAI.py プロジェクト: ethanlouie/DeepBlueDream
class IOAI():
    def __init__(self,col,row,p,**kwargs):
        command = kwargs['ai_path']
        command = get_prefix(command)
        command = command + " " + str(col) + " " + str(row) + " " + str(p) + " " + " t"
        self.communicator = Communicator(command,kwargs['time'])

    def get_move(self,move):
        self.communicator.send(str(move).encode())
        ai_move,err = self.communicator.recv(return_stderr=True)
        if len(err) > 1:
            print("exception")
            raise Exception(err.decode())
        ai_move = ai_move.decode().split("\n")[-1].rstrip()
        return Move.from_str(ai_move)

    def close(self):
        self.communicator.close()
コード例 #12
0
 def handle_read(self):
     try:
         if Communicator.handle_read(self) is -1:
             return
     except Communicator.Error, e:
         # empty connection opened (chrome for example)
         if e.args[0][0][1] in ['SSL23_READ', 'SSL3_READ_BYTES']:
             self.handle_close()
             return
         else:
             raise
コード例 #13
0
 def __init__(self,
              height,
              width,
              terrainRatio,
              waterIntervals=[1, 2],
              rockIntervals=[0, 1],
              grassIntervals=[0, 3],
              communicator=None):
     self.terrainRatio = terrainRatio
     self.waterIntervals = waterIntervals
     self.rockIntervals = rockIntervals
     self.grassIntervals = grassIntervals
     self.height = height
     self.width = width
     self.square = height * width
     self.communicator = Communicator()
     self.groundMatrix = []
     self.createField()
     self.placeObj(0)
     self.placeObj(1)
     self.placeObj(2)
コード例 #14
0
ファイル: Robot.py プロジェクト: JackBlair87/HackTJ2021
 def __init__(self, image, x=0.0, y=0.0, angle=0):
     pygame.sprite.Sprite.__init__(self)
     self.image = image.convert_alpha()
     self.size = self.image.get_size()
     self.left_encoder_counts = 0
     self.right_encoder_counts = 0
     self.location = (x, y)
     #^separate things above here into just the draw_robot method
     self.angle = angle
     self.dataPackets = [InfoPacket(angle=90),
                         InfoPacket(angle=90)
                         ]  #angles here should be changed to 0?
     self.communicator = Communicator(enabled=False)
     self.communicator.initiate_bluetooth()
     self.state = State.stop
     self.communicator.transmit_info(self.state)
     self.logger = Logger("Robot")
     self.max_dist = 150
     self.last_index = -1
     self.rectifier = None
     self.last_state_switch_time = int(round(time.time() * 1000))
コード例 #15
0
ファイル: Simulation.py プロジェクト: dariaugin/gruppa_oop
    def __init__(
        self,
        ID,
        statistics,
        environment,
        occupyPercent,
        sidesRatio=[20, 80],
        hunterRatio=[33, 33, 34],
        preyRatio=[33, 33, 34],
        display=False,
        maxDayNum=10,
        grassUpdateFrequency=7,
        T=30,
        sunMode="const",
        communicator=None,
    ):
        self.environment = environment
        self.ID = ID
        self.statistics = statistics
        self.communicator = Communicator()
        self.statistics.writeMapData(self.environment)
        self.occupyPercent = occupyPercent
        self.sidesRatio = sidesRatio
        self.hunterRatio = hunterRatio
        self.preyRatio = preyRatio
        self.display = display
        self.cycles = 0
        self.days = 0
        self.minProductivity = self.environment.grassCellNum // 5
        self.grassUpdateFrequency = grassUpdateFrequency
        self.maxDayNum = maxDayNum
        self.T = T
        self.sunMode = self.__class__.mode[sunMode]
        self.cellDict = {}

        Animal.AnimalPlacer.initBiota(self)
        Animal.AnimalPlacer.initAnimalMatrix(self)
        Animal.AnimalPlacer.placeAllAnimals(self)
コード例 #16
0
ファイル: Main.py プロジェクト: kamperud/NTNU
    def __init__(self):

        self.messageHandler = MessageHandler()
        self.communicator = Communicator(self.messageHandler)
        self.controller = Controller(self.communicator)
        self.messageHandler.setController(self.controller)

        print "MAIN initialize"

        ## test code.
        print "--------------"
        sleep(2)
        print "testing start"

        peer = Peer("78.91.5.10")
        message = Message("stillAlive", peer.IP, "", "", "", "")

        self.communicator.broadcast(message)

        #self.communicator.sendToOne(peer, message)

        print "testing complete"
        print "--------------"
コード例 #17
0
ファイル: Start.py プロジェクト: mathaholic/ferm-control
def main():

    while 1:
        print "Starting up connection"
        reader = Communicator("/dev/ttyS1", 9600, 30)
        reader.setDaemon(True)
        reader.start()
        writer = DataWriter.DatabaseWriter()

        while threading.active_count() > 0:
            time.sleep(5)                        
            if reader.IsValid():
                #Save our data off to the database if we've had an update
                #TODO: Change this so that instead of just taking this time as our value,
                #we only update the updated time on the ArduinoState whenever the primary temperature got a new value.  
                #Then we can use that value to update our database
                x = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
                writer.writeData([x, 
                                    reader.m_ArduinoState.m_PrimaryTemperature, 
                                    reader.m_ArduinoState.m_HeatingState, 
                                    reader.m_ArduinoState.m_CoolingState])
                print reader.ToString() 
        print "All done"
コード例 #18
0
 def getchannelstatus(self) -> json or None:
     """
     Load the status of available channels in the NVR
     :returns: json
     """
     try:
         body = [{"cmd": "GetChannelStatus", "action": 0}]
         param = {"cmd": "GetChannelStatus", "token": self.token}
         response = Communicator.send(self.url, data=body, params=param)
         if response is not None:
             return response.text
         else:
             return None
     except Exception as e:
         print("Get Channel Status Error \n", e)
         raise
コード例 #19
0
 def logout(self) -> bool:
     """
     Log out of the NVR
     :return: bool
     """
     try:
         body = [{"cmd": "Logout", "action": 0}]
         param = {"cmd": "Logout", "token": self.token}
         response = Communicator.send(self.url, data=body, params=param)
         if response is not None:
             data = json.loads(response.text)[0]
             code = data["value"]["rspCode"]
             print("Logout ", code)
             return code == 200
     except Exception as e:
         print("Logout Error \n", e)
         raise
コード例 #20
0
def main():

    while 1:
        print "Starting up connection"
        reader = Communicator("/dev/ttyS1", 9600, 30)
        reader.setDaemon(True)
        reader.start()
        writer = DataWriter.DatabaseWriter()

        while threading.active_count() > 0:
            time.sleep(5)
            if reader.IsValid():
                #Save our data off to the database if we've had an update
                #TODO: Change this so that instead of just taking this time as our value,
                #we only update the updated time on the ArduinoState whenever the primary temperature got a new value.
                #Then we can use that value to update our database
                x = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
                writer.writeData([
                    x, reader.m_ArduinoState.m_PrimaryTemperature,
                    reader.m_ArduinoState.m_HeatingState,
                    reader.m_ArduinoState.m_CoolingState
                ])
                print reader.ToString()
        print "All done"
コード例 #21
0
 def __init__(self, conn, f_ctrl):
     Communicator.__init__(self, conn)
     self.f_ctrl = f_ctrl
     self.lastPacketTime = time.time()
コード例 #22
0
ファイル: function_opt.py プロジェクト: stjordanis/smarties
            # increase the self.percSuccess average over last 10 steps
            self.percSuccess = .9 * self.percSuccess + 0.1
        else:
            # decrease the self.percSuccess average over last 10 steps
            self.percSuccess = .9 * self.percSuccess
        # this function should return if time-series is over
        episodeIsOver = self.t > 200
        return episodeIsOver


if __name__ == '__main__':
    # state is x, v, angle, omega, cos(angle), sin(angle), action is Fx
    # This specifies states and action dimensionality
    dimState = 2  # how many state variables
    dimAction = 1  # how many action variables
    comm = Communicator(dimState, dimAction)
    # create environment defined above
    env = EnvironmentForRL()

    # Define action space:
    actionMax = 1.9 * np.ones(dimAction)
    actionMin = 0.1 * np.ones(dimAction)
    isActBounded = True
    comm.set_action_scales(actionMax, actionMin, bounded=isActBounded)

    bObservable = np.ones(dimState)
    bObservable[0] = 0
    comm.set_state_observable(bObservable)

    while 1:  #train loop, each new episode starts here
        env.reset()  # (slightly) random initial conditions are best
コード例 #23
0
        state = np.copy(self.u)
        state.resize(6)
        state[4] = np.cos(self.u[2])
        state[5] = np.sin(self.u[2])
        return state

    def getReward(self):
        #double angle = std::fmod(u.y3, 2*M_PI); #swingup
        #angle = angle<0 ? angle+2*M_PI : angle;
        #return fabs(angle-M_PI)<M_PI/6 ? 1 : 0;
        return 1 - (abs(self.u[2]) > np.pi / 15 or abs(self.u[0]) > 2.4)


if __name__ == '__main__':
    # state is x, v, angle, omega, cos(angle), sin(angle), action is Fx
    comm = Communicator(6, 1)
    env = CartPole()
    #Here, the action space is in [-10, 10] and is bounded.
    comm.set_action_scales(10 * np.ones(1), -10 * np.ones(1), bounded=True)
    #Agent knows cos and sin of angle, angle itself is hidden
    bObservable = np.ones(6)
    bObservable[2] = 0
    comm.set_state_observable(bObservable)

    while 1:  #train loop, each new episode starts here
        env.reset()  # (slightly) random initial conditions are best
        # send initial state along with info that it is an initial state:
        comm.sendInitState(env.getState())

        while 1:  #simulation loop
            action = comm.recvAction()
コード例 #24
0
ファイル: Main.py プロジェクト: BennetBartmann/Pallaber-Bot
from Counter import Counter
from defaultlib import defaultlib
from Query import Query
from Citations import Citations
import Connection
import traceback

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

irc.connect((Connection.network, Connection.port))
print irc.recv(4096)
defaultlib(irc)
irc.send("NICK " + Connection.nick + "\r\n")
irc.send("USER botty botty botty :IRC Bot\r\n")
irc.send("JOIN " + Connection.channel + "\r\n")
communicator = Communicator()

modules = []
count = Counter(communicator)
cite = Citations(communicator)
communicator.counter = count

modules.append(UserList(communicator))
modules.append(count)
modules.append(Seen(communicator))
modules.append(Title(communicator))
modules.append(Query(communicator))
modules.append(cite)

while True:
    data = irc.recv(4096)
コード例 #25
0
ファイル: Robot.py プロジェクト: JackBlair87/HackTJ2021
class Robot:
    def __init__(self, image, x=0.0, y=0.0, angle=0):
        pygame.sprite.Sprite.__init__(self)
        self.image = image.convert_alpha()
        self.size = self.image.get_size()
        self.left_encoder_counts = 0
        self.right_encoder_counts = 0
        self.location = (x, y)
        #^separate things above here into just the draw_robot method
        self.angle = angle
        self.dataPackets = [InfoPacket(angle=90),
                            InfoPacket(angle=90)
                            ]  #angles here should be changed to 0?
        self.communicator = Communicator(enabled=False)
        self.communicator.initiate_bluetooth()
        self.state = State.stop
        self.communicator.transmit_info(self.state)
        self.logger = Logger("Robot")
        self.max_dist = 150
        self.last_index = -1
        self.rectifier = None
        self.last_state_switch_time = int(round(time.time() * 1000))

    def add_data(self):
        new_packet = self.communicator.recieve_info(self.state)
        if new_packet != None:
            self.dataPackets.append(new_packet)
            self._update_location()
            self.logger.log(self.dataPackets[-1])
            self.logger.log('adding data to robot')
            return self.generate_points()  #returns two points

    def quitProgram(self):
        self.communicator.transmit_info(State.stop)
        self.communicator.deactivate_bluetooth()

    def _update_location(self):
        if self.rectifier is None and len(
                self.dataPackets
        ) >= 3:  # when we get the first new data, initialize
            last_packet = self.dataPackets[-1]
            self.rectifier = Rectifier(
                start_angle=last_packet.rotation,
                start_l_encoder=last_packet.left_encoder_counts,
                start_r_encoder=last_packet.right_encoder_counts)

        self.logger.log('rectifier logs:')
        last_packet = self.dataPackets[-1]
        self.logger.log(f'last packet: {last_packet}')
        last_packet.rotation = self.rectifier.offset_angle(
            last_packet.rotation)
        last_packet.left_encoder_counts = self.rectifier.offset_l_encoder(
            last_packet.left_encoder_counts)
        last_packet.right_encoder_counts = self.rectifier.offset_r_encoder(
            last_packet.right_encoder_counts)

        self.logger.log(last_packet.rotation, last_packet.left_encoder_counts,
                        last_packet.right_encoder_counts)

        delta_x, delta_y, angle = self._calculate_delta_location_change()
        self.logger.log("delta_x, delta_y, delta_angle:", delta_x, delta_y,
                        angle)
        self.location = (self.location[0] + delta_x,
                         self.location[1] + delta_y)
        self.logger.log('new position:', self.location[0], self.location[1],
                        self.angle)

    def _calculate_delta_location_change(self):
        differenceR = self.dataPackets[
            -1].right_encoder_counts - self.dataPackets[
                -2].right_encoder_counts  #Find the difference between last transmittion
        differenceL = self.dataPackets[
            -1].left_encoder_counts - self.dataPackets[-2].left_encoder_counts
        difference_average = (differenceL + differenceR) / 2
        if self.dataPackets[-1].state == State.turn_left or self.dataPackets[
                -1].state == State.turn_right:  #Or the difference between last angle if rotation
            delta_x = 0
            delta_y = 0
            angle = self.dataPackets[-1].rotation
        elif self.dataPackets[-1].state == State.forward or self.dataPackets[
                -1].state == State.reverse:
            delta_r_cm = difference_average * WheelInfo.WHEEL_CM_PER_COUNT
            angle = self.dataPackets[-1].rotation

            #if it's going reverse, calculate it like it's going forward backward
            if self.dataPackets[-1].state == State.reverse:
                angle + 180

            self.logger.log("angle: " + str(angle))
            angle_radians = math.radians(angle)
            self.logger.log("angle_radians: " + str(angle_radians))

            #if we adjusted the angle value bc we're going backward, undo that when we return delta_angle
            if self.dataPackets[-1].state == State.reverse:
                angle - 180

            #transform the data with the angle
            delta_x = delta_r_cm * math.cos(math.radians(angle))
            delta_y = delta_r_cm * math.sin(math.radians(angle))
        else:
            delta_x = 0
            delta_y = 0
            #angle = 0
            angle = self.dataPackets[-1].rotation  #experimental

        return delta_x, delta_y, angle

    def generate_points(self):
        if self.dataPackets[-1] != None:
            distForward = self.dataPackets[-1].front_distance  #in cm
            distRight = self.dataPackets[-1].right_distance  #in cm

            if distForward >= 0 and distForward < self.max_dist and distRight >= 0 and distRight < self.max_dist:
                forward = (distForward * math.cos(math.radians(self.angle)),
                           distForward * math.sin(math.radians(self.angle)))
                right = (distRight * math.cos(math.radians(self.angle - 90)),
                         distRight * math.sin(math.radians(self.angle - 90)))
                return (forward, right)
            elif distForward >= 0 and distForward < self.max_dist:
                return ((distForward * math.cos(math.radians(self.angle)),
                         distForward * math.sin(math.radians(self.angle))))
            elif distRight >= 0 and distRight < self.max_dist:
                return ((distRight * math.cos(math.radians(self.angle - 90)),
                         distRight * math.sin(math.radians(self.angle - 90))))
            else:
                return ()

    def get_state_from_encoder(self, r, l):
        difference = r - l
        if math.abs(difference) < 2:
            if r > 0 and l > 0:
                return State.forward
            else:
                return State.reverse
        elif r > l:
            return State.turn_left
        elif l > r:
            return State.turn_right
        else:
            raise Exception("get_state_from_encoder method()")

    def front_is_clear(self):
        # self.logger.log("Rahel needs to work on this method BIG SMH")
        return self.dataPackets[-1].front_distance > 20

    def right_is_clear(self):
        return self.dataPackets[-1].right_distance > 20

    def change_state(self, new_state=State.stop):
        self.state = new_state
        self.communicator.transmit_info(self.state)
        self.logger.log("State changed to: " + State.all_states[self.state])

    def sweep(self):
        self.logger.log("sweep method")
        if int(round(time.time() * 1000)) - self.last_state_switch_time > 250:
            self.logger.log("sweep method testing")
            self.last_state_switch_time = int(round(time.time() * 1000))
            if self.front_is_clear():
                self.state = State.forward
            else:
                self.state = State.turn_right

        self.communicator.transmit_info(self.state)
        self.logger.log("State changed to: " + State.all_states[self.state])
コード例 #26
0
ファイル: heybuddy.py プロジェクト: yamatt/python-hellobuddy
class application :
	def __init__(self):
		#init threading
		gobject.threads_init()
		#keep track of the window size
		self.window_height=0
		self.window_width=0
		self.window_is_hidden = False
		self.has_status_icon = False
		#keep track of the initial conversation id so that conversations don't colide
		self.conversation_id="0"
		#keep track of the filters
		self.filters ={'users':[],'strings':[]}
		self.options={'run_as_tray_app':False,'context_backwards':False,'no_avatars':False,'notifications':True,'notify_replies':False}
		#keep track of the direct_message requests
		self.last_direct_message_time=0
		#something something direct message
		self.is_direct_message_mode=False
		self.direct_message_to=None
		self.waiting_requests=0
		self.is_first_dents = True
		#keep track of the respond to id
		self.respond_to_id=0
		self.pre_group_page=None
		self.pre_user_page=None
		#keep track of the last time statuses where pulled
		self.last_get_statuses = 0
		#what are the assets?
		asset_dir = 'assets'
		heybuddy_dir = os.path.dirname( os.path.realpath( __file__ ) )
		self.readme_file = os.path.join(heybuddy_dir,'README.txt')
		self.standard_icon_path = os.path.join(heybuddy_dir,asset_dir,'icon.png')
		self.direct_icon_path = os.path.join(heybuddy_dir,asset_dir,'direct_icon.png')
		self.networking_icon_path = os.path.join(heybuddy_dir,asset_dir,'icon1.png')
		self.throbber_icon_path = os.path.join(heybuddy_dir,asset_dir,'throbber.gif')
		self.default_icon_path = self.standard_icon_path
		self.conf = Configuration(app_name)
		#has the account info been authenticated?
		self.credentials_verified = self.conf.get_bool('access', 'credentials_verified')
		self.xmlprocessor = XMLProcessor()
		#create a regex to replace parts of a dent
		self.regex_tag = re.compile("(^| )#([\w-]+)", re.UNICODE)
		self.regex_group = re.compile("(^| )!([\w-]+)")
		self.regex_user=re.compile("(^|[^A-z0-9])@(\w+)")
		self.regex_url=re.compile("(http[s]?://.*?)(\.$|\. |\s|$)",re.IGNORECASE)
		#get the initial dents
		self.initial_dents = self.conf.get('settings','initial_dents',default='20' )
		self.dent_limit = int(self.initial_dents)*2
		#get the pull time
		self.pull_time = self.conf.get('settings','pull_time',default='60')
		self.pull_time_changed_bool = False
		self.pull_time_mentions = False
		#build the gui
		self.build_gui()
		
		#where is the certs file?
		ca_certs_files = [
			"/etc/ssl/certs/ca-certificates.crt",
			"/etc/ssl/certs/ca-bundle.crt",
			]
		#what if there isn't a cert_file
		cert_file=None
		#determine the certs_file
		for f in ca_certs_files:
			if os.path.exists(f):
				cert_file=f
				break	
		
		#create the communicator
		self.comm = Communicator(app_name, cert_file)
		self.comm.connect('statusesXML',self.process_statusesXML,self.dentspage)
		self.comm.connect('mentionsXML',self.process_statusesXML,self.mentionspage)
		self.comm.connect('favoritesXML', self.process_statusesXML,self.favoritespage)
		self.comm.connect('group-statusesXML',self.process_statusesXML,self.grouppage)
		self.comm.connect('user-statusesXML',self.process_statusesXML,self.userpage)
		self.comm.connect('direct_messagesXML',self.process_statusesXML,self.directspage,True)
		self.comm.connect('conversationXML',self.process_conversationXML)
		self.comm.connect('userXML',self.process_userXML)
		self.comm.connect('groupXML',self.process_groupXML)
		self.comm.connect('new-statusXML',self.process_new_statusXML)
		self.comm.connect('redent-statusXML',self.process_new_statusXML)
		self.comm.connect('user_is_friendXML',self.process_user_is_friendXML)
		self.comm.connect('user_is_memberXML',self.process_user_is_memberXML)
		self.comm.connect('friendshipXML',self.process_friendshipXML)
		self.comm.connect('exception-caught',self.process_communication_exception)
		self.comm.connect('widget-image',self.process_widget_image)
		self.comm.connect('direct-messageXML',self.process_new_directXML)
		self.comm.connect('verify_credentialsXML',self.process_verifycredentialsXML)
		self.comm.connect('configXML',self.process_configXML)
		#create an image cacher thingy
		self.imagecache = ImageCache()
		self.imagecache.set_disabled( self.conf.get_bool_option('no_avatars') )
		self.imagecache.connect('get-widget-image', self.get_widget_image)
	
		#Create notify-er if has pynotify
		if has_pynotify:
			self.notify = Notify()

		#align the window
		self.align_window()
		# do we need to create the status icon
		if self.conf.get_bool_option('run_as_tray_app'):
			self.create_status_icon()
		
	def build_gui(self):
		#build the GUI 
		self.mainwindow=MainWindow.MainWindow(app_name,version,branch)
		try:
			self.mainwindow.set_icon_from_file(self.default_icon_path)
		except:
			pass
		self.mainwindow.set_textlimit( self.conf.textlimit() )	
		self.mainwindow.set_ctrl_enter( self.conf.get_bool_option('ctrl_enter') )
		self.mainwindow.connect('quit', self.quit_triggered )
		self.mainwindow.connect('window-to-tray', self.window_to_tray )
		self.mainwindow.connect('update-status',self.update_status)
		self.mainwindow.connect('get-conversation',self.get_conversation)
		self.mainwindow.connect('show-user',self.get_user_info)
		self.mainwindow.connect('show-group',self.get_group_info)
		self.mainwindow.connect('notebook-page-change',self.page_change)
		self.mainwindow.connect('follow-user',self.follow_user)
		self.mainwindow.connect('join-group',self.join_group)
		self.mainwindow.connect('clear-respond-to-id',self.clear_respond_to_id)
		#keep track of the window size
		self.mainwindow.connect('size-allocate', self.window_size_allocate)
		#self.mainwindow.connect('window-state-event', self.mainwindow_state_event)
		self.mainwindow.connect('delete-event', self.mainwindow_delete_event)
		
		# local function to create a closeable tab label for closeable tabs
		def closeable_tab_label(caption, tab):
			tablabel = gtk.HBox(False,2)
			tablabel.pack_start(gtk.Label(caption),False,False,0)
			closebutton = gtk.Button()
			closeicon = gtk.Image()
			closeicon.set_from_stock(gtk.STOCK_CLOSE,gtk.ICON_SIZE_MENU)
			closebutton.set_image(closeicon)
			closebutton.set_relief(gtk.RELIEF_NONE)
			tinybutton_style = gtk.RcStyle()
			tinybutton_style.xthickness = 0
			tinybutton_style.ythickness = 0
			closebutton.modify_style(tinybutton_style)
			if tab != None:	# if this isn't a mock-add
				closebutton.connect('clicked',tab.close)
			#don't show a tooltip on maemo
			if not has_hildon:
				closebutton.set_tooltip_text(_("Close"))
			tablabel.pack_start(closebutton,False,False,0)
			tablabel.show_all()
			return tablabel

		# do a mock add of dentspage, with a close label, so as to determine height needed for uncloseable tabs' labels, then break it all down again
		# this is ridiculously hacky, but it works, and doesn't leave anything behind
		self.dentspage = ScrollPage()
		self.mock_label = closeable_tab_label(_("Dents"),None)
		self.mainwindow.notebook.append_page(self.dentspage,self.mock_label)
		self.mainwindow.show_all() # we have to do this so the tab gets actualised, and thus gets a height
		min_tab_height = self.mock_label.allocation.height
		self.mainwindow.hide_all()
		self.mainwindow.notebook.remove_page(-1)
		del self.mock_label
		
		# local function to create a label the same height as the closeable tabs' labels
		def uncloseable_tab_label(caption):
			tablabel = gtk.Label(caption)
			tablabel.set_size_request(-1,min_tab_height)
			tablabel.show()
			return tablabel
		
		# create and add all of the pages
		self.dentspage = ScrollPage()
		self.mainwindow.notebook.append_page(self.dentspage,uncloseable_tab_label(_("Dents") ) )
		
		self.mentionspage = ScrollPage()
		self.mainwindow.notebook.append_page(self.mentionspage,uncloseable_tab_label(_("Mentions")) )

		self.favoritespage = ScrollPage()
		self.mainwindow.notebook.append_page(self.favoritespage,uncloseable_tab_label(_("Favorites")) )
		
		self.directspage = ScrollPage()
		self.mainwindow.notebook.append_page(self.directspage,uncloseable_tab_label(_("Directs")) )
		
		#make the conversation page
		self.contextpage=ContextPage()
		self.contextpage.connect('context-page-hide',self.hide_contextpage)
		#add the contextpage
		context_label = closeable_tab_label(_("Context"), self.contextpage)
		self.mainwindow.notebook.append_page(self.contextpage, context_label)
		
		#create a user page
		self.userpage=UserPage()
		self.userpage.connect('user-page-hide',self.hide_userpage)
		self.userpage.connect('follow-user',self.follow_user)
		self.userpage.connect('direct-clicked',self.direct_clicked)
		self.userpage.connect('open-link',self.open_link)
		self.userpage.connect('block-create',self.block_create)
		self.userpage.connect('block-destroy',self.block_destroy)
		
		#add the userpage
		user_label = closeable_tab_label(_("User"),self.userpage ) 
		self.mainwindow.notebook.append_page(self.userpage, user_label)
		
		#create a Group page
		self.grouppage=GroupPage()
		self.grouppage.connect('group-page-hide',self.hide_grouppage)
		self.grouppage.connect('join-group',self.join_group)
		self.grouppage.connect('open-link',self.open_link)

		#add the Grouppage
		group_label = closeable_tab_label(_("Group"),self.grouppage ) 
		self.mainwindow.notebook.append_page(self.grouppage, group_label)
		
		#create and add the account page
		self.settingspage = SettingsPage(has_hildon,has_pynotify)
		self.settingspage.set_initial_dents( self.initial_dents )
		self.settingspage.set_pull_time(self.pull_time)
		#update the configuration of the settings
		self.settingspage.connect('update-account',self.update_account)
		self.options['ctrl_enter'] = self.conf.get_bool_option('ctrl_enter')
		self.settingspage.set_ctrl_enter( self.options['ctrl_enter']	)
		self.options['run_as_tray_app'] = self.conf.get_bool_option('run_as_tray_app')
		self.settingspage.set_run_as_tray_app( self.options['run_as_tray_app']	)
		self.options['context_backwards']	= self.conf.get_bool_option('context_backwards')
		self.settingspage.set_context_backwards( self.options['context_backwards'] )
		self.options['no_avatar']= self.conf.get_bool_option('no_avatars')
		self.settingspage.set_no_avatars( self.options['no_avatar'] )
		self.options['api_retweet'] = self.conf.get_bool_option('api_retweet')
		self.settingspage.set_api_retweet( self.options['api_retweet']	)
		self.options['notifications']= self.conf.get_bool_option('notifications')
		self.settingspage.set_notifications( self.options['notifications'] )
		self.options['notify_replies']= self.conf.get_bool_option('notify_replies')
		self.settingspage.set_notify_replies( self.options['notify_replies'] )
		link_color = self.conf.get('settings','link_color',default='blue')
		self.settingspage.set_link_color( link_color )
		self.theme_link_color(link_color)
		#connect the setting signals
		self.settingspage.connect('option-run-as-tray-app', self.option_changed, 'run_as_tray_app')
		self.settingspage.connect('option-ctrl-enter', self.option_changed, 'ctrl_enter')
		self.settingspage.connect('option-context-backwards',self.option_changed, 'context_backwards')
		self.settingspage.connect('option-no-avatars',self.option_changed, 'no_avatars')
		self.settingspage.connect('option-api-retweet', self.option_changed, 'api_retweet')
		self.settingspage.connect('option-notifications',self.option_changed, 'notifications')
		self.settingspage.connect('option-notify-replies',self.option_changed, 'notify_replies')
		self.settingspage.connect('initial-dents',self.set_initial_dents)
		self.settingspage.connect('pull-time',self.set_pull_time)
		self.settingspage.connect('link-color',self.set_link_color)
		self.settingspage.connect('add-string-filter', self.add_string_filter )
		self.settingspage.connect('remove-string-filter', self.remove_string_filter )
		self.settingspage.connect('add-user-filter', self.add_user_filter )
		self.settingspage.connect('remove-user-filter', self.remove_user_filter )
		#add the settings to the mainwindow
		self.mainwindow.add_notebook_page(self.settingspage,uncloseable_tab_label(_("Settings") ) )
		#create and add the about page
		about = About(version,branch,self.standard_icon_path,self.readme_file)
		about.connect('open-link',self.open_link)
		self.mainwindow.add_notebook_page( about, uncloseable_tab_label(_("About") ) )
		self.mainwindow.show_some()
		#hide some stuff
		self.grouppage.hide_all()
		self.userpage.hide_all()
		self.contextpage.hide_all()
		
	def align_window(self):
		#try to set the mainwindows size based on conf info
		try:
			w = int( self.conf.get('window_info','width') )
			h = int( self.conf.get('window_info','height') )
			self.mainwindow.resize(w,h)
		except:
			pass
		try:
			x = int( self.conf.get('window_info','x') )
			y = int( self.conf.get('window_info','y') )
			self.mainwindow.move(x,y)
		except:
			pass
		
		#get the filters
		try: 
			#read the filters
			filters = self.conf.get('settings','filters',True)
			#the filters should be an array
			if len(filters):
				#self.filters = filters
				self.filters['users']	= filters['users']
				self.filters['strings']	= filters['strings']
				#set the filters
				self.settingspage.set_string_filters( self.filters['strings'] )
				self.settingspage.set_user_filters( self.filters['users'] )
		except:
			pass
	
	def create_status_icon(self):
		if not self.has_status_icon:
			#create the statusicon
			self.statusicon = StatusIcon()
			self.statusicon.connect('activate', self.status_clicked )
			self.statusicon.connect('quit-selected',self.quit_app)
			self.statusicon.set_icon( self.standard_icon_path )
		self.statusicon.set_property("visible",True)
		self.has_status_icon=True
	
	def destroy_status_icon(self):
		self.statusicon.set_property("visible",False)
		self.has_status_icon=False
		
	def update_account(self, widget, n, p, s):
		#check if these are valid
		self.mainwindow.set_message(_("Authenticating account..."))
		self.increment_requests()
		self.comm.verify_credentials(n, p, s)
			
	def increment_requests(self):
		self.waiting_requests+=1
		if self.waiting_requests==1:
			try:
				self.mainwindow.set_icon_from_file(self.networking_icon_path)
			except:
				pass
			try:
				self.mainwindow.set_throbber(self.throbber_icon_path)
			except:
				pass
			if self.has_status_icon:
				self.statusicon.set_icon( self.networking_icon_path)
				
	def decrement_requests(self):
		self.waiting_requests-=1
		if self.waiting_requests==0:
			try:
				self.mainwindow.set_icon_from_file(self.default_icon_path)
			except:
				pass
			try:
				self.mainwindow.set_throbber(self.default_icon_path)
			except:
				pass
			if self.has_status_icon:
				self.statusicon.set_icon( self.default_icon_path )
		if self.waiting_requests<0:
			self.waiting_requests=0
	
	def valid_account_info(self, n, p, s):
		self.conf.name( n )
		self.conf.password( p )
		self.conf.service( s )
		self.conf.save()
		#update the comm
		self.comm.set_name_and_password( n,p )
		self.comm.set_service( s )
		
	def get_statuses(self,count="20"):
		if self.credentials_verified:
			#do some time handling for the good doctor
			now = time.time()
			if now - self.last_get_statuses > 2*self.pull_time:
				count = self.initial_dents
			self.last_get_statuses = now
			self.increment_requests()
			self.comm.get_statuses(count=count, since=highest_id['dent_previous'])
			#clean up the garbage
			gc.collect()
	
	def get_mentions(self,count="20"):
		if self.credentials_verified:
			self.increment_requests()
			self.comm.get_mentions(count=count,since=highest_id['mention_previous'])

	def get_favorites(self):
		if self.credentials_verified:
			self.increment_requests()
			self.comm.get_favorites()
	
	def get_direct_messages(self):
		if self.credentials_verified:
			now = time.time()
			#NOTE this could be changed to 3 minutes just setting it 
			#this way for now
			#has it been 3 times the pull time?
			if now - (3 * int(self.pull_time) ) > self.last_direct_message_time:
				self.increment_requests()
				self.comm.get_direct_messages(highest_id['direct_previous'])	
				self.last_direct_message_time=now
	
	def run(self, enable_logging=False):
		self.logging = enable_logging
		#start the communicator
		self.comm.start()
		self.main_loop = gobject.MainLoop()
		
		#we have to temporarily show the various pages or nothing works
		''' why the f**k do I need to do this? '''
		self.mainwindow.set_notebook_page(DIRECT)
		self.mainwindow.set_notebook_page(MENTION)
		self.mainwindow.set_notebook_page(FAVORITE)
		self.mainwindow.set_notebook_page(DENT)
		#send the service to the settings page
		self.settingspage.set_service(self.conf.service() )
		#did the conf read a name and password?
		if( self.conf.name() !="" and self.conf.password()!=""):
			if self.credentials_verified:
				self.comm.set_name_and_password( self.conf.name(),self.conf.password() )
				self.comm.set_service( self.conf.service() )
				#fill the Account tab name/pw fields to show the user that they're logged in
				self.settingspage.set_name(self.conf.name())
				self.settingspage.set_password(self.conf.password())
				#add a function to the main loop
				gobject.timeout_add(int(self.pull_time)*1000, self.update_statuses )
				gobject.timeout_add(int(self.pull_time)*1500, self.update_mentions )
				#add a timout to get dents
				gobject.timeout_add(500,self.get_statuses,self.initial_dents )
				gobject.timeout_add(600,self.get_mentions,self.initial_dents )
			#gobject.timeout_add(1000,self.get_direct_messages )
		else:
			#set the focus on the account page; the last page
			self.mainwindow.set_notebook_page(ACCOUNT)
		
		self.mainwindow.run()
		self.main_loop.run()
		#if we ever get here, we should quit

	def update_statuses(self):
		self.get_statuses()
		if(self.pull_time_changed_bool):
			self.pull_time_changed_bool= False
			gobject.timeout_add(int(self.pull_time)*1000, self.update_statuses)
			return False
		return True
	
	def update_mentions(self):
		self.get_mentions()
		if(self.pull_time_mentions):
			self.pull_time_mentions=False
			gobject.timeout_add(int(self.pull_time)*1500, self.update_mentions)
			return False
		return True
	
	def update_direct_messages(self):
		self.get_direct_messages()
		return True
	
	def update_status(self,widget,text):
		self.increment_requests()
		#remove newlines from text
		text=text.replace("\n","")
		#is this direct message mode?
		if self.is_direct_message_mode:
			self.comm.send_direct_message(text,self.direct_message_to)
			self.set_is_direct_message_mode(False)
		else:
			self.comm.send_update_status(text,self.respond_to_id)
		self.clear_respond_to_id()
		
	def quit_app(self,widget=None):
		#quit the communicator loop
		self.comm.quit()
		#quit the main loop
		self.main_loop.quit()
		
	def get_widget_image(self,imagecache,image):
		self.comm.get_widget_image(image)
	
	def get_conversation(self,id,conversation_id):
		if self.credentials_verified:
			self.increment_requests()
			self.comm.get_conversation(id,conversation_id)
	
	def parse_profile(self, profile=None, name=None ):
		#is this a remote user?
		remote_user = True
		service = ''
		#did we get a name?
		if profile!=None:
			bits = profile.rsplit("/")
			service = bits[2]
			if name==None:
				name = bits[3]
				#if there is no name, use the first subdomain as a name
				if name==None:
					dot_split = service.split(".")
					name = dot_split[0]
			if service==self.conf.service():
				remote_user = False
		else:
			remote_user = False
		return {'service':service, 'remote':remote_user,'name':name}
	
	def get_user_info(self, profile=None, name=None):
		#parse the info
		result = self.parse_profile( profile, name )
		#is this a remote user?
		remote_user = result['remote']
		name = result['name']
		service = result['service']
		
		#is this not a remote user?
		if not remote_user:
			if self.credentials_verified:
				self.increment_requests()
				self.comm.get_user_info(name)
				self.increment_requests()
				self.comm.get_user_statuses(name)
			return
	
		self.increment_requests()
		self.comm.get_remote_user_info(service,name)
		self.increment_requests()
		self.comm.get_remote_user_statuses(service,name)
		
	
	def get_group_info(self,name):
		if self.credentials_verified:
			self.increment_requests()
			self.comm.get_group_info(name)
	
	def follow_user(self,widget,name,bool):
		if self.credentials_verified:
			if bool:
				self.comm.friendship_create(name)
			else:
				self.comm.friendship_destroy(name)
	
	def join_group(self,widget,name,bool):
		if self.credentials_verified:
			if bool:
				self.comm.group_join(name)
			else:
				self.comm.group_leave(name)
	
	def process_friendshipXML(self,widget,text):
		pass
	
	def page_change(self,widget,old_id,new_id):
		if new_id==MainWindow.DIRECT:
			self.get_direct_messages()
		elif new_id==MainWindow.FAVORITE:
		    self.get_favorites()
		else:
			if self.is_direct_message_mode:
				self.set_is_direct_message_mode(False)
		#should we clear any warning message?
		self.mainwindow.clear_message()
	
	def process_userXML(self,comm,text):
		self.decrement_requests()
		data = self.xmlprocessor.get_user_info(text)
		if data['profile_image_url']!=None:
			self.imagecache.add_image_to_widget(data['profile_image_url'],self.userpage)
		self.userpage.set_user_data(data)
	
	def process_groupXML(self,comm,text):
		self.decrement_requests()
		data = self.xmlprocessor.get_group_info(text)
		if data['stream_logo']!=None:
			self.imagecache.add_image_to_widget(data['stream_logo'],self.grouppage)
		'''#is this user a member of this group
		self.increment_requests()
		self.comm.get_user_is_member(data['id'])'''
		self.increment_requests()
		self.comm.get_group_statuses(data['id'])
		self.grouppage.set_group_data(data)
	
	def process_user_is_friendXML(self,comm,text):
		self.decrement_requests()
		is_friend = self.xmlprocessor.get_user_is_friend(text)
		self.mainwindow.display_user_is_friend( is_friend )
	
	def process_user_is_memberXML(self,comm,text):
		self.decrement_requests()
		is_member = self.xmlprocessor.get_user_is_member(text)
		self.mainwindow.display_user_is_member( is_member )
	
	def process_new_directXML(self,comm,text):
		#a update status was sent
		self.decrement_requests()
		#clear the textview thing
		self.mainwindow.emit_update_textview_responsed()
	
	def process_new_statusXML(self,comm,text):
		#a update status was sent
		self.decrement_requests()
		#clear the textview thing
		self.mainwindow.emit_update_textview_responsed()
		#there is one status and it is the DOM
		status = self.xmlprocessor.get_dom(text)
		data = self.xmlprocessor.get_dent_data(status)
		data['markup'] = self.markup_dent_text(data['text'])
		#add the dent
		dent = self.connect_dent(data,self.dentspage)

	def process_verifycredentialsXML(self, object, text, data):
		#actually, if we are here, the authorization worked!
		self.conf.set('access', 'credentials_verified', True)
		self.credentials_verified = True
		self.mainwindow.message_label.hide()
		(n, p, s) = data
		self.valid_account_info(n, p, s)
		#get the config
		self.comm.get_config()
		#switch to the dents page
		self.mainwindow.set_notebook_page(DENT) 
		self.get_statuses()
		self.get_mentions()

	def process_conversationXML(self,object,text,conversation_id):
		self.decrement_requests()
		#is this the current conversation Id? if not, then do nothing
		#convert to int because there is a problem with string comparison
		'''is one of the strings unicode?'''
		if int(self.conversation_id)==int(conversation_id):
			#get the status
			status = self.xmlprocessor.get_dom(text)
			data = self.xmlprocessor.get_dent_data(status)
			data['markup']=self.markup_dent_text(data['text'])
			#since this is a conversation, we can get rid of the in_reply_to_screen_name
			data['in_reply_to_screen_name']=None
			#tell the mainWindow to add the dent
			dent = self.connect_dent(data,self.contextpage,True, self.options['context_backwards'] )
			if data['in_reply_to_id']!=None:
				#recursively get in_reply_to_ids
				self.get_conversation(id=data['in_reply_to_id'],conversation_id=conversation_id)

	def process_configXML(self, object, text):
		self.decrement_requests()
		server = self.xmlprocessor.get_server_config(text)
		print server
		self.conf.textlimit( server['textlimit'] )
		self.conf.save()
		self.mainwindow.set_textlimit( server['textlimit'] )

	def connect_dent(self,data,target_page,is_conv=False,conv_backwards=False,is_direct_dent=False):
		#make the dent
		dent = Dent(data,is_direct=is_direct_dent)
		if target_page.dentScroller.add_dent( dent, is_conv, conv_backwards ):
			dent.connect('group-clicked', self.view_group)
			dent.connect('reply-clicked', self.reply_clicked)
			dent.connect('direct-clicked', self.direct_clicked)
			dent.connect('view-conversation-clicked', self.view_conversation)
			dent.connect('user-clicked', self.view_user_name)
			dent.connect('profile-clicked', self.view_user_profile)
			dent.connect('id-clicked', self.view_id)
			dent.connect('text-label-clicked',self.dent_text_clicked)
			dent.connect('redent-clicked',self.redent_clicked)
			dent.connect('favorite-clicked',self.favorite_clicked)
			dent.connect('unfavorite-clicked',self.unfavorite_clicked)
			dent.connect('open-link',self.open_link)
			if target_page!=self.userpage:
				#get the image for this dent
				self.imagecache.add_image_to_widget(data['profile_image_url'],dent)
			return True
		else:
			dent.destroy()
			del dent
			return False
			
	def reply_clicked(self,dent,name):
		#set the text buffer
		self.mainwindow.update_textbuffer.set_text("@%s " % (name) )
		self.mainwindow.update_textview.grab_focus()
		#set the respond_to_id
		self.respond_to_id=dent.id

	
	def favorite_clicked(self,dent):
		id=dent.id
		self.comm.favorite(id)
	
	def unfavorite_clicked(self,dent):
		id=dent.id
		self.comm.unfavorite(id)
	
	def direct_clicked(self,widget,name):
		self.direct_message_to = name
		if type(widget).__name__=="Dent":
			self.respond_to_id=widget.id
		else:
			self.respond_to_id=None
		self.set_is_direct_message_mode(True,name)
		#we should be on the directs page
		self.mainwindow.set_notebook_page(DIRECT)
		#set the text buffer
		self.mainwindow.update_textbuffer.set_text("")
		self.mainwindow.update_textview.grab_focus()
	
	def view_conversation(self,dent,id):
		self.conversation_id=id
		self.pre_context_page=self.mainwindow.notebook_current_page
		self.contextpage.dentScroller.clear()
		self.contextpage.show_all()
		#get conversation starting with id
		self.get_conversation(id,id)
		self.mainwindow.notebook.set_current_page(CONTEXT)
		
	def view_user_profile(self, widget, profile_url, screen_name):
		self.get_user_info(profile=profile_url, name=screen_name)
		#self.get_user_info(screen_name)
		self.pre_user_page=self.mainwindow.notebook_current_page
		#make the user page checkbox insensitive
		self.userpage.disable()
		#show the page 
		self.userpage.show_all()
		#rehide its collapsed widgetbox, that doesn't need to be visible yet
		self.userpage.widgetbox_collapsed.hide()
		#clear the userpage stuff
		self.userpage.clear()
		#change to the user page
		self.mainwindow.set_notebook_page(USER)
			
	def view_id(self, widget, id):
		url = 'http://%s/notice/%s' % (self.conf.service(), id)
		self.open_link(None, url)
		
	def view_user_name(self, widget, screen_name):
		#TODO: merge this function with view_user_profile
		self.get_user_info(name=screen_name)
		#self.get_user_info(screen_name)
		self.pre_user_page=self.mainwindow.notebook_current_page
		#make the user page checkbox insensitive
		self.userpage.disable()
		#show the page 
		self.userpage.show_all()
		#rehide its collapsed widgetbox, that doesn't need to be visible yet
		self.userpage.widgetbox_collapsed.hide()
		#clear the userpage stuff
		self.userpage.clear()
		#change to the user page
		self.mainwindow.set_notebook_page(USER)	
			
	#does this function even get called? get rid of it
	def get_dent_time(self,text):
		#print text
		pass
		
	def markup_dent_text(self,text,is_notification=False):
		#process the text to markup
		#xmlencode the string
		text = self.xmlprocessor.xmlentities(text)
		#regex find the highlights
		markup = self.regex_tag.sub(r'\1#<b>\2</b>',text)
		#regex find users
		if has_hildon or links_unavailable or is_notification:
			markup = self.regex_group.sub(r'\1!<b>\2</b>',markup)
			markup = self.regex_user.sub(r'\1@<b>\2</b>',markup)
		else:
			#find urls
			markup = self.regex_url.sub(r'<a href="\1">\1</a>\2',markup)
			markup = self.regex_user.sub(r'\1@<a href="@\2">\2</a>',markup)
			markup = self.regex_group.sub(r'\1!<a href="!\2">\2</a>',markup)
		return markup
	
	def process_statusesXML(self,object,text,target_page,is_direct=False):
		#based on the target, what is the counting thingy?
		count_ref=None
		if target_page==self.dentspage:
			count_ref = "dent"
		elif target_page==self.mentionspage:
			count_ref = "mention"
		elif target_page==self.directspage:
			count_ref = "direct"
		self.decrement_requests()
		#set the "previous" count ref, do this now and get data twice
		if count_ref!=None:
			highest_id[count_ref+"_previous"] = highest_id[count_ref]
		#get a list of the statuses
		statuses = self.xmlprocessor.get_statuses(text,is_direct)
		#if there aren't any statuses, return
		if len(statuses)==0:
			return
		#reverse the statuses list
		statuses.reverse()
		dent_count=0
		reply_count=0
		#what is the highest id of the target index?	
		for status in statuses:
			filtered_status = False
			data = self.xmlprocessor.get_dent_data(status)

			if target_page==self.dentspage:
				#we should check for filtration
				filtered = self.check_filtered( data )
				filtered_status=filtered[0]
			if not filtered_status:
				#get the markup
				data['markup'] = self.markup_dent_text(data['text'])
				#did this dent connect
				if not self.connect_dent(data,target_page,is_direct_dent=is_direct):
					continue

				#if the target_page = 0 and not first_dents and not is_conf
				if target_page==self.dentspage and not self.is_first_dents:
					if "@"+self.conf.name() in data['markup']:					
						dent=self.connect_dent(data, self.mentionspage )
						reply_count+=1
						if self.options['notify_replies'] and has_pynotify:
							user = data['screen_name']
							#the message shouldn't be marked up if the server doesn't understand markup
							if notifier_reads_markup:
								message = self.markup_dent_text(data['text'],True)
							else:
								message = data['text']
							avatar = self.imagecache.get_image_path(data['profile_image_url'])
							self.notify.notify_reply(user,message,avatar)
					else:
						dent_count+=1
			else:
				self.log("filter #%s %s" %(data['status_id'], filtered[1] ) )
		
		#keep track of the last status_id			
		if count_ref!=None and data!=None:
				highest_id[count_ref]=data['status_id']
				
		self.is_first_dents=False
		#get the related images
		self.imagecache.get_images()
		#do we notify?
		if (dent_count!=0 or reply_count!=0) and has_pynotify and target_page==self.dentspage:
			if self.options['notifications']:
				if not self.options['notify_replies']:
					self.notify.notify_updates_replies(dent_count,reply_count,self.standard_icon_path)
				else:
					if dent_count!=0:
						self.notify.notify_updates(dent_count,self.standard_icon_path)
		#prune off the extra dents
		target_page.dentScroller.prune(self.dent_limit)
		
	def process_widget_image(self,comm,data,name):
		self.imagecache.widget_image_add(data,name)	
		
	def process_communication_exception(self,communicator,code,data,signal=None):
		if self.logging:
			self.log("code:%s, signal:%s" % (code,signal) )
		self.decrement_requests()
		#is there an error message?
		try:
			error_message = self.xmlprocessor.get_error_message(data)
		except:
			error_message = False
		if error_message and not code:
			self.mainwindow.set_message( error_message, MainWindow.ERROR_MESSAGE)
		elif code=='401': 
			#bad authorization
			self.mainwindow.set_notebook_page(MainWindow.ACCOUNT)
			error_message = _("Invalid Authorization: Your name or password is incorrect")
		elif code == '404':
			error_message = _("Service Not Found")
		elif code == '503':
			error_message = _("Service Unavailable")
		elif code == 'unknown error':
			error_message = _("Unknown Error")
		else:
			error_message = code
		#send the error message
		self.mainwindow.set_message(error_message, MainWindow.ERROR_MESSAGE)
		
		#a signal may have been passed from the comm
		if signal == "new-statusXML":
			#a dent was sent but it failed
			self.mainwindow.emit_update_textview_responsed(error=True)
	
	#functions to handle the filtration system
	def add_string_filter(self,winder,string):
		if not string in self.filters['strings']:
			self.filters['strings'].append(string)
			self.filters['strings'].sort()
			self.settingspage.set_string_filters( self.filters['strings'] )
		
	def remove_string_filter(self,winder,string):
		if string in self.filters['strings']:
			self.filters['strings'].remove(string)
			self.settingspage.set_string_filters( self.filters['strings'] )
			
	def add_user_filter(self,winder,user):
		if not user in self.filters['users']:
			self.filters['users'].append(user)
			self.filters['users'].sort()
			self.settingspage.set_user_filters( self.filters['users'] )
		
	def remove_user_filter(self,winder,user):
		if user in self.filters['users']:
			self.filters['users'].remove(user)
			self.settingspage.set_user_filters( self.filters['users'] )
	
	def check_filtered(self,data):
		if len(self.filters['users'])!=0 :
			#filter against the user
			for user in self.filters['users']:
				if data['screen_name'].lower()==user.lower():
					return (True, "user: %s" % data['screen_name'] )
		
		if len(self.filters['strings'])!=0:
			#filter against the strings
			#get the dent text
			text = data['text']
			#loop through the filter strings
			for string in self.filters['strings']:
				if re.search(string,text, flags=re.IGNORECASE):
					return (True, "string: %s" % string )
		#if we get this far, just return
		return (False, None)		
	
	def status_clicked(self,widget):
		if self.window_is_hidden==True:
			self.window_is_hidden=False
			self.mainwindow.show()
			self.align_window()
			self.mainwindow.present()
		else:
			self.window_to_tray(widget)

	def window_size_allocate(self,widget,size):
		self.window_width = size[2]
		self.window_height = size[3]
			
	def save_app_info(self):
		#save the filters
		self.conf.set('settings','filters', self.filters ,True)
		#save the window info
		self.conf.set('window_info','width', self.window_width )
		self.conf.set('window_info','height', self.window_height )
		try:
			#some themes don't pass root origin?
			origin = self.mainwindow.window.get_root_origin()
			self.window_x = origin[0]
			self.window_y = origin[1]
			self.conf.set('window_info','x', self.window_x )
			self.conf.set('window_info','y', self.window_y )
		except:
			pass
		self.conf.save()
		
	def mainwindow_delete_event(self,window,event=None):
		self.save_app_info()
		#are we in tray mode?
		if self.conf.get_bool_option('run_as_tray_app') or self.has_status_icon:
			#is the status icon embedded?
			if self.statusicon.is_embedded():
				self.window_is_hidden=True
				self.mainwindow.hide_on_delete()
				#do not propogate the signal
				return True
		else:
			#we need to quit
			self.quit_app()
			
	def quit_triggered(self,widget):
		self.save_app_info()
		self.quit_app()
	
	def option_changed(self,widget,value,option):
		#save the option change in the configuration
		self.conf.set('options',option,value)
		self.options[option]=value
		self.conf.save()
		#is this the run_tray_app:
		if option=='run_as_tray_app':
			if value:
				self.create_status_icon()
			else:
				self.destroy_status_icon()
		elif option=='no_avatars':
			self.imagecache.set_disabled(value)
		elif option=='ctrl_enter':
			self.mainwindow.set_ctrl_enter(value)
		 
	def redent_clicked(self,dent,name,text):
		if self.options['api_retweet']:
			self.comm.send_redent(dent.id)
		else:
			self.respond_to_id=dent.id
			#formatted_text= u'\u267A @%s: %s' % (name,text)
			formatted_text= u'\u267A @%s: %s' % (name,text)
			self.mainwindow.update_textbuffer.set_text(formatted_text )
			self.mainwindow.update_textview.grab_focus()
	 
	def view_group(self,widget,group_name):
		#where were we?
		self.pre_group_page=self.mainwindow.notebook_current_page
		#make some flags
		self.grouppage.joined_checkbutton.set_sensitive(False)
		#make the grouppage visible
		self.grouppage.show_all()
		#rehide its collapsed widgetbox, that doesn't need to be visible yet
		self.grouppage.widgetbox_collapsed.hide()
		#clear the grouppage
		self.grouppage.clear()
		#switch to the group page
		self.mainwindow.set_notebook_page(GROUP)
		#get the group info
		self.get_group_info(group_name)

	def hide_contextpage(self,widget):
		#end any conversation in progress
		self.conversation_id="0"
		self.mainwindow.set_notebook_page( self.pre_context_page )
		self.contextpage.hide()

	def hide_grouppage(self,widget):
		self.mainwindow.set_notebook_page( self.pre_group_page )
		self.grouppage.hide()

	def hide_userpage(self,widget):
		self.mainwindow.set_notebook_page( self.pre_user_page )
		self.userpage.hide()

	def dent_text_clicked(self,dent,text_label):
		self.mainwindow.last_clicked_label = text_label

	def clear_respond_to_id(self,widget=None):
		self.respond_to_id=0
		
	def set_initial_dents(self,widget,value):
		self.initial_dents=value
		self.dent_limit = int(self.initial_dents)*2
		self.conf.set('settings','initial_dents',value)
		
		
	def set_pull_time(self, widget,value):
		"""A method for setting the time between pulls. obvious comment
		is obvious. Very possible everything will die now that I've added
		this. 
		--Muel Kiel (aka samsnotunix)"""
		self.pull_time=value
		self.conf.set('settings','pull_time',value)
		self.pull_time_changed_bool = True
		self.pull_time_mentions = True
	
	def set_link_color(self,widget,string):
		self.conf.set('settings','link_color',string)
		self.theme_link_color(string)
		
	def theme_link_color(self,color):
		style='''
		style "label" {
			GtkLabel::link-color="%s"
		}
		widget_class "*GtkLabel" style "label"
		''' % (color)
		gtk.rc_parse_string(style)
		#f**k you GTK for not make this work, more than once!
	
	#functions for blocking/unblocking
	def block_create(self,widget,user_id):
		self.comm.block_create(user_id)
		
	def block_destroy(self,widget,user_id):
		self.comm.block_destroy(user_id)
		
		
	def set_is_direct_message_mode(self,mode,user=None):
		self.is_direct_message_mode=mode
		self.mainwindow.set_is_direct_message_mode(mode,user)
		if mode:
			self.default_icon_path=self.direct_icon_path
		else:
			self.default_icon_path=self.standard_icon_path
		#if we aren't waiting on any requests, swap the graphic
		if self.waiting_requests==0:
			try:
				self.mainwindow.set_icon_from_file(self.default_icon_path)
			except:
				pass
			try:
				self.mainwindow.set_throbber(self.default_icon_path)
			except:
				pass
			
	def simple_decrement(self,text=None,data=None):
		self.decrement_requests()

	'''
	function window_to_tray
	sets the run_as_tray_app to true and minimizes the app
	'''
	def window_to_tray(self,window):
		if self.options['run_as_tray_app']:
			self.mainwindow_delete_event(window)
			
			
	def open_link(self, widget, uri):
		webbrowser.open(uri)
		return True
		'''
		command = "xdg-open '%s'" % ( uri )
		#print command
		subprocess.Popen(command,shell=True)
		return True
		'''

	def log(self,string):
		if self.logging:
			now = time.strftime("%H:%M:%S")
			file = os.path.join( os.path.expanduser("~"),"heybuddy.log")
			f = open(file,'a')
			f.write("%s %s\n" % (now,string) )
			f.close() 
コード例 #27
0
def print_details(sql):

    comm = Communicator()

    comm.say("SQL: %s" % sql)
コード例 #28
0
class Map:
    terrain = {"rock": "#", "ground": ",", "water": "~"}

    def __init__(self,
                 height,
                 width,
                 terrainRatio,
                 waterIntervals=[1, 2],
                 rockIntervals=[0, 1],
                 grassIntervals=[0, 3],
                 communicator=None):
        self.terrainRatio = terrainRatio
        self.waterIntervals = waterIntervals
        self.rockIntervals = rockIntervals
        self.grassIntervals = grassIntervals
        self.height = height
        self.width = width
        self.square = height * width
        self.communicator = Communicator()
        self.groundMatrix = []
        self.createField()
        self.placeObj(0)
        self.placeObj(1)
        self.placeObj(2)

    def createField(self):
        self.groundMatrix = [[
            Map.terrain["ground"] for _ in range(self.width)
        ] for _ in range(self.height)]

    def placeObj(self, obj):
        percent = self.terrainRatio[obj]
        if obj == 0:
            self.interval = self.waterIntervals
            terrain = "water"
            multiplier = 5
        elif obj == 1:
            self.interval = self.rockIntervals
            terrain = "rock"
            multiplier = 3
        elif obj == 2:
            self.interval = self.grassIntervals
            grass = range(1, 10)
            multiplier = 4

        cellNum = (self.square // 100) * percent
        Oy = range(self.height)
        Ox = range(self.width)
        sigma = range(self.interval[0], self.interval[1] + 1)
        if obj == 2:
            self.grassCellNum = cellNum
            self.startGrassAmount = cellNum
        while cellNum:
            x = random.choice(Ox)
            y = random.choice(Oy)
            s = random.choice(sigma)
            maxX = 0
            maxY = 0
            n = s * cellNum * multiplier
            while n:
                divx = int(random.gauss(x, s))
                divy = int(random.gauss(y, s))
                if (0 <= divy < self.height) and (0 <= divx < self.width):
                    if self.groundMatrix[divy][divx] == Map.terrain["ground"]:
                        cellNum -= 1
                        if obj != 2:
                            self.groundMatrix[divy][divx] = Map.terrain[
                                terrain]

                        elif obj == 2:
                            self.groundMatrix[divy][divx] = random.choice(
                                grass)
                if not cellNum:
                    return None
                n -= 1

    def saveMap(self):
        path = "maps_directory"
        if not os.path.isdir("maps_directory"):
            os.mkdir("maps_directory")
        fileList = os.listdir(path)
        fileName = path + "\\" + "mapObj" + str(len(fileList) + 1) + ".txt"
        print(fileName)

        i = 1
        while True:
            if not os.path.exists(fileName):
                newFile = open(fileName, "wb")
                pickle.dump(self, newFile)
                newFile.close()
                break
            else:
                fileName = path + "\\" + "mapObj" + str(len(fileList) +
                                                        i) + ".txt"

            i += 1

    def copyMap(self, n=1):
        if n == 1:
            objCopy = copy.deepcopy(self)
            return objCopy

        else:
            copyList = []
            i = 0
            while i < n:
                copyList.append(copy.deepcopy(self))
                i += 1
            return copyList

    @staticmethod
    def loadMap(name):
        if os.path.isdir("maps_directory"):
            path = "maps_directory"
            mapFile = open(path + "\\" + name, "rb")
            mapObj = pickle.load(mapFile)
            mapFile.close()
            return mapObj

    def rewriteGrass(self):
        for i in range(self.height):
            for j in range(self.width):
                if type(self.groundMatrix[i][j]) is int:
                    self.groundMatrix[i][j] = Map.terrain["ground"]

        self.placeObj(2)

    def addGrass(self):
        if self.grassCellNum < self.startGrassAmount:
            diff = self.startGrassAmount - self.grassCellNum
            i = 0
            while i < diff:
                y = random.randint(0, self.height - 1)
                x = random.randint(0, self.width - 1)
                if self.groundMatrix[y][x] == ",":
                    self.grassCellNum += 1
                    self.groundMatrix[y][x] = 1
                    i += 1
                    continue

                elif str(self.groundMatrix[y][x]) not in ("#", "~"):
                    self.groundMatrix[y][x] += 1
                    if self.groundMatrix[y][x] > 9:
                        self.groundMatrix[y][x] = 9
                    i += 1

    def MatrixToStrFlow(self):
        resultMatrix = self.groundMatrix

        resultList = []
        for row in resultMatrix:
            resultList.extend(row)

        resultStr = ''.join([str(elem) for elem in resultList]) + ' '
        return resultStr

    def showMapGraphic(self):
        resultStr = self.MatrixToStrFlow()
        self.communicator.sendResolution(self.width, self.height)
        self.communicator.sendSignal("open")
        self.communicator.runGraphic()
        while True:
            if keyboard.is_pressed('q'):
                self.communicator.closeProgram()
                break

            if not self.communicator.getData():
                self.communicator.sendData(resultStr)

    def showMapText(self):
        for i in range(self.height):
            for j in range(self.width):
                print(self.groundMatrix[i][j], end="")
            print()
コード例 #29
0
ファイル: IOAI.py プロジェクト: ethanlouie/DeepBlueDream
 def __init__(self,col,row,p,**kwargs):
     command = kwargs['ai_path']
     command = get_prefix(command)
     command = command + " " + str(col) + " " + str(row) + " " + str(p) + " " + " t"
     self.communicator = Communicator(command,kwargs['time'])
コード例 #30
0
    DBCorpusClassifier().train(corpus_path, db_model_path)
    comm.say("Database classifier trained.")


"""
Training for SQL Queries using the grammar in corpus.py file
"""


def train_sql_classifier():
    comm.say("Training SQL grammar classifier.")

    SQLGrammarClassifier().train(sql_model_path)
    comm.say("SQL grammar classifier trained.")


if __name__ == '__main__':

    #Initialize the Communicatior
    comm = Communicator()
    #Check for the path in Configuration file.
    comm.say("Setting up the Training Environment.")
    #Creating a DB Graph consisting of all the table mappings of the database
    create_db_graph()
    #Assigning tags/tokens to all the database table values
    create_db_corpus()
    #Training the complete database using classifier
    train_db_classifier()
    #Training for SQL Queries using the grammar in corpus.py file
    train_sql_classifier()
    comm.say("Set up complete.")
コード例 #31
0
ファイル: Simulation.py プロジェクト: dariaugin/gruppa_oop
        resultStr = ''.join([str(elem) for elem in resultList]) + ' '
        return resultStr


if __name__ == '__main__':
    dayNum = 100
    occupyPercent = 20
    resolution = input("Resolution(WxH): ")  #max: 235 130
    width, height = [int(elem) for elem in resolution.split(' ')]

    while True:
        if 10 > width or 10 > height:
            print("Change width or height(it must be bigger than 10): ",
                  end="")
            width, height = [int(elem) for elem in input().split(' ')]
            continue
        break

    stat = Statistics.Statistics()
    mapObj = Map.Map(width, height, [20, 3, 60])
    comm = Communicator()
    mapObj.showMapGraphic()
    sim = Simulation(0,
                     stat,
                     mapObj,
                     occupyPercent,
                     communicator=comm,
                     grassUpdateFrequency=20,
                     maxDayNum=dayNum,
                     display=True)
    sim.run()
コード例 #32
0
 def handle_read(self):
     try:
         if Communicator.handle_read(self) is -1:
             return
     except Exception, e:
         raise
コード例 #33
0
ファイル: Simulation.py プロジェクト: dariaugin/gruppa_oop
class Simulation:
    mode = {"sin": sin, "const": None}  #T=30

    def __init__(
        self,
        ID,
        statistics,
        environment,
        occupyPercent,
        sidesRatio=[20, 80],
        hunterRatio=[33, 33, 34],
        preyRatio=[33, 33, 34],
        display=False,
        maxDayNum=10,
        grassUpdateFrequency=7,
        T=30,
        sunMode="const",
        communicator=None,
    ):
        self.environment = environment
        self.ID = ID
        self.statistics = statistics
        self.communicator = Communicator()
        self.statistics.writeMapData(self.environment)
        self.occupyPercent = occupyPercent
        self.sidesRatio = sidesRatio
        self.hunterRatio = hunterRatio
        self.preyRatio = preyRatio
        self.display = display
        self.cycles = 0
        self.days = 0
        self.minProductivity = self.environment.grassCellNum // 5
        self.grassUpdateFrequency = grassUpdateFrequency
        self.maxDayNum = maxDayNum
        self.T = T
        self.sunMode = self.__class__.mode[sunMode]
        self.cellDict = {}

        Animal.AnimalPlacer.initBiota(self)
        Animal.AnimalPlacer.initAnimalMatrix(self)
        Animal.AnimalPlacer.placeAllAnimals(self)

    def run(self):
        if self.display:
            self.communicator.sendResolution(self.environment.width,
                                             self.environment.height)
            self.communicator.sendSignal("open")
            self.communicator.runGraphic()

        self.maxProductivity = self.environment.startGrassAmount
        amountListHunter = []
        amountListPrey = []

        while True:
            if self.totalNum <= 1 or keyboard.is_pressed(
                    'q'
            ) or self.cycles / self.grassUpdateFrequency > self.maxDayNum:
                self.communicator.closeProgram()
                break

            if not self.communicator.getData():
                #self.simulationControl([0, 1, 0])#
                amountListHunter.append(copy.copy(self.speciesAmount[0]))
                amountListPrey.append(copy.copy(self.speciesAmount[1]))
                asyncio.run(self.passCycle())
                if self.cycles % self.grassUpdateFrequency == 0:
                    self.statistics.writeSimulationData(
                        self, amountListHunter, amountListPrey)
                    amountListHunter = []
                    amountListPrey = []
                    self.sunActivityFunc()
                    self.environment.addGrass()
                    self.days += 1

                self.cycles += 1
                if self.display:
                    resultStr = self.composeResultMatrix()
                    self.communicator.sendData(resultStr)

    def sunActivityFunc(self):
        if self.sunMode == None:
            return None
        self.environment.startGrassAmount = self.maxProductivity * self.sunMode(
            self.days, self.T)
        if self.environment.startGrassAmount < self.minProductivity:
            self.environment.startGrassAmount = self.minProductivity

    async def passCycle(self):
        i = 0
        for animal in self.animalList:
            await animal.activityProcess(i)
            i += 1

    def showAnimalData(self):
        i = 1
        for animal in self.animalList:
            print(i, ". ", animal.symbol, end=": ")
            for cell in animal.cellList:
                print("(", cell.y, ",", cell.x, ")", end=" | ")
            print(animal.cellLife, " | ", animal.cellList[0].localDirect)
            i += 1

    def showMap(self, needShow=[1, 1, 1]):
        if needShow[0]:
            print("mapMatrix:")
            for i in range(self.environment.height):
                for j in range(self.environment.width):
                    print(self.environment.groundMatrix[i][j], end="")
                print()
        if needShow[1]:
            print("animalMatrix:")
            for i in range(self.environment.height):
                for j in range(self.environment.width):
                    if self.animalMatrix[i][j] != None:
                        print(self.animalMatrix[i][j], end="")
                    else:
                        print(" ", end="")
                print()

        resultMatrix = copy.deepcopy(self.environment.groundMatrix)
        for i in range(self.environment.height):
            for j in range(self.environment.width):
                if self.animalMatrix[i][j] != None:
                    resultMatrix[i][j] = self.animalMatrix[i][j]

        if needShow[2]:
            print("resultMatrix:")
            for i in range(self.environment.height):
                for j in range(self.environment.width):
                    print(resultMatrix[i][j], end="")
                print()

    def simulationControl(self, needShow=[1, 1, 1]):
        self.showMap(needShow)
        self.showAnimalData()
        cellCoords = self.cellDict.keys()
        print(len(cellCoords), cellCoords)

    def composeResultMatrix(self):
        resultMatrix = copy.deepcopy(self.environment.groundMatrix)
        for i in range(self.environment.height):
            for j in range(self.environment.width):
                if self.animalMatrix[i][j] != None:
                    resultMatrix[i][j] = self.animalMatrix[i][j]

        resultList = []
        for row in resultMatrix:
            resultList.extend(row)

        resultStr = ''.join([str(elem) for elem in resultList]) + ' '
        return resultStr
コード例 #34
0
        self.PyY[step:maxStep] = prey.y
        self.PdX[step:maxStep] = pred.x
        self.PdY[step:maxStep] = pred.y
        self.liney.set_xdata(self.PyX)
        self.lined.set_xdata(self.PdX)
        self.liney.set_ydata(self.PyY)
        self.lined.set_ydata(self.PdY)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        #self.ax.clear()
        #self.ax.plot(self.PyX, self.PyY, 'b-')
        #self.ax.plot(self.PdX, self.PdY, 'r-')
        #plt.draw()
        # time.sleep(0.0001)

comm = Communicator(nQuadrants, 2, 2)
pred = Predator()
prey = Prey()
plot = Plotter()

while(True):
    pred.reset()
    prey.reset()
    comm.sendInitState(pred.getState(prey), agent_id=0)
    comm.sendInitState(prey.getState(pred), agent_id=1)

    step = 0

    while (True):
      plot.update(step, pred, prey)
      pred.advance(comm.recvAction(0))
コード例 #35
0
ファイル: heybuddy.py プロジェクト: yamatt/python-hellobuddy
	def __init__(self):
		#init threading
		gobject.threads_init()
		#keep track of the window size
		self.window_height=0
		self.window_width=0
		self.window_is_hidden = False
		self.has_status_icon = False
		#keep track of the initial conversation id so that conversations don't colide
		self.conversation_id="0"
		#keep track of the filters
		self.filters ={'users':[],'strings':[]}
		self.options={'run_as_tray_app':False,'context_backwards':False,'no_avatars':False,'notifications':True,'notify_replies':False}
		#keep track of the direct_message requests
		self.last_direct_message_time=0
		#something something direct message
		self.is_direct_message_mode=False
		self.direct_message_to=None
		self.waiting_requests=0
		self.is_first_dents = True
		#keep track of the respond to id
		self.respond_to_id=0
		self.pre_group_page=None
		self.pre_user_page=None
		#keep track of the last time statuses where pulled
		self.last_get_statuses = 0
		#what are the assets?
		asset_dir = 'assets'
		heybuddy_dir = os.path.dirname( os.path.realpath( __file__ ) )
		self.readme_file = os.path.join(heybuddy_dir,'README.txt')
		self.standard_icon_path = os.path.join(heybuddy_dir,asset_dir,'icon.png')
		self.direct_icon_path = os.path.join(heybuddy_dir,asset_dir,'direct_icon.png')
		self.networking_icon_path = os.path.join(heybuddy_dir,asset_dir,'icon1.png')
		self.throbber_icon_path = os.path.join(heybuddy_dir,asset_dir,'throbber.gif')
		self.default_icon_path = self.standard_icon_path
		self.conf = Configuration(app_name)
		#has the account info been authenticated?
		self.credentials_verified = self.conf.get_bool('access', 'credentials_verified')
		self.xmlprocessor = XMLProcessor()
		#create a regex to replace parts of a dent
		self.regex_tag = re.compile("(^| )#([\w-]+)", re.UNICODE)
		self.regex_group = re.compile("(^| )!([\w-]+)")
		self.regex_user=re.compile("(^|[^A-z0-9])@(\w+)")
		self.regex_url=re.compile("(http[s]?://.*?)(\.$|\. |\s|$)",re.IGNORECASE)
		#get the initial dents
		self.initial_dents = self.conf.get('settings','initial_dents',default='20' )
		self.dent_limit = int(self.initial_dents)*2
		#get the pull time
		self.pull_time = self.conf.get('settings','pull_time',default='60')
		self.pull_time_changed_bool = False
		self.pull_time_mentions = False
		#build the gui
		self.build_gui()
		
		#where is the certs file?
		ca_certs_files = [
			"/etc/ssl/certs/ca-certificates.crt",
			"/etc/ssl/certs/ca-bundle.crt",
			]
		#what if there isn't a cert_file
		cert_file=None
		#determine the certs_file
		for f in ca_certs_files:
			if os.path.exists(f):
				cert_file=f
				break	
		
		#create the communicator
		self.comm = Communicator(app_name, cert_file)
		self.comm.connect('statusesXML',self.process_statusesXML,self.dentspage)
		self.comm.connect('mentionsXML',self.process_statusesXML,self.mentionspage)
		self.comm.connect('favoritesXML', self.process_statusesXML,self.favoritespage)
		self.comm.connect('group-statusesXML',self.process_statusesXML,self.grouppage)
		self.comm.connect('user-statusesXML',self.process_statusesXML,self.userpage)
		self.comm.connect('direct_messagesXML',self.process_statusesXML,self.directspage,True)
		self.comm.connect('conversationXML',self.process_conversationXML)
		self.comm.connect('userXML',self.process_userXML)
		self.comm.connect('groupXML',self.process_groupXML)
		self.comm.connect('new-statusXML',self.process_new_statusXML)
		self.comm.connect('redent-statusXML',self.process_new_statusXML)
		self.comm.connect('user_is_friendXML',self.process_user_is_friendXML)
		self.comm.connect('user_is_memberXML',self.process_user_is_memberXML)
		self.comm.connect('friendshipXML',self.process_friendshipXML)
		self.comm.connect('exception-caught',self.process_communication_exception)
		self.comm.connect('widget-image',self.process_widget_image)
		self.comm.connect('direct-messageXML',self.process_new_directXML)
		self.comm.connect('verify_credentialsXML',self.process_verifycredentialsXML)
		self.comm.connect('configXML',self.process_configXML)
		#create an image cacher thingy
		self.imagecache = ImageCache()
		self.imagecache.set_disabled( self.conf.get_bool_option('no_avatars') )
		self.imagecache.connect('get-widget-image', self.get_widget_image)
	
		#Create notify-er if has pynotify
		if has_pynotify:
			self.notify = Notify()

		#align the window
		self.align_window()
		# do we need to create the status icon
		if self.conf.get_bool_option('run_as_tray_app'):
			self.create_status_icon()
コード例 #36
0
ファイル: main.py プロジェクト: kamperud/NTNU
from drivertest import Elevator
from Communicator import Communicator
from MessageHandler import MessageHandler
from Controller import Controller
from Message import Message
from Peer import Peer

#Elevator()

messageHandler = MessageHandler()
communicator = Communicator(messageHandler)
controller = Controller(communicator)
messageHandler.setController(controller)

print "main"

message = Message("newOrder")
print message

peer = Peer("129.241.187.145")

#communicator.broadcast(message)
#communicator.sendToOne(peer, message)

print "main end"

コード例 #37
0
ファイル: testApp.py プロジェクト: stjordanis/smarties
import numpy as np
from Communicator import Communicator
import time

N = 1  # number of variables
sigma = 1
maxStep = 1000

# comm = Communicator(N/2, N/2, 2)
comm = Communicator(N, N)

while(True):
    s = np.random.normal(0, sigma, N) # initial state is observation
    comm.sendInitState(s)
    step = 0

    while (True):
      p = comm.recvAction()
      r = - np.sum((p-s)**2)
      o = np.random.normal(0, sigma, N)
      s = 0.5*s + o # s.t. 20 steps BPTT captures most dependency

      if(step < maxStep): comm.sendState(o, r)
      else:
        comm.truncateSeq(o, r)
        break
      step += 1
コード例 #38
0
	def handle_read(self):
		try:
			if Communicator.handle_read(self) is -1:
				return
		except Exception, e:
			raise
コード例 #39
0
	def __init__(self, conn, f_ctrl):
		Communicator.__init__(self, conn)
		self.f_ctrl = f_ctrl
		self.lastPacketTime = time.time()
コード例 #40
0
ファイル: run.py プロジェクト: AbdulrahmanSameem/nlpTOsql
from Communicator import Communicator
from corpus import CORPUS
from sql import NodeGenerator, SQLGenerator
from databasefile import Database, NodeType, Node, SchemaGraph
from Classifiers import SQLGrammarClassifier, DBSchemaClassifier, DBCorpusClassifier
from nltk import word_tokenize

import spacy
import re
import nltk
from nltk import chunk
from spacy import displacy

if __name__ == '__main__':

    comm = Communicator()
    """
    Files Paths 
    """

    graph_path = 'data/graph.p'
    stanford_jar = 'data/stanford-corenlp-full-2018-10-05/stanford-corenlp-3.9.2.jar'
    stanford_models_jar = 'data/stanford-corenlp-full-2018-10-05/stanford-corenlp-3.9.2-models.jar'
    """
    Models Paths 
    """
    sql_model_path = 'data/sql_model.p'
    db_model_path = 'data/db_model.p'

    schema_graph = SchemaGraph(graph_path)
    parser = Parser(stanford_jar, stanford_models_jar)
コード例 #41
0
class AC_Server( LabradServer ):
    name = 'AC Server'
    updateRate = 1.0 #seconds
    maxDaqErrors = 10
        
    @inlineCallbacks
    def initServer( self ):
        #setting up necessary objects
        self.daq = Communicator()
        self.channels = self.daq.channels
        self.channelDict = self.daq.channelDict
        self.averager = RunningAverage(self.channels, averageNumber = 12)
        self.emailer = self.client.emailer
        yield self.emailer.set_recipients(['*****@*****.**']) #### set this later
        self.alarmChecker = AlarmChecker(self.emailer, self.channelDict)
        #stting up constants
        self.PIDparams =([0,0,0],..)####get from registry
        self.daqErrors = 0
        #
        self.responseCalc = ResponseCalculator()
        #begin control
        self.inControl = LoopingCall(self.control)
        self.inControl.start(self.updateRate)


    @setting(0, 'Manual Override', enable = 'b', valvePositions = '*v')
    def manualOverride(self, c, enable, valvePositions = None):
        """If enabled, allows to manual specify the positions of the valves, ignoring feedback"""
        if enable:
            if valvePositions is None: raise Exception("Please specify valve positions")
            if self.inControl.running:
                yield self.inControl.stop()
            raise NotImplementedError
            #### set valve positions through valve class (with error checking there)
            #### make sure still record and save temperatures while in manual mode
        else: #resume automated control
            self.inControl.start(self.updateRate)
            
    @setting(1, 'PID Parameters', PID = '*3v')
    def PID(self, c, PID = None):
        """Allows to view or to set the PID parameters"""
        if PID is None: return self.PID
        self.PIDparams = PID
        ####
        
    @setting(2, 'Reset Integrator')
    def resetIntegrator(self, c):
        pass
    
    @inlineCallbacks
    def control(self):
        try:
            temps = yield self.daq.getTemperatures()
        except: #put error type
            self.daqErros += 1
            yield self.checkMaxErrors()
        else:
            self.averager.add(temps)
            temps = self.averager.getAverage()
            yield self.alarmChecker.check(temps)
            PIDresponse,valveResponse =  self.responseCalc.getResponse(temps)
            toValves = self.Valves.valveSignal(valveResponse)
            yield self.daq.setValves(toValves)
            
            
    @inlineCallbacks
    def checkMaxErrors(self):
        """checks how many errors have occured in sends out a notification email"""
        if self.daqErrors >  self.maxDaqErrors:
            print "TOO MANY DAQ ERRORS"
            yield self.emailer.send('AC ALARM: TOO MANY DAQ ERRORS', '')
            self.daqErrors = 0
            yield self.inControl.stop()