Exemplo n.º 1
0
 def p_command4(self, p):
     """  command  :  setpos '[' value value ']' 
                     | setxy value value """
     if len(p) == 6:
         p[0] = Command("setpos", {'value1': p[3], 'value2': p[4]})
     else:
         p[0] = Command("setpos", {'value1': p[2], 'value2': p[3]})
Exemplo n.º 2
0
 def test_positive_command_5(self):
     cmd = Command("plACe 0    2   N")
     self.assertIsInstance(cmd.GetCommand(), CommandPlace)
     self.assertEqual(cmd.GetCommand().GetPosition()[0], 0)
     self.assertEqual(cmd.GetCommand().GetPosition()[1], 2)
     self.assertEqual(cmd.GetCommand().GetHeading(), "N")
     return
Exemplo n.º 3
0
class GameObject():

	validObjects = ['beacon', 'tower', 'default', 'drone', 'asteroid', 'mine', 'scrap', 'worker', 'fighter'] #Definition list of all possible object type strings

	def __init__(self, loc, objectType, player):
		#Static attributes:
		self.loc = loc

		if(objectType in self.validObjects):
			self.objectType = objectType
		else:
			self.objectType = 'default'

		self.ID = None
		self.player = player
		self.mass = {'beacon':1000, 'tower':100, 'default':10, 'drone':10, 'asteroid':5, 'mine':1, 'scrap':1, 'worker':10, 'fighter':15}[self.objectType] #Get mass from dictionary according to the object type
		#Dynamic attributes:
		self.velocity = [0, 0] #Velocity vector. For example: [1, 0] refers to positive x direction at 1 unit per second
		self.acceleration = [0, 0]
		self.current_cmd = Command('drift') #Initialize GameObjec to drift based on initial acceleration and velocity when created
		self.angle = 0
		#Variable convention:
		#Player: a string representing the player name the object belongs to. Same for every object the player owns
		#ID: A unique ID that is dynamically assigned for each gameObject on the map. In the form player,objectType,number

	def update(self): #Each game object must be updated every tick
		self.current_cmd.runCmd(self)

	def getDict(self):
		obj_dict = self.__dict__.copy()
		del obj_dict['current_cmd']
		return obj_dict
 def __init__(self, drv, device_commands):
     self.drv = drv
     self.device_commands = device_commands
     self.help_command = Command(
         name='get-commands',
         command=self.get_available_commands,
         caption="shows available commands",
         valid_args=[],
         args_check_func=no_args,
     )
     self.get_args_command = Command(
         name="get-args",
         command=self.get_args_by_command,
         caption="",
         valid_args=None,
         args_check_func=str_arg_in_array_of_valid,
     )
     self.get_caption_command = Command(
         name="get-caption",
         command=self.get_caption_by_command,
         caption="shows caption of command",
         valid_args=None,
         args_check_func=str_arg_in_array_of_valid,
     )
     self.service_commands = [
         self.help_command,
         self.get_args_command,
         self.get_caption_command,
     ]
     self.get_args_command.valid_args = [[command.name for command in (self.device_commands +
                                                                       self.service_commands)]]
     self.get_caption_command.valid_args = [[command.name for command in (self.device_commands +
                                                                          self.service_commands)]]
Exemplo n.º 5
0
class ConsoleInput():
    def __init__(self, netobj=Network()):
        kthread = KeyboardThread(self.input_callback)
        self.command = Command(netobj)

    def input_callback(self, inp):
        self.command.execute(inp)
Exemplo n.º 6
0
    def action(self, user_input_list):

        if not Command.isLogged(self):
            return "No user is logged in."

        if not Command.getCredentialss(self) == 2:
            return "Does not have permission"

        # <username> <hw1>
        userUtil = UserUtility()

        username = user_input_list[1]
        homework = user_input_list[2]

        user = userUtil.searchUser(username)

        if (user.getRole() != "TA"):
            return user.getUsername() + " is not a TA"

        # if (user.getLabs() == None or "None"):
        #     return "Can't assign this TA homework because they are not assigned to a lab. "

        user.setAssignment(homework)
        userUtil.updateUser(user)

        return username + " has been assigned " + homework
Exemplo n.º 7
0
 def Process():
     toy = Robot()
     try:
         print("\n")
         print("Welcome to the Toy Robot application.\n")
         print("Proceed to enter commands. Press CTRL-C to exit.\n")
         # Loop until we receive a kill signal.
         while True:
             # BUG: Change to input() for Python 3.x
             line = raw_input("> ")
             try:
                 # Parse the command.
                 cmd = Command(line)
                 # Execute the validated command on the robot.
                 cmd.Execute(toy)
             except CommandException as ce:
                 print(ce)
             except RobotException as re:
                 print(re)
             except CompassHeadingException as he:
                 print(he)
     except KeyboardInterrupt as kb:
         print("Keyboard exit signal detected.")
         pass
     finally:
         print("Exit requested.")
         toy.Cleanup()
         print("Application successfully exited.")
     return
Exemplo n.º 8
0
        def handle_standard_command(message):

            command = Command()
            command.type = Command.CommandType.STANDARD_COMMAND
            command.message = message
            command.bot = self.__bot
            CommandExecutor.execute_command(command)
    def parse(self, read_command):

        # Debug to check ascii code of each char in string
        # print(f"read command is {[ord(c) for c in read_command]}")

        # If empty command
        if len(read_command) == 0:
            return Command("blank")

        list_read = read_command.split(' ')

        if "md" in list_read:
            mission_type = list_read[0]
            start_timestamp = list_read[1]
            num = list_read[2]
            interval = list_read[3]
            down_timestamp = list_read[4]

            try:
                parsed_command = MissionDownlinkCommand(
                    mission_type, num, interval, start_timestamp,
                    down_timestamp)
            except ValueError:
                parsed_command = Command("unknown")

        else:
            parsed_command = Command("unknown")

        return parsed_command
Exemplo n.º 10
0
    def HandleAddSubscriber(self, command):
        """This function handles the case where the client wants to add a subscriber to the network"""
        print "Handling Add Subscriber..."

        # modifying global shared data so we need to protect this part.
        # check if the requested publisher exists
        if Pubs.has_key(command.Payload):

            publisher = Pubs[command.Payload]

            # if this is the first subscriber for this publisher then send the start publishing command to the publisher
            if 0 == len(publisher.Subs):
                # RQ 19a
                # RQ 19b
                publisher.SendCommand(Command.START_PUBLISHING)

            # add the subscriber to the publishers dictionary
            publisher.Subs[self.client_address] = Subscriber(self.request, self.client_address)

            print "Client " + self.GetClientString() + " added subscriber to publisher=" + command.Payload + "."

            # RQ 17c
            # RQ 17d
            # RQ 17f
            # build the success packet with the port number for the subscriber
            return Command().CreateFromParams(Command.SUCCESS, command.TransactionID, 0, publisher.BroadcastPort)

        else:
            print "Client " + self.GetClientString() + " tried to add a subscriber to " \
                  + command.Payload + " which does not exist"

            # RQ 17e
            # return the failure packet
            return Command().CreateFromParams(Command.FAILURE, command.TransactionID, 0, Command.PUB_DOES_NOT_EXIST)
def _make_graphics(root,lst,dbg=0):
    "make up the selection window"
    grx=Toplevel()
    if root != None:
        geom=root.wm_geometry();
        grx.geometry=geom
    else:
        grx.geometry='800x600+0+0'

    grx.title("Select item to print")
    dlist=[]
    for t in lst:
        dlist.append(t[0])
    slb=Pmw.ScrolledListBox(grx,items=dlist)
    slb.configure(dblclickcommand=Command(_selected,grx,slb,dbg))
    slb.pack(expand=1,fill=BOTH)
    slb.root=grx
    slb.lst=lst
    fr=Frame(grx)
    Button(fr,text='Done\nselecting items\n to print',command=grx.destroy,width=40).pack(side=RIGHT)
    Button(fr,text='Select item\nto preview\nbefore print',command=Command(_selected,grx,slb,dbg),width=40).pack(side=RIGHT)
    fr.pack()

    def _freeze_window(tp,geom,event=None,*args):
        if tp.wm_geometry() != geom:
            tp.wm_geometry(geom)

    if dbg==0:
        grx.bind('<Configure>',Command(_freeze_window,grx,geom))
    else:
        _freeze_window(grx,geom)
    return grx    
Exemplo n.º 12
0
 def visit_Var(self, node):
     if node.index is not None:
         #with index
         if type(node.index).__name__ == 'Num':
             #with numeric index
             index = self.visit(node.index)
             address = self.symtab.lookup_address(node.var_name, index)
             return [Command(address, 'address')]
         else:
             if type(node.index).__name__ == 'Var':
                 #with variable index
                 commands = [Command('LDA', 'instruction')]
                 commands.extend(self.visit(node.index))
             else:
                 #with expression index
                 commands = self.visit(node.index)
             var_address = self.symtab.lookup_address(node.var_name, 0)
             commands.append(Command('ADI', 'instruction'))
             commands.append(Command(var_address, 'address'))
             return commands
     else:
         commands = [
             Command(self.symtab.lookup(node.var_name).address, 'variable')
         ]
         return commands
Exemplo n.º 13
0
    def handle_messages(self):
        # Initialize DB
        self.conn = sqlite3.connect('telegram.db')
        self.c = self.conn.cursor()

        # Create tables
        self.c.execute('''create table if not exists Telegram (name STRING, last_name STRING, userid STRING UNIQUE)''')

        while True:
            print ("Waiting for message in queue")
            message = self.queue.get()
            user_info = message[1]
            user_id = user_info[0]
            first_name = user_info[1]
            last_name = user_info[2]
            if last_name is None:
                last_name = "N/A"
            print ("Got and handle message "+str(message.text))
            res="Command not understood"
            try:
                #Extract the command
                cmd_list = message.text.split()
                if str(message.text) == "/start":
                    self.new_user(first_name, last_name, user_id)
                    continue
                #Replace protocol command with OS command
                cmd = commands.allowable_commands[cmd_list[0]]
                cmd_list[0] = cmd
                runner = Command(cmd_list)
                runner.run(5)
                print("RES "+str(runner.res)+" /RES")
                self._send_message(message.sender.id, runner.res)
            except Exception as e:
                print ("Except: "+str(e))
Exemplo n.º 14
0
 def __init__(self, plane, base, nb_drop):
     Command.__init__(self)
     if plane is None or base is None:
         raise "DropMilitarsCommand : Null reference"
     self.planeSrc = plane
     self.baseTarget = base
     self.quantity = nb_drop
Exemplo n.º 15
0
def sendCommand(f):
	print '--------- Datalogger Simulator -----------'
	while len(sensorReceiver) > 0:
		print 'Ingrese uno de los siguientes comandos:'
		
		for key,val in sorted(command.items()):
			print " "*5,key, ":", val
		
		commandInput = raw_input('>>')
		if command.has_key(commandInput):	
			print 'Ingrese un sensor destinatario'
			for key,val in sorted(sensorReceiver.items()):
				print " "*5,key, ":", val
			sensorInput = raw_input('>>')
			
			if sensorReceiver.has_key(sensorInput):
				if commandInput == '1':
					frequency = 0
				elif commandInput == '2':
					print 'Ingrese una valor de frecuencia'
					frequency = raw_input('>>')
				else:
					frequency = 0
					
				comando = Command(sensorReceiver[sensorInput],'client03' , 5, 100, ' ',command[commandInput], frequency)
				com.send(comando)
				f.write(comando.getReceiver().center(15)+ comando.getCommand().center(10) +str(comando.getValue()).center(10)
					+'-'.center(10)+'-'.center(10)+ time.strftime("%H:%M:%S").center(10)+'\n')
				if commandInput == '3':
					del sensorReceiver[sensorInput];
			else: 
				print 'el sensor no existe\n'
		else:
			print 'comando erroneo\n'
	exit(0)
Exemplo n.º 16
0
    def action(self, user_input_list):

        if not Command.isLogged(self):
            return "No user is logged in."

        if Command.getCredentialss(self) < 3:
            return "Do not have permission"

        util = UserUtility()
        username = str(user_input_list[1]).upper()  # force uppercase
        password = user_input_list[2]

        user = util.searchUser(username)

        if user is not None and user.getUsername() is not None:
            return "User already exists."

        user = User("first", "last", username, password, "role", "phone",
                    "email", "address", ["None"], ["None"], "assignment",
                    "officehours")
        # user = User()

        user.setAccount(username, password)

        util.updateUser(user)

        util.addToMasterUserList(username)

        return username + " has been added"
def _win_work(container, printfunction, pname, fname, prt, imagesize=None):

    container.imgsize = imagesize
    keys = Frame(container)
    byes = Button(keys,
                  text='Print\nthis\nimage',
                  command=Command(printfunction, container, pname, fname, prt),
                  width=10)
    bdel = Button(keys,
                  text='Delete\nthis\nimage',
                  command=Command(_delme, container, fname),
                  width=10)
    bno = Button(keys,
                 text='Close\nthis\nwindow',
                 command=Command(_gone, container, 0),
                 width=10)
    container.protocol('WM_DELETE_WINDOW', Command(_gone, container, 0))
    container.bind('<Return>', Command(_gone, container, 0))
    bno.pack(side='right')
    bdel.pack(side='right')
    byes.pack(side='right')

    keys.pack(side='bottom')
    container.fr.pack(side='bottom', expand=1, fill=BOTH)

    container.grab_set()
    container.focus_set()
    container.wait_window()
    ans = container.answer
    try:
        container.destroy()
    except:
        pass
    return ans
Exemplo n.º 18
0
    def course_format_section(self):
        Command.command_execute(Command.course_format_command(self))

        params = ["format='topics'", "value=0"]
        self.update('mdl_course_format_options',
                    ', '.join([str(i) for i in params]),
                    "courseid='%s' AND name = 'numsections'" % self.id)
Exemplo n.º 19
0
def get_redirect_url(search_query):
    # Use LRU cache to stash recent queries to save time for upcoming calls
    cmd, arg = tokenize(search_query)
    if cmd is None:
        return ''
    default = Command.default(cmd + ' ' + (arg or ''))
    if cmd in shortcut_to_function_map:
        try:
            # Get the relevant Command function pointer and invoke it on arg
            command_function = getattr(Command,
                                       shortcut_to_function_map[cmd].__name__)
            url = command_function.__call__(arg)
            if url is None:
                # If shortcut is not implemented but is present
                return Command.default(cmd + ' ' + (arg or ''))
            return url
        except TypeError as te:
            print(repr(te))
            return default
        except AttributeError as ae:
            print(repr(ae))
            return default
        except Exception as e:
            print(repr(e))
            return default
    return default
    def action(self, user_input_list):

        if not Command.isLogged(self):
            return "No user is logged in."

        if Command.getCredentialss(self) < 3:
            return "Do not have permission"

        userUtil = UserUtility()
        courseUtil = CourseUtility()
        username = str(user_input_list[1]).upper()  # force uppercase
        courseName = str(user_input_list[2]).upper()  # force uppercase

        user = userUtil.searchUser(username)
        if (user == None):
            return username + " does not exist"

        if (courseUtil.getContents(courseName) == False
            ):  # if course doesn't exist, return error
            return "Course doesn't exist"

        if (courseUtil.unAssignCourse(username) == False):
            return username + " is not a part of this course"

        courseUtil.writeContents()

        user.unAssignCourse(courseName)
        userUtil.updateUser(user)

        return "Unassigned " + username + " from " + courseName
Exemplo n.º 21
0
def fvm_test(base_path, test_path, testing=False, procs=1):
    log("Starting fvm test\n")

    prev_path = os.getcwd()
    path = os.path.join(test_path, '..')
    os.chdir(path)

    nodes = 1
    size = (32 if procs == 1 else 64)
    ssize = 8
    levels = 3
    re_end = 0

    p = Command('python runtest.py %d %d %d %d %d' %
                (nodes, procs, size, ssize, levels),
                env=env_vars(base_path, testing))
    p.run()

    fname = 'FVM_LDCav_nn%02d_np%d_nx%d_sx%d_L%d_%d' % (nodes, procs, size,
                                                        ssize, levels, re_end)
    shutil.copy(
        fname + '.out',
        test_path + '/' + fname + ('' if not testing else '_testing') + '.out')

    log("Test output:\n\n")
    log(p.out)

    log("Test errors:\n\n")
    log(p.err)

    os.chdir(prev_path)
Exemplo n.º 22
0
 def test_positive_command_4(self):
     cmd = Command("place 1,2,E")
     self.assertIsInstance(cmd.GetCommand(), CommandPlace)
     self.assertEqual(cmd.GetCommand().GetPosition()[0], 1)
     self.assertEqual(cmd.GetCommand().GetPosition()[1], 2)
     self.assertEqual(cmd.GetCommand().GetHeading(), "E")
     return
Exemplo n.º 23
0
    def insert_command_at(self, idx, command):
        if command is None:
            return

        if isinstance(command, str):
            if len(command.strip()) == 0:
                raise TypeError('Passin command type is not corrent.')
            command = Command(command)
            self._command_order.insert(idx, command.__hash__())
            self._commands[command.__hash__()] = command
        elif isinstance(command, Command):
            self._command_order.insert(idx, command.__hash__())
            self._commands[command.__hash__()] = command
        elif isinstance(command, list):
            for cmd in command:
                if isinstance(cmd, str):
                    cmd = Command(cmd)
                    self._command_order.insert(idx, cmd.__hash__())
                    self._commands[cmd.__hash__()] = cmd
                elif isinstance(cmd, Command):
                    self._command_order.insert(idx, cmd.__hash__())
                    self._commands[cmd.__hash__()] = cmd
                idx += 1
        else:
            raise TypeError('Passin command type is not corrent.')
Exemplo n.º 24
0
    def action(self, user_input_list):
        if not Command.isLogged(self):
            return "No user is logged in."

        if len(user_input_list) is 1:
            user = self._logger
            util = UserUtility()
            user = util.searchUser(user.getUsername())
            return "First Name: " + user.getFirstName() + "\nLast Name: " + user.getLastName() \
                    + "\nemail: " + user.getEmail() + "\nphone: " + user.getPhone() \
                    + "\naddress: " + user.getAddress() + "\nOffice Hours: " + user.getOfficeHours()

        util = UserUtility()
        username = str(user_input_list[1]).upper()  # force uppercase
        user = util.searchUser(username)
        if user is None:
            return username + " doesn't exist!"

        user_rank = Command.getCredentialss(self)
        role = user.getRole()
        search_rank = ShowCommand.checkRank(self, role)

        if user_rank < search_rank:
            return "You do not have permission to view " + username

        if user_rank <= 2:
            string = "First Name: " + user.getFirstName() + "\nLast Name: " + user.getLastName() \
                     + "\nemail: " + user.getEmail() + "\nOffice Hours: " + user.getOfficeHours()
        else:
            string = "First Name: " + user.getFirstName() + "\nLast Name: " + user.getLastName() \
                     + "\nemail: " + user.getEmail() + "\nphone: " + user.getPhone() \
                     + "\naddress: " + user.getAddress() + "\nOffice Hours: " + user.getOfficeHours()

        return string
Exemplo n.º 25
0
    def action(self, user_input_list):

        if not Command.isLogged(self):
            return "No user is logged in."

        if Command.getCredentialss(self) < 3:
            return "Do not have permission"

        util = UserUtility()
        courseUtil = CourseUtility()
        username = str(user_input_list[1]).upper()  # force uppercase

        user = util.searchUser(username)
        if user is None:
            return username + " doesn't exist!"

        courses = user.getCourses()
        if courses[0] != "None":
            for i in range(0, user.getCourses().__len__()):
                courseUtil.getContents(user.getCourses()[i])
                courseUtil.unAssignCourse(username)
                courseUtil.writeContents()


        if (user.getRole() == "Instructor"):
            courseUtil.removeDBInstructor(username)

        util.removeUser(username)

        util.removeFromMasterUserList(username)

        return username + " has been removed."
Exemplo n.º 26
0
    def action(self, user_input_list):

        if not Command.isLogged(self):
            return "No user is logged in."

        if Command.getCredentialss(self) < 2:
            return "Do not have permission"

        # <course> <lab>
        courseUtil = CourseUtility()
        userUtil = UserUtility()

        courseName = str(user_input_list[1]).upper()    # force uppercase
        labName = str(user_input_list[2]).upper()       # force uppercase

        if (courseUtil.getContents(courseName) == False):
            return courseName + " does not exist"


        # make sure to remove lab from user file
        for i in range(0,courseUtil.getLabs().__len__()):
            if (labName == courseUtil.getLabs()[i]):
                TA = userUtil.searchUser(courseUtil.getTAs()[i])
                if (TA != None):
                    TA.unAssignLab(courseName,labName)
                    userUtil.updateUser(TA)

        if (courseUtil.removeLab(labName) == False):
            return labName + " does not exist"

        courseUtil.writeContents()

        return labName +" has been removed"
Exemplo n.º 27
0
def execute(executor, *args, **kwargs):
    ls_command = Command('ls')
    for arg in args:
        ls_command.add_argument(arg)

    ls = type(executor)(reference=executor)
    ls.add_command(ls_command)
    return ls()
 def __init__(self, plane, mil_qty, fuel_qty, delete):
     Command.__init__(self)
     if plane is None:
         raise "LoadRessourcesCommand : Null reference"
     self.planeSrc = plane
     self.militarQuantity = mil_qty
     self.fuelQuantity = fuel_qty
     self.delete_ressources = delete
Exemplo n.º 29
0
 def scorm_add(self):
     self.scorm_import_folder()
     zip_name = self.scorm_zip()
     Command.command_execute(
         Command.activity_create_command(
             options=self.get_scorm_options(zip_name),
             type=self.type,
             id=self.course.id))
Exemplo n.º 30
0
Arquivo: Mp3.py Projeto: serl/rasplarm
 def __init__(self, config):
   Command.__init__(self, config)
   if self.config.has_key('directory') and not os.path.isdir(self.config['directory']):
     raise Exception("directory '%s' does not exists" % (self.config['directory'],))
   if self.config.has_key('directory') and not os.listdir(self.config['directory']):
     raise Exception("directory '%s' is empty" % (self.config['directory'],))
   if not self.config.has_key('count'):
     self.config['count'] = 1
Exemplo n.º 31
0
def main():
    # Command Line Defaults:
    SETUP_PATH = u''
    BONUS_FILE = u'bonus'
    TILES_FILE = u'tiles'
    WORDS_FILE = u'words'
    FILE_EXT = u'txt'  # Default File Extension
    PLAYERS = 2
    BOARD_SIZE = 15

    try:
        command = Command(BONUS_FILE, TILES_FILE, WORDS_FILE, FILE_EXT,
                          PLAYERS, BOARD_SIZE)
        if command.Parse(sys.argv):
            verbose = command.verbose

            if command.players <= 0:
                print(u'The # of players must be greater than 0')
                return

            tileManager = FileManager(SETUP_PATH, command.file_ext, verbose)
            tileManager.load(command.tiles_file)
            tiles = Tile(tileManager.records)

            bonusManager = FileManager(SETUP_PATH, command.file_ext, verbose)
            bonusManager.load(command.bonus_file)

            #
            # Test Board
            #
            #testBoard = Board(command.size_x, command.size_y, bonusManager.records, tiles)
            #testBoard.Test()

            board = Board(command.size_x, command.size_y, bonusManager.records,
                          tiles)

            wordManager = FileManager(SETUP_PATH, command.file_ext, verbose)
            wordManager.load(command.words_file)
            player = Player(command.players, wordManager.records, board,
                            command.reverse, command.debug)
            #player.Test()

            testCommands = [
                u'play g8=c,h8=a,i8=t', u'play k8=t,l8=o,m8=n,n8=i,o8=c',
                u'play k9=u,k10=f,k11=f', u'play i9=o,j9=v,l9=m',
                u'play j8=a,j10=o,j11=i,j12=d', u'board'
            ]
            #player.perform(testCommands)

            turn_player = player.start()

    except Exception as ex:
        #type_name = type(ex).__name__
        trace = traceback.format_exc()
        print(trace)

    #[Debug]
    raw_input(u'Press Enter')
Exemplo n.º 32
0
 def test_positive_robot_3(self):
     bot = Robot()
     Command("place 3,2,E").Execute(bot)
     Command("MOVE").Execute(bot)
     self.assertEqual(bot.IsPlaced(), True)
     self.assertEqual(bot.GetPosition()[0], 4)
     self.assertEqual(bot.GetPosition()[1], 2)
     self.assertEqual(bot.GetPosition()[2], "E")
     return
Exemplo n.º 33
0
def get_categories_menu():
    keys = []
    response = get('/categories')
    for category in response.json():
        keys.append([{'text': category['name'],
                      'callback_data': Command('get_category', '{"id": "' + str(category['id']) + '"}').__str__()}])
    keys.append([{'text': 'Дабавить категорию', "callback_data": Command('add_category').__str__()}])
    keys.append([{'text': 'В меню', "callback_data": Command('menu').__str__()}])
    return {'inline_keyboard': keys}
Exemplo n.º 34
0
 def quiz_add(self):
     self.id = Command.command_execute(
         Command.activity_create_command(options=self.get_quiz_options(),
                                         type=self.type,
                                         id=self.course.id))
     self.id = self.id[0].rstrip()
     self.create_xml_file()
     Command.command_execute(Command.import_questions_command(self.id))
     self.create_feedback()
Exemplo n.º 35
0
    def action(self, user_input_list):

        if not Command.isLogged(self):
            return "No user is logged in."

        if Command.getCredentialss(self) < 2:
            return "Do not have permission"

        # <username> <course> <lab>
        courseUtil = CourseUtility()
        userUtil = UserUtility()

        username = str(user_input_list[1]).upper()      # force uppercase
        courseName = str(user_input_list[2]).upper()    # force uppercase
        labName = str(user_input_list[3]).upper()       # force uppercase

        if (courseUtil.getContents(courseName) == False):
            return courseName + " does not exist"

        labFound = False
        for i in range(0, courseUtil.getLabs().__len__()):
            if (labName == courseUtil.getLabs()[i]):
                labFound = True
                break
        if (labFound == False):
            return labName + " does not exist"

        user = userUtil.searchUser(username)
        if (user == None):
            return username + " does not exist"

        if (user.getRole() != "TA"):
            return user.getUsername()+" is not a TA"

        oldTA = courseUtil.assignLab(username,labName)

        if (oldTA != "None"):
            if (oldTA == username):
                return username + " is already assigned to " + courseName+"-"+labName
            oldUser = userUtil.searchUser(oldTA)
            if (oldUser != None):
                oldUser.unAssignLab(courseName,labName)
                userUtil.updateUser(oldUser)


        courseUtil.writeContents()

        #user = userUtil.searchUser(username)
        #user.setClass(courseName,courseName+"-"+labName)

        # we know the course and lab already exist, so assign them to this user
        if (user.assignLab(courseName,labName) == False):
            return username + " is already assigned to " + courseName+"-"+labName

        userUtil.updateUser(user)

        return username + " has been assigned to " + labName
Exemplo n.º 36
0
 def __init__(self, fromDev, toDev, devType, group):
     self.fromDev = fromDev
     self.toDev = toDev
     self.group = group
     self.devType = devType
     if devType == Link.CONTROLLER:
         self.name = fromDev.name +" is controller for "+ Command.bToS(toDev)
     else:
         self.name = fromDev.name +" is a responder to "+ Command.bToS(toDev) +" Group: "+ group
Exemplo n.º 37
0
def run_x86(file, output=None):
    if (not which("gcc")):
        print(note)
    else:
        compile_x86(file)
        print('./x86/{}'.format(file[:-2]))
        command = Command('./x86/{}'.format(file[:-2]))
        stdout = command.run()
        for line in stdout:
            print(line[2:-3])
def ChooseRUDrive(root,edict):
    global _sd,_ans,_val
    
    
    def _execute(dialog,key,*other):
        dialog._answer=key
        dialog.deactivate()

    while 1:        
        # locate possible SD
        forced=0
        selected=removable.possible()
        if selected == 0:
            selected=removable.possible(1)   # allow fixed but warn them
            forced=1
        c=[]
        for d in range(32):
            mask = 1<<d
            if selected & mask:
                c.append('%c:' % chr(ord('A')+d))
        bcolor=['light yellow','LightBlue1']
        which=0
        if len(c) == 0:
            ans=tkMessageBox.askokcancel("Selecting client USB drive",'Want to rescan looking for client USB drive?')
            if ans:
                continue
            return None
        _sd=Pmw.Dialog(root,title='Selecting Storage Drive for remote user',buttons=['Cancel','Rescan',])
        _sd.configure(command=Command(_execute,_sd))
        fr=_sd.interior()
        for drv in c:
            Button(fr,text='Click here to use drive '+drv+' for remote user storage',borderwidth=3,height=10,relief='raised',command=Command(_execute,_sd,drv),font=('Arial',16),bg=bcolor[which]).pack(side=TOP,expand=1,fill='x')
            which = 1-which
        
        gpos='=%dx%d+0+%d' % (root.maxw,root.maxh-90,25)
        hull=_sd.component('hull')
        hull.wm_geometry(gpos)
        hull.update()
        hull.transient(root)
        def _freeze_window(tp,geom,event,*args):
            if tp.wm_geometry() != geom:
                tp.wm_geometry(geom)
        hull.bind('<Configure>',Command(_freeze_window,hull,hull.wm_geometry()))
        
        _sd._answer=None
        _sd.activate()

        answer=_sd._answer
        del _sd
        if answer == None or answer =='Cancel':
            return None         # window destroyed
        if answer == 'Rescan':
            continue
        # here if a button was pushed
        return answer
Exemplo n.º 39
0
class Tray(QtGui.QSystemTrayIcon):
    def __init__(self, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, parent)

        self.window = parent
        self.setIcon(QtGui.QIcon("resources/img/icon.png"))

        self.iconMenu = QtGui.QMenu(parent)
        appactivate = self.iconMenu.addAction("Activate")

        skyzoneMenu = QtGui.QMenu(self.iconMenu)
        skyzoneMenu.setTitle("Skyzone")
        self.iconMenu.addMenu(skyzoneMenu)

        strikeMenu = QtGui.QMenu(self.iconMenu)
        strikeMenu.setTitle("Strike")
        self.iconMenu.addMenu(strikeMenu)


        skyzonedevup = skyzoneMenu.addAction("Up Dev")
        skyzoneupprod = skyzoneMenu.addAction("Up Prod")

        strikedevup = strikeMenu.addAction("Up Dev")
        strikeupprod = strikeMenu.addAction("Up Prod")

        self.setContextMenu(self.iconMenu)
        self.connect(appactivate,QtCore.SIGNAL('triggered()'),self.appActivate)

        self.connect(skyzonedevup,QtCore.SIGNAL('triggered()'),self.skyzonedevup)
        self.connect(strikedevup,QtCore.SIGNAL('triggered()'),self.strikedevup)

        quitAction = QtGui.QAction("&Quit", self, triggered=QtGui.qApp.quit)
        self.iconMenu.addAction(quitAction)

        self.show()

    def skyzonedevup(self):
        self.thread = Command('Up Skyzone Dev')
        self.window.printMessage('Up Skyzone Dev')
        QtCore.QObject.connect(self.thread, QtCore.SIGNAL("executeCommandFinished(PyQt_PyObject, PyQt_PyObject)"), self.executeCommandFinished)
        self.thread.start()

    def strikedevup(self):
        #self.window.createCommand('Up Strike Dev')
        self.window.printMessage('Up Strike Dev')
        self.thread = Command('Up Strike Dev')
        QtCore.QObject.connect(self.thread, QtCore.SIGNAL("executeCommandFinished(PyQt_PyObject, PyQt_PyObject)"), self.executeCommandFinished)
        self.thread.start()


    def executeCommandFinished(self, command, result):
        TooltipManage.create('Command', command, result)

    def appActivate(self):
        self.window.activate() # reffer Milana.py activate
Exemplo n.º 40
0
def run_riscv(file, output=None):
    if (not which("spick")) and (not which("riscv64-unknown-elf-gcc") and
                                 (not which("dtc"))):
        print(note)
    else:
        compile_riscv(file)
        print('spike pk riscv/{}'.format(file[:-2]))
        command = Command('spike pk riscv/{}'.format(file[:-2]))
        stdout = command.run()
        for line in stdout:
            print(line[2:-3])
 def run(self):
     while not self._stop:
         #print "hasRun: " + str(self._hasRun) + ", command: " + str(self._command) + ", argument: " + str(self._argument)
         if not self._hasRun and self._command is not None and self._argument is not None:
             #print("executing command: " + self._command + " " + self._argument)
             command = Command(self._command, self._argument)
             self._scriptResponse = command.runAndGetOutputString()
             self._hasRun = True
             #print("result: " + str(self._scriptResponse))
         else:
             #print("not executing command")
             time.sleep(0.1)
     if DEBUG:
         print("ending MultipleCommandExecutionThread")
Exemplo n.º 42
0
  def run(self):
    logging.info('Kill old sessions.')
    self.kill_tcp_processes()

    logging.info('Starting sniffers.')

    if FLAGS.sspath:
      ss_log_name = '%s_%s_%s_%s.ss.log' % \
                     (self.carrier, self.browser, self.domain, str(time.time()))
      ss_log_path = os.path.join(FLAGS.logdir, ss_log_name)
      ss_fh = open(ss_log_path + '.tmp', 'w')
      ss_log = subprocess.Popen([FLAGS.sspath,'-g'], stdout = ss_fh)

    pcap_name = '%s_%s_%s_%s.pcap' % (self.carrier, self.browser, self.domain,
                                      str(time.time()))
    pcap_path = os.path.join(FLAGS.logdir, pcap_name)
    pcap = subprocess.Popen(
      ['tcpdump','-i','%s' % self.interface,'-w', pcap_path + '.tmp'])
    logging.info(str(['tcpdump','-i','%s' % self.interface,'-w', pcap_path]))
    time.sleep(2)

    logging.info('Starting browser.')

    # TODO(tierney): Hacks to fix how we deal with non-terminating connections.
    to_kill = None
    if self.browser == 'chrome':
      to_kill = 'chromedriver'
    elif self.browser == 'firefox':
      to_kill = '/usr/lib/firefox-10.0.2/firefox'

    command = Command('./BrowserRun.py --browser %s --domain %s' % \
                        (self.browser, self.domain))
    command.run(timeout = FLAGS.timeout, pskill = to_kill)

    pcap.terminate()
    os.rename(pcap_path +'.tmp', pcap_path)

    if FLAGS.sspath:
      ss_fh.flush()
      ss_log.terminate()
      ss_fh.flush()
      ss_fh.close()
      os.rename(ss_log_path + '.tmp', ss_log_path)
    return
Exemplo n.º 43
0
	def main_loop(self):
		"""The loop through the lines of the input on which it does stuff. """
		
		input = self.file
		output = self.dest
		
		#different namespaces may be used in a later version of the tool to be
		# able to easily undefine a group of macro's
		namespace = namespaces.NormalNameSpace()
		
		#this linenumber is used in error messages
		self.inputLineNo = 0
		#this linenumber might later be available as a macro
		self.outputLineNo = 0
		
		if self.shebang:
			self.inputLineNo += 1
			line = input.readLine()
		
		for line in input:
			self.inputLineNo += 1
			#when a command is not found, command and after are empty strings
			(before, command, after) = self.command_split(line)
			
			#check if the text is just followed or actually processed
			lc = self.last_condition()
			if lc:
				#only output a line when there was more than whitespace before the
				# command prefix, or when the empty_line option is True. 
				if (before.strip() != "" 
						or (self.options["empty_line"] and command == "")):
					output.write(self.replace_object_macro(namespace, before))
					self.outputLineNo += 1
			
			#check if the command here is to be ignored
			if (command != "" and Command.command_allowed(command, lc)):
				try:
					Command.get_command_func(command)(namespace, after, 
						self.last_condition, self.conditions, self.else_found)
				except ValueError as e:
					self.error(e.args[0])
				except IndexError as e:
					self.error(e.args[0])
Exemplo n.º 44
0
def download(uri, dirname=None, output=None):

    if dirname is None:
        dirname = os.getcwd()

    if output is None:
        output = '/dev/null'

    dest_path = os.path.join(dirname, os.path.basename(uri))
    cmd = get_download_command(uri, dest_path, output)
    if cmd is None:
        return False

    command = Command(cmd, dirname)
    try:
        command.run()
    except:
        return False

    return os.path.exists(dest_path)
Exemplo n.º 45
0
 def traverseAldb(self, startAddress):
     
     while startAddress > 0x00:
         print("Checking: 0x%0.2x" % startAddress)
         SerialInstance().ser.flushInput()
         SerialInstance().ser.flushOutput()
         Command.queryMemory(self.deviceId, bytes([0x0F, startAddress]))
         i = SerialInstance().ser.readline()
         sleep(.3)
         #Keep reading the address until we don't get a NACK
         if re.search(r'(\w)+(15)\b', Command.bToS(i)):
             print('Received NACK')
             continue #This makes it stop here and try again
             
         elif re.search(r'(\w)+(06)\b', Command.bToS(i)):
             for _ in range(50):
                 SerialInstance().ser.flushInput()
                 SerialInstance().ser.flushOutput()
                 i = SerialInstance().ser.readline()
                 cmdStr = Command.bToS(i)
                 if len(i) > 0:
                     print("06: %s" % cmdStr)
                 if (len(i) > 0 and len(cmdStr) == 50):
                     self.addToAldb(i)
                     startAddress = startAddress - 0x08
                     print("address Decremented")
                     break
         if re.search(r'(\w)+0(0|1)0000000000000000(\w\w){0,1}\b', Command.bToS(i)):
             print("Found blank address: %02x" % startAddress)
             return bytearray([i[13], i[14]])
Exemplo n.º 46
0
 def addLinkToAldb(self, deviceTolink, groupNum):
     msg = bytearray([0x02, 0x62])
     msg.extend(self.deviceId)
     msg.extend([0x1F, 0x2f, 0x00, 0x00, 0x00, 0x02])
     msg.extend(self.confirmFreeMem())
     msg.append(0x08)
     if True: #self.isController:
         msg.append(0xE2)
     else:
         msg.append(0xA2)
     msg.append(groupNum)
     msg.extend(deviceTolink.deviceId)
     #Device Data - based on other aldb data
     msg.append(self.data1)
     msg.append(self.data2)
     if self.data3 == 0xbad: #Code used for same as groupNum
         msg.append(groupNum)
     else:
         msg.append(self.data3)
     if self.data4 == 0xbad: #Must be a checksum
         msg.append(Util.getChecksum(msg))
     else:
         msg.append(self.data4)
     print('ALDB Add: %s' % Command.spaceOut(Command.bToS(msg)))
Exemplo n.º 47
0
    def disconnect(client):

        try:
            # remove it from the list
            ConnectionsManager.clients.remove(client)
            # close the socket listening
            client.socket.close()
            # broadcast the disconnexion
            message=Command.create(command=Command.LOGOUT,id=str(client.id))
            ConnectionsManager.broadcast(message)

            print("disconnection of "+repr(client.address))
            print(ConnectionsManager.clientSize())
        except ValueError:
            print('noting to disconnect or already disconnected')
Exemplo n.º 48
0
	def __init__(self, loc, objectType, player):
		#Static attributes:
		self.loc = loc

		if(objectType in self.validObjects):
			self.objectType = objectType
		else:
			self.objectType = 'default'

		self.ID = None
		self.player = player
		self.mass = {'beacon':1000, 'tower':100, 'default':10, 'drone':10, 'asteroid':5, 'mine':1, 'scrap':1, 'worker':10, 'fighter':15}[self.objectType] #Get mass from dictionary according to the object type
		#Dynamic attributes:
		self.velocity = [0, 0] #Velocity vector. For example: [1, 0] refers to positive x direction at 1 unit per second
		self.acceleration = [0, 0]
		self.current_cmd = Command('drift') #Initialize GameObjec to drift based on initial acceleration and velocity when created
		self.angle = 0
Exemplo n.º 49
0
 def checkSyntax(self):
     test = self.getInput().strip()
     
     if (test[0] == '{') and (test[len(test)-1] == '}'):
         c = Command(test[1:len(test)-1],self) #supposed to put though everything between {}
         c.setSyntaxOnly(self.syntax_only)
         if not self.syntax_only:
             c.setPropertyList(self.property_list) #commands should get access to all already existing propertylists?
         if c.checkSyntax():
             if not self.syntax_only:
                 cList = c.getPropertyList().getDict()
                 sList = self.property_list.getDict()
                 sList.update(cList)
             return True
         else:
             return False
     else:
         print "The first symbol (currently '" + test[0] + ("') needs to be '{' and the last symbol "
             "(currently '") + test[len(test)-1] + "') needs to be '}'. Therefore the block is not valid."
         return False
Exemplo n.º 50
0
 def __init__(self, plane):
     Command.__init__(self)
     if plane is None:
         raise "WaitCommand : null reference"
     self.plane = plane
Exemplo n.º 51
0
__author__ = 'wenychan'

from Command import Command
from LocalExecutor import LocalExec
from RemoteExecutor import RemoteExec

command = Command('echo')
command.add_argument('${text}')
dict = {}
dict['text'] = 'aaaaaaaa'
command.set_substitution_dict(dict)
command1 = Command('ls -a')
command2 = Command('echo')
command2.add_argument('${text}')
dict = {}
dict['text'] = 'bbbbbbbbbbb'
command2.set_substitution_dict(dict)
ins = LocalExec(command)

ins.add_command(command1)
ins.insert_command_at(1, command2)
# ins.show_commands()

ins.add_command("python aaa.py")

print
print

ins2 = LocalExec([command1, command2])
# ins2.show_commands()
print
Exemplo n.º 52
0
 def __init__(self):
     Command.__init__(self, Constants.RESTART_TAG)
Exemplo n.º 53
0
 def __init__(self, plane, quantity_fuel):
     Command.__init__(self)
     if plane is None:
         raise "FillFuelTankCommand : Null reference"
     self.planeSrc = plane
     self.quantity = quantity_fuel
Exemplo n.º 54
0
 def __init__(self, config, **params):
     Command.__init__(self, config, **params)
Exemplo n.º 55
0
 def __init__(self, plane, base):
     Command.__init__(self)
     if base is None or plane is None:
         raise "LandCommand : null reference"
     self.plane = plane
     self.base = base
Exemplo n.º 56
0
 def __init__(self):
     Command.__init__(self, Constants.SHUTDOWN_TAG)
Exemplo n.º 57
0
	def __init__(self, main):
		Command.__init__(self, main)
Exemplo n.º 58
0
 def printAldb(self):
     print('Device: %s' % self.name)
     for x in range(len(self.aldb)):
         print('%d: %s' % (x, Command.spaceOut(Command.bToS(self.aldb[x]))))
Exemplo n.º 59
0
	def __init__(self):
		Command.__init__(self)
Exemplo n.º 60
0
	def __init__(self, template):
		Command.__init__(self)
		self.eventTemplate = template