コード例 #1
0
def getGradesByStudentId(student_id):
    sch = schedule.getSchedule()
    sch = [s for s in sch]
    ret = []
    tab = getTable(TABLE_NAME)
    for s in sch:
        g = tab.find_one(
            {
                'grade_list.student_id': str(student_id),
                'class_id': s['class_id'],
                'date.week': s['date']['week'],
                'date.cod': s['date']['cod'],
                'date.dow': s['date']['dow'],
                'teacher': s['teacher']
            }, {'grade_list.$': 1})
        if g:
            grade = g['grade_list'][0]['grade']
            teacher_name = teacher.getTeacherById(s['teacher'])['name']
            ret.append({
                'date': s['date'],
                'teacher': teacher_name,
                'content': (s['content'] if ('content' in s) else ''),
                'grade': grade
            })
    return ret
コード例 #2
0
def sch(bot, update, args):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    day = "завтра"
    if len(args) == 1:
        day = args[0].lower()
    update.message.reply_text(schedule.getSchedule(day))
コード例 #3
0
ファイル: boxscore.py プロジェクト: Ziwei-Wei/nba-datamining
def recordBoxscore(year, month, path="../data/boxscore"):
    schedule_table = schedule.getSchedule(year, month)
    schedule_header = schedule.getHeader(year)
    schedule_table.columns = schedule_header
    for _, row in schedule_table.iterrows():
        if row["Date"] == "Playoffs":
            return False
        dateTokens = row["Date"].replace(
            ' ', '_').replace(',', '').split("_")
        date = dateTokens[3] + "_" + \
            dateDict[dateTokens[1]] + "_" + dateTokens[2]
        home = teamDict[row["Home/Neutral"]]
        away = teamDict[row["Visitor/Neutral"]]
        url = row["box_score_text"]
        print("Process " + home + " vs " + away)
        boxscore_home, boxscore_away = getBoxscoreByUrl(url, home, away)
        print("Processed " + home + " vs " + away)
        if not os.path.exists(path):
            os.mkdir(path)
        save(boxscore_home, "csv", path +
             "/boxscore_{}_{}_{}_home.csv".format(date, home, away))
        save(boxscore_away, "csv", path +
             "/boxscore_{}_{}_{}_away.csv".format(date, home, away))
        print("Saved " + home + " vs " + away)
    return True
コード例 #4
0
def getHybrid(group="пр1-15", day="завтра"):
    zamen = replacements.findChange(group, day).replace(u'\xa0',
                                                        '').split('\n')
    rsps = schedule.getSchedule(day).replace(u'\xa0', '').replace(
        u'\ufeff', '').replace(u'\r', '').split('\n')
    if zamen[0] == "Расписание не готово.":
        return zamen[0]
    elif zamen[0] == "Что-то не так. Проверьте замены вручную.":
        return zamen[0]
    elif zamen[0] == "Нет замен.":
        return schedule.getSchedule(day)
    elif zamen[0] == "Сервер недоступен.":
        return zamen[0]
    if rsps[0] == "Пятница":
        if replacements.getStar("tomorrow") == 1:
            del rsps[3]
        else:
            del rsps[2]
    last = ""
    zm = 0
    fr = True
    for i in range(0, len(rsps) - 1):
        for j in range(1 + zm, len(zamen)):
            if zamen[j][0:6] == rsps[i][0:6]:
                if fr == True:
                    rsps[i] = zamen[j]
                else:
                    rsps[i] += "\n" + zamen[j]
                zm += 1
                fr = False
        rsps[i] += "\n"
        fr = True
    if len(zamen) - zm != 2:
        for i in range(1 + zm, len(zamen) - 1):
            rsps.append(zamen[i] + "\n")
    ans = ''.join(rsps).rstrip('\n')
    return ans
コード例 #5
0
def findCommand(lastUpdate):
    lastTime = int(getTime(lastUpdate))
    command = getText(lastUpdate)
    chatId = getChatId(lastUpdate)

    if (command == '/schedule'):
        return getSchedule(chatId, lastTime)
    elif (command == '/start'):
        return sendStart(chatId)
    elif (command == '/help'):
        return sendHelp(chatId)
    elif (command == '/timelesson'):
        return sendTimeLesson(chatId, lastTime)
    else:
        return sendMess(chatId,
                        'Неверная команда. Воспользуйтесь командой /help')
コード例 #6
0
def showEmployeeGantt(wl=[], ws=[]):

    global start_date, end_date

    # if do not receive a list of tasks, load example from json
    if len(wl) == 0:
        wl = jm.loadJSON_tasks()  #load list of tasks from JSON

    if len(ws) == 0:
        work_shift = jm.loadJSON_employee_ws(
        )  #load list of work shifts from JSON

    #initialize global variables
    start_date = ''
    end_date = ''
    gantt = []
    list_tasks = []
    full_schedule = []

    # aggregate tasks by employee
    for task in wl['workload']:
        idx = -1
        i = 0

        while i < len(list_tasks):
            if (list_tasks[i]['employee'] == task['employee']):
                idx = i
            i += 1

        if (idx < 0):
            list_tasks.append({'employee': task['employee'], 'schedule': []})
            list_tasks[-1]['schedule'].append({
                'start': task['start'],
                'end': task['end']
            })
        else:
            list_tasks[idx]['schedule'].append({
                'start': task['start'],
                'end': task['end']
            })

    # order each list of tasks by start date
    for i in list_tasks:
        i['schedule'].sort(key=schedule.sortingRule)

    # identifies the first and last date at all
    for i in list_tasks:
        if (start_date == '' or i['schedule'][0]['start'] < start_date):
            start_date = i['schedule'][0]['start']
        if (end_date == '' or i['schedule'][-1]['end'] > end_date):
            end_date = i['schedule'][-1]['end']

    start_date = start_date[:11] + "00:00"
    end_date = end_date[:11] + "23:59"

    # get full schedule (with busy, idle and unavailable time)
    for i in list_tasks:
        full_schedule.append({
            'employee':
            i['employee'],
            'schedule':
            schedule.getSchedule(i['schedule'],
                                 schedule.getEmployeeWorkShift(i['employee']),
                                 start_date, end_date)
        })

    # add the whole schedule into the gantt chart
    for emp in full_schedule:
        for sc in emp['schedule']:
            for appt in sc['list']:
                day = sc['day'].strftime('%Y-%m-%d') + " "
                new = dict(Task=emp['employee'],
                           Start=(day + appt['start']),
                           Finish=(day + appt['end']),
                           Resource=appt['type'])
                gantt.append(new)

    colors = {
        'busy': 'rgb(30,144,255)',
        'overtime': 'rgb(230,90,90)',
        'idle': 'rgb(171,219,123)',
        'unavailable': 'rgb(205,205,205)'
    }

    # shows the gantt chart on screen
    fig = ff.create_gantt(gantt,
                          colors=colors,
                          index_col='Resource',
                          show_colorbar=True,
                          group_tasks=True)

    # plot figure
    fig.show()
コード例 #7
0
import pastStats
import schedule
import dataFunctions

from datetime import datetime
import dateutil
from dateutil.parser import parse
from pprint import pprint
import time
import pdb


scheduleOutput = schedule.getSchedule()
try:
    teamStats = dataFunctions.importLocalJSON('teamStats.txt')
except:
    teamStats = {'league': {}}


averages1 = ['RYA', 'RTDA', 'PYA', 'PTDA', 'GrossYA']
# teamFields['averages'].update(averages)


def loopGames():
    for game in scheduleOutput['fullgameschedule']['gameentry']:
        while True:
            try:
                homeTeam = game['homeTeam']['Abbreviation']
                awayTeam = game['awayTeam']['Abbreviation']
                date = game['date'].replace('-', '')
                dateDT = dateutil.parser.parse(date)
コード例 #8
0
    def calcFitness(self):
        '''Check constraints and update the fitness value'''
        
        # reset fitness value
        self.fitness = 0

        # check hard constraints, the ones that invalidate the chromosome
        self.checkHardConstraints()

        # continue checking the soft constraints only if passed through hard constraints
        if (self.fitness < 0):
            return

        # if consider Employee Wage to calc fitness
        if (config.useEmployeeWage == True):
            # the soft constraints below are used to calculate the fitness of the solution
            employees = []
            jobs = []
            
            # aggregate them by employee
            count = 0
            for task in self.task_list:

                idx = search(employees, task['employee'])
                if idx < 0:
                    employees.append( task['employee'] )
                    jobs.append( [ {'start': task['start'],
                                    'end': task['end'] } ] )
                else:
                    jobs[idx].append( {'start': task['start'],
                                    'end': task['end'] } )

                count += 1

            # calculate the overtime cost
            overtime_cost = 0
            emp = 0
            while emp < (len(employees)):
                sum_overtime = 0

                list_tasks = jobs[emp]
                list_ws = schedule.getEmployeeWorkShift(employees[emp])
                start_date = self.pop.start_date.strftime("%Y-%m-%d %H:%M")
                end_date = self.pop.end_date.strftime("%Y-%m-%d %H:%M")

                emp_schedule = schedule.getSchedule( list_tasks, list_ws, start_date, end_date)

                for day in emp_schedule:
                    for period in day['list']:
                        if (period['type'] == 'overtime'):
                            p1 = period['start']
                            p2 = period['end']
                            tdelta = datetime.strptime(p2, '%H:%M') - datetime.strptime(p1, '%H:%M')
                            sum_overtime += tdelta.seconds / 60 # in minutes

                
                hourly_wage = getEmployeeHourlyWage( self, employees[emp] )
                overtime_cost += hourly_wage * (sum_overtime / 60) # in hours

                emp += 1

            self.employeeCost = overtime_cost

            
        # if consider Equipment Cost to calc fitness
        if (config.useEquipmentCost == True):

            equipments = []
            jobs = []

            # aggregate them by equpiment
            count = 0
            for task in self.task_list:

                idx = search(equipments, task['equipment'])
                if idx < 0:
                    equipments.append( task['equipment'] )
                    jobs.append( [ {'start': task['start'],
                                    'end': task['end'] } ] )
                else:
                    jobs[idx].append( {'start': task['start'],
                                    'end': task['end'] } )

                count += 1

            # calculate the stopped equipment cost
            overtime_cost = 0
            eqp = 0
            while eqp < (len(equipments)):
                sum_overtime = 0

                list_tasks = jobs[eqp]
                list_ws = schedule.getEquipmentWorkShift(equipments[eqp])
                start_date = self.pop.start_date.strftime("%Y-%m-%d %H:%M")
                end_date = self.pop.end_date.strftime("%Y-%m-%d %H:%M")

                eqp_schedule = schedule.getSchedule( list_tasks, list_ws, start_date, end_date)

                for day in eqp_schedule:
                    for period in day['list']:
                        if (period['type'] == 'busy'):
                            p1 = period['start']
                            p2 = period['end']
                            tdelta = datetime.strptime(p2, '%H:%M') - datetime.strptime(p1, '%H:%M')
                            sum_overtime += tdelta.seconds / 60 # in minutes

                
                hourly_wage = getEquipmentHourlyCost( self, equipments[eqp] )
                overtime_cost += hourly_wage * (sum_overtime / 60) # in hours

                eqp += 1

            self.equipmentCost = overtime_cost


        # calculate the final fitness value
        self.fitness = round( self.employeeCost + self.equipmentCost, 2)