コード例 #1
0
    def print_outputs(self, output1, output2, ret):
        printed_output = False
        code1 = relative_path(self.code1)
        code2 = relative_path(self.code2)
        if (len(output1.split('\n')) < 30 and len(output2.split('\n')) < 30):
            table_data = [['#', code1, code2]]
            output1 = output1.split('\n')
            output2 = output2.split('\n')
            l1 = len(output1)
            l2 = len(output2)
            for i in range(max(l1, l2)):
                o1, o2 = '', ''
                if i < l1: o1 = output1[i]
                if i < l2: o2 = output2[i]
                table_data.append([str(i + 1), o1, o2])

            print(Tabular(table_data))
            printed_output = True

        if (not printed_output):
            # Only print the bad line
            if (len(output1.split('\n')) > ret
                    and len(output2.split('\n')) > ret):
                table_data = [[self.code1, self.code2],
                              [
                                  output1.split('\n')[ret - 1],
                                  output2.split('\n')[ret - 1]
                              ]]
                print(Tabular(table_data))
コード例 #2
0
    def get_teachers(matrix):
        '''
        input should be a Tabular object, or a path
        '''
        if type(matrix) is str:
            Verifier.verify_teachers_list(matrix)
            temp = Tabular()
            temp.load_xls(matrix,strict=True)
            matrix = temp
        ret = []
        header = matrix[0]
        cols = len(header)
        if(cols < 2):
                raise Exception('too few columns')
        matrix = matrix[1:]
        idd = 2
        for row in matrix:
            info = ""
            kwargs = dict()
            if(cols >= 3): info = row[2]
            if(cols > 3):
                i = 3
                while i < cols:
                    kwargs[header[i]] = row[i]
                    i += 1
            temp = Teacher(idd,row[0],row[1],info,**kwargs)
            ret.append(temp)
            idd += 1

        return ret
コード例 #3
0
    def dump_output(self, teachers_list, session_list, output_path):
        matrix = [["Name of Faculty Member", "Info"]]
        if debug:
            matrix[0].extend(['rank', 'total', 'res', 'credits'])  # srbdebug
        for session in session_list:
            matrix[0].append(session.name)
        matrix[0].append("Total")

        for teacher in teachers_list:
            if teacher.duties != len(teacher.alloted):
                print('broke on')
                print(teacher)
                sys.exit(1)
            teachers_row = [teacher.name, teacher.info]
            if debug:
                teachers_row.extend([
                    teacher.rank,
                    len(teacher.alloted),
                    len(teacher.alloted_res),
                    int(teacher._credits)
                ])
            for session in session_list:
                if session.name in teacher.alloted:
                    teachers_row.append(teacher.alloted[session.name])
                else:
                    teachers_row.append('-')
            teachers_row.append(len(teacher.alloted))
            matrix.append(teachers_row)

        sheet = Tabular(matrix)
        sheet.write_xls(output_path)
コード例 #4
0
ファイル: room.py プロジェクト: Spider34/Exam_scheduler
    def get_rooms(matrix):
        '''
        input should be a Tabular object, or a path
        '''
        if type(matrix) is str:
            Verifier.verify_room_list(matrix)
            temp = Tabular()
            temp.load_xls(matrix, strict=True)
            matrix = temp
        ret = []
        header = matrix[0]
        cols = len(header)
        if (cols < 2):
            raise Exception('too few columns')

        matrix = matrix[1:]
        for row in matrix:
            capacity = 0
            kwargs = dict()
            if (cols >= 3): capacity = row[2]
            if (cols > 3):
                i = 3
                while i < cols:
                    kwargs[header[i]] = row[i]
                    i += 1
            temp = Room(row[0], row[1], capacity, **kwargs)
            ret.append(temp)

        return ret
コード例 #5
0
 def __str__(self):
     a = [[self.name]]
     a[0].append(self.unfilled)
     for room in self.room_list:
         a[0].append(room.name + ' ' +
                     str(room.teachers - len(room.teachers_alloted)))
     a = Tabular(a)
     return a.__str__()
コード例 #6
0
 def _read(file_path):
     matrix = Tabular()
     try:
         matrix.load_xls(file_path,strict=True)
     except:
         print('unable to read file : ',file_path)
         raise
         sys.exit(1)
     return matrix
コード例 #7
0
    def __init__(self, filepath):
        matrix = Tabular()
        matrix.load_xls(filepath, strict=True)
        matrix = matrix.matrix[1:]
        self.ratio = {}
        self.credits = {0: 999999}
        for x in matrix:
            self.ratio[int(x[0])] = float(x[1])

        if not 1 in self.ratio: self.ratio[1] = 100
        for x in matrix:
            self.credits[int(x[0])] = self._credits_calc(int(x[0]))
コード例 #8
0
    def __str__(self):
        a = [
                ["name",self.name],
                ["teachers-required",self.teachers],
                ["capacity",self.capacity],
                ["teachers-alloted"," ".join([teacher.name for teacher in self.teachers_alloted])]
            ]
        for key in self.extra:
            a.append([key,getattr(self,key)])

        a = Tabular(a)
        return a.__str__()
コード例 #9
0
 def __str__(self):
     table = [
         ['Roll num', self.roll_num],
         ['Name', self.name],
         ['Points', self.points],
         ['Cgpa', self.cgpa],
         ['Sgpa', self.sgpa],
         ['Branch', self.branch],
         ['Rank', self.rank],
         ['Gender', self.gender],
         ['Gender rank', self.rank],
     ]
     table = Tabular(table)
     return table.__str__()
コード例 #10
0
    def upcoming_contest(display=False):
        url = "http://codeforces.com/contests"
        soup = Soup.get_soup(url)

        contests = [['id', 'title', '', 'time', 'dur.', 'link']]
        if (soup is None):
            Colour.print('unable to fetch upcoming contests list', Colour.RED)
            return contests

        datatable = soup.find_all(
            'div', {'class': 'datatable'})[0].find_all('table')[0]
        contest_rows = datatable.find_all('tr')[1:]
        for row in contest_rows:
            c_name = row['data-contestid']
            c_type = 'contests'
            data = row.find_all('td')
            title = data[0].get_text().strip()
            title = Contest.get_short_contest_title(title)
            title = utils.shrink(title)
            writer = data[1].get_text().strip()
            time = data[2].get_text().strip()
            time = Contest.get_formatted_time(time)
            duration = data[3].get_text().strip()
            link = "www.codeforces.com/" + c_type + "/" + c_name
            contests.append([c_name, title, writer, time, duration, link])

        if (display is True): print(Tabular(contests))
        return contests
コード例 #11
0
    def __str__(self):
        a = [
                ["id",self.idd],
                ["name",self.name],
                ["rank",self.rank],
                ["info",self.info],
                ["duties",self.duties],
                ["alloted_res","\n".join([str(x) for x in self.alloted_res])],
                ["alloted","\n".join([str((x,self.alloted[x])) for x in self.alloted])],
            ]
        if debug: a.append(["credits",self._credits])
        for key in self.extra:
            a.append([key,getattr(self,key)])

        a = Tabular(a)
        return a.__str__()
コード例 #12
0
    def get_teachers(matrix):
        '''
        input should be a Tabular object, or a path
        '''
        if type(matrix) is str:
            matrix = Tabular(matrix)
        ret = []
        header = matrix[0]
        cols = len(header)
        if (cols < 2):
            raise Exception('too few columns')
        matrix = matrix[1:]
        idd = 2
        for row in matrix:
            dept = ""
            desg = ""
            kwargs = dict()
            if (cols >= 3): dept = row[2]
            if (cols >= 4): desg = row[3]
            if (cols > 4):
                i = 4
                while i < cols:
                    kwargs[header[i]] = row[i]
                    i += 1
            temp = Teacher(idd, row[0], row[1], dept, desg, **kwargs)
            ret.append(temp)
            idd += 1

        return ret
コード例 #13
0
    def display_problem(self):
        if(not self.is_good):
            table_data = [[Colour.FULLRED+Colour.BOLD+'WARNING:'+Colour.END+Colour.RED+' Problem incomplete'+Colour.END]]
            print(Tabular(table_data))

        table_data = [[Colour.PURPLE+self.p_title+Colour.END],[self.time_limit]]
        print(Tabular(table_data))

        table_data = [[Colour.CYAN+'Description'+Colour.END],[utils.shrink(self.p_desc,80,[32])]]
        print(Tabular(table_data))
        table_data = [[Colour.CYAN+'Input'+Colour.END],[utils.shrink(self.i_desc,80,[32])]]
        print(Tabular(table_data))
        table_data = [[Colour.CYAN+'Output'+Colour.END],[utils.shrink(self.o_desc,80,[32])]]
        print(Tabular(table_data))

        table_data = [[Colour.CYAN+'Examples'+Colour.END]]
        print(Tabular(table_data))

        printer = [['#','input','output']]
        for i in range(len(self.inputs)):
            inp = self.inputs[i]
            out = self.outputs[i]
            printer.append([i+1,inp,out])

        tt = texttable.Texttable()
        tt.add_rows(printer)
        print(tt.draw())

        table_data = [[Colour.CYAN+'Hint'+Colour.END],[utils.shrink(self.h_desc,80,[32])]]
        print(Tabular(table_data))
コード例 #14
0
    def get_sessions(matrix, room_data):
        '''
        input matrix should be a Tabular object, or a path
        room_data should be a tabular object or a path
        '''
        if type(matrix) is str:
            Verifier.verify_schedule_list(matrix)
            temp = Tabular()
            temp.load_xls(matrix, strict=True)
            matrix = temp
        if type(room_data) is str:
            room_data = Room.get_rooms(room_data)

        room_json = {}
        for room in room_data:
            room_json[room.name] = room

        ret = []
        header = matrix[0][1:]  # remove first elem from header
        cols = len(header) + 1
        if (cols < 2):
            raise Exception('too few columns')
        for i in range(1, len(matrix)):
            row = matrix[i]
            room_list = []
            for room in header:
                need = row[room]
                if need == 'y' or need == 'Y':
                    if room in room_json:
                        room_list.append(room_json[room].copy())
                    else:
                        # raise Exception('Room ' +room+ ' not present in rooms file')
                        Colour.print(
                            'Room ' + room + ' not present in room list',
                            Colour.RED)
                        sys.exit()

            temp = Session(row[0], room_list)
            ret.append(temp)

        return ret
コード例 #15
0
 def display_contest(self):
     table_data = [[Colour.BOLD + Colour.GREEN + self.c_title + Colour.END]]
     print(Tabular(table_data))
     table_data = [['#', 'Name', 'submissions', 'Link']]
     prob_list = []
     for prob in self.prob_mapp.values():
         if len(prob.p_title) > 1 and prob.p_title[1] == '.':
             prob.p_title = prob.p_title[3:]
         prob_list.append(prob)
     prob_list.sort(key=lambda x: int(x.subm), reverse=True)
     for prob in prob_list:
         table_data.append(
             [prob.p_name, prob.p_title, prob.subm, prob.link])
     print(Tabular(table_data))
     table_data = [['S no', 'Announcements']]
     for a, ann in enumerate(self.announce_arr):
         table_data.append([a + 1, utils.shrink(ann, max_len=80)])
     if (len(table_data) > 1):
         print(Tabular(table_data))
     else:
         print(Tabular([['No Announcements']]))
コード例 #16
0
    def get_teachers(matrix, workratio):
        '''
        input should be a Tabular object, or a path
        workratio is WorkRatio object
        '''
        if type(matrix) is str:
            temp = Tabular()
            temp.load_xls(matrix, strict=True)
            matrix = temp
        ret = []
        header = matrix[0]
        cols = len(header)
        if (cols < 2):
            raise Exception('too few columns')
        idd = 2
        for row in matrix:
            info = ""
            kwargs = dict()
            if (cols >= 3): info = row[2]
            if (cols > 3):
                i = 3
                while i < cols:
                    kwargs[header[i]] = row[i]
                    i += 1
            temp = Teacher(idd, row[0], row[1], info, **kwargs)
            temp._credits = workratio.credits_calc(
                temp.rank) / 10  # just for initial sort
            ret.append(temp)
            idd += 1

        return ret
コード例 #17
0
ファイル: session.py プロジェクト: srbcheema1/Exam_scheduler
    def get_sessions(matrix,room_data,workratio):
        '''
        input matrix should be a Tabular object, or a path
        room_data should be a tabular object or a path
        workratio is obj of WorkRatio
        '''
        if type(matrix) is str:
            Verifier.verify_schedule_list(matrix)
            temp = Tabular()
            temp.load_xls(matrix,strict=True)
            matrix = temp
        if type(room_data) is str:
            room_data = Room.get_rooms(room_data,workratio)

        room_json = {}
        for room in room_data:
            room_json[room.name] = room

        ret = []
        header = matrix[0][1:] # remove first elem from header
        cols = len(header) + 1
        if(cols < 2):
                raise Exception('too few columns')
        for row in matrix:
            room_list = []
            for room in header:
                need = row[room]
                if need == 'y' or need == 'Y':
                    if room in room_json:
                        room_list.append(room_json[room].copy())
                    else:
                        raise Exception('Room ' +room+ ' not present in rooms file')

            if (len(room_list) > 0): # dont consider empty session
                temp = Session(row[0], room_list)
                ret.append(temp)

        return ret
コード例 #18
0
    def schedule(self, output_path=default_output_xlsx_path):
        teacher_list_for_pq = randomize(Teacher.get_teachers(
            self.teacher_list))
        pq = PriorityQueue(teacher_list_for_pq)

        teacher_list = Teacher.get_teachers(self.teacher_list)
        session_list = Session.get_sessions(self.schedule_list, self.room_list)

        for session in session_list:
            done_list = []
            for i in range(len(session.room_list)):
                for j in range(session.room_list[i].teachers):
                    teacher = pq.pop()
                    session.room_list[i].teachers_alloted.append(teacher)
                    teacher._credits += credits_calc(teacher.rank)
                    done_list.append(teacher)
                    teacher_list[teacher.idd - 2].alloted[
                        session.name] = session.room_list[i].name
            for teacher in done_list:
                pq.push(teacher)

        matrix = [["Name of Faculty Member", "Designation", "Dept"]]
        for session in session_list:
            matrix[0].append(session.name)
        matrix[0].append("Total")

        for teacher in teacher_list:
            teacher_row = [teacher.name, teacher.desg, teacher.dept]
            for session in session_list:
                if session.name in teacher.alloted:
                    teacher_row.append(teacher.alloted[session.name])
                else:
                    teacher_row.append('-')
            teacher_row.append(len(teacher.alloted))
            matrix.append(teacher_row)

        sheet = Tabular(matrix)
        sheet.write_xls(output_path)
コード例 #19
0
ファイル: Profile.py プロジェクト: ChandanSitlani/CoolKit
 def print_data(self):
     '''
     print data of user as displayed on his profile-page
     '''
     table_data = [[self.link]]
     table_data.append([self.colour + self.title + Colour.END])
     table_data.append([self.colour + self.user_name + Colour.END])
     table_data.append([
         'Contest rating: ' + self.colour + self.rating + Colour.END +
         ' (max. ' + Colour.get_colour(self.max_title) + self.max_title +
         ',' + self.max_rating + Colour.END + ')'
     ])
     table_data.append(['Friend of: ' + self.friends + ' users'])
     table_data.append(['Registered: ' + self.reg_date])
     print(Tabular(table_data))
コード例 #20
0
ファイル: session.py プロジェクト: srbcheema1/Exam_scheduler
 def __str__(self):
     a = [[self.name]]
     a[0].append('rem ' + str(self.remaining))
     a[0].append('top_pq ' + self.room_pq.top().name)
     a[0].append('top_pq_unfill ' + str(self.room_pq.top().unfilled()))
     a[0].append('top_pq_fill ' + str(self.room_pq.top().filled()))
     a[0].append('top_pq_type ' + self.room_pq.top().get_type())
     b = [[' => ']]
     for room in self.room_list:
         b[0].append(room.name + ' ' + str(room.teachers - len(room.teachers_alloted)))
     a = Tabular(a)
     b = Tabular(b)
     return a.__str__() + '\n' + b.__str__() + '\n'
コード例 #21
0
def extract_output():
    data = [[
        "Sno", "N", "Cap", "SA", "SA-time", "ACO", "ACO-time", "ACO-SA",
        "ACO-SA-time", "Kmean-SA", "Kmean-SA-time"
    ]]
    for i in range(100):
        cities = City.generate_cities()
        n = len(cities)
        cap = 10 if n <= 60 else 20
        c_ret, t_ret, h_ret = run(cities, cap, disp=False)
        tabular_ret = [i + 1, n, cap]
        for a, b in zip(c_ret, t_ret):
            tabular_ret.append(a)
            tabular_ret.append(b)
        data.append(tabular_ret)
        print(Tabular([tabular_ret]))
    tabular = Tabular(data)
    tabular.write_json('output/out.json')
    tabular.write_xls('output/data.xls')
コード例 #22
0
 def __str__(self):
     a = [[self.name]]
     for room in self.room_list:
         a[0].append(room.name)
     a = Tabular(a)
     return a.__str__()
コード例 #23
0
 def __init__(self, filename):
     '''
     belives that file is already compiled
     '''
     self.mat = Tabular()
     self.mat.load_xls(filename, strict=True)
コード例 #24
0
ファイル: main.py プロジェクト: ChandanSitlani/CoolKit
def safe_main():
    parser = Parser.create_parser()
    pars_args = parser.parse_args()
    Parser.validate_args(pars_args)

    args = {}
    first_arg = pars_args.first_arg

    if (first_arg == "init"):
        '''
        initilize a repo as coolkit repo
        creates a .coolkit folder and a config file inside it.
        automatically detects contest name from foldername
        if parent repo is initilized then creates its ditoo copy of config
            parameters override
            contest name(overrides only if detected)
        '''
        args['c_name'] = pars_args.contest
        args['c_type'] = pars_args.type
        args['p_name'] = pars_args.prob
        args['c_site'] = pars_args.site
        Args.init_repo(args, init=True)

    elif (first_arg == "set"):
        '''
        just set values to config file in nearest ancestor coolkit directory
        doesn't initilize a repo as coolkit repo if any parent repo is already initilized.
        '''
        '''
        if condition required as it may or may not be given a value
        '''
        if (pars_args.contest): args['c_name'] = pars_args.contest
        if (pars_args.type): args['c_type'] = pars_args.type
        if (pars_args.prob): args['p_name'] = pars_args.prob
        if (pars_args.site): args['c_site'] = pars_args.site
        Args.set_local_config(args)

    elif (first_arg == "run"):
        '''
        runs the given problem.
        if no prob given it will check in cache.
        if no prob in cache then it will stop
        sets up cache for next time
        '''
        if (not Args.check_init()):
            Colour.print('coolkit repo not found', Colour.YELLOW)
            Args.init_repo()

        args['inp'] = pars_args.inp  # can be none
        args['test'] = pars_args.test  # 0 means all
        args['p_name'] = pars_args.prob  # can be None

        config_data = Args.fetch_data_from_local_config()
        args['c_type'] = config_data['c_type']  # contest/gym
        args['c_name'] = config_data['c_name']  # can be None
        args['c_site'] = config_data['c_site']  # can be None

        if (not args['c_name']):
            Colour.print(
                'contest not set, please set it : `coolkit set -c <contest_num>`',
                Colour.RED)
            if (debug):
                Colour.print('repo at : ' + Args.check_init(), Colour.CYAN)
            sys.exit(1)

        if (not args['inp']):
            Colour.print('no input file provided or found in cache',
                         Colour.RED)
            sys.exit(1)

        if (not args['p_name']):
            Colour.print(
                "Prob name not provided, trying to detect from filename",
                Colour.YELLOW)
            p = get_problem_name(args['inp'].split('/')[-1])
            if (p == None):
                Colour.print("Unable to detect prob name from file name",
                             Colour.YELLOW)
                p = config_data['p_name']
            if (p == None):
                Colour.print('No cached problem name found', Colour.YELLOW)
                Colour.print('Please provide the problem name using -p option',
                             Colour.RED)
                Args.set_local_config(
                    {'inp':
                     args['inp']})  #cache up the input file for next turn
                sys.exit(1)
            args['p_name'] = p

        Args.set_local_config(args)  #cache up the args for next turn
        Args.run(args)

    elif (first_arg == "submit"):
        if (not Args.check_init()):
            Args.init_repo()

        args['inp'] = pars_args.inp  # can be None
        args['p_name'] = pars_args.prob  # can be None

        config_data = Args.fetch_data_from_local_config()
        args['c_name'] = config_data['c_name']  # can be None
        args['c_type'] = config_data['c_type']
        args['c_site'] = config_data['c_site']

        if (not args['c_name']):
            Colour.print(
                'contest not set, please set it : `coolkit set -c <contest_num>`',
                Colour.RED)
            if (debug):
                Colour.print('repo at : ' + Args.check_init(), Colour.CYAN)
            sys.exit(1)

        if (not args['inp']):
            Colour.print('no input file provided or found in cache',
                         Colour.RED)
            sys.exit(1)

        if (not args['p_name']):
            Colour.print(
                "Prob name not provided, trying to detect from filename",
                Colour.YELLOW)
            p = get_problem_name(args['inp'].split('/')[-1])
            if (p == None):
                Colour.print("Unable to detect prob name from file name",
                             Colour.YELLOW)
                Colour.print('Please provide the problem name using -p option',
                             Colour.RED)
                sys.exit(1)
            args['p_name'] = p

        config_data = Args.fetch_global_config()
        if (not config_data['user']):
            Colour.print(
                'Please configure your username using "coolkit config -u <username>"',
                Colour.YELLOW)
            config_data['user'] = input(
                'Enter your username : '******'pswd']):
            Colour.print(
                'Please configure your password using "coolkit config -p <password>"',
                Colour.YELLOW)
            config_data['pswd'] = getpass.getpass(
                'Enter your password : '******'user'] = config_data['user']
        args['pswd'] = config_data['pswd']
        args['test'] = -1
        args['force'] = pars_args.force
        args['force_stdout'] = pars_args.force_stdout

        if (pars_args.secondary):  # special case for others
            if config_data.get('secondary_user') and config_data.get(
                    'secondary_pswd'):
                args['user'] = config_data['secondary_user']
                args['pswd'] = config_data['secondary_pswd']
                if (debug):
                    Colour.print('Using secondary user, ' + args['user'],
                                 Colour.GREEN)
            else:
                Colour.print(
                    'Please configure your secondary user in config file manually',
                    Colour.YELLOW)
                sys.exit(0)
        Args.submit_it(args)

    elif (first_arg == "fetch"):
        # Args.check_init() # fetching can be done even without this if contest name given
        args['c_name'] = pars_args.contest  # can be None
        args['c_type'] = pars_args.type
        args['c_site'] = pars_args.site
        args['force'] = pars_args.force

        if (not args['c_name']):
            if (not Args.check_init()):
                Colour.print(
                    'no contest provided, either provide contest using -c or run command from a coolkit repo',
                    Colour.RED)
                sys.exit(1)
            config_data = Args.fetch_data_from_local_config()
            args['c_name'] = config_data['c_name']  # can be none
            if (not args['c_name']):
                Colour.print(
                    'contest not set, use `coolkit set -c <contest num>`, or provide contest name using -c parameter',
                    Colour.RED)
                if (debug):
                    Colour.print('repo at : ' + Args.check_init(), Colour.CYAN)
                sys.exit(1)
        Args.fetch_contest(args)

    elif (first_arg == "config"):
        config_data = Args.fetch_global_config()
        if (pars_args.user):
            config_data['user'] = pars_args.user
        else:
            user = input('Enter your user name (default: ' +
                         str(config_data.get('user')) + '): ')  # str for None
            if user != '': config_data['user'] = user
        if (pars_args.pswd):
            config_data['pswd'] = pars_args.pswd
        else:
            pswd = getpass.getpass(
                'Enter your password (press enter to not to change): ')
            if pswd != '': config_data['pswd'] = pswd

    elif (first_arg == "view"):
        second_arg = pars_args.second_arg
        config_data = Args.fetch_global_config().data

        if (second_arg == "user"):
            u_name = pars_args.u_name
            if (not u_name):
                if not config_data.get('user'):
                    Colour.print(
                        'Please provide username using flag -u/--user or configure your username',
                        Colour.YELLOW)
                    sys.exit(0)
                u_name = input('Enter username (default: ' +
                               config_data.get('user') + '): ')
                if u_name == '': u_name = config_data.get('user')
            dummy_user = Dummy_user(u_name, verbose=False)
            dummy_user.print_data()
            print(Tabular(dummy_user.contest_table))

        elif (second_arg == "contest"):
            c_name = pars_args.c_name
            if (not c_name):
                if (Args.check_init()):
                    Colour.print(
                        'contest not set, use `coolkit set -c <contest num>`',
                        Colour.YELLOW)
                c_name = input('Enter contest name : ')

            temp_contest = Contest(c_name)
            temp_contest.pull_contest()
            temp_contest.display_contest()

        elif (second_arg == "standings"):
            c_name = pars_args.c_name
            if (not c_name):
                if (Args.check_init()):
                    Colour.print(
                        'contest not set, use `coolkit set -c <contest num>`',
                        Colour.YELLOW)
                c_name = input('Enter contest name : ')

            if (not config_data['user']):
                Colour.print(
                    'Please configure your username using "coolkit config -u <username>"',
                    Colour.RED)
                config_data['user'] = input('Enter your username : '******'pswd']):
                Colour.print(
                    'Please configure your password using "coolkit config -p <password>"',
                    Colour.RED)
                config_data['pswd'] = getpass.getpass('Enter your password : '******'user'],
                                     config_data['pswd'])
            temp_Standing.show()

        elif (second_arg == "friends"):
            config_data = Args.fetch_global_config()
            if (not config_data['user']):
                Colour.print(
                    'Please configure your username using "coolkit config -u <username>"',
                    Colour.RED)
                config_data['user'] = input(
                    'Enter your username : '******'pswd']):
                Colour.print(
                    'Please configure your password using "coolkit config -p <password>"',
                    Colour.RED)
                config_data['pswd'] = getpass.getpass('Enter your password : '******'user'], config_data['pswd'])
            temp_friends.show()

        elif (second_arg == "prob"):
            if (not Args.check_init()):
                Colour.print('please run this command from a coolkit repo',
                             Colour.RED)
                sys.exit(1)
            p_name = pars_args.p_name
            c_name = Args.fetch_data_from_local_config()['c_name']
            if (not c_name):
                Colour.print(
                    'contest not set, use `coolkit set -c <contest num>`',
                    Colour.YELLOW)
                c_name = input('Enter contest name : ')
                Args.set_local_config({'c_name', c_name})
            if (not p_name):
                Colour.print(
                    'problem not set, use `coolkit set -p <problem name>`',
                    Colour.YELLOW)
                p_name = input('Enter problem name : ')
                Args.set_local_config({'p_name', p_name})

            prob = Problem(p_name, c_name)
            prob.pull_problem(force=False)
            prob.display_problem()
            Colour.print(prob.link, Colour.CYAN)

        elif (second_arg == "upcoming"):
            Contest.upcoming_contest(display=True)
コード例 #25
0
ファイル: evaluate.py プロジェクト: srbcheema1/srb_VRP
from srblib import Tabular

a = Tabular()
a.load_json('data/out.json')

summ = [0, 0, 0, 0]
mint = [0, 0, 0, 0]
time = [0, 0, 0, 0]

for row in a:
    summ[0] += row[3]
    summ[1] += row[5]
    summ[2] += row[7]
    summ[3] += row[9]

    time[0] += row[4]
    time[1] += row[6]
    time[2] += row[8]
    time[3] += row[10]

    minn = min(row[3], row[5], row[7], row[9])
    if (minn == row[3]): mint[0] += 1
    elif (minn == row[5]): mint[1] += 1
    elif (minn == row[7]): mint[2] += 1
    elif (minn == row[9]): mint[3] += 1

n = len(a) - 1
avg = [round(x / n, 2) for x in summ]
time = [round(x / n, 2) for x in time]

b = Tabular([["Prop", "SA", "ACO", "ACO-SA", "Kmean-SA"], ["avg cost"] + avg,
コード例 #26
0
ファイル: tabular_test.py プロジェクト: srbcheema1/srblib
def test_tabular():
    if(not on_travis):
        return

    a = Tabular('spike/excel.xlsx')
    print(a,a[0])
    assert(len(a) == 3)
    assert(len(a[0]) == 3)
    assert(a[0][0] == 'name')
    assert(a[1]['name'] == 'pagal')
    assert(a['name'][0] == 'pagal')
    assert(len(a['name']) == 2)
    a.write_csv('test.csv')
    a.write_json('test.json')
    a.write_xls('test.xlsx')

    # strict
    a.load_xls('spike/strict.xlsx',strict=True)
    assert(len(a) == 8)


    b = Tabular('test.xlsx')
    assert(len(b) == 3)
    assert(len(b[0]) == 3)
    assert(b[0][0] == 'name')
    assert(b[1]['name'] == 'pagal')
    assert(b['name'][0] == 'pagal')
    assert(len(b['name']) == 2)

    c = Tabular('test.csv')
    c = Tabular('test.json')
コード例 #27
0
    def dump_output(self, teachers_list, session_list, output_path):
        matrix = [["Name of Faculty Member", "Info"]]
        if debug:
            matrix[0].extend(['_rank', '_total', '_res',
                              '_credits'])  # srbdebug

        dmap = {}  # map to contain count of avg duties of some rank
        rmap = {}  # map to contain count of teachers of some rank
        for teacher in teachers_list:
            rmap[teacher.rank] = 0
            dmap[teacher.rank] = 0
        for teacher in teachers_list:
            rmap[teacher.rank] += 1
            dmap[teacher.rank] += teacher.duties

        def divide(a, b):
            a = int((a * 1000) / b)
            return a / 1000

        for rank in rmap:
            dmap[rank] = divide(dmap[rank], rmap[rank])

        tmap = {}  # map to contain count of room types
        for session in session_list:
            matrix[0].append(session.name)
            for room in session.room_list:
                if room.reserved:
                    continue
                if room.get_type() in tmap:
                    tmap[room.get_type()] += 1
                else:
                    tmap[room.get_type()] = 1

        matrix[0].append("Total")
        matrix[0].append("mail")
        same_day_duties = self._get_same_day_multiple_duties(teachers_list)
        if (same_day_duties): matrix[0].append("s_d_m_d")

        for teacher in teachers_list:
            teachers_row = [teacher.name, teacher.info]
            if teacher.duties != len(teacher.alloted) - len(
                    teacher.alloted_res):
                print(
                    'ERROR: teacher unable to get enough slots as anticipated')
                print(teacher)
                raise Exception(
                    'ERROR: teacher unable to get enough slots as anticipated')
            if debug:
                teachers_row.extend([
                    teacher.rank,
                    len(teacher.alloted),
                    len(teacher.alloted_res),
                    int(teacher._credits),
                ])
            for session in session_list:
                if session.name in teacher.alloted:
                    teachers_row.append(teacher.alloted[session.name])
                else:
                    teachers_row.append('-')
            teachers_row.append(len(teacher.alloted))
            teachers_row.append(teacher.mail)
            if (same_day_duties):
                same_day_duties_t = 0  # compute same day duties per teacher
                sess_set = set()
                for session_name in teacher.alloted.keys():
                    if Session.get_base(session_name) in sess_set:
                        same_day_duties_t += 1
                        continue
                    sess_set.add(Session.get_base(session_name))
                teachers_row.append(same_day_duties_t)
            matrix.append(teachers_row)

        lmap = json.dumps(rmap, indent=3, sort_keys=True)
        Colour.print('rank count : ', Colour.CYAN, end='')
        Colour.print(lmap, Colour.GREEN)

        lmap = json.dumps(dmap, indent=3, sort_keys=True)
        Colour.print('average duties : ', Colour.CYAN, end='')
        Colour.print(lmap, Colour.GREEN)

        lmap = json.dumps(tmap, indent=3, sort_keys=True)
        Colour.print('type of rooms : ', Colour.CYAN, end='')
        Colour.print(lmap, Colour.GREEN)

        matrix.extend([[], [], ['', 'rank', 'count', 'avg duties']])
        for key in sorted(rmap):
            matrix.append(['', key, rmap[key], dmap[key]])

        matrix.extend([[], [], ['', 'type of room', 'number']])
        for key in sorted(tmap):
            matrix.append(['', key, tmap[key]])

        if same_day_duties > 0:
            Colour.print('Got ' + str(same_day_duties) + ' same-day-duties',
                         Colour.YELLOW)
            matrix.extend(
                [[], [],
                 ['', 'WARNING:', 'Adv-algo value was ' + str(self.adv)]])
            matrix.extend(
                [['', '', 'You may get teacher duty multiple in a day']])
            matrix.extend(
                [['', '', 'We got ' + str(same_day_duties) + ' such cases']])
            matrix.extend([[
                '', '',
                'Please visit s_d_m_d(same-day-multiple-duties) column for number of such cases per teacher'
            ]])

        matrix.extend(
            [[], [],
             [
                 '', 'Help:',
                 'In case help required please visit help section on website'
             ]])
        matrix.extend([[
            '', '',
            'In case of unsatisfactory results please contact [email protected]'
        ]])
        matrix.extend([[], [], ['', '', 'a srbcheema1 Production']])

        sheet = Tabular(matrix)
        sheet.write_xls(output_path)
コード例 #28
0
 def safe(self):
     if self.exception:
         print(Tabular([[str(self)]]))
         raise self.exception
     return bool(self)
コード例 #29
0
class Output:
    def __init__(self, filename):
        '''
        belives that file is already compiled
        '''
        self.mat = Tabular()
        self.mat.load_xls(filename, strict=True)

    def json(self):
        debugcols = ['_rank', '_total', '_res', '_credits', 's_d_m_d']
        infocols = ['Info', 'Name of Faculty Member', 'Total', 'mail']
        header = []
        for col in self.mat[0]:
            if col in debugcols:
                continue
            header.append(col)

        ret_json = []
        for row in self.mat:
            teacher = dict()
            teacher['duties'] = dict()
            for head in header:
                if head in infocols:
                    teacher[head] = row[head]
                elif row[head] and row[head] != '-':
                    teacher['duties'][head] = row[head]
            ret_json.append(teacher)
        return ret_json

    def mail(self, email, password, custom_message=''):
        subject = "Alloted Duties In examination"
        header = self.mat[0]
        if not 'mail' in header:
            return 0
        sent = 0
        for teacher in self.mat:
            if teacher['mail']:
                data = [[], []]
                for i in range(0, len(header) - 1):
                    if (not teacher[i]) or teacher[i] == '-':
                        continue
                    data[0].append(header[i])
                    data[1].append(teacher[i])
                try:
                    Output.__send_email(
                        email, password, teacher['mail'],
                        Output.__makebody(data, custom_message), subject)
                    sent += 1
                except:
                    pass
        return sent

    @staticmethod
    def __makebody(data, custom_message):
        infocols = [
            'Info', 'Name of Faculty Member', 'Total', 'mail', '_rank',
            '_total', '_res', '_credits', 's_d_m_d'
        ]
        duties = ''
        for i in range(len(data[0])):
            print(data[0][i])
            if (data[0][i] in infocols):
                continue
            duties += str(data[0][i]) + ' : ' + str(data[1][i]) + '\n'
        body = mainbody.format(name=data[1][0],
                               dutiesdata=duties,
                               custom_message=custom_message)
        print(body)
        return body

    @staticmethod
    def __send_email(email, password, toaddr, body='', subject=''):
        mail = Email()
        mail.fromaddr = email
        mail.password = password
        mail.toaddr = toaddr
        mail.subject = subject
        mail.body = body
        mail.send()