Пример #1
0
    def __init__(self):

        # this is only changed once the ball is kicked
        self.switch_goal = False
        self.prev_state = state.none
        self.prev_ball = -1
        self.prev_goal = -1

        # CONDITIONS
        self.ball_in_dribbler = False
        self.ball_found = False
        self.goal_found = False
        self.goal_aligned = False

        # STATES
        self.state = state.none
        self.search = search.none

        # OBJECTS
        self.drive_sys = Drive()
        self.dribbler = Dribbler()
        self.field = Field()
        self.kicker = Kicker()

        # MOTOR pwm
        self.left_motor = 0
        self.right_motor = 0

        # range/headings
        self.obs_range = [None, None, None]
        self.obs_heading = [None, None, None]
        self.ball_range = None
        self.ball_heading = None
        self.goal_range = None
        self.goal_heading = None
Пример #2
0
class StateMachineNode:

    def __init__(self):
        rospy.init_node('state_machine')

        self.markers_subscriber = rospy.Subscriber(AR_TAG_TOPIC, AlvarMarkers,
                                                   self.markers_callback, queue_size=10)
        self.starter_subscriber = rospy.Subscriber(STARTER_TOPIC, Bool,
                                                   self.start_callback, queue_size=10)

        self.lights_off = False

        self.state = State.nothing

        self.drive = Drive()
        self.image_processor = ImageProcessor()
        self.cv_bridge = CvBridge()

        self.drive_speed = 1.2503309
        self.left_goal_dist = 0.90
        self.right_goal_dist = 0.8

    def markers_callback(self, msg):
        self.update_state(msg.markers)

        print("State: %s" % self.state)

        if self.state == State.follow_middle:
            self.drive.drive_middle(self.drive_speed)
                    elif self.state == State.follow_left:
            self.drive.drive_left(self.left_goal_dist, self.drive_speed)
Пример #3
0
 def __init__(self, config, service_type):
     self.__config = config
     self.info = {
         'details': []
     }
     if service_type == SERVICE_DRIVE:
         self.service = Drive(config)
     elif service_type == SERVICE_DROPBOX:
         raise NotImplementedError('not implemented yet!')
Пример #4
0
def get_email_user():
    drive = Drive()
    creds = drive.setup_creds()
    emailUser = []

    print("GETTING USER EMAIL")
    emailUser.append(drive.get_user_info(creds)['email'])
    print("DONE!")

    return emailUser
Пример #5
0
def main():

    import config
    import time
    import logging
    from drive import Drive

    logging.basicConfig(level=logging.DEBUG)
    log = logging.getLogger(__name__)

    log.info("Testing vision subsystem")

    vision = Vision(config)
    drive = Drive()
    drive.close_tray()

    calibration_markers = None
    while True:

        drive.close_tray()

        log.info("Acquiring calibration image")
        image_filename = vision.image_acquire()
        if not image_filename:
            log.warn(
                "Could not acquire image for calibration, please check the camera"
            )
            time.sleep(config.camera_calibration_delay)
            continue

        (calibration_markers, frame) = vision.detect_markers(image_filename)
        os.unlink(image_filename)

        log.debug("Markers detected during calibration: '{}'".format(
            calibration_markers))

        if calibration_markers and 'disk_center' in calibration_markers and 'disk_edge' in calibration_markers:
            break
        else:
            log.warn(
                "Both calibration markers need to be detectable, please adjust the camera or lighting conditions"
            )
            time.sleep(config.camera_calibration_delay)

    log.info(
        "Camera calibration was successful, calibration markers detected: {}".
        format(calibration_markers))

    drive.open_tray()

    camera_image_filename = vision.image_acquire('camera-image')
    vision.write_cover_image(camera_image_filename, 'cover.png',
                             calibration_markers)

    drive.close_tray()
Пример #6
0
 def __init__(self,mode,device,calibrationSpeeds):
     baud = 9600
     if mode == Mode.SIM:
         self.drive = Drive(device,baud,simulate=1,calibration=calibrationSpeeds)
     elif mode == Mode.LIVE:
         self.drive = Drive(device,baud,simulate=0,calibration=calibrationSpeeds, persist=False)
     self.pos = self.azalt()
     self.getCurrentPos()
     self.location = self.drive.location  #TODO - use this
     self.status = Status.INIT
     self.mode = mode
Пример #7
0
	def mount(drive_name):
		'''
		Reconnects a drive as a volume.
		Any data on the drive is preserved.
		Returns the volume.
		'''
		drive = Drive.reconnect(drive_name)
		inputt = drive.read_block(0)
		data = inputt.splitlines()
		length = int(data[0])
		i = 1
		while i < length:
			inputt = drive.read_block(i)
			data.extend(inputt.splitlines())
			i+=1
		i = 1
		outcome = False
		
		data[len(data)-1] = data[len(data)-1].rstrip()
	
		while len(data) > (i+1):
			while len(data) > (i+1) and data[i+1].isdigit() == outcome:
				data[i] += data[i+1]
				data.pop(i+1)
			i+=1
			outcome = not outcome
		
		volume = Volume(drive, data[1])
		for i in range(len(data[3])):                #TODO Needs better fix
			if data[3][i] == 120:
				volume.bmap[i] = b'x'
		volume.import_files()

		return volume
Пример #8
0
    def mount(drive_name):
        '''
        Reconnects a drive as a volume.
        Any data on the drive is preserved.
        Returns the volume.
        '''
        drive = Drive.reconnect(drive_name)
        vol = Volume()

        block = drive.read_block(0).split(b'\n')
        volinfosize= int(bytes.decode(block[0]))
        volinfo =b''
        volinfo+=drive.read_block(0)
        if volinfosize!=1:
            for i in range (1,volinfosize+1):
                volinfo+=drive.read_block(i)
        vol.setSize(int(bytes.decode(block[2])))
        vol.setDrive(drive)

        bmpArr =[]
        
        bmp = bytes.decode(volinfo.split(b'\n')[3])

        for i,v in enumerate(bmp):
            if v == 'x':
                bmpArr.append(1)
            else:
                bmpArr.append(0)
        vol.setVolInfo(volinfo)
        vol.setBitmapArray(bmpArr)
        return vol
Пример #9
0
 def __init__(self, args):
     self._args = args
     self._drive = DummyDrive() if args.nohw else Drive()
     self._finder = PositionsFinder(args.debug)
     self._hysteresis = Hysteresis(frames=args.frames,
                                   resolution=args.resolution,
                                   threshold=args.threshold)
Пример #10
0
 def __init__(self):
     super().__init__()
     self.loader = Loader()
     self.shooter = Shooter()
     self.drive = Drive(config.robotDrive, config.leftJoy, config.hsButton,
                        config.alignButton)
     self.componets = [ self.loader, self.shooter, self.drive ]
Пример #11
0
 def get_drives(self):
     drives = []
     for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
         drive = Drive(letter)
         if drive.type:
             log.debug('drive=%s' % str(drive))
             drives.append(drive)
     return drives
Пример #12
0
 def __init__(self, config, service_type):
     self.__config = config
     self.info = {
         'details': []
     }
     if service_type == SERVICE_DRIVE:
         self.service = Drive(config)
     elif service_type == SERVICE_DROPBOX:
         raise NotImplementedError('not implemented yet!')
Пример #13
0
 def _initEmptyBoard(self):
     """
     :return: the initialized board
     """
     board = [[Square(None, i, j) for j in range(5)] for i in range(5)]
     board[0][0] = Square(Note(False), 0, 0)
     board[0][1] = Square(Governance(False), 0, 1)
     board[0][2] = Square(Relay(False), 0, 2)
     board[0][3] = Square(Shield(False), 0, 3)
     board[0][4] = Square(Drive(False), 0, 4)
     board[1][4] = Square(Preview(False), 1, 4)
     board[3][0] = Square(Preview(True), 3, 0)
     board[4][0] = Square(Drive(True), 4, 0)
     board[4][1] = Square(Shield(True), 4, 1)
     board[4][2] = Square(Relay(True), 4, 2)
     board[4][3] = Square(Governance(True), 4, 3)
     board[4][4] = Square(Note(True), 4, 4)
     return board
Пример #14
0
class Upload(object):
    """
    TODO interface or abstract class for upload services
    """

    def __init__(self, config, service_type):
        self.__config = config
        if service_type == SERVICE_DRIVE:
            self.service = Drive(config)
        elif service_type == SERVICE_DROPBOX:
            raise NotImplementedError('not implemented yet!')

    def run(self, paths):
        """
        """
        for path in paths:
            self.service.upload(path)
            log_dict(self.service.info)
Пример #15
0
    def __init__(self):
        rospy.init_node('state_machine')

        self.markers_subscriber = rospy.Subscriber(AR_TAG_TOPIC, AlvarMarkers,
                                                   self.markers_callback, queue_size=10)
        self.starter_subscriber = rospy.Subscriber(STARTER_TOPIC, Bool,
                                                   self.start_callback, queue_size=10)

        self.lights_off = False

        self.state = State.nothing

        self.drive = Drive()
        self.image_processor = ImageProcessor()
        self.cv_bridge = CvBridge()

        self.drive_speed = 1.2503309
        self.left_goal_dist = 0.90
        self.right_goal_dist = 0.8
Пример #16
0
 def test_long_volume_name(self):
     blocks = 100
     drive_name = 'driveH.txt'
     disk = Drive.format(drive_name, blocks)
     name = b'long volume name' * 100
     volume = Volume.format(disk, name)
     self.assertEqual(name, volume.name())
     self.assertEqual(blocks, volume.size())
     self.assertEqual(99, volume.root_index())
     volume.unmount()
Пример #17
0
    def mount(drive_name):
        drive = Drive.reconnect(drive_name)
        allVolumeData = drive.read_block(0).decode()
        numOfBlocksUsed = allVolumeData.split('\n',1)[0]
        if int(numOfBlocksUsed)>1:
            for i in range(1,int(numOfBlocksUsed)):
                allVolumeData+=drive.read_block(i).decode() 
                
        data = allVolumeData.split('\n')
        numOfBlocksUsed=int(data[0])
        name = data[1]
        #dont need this
        numOfBlocksInDrive = int(data[2])
        bitmap = data[3]
        rootIndex = int(data[4])
        usedDrives=[False]*numOfBlocksInDrive
        Volume.calculate_volume_data_blocks(name, drive, rootIndex)
        numOfDataBlocks = Volume.calculate_volume_data_blocks(name, drive, rootIndex )
        for i in range(numOfDataBlocks):
            usedDrives[i]=True
        usedDrives[rootIndex]=True
        volume = Volume(drive, name.encode(), rootIndex, usedDrives, numOfBlocksUsed)
        #read the rootdirectory
        rootString = drive.read_block(rootIndex).decode()
        root= rootString.split('\n')
        for i in range(len(root)):
            if root[i].isdigit():
                if int(root[i])!=0:

                    fileData =  volume.drive.read_block(int(root[i])).decode().split('\n')
                    for i in range(0,len(fileData)-1,3):
                        fileName = fileData[i]
                        fileDataLength =  fileData[i+1]
                        fileStart = fileData[i + 2]
                        #then go into the fileStart
                        fileDirectory = volume.drive.read_block(int(fileStart))
                        fileDirectory = fileDirectory.decode().split('\n')
                        dataLocations = []
                        for j in range(len(fileDirectory)):
                            if fileDirectory[j].isdigit():
                                dataLocations.append(fileDirectory[j])
                        #now that we have all the locations of the data, we can read all the locations and concatinate them
                        dataOnFile = b''
                        for k in range(len(dataLocations)):
                            dataOnFile+=volume.drive.read_block(int(dataLocations[k]))
                        #only want the first n bits
                        dataOnFile = dataOnFile[:int(fileDataLength)]    
                        file = volume.open(fileName.encode())
                        file.write(0, dataOnFile)
                        print (file.data)
                    
        #print (root)
        
        return volume
        '''
Пример #18
0
    def __init__(self):
        Config.update()

        self.sound = Sound()

        # sensor values
        self.sensLeft = ColorSensor(INPUT_1)
        self.sensRight = ColorSensor(INPUT_4)  # TODO: Sensoren anschließen
        self.sensIR = InfraredSensor(INPUT_2)
        self.sensTouch = TouchSensor(INPUT_3)

        self.btn = Button()

        self.sensValues = {}

        # Classes for features
        self.drive = Drive()
        self.cross = Cross()
        # statemachine
        self.fsm = StateMachine()
        # adding States
        self.fsm.states["followLine"] = State("followLine")
        self.fsm.states["followLine"].addFunc(self.drive.followLine,
                                              self.sensValues)

        self.fsm.states["brake"] = State("brake")

        self.fsm.states["crossFirstTurn"] = State("crossFirstTurn")
        self.fsm.states["crossFirstTurn"].addFunc(self.cross.firstTurn,
                                                  self.sensValues)

        self.fsm.states["checkNextExit"] = State("checkNextExit")
        self.fsm.states["checkNextExit"].addFunc(self.drive.followLine,
                                                 self.sensValues)

        # adding Transitions
        self.fsm.transitions["toFollowLine"] = Transition("followLine")

        self.fsm.transitions["toBrake"] = Transition("brake")
        self.fsm.transitions["toBrake"].addFunc(self.drive.brake)

        self.fsm.transitions["toCrossFirstTurn"] = Transition("crossFirstTurn")
Пример #19
0
def simulate(drive_sizes, file_size, strategy):
    drives = list(map(lambda drive_size: Drive(drive_size), drive_sizes))
    candidates = list(filter(lambda drive: drive.free() >= file_size, drives))
    while candidates:
        for drive in drives:
            drive.tick()
        selection = strategy(candidates)
        selection.store(file_size)
        if selection.free() < file_size:
            candidates.remove(selection)
    return drives
Пример #20
0
 def test_long_volume_name(self):
      blocks = 10
      drive_name = 'driveB.txt'
      drive = Drive.format(drive_name, blocks)
      name = b'long volume name' * 10
      volume = Volume.format(drive, name)
      self.assertEqual(3, volume.volume_data_blocks())
      self.assertEqual(name, volume.name())
      self.assertEqual(blocks, volume.size())
      self.assertEqual(b'xxx------x', volume.bitmap())
      self.assertEqual(9, volume.root_index())
      volume.unmount()
Пример #21
0
 def test_reconnect_drive(self):
      blocks = 10
      drive_name = 'driveC.txt'
      drive = Drive.format(drive_name, blocks)
      drive.disconnect()
      with self.assertRaises(IOError):
          Drive.reconnect('badname')
      drive = Drive.reconnect(drive_name)
      self.assertEqual(blocks * Drive.BLK_SIZE, drive.num_bytes())
      name = b'reconnect volume'
      volume = Volume.format(drive, name)
      volume.unmount()
      with self.assertRaises(IOError):
          Volume.mount('driveZ')
      volume = Volume.mount(drive_name)
      self.assertEqual(1, volume.volume_data_blocks())
      self.assertEqual(name, volume.name())
      self.assertEqual(blocks, volume.size())
      self.assertEqual(b'x--------x', volume.bitmap())
      self.assertEqual(9, volume.root_index())
      volume.unmount()
Пример #22
0
class Robot():

    # 100 ms update (stable frequency) / 50 ms update (maximum frequency)
    PERIODIC_DELAY = 0.05

    stopped = False

    def __init__(self):
        self.drive = Drive()
        self.oi = OperatorInterface(self.drive)
        self.drive.setOperatorInterface(self.oi)

    def update(self):
        self.drive.update()

    def stop(self):
        self.stopped = True
        self.drive.stop()
        self.oi.stop()

    def periodic(self):
        nextTime = time.time()
        while (not self.stopped):
            try:
                self.update()

                nextTime = nextTime + self.PERIODIC_DELAY
                delay = max(0, nextTime - time.time())
                if (delay == 0):
                    print("--------------THRASH--------------")
                time.sleep(delay)
            except:
                print("Exception in Periodic")
                traceback.print_exc()
                self.stop()
Пример #23
0
    def __init__(self):

        self.circle_obstacle = False
        self.goto_ball = False
        self.ball_captured = False
        self.goto_obstacle = False
        self.goto_goal = False
        self.ball_found = False
        self.goal_found = False
        self.goal_clear = False
        self.spin = False
        self.search_obs = False
        self.timer = Timer()

        self.target_side = -1
        self.ball_side = -1
        self.goal_side = -1
        self.wall_side = -1
        self.obs_side = -1
        self.speed_mod = 1

        self.no_target_count = 0
        self.circle_count = 0

        self.obs_r = None
        self.obs_h = None
        self.ball_r = None
        self.ball_h = None
        self.goal_r = None
        self.goal_h = None
        self.wall_r = None
        self.wall_h = None
        self.target_r = None
        self.target_h = None
        self.target_found = False

        self.drive_sys = Drive()
        self.dribbler = Dribbler()
        self.kicker = Kicker()
Пример #24
0
class Upload(object):
    """
    TODO interface or abstract class for upload services
    """

    def __init__(self, config, service_type):
        self.__config = config
        self.info = {
            'details': []
        }
        if service_type == SERVICE_DRIVE:
            self.service = Drive(config)
        elif service_type == SERVICE_DROPBOX:
            raise NotImplementedError('not implemented yet!')

    def run(self, paths):
        """
        """
        for path in paths:
            self.service.upload(path)
            self.info['details'].append(self.service.info)
            log_dict(self.service.info)
Пример #25
0
 def format(self, name):
     thisDrive = Drive(name)
     thisDrive.format()
     thisDrive.write_block(0, "+" + "-" * 127 + ("f:" + " " * 9 + "0000:" + "000 " * 12) * 6)
     global availableBlocksList
     availableBlocksList = ['+'] + ['-' for x in range(127)]
     global availableBlockIndices 
     availableBlockIndices = list(range(1, 128))
     self.currentDrive = thisDrive
     self.rootDirectory = Directory(self.currentDrive, None, 0, None, None) #drive, fileNum, parentBlockNum, parent, name
     self.blocksAvailability = thisDrive.read_block(0)[:127]
Пример #26
0
 def test_file_reads(self):
      volume = Volume.format(Drive.format('driveE.txt', 8), b'file read volume')
      file = volume.open(b'fileA')
      data = b'A different fileA'
      file.write(0, data)
      with self.assertRaises(IOError):
          file.read(30, 1)
      with self.assertRaises(IOError):
          file.read(0, 50)
      self.assertEqual(data, file.read(0, len(data)))
      self.assertEqual(b'if', file.read(3, 2))
      file.write(file.size(), b'Aaargh' * 10)
      self.assertEqual(b'arghAaarghAaargh', file.read(61, 16))
      volume.unmount()
Пример #27
0
 def test_file_reads(self):
     volume = Volume.format(Drive.format("driveK.txt", 100), b'file read volume')
     file = volume.open(b'fileA')
     data = b'A different fileA' * 10
     file.write(0, data)
     with self.assertRaises(IOError):
         file.read(300, 1)
     with self.assertRaises(IOError):
         file.read(0, 500)
     self.assertEqual(data, file.read(0, len(data)))
     self.assertEqual(b'if', file.read(71, 2))
     file.write(file.size(), b'Aaargh' * 100)
     self.assertEqual(b'AaarghAaargh', file.read(500, 12))
     volume.unmount()
Пример #28
0
 def test_reconnect_drive_with_files(self):
     drive_name = 'driveF.txt'
     volume = Volume.format(Drive.format(drive_name, 12), b'reconnect with files volume')
     filenames = [b'file1', b'file2', b'file3', b'file4']
     files = [volume.open(name) for name in filenames]
     for i, file in enumerate(files):
         file.write(0, bytes(str(i).encode()) * 64)
     files[0].write(files[0].size(), b'a')
     volume.unmount()
     volume = Volume.mount(drive_name)
     file4 = volume.open(b'file4')
     self.assertEqual(b'3333', file4.read(0, 4))
     file1 = volume.open(b'file1')
     self.assertEqual(65, file1.size())
     self.assertEqual(b'0a', file1.read(63, 2))
     volume.unmount()
Пример #29
0
 def test_simple_file_creation(self):
     # the Volume didn't call format in the original
     volume = Volume.format(Drive.format('driveD.txt', 8), b'file creation volume')
     with self.assertRaises(ValueError):
      volume.open(b'fileA\n')
     file = volume.open(b'fileA')
     self.assertEqual(0, file.size())
     data = b'Hello from fileA'
     file.write(0, data)
     self.assertEqual(len(data), file.size())
     file.write(file.size(), data)
     self.assertEqual(2 * len(data), file.size())
     file = volume.open(b'fileB')
     data = b'Welcome to fileB'
     file.write(50, data)
     self.assertEqual(50 + len(data), file.size())
     volume.unmount()
Пример #30
0
def get_files():
    drive = Drive()
    service = drive.setup_service(drive.setup_creds())

    print("GETTIN FILES EXTENSION")
    fileExtension = drive.get_file_extension(service)
    print("DONE!")
    print("GETTING FILES FROM GOOGLE DRIVE")
    files = drive.get_data_api(service)
    print("DONE!")

    return files, fileExtension
Пример #31
0
def main():
    """Uploads files in a directory to Google Drive.

    """
    upload_dir_path = os.path.abspath(arguments.upload_dir) + "/"
    my_drive = Drive()
    folder = my_drive.query("name = 'Drone Club Videos'")
    folder_id = folder['files'][0]['id']
    new_folder_id = my_drive.create_folder(str(datetime.date.today()),
                                           folder_id)
    for f in os.scandir(upload_dir_path):
        my_drive.upload_file(f.name, f.path, new_folder_id)
Пример #32
0
 def test_simple_file_creation(self):
     volume = Volume.format(Drive.format('driveJ.txt', 100), b'file creation volume')
     with self.assertRaises(ValueError):
         volume.open(b'dir/fileA')    # incase we ever implement subdirectories
     with self.assertRaises(ValueError):
         volume.open(b'fileA\n')
     file = volume.open(b'fileA')
     self.assertEqual(0, file.size())
     data = b'Hello from fileA' * 10
     file.write(0, data)
     self.assertEqual(len(data), file.size())
     file.write(file.size(), data)
     self.assertEqual(2 * len(data), file.size())
     file = volume.open(b'fileB')
     data = b'Welcome to fileB'
     file.write(500, data)
     self.assertEqual(500 + len(data), file.size())
     volume.unmount()
Пример #33
0
 def test_new_volume(self):
     blocks = 10
     drive_name = 'driveA.txt'
     drive = Drive.format(drive_name, blocks)
     with self.assertRaises(ValueError):
         Volume.format(drive, b'')
     with self.assertRaises(ValueError):
         Volume.format(drive, b'Volume\nA')
     with self.assertRaises(ValueError):
         Volume.format(drive, b'a' * blocks * Drive.BLK_SIZE)
     name = b'new volume test'
     volume = Volume.format(drive, name)
     self.assertEqual(1, volume.volume_data_blocks())
     self.assertEqual(name, volume.name())
     self.assertEqual(blocks, volume.size())
     self.assertEqual(b'x--------x', volume.bitmap())
     self.assertEqual(9, volume.root_index())
     volume.unmount()
Пример #34
0
 def test_reconnect_disk_with_files(self):
     drive_name = 'driveL.txt'
     volume = Volume.format(Drive.format(drive_name, 500), b'reconnect with files volume')
     files = []
     for i in range(100):
         name = 'file{:02}'.format(i).encode()
         files.append(volume.open(name))
     for i,file in enumerate(files):
         file.write(0, str(i).encode() * 64)
     files[99].write(files[99].size(), b'a')
     volume.unmount()
     volume = None
     volume = Volume.mount(drive_name)
     file4 = volume.open(b'file04')
     self.assertEqual(b'4444', file4.read(0, 4))
     file99 = volume.open(b'file99')
     self.assertEqual(129, file99.size())
     self.assertEqual(b'9a', file99.read(file99.size() - 2, 2))
     volume.unmount()
Пример #35
0
 def create(self, entity_type, name, parent_path):
     if entity_type != Drive and not parent_path:
         raise IllegalFileSystemOperation(
             'only drives can be at the root level')
     # if a drive is being created
     if entity_type == Drive and not parent_path:
         self.add_drive(Drive(name))
         return
     parent = self.get_entity(parent_path)
     if type(parent) == Text:
         raise IllegalFileSystemOperation('parent cannot be a text file')
     if entity_type == Drive and parent_path:
         raise IllegalFileSystemOperation('drive cannot have a parent')
     # if PathNotFound, we know that the path is available
     try:
         self.get_entity(parent_path + '\\' + name)
         raise PathAlreadyExists
     except PathNotFound:
         parent.add_child(entity_type(name, parent))
Пример #36
0
 def undo_EFI_folder(self, associated_task):
     for efi_drive in 'HIJKLMNOPQRSTUVWXYZ':
         drive = Drive(efi_drive)
         if not drive.type:
             break
     efi_drive = efi_drive + ':'
     log.debug("Temporary EFI drive %s" % efi_drive)
     try:
         run_command(['mountvol', efi_drive, '/s'])
         dest = join_path(efi_drive, 'EFI',
                          self.info.previous_target_dir[3:], 'wubildr')
         dest.replace(' ', '_')
         dest.replace('__', '_')
         if os.path.exists(dest):
             log.debug('Removing EFI folder %s' % dest)
             shutil.rmtree(dest)
         run_command(['mountvol', efi_drive, '/d'])
     except Exception, err:  #this shouldn't be fatal
         log.error(err)
Пример #37
0
 def modify_EFI_folder(self, associated_task, bcdedit):
     command = [bcdedit, '/enum', '{bootmgr}']
     boot_drive = run_command(command)
     if 'partition=' in boot_drive:
         boot_drive = boot_drive[boot_drive.index('partition=') + 10:]
     else:
         boot_drive = boot_drive[boot_drive.index('device') + 24:]
     boot_drive = boot_drive[:boot_drive.index('\r')]
     log.debug("EFI boot partition %s" % boot_drive)
     # if EFI boot partition is mounted we use it
     if boot_drive[1] == ':':
         efi_drive = boot_drive
     else:
         for efi_drive in 'HIJKLMNOPQRSTUVWXYZ':
             drive = Drive(efi_drive)
             if not drive.type:
                 break
         efi_drive = efi_drive + ':'
         log.debug("Temporary EFI drive %s" % efi_drive)
     if efi_drive != boot_drive:
         run_command(['mountvol', efi_drive, '/s'])
     src = join_path(self.info.root_dir, 'winboot', 'EFI')
     src.replace(' ', '_')
     src.replace('__', '_')
     dest = join_path(efi_drive, 'EFI', self.info.target_dir[3:])
     dest.replace(' ', '_')
     dest.replace('__', '_')
     if not os.path.exists(dest):
         shutil.os.mkdir(dest)
     dest = join_path(dest, 'wubildr')
     if os.path.exists(dest):
         shutil.rmtree(dest)
     log.debug('Copying EFI folder %s -> %s' % (src, dest))
     shutil.copytree(src, dest)
     if self.get_efi_arch(associated_task, efi_drive) == "ia32":
         efi_path = join_path(dest, 'grubia32.efi')[2:]
     else:
         efi_path = join_path(dest, 'shimx64.efi')[2:]
     if efi_drive != boot_drive:
         run_command(['mountvol', efi_drive, '/d'])
     return efi_path
Пример #38
0
    def mount(drive_name):
        '''
        Reconnects a drive as a volume.
        Any data on the drive is preserved.
        Returns the volume.
        '''
        print("mounting volume: " + str(drive_name))

        volume = Volume()
        volume.drive = Drive.reconnect(drive_name)
        # volume.drive_name = drive.name
        # int
        volume.block_info_occupied_blocks_num = int(volume.drive.read_block(0).split()[0].decode())
        # int
        volume.BLK_SIZE = volume.drive.BLK_SIZE
        # print("mounting: " + str(volume.drive.read_block(0)))
        volumeInfoByte = volume.read_block_info()
        volumeInfoStr = volumeInfoByte.decode().split('\n')

        # volume.volumeName = volumeInfoStr[1].encode()
        # volume.numberOfBlocks = int(volumeInfoStr[2])
        # volume.bitmapStr = volumeInfoStr[3]
        # volume.rootDirIndex = int(volumeInfoStr[4])
        # volume.rootFileList = volume.getRootFileList()
        # volume.openingFiles = []
        print("volumeInfoStr: " + str(volumeInfoStr))
        # byte
        volume.volume_name = volumeInfoStr[1].encode()
        # int
        volume.total_num_of_blocks = int(volumeInfoStr[2])
        # str
        volume.bitmapStr = volumeInfoStr[3]
        print("mounting volume with bitmap: " + volume.bitmapStr)
        # int int(volumeInfoStr[4]) [s.strip() for s in content_byte.decode().split("\n") if s.strip() != ""]
        volume.root_files_block_index = [int(i) for i in volumeInfoStr[4].split() if i.strip() != "" and i.isdigit()]
        print("root_files_block_index: " + str(volume.root_files_block_index))
        # array
        volume.rootFileList = volume.get_root_file_list()
        volume.openingFiles = []
        return volume
Пример #39
0
    def store_drives(raw_drives):
        # takes as input raw_drives from the blkid command
        # Returns a list of Drive objects

        connected_drives = []
        for i in range(len(raw_drives)):
            temp_drive = Drive()
            temp_raw_drive = raw_drives[i].split()
            for attribute in temp_raw_drive:
                if '/dev' in attribute:
                    attribute = list(attribute)
                    attribute.pop()
                    attribute = ''.join(attribute)
                    temp_drive.set_source(attribute)
                elif 'TYPE' in attribute:
                    temp_drive.set_fs(attribute)
            connected_drives.append(temp_drive)
        return connected_drives
Пример #40
0
    def __init__(self):
        proc = subprocess.Popen('sudo blkid',
                                stdout=subprocess.PIPE,
                                shell=True)
        (drives, err) = proc.communicate()
        drives = drives.decode('utf-8').split('\n')

        connected_drives = []
        for i in range(len(drives)):
            temp_drive = Drive()
            temp_source = ''
            temp_fs = ''
            temp_raw_drive = drives[i].split()
            for attribute in temp_raw_drive:
                if '/dev' in attribute:
                    attribute = list(attribute)
                    attribute.pop()
                    attribute = ''.join(attribute)
                    temp_drive.set_source(attribute)
                elif 'TYPE' in attribute:
                    temp_drive.set_fs(attribute)
            connected_drives.append(temp_drive)
        self.drives = connected_drives
Пример #41
0
class SRT():   
    def __init__(self,mode,device,calibrationSpeeds):
        baud = 9600
        if mode == Mode.SIM:
            self.drive = Drive(device,baud,simulate=1,calibration=calibrationSpeeds)
        elif mode == Mode.LIVE:
            self.drive = Drive(device,baud,simulate=0,calibration=calibrationSpeeds, persist=False)
        self.pos = self.azalt()
        self.getCurrentPos()
        self.location = self.drive.location  #TODO - use this
        self.status = Status.INIT
        self.mode = mode

    def getCurrentPos(self):
        """
        Returns current position in azalt.
        """
        return self.pos
        
    def setCurrentPos(self, pos):
        self.pos = pos
        
    def getMode(self):
        return self.mode

    def setMode(self,mode):
        self.mode = mode

    def skycoord(self):
        """
        Returns the position information of the telescope in an astropy SkyCoord object.

        Returns
        -------
        SkyCoord : An astropy SkyCoord.
        """
        position = self.getCurrentPos()
        observatory = self.drive.location
        time = self.drive.current_time

        coord = SkyCoord(AltAz(az = position[0]*u.degree, alt = position[1]*u.degree, obstime = time, location = observatory))
        return coord
        
        
    def azalt(self):
        """
        Returns the azimuth and altitude of the SRT by calling the status() method of the drive class.
        """
        #status = self.drive.status()
        az,alt = self.drive.az, self.drive.alt
        #print("status " + "%f %f" % (az,alt))
        return (az,alt)

    def radec(self):
        """
        Returns the right ascention and declination of the SRT by calling the status() method of the drive class.
        """
        status = self.drive.status()
        ra,dec = status['ra'],status['dec']
        return (ra,dec)

    def galactic(self):
        """
        """
        return (0.00,0.00)


    def stow(self):
        """
        A wrapper function for Drive.stow().
        """
        self.setStatus(Status.SLEWING)
        if self.mode == Mode.SIM:
            self.slew((0,90))
        elif self.mode == Mode.LIVE:
            self.drive.stow()

    def home(self):
        """
        A wrapper function for Drive.home().
        """
        self.setStatus(Status.SLEWING)
        if self.mode == Mode.SIM:
            self.slew((90,0))
        elif self.mode== Mode.LIVE:
            self.drive.home()

    def calibrate(self):
        """
        A wrapper function for Drive.calibrate().
        """
        if self.mode == Mode.SIM:
            print("Calibration only works in live mode.")
        elif self.mode == Mode.LIVE:
            self.setStatus(Status.CALIBRATING)
            self.drive.calibrate()

    def slew(self,pos):
        """
        Slews to position pos in degrees.
        """
        delay = 0.05
        self.status = Status.SLEWING
            
        if self.mode == Mode.SIM:
            print("Slewing in sim mode.")
            if isinstance(pos,SkyCoord):
                now = Time.now()
                altazframe = AltAz(obstime=now,location=self.drive.location)
                apos = pos.transform_to(altazframe)
                x, y = int(apos.az.value), int(apos.alt.value)
            else:
                (xf,yf) = pos # target position in degrees
                x = int(xf)
                y = int(yf)
            (cxf,cyf) = self.pos # current position in degrees
            cx = int(cxf)
            cy = int(cyf)
            if x < cx:
                for i in reversed(range(x,cx)):
                    self.setCurrentPos((i,cy))
                    QtGui.QApplication.processEvents()
                    time.sleep(delay)
            elif x > cx:
                for i in range(cx,x+1):
                    self.setCurrentPos((i,cy))
                    QtGui.QApplication.processEvents()
                    time.sleep(delay)
            if y < cy:
                for i in reversed(range(y,cy)):
                    self.setCurrentPos((x,i))
                    QtGui.QApplication.processEvents()
                    time.sleep(delay)
            elif y > cy:
                for i in range(cy,y+1):
                    self.setCurrentPos((x,i))
                    QtGui.QApplication.processEvents()
                    time.sleep(delay)
        else:
            # This is where live code goes
            # remember self.getCurrentPos() is now in degrees in azalt - NOT pixel coordinates.
            print("Slewing in live mode.")
            if isinstance(pos,SkyCoord):
                now = Time.now()
                altazframe = AltAz(obstime=now,location=self.drive.location)
                apos = pos.transform_to(altazframe)
                x, y = int(apos.az.value), int(apos.alt.value)
            else:
                (x,y) = pos # target - mouse click position in degrees
            (cx,cy) = self.pos # current position in degrees.
            #print("Target Pos: (" + str(x) + "," + str(y) + ")")
            #print("Current Pos: (" + str(cx) + "," + str(cy) + ")")
            # construct a SkyCoord in correct coordinate frame.
            # TODO: fix this -- drive.location
            acreRoadAstropy = self.location
            now = Time(time.time(),format='unix')
            altazframe = AltAz(x*u.deg,y*u.deg,obstime=now,location=acreRoadAstropy)
            skycoordazel = SkyCoord(altazframe)        
            self.drive.goto(skycoordazel,track=self.drive.tracking)

        
    def slewSuccess(self,targetPos):
        """
        """
        (tx,ty) = targetPos
        targetPos = SkyCoord(AltAz(tx*u.deg,ty*u.deg,obstime=self.drive.current_time,location=self.drive.location))
        (cx,cy) = self.pos
        realPos = SkyCoord(AltAz(cx*u.deg,cy*u.deg,obstime=self.drive.current_time,location=self.drive.location))
        d = 0.5
        
        if targetPos.separation(realPos).value <= d:
            #print("Finished slewing to " + str(self.getCurrentPos()))
            return True
        else:
            return False

    def getStatus(self):
        return self.status

    def setStatus(self,status):
        self.status = status

    def track(self,src):
        """
        The SRT will follow the source as it move across the sky.
        """
        if self.mode == Mode.SIM:
            #pos = src.getPos()
            #self.slew(pos)
            self.status = Status.TRACKING
        else:            
            pass
#!/usr/bin/python

import os

from runkeeper import upload_to_runkeeper
from drive import Drive
from models import DriveActivity

drive_service = Drive(
    os.environ['GOOGLE_API_CLIENT_ID'],
    os.environ['GOOGLE_API_CLIENT_SECRET'],
)

folders = drive_service.folders()
print("Please select a folder to sync tracks from:")
for i, folder in enumerate(folders):
    print "{}: {}".format(i, folder['title'])
index = raw_input("Folder number: ")

folder = folders[int(index)]
print("You chose the folder: {}".format(folder['title']))

tracks = drive_service.files(folder)
for i, track in enumerate(tracks):
    print('{}: {}'.format(i, track['title']))
index = raw_input("Track number: ")
track = tracks[int(index)]

q = DriveActivity.all()
q.filter('pk =', track['id'])
drive_activity = q[0]
Пример #43
0
class MyRobot(wpilib.SimpleRobot):
    def __init__(self):
        super().__init__()
        self.loader = Loader()
        self.shooter = Shooter()
        self.drive = Drive(config.robotDrive, config.leftJoy, config.hsButton,
                           config.alignButton)
        self.componets = [ self.loader, self.shooter, self.drive ]

    def RobotInit(self):
        wpilib.Wait(0.25)
        shooterEncoder.Start()

    def Disabled(self):
        while wpilib.IsDisabled():
            CheckRestart()
            wpilib.Wait(0.01)

    def Autonomous(self):
        while wpilib.IsAutonomous() and wpilib.IsEnabled():
            CheckRestart()
            wpilib.Wait(0.01)

    def OperatorControl(self):
        dog = self.GetWatchdog()
        dog.SetEnabled(True)
        dog.SetExpiration(0.25)

        self.drive.stop()
        shooterMotor.Set(0)
        tipperMotor.Set(0)
        rollerMotor.Set(0)

        while self.IsOperatorControl() and self.IsEnabled():
            dog.Feed()
            CheckRestart()
            for componet in self.componets:
                componet.tick()

            #Teleop Code
            #if not self.drive.aligning :
            #    self.drive.arcadeDrive(leftJoy.GetRawButton(halfSpeed))
            shooterMotor.Set(rightJoy.GetY())

            ## Alignment
            #if leftJoy.GetRawButton(allignButton) :
            #    if not self.drive.aligning:
            #        self.drive.aligning = True
            #        robotDrive.StopMotor()
            #    self.drive.align()
            #else:
            #    self.drive.aligning = False

            ## Tipper Up and Down
            if rightJoy.GetRawButton(tipperUp):
                tipperMotor.Set(-1)
            elif rightJoy.GetRawButton(tipperDown):
                tipperMotor.Set(1)
            else:
                tipperMotor.Set(0)

            ## Roller Up and Down
            if rightJoy.GetRawButton(rollerUpButton):
                rollerMotor.Set(-1)
            elif rightJoy.GetRawButton(rollerDownButton):
                rollerMotor.Set(1)
            else:
                rollerMotor.Set(0)

            ## Loading
            if rightJoy.GetRawButton(feederButton):
                self.loader.load()

            ## Shooting
            if rightJoy.GetRawButton(latchButton):
                self.shooter.unlatch()

            ## Debug & Tuning

            wpilib.Wait(0.01)
Пример #44
0
    def __init__(self, dbname='SOS.db', sheet_name='', drop=False):
        self.drive = Drive(sheet_name)
        self.con = sqlite3.connect(dbname)
        self.con.row_factory = sqlite3.Row

        class Median:
            def __init__(self):
                self.values = []

            def step(self, value):
                self.values.append(value)

            def finalize(self):
                count = len(self.values)
                values = sorted(self.values)
                if count % 2 == 1:
                    return values[math.ceil(count / 2)]
                else:
                    return (values[int(count / 2) - 1] +
                            values[int(count / 2)]) / 2

        self.con.create_aggregate("median", 1, Median)

        self.c = self.con.cursor()
        self.diff_table = False
        self.median_table = False

        self.cats_conf = OrderedDict({
            "R": {
                "precision": 1,
                "close_limit": 3,
                "batting": True,
                "real": True
            }
        })
        self.cats_conf["HR"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": True,
                "real": True
        }
        self.cats_conf["RBI"] = {
                "precision": 1,
                "close_limit": 3,
                "batting": True,
                "real": True
        }
        self.cats_conf["SB"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": True,
                "real": True
        }
        self.cats_conf["H"]=  {
                "precision": 0,
                "batting": True,
                "real": False
        }
        self.cats_conf["AB"] = {
                "precision": 0,
                "batting": True,
                "real": False
        }
        self.cats_conf["AVG"] = {
                "precision": 3,
                "close_limit": 0.020,
                "batting": True,
                "real": True,
                "expr": "ifnull(1.0 * $(H) / $(AB), 0)",
        }
        self.cats_conf["W"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": False,
                "real": True
        }
        self.cats_conf["SV"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": False,
                "real": True
        }
        self.cats_conf["K"] = {
                "precision": 0,
                "close_limit": 5,
                "batting": False,
                "real": True
        }
        self.cats_conf["IP"] = {
                "precision": 1,
                "batting": False,
                "real": False
        }
        self.cats_conf["ER"] = {
                "precision": 1,
                "batting": False,
                "real": False
        }
        self.cats_conf["WH"] = {
                "precision": 0,
                "batting": False,
                "real": False
        }
        self.cats_conf["ERA"] = {
                "precision": 2,
                "close_limit": 0.50,
                "batting": False,
                "real": True,
                "invert": True,
                "expr": "ifnull($(ER) * 9 / $(IP), 0)"
        }
        self.cats_conf["WHIP"] = {
                "precision": 2,
                "close_limit": 0.10,
                "batting": False,
                "real": True,
                "invert": True,
                "expr": "ifnull($(WH) / $(IP), 0)"
        }

        if drop:
            self.drop_db()
            self.create_db()
Пример #45
0
class FantasyDB(object):
    def __init__(self, dbname='SOS.db', sheet_name='', drop=False):
        self.drive = Drive(sheet_name)
        self.con = sqlite3.connect(dbname)
        self.con.row_factory = sqlite3.Row

        class Median:
            def __init__(self):
                self.values = []

            def step(self, value):
                self.values.append(value)

            def finalize(self):
                count = len(self.values)
                values = sorted(self.values)
                if count % 2 == 1:
                    return values[math.ceil(count / 2)]
                else:
                    return (values[int(count / 2) - 1] +
                            values[int(count / 2)]) / 2

        self.con.create_aggregate("median", 1, Median)

        self.c = self.con.cursor()
        self.diff_table = False
        self.median_table = False

        self.cats_conf = OrderedDict({
            "R": {
                "precision": 1,
                "close_limit": 3,
                "batting": True,
                "real": True
            }
        })
        self.cats_conf["HR"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": True,
                "real": True
        }
        self.cats_conf["RBI"] = {
                "precision": 1,
                "close_limit": 3,
                "batting": True,
                "real": True
        }
        self.cats_conf["SB"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": True,
                "real": True
        }
        self.cats_conf["H"]=  {
                "precision": 0,
                "batting": True,
                "real": False
        }
        self.cats_conf["AB"] = {
                "precision": 0,
                "batting": True,
                "real": False
        }
        self.cats_conf["AVG"] = {
                "precision": 3,
                "close_limit": 0.020,
                "batting": True,
                "real": True,
                "expr": "ifnull(1.0 * $(H) / $(AB), 0)",
        }
        self.cats_conf["W"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": False,
                "real": True
        }
        self.cats_conf["SV"] = {
                "precision": 1,
                "close_limit": 1,
                "batting": False,
                "real": True
        }
        self.cats_conf["K"] = {
                "precision": 0,
                "close_limit": 5,
                "batting": False,
                "real": True
        }
        self.cats_conf["IP"] = {
                "precision": 1,
                "batting": False,
                "real": False
        }
        self.cats_conf["ER"] = {
                "precision": 1,
                "batting": False,
                "real": False
        }
        self.cats_conf["WH"] = {
                "precision": 0,
                "batting": False,
                "real": False
        }
        self.cats_conf["ERA"] = {
                "precision": 2,
                "close_limit": 0.50,
                "batting": False,
                "real": True,
                "invert": True,
                "expr": "ifnull($(ER) * 9 / $(IP), 0)"
        }
        self.cats_conf["WHIP"] = {
                "precision": 2,
                "close_limit": 0.10,
                "batting": False,
                "real": True,
                "invert": True,
                "expr": "ifnull($(WH) / $(IP), 0)"
        }

        if drop:
            self.drop_db()
            self.create_db()

    def drop_db(self):
        self.c.executescript("""
            DROP TABLE IF EXISTS team;
            DROP TABLE IF EXISTS matchup;
            DROP TABLE IF EXISTS week_stats;
        """)

    def create_db(self):
        self.c.executescript("""
            CREATE TABLE team (team_id integer, team_key text,
                               label text, manager text);

            CREATE TABLE matchup (team_id1 integer, team_id2 integer,
                                  week integer);

            CREATE TABLE week_stats
                (team_id integer, opponent_id integer, week integer, R integer,
                 HR integer, RBI integer, SB integer, H integer, AB integer,
                 W integer, SV integer, K integer, IP real, ER integer,
                 WH integer);
        """)

    def create_tmp_stats_table(self, table_name):
        self.c.executescript("""
            DROP TABLE IF EXISTS %s;
            CREATE TABLE %s
                (team_id integer, opponent_id integer, week integer,
                 R integer, HR integer, RBI integer, SB integer, AVG real,
                 W integer, SV integer, K integer, ERA real, WHIP real);
        """ % (table_name, table_name))

    def create_tmp_matchup_table(self, table_name):
        self.c.executescript("""
            DROP TABLE IF EXISTS %s;
            CREATE TABLE %s (team_id integer, week integer,
                R integer, HR integer, RBI integer, SB integer, AVG real,
                W integer, SV integer, K integer, ERA real, WHIP real);
        """ % (table_name, table_name))

    def insert(self, sql, data=None):
        if data is None:
            self.c.execute(sql)
        else:
            for line in data:
                self.c.execute(sql, line)
        self.con.commit()

    def add_teams(self, teams):
        self.insert("INSERT INTO team VALUES (?, ?, ?, ?)", teams)

    def add_matchups(self, matchups):
        self.insert("INSERT INTO matchup VALUES(?, ?, ?)", matchups)

    def add_stats(self, stats):
        sql = "INSERT INTO week_stats ("
        sql += ", ".join(stats.keys())
        sql += ") VALUES("
        sql += ", ".join(["?"] * len(stats)) + ")"
        self.insert(sql, [tuple(stats.values())])

    def save_data(self, data, name):
        # Save to file
        f = open("export/" + name + ".txt", "w", encoding="utf-8")
        f.write(data)
        f.close()

        # Save to Google Drive
        if self.drive is not None:
            self.drive.login()
            self.drive.create_sheet(name, data)

    def nb_weeks(self):
        sql = "SELECT DISTINCT COUNT(*) FROM week_stats GROUP BY team_id"
        return self.c.execute(sql).fetchone()[0]

    def get_select(self, aggregate="AVG", real_only=True, use_alias=True,
                   use_round=True, as_string=True, table_alias=""):
        columns = OrderedDict({})
        if len(table_alias):
            table_alias += "."
        for cat, conf in self.cats_conf.items():
            if real_only and not conf["real"]:
                continue
            expr = "$(" + cat + ")" if "expr" not in conf else conf["expr"]
            col = expr.replace("$(", aggregate + "(" + table_alias)
            if use_round:
                col = self.apply_round(cat, col)
            if use_alias:
                col = self.apply_alias(cat, col)

            columns[cat] = col

        return ", ".join(columns.values()) if as_string else columns

    def apply_round(self, cat, expr):
        precision = str(self.cats_conf[cat]["precision"])
        return "round(" + expr + "," + precision + ")"

    def apply_alias(self, cat, expr):
        return expr + " AS " + cat

    def stats_avg_query(self):
        sql = "SELECT 'Moyenne' as Moyenne, "
        sql += self.get_select()
        sql += " FROM week_stats w"
        # sql += " WHERE team_id <> 6 OR week < 7 "
        return sql

    def stats_query(self):
        sql = "SELECT t.label AS Team, "
        sql += self.get_select()
        sql += " FROM week_stats w JOIN team t ON(w.team_id = t.team_id) "
        sql += "GROUP BY t.team_id"
        print(sql)
        return sql

    def stats_against_query(self):
        sql = "SELECT t.label AS Team, "
        sql += self.get_select()
        sql += " FROM week_stats w JOIN team t ON(w.opponent_id = t.team_id) "
        sql += "GROUP BY t.team_id"
        return sql

    def stats_diff_query(self):
        sql = "SELECT t.label AS Team"
        cols = self.get_select("AVG", table_alias="for", use_alias=False,
                               use_round=False, as_string=False)

        for cat, col in cols.items():
            col = col + " - " + col.replace("for.", "against.")
            col = self.apply_round(cat, col)
            if "invert" in self.cats_conf[cat]:
                col = "- (" + col + ")"
            col = self.apply_alias(cat, col)
            sql += ", " + col

        sql += """
            FROM week_stats against
            JOIN team t ON(against.opponent_id = t.team_id)
            JOIN week_stats for ON(t.team_id = for.team_id)
            GROUP BY t.team_id
        """
        return sql

    def create_diff_table(self):
        if self.diff_table:
            return

        select = "SELECT for.team_id, against.team_id, for.week"
        cols = self.get_select("AVG", table_alias="for", use_alias=False,
                               use_round=False, as_string=False)

        for cat, col in cols.items():
            col = col + " - " + col.replace("for.", "against.")
            col = self.apply_round(cat, col)
            if "invert" in self.cats_conf[cat]:
                col = "- (" + col + ")"
            col = self.apply_alias(cat, col)
            select += ", " + col

        select += """
            FROM week_stats against
            JOIN week_stats for ON(against.opponent_id = for.team_id
                 AND against.week = for.week)
            GROUP BY for.team_id, for.week
        """

        # Temp table creation
        table = "tmp_stats"
        self.create_tmp_stats_table(table)
        self.insert("INSERT INTO tmp_stats " + select)
        self.diff_table = True

    def create_median_table(self, win=True):
        # if self.median_table:
        #     return

        select = "SELECT team_id, week"
        cols = self.get_select("", use_alias=False,
                               use_round=False, as_string=False)

        for cat, expr in cols.items():
            col = "(SELECT COUNT(*) FROM week_stats "
            col += "WHERE team_id = w1.team_id AND week = w1.week "
            query = "SELECT median(%s) FROM week_stats w3 " % expr
            query += "WHERE w3.week = w1.week AND w1.team_id != w3.team_id"
            invert = "invert" in self.cats_conf[cat]
            lt = invert if win else not invert
            op = "<" if lt else ">"
            col += "AND %s %s (%s))" % (expr, op, query)
            select += ", " + col

        select += " FROM week_stats w1"
        select += " GROUP BY team_id, week"

        # Temp table creation
        table = "tmp_medium_stats_%s" % ("W" if win else "L")
        self.create_tmp_matchup_table(table)
        self.insert("INSERT INTO %s %s" % (table, select))
        self.median_table = True

    def stat_diff_win_query(self, win=True):
        self.create_diff_table()

        op = ">" if win else "<"
        sql = "SELECT t.label AS Team"
        for cat, conf in self.cats_conf.items():
            if not conf["real"]:
                continue
            expr = "AVG(" + cat + ")"
            query = "SELECT ifnull(" + self.apply_round(cat, expr) + ", '') FROM tmp_stats "
            query += "WHERE " + cat + " " + op + " 0 AND team_id = tmp.team_id"
            sql += self.apply_alias(cat, ", (" + query + ")")

        sql += " FROM tmp_stats AS tmp"
        sql += " JOIN team t ON(tmp.team_id = t.team_id)"
        sql += " GROUP BY tmp.team_id"

        return sql

    def close_diff_win_query(self, win=True):
        self.create_diff_table()

        sql = "SELECT t.label AS Team"
        for cat, conf in self.cats_conf.items():
            if not conf["real"]:
                continue

            if win:
                cond = cat + " > 0 AND " + cat + " <= " + str(conf["close_limit"])
            else:
                cond = cat + " >= -" + str(conf["close_limit"]) + " AND " + cat + " < 0"

            query = "SELECT COUNT(*) FROM tmp_stats"
            query += " WHERE " + cond + " AND team_id = tmp.team_id"
            sql += self.apply_alias(cat, ", (" + query + ")")

        sql += " FROM tmp_stats AS tmp"
        sql += " JOIN team t ON(tmp.team_id = t.team_id)"
        sql += " GROUP BY tmp.team_id"

        return sql

    def standings(self, sql, filename):
        self.c.execute(sql)

        results = "\t".join(map(lambda x: str(x[0]), self.c.description)) + "\n"

        for row in self.c.fetchall():
            results += "\t".join(map(str, row)) + "\n"

        self.c.execute(self.stats_avg_query())
        results += "\n" + "\t".join(map(str, self.c.fetchone())) + "\n"

        self.save_data(results, filename)

    def close_standings(self, filename):
        wins = self.con.execute(self.close_diff_win_query())
        losses = self.con.execute(self.close_diff_win_query(False))

        results = "\t".join(map(lambda x: str(x[0]), wins.description))
        results += "\tTotal\tPct\n"

        while True:
            win = wins.fetchone()
            loss = losses.fetchone()
            if win is None:
                break

            results += win[0]
            total_win = 0
            total_loss = 0
            for cat, W in OrderedDict(win).items():
                if cat in self.cats_conf:
                    results += '\t="%d-%d"' % (W, loss[cat])
                    total_win += W
                    total_loss += loss[cat]
            results += '\t="%d-%d"' % (total_win, total_loss)
            if total_win + total_loss == 0:
                results += '\n'
            else:
                results += '\t%.2f\n' % (total_win / (total_win + total_loss))

        results += "\nMargin"
        for cat, conf in self.cats_conf.items():
            if conf["real"]:
                results += "\t%s" % str(conf["close_limit"])

        self.save_data(results, filename)

    def median_standings(self, filename):
        self.create_median_table()
        self.create_median_table(False)

        sql = "SELECT t.label AS Team"
        wins = []
        losses = []

        for cat, conf in self.cats_conf.items():
            if not conf["real"]:
                continue

            win = "SUM(W.%s) / MAX(W.week)" % cat
            loss = "SUM(L.%s) / MAX(W.week)" % cat
            expr = "printf('=\"%%d-%%d\"', %s, %s)" % (win, loss)
            sql += ", " + self.apply_alias(cat, expr)
            wins.append(win)
            losses.append(loss)

        wins_expr = " + ".join(wins)
        losses_expr = " + ".join(losses)
        sql += ", printf('=\"%%d-%%d\"', %s, %s) AS Total" % (wins_expr, losses_expr)
        sql += ", round((%s) / (%s + %s + 0.0), 3) AS Pct" % (wins_expr, wins_expr, losses_expr)
        sql += " FROM tmp_medium_stats_W W JOIN team t USING (team_id)"
        sql += " JOIN tmp_medium_stats_L L USING (team_id)"
        sql += " GROUP BY W.team_id"
        sql += " ORDER BY Pct DESC"

        print(sql)
        self.c.execute(sql)
        results = "\t".join(map(lambda x: str(x[0]), self.c.description)) + "\n"

        for row in self.c.fetchall():
            results += "\t".join(map(str, row)) + "\n"

        self.save_data(results, filename)

    def value_standings(self, sql, filename):
        # Diff par rapport à la moyenne de la league
        avg = self.c.execute(self.stats_avg_query()).fetchone()
        results = self.con.execute(sql)
        min = {}
        max = {}
        data = []

        while(True):
            stats = results.fetchone()
            if stats is None:
                break
            stats = OrderedDict(stats)

            # Calculate min and max values
            for cat, value in stats.items():
                if cat not in min:
                    min[cat] = value
                elif value < min[cat]:
                    min[cat] = value
                if cat not in max:
                    max[cat] = value
                elif value > max[cat]:
                    max[cat] = value

            data.append(stats)

        # Second pass to calculate variations
        variations = []
        for stats in data:
            total = 0
            for cat, value in stats.items():
                if cat == "Team":
                    continue

                if value > avg[cat]:
                    value = 1 - (max[cat] - value) / (max[cat] - avg[cat])
                elif value < avg[cat]:
                    value = (value - min[cat]) / (avg[cat] - min[cat]) - 1
                else:
                    value = 0

                if cat in ["ERA", "WHIP"]:
                    value = 0 - value

                total += value
                stats[cat] = "%.2f" % value

            stats["total"] = "%.2f" % total
            variations.append(stats)

        results = "\t".join(map(lambda x: str(x[0]), results.description)) + "\tTotal\n"

        # Order by total value
        def getTotal(item):
            return float(item["total"])
        variations = sorted(variations, key=getTotal, reverse=True)

        for stats in variations:
            results += "\t".join(stats.values()) + "\n"

        self.save_data(results, filename)

    def calculate_stats_ratio(self):
        avg = self.calculate_row(self.c.execute(self.stats_avg_query()).fetchone(), False)
        R = avg["R"]
        del avg["R"]

        ratio = {}
        for cat, value in avg.items():
            ratio[cat] = R / value

        ratio["R"] = 1
        print(ratio)
        return ratio
Пример #46
0
from __future__ import division
import numpy as np
import time
from drive import Drive

drive = Drive('/dev/ttyACM0')

last_odom = [0, 0, 0, 0]
ID = 1

while True:

    # ODOM TEST:

    odom, timestamp = drive.get_odom()

    if not np.allclose(odom, last_odom):
        last_odom = odom
        print np.round(odom, 2)

    time.sleep(10 / 1000)

    # MOTOR TEST:

    # val = 15
    # rest = 1

    # print "forward"
    # drive.set_effort([val+10, val])
    # time.sleep(rest)
Пример #47
0
            self.ui = raw_input(self.prompt).split()
            self.drive.echo(False)

            if not self.ui: continue

            # make ints out of int arguements
            if self.ui[0] != "cd":
                for i, v in enumerate(self.ui):
                    try:
                        self.ui[i] = int(v)
                    except:
                        pass

            #print(self.ui)

            try:
                #get function by name, then pull out first element in the self.options.
                #This is where the function is
                function = self.options[self.ui[0]][0]
            except:
                print("command unknown")
                function = None

            if function: function()


if __name__ == '__main__':
    drive = Drive()
    cli = CLI(drive)
    cli.run()
Пример #48
0
display = Display(config)

arm = UArm(serial.Serial(port=args.device, baudrate=115200, timeout=config.serial_port_timeout), config)
if arm.connect():
    log.info("Detected UArm on device {}".format(args.device))
else:
    log.fatal("Could not connect to UArm using device '{}'".format(args.device))

storage_path = args.storage_path
capture_id = args.capture_id

log.info("Using storage '{}'".format(storage_path))

vision = Vision(config)

drive = Drive("/dev/cdrom", storage_path)

calibration_markers = None
with open(args.calibration_markers_file, 'r') as f:
    calibration_markers = json.load(f)

log.info("Calibration data loaded from '{}': {}".format(args.calibration_markers_file, calibration_markers))

log.info("Starting capture")

log.info("Picking up disk from source tray")
display.msg("PICKUP SRC TRAY")

# Pickup disk
cd_pickedup = arm.pickup_object(config.src_tray_pos, config.src_tray_z_min)
if not cd_pickedup:
Пример #49
0
def DriveService():
    return Drive(credentials['client_id'], credentials['client_secret'])
Пример #50
0
class Volume:
    
    def __init__(self):
        self.currentDrive = None
        self.rootDirectory = None  
        self.blocksAvailability = None      

    def format(self, name):
        thisDrive = Drive(name)
        thisDrive.format()
        thisDrive.write_block(0, "+" + "-" * 127 + ("f:" + " " * 9 + "0000:" + "000 " * 12) * 6)
        global availableBlocksList
        availableBlocksList = ['+'] + ['-' for x in range(127)]
        global availableBlockIndices 
        availableBlockIndices = list(range(1, 128))
        self.currentDrive = thisDrive
        self.rootDirectory = Directory(self.currentDrive, None, 0, None, None) #drive, fileNum, parentBlockNum, parent, name
        self.blocksAvailability = thisDrive.read_block(0)[:127]

    def mkfile(self, path):
        try:
            nodes = path.strip('/').split('/')
            lastNode = self.rootDirectory
            for node in nodes[:-1]:
                lastNode = lastNode.getChild(node)
        except:
            print("Um there is some problem with your input")
        lastNode.addFile(nodes[-1])

    def mkdir(self, path):
        try:
            nodes = path.strip('/').split('/')
            lastNode = self.rootDirectory
            for node in nodes[:-1]:
                lastNode = lastNode.getChild(node)
        except:
            print("Um there is some problem with your input")
        lastNode.addDirectory(nodes[-1])

    def reconnect(self, name):
        self.currentDrive = Drive(name)
        self.rootDirectory = Directory(self.currentDrive, None, 0, None, name)
        self.currentDrive.reconnect()      
        self.blocksAvailability = self.currentDrive.read_block(0)[:127]

    def append(self, path, data):
        try:
            nodes = path.strip('/').split('/')
            lastNode = self.rootDirectory
            for node in nodes:
                lastNode = lastNode.getChild(node)
        except:
            print("Um there is some problem with your input")
        lastNode.appendData(data)
            
    def ls(self, path):
        try:
            nodes = path.strip('/').split('/')
            lastNode = self.rootDirectory
            for node in nodes:
                if node != "":
                    lastNode = lastNode.getChild(node)
            lastNode.list()
        except:
            print("Um there is some problem with your input")

    def print(self, path):
        try:
            nodes = path.strip('/').split('/')
            lastNode = self.rootDirectory
            for node in nodes:
                if node != "":
                    lastNode = lastNode.getChild(node)
            lastNode.print()
        except:
            print("Um there is some problem with your input")

    def delfile(self, path):
        try:
            nodes = path.strip('/').split('/')
            lastNode = self.rootDirectory
            for node in nodes:
                if node != "":
                    lastNode = lastNode.getChild(node)
            lastNode.delete()
        except:
            print("Um there is some problem with your input")

    def deldir(self, path):
        try:
            nodes = path.strip('/').split('/')
            lastNode = self.rootDirectory
            for node in nodes:
                if node != "":
                    lastNode = lastNode.getChild(node)      
            lastNode.delete()
        except:
            print("Um there is some problem with your input")  
Пример #51
0
 def get_system_drive(self):
     system_drive = os.getenv('SystemDrive')
     system_drive = Drive(system_drive)
     log.debug('system_drive=%s' % system_drive)
     return system_drive
Пример #52
0
 def reconnect(self, name):
     self.currentDrive = Drive(name)
     self.rootDirectory = Directory(self.currentDrive, None, 0, None, name)
     self.currentDrive.reconnect()      
     self.blocksAvailability = self.currentDrive.read_block(0)[:127]