예제 #1
0
 def __init__(self):
     self.ui = Tk()
     self.start_ui()
     self.reader = Driver()
     self.homework = HomeworkList()
     self.timer = 0
     self.auto = threading.Thread(target=self.auto_load_thread, daemon=True)
     self.id_input = Label(self.ui,
                           text='아이디',
                           font='Verdana 10 bold',
                           background='white')
     self.id_value = Entry(self.ui)
     self.password_input = Label(self.ui,
                                 text='비밀번호',
                                 font='Verdana 10 bold',
                                 background='white')
     self.password_value = Entry(self.ui, show='*')
     self.password_value.bind('<Return>', self.enter_key)
     self.login_btn = Button(self.ui,
                             text='로그인',
                             command=self.click_login,
                             height=2,
                             font='Verdana 10 bold',
                             background='white')
     self.subject_name = []
     self.homework_name = []
     self.end_time = []
     self.remain = []
     self.submit_btn = []
     self.submit = []
     self.login()
     self.ui.mainloop()
예제 #2
0
def main():
    with open("testfiles/parsing/Valid.txt", "r") as testfile:
        blueprint = TestCase.parse_syntax(testfile)
        if blueprint is not None:
            tc = TestCase(blueprint)
            dr = Driver(tc)
            dr.execute()
예제 #3
0
def loop():
    while True:
        message = Log.get_current_message()
        if message == "Start" or message == "Continue":
            try:
                driver = Driver()
                driver.run()

            except KeyboardInterrupt:
                Log.send("Keyboard Interrupt. Bot will exit now.")
                print("Exiting...")
                break
            except socket_error as err:
                raise err
            except Exception as err:
                for frame in traceback.extract_tb(sys.exc_info()[2]):
                    fname, lineno, fn, text = frame
                error = "Error in " + str(fname) + " on line " + str(
                    lineno) + ": " + str(err)
                print(error)
                Log.send(error)
                pass
        else:
            if message == "Stop" or message == "Exit":
                Log.send("XING Bot will exit now.")
                raise Exception
            sleep(1)
예제 #4
0
class Engine:
    def __init__(self, dBRange, timeOut, ledGpioPins, groveChannel,
                 piezoGpioPIN):

        self.__dBRange = dBRange
        self.__driver = Driver(ledGpioPins, groveChannel, piezoGpioPIN)
        #self.__currentdB = self.__driver.GetCurrentdB()
        # what is this range ? maybe could be used for rounding values of dB
        # or maybe even better an array of maxdB/NUMBER_OF_LED ya better
        # soundRange = 0 ? [255*1/8, 255*2/8, 255*3/8, 255*4/8, 255*5/8, 255*6/8, 255*7/8, 255*8/8]
        # self.__soundRange = soundRange
        #self.__timeOut = timeOut

    def Start(self):
        print("SoundAnalyzer engine started...")
        unit = self.__dBRange * (1 / 8)
        dBInterval = [
            unit * 1, unit * 2, unit * 3, unit * 4, unit * 5, unit * 6,
            unit * 7, unit * 8
        ]

        while True:
            # say dB is 0-255
            currentSoundLevel = self.__driver.GetCurrentdB()
            #currentSoundLevel = random.randint(1, 70)
            # if currentSoundLevel < soundRange[i]:
            if currentSoundLevel < dBInterval[0]:
                self.__driver.LightUpToNthLed(0)

            elif currentSoundLevel < dBInterval[1]:
                self.__driver.LightUpToNthLed(1)

            elif currentSoundLevel < dBInterval[2]:
                self.__driver.LightUpToNthLed(2)

            elif currentSoundLevel < dBInterval[3]:
                self.__driver.LightUpToNthLed(3)

            elif currentSoundLevel < dBInterval[4]:
                self.__driver.LightUpToNthLed(4)

            elif currentSoundLevel < dBInterval[5]:
                self.__driver.LightUpToNthLed(5)
                #self.__driver.TriggerPiezo(duration=4)
                # timout to quiet
                # self.__driver.TimeOutPiezo(2)

            elif currentSoundLevel < dBInterval[6]:
                self.__driver.LightUpToNthLed(6)
                # vary duration ?
                #self.__driver.TriggerPiezo(duration=4)

            elif currentSoundLevel < dBInterval[7]:
                self.__driver.LightUpToNthLed(7)
                #self.__driver.TriggerPiezo(duration=4)

            self.__driver.CheckForShutdown()

            time.sleep(.07)
예제 #5
0
    def __init__(self, db_connection):

        # Function Description: Intialise the Event_Driver. Inherits from Driver.
        # Function Parameters: db_connection (pymysql.connections.Connection: The connection to the database.)
        # Function Throws: Nothing
        # Function Returns: Nothing

        Driver.__init__(self, db_connection)  # Send the parameters up.
예제 #6
0
    def __init__(self, db_connection):

        # Function Description: Intialise the Game_Driver. The Game_Driver will handle all the function related to a Game:
        #       1. Insert a new instance of a Game.
        # Paramters: db_connection (pymysql.connections.Connection: The connection to the database.)
        # Function Throws: Nothing
        # Function Returns: Nothing

        Driver.__init__(self, db_connection)
예제 #7
0
    def __init__(self, db_connection, max_size=1000):

        # Class Description: The function will manage all the individual batch queues. Note: The key identifying each Batch_Queue
        #    must match each table name.
        # Class Parameters: db_connection (The existing connection to the database.),
        #    max_size (The point where we insert all the queues into the database.)

        Driver.__init__(self, db_connection)
        self.max_size = max_size
        self.queues = {}
        self.current_size = 0  # Manage the size of the queue. Empty the queue when it gets to large.
예제 #8
0
    def __init__(self, db_connection):

        # Class Description: The class will manage and control the data insertions into the baseball database. Note, 
        #   the class does not perform any queries. The queries are delegated to the specific drivers.

        Driver.__init__(self, db_connection)                                                          # The path to the pymysql connector to access the database.
        self.path_to_raw_data = Path("BaseballAnalytics/bin/db/raw_data/")                            # The path to the raw data that will be inserted into the database.
        self.path_to_player_list = self.path_to_raw_data / 'rosters'                                  # The folder containing the player data.
        self.path_to_pickle_player_data = self.path_to_player_list / 'pickle_player_data.pickle'      # The path to the pickle file containing the player information. 
        self.log_folder = Path('BaseballAnalytics/logs/insert_file_logs/')                            # The path to the log file.
        self.path_to_raw_data = Path('C:/Users/micha/Desktop/')
        self.log_file = self.__initiate_log_file(self.log_folder)
예제 #9
0
def main():
    c1 = Car(brand="opel", model="astra", maxSpeed=22)
    c2 = Car()
    print(int(c1))
    print(c2)

    d1 = Driver()
    d2 = Driver("Ivan", c1)
    print(d1)
    print(d2)

    r1 = Race()
예제 #10
0
    def __init__(self, id, num, ser):
        Driver.__init__(self, id)
        self.ser = ser
        self.num = num

        if os.path.isfile("persist/"+str(self.id)):
            f = open("persist/"+str(self.id), "rb")
            self.setParameters(pickle.load(f))
            f.close()
        else: 
            self.status = 0
            self.setStatus(self.status)
예제 #11
0
def main():
    instabot = Driver(key.username, key.password)
    instabot.login()
    instabot.messages()
    starttime = time.time()
    while True:
        print(instabot.getactivity())
        time.sleep(60.0 - ((time.time() - starttime) % 60.0))
        instabot.refresh()
예제 #12
0
def main():
    # confirm python3
    version_info = sys.version_info
    try:
        assert version_info.major >= 3
    except AssertionError:
        print("Use python3.")
        print("Usage: python3 main.py [parameter_file]")
        return

    # Initilize
    from Driver import Driver

    driver = Driver()

    try:
        # Command line arguments
        args = sys.argv
        if len(args) < 2:
            raise InitialArgumentsError
        # Load parameters
        driver.load(args[1])
        # Control Loop
        driver.doOperation()
    except InitialArgumentsError:
        print("[ERROR] NO ARGUMENTS")
        print("Usage: python3 main.py [parameter_file]")
    except KeyboardInterrupt:
        print("KeyboardInterrupt")
    finally:
        # If you finalize this program,
        # this program set the system to stop
        driver.finalize()
        print("finish")
예제 #13
0
class TestOpenAccount(unittest.TestCase):
    def setUp(self):
        self.D = Driver()
        self.driver = self.D.browser_open("http://10.7.106.235:8000/login")
        self.oa = OpenAccount(self.driver)

    def test004_openaccount(self):
        # self.oa.open_account('18252023049', 'cjs123456', u'陈进松', '320621199301178313', '6214852116479075',
        #                      '18051969073')
        # 该账户已开通了
        # self.oa.open_account('18252023050', 'cjs123456', u'陈进松', '320621199301178313', '6214852116479075',
        #                      '18051969073')
        pass

    def tearDown(self):
        self.D.browser_close()
def VideoStream():
    global command_client
    global driver
    global recv_inst
    print("Started")
    driver = Driver()
    recv_inst = True
    command_client = socket.socket()
    command_client.connect((host, command_port))
    Thread(target=steer).start()
    sleep(1)
    cam = cv2.VideoCapture(0)
    client = NetGear(address=host,
                     port=video_port,
                     protocol='tcp',
                     pattern=0,
                     recieve_mode=False,
                     logging=False)
    cam.set(3, 320)
    cam.set(4, 240)
    #cam.set(cv2.CAP_PROP_FPS, 10)
    while recv_inst:
        ret, frame = cam.read()
        if frame is None:
            break
        cv2.imshow("Car Cam", frame)
        client.send(frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cam.release()
    client.close()
    command_client.close()
    cv2.destroyAllWindows()
예제 #15
0
def analysis(foldername, outdir, partitionssize, referencenum, maxsize=None):
    """
    Start the analysis

    Input:
        1) Path to the driver directory
        2) Path where the submission file should be written
        3) Number of drivers to compare against
    """
    seed(42)
    start = datetime.now()
    submission_id = datetime.now().strftime("%H_%M_%B_%d_%Y")
    folders = [
        os.path.join(foldername, f) for f in os.listdir(foldername)
        if os.path.isdir(os.path.join(foldername, f))
    ]
    referencefolders = [
        folders[i] for i in sorted(sample(xrange(len(folders)), referencenum))
    ]
    referencedrivers = []
    for referencefolder in referencefolders:
        referencedrivers.append(Driver(referencefolder))
    #for testing
    if maxsize:
        folders = folders[:maxsize]
    results = []
    for folderlist in chunks(folders, partitionssize):
        results.append(perform_analysis(folderlist, referencedrivers))
    with open(
            os.path.join(outdir, "pyMultiClass_{0}.csv".format(submission_id)),
            'w') as writefile:
        writefile.write("driver_trip,prob\n")
        for item in results:
            writefile.write("%s\n" % item)
    print 'Done, elapsed time: %s' % str(datetime.now() - start)
예제 #16
0
def perform_analysis(folder):
    print("Working on {0}".format(folder))
    sys.stdout.flush()
    temp = Driver(folder)
    cls = RegressionDriver(temp, REFERENCE_DATA)
    cls.classify()
    return cls.toKaggle()
예제 #17
0
    def __init__(self, file_name=None):
        """Creates a DriversDict composed by Driver objects,
        from a file with a list of drivers.

        Requires: If given, file_name is str with the name of a .txt file containing
        a list of drivers organized as in the examples provided in
        the general specification (omitted here for the sake of readability).

        Ensures:
        if file_name is given:
            a DriversDict, composed by objects of class Driver that correspond to the drivers listed
            in file with name file_name.
        if file_name is none:
            a empty DriversList."""

        UserDict.__init__(self)

        if file_name is not None:
            inFile = FileUtil(file_name)
            for line in inFile.getContent():
                driverData = line.rstrip().split(", ")
                driverName = driverData.pop(DriversDict.INDEXDriverName)
                driverEntryTime, driverAccumTime = driverData
                driverEntryTime = Time(driverEntryTime)
                driverAccumTime = Time(driverAccumTime)
                newDriver = Driver(driverName, driverEntryTime,
                                   driverAccumTime)

                self[driverName] = newDriver
예제 #18
0
    def __init__(self):
        # Constructor for Repository class

        self.__address = {}
        self.__driver = {}

        with open("addresses", "r") as file:
            data = file.read()
            data = data.split("\n")
            if len(data) != 1:
                for address in data:
                    address = address.split(",")
                    self.__address[int(address[0].strip())] = Address(
                        int(address[0].strip()), address[1].strip(),
                        int(address[2].strip()), int(address[3].strip()))

        with open("drivers", "r") as file:
            data = file.read()
            data = data.split("\n")
            if len(data) != 1:
                for driver in data:
                    driver = driver.split(",")
                    self.__driver[driver[0].strip()] = Driver(
                        driver[0].strip(), int(driver[1].strip()),
                        int(driver[2].strip()))
예제 #19
0
def perform_analysis(trainfolder):
    print "Working on {0}".format(trainfolder)
    sys.stdout.flush()
    temp = Driver(trainfolder)
    cls = RegressionDriver(temp, REFERENCE_DATA)
    cls.classify()
    return cls.validate(TEST_DATA)
예제 #20
0
def analysis(foldername, outdir, referencenum):
    """
    Start the analysis

    Input:
        1) Path to the driver directory
        2) Path where the submission file should be written
        3) Number of drivers to compare against
    """
    seed(42)
    start = datetime.now()
    submission_id = datetime.now().strftime("%H_%M_%B_%d_%Y")
    driver_No = [int(f) for f in os.listdir(foldername)]
    driver_No = [str(f) for f in sorted(driver_No)]
    folders = [os.path.join(foldername, f) for f in driver_No]
    referencefolders = [
        folders[i] for i in sorted(sample(range(len(folders)), referencenum))
    ]
    referencedrivers = []
    for referencefolder in referencefolders:
        referencedrivers.append(Driver(referencefolder))
    generatedata(referencedrivers)
    results = [perform_analysis(folder) for folder in folders]
    with open(os.path.join(outdir,
                           "pyRegression_{0}.csv".format(submission_id)),
              'w',
              newline='') as writefile:
        writefile.write("driver_trip,prob\n")
        for item in results:
            writefile.write("%s\n" % item)
    print('Done, elapsed time: %s' % str(datetime.now() - start))
예제 #21
0
 def __init__(self):
     self._state = {}
     GPIO.setmode(GPIO.BCM)
     self._gpio = GPIO
     self._driver = Driver.Driver(self._gpio)
     self._sensors = Sensors.Sensors(self._gpio)
     self._vision = Vision.Vision((640, 480))
     self._laser = Laser.Laser(self._gpio, 25)
예제 #22
0
def analysis(trainfoldername, testfoldername, outdir, referencenum):
    """
    Start the analysis

    Input:
        1) Path to the driver directory
        2) Path where the submission file should be written
        3) Number of drivers to compare against
    """
    seed(42)
    start = datetime.now()
    submission_id = datetime.now().strftime("%H_%M_%B_%d_%Y")
    trainfolders = [
        os.path.join(trainfoldername, f) for f in os.listdir(trainfoldername)
        if os.path.isdir(os.path.join(trainfoldername, f))
    ]
    referencefolders = [
        trainfolders[i]
        for i in sorted(sample(xrange(len(trainfolders)), referencenum))
    ]
    referencedrivers = []
    for referencefolder in referencefolders:
        referencedrivers.append(Driver(referencefolder))
    generatedata(referencedrivers)
    testdrivers = []
    testfolders = [
        os.path.join(testfoldername, f) for f in os.listdir(testfoldername)
        if os.path.isdir(os.path.join(testfoldername, f))
    ]
    for testfolder in testfolders:
        testdrivers.append(Driver(testfolder))
    generatetestdata(testdrivers)
    results = Parallel(n_jobs=10)(delayed(perform_analysis)(trainfolder)
                                  for trainfolder in trainfolders)
    with open(
            os.path.join(outdir,
                         "testing_results_{0}.txt".format(submission_id)),
            'w') as writefile:
        for item in results:
            writefile.write("%.4f\n" % item)
        mean = sum(results) / len(results)
        writefile.write("Mean: %.4f\n" % mean)
        writefile.write("Median: %.4f\n" % median(results))
        writefile.write("Min: %.4f\n" % min(results))

    print 'Done, elapsed time: %s' % str(datetime.now() - start)
예제 #23
0
    def __init__(self, inputData):
        self.inputData = inputData

        nBuses = self.inputData.nBuses
        nDrivers = self.inputData.nDrivers
        nServices = self.inputData.nServices

        start = self.inputData.start
        duration = self.inputData.duration
        kms = self.inputData.kms
        passengers = self.inputData.passengers

        capacity = self.inputData.capacity
        cost_km = self.inputData.cost_km
        cost_min = self.inputData.cost_min

        maxWorkingTime = self.inputData.maxWorkingTime

        self.maxBuses = self.inputData.maxBuses
        self.BM = self.inputData.BM
        self.CBM = self.inputData.CBM
        self.CEM = self.inputData.CEM

        self.drivers = []
        self.buses = []
        self.services = []
        self.overlapping = [[0 for x in range(nServices)]
                            for y in range(nServices)]

        for sId in xrange(
                0,
                nServices):  #hopefully really 0..(nServices-1) --> Check that
            service = Service(sId, start[sId], duration[sId], kms[sId],
                              passengers[sId])
            self.services.append(service)

        for dId in xrange(0, nDrivers):
            driver = Driver(dId, maxWorkingTime[dId])
            self.drivers.append(driver)

        for bId in xrange(0, nBuses):
            bus = Bus(bId, capacity[bId], cost_km[bId], cost_min[bId])
            self.buses.append(bus)

        for s1 in xrange(0, nServices):
            for s2 in xrange(0, nServices):
                startS1 = self.services[s1].getStart()
                endS1 = startS1 + self.services[s1].getDuration()

                startS2 = self.services[s2].getStart()
                endS2 = startS2 + self.services[s2].getDuration()

                if not (endS1 < startS2 or startS1 > endS2):
                    self.overlapping[s1][s2] = 1
                    self.overlapping[s2][s1] = 1
                else:
                    self.overlapping[s1][s2] = 0
                    self.overlapping[s2][s1] = 0
예제 #24
0
 def __init__(self, jid, password, params_map):
     super().__init__(jid, password)
     self.race_name = ""
     self.desire = False
     self.params_map = params_map
     self.track = []
     self.track_length = 0
     self.driver = Driver(jid)
     self.environment_jid = ""
예제 #25
0
def F_writeFeaturesfile4onedriver(folder, exten, nonstandfeatfile):
    print "Writing features for {0}".format(folder)
    sys.stdout.flush()
    STAND = False
    temp = Driver(folder, exten, STAND)
    with open(nonstandfeatfile, 'a') as featsfile:
        csvwriter = csv.writer(featsfile, delimiter=',')
        for i in xrange(len(temp.generate_data_model)):
            csvwriter.writerow(temp.generate_data_model[i])
예제 #26
0
    def __init__(self, device):
        """
        :param device: the linux event file of the Wacom device to connect to (eg: /dev/input/event12)
        """
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)

        self.driver = Driver(device)
        self.driver.start()  # Start Async Task
        self.dataSet = DataSet()
        self.digitSets = []

        # Externally set variables
        self.activeDrawingWindow = None
        self.activeDigitSet = None

        self.currentDigitPhase = 0
        self.count = 0
예제 #27
0
def perform_analysis(folders, referencedrivers):
    print folders
    sys.stdout.flush()
    temp = []
    for folder in folders:
        temp.append(Driver(folder))
    cls = MultiClassDriver(temp, referencedrivers)
    cls.classify()
    return cls.toKaggle()
예제 #28
0
 def create_query(self):
     drivers = {}
     riders = {}
     for key, driver in self.drivers.items():
         drivers[key] = Driver(driver.start, driver.dest, driver.endTime,
                               driver.seats)
     for key, rider in self.riders.items():
         riders[key] = Rider(rider.start, rider.endTime)
     return Query(riders, drivers)
예제 #29
0
    def __init__(self, id, id1, id2, q):
        Driver.__init__(self, id)
        self.id1 = id1
        self.id2 = id2
        self.q = q.queue
        q.start()

        if os.path.isfile("persist/"+str(self.id)):
            f = open("persist/"+str(self.id), "rb")
            self.setParameters(pickle.load(f))
            f.close()
        else: 
            self.status = 0
            self.brightness = 100
            self.mode = 1 # 1=temp, 0=color
            self.color = 0
            self.temp = 100
            self.setStatus(self.status)
            self.apply()
예제 #30
0
class Simcar:
    driver = Driver()

    __init__(self, driver, env = Env()):
        super()
        self.driver = driver

        steerAngle = 0
        accelerator = 0
        brake = 0
        speed = 0
 def _loadFile(self):
     """
     :return: reads the drivers from the given text file and adds them in the repo
     """
     f = open(self._fileName, "r")
     line = f.readline().strip()
     while len(line) >= 2:
         tok = line.split(",")
         driver = Driver(int(tok[0]), tok[1])
         Repository.add(self, driver)
         line = f.readline().strip()
예제 #32
0
    def run(self) -> None:
        driver = Driver()
        driver = driver.get_driver()
        driver.get(
            'https://domclick.ru/search?offset=10&limit=10&sort_dir=desc')
        html = driver.page_source
        soup = BeautifulSoup(html)

        max_ads = re.search(
            '(\d*)',
            soup.find('div', {
                'class': 'listing-title'
            }).text.replace(' ', '')).group(1)
        for i in range(0, int(max_ads), 100):
            soup = BeautifulSoup(
                requests.get(self._ads_list_url_pattern.format(i)).text)
            hrefs = list(map(lambda a: a.get('href', ''), soup.find_all('a')))
            for href in hrefs:
                if href.find('card') != -1:
                    self._data.put(href)
예제 #33
0
class Wrapper():

    def __init__(self):
        self.myDriver = Driver()
        self.data = ''
        self.start_time = 0
        self.end_time = -1
        self.total_time = -1

    def run(self):
        colnames = ['STIME','TIME','UID','PID','D','BLOCK','SIZE','COMM','PATHNAME']
        data = pandas.read_csv(self.data,names = colnames)
        data_dir = data.D.tolist()
        data_addr = map(lambda x: x*512, data.BLOCK.tolist())
        data_size = data.SIZE.tolist()
        arrs = []
        length = len(data_dir)
        self.start_time = time.time()
        for i in range(0,length):
            self.myDriver.drive(data_dir[i],data_addr[i],data_size[i])
        self.end_time = time.time()
        self.total_time = self.end_time - self.start_time
    
        self.myDriver.close()

    def open(self,data,target):
        self.myDriver.open(target)
        self.data = data

    def get_time(self):
        return self.total_time
예제 #34
0
 def __init__(self):
     self.myDriver = Driver()
     self.data = ''
     self.start_time = 0
     self.end_time = -1
     self.total_time = -1
예제 #35
0
파일: main.py 프로젝트: stetro/AMSRobot
from detection.SquareDetection import SquareDetection
from detection.CircleDetection import CircleDetection
from Stepper import Stepper
from Driver import Driver

import time

#
# This script is controlling the main logic for the 
# autonomous robot decisions.
#

if __name__ == '__main__':

	# initialize Driver object for stepper motor controls
	d = Driver(0.003)

	# move a bit forwards (first feedback)
	for i in range(0,10):
		d.forwards()

	# this first initialization will also initialize the 
	# raspberry pi camera (will happen only once in this program)
	circleDetection = CircleDetection(draw=False,width=640 ,height= 480, debug=True)

	while(circleDetection.isRunning()):
		# does the detection and frame analysis
		(circle, frame) = circleDetection.loop()

		print("circle found: " + str(circle))
		# if no circle is shown, turn right (right hand rule)