Exemplo n.º 1
0
def register():
    if request.method == 'POST':
        logger.info('Registration POST: %s%s%s'\
                    % (request.form['email'], \
                       request.form['name'],\
                       request.form['tel']))
        user = User()
        user.name = request.form.get('name', None)
        user.email = request.form.get('email', None)
        user.tel = request.form.get('tel', None)
        user.msg = request.form.get('message', None)

        if not user.is_valid:
            logger.error('No valid form. Request:%s' % request)
            return jsonify(False)

        try:
            user.save()
        except:
            logger.error('Don\'t save in base. Request:%s' % request)
            return jsonify('Error')
        
        logger.info('Register:Done!')
        send_email(user)
        return jsonify(True)

    else:
        return jsonify(False)
Exemplo n.º 2
0
def main():
    # Create the client
    yesterday = datetime.date.today() - datetime.timedelta(days=1)
    hc = HillsClient(yesterday, days=2)

    # File names
    fname = str(hc.get_date()).replace('/', '-')
    fname_csv = fname + '.csv'
    fname_log = fname + '.log'

    # Logging
    level = logging.DEBUG
    root = logging.getLogger()
    root.setLevel(level)

    # Run the scraper.
    all_recs = hc.run()

    # Write the arrest records to file.
    with open(fname_csv, "w") as f:
        write_csv(f, all_recs)

    # Send the email with results attached.
    send_email(config.EMAIL_TO,
               subject="Hillsborough County Arrests",
               attachment=fname_csv)
Exemplo n.º 3
0
def success():
    if request.method == 'POST':  # the function process' only "POST" requests
        email = request.form[
            "email_name"]  # syntax for capturing value sent to the webserver
        height = request.form["height_name"]
        # print(email, height)

        # print(request.form)
        # print(db.session.query(Data).filter(Data.email_==email).count())  # checks if the email address is already in the database;\
        # if the result is "0" the email is not in the database
        # "pip install psycopg2" + "pip install Flask-SQLAlchemy"\
        # in order to access the PostreSQL database
        if db.session.query(Data).filter(Data.email_ == email).count(
        ) == 0:  # if the email is not in the data base it adds is
            data = Data(email, height)
            db.session.add(data)
            db.session.commit()
            average_height = db.session.query(func.avg(Data.height_)).scalar()
            average_height = round(average_height)
            count = db.session.query(Data.height_).count()
            send_email(email, height, average_height, count)
            #print(average_height)
            return render_template("success.html")
    # if the email is in the data base it returns to the homepage
    return render_template(
        "index.html",
        text="Seems like we've got something from that email address already!")
Exemplo n.º 4
0
def wish(mail,dob,name):
	while  True:
		d = db.session.query(Data.id).all()
		if d != None:
			for id_ in d:
				date_ = db.session.query(Data.date).filter(Data.id == id_[0]).scalar()
				
				if date_.year==dt.now().year and date_.month ==dt.now().month and date_.day ==dt.now().day and dt.now().hour== 0 and dt.now().minute == 0 and dt.now().second ==0:
					name = db.session.query(Data.name).filter(Data.id==id_[0]).scalar()
					mail = db.session.query(Data.email).filter(Data.id==id_[0]).scalar()
					send_email(mail,name)
Exemplo n.º 5
0
def recup_entree():
    """La fonction recup_entree récupère les données dans les entry box,
    les attribus à des variables, qui elles mêmes sont attribuées aux 
    variables utilisés dans send_email.py, importer de facon modulaire,
    pour etre utiliser en tant que id, pw etc... dans le mail final"""
    s_e = entry_from.get()
    r_e = entry_to.get()
    pw = entry_mdp.get()
    msg = entry_message.get()

    send_mail.send_email(s_e, r_e, pw, msg)
    print(f"from ", s_e, " --- to ", r_e, " --- txt : ", r_e, msg,
          "\n\n time = ", time)
Exemplo n.º 6
0
def main():
    today = str(datetime.date.today())
    year, month, day = [int(x) for x in today.split("-")]
    month_2 = abs(month - 6) % 12 + 1
    start_date = datetime.datetime(year if month - 6 > 0 else year - 1,
                                   month_2, 1)
    end_date = datetime.datetime(year, month, 15)
    receiver_email = '*****@*****.**'

    symbols, names = get_symbols()
    if 'results.csv' in os.listdir():
        os.remove('results.csv')
    for s in range(len(symbols)):
        analyze_stock(symbols[s], names[s], start_date, end_date)
    send_email(receiver_email)
Exemplo n.º 7
0
def success():
    if request.method == "POST":
        email = request.form['email']
        height = request.form['height']
       
        if(db.session.query(Data).filter(Data.email_ == email).count() >= 1):
            return render_template("index.html",text="Seems like email you enter is duplicate. please try again")
        data=Data(email,height)
        db.session.add(data)
        avg_height = db.session.query(func.avg(Data.height_)).scalar()
        avg_height = round(avg_height,1)
        count=db.session.query(Data.height_).count()
        send_email(email,height,avg_height,count)
        db.session.commit()
    return render_template("success.html")
Exemplo n.º 8
0
def callback(ch, method, properties, body):
    data = json.loads(body)

    print "[>] Received '%s' (try: %d)" % (data.get('mail_from'), 1 + int(properties.priority))

    if properties.priority >= max_retries - 1: # example handling retries
        ch.basic_ack(delivery_tag=method.delivery_tag)
        print "[!] '%s' rejected after %d retries" % (data.get('mail_from'), 1 + int(properties.priority))
    else:
        try:
            mail_from = data.get("mail_from")
            mail_to = data.get("mail_to")
            mail_body = data.get("mail_body")
            # print "data :", data
            res = send_email(mail_from, mail_to, mail_body)
            if res:
                print "Error in sending mail"
            else:
                # update record entry for mail sent
                print "Mail sent"

            # time.sleep(len(data.get('keyword')))
            ch.basic_ack(delivery_tag=method.delivery_tag)
            print "[+] Done"

        except:
            print "Exception in sending mail from queue"
Exemplo n.º 9
0
def email_page():
	if request.method == "POST":
		e_usr = request.form["from_email"]
		e_pwd = request.form["password"]
		e_to = request.form["to_email"]
		e_sub = request.form["title"]
		e_msg = request.form["message"]
		try:
            #username, password, to email, subject, message
			send_email(e_usr, e_pwd, e_to, e_sub, e_msg)
			print("Email Sent...")
			return redirect("/email")
		except:
			print("Error while sending...")
			return redirect("/email")
	return render_template("email.html")
Exemplo n.º 10
0
def recieve_question():
    if request.method == "POST":
        try:

            data = request.data
            data = json.loads(data)
            question = data['data']
            recepient_user_email = data['email_id']

            pdf_generation = pdf_generator(question, 'related_questions.pdf')
            pdf_generation.pdf_generator()

            attachment = 'related_questions.pdf'
            sending_mails = send_email(
                email_creds.email_creds["username"],
                email_creds.email_creds["password"],
                recepient_user_email,
                "related questions",
                "question related to asked question",
                fromaddr=email_creds.email_creds["username"],
                attachment=attachment)
            sending_mails.send_email()

            return "Mail sent"

        except:
            logging.exception("message")
Exemplo n.º 11
0
 def open(self, path, flags):
     full_path = self._full_path(path)
     uid, gid, pid = fuse_get_context()
     fd = open("users.reg", "r")
     users = json.load(fd)
     fd.close()
     if (uid != self.idroot):
         contact = users[str(uid)]
         fd = open("activation.json", "r")
         data = json.load(fd)
         fd.close()
         info = data[str(contact)]
         if str(full_path) not in info["files"]:
             send_mail.send_email(str(contact), full_path)
             raise FuseOSError(errno.EACCES)
         else:
             return os.open(full_path, flags)
     return os.open(full_path, flags)
Exemplo n.º 12
0
def submit_file():
    if request.method == 'POST':
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']
        if customer == '' or dealer == '':
            return render_template('index.html',
                                   message='Please enter required fields')
        if db.session.query(feedback_form).filter(
                feedback_form.customer == customer).count() == 0:
            data = feedback_form(customer, dealer, rating, comments)
            db.session.add(data)
            db.session.commit()
            send_email(customer, dealer, rating, comments)
            return render_template('success.html')
        return render_template('index.html',
                               message='You have already submitted feedback!')
 def share_file(self, group, file):
     html = check_login()
     file_name = os.path.basename(file)
     user = cherrypy.session['cur_user']
     uemail = [db_handler.fetch_member_email(group)]
     keys = encrypt_handler.get_aggre_key(group)
     for i,j in zip(range(0,len(uemail[0].keys())),range(1,len(keys))):
        out = db_handler.file_share(uemail[0].keys()[i],file_name,keys[j],group)
     skey = keys[0]
     msg = " %s shared %s with you! key = %s " % (user,file_name,skey)
     if out != "Share Exists!":
      for u in uemail:
             send_mail.send_email(u.values(),msg)
             html += """ File Shared, \nResult : %s """ % out
     else:
             html += """ File Sharing Failed, \nResult : %s """ % out
     html += footer
     return html
Exemplo n.º 14
0
def submit():
    if request.method == "POST":
        customer = request.form['cname']
        email = request.form['email']
        dealer = request.form['dname']
        rating = request.form['rate']
        comment = request.form['message']
        if (not customer) or (not dealer) or (not email):
            return render_template("index.html", message="Please enter "
                                                         "required fields")
        if db.session.query(Feedback).filter(Feedback.email == email).count() == 0:
            data = Feedback(customer, email, dealer, rating, comment)
            db.session.add(data)
            db.session.commit()
            send_email(customer, dealer, rating, comment, email)
            return render_template("success.html")
        return render_template("index.html", message="You have already submitted")
    else:
        redirect(url_for('hello_world'), message='')
Exemplo n.º 15
0
 def share_file(self, group, file):
     html = check_login()
     file_name = os.path.basename(file)
     user = cherrypy.session['cur_user']
     uemail = [db_handler.fetch_member_email(group)]
     keys = encrypt_handler.get_aggre_key(group)
     for i, j in zip(range(0, len(uemail[0].keys())), range(1, len(keys))):
         out = db_handler.file_share(uemail[0].keys()[i], file_name,
                                     keys[j], group)
     skey = keys[0]
     msg = " %s shared %s with you! key = %s " % (user, file_name, skey)
     if out != "Share Exists!":
         for u in uemail:
             send_mail.send_email(u.values(), msg)
             html += """ File Shared, \nResult : %s """ % out
     else:
         html += """ File Sharing Failed, \nResult : %s """ % out
     html += footer
     return html
Exemplo n.º 16
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        editor = request.form['IDE/Text Editor']
        rating = request.form['rating']
        comments = request.form['comments']
        # print(customer, editor, rating, comments)
        if customer == '' or editor == '':
            return render_template('index.html',
                                   message="Please enter required fields.")
        if db.session.query(feedback).filter(
                feedback.customer == customer).count() == 0:
            data = feedback(customer, editor, rating, comments)
            db.session.add(data)
            db.session.commit()
            send_email(customer, editor, rating, comments)
            return render_template('success.html')
        return render_template(
            'index.html', message="You have already submitted the feedback.")
Exemplo n.º 17
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']
        # print(customer, dealer, rating, comments)
        # return render_template('success.html')

    # make sure both customer and dealer input are not empty
    if customer == '' or dealer == '':
        return render_template('index.html', message="Please enter required fields")
    # make that customer does not exist before we added into database
    if db.session.query(Feedback).filter(Feedback.customer == customer).count() == 0:
        data = Feedback(customer, dealer, rating, comments)
        db.session.add(data)
        db.session.commit()
        send_email(customer, dealer, rating, comments)
        return render_template('success.html')
    return render_template('index.html', message="You have already submitted feedback")
Exemplo n.º 18
0
def main(q_key, who_are_u, max_result):

    get_information_arxiv(q_key=q_key, f_max_results=max_result)
    q_key = q_key.replace(" ", "_")
    arr = os.listdir(q_key)

    for i in range(len(arr)):
        pdfparser(data=q_key + "/" + arr[i], pdf_name=arr[i], dic_q_key=q_key)

    arr_txt = os.listdir(q_key + "_txt")
    print(arr_txt)

    liste = []
    pdf_link_lst = []
    path_z = str(q_key + "_txt")

    for i, item in enumerate(arr_txt):
        ozet = lex_summary_2(file_path=path_z + "/" + arr_txt[i])
        print(ozet)
        pdf_link = str(q_key + "_txt" + "/" + arr_txt[i])
        liste.append(ozet)
        pdf_link_lst.append(pdf_link)
        print("-------")

    dataframe = pd.DataFrame({
        "text": liste,
        "pdf_link": pdf_link_lst,
    })
    print(dataframe)

    pdf_name = create_pdf_page(full_name=q_key,
                               address_parts=[who_are_u],
                               metin=dataframe)

    send_email(gmail_user="******",
               gmail_pwd=" ",
               send_to=who_are_u,
               subject=q_key + " özetler",
               text="Akademik özet geç ",
               path=pdf_name)
Exemplo n.º 19
0
def submit():
    if request.method == "POST":
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']

        #print(customer, dealer, rating, comments)
        # check customer and dealer fields are not empty
        if customer == '' or dealer == '':
            return render_template('index.html', message='Please enter the required fields!')
        
        # enable customer to give feedback only once
        if db.session.query(Feedback).filter(Feedback.customer == customer).count() == 0:
            data = Feedback(customer, dealer,rating,comments)
            db.session.add(data)
            db.session.commit()

            # send email
            send_email(customer, dealer, rating, comments)
            return render_template('success.html')
        return render_template('index.html', message='You have already submitted feedback!')
def repeat_task():
    connections_list = shared_module.get_config_var('connections')

    for connection in connections_list:
        connection_in_str = "".join(connection)

        ssh_obj = Ssh_Util(*connection)
        command = "ls -l " + connection[
            3] + " | awk -F ' ' '{print $6\" \"$7\" \"$8}'"
        command_output, result_flag = ssh_obj.execute_command(command)

        if result_flag:
            last_timestamp = timestamp_dict.get(connection_in_str)
            print(last_timestamp)
            if last_timestamp:
                if command_output[0] != last_timestamp:

                    #connecting and downloading the target remote file
                    ssh_obj.download_file()

                    #parsing and storing the data into mongodb database
                    ssh_obj.parsefile(connection_in_str, connection[4])

                    #sendingthe mail to user with updated file as attachement
                    mail_inst = send_email(connection_in_str, connection[4])
                    mail_inst.send_mail_alert()
                    timestamp_dict[connection_in_str] = command_output[0]

                else:
                    print("file didn't modified since %s" %
                          (timestamp_dict.get(connection_in_str)))
            else:
                timestamp_dict[connection_in_str] = command_output[0]
                print(timestamp_dict)
        else:
            if command_output:
                print("there is problem while executing the commanda: %s" %
                      (command_output[0]))
            else:
                print(
                    "there is problem while executing the command please check the connection"
                )

        print(time.ctime())
Exemplo n.º 21
0
        """
        db = self.client[db_name]
        colls = db.collection_names()
        colls = set(colls).difference(set(filtered))
        db_error = list()
        for coll in colls:
            db[coll].distinct('meta_updated')
            result = db[coll].count({'meta_updated': {'$gte': self.last_date}})
            if result == 0:
                # slack alarm
                db_error.append(coll)
        self.errors.update({db_name: db_error})

    def __del__(self):
        self.client.close()


if __name__ == "__main__":
    cfg_file = sys.argv[1]
    conf = ConfigParser.ConfigParser()
    conf.read(cfg_file)
    monitor = MongoMonitor()
    for db in ['perimit', 'permit', 'cpdaily', 'jediDB', 'price']:
        filtered = list()
        if conf.has_section(db):
            filtered = conf.items(db)[0][1].replace('[', '').replace(
                ']', '').replace(' ', '').split(',')
        monitor.check_insert_stat(db, filtered)
    send_email(
        json.dumps(monitor.errors) + "\r\n 表名与数据源关系参照: http://gitlab.****")
Exemplo n.º 22
0
       logging.info("waiting for next  user!!")
       time.sleep(random.randrange(60, 180, 10))
    else :
          break

time.sleep(random.randrange(1, 10, 1))
logging.info("user all done!!")
display.stop()


### Send Email on monday 

#today_week = datetime.date.today().strftime("%w")

if today_week == '1' :
     ### read for log last 47 line of mail body
     body = '' 
     try:
             with open('p2p_login_with_reply.log') as fp:
              data = fp.readlines()
              for i in data[-47:]:
               body  = body + i
     
     finally:
         fp.close()
     
     
     send_mail.send_email('p2plogin auto loging',body)


Exemplo n.º 23
0
# -*- coding: utf-8 -*-

from scraper import OLXScraper
from database import get_offers, update_offers_table
from send_mail import create_email_content, send_email
from config import SMTP_SERVER, PORT, SERVER_LOGIN, SERVER_PASSWORD, SENDER, RECEIVERS, SUBJECT, MAX_PRICE

if __name__ == '__main__':
    scraper = OLXScraper()
    offers = scraper.get_offers()
    update_offers_table(offers)
    offers = get_offers(max_price=MAX_PRICE)
    content = create_email_content(offers)
    send_email(smtp_server=SMTP_SERVER,
               port=PORT,
               server_login=SERVER_LOGIN,
               server_password=SERVER_PASSWORD,
               sender=SENDER,
               receivers=RECEIVERS,
               message=content,
               subject=SUBJECT)
Exemplo n.º 24
0
                      ' Custom Region', id)
            elif (st == "40p"):
                #bplot(df,id,nme)
                andvil1, andviu1, andvin1, andvia1, sdf1 = predict(df, trshld)
                aplot(andvil1, andviu1, andvin1, andvia1, sdf1,
                      ' Custom Region', id)
            elif (st == "lm"):
                print("No data is available for current month for " + nme)
                continue

        print(unique_mail_dict)
        print(unique_mail_farm_dict)
        unique_mail_list = list(set(mail))
        print("Length of mail: " + str(len(mail)))
        print("Length of unique_mail_list: " + str(len(unique_mail_list)))
        status = send_mail.send_email(unique_mail_list, unique_mail_farm_dict)
        print("results -----------")
        print("deleting the .png files")
        delete_image_files()
        if status == False:
            print(
                'UNABLE TO SEND EMAILs...could not retrieve SMTP server details'
            )
            send_mail.write_to_file(
                'ERROR-EMAIL',
                'UNABLE TO SEND EMAILs...could not retrieve SMTP server details'
            )
        else:
            print(status)
            send_mail.write_to_file('SUCCESS-EMAIL', str(status))
Exemplo n.º 25
0
        output_file = 'processed/' + name_file 

        # PASO 4: Cambia el estado de la imagen procesada en la base de datos

        update_processed_files(
            connection,
            cursor,
            data['image_pk'], 
            data['design_pk'],
            output_file)
        
        # PASO 5: Envía el email de la imagen procesada
        
        send_email(
            EMAIL_PASSWORD,
            data['email'],
            data['creator'],
            name_file
        )

        print(
            '{} \t Diseño: "{}" procesado con exito en [{}] con ({},{})px'.format(
                datetime.now(), data['image'], SIZING_METHOD, default_width, default_height
            )) 
         
    except Exception as error:
        
        print("{} \t Error en diseño: {} -> {}"
            .format(datetime.now(), data['image'], error))

close_connection(cursor)
Exemplo n.º 26
0
        for line in open('mailing list.txt', 'r'):
            (email, name) = line.split(',')
            emails[email] = name.strip()
    except FileNotFoundError as err:
        print(err)

    return emails


def get_scheduler():
    try:
        scheduler_file = open('scheduler.txt', 'r')
        schedule = scheduler_file.read()

    except FileNotFoundError as err:
        print(err)

    return schedule


if __name__ == '__main__':
    emails = get_emails()

    schedule = get_scheduler()

    forecast = weather.get_weather_forecast()

    send_mail.send_email(emails, schedule, forecast)

    print('mail sent!')
Exemplo n.º 27
0
the_year = stock_season_report(today.year, season, 'undefined',
                               'undefined')  ## the year season

s_df = the_year.merge(
    last_year,
    how='inner',
    on=['公司代號', '公司簡稱'],
    suffixes=('_%s' % str(today.year),
              '_%s' % str(today.year - 1))).copy()  ## merge 2021_Q3 & 2020_Q3

#### (累計EPS / 去年累計EPS - 1) * 100%
s_df['EPS成長%'] = (((s_df.iloc[:, 2] - (s_df.iloc[:, 3]).abs()) /
                   (s_df.iloc[:, 3]).abs()) * 100).round(
                       2)  ## 計算成長% (2021- 2020) /2020 * 100%

#s_df['EPS成長%'] = (( (s_df['Q3累積盈餘_2021'] - (s_df['Q3累積盈餘_2020']).abs() )/ (s_df['Q3累積盈餘_2020']).abs() ) * 100 ).round(2)

match_row = s_df.sort_values(by=['EPS成長%'], ascending=False).copy()

if time.strftime("%H:%M:%S", time.localtime()) > mail_time:
    #match_row.to_html('hot_news_link.log')
    if not match_row.empty:
        body = match_row.to_html(escape=False)
        #log_date = datetime.date.today().strftime("%Y-%m-%d")
        send_mail.send_email(
            '{year} stock_Q{season}_report'.format(year=today.year,
                                                   season=season), body)
else:
    print(match_row.to_string(index=False))
       logging.info("waiting for next  user!!")
       time.sleep(random.randrange(60, 180, 10))
    else :
          break

time.sleep(random.randrange(1, 10, 1))
logging.info("user all done!!")
display.stop()


### Send Email on monday 

#today_week = datetime.date.today().strftime("%w")

#if today_week == '1' :
     ### read for log last 47 line of mail body
body = '' 
try:
      with open('p2p_login_with_reply_drama.log') as fp:
           data = fp.readlines()
           for i in data[-47:]:
             body  = body + i
     
finally:
         fp.close()
     
     
send_mail.send_email('p2plogin_drama auto loging',body)


Exemplo n.º 29
0
       time.sleep(random.randrange(60, 180, 10))
    else :
          break

time.sleep(random.randrange(1, 10, 1))
logging.info("user all done!!")
display.stop()


### Send Email on monday 

#today_week = datetime.date.today().strftime("%w")

if today_week == '1' :
     ### read for log last 47 line of mail body
     body = ''
     log_date = datetime.date.today().strftime("%Y-%m-%d")
     try:
          with open('awa_login_with_reply.log') as fp:
            data = fp.readlines()
            for i in data[-100:]:
              if log_date in i:  ## read only  today log 
                  body  = body + i
     
     finally:
         fp.close()
     
     
     send_mail.send_email('awalogin auto loging',body)

Exemplo n.º 30
0
      
      else : 
            u_num = len(myusername_list) ## seat is all full


      ### Waiting next trun user

      if u_num < (len(myusername_list)-1):
           logging.info("waiting for next  user!!")
           time.sleep(random.randrange(60, 180, 10))
      else :
           break
      

web.quit()
display.stop()

body = ''
log_date = datetime.date.today().strftime("%Y-%m-%d")
try:
    with open('kingbus.log') as fp:
      data = fp.readlines()
      for i in data[-100:]:
          if log_date in i:  ## read only  today log 
             body  = body + i

finally:
    fp.close()

send_mail.send_email('kingbus auto booking ',body)
Exemplo n.º 31
0
def main(filePar):
    """Lancia l'esperimento.

    In un file ricopia il file della rete ed il file dei parametri.
    Salva anche un grafico della rete.

    Salva le prestazioni medie della rete durante i fold ed invia una mail con i
    risultati a esperimento concluso.


    """
    # leggo il file della rete neurale come stringa
    with open(filePar, 'r') as ymlfile:
        cfg = yaml.load(ymlfile,  Loader=yaml.FullLoader)
        pathNetwork = cfg["Alg"]["path"]

        nomeFileNetwork = cfg["Alg"]["file"]

        nDirOut = cfg["file"]["outputDir"]

    nomeFileRete=pathNetwork + nomeFileNetwork +".py"
    print(nomeFileRete)
    # leggo il file della rete neurale come stringa
    fin = open(nomeFileRete, "r")
    file_rete = fin.readlines()
    fin.close()

    # leggo il file dei parametri come stringa
    fin = open(filePar, "r")
    parametri = fin.readlines()
    fin.close()


    # Genera il nome del file di output
    nFOut = local_lib.nomeFileOut(filePar)

    # controlla che esista la dir, altrimenti la crea

    if not os.path.exists(nDirOut):
        os.makedirs(nDirOut)

    nFilePre = os.path.join(nDirOut, nFOut)

    # apre il file
    #>>>>>>>>>>>>>>>>>>>>>>
    with open(nFilePre + "_descr_rete.net", "w") as f:
        # inserisce le informazioni nel file dei risultati

        #=======================================================
        # scrive le stringhe del file della rete e dei parametri
        f.write("File_rete\n")
        f.write("".join(file_rete))

        f.write("Parametri_passati\n")
        f.write("".join(parametri))
        # =======================================================

    print("carica il dataset e crea la lista di indici del k-fold")
    df, fold = local_lib.prepara_ambiente(filePar)

    # esegue il test ottenendo le medie
    # dei parametri di output
    print("eseguo l'esperimento")

    ### tempo di run <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    start_time = time.time()

    M_acc, M_prec, M_rec = re.test(df, fold, filePar )

    ### TEMPO DI run <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    runtime = (time.time() - start_time)

    # scrivere i risultati in un file
    #nFOut = local_lib.nomeFileOut(filePar)

    # apre il file
    # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    with open(nFilePre + "_totale_training.csv", "w") as f:
        f.write("Tempo totale di run (in sec)" + ","+ str(runtime) + "\n")
        f.write("Media Accuracy"+ "," + str(M_acc)+ "\n")
        f.write("Media Precision"+","+ str(M_prec)+ "\n")
        f.write("Media Recall"+","+ str(M_rec)+ "\n")


    # email risultati
    subject = "Esperimenti prova " + nFilePre
    body = "finiti tutti gli esperimenti" + "\n"
    body +=  "Accuracy media :" + str( M_acc) + "\n"
    body +=  "Precision media:" + str( M_prec) + "\n"
    body +=  "Recall media:" + str( M_rec) + "\n"

    sm.send_email(dm.user, dm.pwd, dm.recipient, subject, body)
    web.quit()

    ### Waiting next trun user
    if num < (len(myusername_list) - 1):
        logging.info("waiting for next  user!!")
        time.sleep(random.randrange(60, 180, 10))
    else:
        break

time.sleep(random.randrange(1, 10, 1))
logging.info("user all done!!")
display.stop()

### Send Email on monday

#today_week = datetime.date.today().strftime("%w")

#if today_week == '1' :
### read for log last 47 line of mail body
body = ''
try:
    with open('p2p_login_with_reply_software.log') as fp:
        data = fp.readlines()
        for i in data[-47:]:
            body = body + i

finally:
    fp.close()

send_mail.send_email('p2plogin_software auto loging', body)