def file_update(update_type='setup', changing_entries=None):
    """this should be called to ensure that the user info is populated. call with 'push' to update instead of setup
       you should pass a list of the entries that will change if you intend to push an update.
       example call: file_update('push', [1, 2]) this will update only the indices 1 and 2 so character and league
    """

    # check if userdata.txt exists and if not create it with the proper format
    if os.path.exists('userdata.txt') and update_type == 'setup':
        print('userdata.txt exists nothing further needed here')
    elif update_type == 'push':
        # the purpose of this case is to allow the function to be used as both a setup and to push updates to UserData
        # first open the file and read it into memory then replace the entries specified finally push the update
        with open('userdata.txt', 'r') as file:
            temp_file = file.readlines()
            for i, item in enumerate(User.user_data_file_structure):
                if i in changing_entries:
                    temp_file[i] = item.replace('%',
                                                user_inputted_info[i]) + '\n'
                else:
                    continue
            file.close()
        with open('userdata.txt', 'w') as file:
            file.writelines(temp_file)
            file.close()
    else:
        with open('userdata.txt', 'w') as file:
            a = 0
            for item in User.user_data_file_structure:
                file.writelines(
                    item.replace('%', user_inputted_info[a]) + '\n')
                a += 1
            file.close()
    User.load_user_data()
Example #2
0
    def __init__(self, user):
        self.__last_update_time = None
        self.__id = user.id
        self.__username = user.username

        if not UserData.check_user_exists(self.__id):
            User.logger.info("Adding new user {} with id {}".format(self.__username, self.__id))
            UserData.add_user(self.__id)
            self.__email = None
        else:
            self.__email = UserData.get_email(self.__id)
            if self.__email == "None":
                self.__email = None

        # Получаем расписание только по безопасному запросу
        self.__timetable = None
        # Время обновления в цикле обновим
        self.__last_update_time = None
        # Мы не обновляли расписание ещё и нам его нужно сейчас обновить
        self.__next_update_needed = datetime.datetime.now()

        self.commandExec = {'start': self.__print_hello,
                            'setemail': self.__set_email,
                            'getemail': self.__get_email,
                            'gettoday': self.__get_today,
                            'getleft': self.__get_left,
                            'gettmrw': self.__get_tomorrow}
def program_startup():
    """handles all the necessary checks and routines for startup"""

    global nav_menu_initiated_flag

    if nav_menu_initiated_flag == 0:
        # initialize the menu since it should always be available
        init_nav_menu()
        nav_menu_initiated_flag += 1

    # check if the userdata.txt file is found if not make the user enter all necessary data
    if os.path.exists('userdata.txt'):
        # load user data first
        User.load_user_data()
        # populate all necessary data
        InventoryParser.inventory_data_setup()
        # open the client.txt file for monitoring and tracking player
        file = open(User.client_txt_path)
        start_player_tracking(file)
        # start tracking player's inventory value. updates every 1 second
        inventory_value_updater()
        # display main screen here
        display_main_menu()
    else:
        missing_user_file = 'userdata.txt not found. complete first time setup'
        display_message_box(missing_user_file, display_user_data_entry_fields)
Example #4
0
def Handler(confd, addr):
    while True:
        logindata = confd.recv(1024).decode()
        logindata = logindata.split('#')
        # 注册
        if logindata[0] == 'signup':
            username = logindata[1]
            password = logindata[2]
            UserData.restore_info(username, password)
            msg = 'signup#success'
            confd.send(msg.encode())
        # 登录
        elif logindata[0] == 'signin':
            username = logindata[1]
            password = logindata[2]
            if UserData.match_info(username) == password:
                msg = 'Success'
            elif UserData.match_info(username) == '':
                msg = 'False'
            else:
                msg = 'Failed'
            confd.send(msg.encode())
        elif logindata[0] == 'quit':
            print(logindata[1], 'quited')
            break
Example #5
0
def main_program():
    logger.info("Application started")
    UserData.init()
    RUZPython.init()
    BotLogic.start()
    while True:
        BotLogic.update()
        sleep(0.5)
Example #6
0
    def __set_email(self, params):
        User.logger.info("Setting mail for {}".format(self.__username))
        if params is None or params == "":
            self.__email_help()
            return

        if User.email_re.match(params.strip()) is None:
            self.__wrong_email(params.strip())
            return
        mail = params.strip()
        UserData.set_email(self.__id, mail)
        User.bot.sendMessage(chat_id=self.__id,
                             text=User.mailChangedMessage.format(mail))
        self.__email = mail
        self.__get_timetable(force=True)
Example #7
0
    def configure(
        self, num_of_movie_need_rating=60,
        knn_sim_metric="correlation", knn_n_neighbor=10,
        df_user=None, df_app_user=None,
        df_data=None, df_ratmat=None, df_app_data=None,
        df_movie=None,df_movie_genre=None):
        """Instantiates, wire and configure all the object comprising of the system.

        Args:
            num_of_movie_need_rating: minimum amount of rating required for a user
            knn_sim_metric: KNN metric option, default: "correlation"
            knn_n_neighbor: number of K nearest users for KNN
            df_user: optional custom data set for base user
            df_app_user: optional custom data set for app user
            df_data: optional custom data set for base user rating data
            df_ratmat: optional custom data set for userxrating matrix
            df_app_data: optional custom data set for app user rating data
            df_movie: optional custom data set for movie information
            df_movie_genre: optional custom data set for movie by genre information
        """
        self.num_of_movie_need_rating = num_of_movie_need_rating

        # configure model objects
        self.knn_n_neighbor = knn_n_neighbor
        knn = Knn.Knn(knn_sim_metric)
        genre = Genre.Genre()

        # configure backend data objects
        movie_data = md.MovieData(df_movie=df_movie, df_movie_genre=df_movie_genre)
        user_data = ud.UserData(df_user=df_user)
        app_user_data = ud.AppUserData(user_data, df_app_user=df_app_user)
        rating_data = rd.RatingData(df_data=df_data, df_ratmat=df_ratmat, df_app_data=df_app_data)

        # configure backend service objects
        user_service = us.UserService(user_data, app_user_data)
        movie_service = ms.MovieService(movie_data, rating_data)
        recommend_service = cs.RecommendService(rating_data, movie_data, user_data, app_user_data, knn, genre)
        rating_service = rs.RatingService(rating_data, movie_data, user_data, app_user_data)

        # app reference to backend service end points
        self.bs_movie = bs.MovieService(movie_service)
        self.bs_user = bs.UserService(user_service)
        self.bs_recommend = bs.RecommendService(recommend_service)
        self.bs_rating = bs.RatingService(rating_service)

        # configure frontend UI object and passes over backend end points
        self.fe = UI.UI(self, num_of_movie_need_rating)
        self.fe.configure(self.bs_movie, self.bs_user, self.bs_recommend, self.bs_rating)
    def main(self):
        for fold in self.walk_dir(config.POSITIVE_DIR):
            if not os.path.exists(config.TRAIN_DIR + fold):
                os.makedirs(config.TRAIN_DIR + fold)
            print "Reading training images..."
            faces = []
            labels = []
            pos_count = 0
            neg_count = 0
            count = 0
            List = UserData.UserData()
            pose_list = config.LIST_DIR + fold + '.pkl'
            folder_path = config.POSITIVE_DIR
            List.WriteList(pose_list, folder_path)
            List.ReadList(pose_list, folder_path)
            # Read all positive images
            for filename in self.walk_files(config.POSITIVE_DIR + fold,
                                            '*.pgm'):
                faces.append(self.prepare_image(filename))
                labels.append(config.POSITIVE_LABEL)
                pos_count += 1
            # Read all negative images
            for filename in self.walk_files(config.NEGATIVE_DIR, '*.pgm'):
                faces.append(self.prepare_image(filename))
                labels.append(config.NEGATIVE_LABEL)
                neg_count += 1
            print 'Read', pos_count, 'positive images and', neg_count, 'negative images.'

            # Train model
            print 'Training model...'
            model = cv2.createEigenFaceRecognizer()
            model.train(np.asarray(faces), np.asarray(labels))

            # Save model results
            trainfile = os.path.join(config.TRAIN_DIR + fold,
                                     config.TRAINING_FILE)
            model.save(trainfile)
            print 'Training data saved to', config.TRAIN_DIR + fold, config.TRAINING_FILE

            # Save mean and eignface images which summarize the face recognition model.
            meanfile = os.path.join(config.TRAIN_DIR + fold, MEAN_FILE)
            positivefile = os.path.join(config.TRAIN_DIR + fold,
                                        POSITIVE_EIGENFACE_FILE)
            negativefile = os.path.join(config.TRAIN_DIR + fold,
                                        NEGATIVE_EIGENFACE_FILE)
            mean = model.getMat("mean").reshape(faces[0].shape)
            cv2.imwrite(meanfile, self.normalize(mean, 0, 255, dtype=np.uint8))
            eigenvectors = model.getMat("eigenvectors")
            pos_eigenvector = eigenvectors[:, 0].reshape(faces[0].shape)
            cv2.imwrite(
                positivefile,
                self.normalize(pos_eigenvector, 0, 255, dtype=np.uint8))
            neg_eigenvector = eigenvectors[:, 1].reshape(faces[0].shape)
            cv2.imwrite(
                negativefile,
                self.normalize(neg_eigenvector, 0, 255, dtype=np.uint8))

            count += 1
        else:
            execfile('admin.py')
Example #9
0
    def cap_scenes():
        import hs, os.path, UserData

        _path = os.path.abspath(os.path.join(UserData.Create("cap"), 'sister'))
        if not os.path.exists(_path): os.makedirs(_path)

        hs.move_camera(pos=(0.0, 0.8, 0.0),
                       dir=(0.0, 0.0, -2.3),
                       angle=(21.9, 169.7, 0.0),
                       fov=23.0)
        # begin females
        hsfem = hs.HSFemale.create_female('[GX]Sister', attach=True)
        hsfem.load_animation('h/anim/female/00.unity3d', 'ha_f_02')
        hsfem.move(pos=(0.0, 0.1, -0.6), rot=(7.4, 3.2, 356.0))
        hsfem.chara.SetActiveTop(True)
        hsfem.chara.ChangeBlinkFlag(False)
        hsfem.chara.ChangeEyesPtn(28, True)
        hsfem.chara.ChangeMouthPtn(16, True)
        hsfem.chara.ChangeLookNeckPtn(1)
        hsfem.chara.ChangeLookEyesPtn(1)
        hsfem.set_clothes_state_all(2)
        # begin items
        item = hs.HSItem.create_item('Bathtub (Yellow)')
        item.move(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0))
        yield os.path.join(_path, 'dailybath (3).png')

        yield None
Example #10
0
 def set_history(self):
     """
     Loads history from database
     :return:
     """
     self.user_score = UserData()
     self.user_score.load_or_create_db()
     self.history = self.user_score.db
 def ReadCardID(self):
     global ID
     global camera
     global door
     global led
     User = UserData.UserData()
     ID = User.UserID()
     camera = config.get_camera()
     door = hardware.Door()
     led = hardware.Led()
Example #12
0
def play_actions(hsfem, rootname, moodmap, clothset):
    import os, time
    import hs
    import UserData, YS_Assist
    from collections import OrderedDict as od
    from UnityEngine import Time

    if hsfem == None:
        hsfem = hs.get_first_active_female()
    elif isinstance(hsfem, str):
        hsfem = create_female(hsfem)
    if not isinstance(hsfem, hs.HSFemale):
        yield None

    hsfem.reset()

    _path = os.path.abspath(os.path.join(UserData.Create("cap"), rootname))

    aplayer = None
    for cloth, clothes in clothset.iteritems():
        for k, v in clothes.iteritems():
            if k == 'clothes':
                hsfem.apply_clothes(v)
                hsfem.enable_clothes(0)
            elif k == 'state':
                hsfem.enable_clothes(v)
            elif k == 'acc':
                hsfem.enable_accessories(v)

        for mood, states in moodmap.iteritems():
            _subdir = os.path.join(_path, mood)
            if not os.path.exists(_subdir): os.makedirs(_subdir)
            fname = os.path.join(_subdir, cloth + ".png")

            # speed up time so captures dont miss
            oldTimeScale = Time.timeScale
            Time.timeScale = 5.0
            try:
                for k, v in states.iteritems():
                    if k == 'persona':
                        if not aplayer or aplayer.personality != v:
                            aplayer = hsfem.load_personality(v)
                    elif k == 'action':
                        if aplayer: aplayer.play(v)
                    elif k == 'mood':
                        hsfem.set_mood(v)
            finally:
                Time.timeScale = oldTimeScale

            yield fname

    yield None
Example #13
0
    def get_user(self, user_id):
        cursor = self.db.cursor()
        cursor.execute('SELECT id, name, creation_time FROM users WHERE id=%s',
                       [user_id])

        rows = cursor.fetchall()

        if rows and len(rows) > 0:
            user = UserData.User()
            user.id, user.name, user.creation_time = rows[0]
            return user
        else:
            return None
Example #14
0
async def stop(ctx: commands.Context):
    dm = ctx.guild is None
    if not dm:
        if ctx.guild.id not in allowed_channels:
            return
        if ctx.channel.id not in allowed_channels[ctx.guild.id]:
            return
    if ctx.author.id in users:
        user = users[ctx.author.id]
    else:
        if not dm:
            user = UserData.UserData(ctx.guild.id, ctx.channel.id)
        else:
            user = UserData.UserData(None, ctx.channel.id)
        users[ctx.author.id] = user

    if (dm and user.can_dm()) or not dm:
        user.toggle_pause()
        if user.paused():
            await ctx.send("I will stop messaging you")
        else:
            await ctx.send("I will resume messaging you")
Example #15
0
async def dmme(ctx: commands.Context):
    dm = ctx.guild is None
    if not dm:
        if ctx.guild.id not in allowed_channels:
            return
        if ctx.channel.id not in allowed_channels[ctx.guild.id]:
            return
    if ctx.author.id in users:
        user = users[ctx.author.id]
    else:
        if not dm:
            user = UserData.UserData(ctx.guild.id, ctx.channel.id)
        else:
            user = UserData.UserData(None, ctx.channel.id)
        users[ctx.author.id] = user

    if user.paused():
        await stop(ctx)

    user.toggle_dm()
    if user.can_dm():
        await ctx.send("I will now be able to send you direct messages")
    else:
        await ctx.send("I will no longer be able to send you direct messages")
Example #16
0
async def total(ctx: commands.Context):
    dm = ctx.guild is None
    if not dm:
        if ctx.guild.id not in allowed_channels:
            return
        if ctx.channel.id not in allowed_channels[ctx.guild.id]:
            return
    if ctx.author.id in users:
            user = users[ctx.author.id]
    else:
        if not dm:
            user = UserData.UserData(ctx.guild.id, ctx.channel.id)
        else:
            user = UserData.UserData(None, ctx.channel.id)
        users[ctx.author.id] = user

    if user.paused():
        await stop(ctx)

    if (dm and user.can_dm()) or not dm:
        await ctx.send("In total you've drank %i times" % user.times_drunk())
    else:
        await ctx.send("You have not enabled direct messages. Enable them with ``%sdmme`` first" % prefix)
        return
Example #17
0
async def sip(ctx: commands.Context, *time):
    dm = ctx.guild is None
    if not dm:
        if ctx.guild.id not in allowed_channels:
            return
        elif ctx.channel.id not in allowed_channels[ctx.guild.id]:
            return
    if ctx.author.id in users:
        user = users[ctx.author.id]
    else:
        if not dm:
            user = UserData.UserData(ctx.guild.id, ctx.channel.id)
        else:
            user = UserData.UserData(None, ctx.channel.id)
        users[ctx.author.id] = user
    if time.__len__() > 0:
        time = datetime_formatting.read_timedelta(list(time))
    else:
        time = user.drink_break

    if user.paused():
        await stop(ctx)

    if (dm and user.can_dm()) or not dm:
        if not dm:
            user.update_channel(ctx.guild.id, ctx.channel.id)
        else:
            user.update_channel(None, ctx.channel.id)
        user.set_break(time)
        user.drink()
        time = user.next_drink() - datetime.datetime.now()
        await ctx.send("Great! I will remind you to drink again in %s" % datetime_formatting.neat_timedelta(time))
    else:
        await ctx.send("You have not enabled direct messages. Enable them with ``%sdmme`` first" % prefix)
        return
    await remind(ctx.author.id)
Example #18
0
    def get_all_users(self):
        cursor = self.db.cursor()

        cursor.execute('SELECT id from users')

        rows = cursor.fetchall()

        result = []
        if rows and len(rows) > 0:
            for row in rows:
                user = UserData.User()
                user.id = row[0]
                user.emails = self.get_emails(user.id)

                result.append(user)
        return result
Example #19
0
    def get_emails(self, user_id):
        cursor = self.db.cursor()

        cursor.execute(
            'SELECT id, email, type, auth_data from user_emails WHERE user_id=%s',
            [user_id])

        rows = cursor.fetchall()

        result = []
        if rows and len(rows) > 0:
            for row in rows:
                email = UserData.EmailSettings()
                email.id, email.email, email.type, email.auth_data = row
                result.append(email)

        return result
Example #20
0
def parseLine(line):
    p = list(map(lambda s: s.strip().replace("\"", ""), line.split(",")))
    try:
        return UserData(int(p[0]), str(p[1]), p[2] == 'True', p[3] == 'True', int(p[4]), int(p[5]), \
            int(p[6]), int(p[7]), int(p[8]), float(p[9]), float(p[10]), float(p[11]), float(p[12]), \
            float(p[13]), float(p[14]), float(p[15]), float(p[16]), float(p[17]), float(p[18]), float(p[19]), \
            float(p[20]), float(p[21]), float(p[22]), float(p[23]), float(p[24]), float(p[25]), float(p[26]), \
            float(p[27]), float(p[28]), float(p[29]), float(p[30]), float(p[31]), float(p[32]), float(p[33]), \
            float(p[34]), float(p[35]), float(p[36]), float(p[37]), float(p[38]), float(p[39]), float(p[40]), \
            float(p[41]), float(p[42]), float(p[43]), float(p[44]), float(p[45]), float(p[46]), float(p[47]), \
            float(p[48]), float(p[49]), float(p[50]), float(p[51]), float(p[52]), float(p[53]), float(p[54]), \
            float(p[55]), float(p[56]), float(p[57]), float(p[58]), float(p[59]), float(p[60]), float(p[61]), \
            float(p[62]), float(p[63]), float(p[64]), float(p[65]), float(p[66]), float(p[67]), float(p[68]), \
            float(p[69]), float(p[70]), float(p[71]), float(p[72]), float(p[73]), float(p[74]), float(p[75]), \
            float(p[76]), float(p[77]), float(p[78]), float(p[79]), float(p[80]), float(p[81]), float(p[82]), \
            float(p[83]), float(p[84]), float(p[85]), float(p[86]), float(p[87]), float(p[88]), float(p[89]), \
            float(p[90]), float(p[91]), float(p[92]), float(p[93]), float(p[94]), float(p[95]), float(p[96]), \
            float(p[97]), float(p[98]), float(p[99]))
    except:
        return None #drop entries where float(x) returns an error (i.e. blank spaces)
Example #21
0
#Trabajo practico del Instituto Tecnologico de Buenos Aires
#Teoria de circuitos- Diseño de filtros analogicos
#Autores:
#   Matias Larroque                 Legajo:56597
#   Lucero Guadalupe Fernanadez     Legajo:57485
#   Manuel Mollon                   Legajo:58023
#   Ezequiel Vijande                Legajo:58057
#
#
#Fecha de entrega:25/10/2018
#
#
#   El siguiente programa consiste en la realizacion de una interfaz grafica que permite que un usuario ingrese
# los parametros necesarios para realizar la plantilla de un filtro analogico. La interfaz grafica permite
# la eleccion del tipo de filtro(Pasa-Bajos, Pasa-Altos, Pasa-Banda,Rechaza-Banda) asi como tambien la aproximacion
# que el usuario desea emplear(Algunas opciones son Butterworth y Chebycheff). Luego de seleccionar el tipo de filtro y
# aproximacion deseada, se deben establecer los parametros de la plantilla que se desea.

import ApGUI as ap
import UserData as u
import Manager as M

data = u.UserData()
interfaz = ap.ApGUI()
Controller = M.Manager(data, interfaz)
while ((Controller.getState()) != M.EXIT):
    interfaz.Update()
    Controller.Dispatch(interfaz.GetEvent())
Example #22
0
with open('mamem-phase2-fall17-export.json', encoding='utf-8') as data_file:

    # Load dataset into list of users
    data = json.load(data_file)

    # Go over users in data set and store participants of MAMEM
    user_data_list = []
    print('Processing of users', end='')
    for uid, user in data['users'].items():

        # Check whether user is participant
        for entry in dfn.user_filter:  # go over known participants
            if uid == entry.uid:  # uid matches
                print('.', end='')
                user_data_list.append(
                    ud.UserData(uid, entry.mid, user, entry.setup_date))

    print('finished.')

    # Sort user data list same as filter list
    sorted_user_data_list = []
    for entry in dfn.user_filter:
        for user_data in user_data_list:
            if user_data.uid == entry.uid:
                sorted_user_data_list.append(user_data)
                break
    user_data_list = sorted_user_data_list

    # Initialize report
    rp.init_file()
Example #23
0
def interface(user, obj: examSystemData.Exam):
    logger.logger.info('Entered User Interface')
    obj_user_data = UserData.UserData()
    obj_questions = QuestionAndSolutions.QuestionData(obj)
    obj_solutions = QuestionAndSolutions.SolutionData()
    permmision = 0  # 1 - C, 2 - L, 3 - C
    print('You can :')
    if user == 'Coordinator':
        print_coordinator_menu()
        logger.logger.info('Entered Coordinator User Interface')
        permmision = 1
    elif user == 'Lecturer':
        print_leturer_menu()
        logger.logger.info('Entered Lecturer User Interface')
        permmision = 2
    elif user == 'Student':
        print_student_menu()
        logger.logger.info('Entered Student User Interface')
        permmision = 3

    while True:
        choice = input()
        if choice == '1' and permmision == 1:
            logger.logger.info('Entered Main Menu')
            lecturer_first_name, lecturer_last_name = input(
                'enter lecturer first name + last name with a whitespace between : '
            ).split()
            obj_user_data.add_lecturer(lecturer_first_name, lecturer_last_name)
            logger.logger.info('Added Lecturer To User System')

        elif choice == '2' and permmision == 1:
            lecturer_first_name, lecturer_name_change = input(
                'enter lecturer first name + the change with a whitespace between : '
            ).split()
            obj_user_data.edit_lecturer_info(lecturer_first_name,
                                             lecturer_name_change)
            logger.logger.info('Edited Lecturer`s info In User System')

        elif choice == '3' and permmision == 1:
            obj_solutions.add_sol(input('Add A solution : '))
            logger.logger.info('Added Solution To DataBase')

        elif choice == '4' and permmision == 1:
            list_of_values = input(
                'enter with - Difficulity, Topic, sub_topic, Code, Format : '
            ).split()
            obj_questions.add_question(list_of_values)
            logger.logger.info('Added Question To DataBase')

        elif choice == '5' and permmision == 1:
            question = int(input("What answer would you want to edit?"))
            new_sol = input('Enter Your Edit')
            obj_solutions.edit_sol(question, new_sol)
            logger.logger.info('Edited Solution In DataBase')

        elif choice == '6' and (permmision == 1 or permmision == 2):
            key = input(
                'enter what you want to change, Difficulity, Topic, sub_topic, Code, Format : '
            )
            num = int(input('Enter questions number : '))
            value = input('enter your new value : ')
            obj_questions.edit_question(num, key, value)
            logger.logger.info('Edited Question In DataBase')

        elif choice == '7' and (permmision == 1 or permmision == 2
                                or permmision == 3):
            obj_questions.print_sorted_question_list_by_diff()
            logger.logger.info('Printed Question List By Diff')

        elif choice == '8' and (permmision == 1 or permmision == 2
                                or permmision == 3):
            key = input('enter your filter-by-criteria : ')
            value = input('enter your filter-by-value : ')
            obj_questions.print_filtered_question_list(key, value)
            logger.logger.info('Printed Question List By Criteria')

        elif choice == '0':
            logger.logger.info('Exited User Interface')
            break

        else:
            print('Invalid Choice, Try Again')
            logger.logger.warning('Bad Input')
Example #24
0
    BotLogic.start()
    while True:
        BotLogic.update()
        sleep(0.5)


if __name__ == "__main__":
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logging.getLogger("telegram.bot").setLevel(logging.WARNING)
    fh = logging.FileHandler('bot.log')
    fh.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    logger.addHandler(fh)
    logger.addHandler(ch)
    while True:
        try:
            main_program()
        except KeyboardInterrupt:
            break
        except:
            trace = traceback.format_exc()
            logger.critical(trace)
            BotLogic.send_admin_alert(alertMsg+trace)
            UserData.destroy()

Example #25
0
class Game:
    """
    Represents a game instance

    Recommended training questions based on the following
    1) Squaring a number
    2) Multiplying two numbers having the same first n-1 digits and ones digit add up to ten
    3) Multiplying two numbers ending with 1
    4) Multiplication between a range
    """

    def __init__(self):
        self.lower = 0
        self.upper = 100
        self.score = 0
        self.total_questions = 0
        self.current_question = None
        self.history = {}
        self.user_score = None
        self.saved_question = []
        self.start_time = 0
        self.end_time = 0
        self.set_history()
        self.question_generator = None

    def set_history(self):
        """
        Loads history from database
        :return:
        """
        self.user_score = UserData()
        self.user_score.load_or_create_db()
        self.history = self.user_score.db

    def start_timing(self):
        self.start_time = clock()

    def end_timing(self):
        self.end_time = clock()

    def save_current_question(self):
        self.saved_question.append(self.current_question)

    def gen_next_question(self, lower=None, upper=None, op_type_value=None):
        """
        Generate a random question based on the given parameter (if any)
        :param lower:
        :param upper:
        :param op_type_value:int Give the operation value
        :return:
        """

        lower_bound = self.lower if lower is None else lower
        upper_bound = self.upper if upper is None else upper
        op1 = randint(lower_bound, upper_bound)
        op2 = randint(lower_bound, upper_bound)
        if op_type_value is None:
            op_type_value = randrange(len(Operation))
        self.current_question = Question(op1, op_type_value, op2)

    def solve_question(self, user_input):
        """
        Take a user input and check whether it solves the current question
        :param user_input:int
        :return:(is_user_correct, solution, time_taken)
        """
        if self.current_question is None:
            raise NoQuestionException
        time_taken = self.end_time - self.start_time
        solution = eval(self.current_question.query)
        is_user_correct = solution == user_input
        self.total_questions += 1
        if hash(self.current_question) in self.history:
            self.current_question = self.history[hash(self.current_question)]
        if is_user_correct:
            self.score += 1
            self.current_question.add_correct_time(time_taken)
        else:
            self.current_question.add_wrong_time(time_taken)
        self.history[hash(self.current_question)] = self.current_question

        # For displaying purposes
        return is_user_correct, solution, time_taken

    def gen_squares(self, lower, upper):
        """
        Generate a square question between range upper and lower inclusive
        :param lower:
        :param upper:
        :return:
        """
        x = randint(lower, upper)
        self.current_question = Question(x, Operation.MULTIPLICATION.value, x)

    def gen_ones_digit_sum_to_ten(self, upper_bound):
        """
        two numbers having the same first n-1 digits and ones digit add up to ten
        :param upper_bound:
        :return:
        """
        ones = randint(1, 9)
        ones_complement = 10 - ones
        tens1 = randint(1, upper_bound)
        self.current_question = Question(tens1 * 10 + ones, Operation.MULTIPLICATION.value,
                                         upper_bound * 10 + ones_complement)

    def gen_tens_digit_are_the_same(self, upper_bound):
        """
        Generate two numbers with the same first n-1 digits and is <= upperbound
        :param upper_bound:
        :return:
        """
        ones1 = randint(0, 9)
        ones2 = randint(0, 9)
        tens = randint(upper_bound)
        self.current_question = Question(tens * 10 + ones1, Operation.MULTIPLICATION.value, tens * 10 + ones2)

    def gen_numbers_ending_with_one(self, upper_bound):
        """
        Generate two numbers ending with one with the first n-1 digit <= upper_bound
        :param upper_bound:
        :return:
        """
        tens1 = randint(upper_bound)
        tens2 = randint(upper_bound)
        self.current_question = Question(tens1 * 10 + 1, Operation.MULTIPLICATION.value, tens2 * 10 + 1)
Example #26
0
"""
Payroll Processing page
"""

from tkinter import *
from UserData import *
from GuiValues import *

ud = UserData()
gv = GuiValues()

# Create our frame
# self = Tk()


class PayrollProcessing(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller

        # Object list
        payrollDesc = Label(self,
                            text="Will process payroll for current pay cycle")
        timecardDesc = Label(self, text="Takes you to import timecards")
        salesDesc = Label(self, text="Takes you to import sales reports")

        spacer = Label(self, text="        ")

        # button
        employeesButton = Button(self,
                                 text="Employee's",
Example #27
0
 def UserID(self):
     global ID
     User = UserData.UserData()
     ID = User.TrainData()
Example #28
0
from UserData import *
getUser = UserData()


def test():

    print getUser.verify("fenglin", "newP")
    '''
    print getUser.signUp("fegli1", "password","*****@*****.**")
    print getUser.setInformation("Feng", "Lin", "1996-08-06", "Windish")
    '''
    print getUser.changeUserEmail("*****@*****.**")


if __name__ == "__main__":
    test()
Example #29
0
    conn = DBConn(outputFile)

    # Loop through all users in our loaded list
    for u in APITools.loadUsersFromCsv(userList):

        # Build and also encode all odd characters to a URL-safe format
        jsonurl = urllib.parse.quote("http://localhost:4444/api/v3/u/" +
                                     str(u) + "/blob",
                                     safe=':/')
        print(u.rstrip())
        try:
            # Attempt to get the JSON blob for a user
            blob = APITools.getDataForUser(jsonurl)

            # Create a UserData object to hold information about the active user
            uData = UserData()
            uData.processBlob(blob)

            # Add their competitive rank to the global list if they placed
            cr = uData.getCompRank()
            if cr is not None:
                complist.append(cr)

            # Get the hero distribution for the user
            dist = uData.getHeroDist()
            if dist is not None:

                # Calculate the standard deviation of the list
                # Note: a std of 0.0 is a "one-trick"
                std = Calculators.getHeroStd(dist[1])
def grab_inventory_data(use_jewels=False):
    """grabs inventory from ggg api and loads the local data with it, use_jewels=True if your jewels have res on them"""

    User.load_user_data()

    params = {
        'accountName': User.account_name,
        'character': User.character_name,
        'reqData': 'False'
    }
    cookie = {'POESESSID': User.poesessid}

    r = requests.get(gear_api_endpoint, params=params, cookies=cookie)
    g = r.json()
    items = g['items']

    t = requests.get(jewel_api_endpoint, params=params, cookies=cookie)
    j = t.json()

    for item in items:
        if item['inventoryId'].lower() in gear_resists:
            if item.get('craftedMods') is not None:
                for resist in item['craftedMods']:
                    if 'resistance' in resist.lower():
                        parse_gear(item, resist.lower())
            if item.get('implicitMods') is not None:
                for resist in item['implicitMods']:
                    if 'resistance' in resist.lower():
                        parse_gear(item, resist.lower())
            for resist in item['explicitMods']:
                # explicit mods in the json formatted "+#% to X Resistance" so strip '+' and split at % to get number
                if 'resistance' in resist.lower():
                    parse_gear(item, resist.lower())
            # if the item has 6 mods, has been crafted or is unique it can't be crafted again (unless u scour the craft)
            if len(item['explicitMods']) == 6 or item.get(
                    'craftedMods') is not None or item['frameType'] == 3:
                gear_resists[item['inventoryId'].lower()]['craftable'] = False
            else:
                gear_resists[item['inventoryId'].lower()]['craftable'] = True

    if use_jewels:
        items = j['items']

        for item in items:
            if item['inventoryId'].lower() in gear_resists:
                for resist in item['explicitMods']:
                    if 'resistance' in resist.lower():
                        parse_gear(item, resist.lower())
    # load all the tree nodes into local memory
    for node in j['skillTreeData']['nodes']:
        tree_nodes[node['id']] = [c for c in node['sd']]

    # compare the hashes to the nodes and if they give resists add to total
    single_rez_pattern = re.compile('\+\d{1,2}% to [a-zA-Z]* Resistance')
    all_rez_pattern = re.compile('\+\d{1,2}% to all Elemental Resistances')
    for h in j['hashes']:
        for stat in tree_nodes[h]:
            if single_rez_pattern.match(stat):
                if 'fire' in stat.lower():
                    gear_resists['tree']['fire'] += int(
                        stat.strip('+').split('%', 1)[0])
                if 'cold' in stat.lower():
                    gear_resists['tree']['cold'] += int(
                        stat.strip('+').split('%', 1)[0])
                if 'lightning' in stat.lower():
                    gear_resists['tree']['lightning'] += int(
                        stat.strip('+').split('%', 1)[0])
            elif all_rez_pattern.match(stat):
                gear_resists['tree']['fire'] += int(
                    stat.strip('+').split('%', 1)[0])
                gear_resists['tree']['cold'] += int(
                    stat.strip('+').split('%', 1)[0])
                gear_resists['tree']['lightning'] += int(
                    stat.strip('+').split('%', 1)[0])

    # no need to keep a giant dict in memory after we use it
    tree_nodes.clear()
    calculate_totals()
Example #31
0
def play_actions(hsfem=None, rootname='mother'):
    import os, time
    import hs
    import UserData, YS_Assist
    from collections import OrderedDict as od
    from UnityEngine import Time

    if hsfem == None:
        hsfem = hs.get_first_active_female()
    elif isinstance(hsfem, str):
        hsfem = create_female(hsfem)
    if isinstance(hsfem, hs.HSFemale):
        hsfem.reset()

        #All clothes on
        #hsfem.enable_clothes(0)
        #yield True
        _path = os.path.abspath(os.path.join(UserData.Create("cap"), rootname))

        moodmap = {
            'normal': od(persona='Strict', action='Normal Wait',
                         mood='normal'),
            'angry': od(persona='Strict', action='Hate', mood='angry'),
            'sad': od(persona='Strict', action='Hate 2', mood='sad'),
            'happy': od(persona='Strict', action='Lewd', mood='happy'),
            'hypno': od(persona='Withdrawn',
                        action='Normal Wait',
                        mood='hypno'),
            'surprised': od(persona='Boyish', action='Like', mood='surprised'),
        }
        clothset = {
            'bath': od(
                name='Bath Towel',
                acc=0,
            ),
            'casual': od(
                name='G|Mother Casual',
                acc=1,
            ),
            'naked': od(name='G|Mother Casual', acc=0, state=2),
            'swimsuit': od(
                name='G|Orange Swim',
                acc=0,
            ),
            'underwear': od(
                name='G|Black Lace',
                acc=1,
            ),
            'work': od(
                name='G|Mother Work',
                acc=1,
            ),
        }

        aplayer = None
        for cloth, clothes in clothset.iteritems():
            for k, v in clothes.iteritems():
                if k == 'name':
                    hsfem.apply_clothes(v)
                    hsfem.enable_clothes(0)
                elif k == 'state':
                    hsfem.enable_clothes(v)
                elif k == 'acc':
                    hsfem.enable_accessories(v)

            for mood, states in moodmap.iteritems():
                _subdir = os.path.join(_path, mood)
                if not os.path.exists(_subdir): os.makedirs(_subdir)
                fname = os.path.join(_subdir, cloth + ".png")

                oldTimeScale = Time.timeScale
                Time.timeScale = 5.0
                try:
                    for k, v in states.iteritems():
                        if k == 'persona':
                            if not aplayer or aplayer.personality != v:
                                aplayer = hsfem.load_personality(v)
                        elif k == 'action':
                            if aplayer: aplayer.play(v)
                        elif k == 'mood':
                            hsfem.set_mood(v)
                finally:
                    Time.timeScale = oldTimeScale
                print fname
                time.sleep(0.5)
                hs.capture(fname)

                yield True

        # loads related animations by character name

        #for name in aplayer.names:
        #    aplayer.play(name)  # names available in aplayer.names
        #    yield True

        #hsfem.set_mood('angry')
        #hsfem.set_hand_position('l', 'dummy')
        #hsfem.set_hand_position('r', 'goo') #fist

    yield None
Example #32
0
def capture_noblock(_path='', _alpha=True, autofit=True):
    import System
    import Manager
    from System import *
    from System.IO import *
    from UnityEngine import *
    from UnityEngine import Object as Object
    from UnityEngine import Time as Time
    width = Screen.width
    height = Screen.height
    tex = Texture2D(
        width, height,
        TextureFormat.RGB24 if not _alpha else TextureFormat.ARGB32, False)
    tex2 = Texture2D(
        width, height,
        TextureFormat.RGB24 if not _alpha else TextureFormat.ARGB32, False)
    if QualitySettings.antiAliasing != 0:
        rt = RenderTexture.GetTemporary(width, height,
                                        0x18 if not _alpha else 0x20,
                                        RenderTextureFormat.Default,
                                        RenderTextureReadWrite.Default,
                                        QualitySettings.antiAliasing)
        rt2 = RenderTexture.GetTemporary(width, height,
                                         0x18 if not _alpha else 0x20,
                                         RenderTextureFormat.Default,
                                         RenderTextureReadWrite.Default,
                                         QualitySettings.antiAliasing)
    else:
        rt = RenderTexture.GetTemporary(width, height,
                                        0x18 if not _alpha else 0x20)
        rt2 = RenderTexture.GetTemporary(width, height,
                                         0x18 if not _alpha else 0x20)
    #RenderCam = Camera.main
    RenderCam = Manager.Studio.Instance.MainCamera
    backRenderTexture = RenderCam.targetTexture
    backRect = RenderCam.rect
    oldBackground = RenderCam.backgroundColor
    oldFlags = RenderCam.clearFlags
    RenderCam.backgroundColor = Color(Single(1), Single(1), Single(1),
                                      Single(1))
    RenderCam.clearFlags = CameraClearFlags.Color
    RenderCam.targetTexture = rt
    RenderCam.Render()
    RenderCam.targetTexture = backRenderTexture
    RenderCam.rect = backRect
    RenderTexture.active = rt
    tex.ReadPixels(Rect(Single(0), Single(0), width, height), 0, 0)
    tex.Apply()
    RenderTexture.active = None
    RenderCam.backgroundColor = Color(Single(0), Single(0), Single(0),
                                      Single(1))
    RenderCam.clearFlags = CameraClearFlags.Color
    RenderCam.targetTexture = rt2
    RenderCam.Render()
    RenderCam.targetTexture = backRenderTexture
    RenderCam.rect = backRect
    RenderTexture.active = rt2
    tex2.ReadPixels(Rect(Single(0), Single(0), width, height), 0, 0)
    tex2.Apply()
    RenderTexture.active = None
    RenderCam.backgroundColor = oldBackground
    RenderCam.clearFlags = oldFlags
    RenderTexture.ReleaseTemporary(rt)
    RenderTexture.ReleaseTemporary(rt2)

    cols1 = tex.GetPixels()
    cols2 = tex2.GetPixels()
    x1, x2 = width, 0
    y1, y2 = height, 0

    for i in xrange(0, cols1.Length - 1):
        c1 = cols1[i]
        c2 = cols2[i]
        a = 1.0
        if c1 != c2:
            a = Single(1) - Math.Max(
                Math.Abs(c1.r - c2.r),
                Math.Max(Math.Abs(c1.g - c2.g), Math.Abs(c1.b - c2.b)))
        else:
            a = Single(
                1) if c1.a < 0.05 else c1.a  # handle bad alpha rendering
        cols1[i] = Color(c1.r, c1.g, c1.b, a)
        if autofit and a > 0.05:
            y = i // width
            x = i - y * width
            if x < x1: x1 = x
            if x > x2: x2 = x
            if y < y1: y1 = y
            if y > y2: y2 = y
    if autofit:

        def irnd(x):
            return x + x % 2

        # add padding then truncate
        padding = 4
        x1, y1 = max(0, irnd(x1 - padding)), max(0, irnd(y1 - padding))
        x2, y2 = min(width, irnd(x2 + padding)), min(height,
                                                     irnd(y2 + padding))
        Object.Destroy(tex)
        w, h = x2 - x1, y2 - y1
        tex = Texture2D(x2 - x1, y2 - y1, TextureFormat.ARGB32, False)
        cols = tex.GetPixels()
        for i in range(x1, x2):
            for j in range(y1, y2):
                cols[(j - y1) * w + (i - x1)] = cols1[j * width + i]
        tex.SetPixels(cols)
        tex.Apply()
    else:
        tex.SetPixels(cols1)
        tex.Apply()
    bytes = tex.EncodeToPNG()
    Object.Destroy(tex)
    tex = None
    if str.Empty == _path:
        import UserData, datetime
        _path = UserData.Create("cap")
        fileName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')[:-3]
        _path = Path.GetFullPath(Path.Combine(_path, fileName + ".png"))
        Console.WriteLine("Capture: " + _path)
    File.WriteAllBytes(_path, bytes)
    return True
Example #33
0
from UserData import *
from WhereToTypes import *
from Destination import *

mattsProfile = UserData( "Matt Gaylor", 24 )

venice = Destination( "Venice", "Italy", TravelledState.HasBeen, 0, 0, 1 )
shanghai = Destination( "Shanghai", "China", TravelledState.HasBeen, 2, 2, 1 )
lima = Destination( "Lima", "Peru", TravelledState.WantsToGo, 3, 3 )
anywhereButHere = Destination( "", "Outside of Natalie's Living Room", TravelledState.WantsToGo, 3, 3 )
georgia = Destination( "Georgia", "USA", TravelledState.WantsToGo, 3, 3 )
singapore = Destination( "", "Singapore", TravelledState.WantsToGo, 3, 3 )

mattsProfile.AddDestination( venice )
mattsProfile.AddDestination( shanghai )
mattsProfile.AddDestination( lima )
mattsProfile.AddDestination( anywhereButHere )
mattsProfile.AddDestination( georgia )
mattsProfile.AddDestination( singapore )

mattsProfile.ToString()

mattsProfile.RegisterTrip( singapore )
mattsProfile.RegisterTrip( venice )

mattsProfile.ToString()

heaven = Destination( "Nigels", "Butthole", TravelledState.WantsToGo, 3, 3, 68 )
mattsProfile.RegisterTrip( heaven )

mattsProfile.ToString()
Example #34
0
def showUserStats():
    mediums = ["Book", "Film", "Audio"]
    userOptions = ["Rental", "Hold"]
    for medium in mediums:
        print medium
    # Carlos change
    print "\n"

    selectMedium = raw_input("Please select from above: ")
    print "\n"

    print "Please enter your selection: "
    if selectMedium == "Book":
        for attr in userOptions:
            print attr
        choice = raw_input("Please select a search parameter: ").lower()
        if choice == str("rental"):
            print "\n"
            UserData.getUserBookRentals()
        elif choice == str("hold"):
            print "\n"
            UserData.getUserBookHolds()
        else:
            print "Invalid selection."

    elif selectMedium == "Film":
        for attr in userOptions:
            print attr
        choice = raw_input("Please select a search parameter: ").lower()
        if choice == str("rental"):
            print "\n"
            UserData.getUserFilmRentals()
        elif choice == str("hold"):
            print "\n"
            UserData.getUserFilmHolds()
        else:
            print "Invalid selection."

    elif selectMedium == "Audio":
        for attr in userOptions:
            print attr
        choice = raw_input("Please select a search parameter: ").lower()
        if choice == "Hold":
            print "\n"
            UserData.getUserAudioRentals()
        elif choice == "Rental":
            print "\n"
            UserData.getUserAudioHolds()
        else:
            print "Invalid selection."

    else:
        print "Invalid selection."
Example #35
0
import LoadDict
import History
import UserData


# LoadDict.loadfromfile()
History.reset_info()
UserData.reset_info()

print('init finished')
Example #36
0
    def cap_scenes():
        import hs, os.path, UserData

        _path = os.path.abspath(os.path.join(UserData.Create("cap"), 'mother'))
        if not os.path.exists(_path): os.makedirs(_path)

        # surprise
        hs.move_camera(pos=(0.0, 0.9, 0.0),
                       dir=(0.0, 0.0, -5.0),
                       angle=(8.5, 184.4, 0.0),
                       fov=23.0)
        # begin females
        hsfem = hs.HSFemale.create_female('[GX] Mother', attach=True)
        #hsfem.load_animation('adv/00.unity3d', 'adv_f_01_00')
        hsfem.play_ik('G Cover')
        hsfem.move(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0))
        hsfem.chara.SetActiveTop(True)
        hsfem.chara.ChangeBlinkFlag(False)
        hsfem.chara.ChangeEyesPtn(11, True)
        hsfem.chara.ChangeMouthPtn(7, True)
        hsfem.chara.ChangeLookNeckPtn(3)
        hsfem.chara.ChangeLookEyesPtn(1)
        hsfem.set_clothes_state_all(2)
        hsfem.enable_accessories(0)
        yield os.path.join(_path, 'dailybath (1).png')

        hs.move_camera(pos=(-0.5, 1.0, 0.0),
                       dir=(0.0, 0.0, -3.8),
                       angle=(24.5, 193.4, 0.0),
                       fov=23.0)
        hsfem.reset()
        #hsfem.load_animation('adv/00.unity3d', 'adv_f_07_00')
        hsfem.play_ik('G Bath Step')
        hsfem.move(pos=(-0.5, -0.3, 0.0), rot=(359.2, 129.0, 359.4))
        hsfem.chara.ChangeBlinkFlag(False)
        hsfem.chara.ChangeEyesPtn(1, True)
        hsfem.chara.ChangeMouthPtn(1, True)
        hsfem.chara.ChangeLookNeckPtn(5)
        hsfem.chara.ChangeLookEyesPtn(1)
        hsfem.set_clothes_state_all(2)
        hsfem.enable_accessories(0)
        # begin items
        item = hs.HSItem.create_item('Bathtub (Yellow)', attach=True)
        item.move(pos=(0.2, -0.1, 0.0), rot=(0.0, 23.0, 4.0))
        yield os.path.join(_path, 'dailybath (2).png')

        hs.move_camera(pos=(-0.4, 0.5, -0.1),
                       dir=(0.0, 0.0, -3.5),
                       angle=(34.0, 157.1, -1.8),
                       fov=23.0)
        # begin females
        hsfem.reset()
        hsfem.load_animation('custom/cf_anim_custom.unity3d', 'edit_F')
        hsfem.play_ik('G Sit Bath 2')
        hsfem.move(pos=(0.0, 0.2, -0.6), rot=(359.7, 7.1, 1.0))
        hsfem.chara.ChangeBlinkFlag(True)
        hsfem.chara.ChangeEyesPtn(5, True)
        hsfem.chara.ChangeMouthPtn(1, True)
        hsfem.chara.ChangeLookNeckPtn(3)
        hsfem.chara.ChangeLookEyesPtn(0)
        hsfem.set_clothes_state_all(2)
        hsfem.enable_accessories(1)
        # begin items
        item = hs.HSItem.create_item('Bathtub (Yellow)', attach=True)
        item.move(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0))
        yield os.path.join(_path, 'dailybath (3).png')

        yield None