Esempio n. 1
0
def parseLine(logfile):
    parseFileGenerator = parseFile(logfile)

    for line in parseFileGenerator:
        item = line.replace('[', "")
        items = item.split("]")
        incidentTime = items[0]
        logName = items[1]
        levelName = items[2]
        errorMessage = items[3]

        if levelName == "ERROR":
            print(line.rstrip('\n'))
            global GLOBAL_TOTAL
            GLOBAL_TOTAL += 1
            message = """
	##SERVER ALERT
	##Received: {incidentdate}
	##Total Alerts: {total:7d}
	##Log Name: {log}
	##The Log Error is {m}""".format(incidentdate=incidentTime,
                                  total=GLOBAL_TOTAL,
                                  log=logName,
                                  m=errorMessage)
            send_email(message)
Esempio n. 2
0
def form():
    #status = True
    status = get_status()  #鍵の状態を読み取り

    if request.method == 'POST':  #IDとパスワードの入力を受けた時
        user = session.query(User).get(
            request.form["id"].strip())  #データベースからIDが一致するものを検索
        if user and hash(str(request.form['pwd'])) == user.password:
            if status == True:
                open_key()  #鍵を開ける。
                #print("open")
                status = get_status()

                #status = False
                if status == True:  #万が一装置が正常に動かなかった場合
                    return render_template('message.html',
                                           message='装置にエラーが発生しました。至急確認してください。')
                else:
                    send_email(user.email, 'note')  #ロックが解除された旨をメールで通知
                    return render_template('opened.html')
            else:
                return render_template('already_opened.html')
        else:
            return render_template('not_opened.html', status="ロックされていません!!")

    else:
        status = get_status()
        if status == True:
            return render_template('mainpage.html', status="OK")
        else:
            return render_template('mainpage.html', status="ロックされていません!!")
Esempio n. 3
0
def to_fir(ipa_path, ipa_plist):
    info = info_plist[build_tag]['fir']
    if len(info['token']) > 0:
        dic = {
            'bundle_id': ipa_plist['CFBundleIdentifier'],
            'name': ipa_plist['CFBundleName'],
            'version': ipa_plist['CFBundleShortVersionString'],
            'build': ipa_plist['CFBundleVersion'],
            'api_token': info['token'],
            'type': info['type'],
            'changelog': '',
            'file': ipa_path
        }
        try:
            t = UploadToFir(dic)
        except Exception as e:
            pass
        else:
            try:
                t.get_fir_apps()
            except Exception as e:
                pass
            else:
                send_email(t.app_address)
            finally:
                pass
        finally:
            pass
def reset_password():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    form = ResetPasswordReq()
    if form.validate_on_submit():
        email = form.email.data
        user = User.query.filter_by(email=email).first()
        if user:
            token = user.verify_expiration_token()
            db.session.commit()
            send_email(
                _l('Request change password'),
                sender=current_app.config['ADMINS'][0],
                recipients=[user.email],
                text_body=render_template(
                    'email/reset_password.txt',
                    token=token),
                html_body=render_template(
                    'email/reset_password.html',
                    token=token)
            )
            flash("Email sent, check your mail now!", "info")
            return redirect(url_for('auth.login'))
        flash("This email not registered", "info")
    return render_template('auth/reset_password_req.html', form=form)
Esempio n. 5
0
def mail_notify(result, config):
    content = generate_mail_contents(result)

    if content:
        send_email(config.get('smtp', 'email'), config.get('smtp', 'password'),
                   config.get('smtp', 'mail_title'), content,
                   config.get('smtp', 'mail_to'),
                   config.get('smtp', 'mail_server'))
 def email_booking(self):
     self.to = "{0}, ".format(self.search_customer_layout.customer_view.model().data(self.search_customer_layout.index[12]))
     self.subject = "You booking for {0}".format(self.model.index(self.treatment_combobox.currentIndex(),1).data())
     self.body = "Hi {2}, \n \n Your {3} appointment with Gentle Effects is booked for {4} at {5}. I look forward to seeing you then. \n \n Please have these handy when calling - Personal ID: {0}, Appointment ID: {1} \n  \n Kind Regards, \n Paula Lawrence \n Aestetic Nurse Practioner \n \n".format(self.search_customer_layout.customer_view.model().data(self.search_customer_layout.index[0]),
                                                                                                                                                                                                                                                                                                  self.app_id,
                                                                                                                                                                                                                                                                                                  self.search_customer_layout.customer_view.model().data(self.search_customer_layout.index[1]),
                                                                                                                                                                                                                                                                                                  self.model.index(self.treatment_combobox.currentIndex(),1).data(),
                                                                                                                                                                                                                                                                                                  self.date_selector.selectedDate().toString(Qt.TextDate),
                                                                                                                                                                                                                                                                                                  self.time_selector.time().toString(Qt.TextDate))
     send_email(self.to,self.subject,self.body)
Esempio n. 7
0
def process_statistics():

    # print statistics
    daily_stats = pprint.pformat(boiler_activity)
    boilog.info(daily_stats)
    send_email(EMAIL_TO, EMAIL_SUBJECT, 'Boiler statistics summary:%s\n\n' % daily_stats)

    global POLL_STATISTICS_SECS
    stat_thread = threading.Timer(POLL_STATISTICS_SECS, process_statistics)
    stat_thread.setDaemon(True)
    stat_thread.start()
Esempio n. 8
0
def to_pgyer(ipa_path):
    info = info_plist[build_tag]['pgyer']
    if len(info['api_key']) > 0 and len(info['api_key']) > 0:
        try:
            address = upload_to_pgyer(ipa_path, info['api_key'],
                                      info['user_key'], info['type'],
                                      info['password'], '')

        except Exception as e:
            pass
        else:
            send_email(address)
Esempio n. 9
0
def success():
    if request.method=='POST':
        email=request.form["email_name"]
        height=request.form["height_name"]
        try:
            create_table()
            insert_data(email,height)
            avg_height=calc_avg()
            count=get_count()
            send_email(email,height,avg_height,count)
            return render_template("success.html")
        except:
            return render_template("index.html", text="Email address already present.!!")
Esempio n. 10
0
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form=PasswordResetRequestForm()
    if form.validate_on_submit():
        user=User.query.filter_by(email=form.email.data).first()
        if user:
           token=user.generate_reset_token()
           send_email(user.email,
                      'Reset Your Password','auth/email/reset_password.txt',
                      user=user,token=token,next=request.args.get('next'))
           flash('An email with instructions to reset your password has been sent to you.')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html',form=form)
Esempio n. 11
0
def register():
    form=RegistrationForm()
    if form.validate_on_submit():
        user=User(email=form.email.data,
                  username=form.username.data,
                  password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token=user.generate_confirmation_token()
        send_email(user.email,'Confirm Your Account','auth/email/comfirm',user=user,token=token)
        flash('A confirmation email has been sent to you by email.')
        return redirect(url_for('main_index'))
        #return redirect(url_for('auth.login'))
    return  render_template('auth/register.html',form=form)
Esempio n. 12
0
def selfemailchanges(flags):
	# print flags
	flag = flags[1]
	current_loc = os.path.realpath('./')
	for i, flag_target in enumerate(_GIT_REPOS_FLAGS):
		if ( flag == flag_target):
			itarget = i
			break
	# print i, _GIT_REPOS_MASTER[i]	
	os.chdir(  _GIT_REPOS_MASTER[itarget] )
	os.system('git show --pretty="format:" --name-only master > tempchangedfile.txt')
	name_of_file= flag+'_changes_file'
	print "Current working directory : " , os.path.realpath('./')
	tarfile = name_of_file+'_'+time.strftime("%m%d%Y_%H-%M")+'.tar'
	print "Creating tarfile : ", tarfile
	os.system('tar -cvf "{}" {}'.format(*[tarfile,'tempchangedfile.txt']))

	text_str = get_last_commit_message()
	# print text_str
	text_str = text_str + '\nChanged or added files\n'
	fopen = open('tempchangedfile.txt','r')
	for line in fopen:
		text_str = text_str + '\t'+line
	# print text_str

	# stop_here
	for i,file1 in enumerate( open('tempchangedfile.txt','r') ):
		if ( os.path.exists(file1.strip()) == True):
			os.system('tar --append --file={} {}'.format(*[tarfile,file1.strip()]) )
			print "Added ", file1.strip(), "Modification time:",\
				time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.localtime(os.path.getmtime(file1.strip())))
		else:
			print "Not a file"
	print "	Created Tarfile : ", tarfile
	print "	Compressing tar file and cleaning up"
	os.system('gzip {}'.format(tarfile) )

	# yesno = ''
	# while (yesno !='y' and yesno != 'n'):
	yesno = raw_input('\nProceed to email? (y/n): ')

	# if ( yesno == 'y'): send_email_file(tarfile,os.path.realpath(tarfile+'.gz'))
	# text_str = os.path.realpath(tarfile+'.gz')
	
	if ( yesno == 'y'):
		send_email(["*****@*****.**"], tarfile+'.gz', 
		text_str,sender='*****@*****.**',
		files=[os.path.realpath(tarfile+'.gz')])
	os.system('mv {}.gz old_tar/'.format(tarfile) )
	os.chdir(current_loc)
Esempio n. 13
0
def change_email_request():
    form=ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            new_email=form.email.data
            token = current_user.generate_email_change_token(new_email)
            send_email(new_email,
                       'Confirm Your Email Address', 'auth/email/change_email',
                       user=current_user, token=token)
            flash('An email with instructions to reset your password has been sent to you.')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid email or password.')
    return render_template("auth/change_email.html",form=form)
Esempio n. 14
0
def confirm():
    if request.method == 'POST':
        users = session.query(User).filter(
            User.email == request.form['adress']).all()  #Eメールアドレスを元にユーザーを検索
        if users:
            for user in users:
                send_email(user.email, 'confirm', id_=user.name)
            return render_template('message.html',
                                   message='メールを送信しました。')  #メールでIDを通知
        else:
            return render_template('message.html',
                                   message='入力されたメールアドレスは登録されていません。')

    else:
        return render_template('confirmation.html')
Esempio n. 15
0
 def render_mail(self, template_prefix, email, ctx):
     to = [email] if isinstance(email, str) else email
     subject = render_to_string("{0}_subject.txt".format(template_prefix), ctx)
     subject = " ".join(subject.splitlines()).strip()
     template = "{0}_message.html".format(template_prefix)
     msg = send_email(template, subject, ctx, to)
     return msg
Esempio n. 16
0
def handle(req):
    json_req = json.loads(req)
    image_data = json_req['image_data']
    filename = json_req['filename']
    detected_objects = json_req['detected_objects']

    # Read config file
    config = ConfigParser.ConfigParser()
    config.read('s3-email.cfg')

    aws_access_key_id = config.get('S3', 'aws_access_key_id')
    aws_secret_access_key = config.get('S3', 'aws_secret_access_key')
    bucket_name = config.get('S3', 'bucket', "rpizero-smart-camera-archive")
    user = config.get('Email', 'user')
    pwd = config.get('Email', 'pwd')

    human_detected = False
    for item in detected_objects:
        if item['class'] == 'person' and item['score'] > 0.5:
            human_detected = True
            break
    print("human_detected = {}".format(human_detected))

    # Define the filename that will appear on S3
    # by stripping the image number at the beginning of the filename provided by Motion
    # as we want the file name to start with a date.
    # For example 04-20170724114420-00.jpg will become 20170724114420-00.jpg
    # The last two digits stand for the frame number.
    # http://htmlpreview.github.io/?https://github.com/Motion-Project/motion/blob/master/motion_guide.html#picture_filename
    # http://htmlpreview.github.io/?https://github.com/Motion-Project/motion/blob/master/motion_guide.html#conversion_specifiers
    filename_s3 = filename[filename.find('-') + 1:]

    # Upload image to S3 and remove the local copy
    url = upload_file(aws_access_key_id, aws_secret_access_key, filename_s3,
                      image_data, bucket_name, human_detected)

    # Send e-mail notification
    if human_detected:
        subject = "Human detected"
        # Send only the top 10 identified objects
        body = "\n".join([
            "{0}: {1:.2f}".format(item['class'], item['score'])
            for item in detected_objects[:10]
        ])
        # Send the link to the image in S3
        body += "\n\n{}".format(url)
        send_email(user, pwd, user, subject, body, image_data)
Esempio n. 17
0
def start_boiler(time_now_utc):    
    global boiler_on_time
    global boiler_off_time
    boilog.debug("about to start boiler...")

    # sanity check
    boiler_is_on = relay.is_output_high()  # read from relay (HW)
    if boiler_is_on:
        # this is bad may indicate a serious bug
	notify_phone.send_push_mesage('potential bug: relay is on when start_boiler is called', datetime.now())
	stop_and_exit()	

    relay.start_relay()
    notify_phone.send_push_mesage('boiler is ON', datetime.now())
    send_email(EMAIL_TO, EMAIL_SUBJECT, 'Boiler is turned ON! \n\n time: %s\n\n' %  str(datetime.now()))
    boiler_on_time = time_now_utc
    boiler_off_time = None
Esempio n. 18
0
def check_boiler_event_wrapper():
    try:
        check_boiler_event()
    except Exception as e:
        boilog.error('unrecoverable exception in check_boiler_event, exit boiler controller !!!\n\n' + str(e))	
	notify_phone.send_push_mesage('boiler controller CRASHED [exiting]', datetime.now())
	boiler_is_on = relay.is_output_high()  # read from relay (HW)
        if boiler_is_on:
	    boilog.debug('check_boiler_event_wrapper crashed while boiler was ON, turn it off and exit')
	    send_email(EMAIL_TO, EMAIL_SUBJECT,
	               'Unrecoverable exception in check_boiler_event, exit boiler controller !!!\n\n Boiler was <ON> while it happened\n\n' + str(e),
		       get_logfile_names())		    
	    stop_and_exit()
 	else:
	   boilog.debug('check_boiler_event_wrapper crashed  while boiler was OFF, turn it off and exit')
           send_email(EMAIL_TO, EMAIL_SUBJECT,
	              'Unrecoverable exception in check_boiler_event, exit boiler controller !!!\n\n Boiler was <OFF> while it happened\n\n' + str(e),
		      get_logfile_names())
def contact():
    form = ContactForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            email = request.form['email']
            msg = request.form['msg']
            name = request.form['name']
            subject = request.form['subject']
            send_email(name, email, subject, msg)
            redirect(url_for('contact'))
            flash('Your email was successfully sent')
        else:
            flash(
                'Your email was not submitted. Remember all fields are required.'
            )
            return render_template('contact.html', form=form)
    elif request.method == 'GET':
        return render_template('contact.html', form=form)
Esempio n. 20
0
def selfemailall(flags):
	# print flags
	flag = flags[1]
	current_loc = os.path.realpath('./')
	for i, flag_target in enumerate(_GIT_REPOS_FLAGS):
		if ( flag == flag_target):
			itarget = i
			break
	# print i, _GIT_REPOS_MASTER[i]
	os.chdir(  _GIT_REPOS_MASTER[itarget] )
	os.system('git ls-files > tempchangedfile.txt')
	name_of_file= flag+'_all_file'

	print "Current working directory : " , os.path.realpath('./')
	tarfile = name_of_file+'_'+time.strftime("%m%d%Y_%H-%M")+'.tar'
	print "	Creating Tarfile : ", tarfile
	os.system('tar -cvf "{}" {}'.format(*[tarfile,'tempchangedfile.txt']))
	for i,file1 in enumerate( open('tempchangedfile.txt','r') ):
		if ( os.path.exists(file1.strip()) == True):
			os.system('tar --append --file={} {}'.format(*[tarfile,file1.strip()]) )
			print "Added ", file1.strip(), "Modification time:",\
				time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.localtime(os.path.getmtime(file1.strip())))
		else:
			print "Not a file"
	print "	Created Tarfile : ", tarfile
	print "	Compressing tar file and cleaning up"

	os.system('gzip {}'.format(tarfile) )
	# stop_here
	yesno = raw_input('Proceed to email? (y/n): ')
	# if ( yesno == 'y'): send_email_file(tarfile,os.path.realpath(tarfile+'.gz'))
	# stop_here
	text_str = get_last_commit_message()
	if ( yesno == 'y'):
		send_email(["*****@*****.**"], tarfile+'.gz', 
		text_str,sender='*****@*****.**',
		files=[os.path.realpath(tarfile+'.gz')])
	os.system('rm {}.gz'.format(tarfile) )

	os.chdir(current_loc)
Esempio n. 21
0
def remind():
    form = forms.RemindPasswordForm(request.form)
    if form.validate_on_submit():
        email = form.email.data.lower()
        user = User.query.filter(db.func.lower(User.email) == email).first()
        if not user:
            flash('Пользователь с таким email не зарегистрирован', 'danger')
        else:
            token = uuid.uuid4().hex
            redis.set('remind-token:{}'.format(token), user.id, 60 * 60 * 24)
            restore_url = url_for('.restore_password', user_id=user.id, token=token,
                                       _external=True)
            send_email(
                template='users/email/restore_password',
                subject='Восстановление пароля',
                recipients=[user.email],
                restore_url=restore_url
            )

            return render_template('users/after_remind.html', email=user.email)

    return render_template('users/remind.html', form=form)
Esempio n. 22
0
def stop_boiler(time_now_utc):
    global boiler_on_time
    global boiler_off_time
    boilog.debug("about to stop boiler...")

    # sanity check
    boiler_is_on = relay.is_output_high()  # read from relay (HW)
    if not boiler_is_on:
        # this is bad may indicate a serious bug
	notify_phone.send_push_mesage('potential bug: relay is off when stop_boiler is called', datetime.now())
	stop_and_exit()	

    relay.stop_relay()
    boiler_off_time = time_now_utc
    on_time = (boiler_off_time - boiler_on_time).total_seconds()
    notify_phone.send_push_mesage('boiler is OFF [%d min]' % (on_time / 60), datetime.now())
    send_email(EMAIL_TO, EMAIL_SUBJECT, 'Boiler is turned OFF! \n\n time: %s\n\n' %  str(datetime.now()))

    # update daily statistics
    boiler_activity[str(date.today())] += on_time
    boiler_on_time = None
    boiler_off_time = None
Esempio n. 23
0
def run_a_tool(benchmark, bench_suit_name, root_folder, heuristic_intensity1, heuristic_intensity2,tool_type):
    start_time = time.time() 
    subject = "starting a run"
    body = "start the test_benchmark with benchmark: " + benchmark + " heuristic_intensity1:" + heuristic_intensity1 + " heuristic_intensity2:" + heuristic_intensity2 + " tool_type:" + tool_type
#     send_email("*****@*****.**", "+1mastermind+", "*****@*****.**", subject, body)

    if(tool_type == "s6"):
        run_test_bench_mark(benchmark, root_folder, bench_suit_name,  heuristic_intensity1, heuristic_intensity2)
    if (tool_type == "various_inputs"):
        run_test_bench_mark_4_input_dep(benchmark, root_folder, bench_suit_name,  heuristic_intensity1, heuristic_intensity2)

    end_time = time.time() 
    config_addr = open("config.txt", "w")
    config_addr.write("benchmark: " + benchmark + "\n") 
    config_addr.write("heuristic_intensity1:" + heuristic_intensity1 + " heuristic_intensity2:" + heuristic_intensity2 + "\n")
    config_addr.write("tool_type: " + tool_type + "\n")
    run_time_duration =  (end_time - start_time)/60
    config_addr.write("run duration(minutes): " + str(run_time_duration))
    config_addr.close() 
    #os.system("python make_backup.py " + benchmark + "  "  + tool_type)

    subject = "ending a run"
    body = "end the test_benchmark with benchmark: " + benchmark + " heuristic_intensity1:" + heuristic_intensity1 + " heuristic_intensity2:" + heuristic_intensity2 + " tool_type:" + tool_type + "run time duration:" + str(run_time_duration)
    send_email("*****@*****.**", "+1mastermind+", "*****@*****.**", subject, body)
Esempio n. 24
0
bench_suit_name= "sd-vbs"
#bench_suit_name= "my_micro_benchmark"

root_folder= "apx_tool_chain"
tool_type = "various_inputs"
#heuristic_intensity1="xxxl"
#heuristic_intensity2= "xxxl"
try:
    run_a_tool(benchmark, bench_suit_name, root_folder, heuristic_intensity1, heuristic_intensity2,tool_type)
except TaskError as er:
    print "TASK ERROR OCCURED" 
    write_error(er)
    subject = "TASK ERROR" 
    body = "error in the test_benchmark with benchmark: " + benchmark + " heuristic_intensity1:" + heuristic_intensity1 + " heuristic_intensity2:" + heuristic_intensity2 + " tool_type:" + tool_type
    send_email("*****@*****.**", "+1mastermind+", "*****@*****.**", subject, body, send_email_activate)
    exit()
except BenchMarkError as er:
    print "BENCHMARK ERROR OCCURED" 
    write_error(er)
    subject = "BENCHMARK ERROR" 
    body = "error in the test_benchmark with benchmark: " + benchmark + " heuristic_intensity1:" + heuristic_intensity1 + " heuristic_intensity2:" + heuristic_intensity2 + " tool_type:" + tool_type
    send_email("*****@*****.**", "+1mastermind+", "*****@*****.**", subject, body, send_email_activate)
    exit()
except Exception as ex:
    traceback.print_exc()
    logger.exception(error)
    subject = "ERROR" 
    body = "error in the test_benchmark with benchmark: " + benchmark + " heuristic_intensity1:" + heuristic_intensity1 + " heuristic_intensity2:" + heuristic_intensity2 + " tool_type:" + tool_type
    send_email("*****@*****.**", "+1mastermind+", "*****@*****.**", subject, body, send_email_activate)
    exit()
Esempio n. 25
0
        data_case = get_test_data(case_name_two)

        if not data_case:
            logging.info("数据不存在!")

        url = data_case["url"]
        data = data_case["data"]
        expect_data = data_case["expect_data"]

        res = requests.post(url=url, data=json.loads(data))
        rece_data = res.text

        self.assertEqual(rece_data, expect_data)


if __name__ == "__main__":
    logging.info(
        "================================== 测试开始 =================================="
    )
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(RunAll))
    with open(report_file, "wb") as f:
        HTMLTestRunner(stream=f,
                       title="API Report",
                       description="测试详情",
                       tester="C罗").run(suite)
    send_email(report_file)
    logging.info(
        "================================== 测试完毕 =================================="
    )
msg = """Dear {fname} {name},

sample text

We look forward to welcoming you in Berlin.
"""

msg += config.email_footer

# Testing on test team
#recipients = root.xpath("//person[ID=124599 or ID=154034 or ID=153772]")
#recipients = root.xpath("//person[ID=154034]")

# Manually exclude recipients from mass mailing
exclude_list = ('158029', '135115', '162015', '155023', '164139', '156529')
recipients_raw = wiasct.get_participants(root)

# Another example
# recipients_raw = root.xpath("//person[paiment_status='-1'][contribution_presenter][not(role)]") # (non-registered speakers)

recipients = [
    p for p in recipients_raw if str(p.ID) not in exclude_list and p.email
]

print(len(recipients))
for p in recipients:
    print(p.findtext('email'))

send_email(msg_subject, msg, recipients, msg_bcc, {}, True)
Esempio n. 27
0
from send_email import *
import time

start = time.time()

print "It has begun."

season = 2017
week_season = range(1,18)

run_stats_import(week_season, season)
import_done_time = time.time()
print "Import Process Complete in " + str(round(import_done_time - start,2)) + " seconds."

#time.sleep(1)

run_points(season)
process_points_time = time.time()
print "Stats Processing in " + str(round(process_points_time - import_done_time,2)) + " seconds."

run_playoff_points((week_season), season)
process_playoff_points_time = time.time()
print "Playoff Stats Processing in " + str(round(process_points_time - process_points_time,2)) + " seconds."

#time.sleep(1)

send_email(week_season, season, html_body(week_season, season))
send_email_time = time.time()
print "Send Email in " + str(round(send_email_time - process_playoff_points_time,2)) + " seconds."
print
print "Script Complete in " + str(round(time.time() - start,2)) + " seconds."
Esempio n. 28
0
def check_boiler_event():
    global next_boiler_event
    global next_poll_time
    global boiler_on_time
    global boiler_off_time
    global MAX_BOILER_TIME_PER_DAY_HOURS

    # time window in which to look for boiler events
    BOILER_EVENT_TIME_WINDOW_HOURS = 4

    # do our periodic work
    now_utc = datetime.utcnow()
    now_plus_window = now_utc + timedelta(hours=BOILER_EVENT_TIME_WINDOW_HOURS)
    now = now_utc.isoformat() + 'Z'  # 'Z' indicates UTC time
    later = now_plus_window.isoformat() + 'Z'  # 'Z' indicates UTC time

    boilog.debug('====> check_boiler_event START time: %s' % next_poll_time.astimezone(get_localzone()))

    # get calendar events and find the first relevant one
    try:
        events = boilercalendar.get_calendar_events(now, later, 5)
    except:
        # we could not read any calendar events, so we will try the next time
        boilog.error('can not read boiler events...will retry in several minutes...')
	send_email(EMAIL_TO, EMAIL_SUBJECT, 'Can not read boiler events...will retry in several minutes...!!!\n\n')
    else:
	# we only want the first boiler event (they are sorted by start time)
        for event in events:
            boiler_event = make_boiler_event(event)
            if boiler_event is None:
                continue
		
	    # we found the first boiler event
	    if is_same_boiler_event(next_boiler_event, boiler_event):
                boilog.debug('we already know about the received boiler event...ignoring.')
                break
            else:
                boilog.debug('we got an updated or new boiler event, using it.')
                next_boiler_event = boiler_event
		break
	else:
	    boilog.debug('could not find any boiler events any time soon...')
	    if next_boiler_event is not None:
	       # this case indicates that we no longer have a boiler event. it can happen
	       # if we poll right after the event ended or if the  user
	       # have cancled or removed it. as we still have a valid next_boiler_event
	       # it means that the boiler may be on, so if this is the case, we must
	       # turn it off and set the next_boiler_event to None.

	       # check the hardware if the boiler is currently on
	       boiler_is_on = relay.is_output_high()
      	       boilog.debug('next_boiler_event is about to be CANCLED, boiler_is_on ? %s' % boiler_is_on)
	       if not boiler_is_on:
	           # we have nothing to do as the next_boiler_event has not activated the boiler yet
		   boilog.debug('next_boiler_event is cancled (boiler was off)')
	       else:
	           # the boiler is on so we must turn it off		   
		   stop_boiler(datetime.now(tzutc()))
		   boilog.debug('next_boiler_event is cancled (boiler was on / event may be over when we polled)')

	       # make sure to disable it
	       next_boiler_event = None	       	       
    finally:        
	boilog.debug('inside main processing boiler loop...')
	
	# if we have a valid boiler event, process it
        if next_boiler_event is not None:	    
            boilog.debug("Processing our next boiler event:  %s" % next_boiler_event['summary'])
            boilog.debug(" + start boiler at: %s" % next_boiler_event['startTime'])
            boilog.debug(" + stop boiler at: %s" % next_boiler_event['endTime'])
            ontime = next_boiler_event['endTime'] - next_boiler_event['startTime']
            boilog.debug(" + duration: %s" % str(ontime))
            time_now_utc = datetime.now(tzutc())
	    if next_boiler_event['startTime'] >= time_now_utc:	    
	       time_to_on = next_boiler_event['startTime'] - time_now_utc
	       boilog.debug(" + time to switch on (in the future): %s" % time_to_on)
	    else: 
               time_to_on = time_now_utc - next_boiler_event['startTime']
	       boilog.debug(" + time to switch on has passed already: %s" % time_to_on)

            # check whether we need to turn the boiler on or off
            # note that we only turn it off if it was on before
            boiler_is_on = relay.is_output_high()  # read from relay (HW)
            now_in_boiler_event = should_turn_on(time_now_utc, next_boiler_event['startTime'], next_boiler_event['endTime'])
            max_boiler_time_per_day_sec = timedelta(hours=MAX_BOILER_TIME_PER_DAY_HOURS).total_seconds()
	    if boiler_is_on:
	        on_time_daily = (time_now_utc - boiler_on_time).total_seconds() + boiler_activity[str(date.today())]
	        boiler_quota_reached = on_time_daily >= max_boiler_time_per_day_sec
	    else:
	        boiler_quota_reached = boiler_activity[str(date.today())] >= max_boiler_time_per_day_sec

            boilog.debug(" + boiler is on ? %s" % boiler_is_on)
            boilog.debug(" + now in boiler event ? %s" % now_in_boiler_event)
            boilog.debug(" + boiler quota reached ? %s" % boiler_quota_reached)

	    # logic for turning the boiler on / off
	    msg_time_now = datetime.now()
            if now_in_boiler_event and not boiler_is_on:
	       if  not boiler_quota_reached:
                   start_boiler(time_now_utc)
	       else:	           
	           notify_phone.send_push_mesage('boiler quota reached, will not start boiler !', msg_time_now)
		   send_email(EMAIL_TO, EMAIL_SUBJECT, 'Boiler quota reached, will not start the boiler !%s\n\n' % str(msg_time_now))
            elif now_in_boiler_event and boiler_is_on and boiler_quota_reached:
	        stop_boiler(time_now_utc)
	        notify_phone.send_push_mesage('boiler quota reached, stopping boiler now !', msg_time_now)				
		send_email(EMAIL_TO, EMAIL_SUBJECT, 'Boiler quota reached, stopping the boiler now !%s\n\n' % str(msg_time_now))
            elif not now_in_boiler_event and boiler_is_on:
                stop_boiler(time_now_utc)            
        else:
            boilog.debug('we have no pending boiler event, will keep polling...')

    # calculate how much to wait so that we run every poll_time_delta
    global POLL_BOILER_EVENT_MINS
    poll_time_delta = timedelta(minutes=POLL_BOILER_EVENT_MINS)
    time_now_utc = datetime.now(tzutc())
    
    # if we are waiting for a boiler event to start before the poll time, shorten the poll interval
    if next_boiler_event is not None and next_boiler_event['startTime'] > time_now_utc:
        diff = (next_boiler_event['startTime'] - time_now_utc).total_seconds()
	diff += 30   # add 30 seconds so we won't wake up eariler than expected (will also work)
        deltatime_to_on = timedelta(seconds=diff)
    elif next_boiler_event is not None and next_boiler_event['endTime'] > time_now_utc:
        diff = (next_boiler_event['endTime'] - time_now_utc).total_seconds()
	diff += 30   # add 30 seconds
	deltatime_to_on = timedelta(seconds=diff)
    else:
        deltatime_to_on = poll_time_delta

    # wait till the minimum of the two
    poll_time_delta = min(deltatime_to_on, poll_time_delta)
    next_poll_time = next_poll_time + poll_time_delta
    next_poll_delta = next_poll_time - time_now_utc

    boilog.debug('Next time to check for boiler events: %s' % next_poll_time.astimezone(get_localzone()))
    boilog.debug('====> Time to wait till next poll time: %s' % (next_poll_delta / 60))
    threading.Timer(next_poll_delta.total_seconds(), check_boiler_event_wrapper).start()
Esempio n. 29
0
    runtime = format_time(timer)

    iscorrect = (P*x == Q and 'Correct!') or 'Wrong'
    print iscorrect
    print 'Tempo de execução: ', runtime

    msg = MIMEText(
        'Máquina: HighTower\n'
        'Algoritmo: parallelized\n'
        'Bits = ' + str(nbits) + ' bits\n'
        'E = '+ str(E) + '\n'
        'P: ' + str(P) + '\n'
        'Q: ' + str(Q) + '\n'
        'x = ' + str(x) + '\n'
        # 'Distinguished point: 28-bit\n'

        + str(iscorrect) + '\n'
        'Tempo de execução: ' + runtime)
    msg['Subject'] = 'Quebra da curva de ' + str(nbits) + ' bits - HighTower'
    send_email(msg)
    print '\n---------------------------------------\n'

if __name__ == '__main__':
    with open('curves.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        spamreader.next()
        for row in spamreader:
            if not len(row):
                break
            main(row)
Esempio n. 30
0
def main(args):
    nbits = int(args[0])
    A = int(args[1])
    B = int(args[2])
    p = int(args[3])
    order = int(args[4])
    Px = int(args[5])
    Py = int(args[6])
    Qx = int(args[7])
    Qy = int(args[8])

    if nbits < 32:
        return

    E = EllipticCurve(p, A, B, order)
    P = E.point(Px, Py)
    Q = E.point(Qx, Qy)

    # E = EllipticCurve(47, 34, 10)
    # P = E.point(30, 26)
    # Q = E.point(35, 41)

    # E = EllipticCurve(229, 1, 44)
    # P = E.point(5, 116)
    # Q = E.point(155, 166)

    print 'Bits =', nbits
    print 'E =', E
    print 'P =', P
    print 'Q =', Q

    while (True):
        try:
            start = time.time()
            now = datetime.now()
            moment = str(now.day)+'/'+str(now.month)+'/'+str(now.year)+' '\
            +str(now.hour)+':'+str(now.minute)+':'+str(now.second)
            print 'Started at', moment

            x = multiprocess(E, P, Q)

            print 'x =', x
            break
        except Exception, e:
            print 'Error:', str(e)

            end = time.time()
            timer = end - start
            runtime = format_time(timer)

            msg = MIMEText(
                'Máquina: HighTower\n'
                'Algoritmo: multiprocess\n'
                'Bits = ' + str(nbits) + ' bits\n'
                'E = '+ str(E) + '\n'
                'P: ' + str(P) + '\n'
                'Q: ' + str(Q) + '\n'
                'Distinguished point: 28-bit\n'
                'Tempo de execução: ' + runtime)
            msg['Subject'] = 'Erro detectado na curva de ' + str(nbits) + ' bits - HighTower'
            send_email(msg)
            print '---------------------------------------'
Esempio n. 31
0
    timer = end - start
    runtime = format_time(timer)

    iscorrect = (P * x == Q and 'Correct!') or 'Wrong'
    print iscorrect
    print 'Tempo de execução: ', runtime

    msg = MIMEText('Máquina: HighTower\n'
                   'Algoritmo: parallelized\n'
                   'Bits = ' + str(nbits) + ' bits\n'
                   'E = ' + str(E) + '\n'
                   'P: ' + str(P) + '\n'
                   'Q: ' + str(Q) + '\n'
                   'x = ' + str(x) + '\n'
                   # 'Distinguished point: 28-bit\n'
                   + str(iscorrect) + '\n'
                   'Tempo de execução: ' + runtime)
    msg['Subject'] = 'Quebra da curva de ' + str(nbits) + ' bits - HighTower'
    send_email(msg)
    print '\n---------------------------------------\n'


if __name__ == '__main__':
    with open('curves.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        spamreader.next()
        for row in spamreader:
            if not len(row):
                break
            main(row)
Esempio n. 32
0
def get_tasks(members):
	for member in  members:

		send_email(member, mem[member], members[member])
Esempio n. 33
0
def get_every_blog_mess(root_url):
    all_blog_url_list = get_all_url(root_url)
    mess_list = get_all_mess(all_blog_url_list)
    return mess_list

#获取总的信息
def get_count_mess(root_url,id):
    me_mess = get_me_mess(root_url,id)
    #写进文件
    write_me_mess(me_mess)
    return me_mess

if __name__=="__main__":
    # user_name = input("请输入你的CSDN博客用户名:")
    user_name = "gamer_gyt"
    root_url = "http://blog.csdn.net/" + user_name
    id = 1
    me_mess_list = []
    # if time.localtime().tm_hour == 23 or time.localtime().tm_hour == 0:
    while True:
        # mess_list = get_every_blog_mess(root_url)
        me_mess = get_count_mess(root_url,id)
        me_mess_list.append(me_mess)
        send_email(me_mess_list,id)
        id += 1
        #一天运行一次
        time.sleep(1*60*10)



Esempio n. 34
0
        log_generator('miss')

    new = diff(current, last)

    #se houver algo novo
    if new:
        #parseando contatos cadastrados
        cadastrados = parse_cadastros(PATH + '/cadastros/cadastrados.txt')

        #enviando para cada cadastrado
        for cadastro in cadastrados:
            send_email(
                cadastro['email'], {
                    'subject':
                    'alerta nova publicação',
                    'body':
                    template_parser({
                        'nome': cadastro['nome'],
                        'msg': new
                    }, PATH + '/templates/alerta.txt')
                })

        #gerando log do hit
        log_generator('hit', "%s" % new)

        #atualizando bkp
        shutil.copyfile(PATH + '/result.json', PATH + '/result-bkp.json')

except ValueError:
    log_generator('no_conection')
    recover()
Esempio n. 35
0
def resend_confirmation():
    token=current_user.generate_confirmation_token()
    send_email(current_user.email,'Confirm Your Account','auth/email/confirm',user=current_user,token=token)
    flash('A new confirmation email has been sent to you by email.')
    return redirect(url_for('main.index'))
def send_regression_report(data_path, estimator, estimator_name, email_to, username, password):
  email_to, username, password = sys.argv[2], sys.argv[3], sys.argv[4]
  rmse1, rmse2 = run_prediction(data_path, estimator, estimator_name, dt)
  plt.clf()
  plot_stats([rmse1, rmse2],["Training set = full", "Training set = only_similar"], estimator_name, dt)
  send_email(email_to, username, password, "smtp.gmail.com", 587, report , subject="Regression report", files=img_names)
Esempio n. 37
0
				#perform fusion first for better checks
				body = makeFieldFusion(auteur, body)
				
				print("email almost ready")
				print("to:" + to)
				print("subject:" + subject)
				print("body:" + body)
				print("attachment:" + attachment_path)
				print("via:" + login)
				
				
				if( args.iamverysure ):
					#this confirm is actually important because it allows to simulate non bot-ish delay for sending and ensure triple checking everything
					confirm = input("[c]Confirm sending or anything else to quit: ")
					if confirm == 'c' :
						if send_email(
								name=auteur,to=to, subject=subject, body_txt=body, attachment_path=attachment_path, login=login, pasw=pasw, server=server, port=port):
							print("done.")
							are_email_sent = True
						else:
							print("failed")
							are_email_sent = False
							break
					else:
						print("quitting because email sending NOT confirmed ")
						quit(1)
				else:
					print("quitting because no very sure (pass iamverysure argument) ")
					are_email_sent = False
					continue
					
	if( args.email and are_email_sent):
Esempio n. 38
0
    send_email(EMAIL_TO, EMAIL_SUBJECT, 'Boiler statistics summary:%s\n\n' % daily_stats)

    global POLL_STATISTICS_SECS
    stat_thread = threading.Timer(POLL_STATISTICS_SECS, process_statistics)
    stat_thread.setDaemon(True)
    stat_thread.start()

if __name__ == '__main__':    
    boilog.info('*' * 40)
    boilog.info('boiler controller started...')
    boilog.info('created by: Yaron Weinsberg')
    boilog.info('*' * 40)

    # dump configuration
    log_config()

    import lan
    controller_ip = lan.get_lan_ip()
    start_time = datetime.now()
    notify_phone.send_push_mesage('boiler controller service started on: %s' % controller_ip, start_time)
    send_email(EMAIL_TO, EMAIL_SUBJECT, 'Boiler service started at: %s on host: %s\n\n%s' %
               (str(start_time), controller_ip, log_config_string().encode("utf-8", "replace")))
    
    # make sure we start in a clean HW state
    relay.stop_relay()

    # start the action
    check_boiler_event_wrapper()
    process_statistics()

def koaxfr(instrObj, tpx=0):
    """
    Transfers the contents of outputDir to its final destination.
    Location transferring to is located in config.live.ini:
        KOAXFR:server
        KOAXFR:account
        KOAXFR:dir
    Email is sent to KOAXFR:emailto upon successful completion
    Email is sent to KOAXFR:emailerror if an error occurs
    """

    # shorthand vars

    instr = instrObj.instr.upper()
    utDate = instrObj.utDate
    log = instrObj.log
    fromDir = instrObj.dirs['output']

    # Verify that the directory to transfer exists

    if not os.path.isdir(fromDir):
        log.error('koaxfr.py directory ({}) does not exist'.format(fromDir))
        return False

    # Read config file

    import configparser
    config = configparser.ConfigParser()
    config.read('config.live.ini')
    emailFrom = config['KOAXFR']['EMAILFROM']
    emailTo = config['KOAXFR']['EMAILTO']

    # If no FITS files then email IPAC verifying (empty) transfer complete

    #    count = len([name for name in os.listdir(instrObj.dirs['lev0']) if name.endswith('.fits.gz')])
    count = 0
    for dirpath, dirnames, filenames in os.walk(instrObj.dirs['lev0']):
        for f in filenames:
            if f.endswith('.fits.gz'):
                count += 1

    if count == 0:
        log.info('koaxfr.py no FITS files to transfer')
        subject = ''.join((utDate.replace('-', ''), ' ', instr))
        message = ''.join(('No metadata for ', utDate.replace('-', '')))
        log.info('koaxfr.py sending no data email to {}'.format(emailTo))
        send_email(emailTo, emailFrom, subject, message)

        if tpx:
            update_koatpx(instr, utDate, 'files_arch', '0', log)
            update_koatpx(instr, utDate, 'sci_files', '0', log)
            update_koatpx(instr, utDate, 'ondisk_stat', 'N/A', log)
            update_koatpx(instr, utDate, 'arch_stat', 'N/A', log)
            update_koatpx(instr, utDate, 'metadata_stat', 'N/A', log)
            update_koatpx(instr, utDate, 'dvdwrit_stat', 'N/A', log)
            update_koatpx(instr, utDate, 'dvdsent_stat', 'N/A', log)
            update_koatpx(instr, utDate, 'dvdstor_stat', 'N/A', log)
            #update_koatpx(instr, utDate, 'tpx_stat', 'N/A', log)

        return True

    # Configure the transfer command

    server = config['KOAXFR']['SERVER']
    account = config['KOAXFR']['ACCOUNT']
    toDir = config['KOAXFR']['DIR']
    toLocation = ''.join((account, '@', server, ':', toDir, '/', instr))
    log.info('koaxfr.py transferring directory {} to {}'.format(
        fromDir, toLocation))
    log.info('koaxfr.py rsync -avz {} {}'.format(fromDir, toLocation))

    # Transfer the data

    import subprocess as sp
    xfrCmd = sp.Popen(["rsync -avz " + fromDir + ' ' + toLocation],
                      stdout=sp.PIPE,
                      stderr=sp.PIPE,
                      shell=True)
    output, error = xfrCmd.communicate()
    if not error:
        # Send email verifying transfer complete and update koatpx
        log.info('koaxfr.py sending email to {}'.format(emailTo))
        subject = ''.join(('lev0 ', utDate.replace('-', ''), ' ', instr))
        message = 'lev0 data successfully transferred to koaxfr'
        send_email(emailTo, emailFrom, subject, message)
        if tpx:
            utcTimestamp = dt.utcnow().strftime("%Y%m%d %H:%M")
            update_koatpx(instr, utDate, 'dvdsent_stat', 'DONE', log)
            update_koatpx(instr, utDate, 'dvdsent_time', utcTimestamp, log)
        return True
    else:
        # Send email notifying of error
        emailError = config['KOAXFR']['EMAILERROR']
        log.error('koaxfr.py error transferring directory ({}) to {}'.format(
            fromDir, toLocation))
        log.error('koaxfr.py sending email to {}'.format(emailError))
        message = ''.join(
            ('Error transferring directory', fromDir, ' to ', toDir, '\n\n'))
        send_email(emailError, emailFrom, 'Error - koaxfr transfer', message)
        return False
Esempio n. 40
0
from template_parser import *
from parse_cadastros import *
from send_email import *
import os
#send_email('*****@*****.**', {'subject': 'boas vindas!', 'body': template_parser({'nome': 'Amanda Cortez'}, 'templates/boas_vindas.txt')})

PATH = os.environ['PATH']

old_cadastrados = parse_cadastros(PATH + '/cadastros/ultimos_cadastrados.txt')
new_cadastrados = parse_cadastros(PATH + '/cadastros/cadastrados.txt')

send_email(
    cadastro['email'], {
        'subject':
        'boas vindas!',
        'body':
        template_parser({
            'nome': cadastro['nome'],
            'msg': new
        }, PATH + '/templates/boas_vindas.txt')
    })
Esempio n. 41
0
def main(args):
    nbits = int(args[0])
    A = int(args[1])
    B = int(args[2])
    p = int(args[3])
    order = int(args[4])
    Px = int(args[5])
    Py = int(args[6])
    Qx = int(args[7])
    Qy = int(args[8])

    if nbits < 32:
        return

    E = EllipticCurve(p, A, B, order)
    P = E.point(Px, Py)
    Q = E.point(Qx, Qy)

    # E = EllipticCurve(47, 34, 10)
    # P = E.point(30, 26)
    # Q = E.point(35, 41)

    # E = EllipticCurve(229, 1, 44)
    # P = E.point(5, 116)
    # Q = E.point(155, 166)

    print 'Bits =', nbits
    print 'E =', E
    print 'P =', P
    print 'Q =', Q

    while (True):
        try:
            start = time.time()
            now = datetime.now()
            moment = str(now.day)+'/'+str(now.month)+'/'+str(now.year)+' '\
            +str(now.hour)+':'+str(now.minute)+':'+str(now.second)
            print 'Started at', moment

            x = multiprocess(E, P, Q)

            print 'x =', x
            break
        except Exception, e:
            print 'Error:', str(e)

            end = time.time()
            timer = end - start
            runtime = format_time(timer)

            msg = MIMEText('Máquina: HighTower\n'
                           'Algoritmo: multiprocess\n'
                           'Bits = ' + str(nbits) + ' bits\n'
                           'E = ' + str(E) + '\n'
                           'P: ' + str(P) + '\n'
                           'Q: ' + str(Q) + '\n'
                           'Distinguished point: 28-bit\n'
                           'Tempo de execução: ' + runtime)
            msg['Subject'] = 'Erro detectado na curva de ' + str(
                nbits) + ' bits - HighTower'
            send_email(msg)
            print '---------------------------------------'
                <th width="50">Warned</th>
                <th width="50">Skipped</th>
                <th width="50">Errored</th>
                <th width="100">Total miniutes</th>
              </tr>
              """

for result in resultlist:
    print(result)
    if result.result == 'PASSED':
        bgcolor = "#32CD32"
    else:
        bgcolor = "#DC143C"
    htmloutput +=  \
            """<tr bgcolor="{bgcolor}">
                <td>{runname}</td>
                <td>{result}</td>
                <td>{total}</td>
                <td>{passed}</td>
                <td>{failed}</td>
                <td>{warned}</td>
                <td>{skipped}</th>
                <td>{errored}</th>
                <td>{totalminutes}</th>
              </tr>
            """.format(runname = result.name, result = result.result, total = result.total, passed = result.passed, failed = result.failed, warned = result.warned, skipped = result.skipped, errored = result.errored,totalminutes = result.totalminutes, bgcolor = bgcolor)
htmloutput += "</table>"
title = "Anroid SDK Integration test result Passed:{0} Failed:{1}".format(passeds, totals - passeds)
send_email(title, htmloutput , contentformat = ContentFormat.Html, fromaddress = configure['email_from'], toaddresses = configure['email_to'] )