def signup():
	
	if request.method == 'POST' :
		# validate name and email
		# check if email is unique
		club_name=request.form['CLUBN']
		email=request.form['EMAIL']
		#generate unique key as current timestamp
		unique_key=''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(32))
		#send mail with unique key and store in db to verify later
		g.cur.execute("insert into pending_verification(club_name,club_mail,unique_key) values('%s','%s','%s')"%(club_name,email,unique_key))
		g.db.commit()
		subject="Signup request from club %s at VIT clubs portal"%(club_name)
		body='''\
A request has been for registration on VIT clubs portal from your e-mail.  To verify you account follow the following steps.

Post the following message to your facebook page.

    Verification of %s on VIT clubs portal.
    Verification code - %s
    Get your club registered today and reach all vitians through VITacademics app.


'''%(club_name,unique_key)
		mailing.send_mail(subject,body,email)
		
		session['messages']='''Your request has been received. Verification is required for registration!
Please follow the steps given in the mail to complete your registration'''
		
	return redirect(url_for('user_management.login'))
예제 #2
0
def check():
    global tries
    output = None
    try:
        output = pg.checkPG(s.login, s.password, s.link, s.look_for)
        if output > s.number_of_exercises and s.status:
            log('{} nowe zadania'.format(output))
            spiner.Update(value=output)
            s.number_of_exercises = output
            ctr['_STATUS_'].Update(value='Nowe zadania! ({})'.format(
                s.number_of_exercises),
                                   text_color='red')
            przycisk.Update(button_color=('white', 'red'))
            if s.minimized:
                s.minimized = False
                tray.hide()
                ctr.un_hide()
            ctr.bring_to_front()
            if s.sound:
                alarmSound()
            if s.send_email:
                mailer.send_mail(s.where_to_email)
            if s.send_notification:
                notif.send_notification(s.private_key, s.device_ID,
                                        output - s.number_of_exercises)
        elif output == s.number_of_exercises:
            log('Brak nowych zadan')
        else:
            raise Exception(output)
    except Exception as err:
        log(err)
        if output == 'Failed to log: incorrect password':
            stop_checking()
            ctr.Element('_STATUS_').Update('Błędny login/hasło',
                                           text_color='red')
            winsound.PlaySound('SystemQuestion',
                               winsound.SND_ALIAS | winsound.SND_ASYNC)
            tries = 0
            return
        elif tries < 5:
            s.timer = Timer(10, check)
            tries += 1
        else:
            ctr.Element('_STATUS_').Update('Błąd sprawdzania',
                                           text_color='red')
            s.timer = Timer(s.interval * 60, check)
    else:
        tries = 0
        s.timer = Timer(s.interval * 60, check)
    finally:
        if s.status and not s.timer.is_alive():
            #s.timer.cancel()
            s.timer.start()
예제 #3
0
    def send_confirmation_mail(self, plugin_ctx, user_email, username, firstname, lastname, token):
        expir_date = (
            datetime.datetime.now().astimezone() +  # system timezone-aware
            datetime.timedelta(seconds=self._confirmation_token_ttl)
        )
        text = ''
        text += _('Hello')
        text += ',\n\n'
        text += _('thank you for using KonText at {url}.').format(url=plugin_ctx.root_url)
        text += '\n'
        tmp = _(
            'To verify your new account {username} (full name: {firstname} {lastname}) please click the link below')
        text += tmp.format(username=username, firstname=firstname, lastname=lastname)
        text += ':\n\n'
        text += plugin_ctx.create_url('user/sign_up_confirm_email', dict(key=token.value))
        text += '\n\n'
        text += time.strftime(_('The confirmation link will expire on %m/%d/%Y at %H:%M'),
                              expir_date.timetuple())
        text += ' ({0:%Z}, {0:%z})'.format(expir_date)
        text += '\n\n\n-----------------------------------------------\n'
        text += _('This e-mail has been generated automatically - please do not reply to it.')
        text += '\n'

        server = mailing.smtp_factory()
        msg = mailing.message_factory(
            recipients=[user_email], subject=_('KonText sign up confirmation'),
            text=text, reply_to=None)
        return mailing.send_mail(server, msg, [user_email])
예제 #4
0
def send_apply_mail():
    company_name = request.args.get('recruitment')

    user = db.users.find_one({'email': get_jwt_identity()['email']})


    try:
        if 'resume_path' in user:
            student = user['grade'] + user['class'] + str(int(user['number']) + 100)[-2:] + user['name']

            send_mail(student, company_name, user['resume_path'])
            return jsonify({'message': 'Sent mail successfully.'}), 200
        else:
            return abort(400, description='Bad request params.')
    except Exception as e:
        print(str(e))
        abort(400, description='Failed to send mail.')
def reset_password():
    error = None
    if request.method == 'POST':

        g.cur.execute(
            "select * from login_data where email='%s' and club_name='%s'" %
            (request.form['MAILID'], request.form['CLUB_NAME']))
        result = g.cur.fetchall()

        if len(result) == 0:
            session[
                'forget_pass_error'] = "Invalid E-mail and Club Name combination!"
            return redirect(url_for('user_management.login'))

        elif len(result) == 1:
            # send the email with password
            #
            result = result[0]
            subject = "Password reset on VIT Club Portal for %s" % (
                request.form['CLUB_NAME'])
            body = '''\
A password reset was requested for this e-mail on VIT Club Portal.
The current password is
%s
Resetting password is highly recommended.

Thank You
VIT Clubs Portal Team
''' % (str(result[2]))
            receiver = request.form['MAILID']
            mailing.send_mail(subject, body, receiver)
            #
            # handle exceptions
            session[
                'messages'] = "Password reset successful. Password sent to %s." % (
                    request.form['MAILID'])
            return redirect(url_for('user_management.login'))

        else:
            #log the multiple email error
            pass

    # add not allowed to access this page since no get request
    return redirect(url_for('user_management.login'))
def reset_password():
	error=None
	if request.method == 'POST' :
		
		g.cur.execute("select * from login_data where email='%s' and club_name='%s'"%(request.form['MAILID'],request.form['CLUB_NAME']))
		result=g.cur.fetchall()
		
		if len(result)==0:
			session['forget_pass_error'] = "Invalid E-mail and Club Name combination!"
			return redirect(url_for('user_management.login'))
			
		elif len(result)==1:
			# send the email with password
			#
			result=result[0]
			subject="Password reset on VIT Club Portal for %s"%(request.form['CLUB_NAME'])
			body='''\
A password reset was requested for this e-mail on VIT Club Portal.
The current password is
%s
Resetting password is highly recommended.

Thank You
VIT Clubs Portal Team
'''%(str(result[2]))
			receiver=request.form['MAILID']
			mailing.send_mail(subject,body,receiver)
			#
			# handle exceptions
			session['messages'] = "Password reset successful. Password sent to %s."%(request.form['MAILID'])
			return redirect(url_for('user_management.login'))
		
		else:
			#log the multiple email error
			pass
	
	# add not allowed to access this page since no get request
	return redirect(url_for('user_management.login'))
def signup():

    if request.method == 'POST':
        # validate name and email
        # check if email is unique
        club_name = request.form['CLUBN']
        email = request.form['EMAIL']
        #generate unique key as current timestamp
        unique_key = ''.join(
            random.SystemRandom().choice(string.ascii_uppercase +
                                         string.digits +
                                         string.ascii_lowercase)
            for _ in range(32))
        #send mail with unique key and store in db to verify later
        g.cur.execute(
            "insert into pending_verification(club_name,club_mail,unique_key) values('%s','%s','%s')"
            % (club_name, email, unique_key))
        g.db.commit()
        subject = "Signup request from club %s at VIT clubs portal" % (
            club_name)
        body = '''\
A request has been for registration on VIT clubs portal from your e-mail.  To verify you account follow the following steps.

Post the following message to your facebook page.

    Verification of %s on VIT clubs portal.
    Verification code - %s
    Get your club registered today and reach all vitians through VITacademics app.


''' % (club_name, unique_key)
        mailing.send_mail(subject, body, email)

        session[
            'messages'] = '''Your request has been received. Verification is required for registration!
Please follow the steps given in the mail to complete your registration'''

    return redirect(url_for('user_management.login'))
예제 #8
0
                    to_omit = [
                        '<div class="typ">', '<span class="kraj">', '</span>',
                        '</div>', '<div class="txt">'
                    ]
                    for subs in to_omit:
                        ad_header = re.sub(r'{0}'.format(subs), '', ad_header)
                        ad_text = re.sub(r'{0}'.format(subs), '', ad_text)

                    ad = f'{ad_header}\n{ad_text}'
                    ads_found.append(ad)

# If nothing new
if len(ads_found) == 0:
    print('No new ads')
else:
    address = '*****@*****.**'
    subject = 'DSlife notification'
    body = '{0} new ads found for you!'.format(len(ads_found))

    print(body)
    print('Sending mail ...')
    send_mail(address, subject, body)

# Writing last check date
date_file = open(CONFIG['check_file_path'], 'w')
date_file.write(str(max(ad_ids)))
date_file.close()

print('FINISHED')
예제 #9
0
def monitor(client_id):

    # Exe_Info Table contains the Execution Info of customer's stocks converted into dtaframe exe_df

    engine = sq.create_engine(
        "mysql+pymysql://root:password@localhost:3306/ethans1")
    exe_df = pd.read_sql("SELECT * FROM Exe_Info", con=engine)
    # client_df defined again for local use

    client_df = pd.read_sql("SELECT * FROM Client_Info", con=engine)
    # Scrape_Sym is a column combined from Stock_Symbol and Market
    # Eg. Stock_Symbol = 'INFY', Market = 'NS', Scrape_Sym = 'INFY.NS'
    for i in range(len(exe_df)):
        if (exe_df.loc[i, 'Stock_Symbol'] == np.nan) | (exe_df.loc[i, 'Market']
                                                        == np.nan):
            exe_df.loc[i, 'Scrape_Sym'] = np.nan
        else:
            exe_df.loc[i, 'Scrape_Sym'] = str(
                exe_df.loc[i]['Stock_Symbol']) + '.' + str(
                    exe_df.loc[i]['Market'])

# gp_cl contains the groups sorted by Client_ID

    gp_cl = exe_df.groupby('Client_ID')

    # gp_trn does a groupby on gp_cl by transaction 'Buy' or 'Sell' for each clients

    gp_trn = gp_cl.get_group(client_id).groupby('Transaction')

    # If Customer hasn't sold any stock there won't be any 'Sell' group
    # then this logic is implemented
    if gp_trn.ngroups == 1:

        buy_gp = gp_trn.get_group(
            'Buy').reset_index()  # 'Buy' group of a client
        unique_sym_buy = buy_gp['Scrape_Sym'].unique(
        )  # unique stock symbols in 'Buy' Group
        buy_quan_dic = dict()  # dictionary for quantity of stock

        # if stock is bought multiple times then total quantity is sum of all the quantity of bought stocks

        for i in unique_sym_buy:
            for j in range(len(buy_gp)):

                qnt = buy_gp.loc[(buy_gp['Scrape_Sym'] == i),
                                 'Quantity'].agg(sum)
            buy_quan_dic[i] = qnt

        df_dic = dict()  # dictionary to create rep_df

        col = [
            'Stock', 'Market', 'Symbol', 'Active', 'Quantity', 'Hit Price',
            'Current price', 'Open', 'Close', '52 Week High', '52 Week Low'
        ]  # columns of rep_df

        for i in col:
            df_dic[i] = [np.nan]  # Initializing dictionary to np.nan

        symbol_list = unique_sym_buy.tolist(
        )  # list of all the unique stock symbols in 'Buy' Group

        stock_list = list()
        market_list = list()

        # Stock List

        for i in symbol_list:
            for j in range(len(buy_gp)):
                if i in buy_gp.loc[j, ['Scrape_Sym', 'Stock']].values:
                    stock_list.append(
                        buy_gp.loc[j, ['Scrape_Sym', 'Stock']].values[1])
                    break

        # Market List

        market_list = [i[-2:] for i in symbol_list]

        # Active List
        # Checks if stock is active
        # If no 'Sell' Group stock is always active

        active_list = []
        for i in symbol_list:
            active_list.append('Yes')

        # Quantity List

        quantity_list = []
        for i in symbol_list:
            quantity_list.append(buy_quan_dic[i])

        # Hitprice List

        hitprice_list = []
        for i in symbol_list:
            hitprice_list.append(buy_gp.loc[(buy_gp['Scrape_Sym'] == i),
                                            'Hit_Price'].values[0])

        global df_current

        current_price_list = []
        open_list = []
        close_list = []
        week52_high_list = []
        week52_low_list = []
        for i in symbol_list:
            current_price_list.append(df_current.loc[i, 'Current price'])
            open_list.append(df_current.loc[i, 'Open'])
            close_list.append(df_current.loc[i, 'Close'])
            week52_high_list.append(df_current.loc[i, '52 Week High'])
            week52_low_list.append(df_current.loc[i, '52 Week Low'])

        df_dic['Stock'] = stock_list
        df_dic['Market'] = market_list
        df_dic['Symbol'] = symbol_list
        df_dic['Active'] = active_list
        df_dic['Quantity'] = quantity_list
        df_dic['Hit Price'] = hitprice_list
        df_dic['Current price'] = current_price_list
        df_dic['Open'] = open_list
        df_dic['Close'] = close_list
        df_dic['52 Week High'] = week52_high_list
        df_dic['52 Week Low'] = week52_low_list

        rep_df = pd.DataFrame(df_dic, columns=col)

        # prompt only when stock is active and current price is higher than Hit price

        for i in range(len(rep_df)):
            if rep_df.loc[i, 'Active'] == 'Yes':
                if rep_df.loc[i, 'Current price'] > rep_df.loc[i, 'Hit Price']:

                    subject = "Prompt about your Stock"

                    # Email Content to be defined here

                    content = """Current Price of {0} is higher than Hit Price.
                        Hit Price : {1}\n
                        Current price : {2}\n
                        """.format(rep_df.loc[i, 'Symbol'],
                                   rep_df.loc[i, 'Hit Price'],
                                   rep_df.loc[i, 'Current price'])

                    # Note : Emails in the Client_Info table in database are not real for this data

                    email = client_df.loc[(
                        client_df['Client_ID'] == int(client_id)),
                                          'Email'].astype('str')
                    #email = '*****@*****.**'

                    mailing.send_mail(email, subject, content,
                                      0)  # No attachment for monitoring

# If 'Sell' Group exists some calculations remain same but few are changed
# Then the following logic is implemented

    else:
        buy_gp = gp_trn.get_group('Buy').reset_index()  # 'Buy' Group

        sell_gp = gp_trn.get_group('Sell').reset_index()  # 'Sell' Group

        unique_sym_buy = buy_gp['Scrape_Sym'].unique(
        )  # unique stock symbols in 'Buy' Group

        unique_sym_sell = sell_gp['Scrape_Sym'].unique(
        )  # unique stock symbols in 'Sell' Group

        buy_quan_dic = dict()
        for i in unique_sym_buy:
            for j in range(len(buy_gp)):
                qnt = buy_gp.loc[(buy_gp['Scrape_Sym'] == i),
                                 'Quantity'].agg(sum)
            buy_quan_dic[i] = qnt  # holds total quantity for 'Buy' Group

        sell_quan_dic = dict()
        for i in unique_sym_sell:
            for j in range(len(sell_gp)):
                qnt1 = sell_gp.loc[(sell_gp['Scrape_Sym'] == i),
                                   'Quantity'].agg(sum)
            sell_quan_dic[i] = qnt1  # holds total quantity for 'Sell' Group

        current_quantity = dict()

        # if particular stock not sold then current quantity remains same

        for i in buy_quan_dic:
            if i not in sell_quan_dic:
                current_quantity[i] = buy_quan_dic[i]

# if particular stock is sold then current quantity reduces

        for i in sell_quan_dic:
            current_quantity[i] = buy_quan_dic[i] - sell_quan_dic[i]

        df_dic = dict()  # dictionary for creating rep_df

        col = [
            'Stock', 'Market', 'Symbol', 'Active', 'Quantity', 'Hit Price',
            'Current price', 'Open', 'Close', '52 Week High', '52 Week Low'
        ]

        for i in col:
            df_dic[i] = [np.nan]  # Initializing dictionary to np.nan

        symbol_list = unique_sym_buy.tolist(
        )  # if symbol exists in sell group it will surely exist in 'Buy' Group

        # Same as previous case

        stock_list = list()
        market_list = list()
        for i in symbol_list:
            for j in range(len(buy_gp)):
                if i in buy_gp.loc[j, ['Scrape_Sym', 'Stock']].values:
                    stock_list.append(
                        buy_gp.loc[j, ['Scrape_Sym', 'Stock']].values[1])
                    break

        market_list = [i[-2:] for i in symbol_list]

        active_list = []
        for i in symbol_list:
            if current_quantity[i] == 0:
                active_list.append('No')
            else:
                active_list.append('Yes')

        quantity_list = []
        for i in symbol_list:
            quantity_list.append(current_quantity[i])

# Logic for Hit price
# If Customers sells the stock, the new Hit Price will be recorded in Hit Price value if stock quantity is not zero

        hitprice_list = []
        for i in symbol_list:
            # youngest transaction date for 'Buy'
            buy_max_date = buy_gp.loc[(buy_gp['Scrape_Sym'] == i),
                                      'Transaction_Date'].max()
            # youngest transaction date for 'Sell'
            sell_max_date = sell_gp.loc[(sell_gp['Scrape_Sym'] == i),
                                        'Transaction_Date'].max()
            if i not in unique_sym_sell:
                hitprice_list.append(
                    buy_gp.loc[((buy_gp['Scrape_Sym'] == i) &
                                (buy_gp['Transaction_Date'] == buy_max_date)),
                               'Hit_Price'].values[0]
                )  # if not sold then the Hit price mentioned in the youngest transction in 'Buy' is the current Hit Price
            else:
                if buy_max_date > sell_max_date:
                    hitprice_list.append(
                        buy_gp.loc[(
                            (buy_gp['Scrape_Sym'] == i) &
                            (buy_gp['Transaction_Date'] == buy_max_date)),
                                   'Hit_Price'].values[0]
                    )  # if sold but youngest transaction is 'Buy'
                else:
                    hitprice_list.append(
                        sell_gp.loc[(
                            (sell_gp['Scrape_Sym'] == i) &
                            (sell_gp['Transaction_Date'] == sell_max_date)),
                                    'Hit_Price'].values[0]
                    )  # if 'Sell' is the youngest transaction

        current_price_list = []
        open_list = []
        close_list = []
        week52_high_list = []
        week52_low_list = []
        for i in symbol_list:
            current_price_list.append(df_current.loc[i, 'Current price'])
            open_list.append(df_current.loc[i, 'Open'])
            close_list.append(df_current.loc[i, 'Close'])
            week52_high_list.append(df_current.loc[i, '52 Week High'])
            week52_low_list.append(df_current.loc[i, '52 Week Low'])

        df_dic['Stock'] = stock_list
        df_dic['Market'] = market_list
        df_dic['Symbol'] = symbol_list
        df_dic['Active'] = active_list
        df_dic['Quantity'] = quantity_list
        df_dic['Hit Price'] = hitprice_list
        df_dic['Current price'] = current_price_list
        df_dic['Open'] = open_list
        df_dic['Close'] = close_list
        df_dic['52 Week High'] = week52_high_list
        df_dic['52 Week Low'] = week52_low_list

        rep_df = pd.DataFrame(df_dic, columns=col)

        # if stock is active and current price > Hit price send the prompt

        for i in range(len(rep_df)):
            if rep_df.loc[i, 'Active'] == 'Yes':
                if rep_df.loc[i, 'Current price'] > rep_df.loc[i, 'Hit Price']:

                    subject = "Prompt about your Stock"

                    content = """Current Price of {0} is higher than Hit Price.
                        Hit Price : {1}\n
                        Current price : {2}\n
                        """.format(rep_df.loc[i, 'Symbol'],
                                   rep_df.loc[i, 'Hit Price'],
                                   rep_df.loc[i, 'Current price'])

                    # print("Current Price of {0} is higher than Stock Price. Contact the client {1}".format(
                    #     rep_df.loc[i, 'Symbol'], client_id))
                    email = client_df.loc[(
                        client_df['Client_ID'] == int(client_id)),
                                          'Email'].astype('str')
                    #email = '*****@*****.**'

                    mailing.send_mail(email, subject, content, 0)