Ejemplo n.º 1
0
def main():
    files = glob.glob("./scans/*.jpg")
    files += glob.glob("./scans/*.jpeg")
    for f in files:
        reset_stats()
        print "Processing: " + f.split("/")[len(f.split("/")) - 1]

        schedule = Schedule()
        schedule.load_data()
        if schedule.get_has_schedule():
            scan_image(f, schedule)

            print "Sheet ok? ",
            while True:
                cv2.imshow("image", cv2.resize(img, (446, 578)))
                cv2.moveWindow("image", 0, 0)
                # user_in = raw_input()
                key = cv2.waitKey(-1)
                if key == ord("y"):
                    print "Sheet ok... Dumping data"
                    dump_stats()
                    os.remove(f)
                    break
                elif key == ord("n"):
                    print "Marking to redo"
                    #os.rename(f, "./scans/redo/" + f.split("/")[len(f.split("/")) - 1])
                    break
                elif key == ord("q"):
                    exit(0)
                else:
                    continue
            cv2.destroyAllWindows()
        else:
            print "Unable to load schedule... Aborting"
Ejemplo n.º 2
0
 def __init__(self, size, data):
     self.schedules = []
     self.data = data
     for i in range(size):
         x = Schedule(data)
         x.generate_sample()
         self.schedules.append(x)
Ejemplo n.º 3
0
def update(requests, experts, scheduleTime):
    """
    Runs the matching function for each client request.
    Requires: requests (ClientsCollection), the collection of clients
    Requires: experts (ExpertsCollection), the collection of experts
    Ensures: tuple of (schedule, updatedExperts)
             schedule (Schedule) is the collection of matches for
              the schedule file.
             updatedExperts (ExpertsCollection) is the updated list of
              experts.
    """

    newExperts = ExpertsCollection(experts.getExpertsList())
    scheduleOutput = Schedule()

    # Running each of the clients in the requests collection parameter
    # through the matchClient function. Updating the Experts each time,
    # generating a Schedule collection and an updated Experts collection.

    for client in requests.items():
        matchResults = matchClient(client, newExperts, scheduleTime)
        scheduleOutput.addToSchedule(matchResults[0])
        newExperts = matchResults[1]

    return scheduleOutput, newExperts
Ejemplo n.º 4
0
    def getSchedule(self, schedule=None, getDom=False):
        if schedule is None:
            schedule = Schedule()
        days = [i for i in range(7)]

        # build command-xml ...
        doc, cmdElem = self._getXML('get')
        schedElem = doc.createElement("SCHEDULE")
        cmdElem.appendChild(schedElem)

        if not getDom:  # return full information
            for d in days:
                dayElem = doc.createElement("Device.System.Power.Schedule." + str(d))
                schedElem.appendChild(dayElem)

        # ... post and parse the result
        dom = self._postCmd(doc)
        if getDom:
            return dom

        tags = dom.getElementsByTagName("SCHEDULE")[0].childNodes
        for tag in tags:
            name = tag.tagName
            if name.find('List') > 0:
                continue
            day = name.split('.')[-1]
            value = tag.firstChild.nodeValue
            schedule.fromTransport(value, int(day))
        return schedule
Ejemplo n.º 5
0
 def test_games(self):
     sched = Schedule('1/1/2015')
     games = sched.get_games()
     size = len(games)
     exp_size = 1230
     self.assertEqual(size, exp_size)
     cols = len(games.columns)
     exp_cols = 40 + 4
     self.assertEqual(cols, exp_cols)
Ejemplo n.º 6
0
def api_schedule():
    try:
        global Global
        a = Global['MyAgent'](request)
        s = Schedule(a)
        return (jsonify({'check': True, 'html': s.ToHtml()}))
    except:
        TB.print_exc()
        return (jsonify({'check': False}))
Ejemplo n.º 7
0
    def test_get_season_name(self):
        sched = Schedule('1/1/2001', '2/1/2001')
        name = sched.get_season_name()
        exp_name = '2000-01'
        self.assertEqual(name, exp_name)

        sched = Schedule('11/1/2001', '12/1/2001')
        name = sched.get_season_name()
        exp_name = '2001-02'
        self.assertEqual(name, exp_name)
Ejemplo n.º 8
0
    def initChromosomes(self, numberOfChromosomes):
        for i in range(0, numberOfChromosomes):
            chromosome = Schedule(self.slots, self.rooms, self.courses,
                                  self.instructors)
            chromosome.createSchedule()

            self.chromosomes.append({
                "chromosome": chromosome,
                "fitness": chromosome.calculateFitness()
            })
Ejemplo n.º 9
0
def index(season=2015):
	season = int(season)
	champ = season - 1
	# render current season
	if (not (champ in availableSeasons)):
		# render season not available
		print 'no data for ' + str(season)
		return redirect(url_for('index'))
		
	
	#data = season
	parser = HReferenceParser('app/static/data/' + str(season) + '.csv')
	games = parser.getGames()
	schedule = Schedule(games)
	gameLog = GameLog()

	stats = Stats()
	beltHolder = availableSeasons[champ]
	defendingChamp = beltHolder
	beltGame = None

	for g in schedule.games:
		beltGame = stats.analyzeGame(g, beltHolder)
		if beltGame:
			gameLog.addGame(beltGame)
			beltHolder = beltGame.getBeltHolderAfterGame()

	upcomingChampGame = schedule.getUpcomingChampionshipGame(beltHolder)
	upcomingChampGameIfHomeTeamWins = None
	upcomingChampGameIfAwayTeamWins = None
	if upcomingChampGame:
		upcomingChampGameIfHomeTeamWins = schedule.getUpcomingChampionshipGame(
			upcomingChampGame.getHomeTeam(), upcomingChampGame.getAwayTeam())
		upcomingChampGameIfAwayTeamWins = schedule.getUpcomingChampionshipGame(
			upcomingChampGame.getAwayTeam(), upcomingChampGame.getHomeTeam())

	data = {
		'id' : beltHolder.getID(),
		'name' : beltHolder.getName()
	}
  
	return render_template('index.html', 
		games = gameLog.getGames(), 
		availableSeasons = availableSeasons,
    defendingChamp = defendingChamp,
		beltHolder = beltHolder,
		isOngoingSeason = season,
		stats = stats,
		gameLog = gameLog,
		upcomingChampGame = upcomingChampGame,
		upcomingChampGameIfHomeTeamWins = upcomingChampGameIfHomeTeamWins,
		upcomingChampGameIfAwayTeamWins = upcomingChampGameIfAwayTeamWins,
    sortedStats = stats.getSortedStats(),
		currentSeason = season,
		)
Ejemplo n.º 10
0
def getSchedule(text):
    text = text.rstrip()
    lines = text.split('\n')
    points = []
    for l in lines:
        nums = l.rstrip().split(' ')
        #print "nums: ", nums
        numericNums = [int(x) for x in nums]
        points.append(s.MultiPhasePoint(numericNums))
    print "number of points: ", len(points)
    return s.SampleSchedule(points)
Ejemplo n.º 11
0
 def make_schedule(self) -> 'list[Schedule]':
     schedule = Schedule()
     schedule_list = []
     if len(self.course_manager.courses) > 0:
         new_schedule_list = []
         schedule_list = schedule.add_course(self.course_manager.courses[0])
         for course in self.course_manager.get_courses()[1:]:
             for schedule in schedule_list:
                 new_schedule_list += schedule.add_course(course)
             schedule_list = new_schedule_list
             new_schedule_list = []
     return schedule_list
Ejemplo n.º 12
0
def index(season=2015):
    season = int(season)
    champ = season - 1
    # render current season
    if (not (champ in availableSeasons)):
        # render season not available
        print 'no data for ' + str(season)
        return redirect(url_for('index'))

    #data = season
    parser = HReferenceParser('app/static/data/' + str(season) + '.csv')
    games = parser.getGames()
    schedule = Schedule(games)
    gameLog = GameLog()

    stats = Stats()
    beltHolder = availableSeasons[champ]
    defendingChamp = beltHolder
    beltGame = None

    for g in schedule.games:
        beltGame = stats.analyzeGame(g, beltHolder)
        if beltGame:
            gameLog.addGame(beltGame)
            beltHolder = beltGame.getBeltHolderAfterGame()

    upcomingChampGame = schedule.getUpcomingChampionshipGame(beltHolder)
    upcomingChampGameIfHomeTeamWins = None
    upcomingChampGameIfAwayTeamWins = None
    if upcomingChampGame:
        upcomingChampGameIfHomeTeamWins = schedule.getUpcomingChampionshipGame(
            upcomingChampGame.getHomeTeam(), upcomingChampGame.getAwayTeam())
        upcomingChampGameIfAwayTeamWins = schedule.getUpcomingChampionshipGame(
            upcomingChampGame.getAwayTeam(), upcomingChampGame.getHomeTeam())

    data = {'id': beltHolder.getID(), 'name': beltHolder.getName()}

    return render_template(
        'index.html',
        games=gameLog.getGames(),
        availableSeasons=availableSeasons,
        defendingChamp=defendingChamp,
        beltHolder=beltHolder,
        isOngoingSeason=season,
        stats=stats,
        gameLog=gameLog,
        upcomingChampGame=upcomingChampGame,
        upcomingChampGameIfHomeTeamWins=upcomingChampGameIfHomeTeamWins,
        upcomingChampGameIfAwayTeamWins=upcomingChampGameIfAwayTeamWins,
        sortedStats=stats.getSortedStats(),
        currentSeason=season,
    )
Ejemplo n.º 13
0
def generate(eventData, competitors, debug):
    activeSchedule = Schedule(
    )  # Create object for initial schedule. Probably add something to store all these objects externally later
    activeSchedule.events = copy.deepcopy(
        eventData)  # Create a local instance of eventData[]

    seniors = []
    team = []

    # Assign periods randomly for self-schedule eventData
    for obj in activeSchedule.events:
        if (obj.selfSchedule == True):
            obj.period = random.randint(1, 6)

    # Loop through all the possible competitor slots in an event.
    for phase in range(3):
        # Shuffle the event lsit so that there is no bias as to when the event is
        random.shuffle(activeSchedule.events)
        # Loop through each event in the current schedule
        for event in activeSchedule.events:
            # If the event isn't filled yet
            if len(event.competitors) < event.size:
                # If we can still add people to the team, get the best competitor out of everyone
                if len(team) < 15:
                    competitor = Competitor.getBestCompetitor(
                        competitors, event.name, event.period, seniors,
                        MAX_GRADE, MAX_QUANTITY)
                # If we're full, get the best competitor out of the people on the team already
                else:
                    competitor = Competitor.getBestCompetitor(
                        team, event.name, event.period, seniors, MAX_GRADE,
                        MAX_QUANTITY)
                # Now that the competitor has been added to this time slot, they are occupied
                competitor.occupied.append(event.period)
                # Add the competitor to the list of poeple competing in the event
                event.competitors.append(competitor)

                # Add the competitor to the list of seniors if they are a senior and aren't already there
                if competitor.grade == MAX_GRADE and competitor.name not in seniors:
                    seniors.append(competitor.name)
                # Add the competitor to the competing team roster if they aren't already there
                if competitor not in team:
                    team.append(competitor)

    # Reset the occupied status of the competitors for the next schedule
    for c in competitors:
        c.occupied = []

    activeSchedule.members = team
    return activeSchedule
Ejemplo n.º 14
0
    def getEmptySchedule(self):
        tmp = Schedule()
        # print(self)
        # print("Schedule size: {}, {}".format(len(self.rooms), self.NUM_TIME_SLOTS))
        tmp.Schedule(len(self.rooms), self.NUM_TIME_SLOTS)

        # print("LEN ROOMS::")
        # print(len(self.rooms))
        # print(len(tmp.schedule))
        for i in range(len(self.rooms)):
            for j in range(self.NUM_TIME_SLOTS):
                # print("i {} j {}".format(i, j))
                tmp.schedule[i][j] = -1
        return tmp
Ejemplo n.º 15
0
 def __init__(self, mainWindow):
     """
     Retrieve Stored locations of Maestro and Job files if they have been saved previously.
     With those names, read the schedule and job files and store as an internal object
     accessible via self.getSched. If the locations have not been previously stored output
     a message asking for them to be selected.
     """
     #Setup main window
     #QMainWindow.__init__(self)
     self.setupUi(MainWindow)
     self.fileSchedule.setText("Read New Runbook Files")
     self.otherGuiSetup()
     #Setup some internally required file locations
     dataDir = self.getDataDir()
     dataDir = self.getDataDir() + os.sep
     self._sqlite_ini_name = 'ini.db'
     self._graphvizTxtFile = dataDir + "Graphviz.txt"
     self._graphvizSvgFile = dataDir + "Graphviz.svg"
     self._db = dataDir + 'schedule.db'
     self._icon = 'Monitor_Screen_32xSM.png'
     self._s = Schedule()
     #Populate GUI with data
     try:
         self.getData()
     except(KeyError):
         return
     self.popSchedsCombo()
 def generate_lists(self):
     bottom = True
     for i in range(0, len(self._transactions)):
         if self._transCounter[i] < len(self._transactions[i]):
             self._list.append(self._transactions[i][self._transCounter[i]])
             self._transCounter[i] += 1
             self.generate_lists()
             self._transCounter[i] -= 1
             self._list.pop()
             bottom = False
     if bottom:
         # print(self._list)
         sch = Schedule(self._list)
         if sch.is_conflict_serializable():
             self._counter += 1
             print(sch.get_printable_schedule())
Ejemplo n.º 17
0
    def printCalendar(self, day, month, year):

        #months[i] = name of month i
        #leave empty so that months[1] = "January"
        months = ["", "January", "February", "March", "April", "May", "June", 
        "July", "August", "September", "October", "November", "December"]
        
        #days[i] = number of days in month i
        days = [0,31,28,31,30,31,30,31,31,30,31,30,31]

        #check for leap year
        if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
            days[2] = 29

        # calculate the number of shifts and weeks covered
        myDict = self.calculate(len(self.workers), month, year, day, days[month], self.dayCannotWork())

        #print calendar header
        print "        " + months[month] + " " + str(year)
        print " S   M   Tu   W  Th   F   S"

        # get calendar and schedule
        myCalendar = self.generateCalendar(month, day, year, days, myDict)
        myWeekList = Schedule().generateSchedule(myCalendar, self.workers, myDict, 
            self.checkHoliday(month, day), day, self.day(month, day, year), self.dayCannotWork())

        #print them out
        for i in range(0,len(myWeekList)):
            print " " + '  '.join(p for p in myCalendar[i])
            print '   '.join(p for p in myWeekList[i])

        return {'calendar': myCalendar, 'schedule': myWeekList}
Ejemplo n.º 18
0
 def closure(coordinates):
     cPoints = [
         sc.MultiPhasePoint(coors,
                            [[quadChooser.getQuadrature(coors[0]), 'B']])
         for coors in coordinates
     ]
     return Common.DependentList(cPoints)
Ejemplo n.º 19
0
def selected():
    try:
        global Global
        a = Global['MyAgent'](request)
        return render_template('selected.html', agent=a, schedule=Schedule(a))
    except:
        TB.print_exc()
        return redirect(url_for('logout'))
Ejemplo n.º 20
0
    def draw_graph(self):
        schedule = self.get_schedule()
        tardiness = Schedule().tardiness(self.d, schedule)
        self.save_result(schedule, tardiness)

        fig, gnt = plt.subplots()
        gnt.set_title('Побудований розклад')

        gnt.set_ylim(0, (self.num_machines + 1) * 10 + 10)
        gnt.set_xlim(
            0,
            max([
                job[0] + job[1] for machine in schedule for due_date in machine
                for job in due_date
            ]) + 5)

        gnt.set_xlabel('Час')
        gnt.set_ylabel('Машина')

        gnt.grid(True)

        yticks = [(i + 1) * 10 + 5 for i in range(self.num_machines)]
        yticklabels = [str(i + 1) for i in range(self.num_machines)]
        gnt.set_yticks(yticks)
        gnt.set_yticklabels(yticklabels)

        # setting the schedules
        for i in range(self.num_machines):
            for j in range(2):
                gnt.broken_barh(
                    schedule[i][j],
                    ((i + 1) * 10, 9),
                    facecolors=('orange', 'green', 'blue') *
                    len(self.num_jobs),  # mark each job with diff color
                    edgecolors='black')  # color of borders
            for due_date in schedule[i]:
                for job in due_date:
                    gnt.text(
                        x=job[0] + job[1] /
                        2,  # x = gorizontal position of the label (center of the bar)
                        y=(i + 1) * 10 +
                        4,  # y = vertical position of the label
                        s=job[1],  # text (length of the job)
                        ha='center',
                        va='center',
                        color='white',
                        size=15)

        # setting the due dates
        for i in range(self.num_d):
            gnt.axvline(x=self.d[i], c='black', linewidth=5)
            # gnt.text(x=self.d[i] + 0.5, y=1, s=f'd = {self.d[i]}', color='black', size=10)  # possible way to
            # set xtick for due date

        gnt.set_xticks(list(gnt.get_xticks()) +
                       self.d)  # set xtick for due date

        fig.show()
Ejemplo n.º 21
0
class Student(Person):
    def __init__(self):
        self.classSchedule = Schedule()

    def getSchedule(self, daysFilter):
        return self.classSchedule.getDescription(daysFilter)

    def getClassSchedule(self):
        return self.classSchedule
Ejemplo n.º 22
0
    def make_today_schedule(self):

        events = [event for event in self.events if datetime.datetime.today.date() == event.start.date()]

        time_available = datetime.timedelta(hours=8) - sum([ev.end - ev.start for ev in events], datetime.timedelta(0))

        tasks_scored = [{'task': task, 'score': self._ranking_function(task)} for task in self.tasks]

        return Schedule(events, self._select_tasks(tasks_scored, time_available))
Ejemplo n.º 23
0
 def adder(point):
     hashValue = hashFunc(point)
     if hashT.has_key(hashValue):
         cPoint = hashT[hashValue]
         cPoint.addQuadrature(point.quadrature)
     else:
         newCPoint = sc.MultiPhasePoint(point.coordinates)
         newCPoint.addQuadrature(point.quadrature)
         hashT[hashValue] = newCPoint
 def _crossover_schedule(self, schedule1, schedule2):
     crossover_schedule = Schedule(self._data).initialize()
     for i in range(0, len(crossover_schedule.get_lectures())):
         if rnd.random() > 0.5:
             crossover_schedule.get_lectures()[i] = schedule1.get_lectures()[i]
         else:
             crossover_schedule.get_lectures()[i] = schedule2.get_lectures()[i]
     return crossover_schedule
class Professor(Person):

    def __init__(self):
        self.teachingSchedule = Schedule()
        
    def getSchedule(self, daysFilter):
        return self.teachingSchedule.getDescription(daysFilter)
    
    def getTeachingSchedule(self):
        return self.teachingSchedule
Ejemplo n.º 26
0
 def GAINIT(self, off):
     onlR = int(self.n * (1 - self.offP))
     GAOP = GAOperator(self.DG, 0, onlR, self.gaN, off)
     trips = GAOP.getResult()
     rejs = GAOP.getRejs()
     shuttles = []
     for trip in trips:
         shuttle = Shuttle(self.MG.depot, trip, [], 0)
         shuttles.append(shuttle)
     return Schedule(shuttles, rejs)
Ejemplo n.º 27
0
class Student(Person):

    def __init__(self):
        self.classSchedule = Schedule()

    def getSchedule(self, daysFilter):
        return self.classSchedule.getDescription(daysFilter)
    
    def getClassSchedule(self):
        return self.classSchedule
Ejemplo n.º 28
0
 def __init__(self):
     self.today = Schedule()  # Current schedule
     self.schedules = {
     }  # Dictionary of schedules like {1:Schedule(date(2015,3,27)),2:Schedule(date...}
     self.tads = {}  # Dict w/ {user_ID: Resource(user_ID), ...}
     self.watches = {}
     self.m = Model()
     self.timeLimit = 360
     self.verbose = True
     self.vars = {}
Ejemplo n.º 29
0
def main():
    vtna = Squadron()
    dates = [
        date(2015, 3, 27), date(2015, 3, 28)
    ]  #Dates to write schedules for. Should be passed via sys.argv Assume unlisted gap dates are blank schedules.
    #Dealing with blank schedules needs more work. Schedules need to know if crew rests constraints apply from the previous day
    i = 1
    for day in dates:
        sked = Schedule(day)
        sked.flyDay = i
        sked.waves[1].first = True
        vtna.schedules[day] = sked
        i = i + 1

    #Creates the events in the syllabus. Would be replaced by call to data if necessary.
    for i in range(-3, 11):
        e = Event(i)
        if i > -3:
            vtna.syllabus[i - 1].followingEvents.add(e)
        if i > 0:
            e.flightHours = 1.0
            if i != 5 and i != 9:
                e.onwing = True
        vtna.syllabus[i] = e

    vtna.syllabus[-3].initialEvent = True
    vtna.syllabus[5].offwing = True
    vtna.syllabus[9].offwing = True
    vtna.syllabus[9].check = True
    vtna.syllabus[10].followsImmediately = True

    s = Student("Test", vtna)
    d = date(2015, 3, 27)
    for k in s.events(d, vtna.schedules[d].waves[1]):
        print d, 1
        print k
    d = date(2015, 3, 28)
    for k in s.events(d, vtna.schedules[d].waves[1]):
        print d, 1
        print k
    for k in s.events(d, vtna.schedules[d].waves[2]):
        print d, 2
        print k
Ejemplo n.º 30
0
def makeNearbyPoints(myCoors, quads):
    allCloseCoordinates = lg.multipleDimensions(
        [makeRange(c) for c in myCoors])
    closeEnoughCoordinates = [
        pt for pt in allCloseCoordinates if distance(myCoors, pt) <= 1
    ]
    return [
        WrapperPoint(sc.MultiPhasePoint(newCoords, quads))
        for newCoords in closeEnoughCoordinates
    ]
Ejemplo n.º 31
0
def patientdb():
    booked = root.child('Checkup').get()
    list = []

    for pubid in booked:

        bookedpatients = booked[pubid]

        if bookedpatients['fullname']:
            bookedpatient = Schedule(bookedpatients['fullname'], bookedpatients['gender'], bookedpatients['contact'], bookedpatients['address'],
                                     bookedpatients['dateofbirth'], bookedpatients['nric'], bookedpatients['condition'],
                                     bookedpatients['email'], bookedpatients['scheduledate'],bookedpatients['emergencycontactname'], 
                                     bookedpatients['emergencycontact'], bookedpatients['time'])

            bookedpatient.set_pubid(pubid)
            print(bookedpatient.get_pubid())
            list.append(bookedpatient)

    return render_template('patientdb.html', booked=list)
def process_data(data):
    """The function processes text from the file and returns a list that is used to create a spreadsheet"""
    # Splitting schedule into sections (0 - general info, 1-5 - days) by "----...----" pattern (2+ dashes in line)
    divided_schedule = re.split('-{2,}\n*', data)

    schedule_info = process_header(divided_schedule[0])
    scd = Schedule(schedule_info)
    # processing info about classes and passing it to Schedule
    scd = process_lessons(scd, divided_schedule[1:])

    return scd
Ejemplo n.º 33
0
def set_schedule():
    repeat = request.form["repeat"]
    if repeat == "0":  #no-repeat
        date = request.form["date"]
        time = request.form["time"]
        day = "None"
    elif repeat == "1":  #everyday
        time = request.form["time"]
        date = "None"
        day = "None"
    else:  #everyweek
        day = request.form["day"]
        time = request.form["time"]
        date = "None"

    coffeetype = request.form["coffeetype"]
    cups = request.form["cups"]
    s = Schedule(date, time, day, repeat, coffeetype, cups)
    s.save_schedule()
    return redirect("/home")
Ejemplo n.º 34
0
    def getSchedule(self):
        ''' Pull the current schedule, requires .icalURL file in same directory '''
        url = ''
        try:
            with open('.icalURL', 'r') as icalURL:
                url = icalURL.readline().replace('\n', '')
        except IOError:
            pass    # No pre made url file, so create dialogue for creating one.

        self.schedule = Schedule(url)
        self.schedule.events = self.schedule.sortEventsByDatetime()
Ejemplo n.º 35
0
def classes():
    try:
        global Global
        a = Global['MyAgent'](request)
        return render_template('classes.html',
                               agent=a,
                               schedule=Schedule(a),
                               db=DB())
    except:
        TB.print_exc()
        return redirect(url_for('logout'))
Ejemplo n.º 36
0
    def localOpt(self, routes, t, rejects):
        routes = self.optimize(routes, t)
        schedule = Schedule(routes, rejects)
        for r in schedule.rejects:
            for i in range(len(schedule.shuttles)):
                k = self.insert(schedule.shuttles[i], r, t)
                if k != schedule.shuttles[i].trip:
                    schedule.shuttles[i].trip = k[:]
                    break

        schedule = Schedule(schedule.shuttles[:], schedule.rejects[:])
        idx = 0
        while len(schedule.shuttles) < self.shutN:
            if idx >= len(schedule.rejects): break
            r = schedule.rejects[idx]
            shuttle = Shuttle(self.depot, [r, -r], [], t)
            if self.shuttleAbleS(shuttle)[0]:
                schedule.shuttles.append(shuttle)
            idx += 1

        return Schedule(schedule.shuttles[:], schedule.rejects[:])
Ejemplo n.º 37
0
	def make_today_schedule(self):
		# TODO: Add logic to handle task <-> project dependence
		# TODO: Add logic to handle task <-> task dependence
		# TODO: Add logic to handle task <-> training dependence

		events = [event for event in self.events if datetime.datetime.today().date() == event.start.date()]

		time_available = datetime.timedelta(hours=8) - sum([ev.end - ev.start for ev in events], datetime.timedelta(0))

		tasks_scored = [{'task' : task, 'score' : self._ranking_function(task)} for task in self.tasks]

		return Schedule(events, self._select_tasks(tasks_scored, time_available))
Ejemplo n.º 38
0
def runScheduleWorkflowTestWithPostSelectionModification(
        cgen, spec, qmap, psel, form, pmod):
    myLogger = logging.getLogger("workflow")
    myLogger.debug("starting workflow:  generating coordinates")
    points = cgen()  # generate some coordinates
    myLogger.debug('generated ' + str(len(points)) +
                   ' points')  # see how many were generated
    #    mySet = set(points)
    #    (l1, l2) = len(mySet), len(points)
    myLogger.debug("selecting special points")
    special = spec()  # select special points
    normal = filterSpecialPoints(
        special,
        points)  # make sure no special points are left in the normal pool
    myLogger.debug(
        "selected special points .... points left in normal pool: " +
        str(len(normal)) + "  specially selected points: " + str(len(special)))
    myLogger.debug("applying quadrature ...")
    (normList, specList) = (
        qmap(normal), qmap(special)
    )  # apply quadrature to both the normal pool and the special pool
    myLogger.debug("quadrature applied to normal and special points")
    numAlreadySelected = len(
        specList.getPoints()
    )  # number of points that still need to be selected:  original minus number of special points
    myLogger.debug("selecting normal points (" + str(numAlreadySelected) +
                   " already selected)")
    selectedList = psel(
        normList,
        numAlreadySelected)  # select that many points from the normal list
    myLen = len(selectedList.getPoints()) + len(
        specList.getPoints()
    )  # the number of points selected is the number in the special list plus the number selected from the normal list
    myLogger.debug("selected " + str(myLen) +
                   " points total (special + normal)")
    allSelectedPoints = selectedList.getMultiPhasePoints(
    ) + specList.getMultiPhasePoints()
    myLogger.debug(
        "applying any post-selection modification operators to selected points ..."
    )
    modifiedPoints = pmod(
        allSelectedPoints)  # apply any post-selection modifications
    myLogger.debug(
        str(len(modifiedPoints)) +
        " points left after applying post-selection modifier ...")
    myLogger.debug("creating sample schedule ...")
    schedule = sc.SampleSchedule(
        modifiedPoints
    )  # create a schedule from all the special points and the normally-selected points
    myLogger.debug("sample schedule completed, formatting schedule")
    formatted = form(schedule)  # format the schedule as a string
    myLogger.debug("sample schedule formatted")
    return (formatted, schedule)
Ejemplo n.º 39
0
class Professor(Person):

    def __init__(self, teachingSchedule=None, **kwargs):
        Person.__init__(self, **kwargs)
        if teachingSchedule is None:
            self.teachingSchedule = Schedule()
        else:
            self.teachingSchedule = teachingSchedule
        
    def getSchedule(self, daysFilter):
        return self.teachingSchedule.getDescription(daysFilter)
    
    def getTeachingSchedule(self):
        return self.teachingSchedule
Ejemplo n.º 40
0
class Student(Person):

    def __init__(self, classSchedule=None, **kwargs):
        Person.__init__(self, **kwargs)
        if classSchedule is None:
            self.classSchedule = Schedule()
        else:
            self.classSchedule = classSchedule

    def getSchedule(self, daysFilter):
        return self.classSchedule.getDescription(daysFilter)
    
    def getClassSchedule(self):
        return self.classSchedule
Ejemplo n.º 41
0
 def __init__(self, teachingSchedule=None, **kwargs):
     Person.__init__(self, **kwargs)
     if teachingSchedule is None:
         self.teachingSchedule = Schedule()
     else:
         self.teachingSchedule = teachingSchedule
Ejemplo n.º 42
0
 def __init__(self, classSchedule=None, **kwargs):
     Person.__init__(self, **kwargs)
     if classSchedule is None:
         self.classSchedule = Schedule()
     else:
         self.classSchedule = classSchedule
Ejemplo n.º 43
0
 def __init__(self):
     self.teachingSchedule = Schedule()
Ejemplo n.º 44
0
 def test_team_list(self):
     sched = Schedule('1/1/2015')
     _list = sched.get_team_list()
     _len = len(_list)
     exp_len = 30
     self.assertEqual(_len, exp_len)
Ejemplo n.º 45
0
 def setExclusiveState(self, start, end, active=True):
     sched = Schedule(not active)  # all ON or OFF schedule
     sched.setState(start, end, active)  # time range in status OFF/ON
     return self.setSchedule(sched)  # write schedule to plug
Ejemplo n.º 46
0
        if len(sys.argv) > 2:
            plug = Plug(sys.argv[1], password=sys.argv[2])

            # query power state
            state = plug.getPowerState()
            print("Power state is active: {0}".format(state))

            # set power state
            result = plug.setPowerState(len(sys.argv) > 3)
            print("Setting power state... success?: {0}".format(result))

            # query current schedule
            print("Current schedule:")
            print(plug.getSchedule())

            sched = Schedule(False)
            sched.setState(TPoint(TPoint.MON, 0, 0), TPoint(TPoint.TUE, 0, 0), True)
            print("input schedule:")
            print(sched)
            print("Setting schedule... success:".format(plug.setSchedule(sched)))
            print("Output schedule from plug:")
            # print plug.getSchedule(getDom=True).toprettyxml()
            print(plug.getSchedule())

            # print \
            #  plug.setState(TPoint(TPoint.FRI,0,0),TPoint(TPoint.SAT,0,0),False).\
            #  toprettyxml()

            # now = TPoint.now()
            # now = now.createAfter(1,0,0)
            # then = now.createAfter(0,3,0)
Ejemplo n.º 47
0
class MaestroUi(Ui_MainWindow):
    """
    This class inherits from a gui class design using QTDesigner and is designed
    to isolate change to the gui layout from any code which deals with user interaction
    and data display. The key to populating the GUI with data is to populate the
    schedule combo Box, everything else will cascade from that eg. schedule defines
    contents of Table view etc.
    """
    def __init__(self, mainWindow):
        """
        Retrieve Stored locations of Maestro and Job files if they have been saved previously.
        With those names, read the schedule and job files and store as an internal object
        accessible via self.getSched. If the locations have not been previously stored output
        a message asking for them to be selected.
        """
        #Setup main window
        #QMainWindow.__init__(self)
        self.setupUi(MainWindow)
        self.fileSchedule.setText("Read New Runbook Files")
        self.otherGuiSetup()
        #Setup some internally required file locations
        dataDir = self.getDataDir()
        dataDir = self.getDataDir() + os.sep
        self._sqlite_ini_name = 'ini.db'
        self._graphvizTxtFile = dataDir + "Graphviz.txt"
        self._graphvizSvgFile = dataDir + "Graphviz.svg"
        self._db = dataDir + 'schedule.db'
        self._icon = 'Monitor_Screen_32xSM.png'
        self._s = Schedule()
        #Populate GUI with data
        try:
            self.getData()
        except(KeyError):
            return
        self.popSchedsCombo()

    def getDataDir(self):
        """
        This application may have a windows executable built from it using cx_Freeze in
        which case the local directly that the script runs from assumed by python
        will be incorrect. Here we derive the data directory. This allows the ini file
        Maestro.ini to be found and intermediate files for Graphviz
        """
        if getattr(sys, 'frozen', False):
        # The application is frozen
            datadir = os.path.dirname(sys.executable)
        else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
            datadir = os.getcwd()

        return datadir

    def getData(self):
        """
        Check schedule database exists. This is done when this class is initialised.
        :return: None
        """
        #Setup an ini.db file for various stored values if it does not exist
        conn = sqlite3.connect(self._sqlite_ini_name)
        c = conn.cursor()
        # Settings database
        c.execute("CREATE TABLE IF NOT EXISTS SETTINGS (KEY TEXT PRIMARY KEY, VALUE TEXT)")
        conn.commit()
        conn.close()
        #Read schedule text files into database table if such table does not exist
        if not os.path.exists(self._db):
            msg = QMessageBox()
            msg.setWindowIcon(QIcon(self._icon))
            msg.setWindowTitle('Maestro')
            msg.setText("Error")
            msg.setIcon(QMessageBox.Critical)
            msg.setInformativeText("Schedule files not yet loaded. Please select them.")
            msg.exec()

            self.getSchedFileNames()  # prompt for new files names and load database
            return

    def otherGuiSetup(self):
        """ Do other setup things required to get the static GUI components set up, and
        components acting correctly upon user interaction. There should NOT be any
        code associated with date reading or population in here.
        """
        self.fileSchedule.triggered.connect(self.getSchedFileNames) #File menu option to look up data file names
        self.exportAction.triggered.connect(self.exportDirectConnections) #File menu option to export current schedule direct dependencies
        self.exportFullConnectionAction.triggered.connect(self.exportFullConnections) #File menu option to export current schedule full connection Map
        self.actionSetDotLoc.triggered.connect(self.setDotLoc) #File menu option to export current schedule
        self.actionShowFullSchedule.triggered.connect(self.showFullSchedule) #File menu option to export current schedule
        self.actionShowCalendars.triggered.connect(self.showFullCalendar)#File menu option to display all calendars
        self.actionFile_Locations.triggered.connect(self.fileInfo) #Options menu, display file names selected
        self.actionCtrl_File_Deps.triggered.connect(self.show_ctrl_file_deps) # File menu, display dependencies of a given control file
        self.actionResource_Dependencies.triggered.connect(self.show_resource_deps) #File menu display resource succ. deps
        #Connect combo box selection to table population
        self.comboBoxSched.activated.connect(self.tablePopulate)
        self.comboBoxSched.currentIndexChanged.connect(self.tablePopulate)
        self.comboBoxSched.editTextChanged.connect(self.findIndex)
        self.comboBoxSched.highlighted.connect(self.tablePopulate)
        #Ensure that a change in the radio button leads to re-population of table view
        self.buttonGroup.buttonClicked[int].connect(self.handleBGChange)
        self.tableView.clicked.connect(lambda: self.tableClicked(self.tableView))
        self.tableView.activated.connect(lambda: self.tableClicked(self.tableView))
        #Connect find processing
        self.lineEditFind.returnPressed.connect(self.findText)

    def getSchedFileNames(self):
        """Allow selection of the schedule and job file names from the ui.
        Displays in succession file dialogs to allow selection of schedule file from
        Maestro followed by the job file. The full paths are serialised in a pickle file
        so that they are available for future runs of the program, until next changed.
        File specification is performed via the File menu on the gui.
        """
        w = QWidget()
        s = QFileDialog.getOpenFileName(w,"Select SCHEDULE file")[0]
        j = QFileDialog.getOpenFileName(w,"Select JOB file")[0]
        cal = QFileDialog.getOpenFileName(w,"Select CALENDAR file")[0]
        #Check Files actually exist - will be an issue in case of cancellation first time in
        msg_text = ''
        if not os.path.exists(s): msg_text = 'SCHEDULE file ' + s + ' does not exist.'
        if not os.path.exists(s): msg_text = 'JOBS file ' + j + ' does not exist.'
        if not os.path.exists(cal): msg_text = 'CALENDAR file ' + cal + ' does not exist.'
        if msg_text != '': #ie. no file chosen in one of the 3 cases
            msg = QMessageBox()
            msg.setWindowIcon(QIcon(self._icon))
            msg.setWindowTitle('Maestro')
            msg.setText(msg_text)
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec()
            return
        #Store values for later use if we got valid file names
        conn = sqlite3.connect(self._sqlite_ini_name)
        c = conn.cursor()
        c.execute("INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)", ('SCHEDULE', str(s)))
        c.execute("INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)", ('JOBS', str(j)))
        c.execute("INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)", ('CALENDARS', str(cal)))
        conn.commit()
        conn.close()
        self.statusbar.showMessage('Populating database........please wait.')
        self._s.read_runbook_files(self._sqlite_ini_name, self._db, self._icon)#Read in schedule and job files to pop. schedule object.
        self.statusbar.showMessage('Database population complete.',1000)
        self.popSchedsCombo()
        self.comboBoxSched.activateWindow()

    def setDotLoc(self):
        """Allow selection of the dot executable location on the windows workstation. This
        must have been installed first. Displays  file dialog to allow selection of file.
        The full paths are serialised in a pickle file so that they are available for
        future runs of the program, until next changed.
        File specification is performed via the File menu on the gui.
        """
        w = QWidget()
        dotLoc = QFileDialog.getOpenFileName(w,"SELECT DOT EXECUTABLE FILE")[0]
        if dotLoc != "":  #Allow cancellation and retain current value
            # Store values for later use
            conn = sqlite3.connect(self._sqlite_ini_name)
            c = conn.cursor()
            c.execute("INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)", ('DOT', str(dotLoc)))
            conn.commit()
            conn.close()
        return dotLoc

    def fileInfo(self):
        """Output a message box with the fully qualified paths and names of the  current
        Maestro schedule and job files that are selected"""
        files = {}
        conn = sqlite3.connect(self._sqlite_ini_name)         # Settings database
        c = conn.cursor()
        c.execute("SELECT DISTINCT VALUE FROM SETTINGS WHERE KEY ='DOT'")
        files['DOT'] = c.fetchone()[0]
        c.execute("SELECT DISTINCT VALUE FROM SETTINGS WHERE KEY ='SCHEDULE'")
        files['SCHEDULE'] = c.fetchone()[0]
        c.execute("SELECT DISTINCT VALUE FROM SETTINGS WHERE KEY ='JOBS'")
        files['JOBS'] = c.fetchone()[0]
        c.execute("SELECT DISTINCT VALUE FROM SETTINGS WHERE KEY ='CALENDARS'")
        files['CALENDARS'] = c.fetchone()[0]
        msg = QMessageBox()
        msg.setWindowIcon(QIcon(self._icon))
        msg.setWindowTitle('Maestro')
        msg.setText("File Locations........")
        txtList = []
        try:
            for k, v in files.items(): txtList.append(k + ": " + v + "\n")
            txt = "\n".join(txtList)
        except AttributeError: txt = "No initialisations yet performed"
        msg.setInformativeText(txt)
        msg.setIcon(QMessageBox.Information)
        msg.exec()

    def popSchedsCombo(self):
        """ Populate the schedule combo box with all schedule names sorted alphabetically """
        display = [k for k in self._s.getAllSchedIds(self._db)]
        display.sort()
        self.comboBoxSched.addItems(display)

    def handleBGChange(self):
        txt = self.comboBoxSched.currentText()
        if self.comboBoxSched.findText(txt) != -1:
            self.tablePopulate(self.comboBoxSched.findText(txt))

    def findIndex (self, txt):
        if self.comboBoxSched.findText(txt) != -1:
            self.tablePopulate(self.comboBoxSched.findText(txt))

    def tablePopulate(self, index):
        """
        Populate table view depending on selected schedule and Radio button selections
        """
        name = self.comboBoxSched.itemText(index)
        try:
            self.scheduleNameLabel.setText(self._s.getSchedName(name, self._db))
            self.statusbar.showMessage('')
        except KeyError:
            self.statusbar.showMessage('Schedule ' + name + ' does not exist.')
            return
        if self.radioButtonJobs.isChecked(): self.populateJobs(name)
        elif self.radioButtonPrecedes.isChecked(): self.populatePrecScheds(name)
        else: self.populateFollowingScheds(name)

    def populateJobs(self,schedNm):
        """Populate jobs from selected schedule"""
        jobs = self._s.getScheduleJobs(schedNm, self._db)
        jobDetails = [(j,self._s.getJobName(j, self._db),self._s.getJobScript(j, self._db)) for j in jobs]
        tModel = JobTableModel(jobDetails,self) #Instantiate this project's table model class with data
        self.tableView.setModel(tModel) # Set the table model of the table view Component on the main Ui
        self.tableView.resizeColumnsToContents()

    def populatePrecScheds(self,schedNm):
        """Populate future schedules from selected schedule"""
        prec = self._s.getFollowingSchedules(schedNm, self._db)
        preceding = [(sch,self._s.getSchedName(sch, self._db)) for sch in prec ]
        tModel = ScheduleTableModel(preceding,self) #Instantiate this project's table model class with data
        self.tableView.setModel(tModel) # Set the table model of the table view Component on the main Ui
        self.tableView.resizeColumnsToContents()

    def populateFollowingScheds(self, schedNm):
        """Populate previous schedules from selected schedule"""
        prev = self._s.getPreviousSchedules(schedNm, self._db)
        preceding = [(sch,self._s.getSchedName(sch, self._db)) for sch in prev ]
        tModel = ScheduleTableModel(preceding,self) #Instantiate this project's table model class with data
        self.tableView.setModel(tModel) # Set the table model of the table view Component on the main Ui
        self.tableView.resizeColumnsToContents()

    def showFullSchedule(self,qComboBox):
        """
        Method to pop up a dialog and display a list of full text of schedule
        """
        text = self._s.getFullSchedule(self.comboBoxSched.currentText(), self._db)
        tDisplay = TextDisplay(self,text)

    def showFullCalendar(self):
        """
        Method to pop up a dialog and display a list of all calendars
        """
        text = self._s.get_calendars(self._db)
        cDisplay = TextDisplay(self,text)

    def show_ctrl_file_deps(self):
        """
        Method to display a picture of all schedules depending on a control file.
        """
        ctl_file_list = self._s.getControlFiles(self._db)
        msg = QInputDialog()
        msg.setWindowIcon(QIcon('Monitor_Screen_32xSM.png'))
        msg.setWindowTitle('Chooser')
        msg.setLabelText('Choose a control file')
        msg.setComboBoxItems(ctl_file_list)
        ok = msg.exec()
        if ok == 0: return # Cancel pressed
        ctl_file = msg.textValue()
        out_list = self._s.getControlFileDependentScheds(self._db, ctl_file)
        self.draw(out_list)
        return

    def show_resource_deps(self):
        """
        Method to display a picture of all schedules depending on a resource.
        """
        resource_list = self._s.get_resources(self._db)
        msg = QInputDialog()
        msg.setWindowIcon(QIcon('Monitor_Screen_32xSM.png'))
        msg.setWindowTitle('Chooser')
        msg.setLabelText('Choose a resource file')
        msg.setComboBoxItems(resource_list)
        ok = msg.exec()
        if ok == 0: return  # Cancel pressed
        needs = msg.textValue()
        out_list = self._s.get_resource_dependent_scheds(self._db, needs)
        self.draw(out_list)
        return

    def tableClicked(self, tView):
        """
        If column 0 of table is clicked take the job or schedule identifier and do something useful with it
        """
        modelIndex = tView.selectionModel().selectedIndexes()
        for index in modelIndex:
            if index.column() == 0: # We selected the first column which contains identifiers
                selection = index.data()
                if self.radioButtonJobs.isChecked():
                    text = self._s.getFullJob(selection, self._db)
                    tDisplay = TextDisplay(self,text) # Pop up dialog with full job
                else:  # Change selected schedule to the one clicked
                    self.comboBoxSched.setCurrentText(selection)

    def exportDirectConnections(self):
        msg = QMessageBox()
        msg.setWindowIcon(QIcon(self._icon))
        msg.setWindowTitle('Maestro')
        msg.setText("Show control files and resources needed?")
        msg.setIcon(QMessageBox.Question)
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg.setDefaultButton(QMessageBox.Yes)
        rc = msg.exec()
        if rc == QMessageBox.Yes: showFileDeps = True
        else : showFileDeps = False

        self.draw(self._s.getGraphvizPart(self.comboBoxSched.currentText(), showFileDeps, self._db))

    def exportFullConnections(self):
        msg = QMessageBox()
        msg.setWindowIcon(QIcon(self._icon))
        msg.setWindowTitle('Maestro')
        msg.setText("Show control files  and resources needed?")
        msg.setIcon(QMessageBox.Question)
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg.setDefaultButton(QMessageBox.Yes)
        rc = msg.exec()
        if rc == QMessageBox.Yes: showFileDeps = True
        else : showFileDeps = False

        self.draw(self._s.getAllConnected(self.comboBoxSched.currentText(), showFileDeps, self._db))

    def draw(self, dependencies):
        """
        Starting from current schedule output all succeeding and preceeding schedules
        recursively in Graphviz format. Run Graphviz to create an svg file picture
        """
        f = open(self._graphvizTxtFile, 'w')
        data = []
        for line in dependencies:
            f.write(line+'\n')
            data.append(line+'\n')
        f.close()
        conn = sqlite3.connect(self._sqlite_ini_name)
        c = conn.cursor()
        # Settings database
        c.execute("SELECT DISTINCT VALUE FROM SETTINGS WHERE KEY ='DOT'")
        returnObject = c.fetchone()
        #Handle invalid values by asking user to choos correct location
        if returnObject: #i.e. we got something back
            dotLoc = returnObject[0]
        else : dotLoc = self.setDotLoc()
        if dotLoc == '': dotLoc = self.setDotLoc()
        #Invoke dot.exe
        try:
            subprocess.call([dotLoc,'-Tsvg', self._graphvizTxtFile, '-o',
                         self._graphvizSvgFile], stderr = None, shell=False)
            subprocess.check_call([dotLoc,'-Tsvg', self._graphvizTxtFile, '-o',
                         self._graphvizSvgFile],stderr = None, shell=False)
            #TODO Proper user friendly error handling DELETE
        except (subprocess.CalledProcessError) as e:
            print ("CalledProcessError error Handling.......")
            print("Returncode {0} command {1} output {2}".format(e.returncode, e.cmd, e.output))
        except OSError as e:
            print ("OSError error Handling.......")
            print("Returncode = {0} meaning '{1}' file = {2}".format(e.errno, e.strerror, e.filename))
            msg = QMessageBox()
            msg.setWindowIcon(QIcon(self._icon))
            msg.setWindowTitle('Maestro')
            msg.setText("Error")
            msg.setIcon(QMessageBox.Critical)
            msg.setInformativeText("Please check dot file location is correctly specified. New map cannot be drawn.")
            msg.exec()
        except ValueError as e:
            print ("ValueError error Handling.......")
        #File to be read for display has been placed above in current working directory
        #Must pass fully qualified filename of graphviz svg file
        SVGDisplay(self,self._graphvizSvgFile, self._s, self._db)

    def findText(self):
        """
        Retrieve text entered from search text bar on screen and look for it
        across jobs and schedules. Output results to a popup window.
        """
        results = self._s.findtext(self.lineEditFind.text(), self._db)
        tDisplay = TextDisplay(self,results)
Ejemplo n.º 48
0
 def __init__(self):
     self.classSchedule = Schedule()
Ejemplo n.º 49
0
# history.readCourses(".\\TimeSchedules\\2015-02-Winter-CSS.tsv", 2015, "winter")
# history.readCourses(".\\TimeSchedules\\2015-03-Spring-CSS.tsv", 2015, "spring")

"""
This function updates the static set 10% yearly increase of enrollment to the average increase of all historic data
"""


# print out enrollment history values for each year
simStart = 2015
simiterations = 5
simYears = []
for i in range(simStart, simStart+simiterations+1):
    simYears.append(i)
# Create the given schedule to fill
givenSchedule = Schedule()

"""
Import of schedule to begin simulation
"""
importCourses = dataImport.importCourses()
for course in importCourses:
    givenSchedule.addCourse(course, course.quarter)
givenSchedule.sortQuarters()
importProfessors = dataImport.importFaculty()
scheduler = Scheduler(givenSchedule, importProfessors, history)


for simYear in simYears:
    print "****===================" + str(simYear) + "===================****"
    history.updateAnnualIncrease()
Ejemplo n.º 50
0
class Window(QtGui.QDialog):
    ''' '''
    def __init__(self):
        super(Window, self).__init__()
        self.INTERVAL = 300000  # update interval in milliseconds

        # Container lists for shift widgets and timeslots.
        self.shiftWidgets = []
        self.timeslotObjects = {}

        self.viewport = Viewport(self)
        self.scrollArea = ScrollArea(self.viewport)
        self.progressbar = Progressbar(self)

        # Regex for grabbing room names from shift summaries.
        self.pattern = re.compile("(\D*) \d*")

        # Initialize a schedule object and related timeslot objects.
        self.getSchedule()
        self.getTimeslots()

        # Create a QThread object for the webscrape.
        self.worker = Worker(self.timeslotObjects)

        # Connect QThread objects signals.
        self.worker.started.connect(self.starting)
        self.worker.finished.connect(self.finished)
        self.worker.signal.connect(self.updateDisplay)

        self.worker.start()

        self.timeslotTimer()

        self.mainLayout()

        self.createActions()
        self.createTrayIcon()

        self.setIcon()
        self.trayIcon.show()

        self.setWindowTitle("RoomWhen")
        self.setFixedHeight(500)

    def starting(self):
        self.progressbar.show()
        print("Starting thread!")

    def finished(self):
        self.progressbar.hide()
        print("Finished thread!")

    def updateDisplay(self, data):
        ''' If first run create widgets and layout, else update widgets
        information. '''
        if data:
            self.createShiftWidgets()
        else:
            self.updateTimeslotStatus()

    def getSchedule(self):
        ''' Pull the current schedule, requires .icalURL file in same directory '''
        url = ''
        try:
            with open('.icalURL', 'r') as icalURL:
                url = icalURL.readline().replace('\n', '')
        except IOError:
            pass    # No pre made url file, so create dialogue for creating one.

        self.schedule = Schedule(url)
        self.schedule.events = self.schedule.sortEventsByDatetime()

    def getTimeslots(self):
        ''' Initiate timeslot objects, requires an already initialized schedule object. '''

        # Schedule.listRooms() returns a dict of room:week for us to
        # create a timeslot for each room and only fetch important weeks.
        roomList = self.schedule.listRooms()

        for room in roomList:
            self.timeslotObjects[room] = Timeslots(room, roomList[room])

    def timeslotTimer(self):
        ''' Method to start the worker thread at given interval. '''

        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.worker.start)
        self.timer.start(self.INTERVAL)

    def setIcon(self):
        ''' '''
        icon =  QtGui.QIcon('images/drink.png')
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)

        self.trayIcon.setToolTip("Placeholder")

    def mainLayout(self):
        ''' Create the main layout '''
        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.scrollArea)
        self.layout.addWidget(self.progressbar)
        self.setLayout(self.layout)

    def createShiftLayout(self):
        ''' Create a layout for a single shift. '''

        for widget in self.shiftsWidgets:
            self.viewport.layout.addWidget(widget)

    def createActions(self):
        self.minimizeAction = QtGui.QAction("Mi&nimize", self,
                triggered=self.hide)

        self.restoreAction = QtGui.QAction("&Restore", self,
                triggered=self.showNormal)

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

    def createTrayIcon(self):
        ''' '''
        self.trayIconMenu = QtGui.QMenu(self)
        self.trayIconMenu.addAction(self.minimizeAction)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addAction(self.quitAction)

        self.trayIcon = QtGui.QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)

    def showMessage(self, titel, body):
        ''' '''
        icon = QtGui.QSystemTrayIcon.MessageIcon(1)
        self.trayIcon.showMessage(
                titel,
                body,
                icon,
                5000
        )


    def createShiftWidgets(self):
        ''' Create a widget with shift information for each shift. Requires
        already initialized schedule and timeslot objects.'''

        # For each shift create QWidget and set it's layout.
        for shift in self.schedule.events:

            # Use regex to get nice room name for our widget.
            patternMatch = re.match(self.pattern, shift['summary'])
            roomNiceName = patternMatch.group(1)

            start = shift['timeStart']
            end = shift['timeEnd'] + datetime.timedelta(minutes=5)
            room = self.schedule.getRoom(shift)

            shiftWidget = ShiftWidget(
                roomNiceName,
                start.strftime("%Y-%m-%d"),
                self.timeslotObjects[room].findGames(start, end),
                room,
                start,
                end,
                parent = self.viewport
            )

            self.shiftWidgets.append(shiftWidget)
            self.viewport.layout.addWidget(shiftWidget)

    def updateTimeslotStatus(self):
        ''' Iterate through all widgets and update any changes. '''

        for widget in self.shiftWidgets:

            # Query timeslot for given widget room, about all games during it.
            timeslots = self.timeslotObjects[widget.room].findGames(widget.start, 
                                                                    widget.end)
            for timeslot in timeslots:

                # Check if there has been any change
                if timeslot['Status'] != widget.statuses[timeslot['Timestamp']].text():

                    # Compose notification message.
                    titel = widget.titel + ' ' + widget.date + " status changed"
                    body = "The " +  widget.titel + " at the " +  widget.date + \
                           " had it's status change from " + \
                           widget.statuses[timeslot['Timestamp']].text() + \
                           " to " + timeslot['Status']

                    self.showMessage(titel, body)

                    # Update widget with the change.
                    widget.statuses[timeslot['Timestamp']].setText(timeslot['Status'])

                else:
                    pass