def test_findUser(self):
     '''Test case method to test for functionality find user'''
     self.new_user.saveUser()
     confirm_user = User('Ali@234', 'Ali12345')
     confirm_user.saveUser()
     found_user = User.findUser("Ali@234")
     self.assertEqual(found_user.userName, confirm_user.userName)
Exemple #2
0
def read_data(file_name):
    # The users dictionary: key = username,
    # value = user object
    users = {}
    tasks = []
    with open(file_name, 'r') as f:
        num_users = int(f.readline())
        i = 0
        while i < num_users:
            line = f.readline().strip()
            parts = line.split(';')
            user = User(parts[0], parts[1], parts[2])
            users[user.login] = user
            i += 1
        num_tasks = int(f.readline())
        i = 0
        while i < num_tasks:
            line = f.readline().strip()
            parts = line.split(';')
            task = Task(parts[0], parts[1], parts[2], parts[3])
            if parts[3] == TASK_ALL_USERS:
                add_task_to_users(users, task)
            else:
                user = users.get(parts[3], None)
                if user:
                    user.add_task(task)
            tasks.append(task)
            i += 1
    return (users, tasks)
Exemple #3
0
    def load_user_button_click(self):
        global f_name_out_label, l_name_out_label, debt_out_label, receivables_out_label

        user = User(username=self.username_entry.get())
        user.load(offer_to_create=False)

        if user.user_id == -1:
            messagebox.showwarning('Error', 'User not found')
            f_name_out_label.destroy()
            l_name_out_label.destroy()
            debt_out_label.destroy()
            receivables_out_label.destroy()

        else:
            f_name_out_label = tk.Label(self.user_overview, text=user.f_name)
            f_name_out_label.grid(row=2, column=1)

            l_name_out_label = tk.Label(self.user_overview, text=user.l_name)
            l_name_out_label.grid(row=3, column=1)

            balance = user.balance()

            debt_out_label = tk.Label(self.user_overview, text=balance[0])
            debt_out_label.grid(row=4, column=1)

            receivables_out_label = tk.Label(self.user_overview,
                                             text=balance[1])
            receivables_out_label.grid(row=5, column=1)
    def post(self):
        #See User Login in Server Terminal
        #print >>sys.stderr, request.get_data()
        #print >>sys.stderr, request.headers

        #Try to Parse Request Data
        try:
            data = request.get_json(force=True)
        except:
            print >> sys.stderr, "JSON request not properly formatted"
            return {'message': "JSON request not properly formatted"}, 500

        #Try to login the user in
        try:
            User.loginUser(data['username'], data['password'])
        except ValueError as error:
            return {'message': str(error)}, 500
        else:
            #If success, create tokens
            access_token = create_access_token(identity=data['username'])
            refresh_token = create_refresh_token(identity=data['username'])

            print >> sys.stderr, "Access Toke : " + access_token
            print >> sys.stderr, "Refresh Token : " + refresh_token
            return {
                'message': 'Logged in as {}'.format(data['username']),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
Exemple #5
0
def registerHandler():
    error = None
    if request.method == 'POST':
        email = request.json.get('email')
        username = request.json.get('username')
        password = request.json.get('password')
        authenticated = False

        ## Check Email Validity and Username Availability
        email_valid = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email)
        if email_valid == None:
            error = "Please enter a valid email address!"
        else:
            checkUser = User.query.filter_by(username=username).first()
            if checkUser != None:
                error = "Username is taken! Please try again!"
            else:
                ## Add user to database
                user = User(email=email, username=username, password=password, authenticated=authenticated)
                db.session.add(user)
                db.session.commit()
                ##Login user
                user.authenticated = True
                db.session.add(user)
                db.session.commit()
                login_user(user, remember=True)
    return jsonify({'message': ' user created'}), 200
Exemple #6
0
def testGraphs():
    #tests the graphs using fake users
    users = [0, 0, 0, 0]
    users[0] = User('Josh', (255, 0, 0))
    users[0].add_edit(Edit(dt.datetime(2018, 9, 6, 11, 59, 0), '1', False))
    users[0].add_edit(Edit(dt.datetime(2018, 9, 6, 11, 54, 0), '123456', True))

    users[1] = User('Keith', (0, 255, 0))
    users[1].add_edit(Edit(dt.datetime(2018, 9, 7, 11, 59, 0), '123', False))
    users[1].add_edit(Edit(dt.datetime(2018, 9, 5, 11, 54, 0), '12345', True))

    users[2] = User('Glyn', (0, 0, 255))
    users[2].add_edit(Edit(dt.datetime(2018, 10, 7, 11, 59, 0), '1234', False))
    users[2].add_edit(Edit(dt.datetime(2018, 10, 5, 11, 54, 0), '1234', True))

    users[3] = User('Michael', (100, 100, 100))
    users[3].add_edit(Edit(dt.datetime(2018, 10, 13, 11, 59, 0), '45', False))

    plt1 = main_file.plot_pie_chart(users, True)
    plt2 = main_file.plot_pie_chart(users, False)
    plt3 = main_file.plot_lines(users, dt.datetime(2018, 9, 4, 11, 54, 0),
                                dt.datetime(2018, 10, 14, 11, 59, 0), True)
    plt4 = main_file.plot_lines(users, dt.datetime(2018, 9, 4, 11, 54, 0),
                                dt.datetime(2018, 10, 14, 11, 59, 0), False)

    save_all_plots([plt1, plt2, plt3, plt4], 'testGraphs.pdf')
Exemple #7
0
def start_message(message):
    user = User(user_id=message.from_user.id,
                chat_id=message.chat.id,
                name=message.from_user.first_name)
    user.check_if_user_exists()
    msg = bot.reply_to(
        message,
        min_planked_time_answer(user=user.name, politeness=user.politeness))
    bot.register_next_step_handler(msg, set_up_time_step)
Exemple #8
0
def home():
    if request.method == 'POST':
        username = request.form['username']
        user = User(username=username)
        user.load()
        balance = user.balance()
        return render_template('load_user.html', f_name=user.f_name, l_name=user.l_name, debt=balance[0], receivables=balance[1])


    return render_template('load_user.html', f_name='', l_name='', debt='', receivables='')
	def registernow(self, paramdct):
		tc=TaskCookie()
		u=User.by_name(paramdct['username'])
		if u!=None:
			paramdct['usernameerror']='Username already exists!'
			paramdct['haserror']=True
		else:
			u=User.register(paramdct['username'], paramdct['password'], paramdct['email'])
			u.put()
			tc.login(u,self)
Exemple #10
0
def getUserInfo():
    """
    Prompt the user for input
    """
    name = str(input("Name: "))
    age = int(input("Age: "))
    email = str(input("E-mail: "))
    user = User(name, age, email)
    print(f"User Registration Successful for {user.name}")
    user.saveprofile()
Exemple #11
0
def handle_docs_video(message):
    user = User(user_id=message.from_user.id,
                chat_id=message.chat.id,
                name=message.from_user.first_name)
    user.check_if_user_exists()
    print('Server time ', datetime.datetime.today())

    if int(datetime.datetime.fromtimestamp(message.date).strftime("%H")) > 2:
        user.check_planked_today(
            datetime.datetime.fromtimestamp(message.date).strftime("%d %b %Y"))
    else:
        user.check_planked_today(
            (datetime.datetime.fromtimestamp(message.date) -
             timedelta(days=1)).strftime("%d %b %Y"))

    if user.planked_today is False:
        if int(datetime.datetime.fromtimestamp(
                message.date).strftime("%H")) > 2:
            if message.video.duration >= user.current_time:
                bot.send_message(
                    message.chat.id,
                    bot_planked_answer(
                        message.from_user.first_name,
                        datetime.datetime.fromtimestamp(message.date),
                        user.politeness))
                user.write_planked_today(
                    datetime.datetime.fromtimestamp(
                        message.date).strftime("%d %b %Y"))
            else:
                bot.send_message(
                    message.chat.id, 'Dear ' + message.from_user.first_name +
                    ', your current minimum planking time is ' +
                    str(user.current_time) + ' seconds. Your video is ' +
                    str(message.video.duration) + ' seconds, which is less.')
                bot.send_sticker(
                    message.chat.id,
                    'CAACAgIAAxkBAAECQv9gkkGyCEsBZZL4RnkOD4A4fXLnKwACiwIAAladvQr3tGImDY878x8E'
                )
        else:
            if message.video.duration >= user.current_time:
                bot.send_message(
                    message.chat.id,
                    bot_planked_answer(
                        message.from_user.first_name,
                        (datetime.datetime.fromtimestamp(message.date) -
                         timedelta(days=1)), user.politeness))
            else:
                bot.send_message(
                    message.chat.id, 'Dear ' + message.from_user.first_name +
                    ', your current minimum planking time is ' +
                    str(user.current_time) + ' seconds. Your video is ' +
                    str(message.video.duration) + ' seconds, which is less.')
    else:
        bot.send_message(message.chat.id,
                         'Bro, you already planked today! You can stop)')
Exemple #12
0
def add_user(newuser):
    value = User.create_id()
    play = {}
    new_user = User(newuser, value, play)
    user_data = {value: new_user.__dict__}
    users_data.update(user_data)
    response = app.response_class(response=json.dumps(user_data),
                                  status=200,
                                  mimetype='application/json')
    print(response)
    return response
Exemple #13
0
def listall():
    error = False
    user = User()
    try:
        results = user.listall()
    except (Exception) as err:
        error = True
        return handleError(err)
    finally:
        if not (error):
            return jsonify({'results': results})
Exemple #14
0
def Follow(id):
    user = User(current_user.username, "", "")
    followingid = user.get_user_id()

    follower_pair = FollowerPair(followingid, id)

    if follower_pair.exists():
        flash('You have already followed that user.')
        return redirect(url_for('page.home_page'))
    else:
        follower_pair.new_follow()
        return redirect(url_for('page.home_page'))
Exemple #15
0
def Unfollow(id):
    user = User(current_user.username, "", "")
    followingid = user.get_user_id()

    follower_pair = FollowerPair(followingid, id)

    if follower_pair.exists() is False:
        flash('You do not follow that user.')
        return redirect(url_for('page.home_page'))
    else:
        follower_pair.unfollow()
        return redirect(url_for('page.home_page'))
Exemple #16
0
def getuserCustomer():
    error = False
    user = User()
    user.id = request.json['id']
    try:
        info = user.getCustomer()
    except (Exception) as err:
        error = True
        return handleError(err)
    finally:
        if not (error):
            return jsonify({'result': 'success', 'data': info})
Exemple #17
0
def deleteUser():
    error = False
    user = User()
    user.id = request.json['id']
    try:
        user.delete()
    except (Exception) as err:
        error = True
        return handleError(err)
    finally:
        if not (error):
            return jsonify({'result': 'success'})
def main():
    '''
    '''
    file_name = make_userfile()
    fl = open(file_name, "a")
    user = User(file_name)
    iterat = True
    while iterat == True:
        print(menu())
        section = input("Choose: ")
        if len(section) < 1:
            iterat = False
        user.choose_section(section)
Exemple #19
0
def listUserCartItems():
    result = []
    error = False
    user = User()
    user.id = request.json['user_id']
    try:
        result = user.listCartItems()
    except (Exception) as err:
        error = True
        return handleError(err)
    finally:
        if not (error):
            return jsonify({'result': 'success', 'data': result})
Exemple #20
0
def check_all_missed_times(chat):
    users_df = pd.read_hdf(users_db_path, key='df')
    message = 'Here is the list of all current lazy debtors: ' + ' \n '
    for user in users_df.loc[users_df['chat_id'] == chat]['user_id']:
        check_user = User(user_id=user, chat_id=chat)
        check_user.check_if_user_exists()
        # member = bot.get_chat_member(chat_id=check_user.chat_id, user_id=check_user.user_id)
        # print('member:', member.status)
        if check_user.times_missed > 0:
            message = message + str(check_user.name) + ' - ' + str(
                check_user.times_missed) + ' \n '

    bot.send_message(chat, message)
def main():
    '''
    Main function. Responsible for program's work.
    '''
    file_name = make_userfile()
    fl = open(file_name, "a")
    user = User(file_name)
    iterat = True
    while iterat == True:
        print(menu())
        section = input("Choose: ")
        if len(section) < 1:
            iterat = False
        user.choose_section(section)
Exemple #22
0
def log_in2():
    if request.method == 'POST':
        usg_time = request.form['usage_time']
        answ = ['yes', 'YES', 'Yes', 'no', 'NO', 'No']
        if usg_time in answ:
            file_name = make_userfile(ACC_NAME, usg_time)
            global FILE_NAME
            FILE_NAME = file_name
            global USER
            USER = User(FILE_NAME)
            USER.set_file(FILE_NAME)
            return render_template('options.html')
        else:
            return render_template('time_usage_page2.html')
Exemple #23
0
def balance_overview(user_ids=-1):
    to_print = ''

    if user_ids == -1:
        user_ids = []
    elif isinstance(user_ids, list):
        pass
    elif isinstance(user_ids, int):
        user_ids = [user_ids]
    else:
        to_print += '\nWrong input'
        return
    users = server_conn('list_users')
    counterpart_ids = users.to_list()
    if not user_ids:
        user_ids = counterpart_ids

    for user_id in user_ids:
        to_print += '\n'
        to_print += ('=' * 50)
        user1 = User(user_id=user_id)
        user1.load()
        to_print += '\n'
        to_print += user1.f_name
        user1_balance = user1.balance()
        to_print += '\n'
        to_print += ('Accumulated debt: {0} RUB'.format(user1_balance[0]))
        to_print += '\n'
        to_print += ('Accumulated receivables: {0} RUB'.format(
            user1_balance[1]))

        remaining_users = [i for i in counterpart_ids if i != user1.user_id]

        for counterpart_id in remaining_users:
            user2 = User(user_id=counterpart_id)
            counterpart_balance = user1.balance(counterpart_id=user2.user_id)
            debt_to_counterpart = counterpart_balance[0]
            receivables_from_counterpart = counterpart_balance[1]
            if debt_to_counterpart != 0 or receivables_from_counterpart != 0:
                user2.load()
                to_print += '\n'
                to_print += ('-' * 20)
                to_print += '\n'
                to_print += ('Debt to {0}: {1} RUB:'.format(
                    user2.f_name, debt_to_counterpart))
                to_print += '\n'
                to_print += ('Receivables from {0}: {1} RUB'.format(
                    user2.f_name, receivables_from_counterpart))
    print(to_print)
    return to_print
Exemple #24
0
def new_user():
    """Create new user."""
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400)  # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)  # existing user
    user = User(username=username)
    user.hash_password(password)
    DB.session.add(user)
    DB.session.commit()
    return jsonify({'username': user.username}), 201, {
        'Location': url_for('new_user', id=user.id, _external=True)
    }
Exemple #25
0
    async def sigma_start(self, message: discord.Message):
        # h = self.get_channel(496450097928732672)
        users[str(message.author.id)] = User.User(message.author.id, client)
        # await message.channel.send(str(await h.create_invite()))

        await self.send(message.channel,
                        f"ユーザーデータのロード完了。\nこんにちは、{message.author.name}さん。")
Exemple #26
0
def start_message(message):
    user = User(user_id=message.from_user.id,
                chat_id=message.chat.id,
                name=message.from_user.first_name)
    user.check_if_user_exists()
    bot.send_message(
        message.chat.id, 'Your current statistics: \n'
        'Name: ' + str(user.name) + ' \n'
        'Current minimum planking time: ' + str(user.current_time) +
        ' seconds. \n'
        'Time increase: ' + str(user.time_increase) + ' seconds \n'
        'Increase in days: ' + str(user.increase_in_days) + ' days \n'
        'Next increase on: ' + str(user.increase_day) + '\n'
        'Vacation: ' + str(user.vacation) + '\n'
        'Times missed: ' + str(user.times_missed) + '\n'
        'Politeness: ' + str(user.politeness))
Exemple #27
0
def finished_round():

    user = User(session['email'])
    user_model = UserModel()
    word_list_view = user_model.get_word_list_view(user)
    seen_list = word_list_view.seen_word_list
    learnt_list = word_list_view.learnt_word_list
    forgotten_list = word_list_view.forgotten_word_list

    # graph_pygal = pygal.Line()
    # graph_pygal.title = '% Change Coolness of programming languages over time.'
    # graph_pygal.x_labels = ['2011', '2012', '2013', '2014', '2015', '2016']
    # graph_pygal.add('Python', [15, 31, 89, 200, 356, 900])
    # graph_pygal.add('Java', [15, 45, 76, 80, 91, 95])
    # graph_pygal.add('C++', [5, 51, 54, 102, 150, 201])
    # graph_pygal.add('All others combined!', [5, 15, 21, 55, 92, 105])

    pie_chart = pygal.Pie()
    pie_chart.title = 'TITLE'
    pie_chart.add('Seen Words', WordModel.get_number_labels(seen_list))
    pie_chart.add('Forgotten Words', WordModel.get_number_labels(forgotten_list))
    pie_chart.add('Learnt Words', WordModel.get_number_labels(learnt_list))
    pie_chart.render()
    graph_data = pie_chart.render_data_uri()

    return render_template('list.html',
                           seen_list=seen_list,
                           learnt_list=learnt_list,
                           forgotten_list=forgotten_list,
                           graph_data=graph_data
                           )
	def post(self):
		try:
			paramdct={}
			paramdct['footer']='Udacity'
			paramdct['username']=self.request.get('username')
			password=self.request.get('password')
			paramdct['haserror']=False
			vl.CheckVal('username',paramdct['username'],False,'usernameerror','not valid username / username required',paramdct)
			vl.CheckVal('password',password,False,'passworderror','not valid password / password required',paramdct)

			u=User.login(paramdct['username'], password)
			if u==None:
				paramdct['haserror']=True
				paramdct['error']='Invalid Login!'
			else:
				tc=TaskCookie()
				tc.login(u, self)

					
			if paramdct['haserror']==False:
				self.redirect('/cookiewelcome')
			else:
				paramdct['title']='User Login'
				paramdct['links']='/'
				paramdct['header']='Login'
				paramdct['footer']='Udacity'
				self.response.write(jw.WriteTemplate('login.html','website_layout.css',path,**paramdct))
		except Exception as err:
			if paramdct.has_key('error'):
				paramdct['error']+=', ' + str(err)
			else:
				paramdct['error']=err
			paramdct['wktemplate']='login.html'
			self.response.write(jw.WriteTemplate(paramdct['wktemplate'], 'website_layout.css', path, **paramdct))
Exemple #29
0
def ChangePassword(UsedUser:classes.User, NewPassword:str):
    if UsedUser not in USERS:
        return 'UserIsNotExists'
    if UsedUser in (ADMINISTRATOR, DEFAULTUSER):
        return 'ThisUserCannotChange'
    UsedUser.password = NewPassword
    return 'PasswordChanged'
def carrinheiro(id_user, date):
    user_carrinheiro = User.get_user(id_user, DATABASE_DIRECTORY)
    path = Path.Path(user_carrinheiro, date, DATABASE_DIRECTORY)

    stop_points = scenario_stop_points(path)

    # download the osm file (scenario)
    file_name_osm = OpenSteetMap.file_osm(MAPS_DIRECTORY, stop_points)

    # download the GeoTiff file (scenario)
    geotiff_name = GeoTiff.geotiff(MAPS_DIRECTORY, stop_points)

    G, nodes_coordinates, nodes_mass_increment = graph_scenario(
        stop_points, geotiff_name, path.material_weights, file_name_osm)

    H = Graph_Collect.create_graph_route(nodes_coordinates,
                                         nodes_mass_increment)

    index_coordinate_start = list(nodes_coordinates.values()).index(
        path.start_point)
    node_source = list(nodes_coordinates.keys())[index_coordinate_start]
    index_coordinate_end = list(nodes_coordinates.values()).index(
        path.end_point)
    node_target = list(nodes_coordinates.keys())[index_coordinate_end]

    cost_total, paths = closest_insertion_path(G, H, node_source, node_target)

    for i in paths:
        fig, ax = ox.plot_graph_route(G,
                                      i,
                                      route_linewidth=6,
                                      node_size=0,
                                      bgcolor='w')

    return paths
	def __load_users(self, path):
		users = {}
		with open(path + "\Person.txt") as f:
			for line in f:
				userdata = line.rstrip().split("\t")
				userid = int(userdata[0])
				try:
					age = userdata[1]
				except:
					age = 0

				try:
					gender = userdata[2]
				except:
					gender = "N/A"

				occupation = "N/A"

				try:
					zip_code = userdata[3]
				except:
					zip_code = "N/A"

				users[userid] = User(userid, age, gender, occupation, zip_code)

		with open(path + "\Vote.txt") as f:
			for line in f:
				data = line.split("\t")
				userid = int(data[0])
				itemid = int(data[1])
				rating = float(data[2])*5
				weight = float(data[3])

				if weight == 1.0:
					users[userid].ratings[itemid] = rating

		return users
def verifyIdAuth(cert):
    user = User(getCertOCSPStatus(cert))
    if user.Status == 'GOOD':
        user.Authenticated = True
    return user