def send_email(symbol, price, sma): send_inst = SendEmail.SendEmail(service) text = 'The price of {0} is {1} and has fallen below its 200 day simple moving average of {2}'.format( symbol, price, sma) message = send_inst.create_message(email, email, 'Stock Alert', text) send_inst.send_message('me', message) return
def test_email_action_with_template_body(): with override_settings(LANGUAGES=(("en", "en"))): SUPER_TEST_TEMPLATE_DATA = { "en": { # English "subject": "Hello, {{ name }}!", "body_template": "<html><style>.dog-color { color: red; }</style><body>%html_body%</body></html>", "body": "Hi, {{ name }}. This is a test.", "content_type": "plain" } } if settings.EMAIL_BACKEND != 'django.core.mail.backends.locmem.EmailBackend': pytest.skip("Need locmem email backend") mail.outbox = [] # Clear the Django testing mail outbox event = get_initialized_test_event() ctx = Context.from_event(event, shop=factories.get_default_shop()) ctx.set("name", "Luke J. Warm") # This variable isn't published by the event, but it's used by the template se = SendEmail({ "template_data": SUPER_TEST_TEMPLATE_DATA, "from_email": {"constant": "*****@*****.**"}, "recipient": {"constant": "*****@*****.**"}, "language": {"constant": "ja"}, }) se.execute(ctx) # Once assert len(mail.outbox) == 1 # 'send_identifier' should ensure this is true msg = mail.outbox[0] assert msg.to == ['*****@*****.**'] assert msg.from_email == '*****@*****.**' assert ".dog-color { color: red; }" in msg.body assert "Luke J. Warm" in msg.body
def get_script_steps(self, form): action_data = { "template_data": {}, "recipient": {"constant": form["base"].cleaned_data["recipient"]}, "language": {"variable": "language"}, "fallback_language": {"constant": settings.PARLER_DEFAULT_LANGUAGE_CODE} } for language in form.forms: form_lang = form[language] # tries to get the cleaned data, otherwise the initial value # since cleaned_data can be blank if the user did not change anything action_data["template_data"][language] = { "content_type": "html", "subject": form_lang.cleaned_data.get("subject", form_lang.initial.get("subject", "")).strip(), "body": form_lang.cleaned_data.get("body", form_lang.initial.get("body", "")).strip() } send_mail_action = SendEmail(action_data) conditions = [] if form["base"].cleaned_data.get("last24hrs"): conditions.append(BooleanEqual({ "v1": {"variable": "dispatched_last_24hs"}, "v2": {"constant": (not form["base"].cleaned_data["last24hrs"])} })) return [Step(next=StepNext.STOP, actions=(send_mail_action,), conditions=conditions)]
def test_notify_item_admin_form(rf, admin_user): event_class = ATestEvent script_item = SendEmail({ "send_identifier": {"constant": "hello"}, "recipient": {"constant": "*****@*****.**"}, "language": {"constant": "en"}, }) send_data = { "b_recipient_c": "*****@*****.**", "b_language_c": "en", "b_message_c" : "Message", "b_send_identifier_c": "hello", "t_en_subject": "Welcome!", "t_ja_subject": "Konnichiwa!", "t_ja_body": "Bye", "t_en_content_type": "html" } form = ScriptItemEditForm( event_class=event_class, script_item=script_item, data=send_data ) initial = form.get_initial() assert initial["b_send_identifier_c"] == "hello" assert not form.is_valid() # Missing template body for default language with pytest.raises(forms.ValidationError): form.save() send_data.update({"t_en_body": "ok now this should pass"}) form = ScriptItemEditForm( event_class=event_class, script_item=script_item, data=send_data ) initial = form.get_initial() assert initial["b_send_identifier_c"] == "hello" assert form.is_valid() form.save() assert script_item.data["template_data"]["en"]["subject"] == "Welcome!" assert script_item.data["template_data"]["ja"]["subject"] == "Konnichiwa!" assert script_item.data["recipient"] == {"constant": "*****@*****.**"} send_data["b_recipient_c"] = admin_user.pk send_data['init_data'] = json.dumps({"eventIdentifier":"order_received","itemType":"action","data":{"identifier":"add_notification"}}) view = script_item_editor request = apply_request_middleware(rf.post("/", data=send_data), user=admin_user) response = view(request) assert response.status_code == 200 # Assert no errors have occurred
def test_email_action(): if settings.EMAIL_BACKEND != 'django.core.mail.backends.locmem.EmailBackend': pytest.skip("Need locmem email backend") mail.outbox = [] # Clear the Django testing mail outbox event = get_initialized_test_event() ctx = Context.from_event(event, shop=factories.get_default_shop()) ctx.set("name", "Luke Warm") # This variable isn't published by the event, but it's used by the template se = SendEmail({ "template_data": TEST_TEMPLATE_DATA, "from_email": {"constant": "*****@*****.**"}, "recipient": {"constant": "*****@*****.**"}, "language": {"constant": "ja"}, "send_identifier": {"constant": "hello, hello, hello"} }) se.execute(ctx) # Once, se.execute(ctx) # Twice! assert len(mail.outbox) == 1 # 'send_identifier' should ensure this is true msg = mail.outbox[0] assert msg.to == ['*****@*****.**'] assert msg.from_email == '*****@*****.**' assert ctx.get("name").upper() in msg.subject # The Japanese template upper-cases the name
def get_script_steps(self, form): action_data = { "template_data": {}, "language": {"variable": "language"}, "fallback_language": {"constant": settings.PARLER_DEFAULT_LANGUAGE_CODE}, } if form["base"].cleaned_data.get("send_to") == "other": action_data["recipient"] = {"constant": form["base"].cleaned_data["recipient"]} else: action_data["recipient"] = {"variable": "customer_email"} for language in form.forms: form_lang = form[language] # tries to get the cleaned data, otherwise the initial value # since cleaned_data will be blank if the user did not change anything action_data["template_data"][language] = { "content_type": "html", "subject": form_lang.cleaned_data.get("subject", form_lang.initial.get("subject", "")).strip(), "body": form_lang.cleaned_data.get("body", form_lang.initial.get("body", "")).strip() } send_mail_action = SendEmail(action_data) return [Step(next=StepNext.STOP, actions=(send_mail_action,))]
angleDiff = Variable(torch.FloatTensor(angleDiff), requires_grad=False).cuda() dimGT = Variable(torch.FloatTensor(dimGT), requires_grad=False).cuda() confidence_arg = Variable(torch.LongTensor(confidence_arg.astype(np.int)), requires_grad=False).cuda() [orient, conf, dim] = model(batch) conf_loss = conf_LossFunc(conf, confidence_arg) orient_loss = Model.OrientationLoss(orient, angleDiff, confidence_multi) dim_loss = dim_LossFunc(dim, dimGT) loss_theta = conf_loss + w * orient_loss loss = alpha * dim_loss + loss_theta if i % 15 == 0: #print confidence print 'loss_conf' print conf_loss print 'loss_orient' print orient_loss print 'loss_dim' print dim_loss print 'total' print loss print '=======' #loss = alpha * dim_loss + loss_theta if i % 150 == 0: #print loss torch.save(model.state_dict(), 'model.pkl') opt_SGD.zero_grad() loss.backward() opt_SGD.step() torch.save(model.state_dict(), 'model.pkl') SE.SendEmail()
import sys sys.path.append('/media/external2/Dash_Cam_Point_Align') import Info import os import subprocess import moviepy.editor as mve from multiprocessing import Pool import SendEmail def RunMatch(ID): info = Info.GetVideoInfo(ID) command = '%s %s' % (Info.Config.OPENSFM_RUN_MATCH, info['video_path']) subprocess.call(command, shell=True) if __name__ == '__main__': ID_lst = Info.GetAllVideoID() #RunMatch(ID_lst[0]) pool = Pool(processes=1) pool.map(RunMatch, ID_lst) SendEmail.SendEmail(Text='RunMatch Finish!!!')
def lambda_handler(event, context): store_id = event phone_no, recipient, acceptance_status = GetApplicantDetails(store_id) SendEmail.SendEmail(recipient, acceptance_status) DynamoDB.UpdateDataInDB(store_id, phone_no, STATUS_ID, STATUS_CODE)
def CheckKerberos(config): ### Only send email if terminal kerberos ticket is about to expire and user has set email DoMail=False HOSTNAME = os.environ['HOSTNAME'] USER = os.environ['USER'] ### klist show two thinigs; ### Valid starting Expires Service principal ### 04/12/19 12:33:47 04/13/19 13:33:47 krbtgt/[email protected] ### renew until 04/17/19 12:33:47 ### 04/12/19 12:33:48 04/13/19 13:33:47 afs/[email protected] ### ^ this can be renewed with 'kinit -R' ### renew until 04/17/19 12:33:47 ### ^ this can be renewed with 'kinit jskim', but we need to type password ###-- klist lists kerberos tickets lines_klist = ShellHelper('klist').split('\n') ticket_info = '' ### afs_kerb is used to only check afs ticket afs_kerb=False ### ticket_is_valid is used to test that kerberos has not expired (would mean som server issue) ticket_is_valid=True ### renewal_expiring is set if ticket is close to expiring (has 5 days from first running) renewal_expiring=False ##-- loop over kerberos list for line in lines_klist: line = line.strip('\n') ##-- only look at afs ticket if "afs/[email protected]" in line: words = line.split() # ['04/12/19', '13:06:33', '04/13/19', '14:06:33', 'afs/[email protected]'] afs_kerb=True ticket_info += "\nCurrent ticket AFS:\n" ticket_info += line+"\n" ## check renew only after we get afs_kerb correctly if not afs_kerb: continue ##-- check expiration of afs ticket if "renew until" in line: ticket_info += line+"\n" words = line.split() # ['renew', 'until', '04/17/19', '12:33:47'] expiration_time = ParseTicketTime(words[2]+' '+words[3]) alert_time = datetime.now() + timedelta(hours=time_renewal) #### check if renewal date is within time_renewal hours from now, if so send email to let user know if expiration_time < datetime.now(): ticket_is_valid=False elif expiration_time < alert_time: renewal_expiring=True ## we only need two lines, just break break ##-- status lets the summary code know what the state of the ticket is default 0 (following bash exit code rule) status = 0 alerting_msg = '' if not afs_kerb: alerting_msg = "Kerberos ticket is NOT AVAILABLE." alerting_msg += "Please log in to "+USER+"@"+HOSTNAME+" to renew the ticket\n" DoMail=True status= 1 if not ticket_is_valid: alerting_msg = "Kerberos ticket has been EXPIRED." alerting_msg += "Please log in to "+USER+"@"+HOSTNAME+" to renew the ticket\n" DoMail=True status= 2 if renewal_expiring: ### ticket is valid and exists, but is close to expiration and will need password to reset alerting_msg += "Ticket is expiring soon\n" alerting_msg += "Please log in to "+USER+"@"+HOSTNAME+" to renew the ticket\n" DoMail=True status = 1 ################################################### if DoMail: import SendEmail exec('from '+config+' import UserInfo') email_content = ticket_info email_content += "\n**********************************************************\n" email_content += alerting_msg email_content += "**********************************************************\n" LogEmail = UserInfo['LogEmail'] if LogEmail != "": SendEmail.SendEmail(LogEmail, LogEmail, '[CrabJobMonitoring] lxplus Kerberos ticket', email_content) #print email_content return status
def CheckProxy(config): DoMail = False ProxyTimeLeft = '' alerting_msg = '' status = 0 HOSTNAME = os.environ['HOSTNAME'] USER = os.environ['USER'] ### First check if we have it set ProxyInfoCheck = subprocess.call('voms-proxy-info &> /dev/null', shell=True) ## if this is 1, means no proxy set if ProxyInfoCheck == 1: DoMail = True status = 2 alerting_msg = 'GRID proxy is NOT SET\n' alerting_msg += "Please log in to " + USER + "@" + HOSTNAME + ", and run\n" alerting_msg += "voms-proxy-init --voms cms --valid 192:00\n" else: ProxyTimeLeft = ShellHelper( 'voms-proxy-info | grep "timeleft"').split()[2] # '191:58:45' #### Check if expired if ProxyTimeLeft == "00:00:00": DoMail = True status = 3 alerting_msg = 'GRID proxy has been EXPIRED\n' alerting_msg += "Please log in to " + USER + "@" + HOSTNAME + ", and run\n" alerting_msg += "voms-proxy-init --voms cms --valid 192:00\n" else: ProxyTimeLeft_hour = int(ProxyTimeLeft.split(':')[0]) if ProxyTimeLeft_hour < time_renewal: DoMail = True status = 1 alerting_msg += "GRID proxy is EXPIRING SOON\n" alerting_msg += "Please log in to " + USER + "@" + HOSTNAME + ", and run\n" alerting_msg += "voms-proxy-init --voms cms --valid 192:00\n" if DoMail: import SendEmail exec('from ' + config + ' import UserInfo') email_content = 'GRID Proxy time left (HH:MM:SS) : ' + ProxyTimeLeft email_content += "\n**********************************************************\n" email_content += alerting_msg email_content += "**********************************************************\n" LogEmail = UserInfo['LogEmail'] if LogEmail != "": SendEmail.SendEmail(LogEmail, LogEmail, '[CrabJobMonitoring] GRID Proxy', email_content) #print email_content return status
import sys sys.path.append('/media/external2/Dash_Cam_Point_Align') import Info import os import subprocess import moviepy.editor as mve from multiprocessing import Pool import SendEmail def RunReconstruct(ID): info = Info.GetVideoInfo(ID) command = '%s %s' % (Info.Config.OPENSFM_RECONSTRUCT, info['video_path']) subprocess.call(command, shell=True) if __name__ == '__main__': ID_lst = Info.GetAllVideoID() #RunReconstruct(ID_lst[0]) pool = Pool(processes=10) pool.map(RunReconstruct, ID_lst) SendEmail.SendEmail(Text='Reconstruct finish!!!!!')
gmm = (data['a'], data['b'], data['c']) mean = data['mean'] pca_transform = data['pca_transform'] image_fvs = [] for image_dec in (frame_desc + pano_desc): image_dec = np.dot(image_dec - mean, pca_transform) fv = ynumpy.fisher(gmm, image_dec, include='mu') image_fvs.append(fv) image_fvs = np.vstack(image_fvs) image_fvs = np.sign(image_fvs) * np.abs(image_fvs)**0.5 norms = np.sqrt(np.sum(image_fvs**2, 1)) image_fvs /= norms.reshape(-1, 1) image_fvs[np.isnan(image_fvs)] = 100 frame_fvs = image_fvs[0:len(frame_sift_lst)] pano_fvs = image_fvs[len(frame_sift_lst):] results, distances = ynumpy.knn(frame_fvs, pano_fvs, nnn=10) #print results #print distances np.save(info['pano_path'] + '/fisher_results', results) if __name__ == '__main__': do_lst = Info.GetStateList(['extractsift', 'fisher'], ['yes', 'no']) #print do_lst pool = Pool(processes=4) pool.map(GetKnn, do_lst) SendEmail.SendEmail(Text='Fisher Finish!!!')
for loc in circle: #print loc try: panoid = PanoProcess.GetPanoID(loc) except: continue if panoid != None and not panoid in id_lst: id_lst.append(panoid) #a = time.time() PanoProcess.GetPanoByID.GetPanoByID(panoid, info['pano_download_path']) #print time.time() - a pano_lst = [x for x in sorted(os.listdir(info['pano_download_path'])) if x.endswith('.jpg')] f_name = '%s/pano_lst.txt'%info['pano_path'] f = open(f_name, 'w') for img_name in pano_lst: s = img_name + '\n' f.write(s) f.close() end = time.time() print '%s use %f minutes and total %d images'%(ID, (end-start_time)/60, len(id_lst)) if __name__ == '__main__': #DownloadPano('000006') do_lst = Info.GetStateList(['reconstruction', 'downloadpano'], ['yes', 'no']) print 'Total %d videos to download'%len(do_lst) #do_lst = Info.GetAllVideoID() #DownloadPano('000006') pool = Pool(processes = 2) pool.map(DownloadPano, do_lst) SendEmail.SendEmail(Text = 'Downlaod finish')
print(":[!] You have added an invalid sentece / character.") print(":::: Closing program...") time.sleep(1) elif (data.t_cifr == None): # Use Honter with your api key if data.opc == 4: h = Hunter(data.apikey, data.domain) h.search() h.showInfo(h.search()) h.saveInfo(h.search()) elif data.opc == 5: se = SendEmail() t_email = data.t_email email = data.email password = data.passw to = data.to subject = data.subj se.setMessage(data.msg) msg = se.getMessage() part = "" if (t_email != None and email != None and password != None and to != None and subject != None and msg != None and data.pic != None): part = ""
#print f_name #print os.path.isfile(f_name) if __name__ == '__main__': start = time.time() ID_lst = Info.GetAllVideoID() CutFrame_lst = Info.GetAllVideoCutFrame() Loc_lst = Info.GetAllVideoLoc() Name_lst = Info.GetAllVideoName() #print ID_lst arg = Info.ArgumentComprass(ID_lst, CutFrame_lst) #print CutVideo(arg[40]) ''' output = [] for index in range(0, len(ID_lst)): output.append(True) ''' pool = Pool(processes=10) output = pool.map(CutVideo, arg) f_name = Info.Config.DATA_PATH + '/list_long_enough.txt' f = open(f_name, 'w') for index in range(0, len(output)): if output[index] == True: s = '%s\t%d\t%f\t%f\t%s\n' % (ID_lst[index], CutFrame_lst[index], Loc_lst[index][0], Loc_lst[index][1], Name_lst[index]) f.write(s) f.close() SendEmail.SendEmail(Text='Check video finish')
frame_short_name = name.split('.')[0] for i in range(0,results.shape[1]): pano_name = pano_sift_lst[results[index, i]] pano_short_name = pano_name.split('.')[0] kp_pairs = lib_SIFTmatch.flann_match('%s/%s'%(info['frame_sift_path'],frame_short_name), '%s/%s'%(info['pano_sift_path'],pano_short_name)) #print kp_pairs try: (mkp1, mkp2) = zip(*kp_pairs) mkp1_pts = [ (x[0],x[1]) for x in mkp1 ] mkp2_pts = [ (x[0],x[1]) for x in mkp2 ] mkp1_pts = np.float32(mkp1_pts) mkp2_pts = np.float32(mkp2_pts) F, mask = cv2.findFundamentalMat(mkp1_pts,mkp2_pts,cv2.FM_RANSAC,20) q_pts = mkp1_pts[mask.ravel()==1] t_pts = mkp2_pts[mask.ravel()==1] Mi.append(len(q_pts)) except: Mi.append(0) continue MM.append(Mi) np.save('%s/results_fundM'%info['pano_path'],MM) if __name__ == '__main__': do_lst = Info.GetStateList(['fisher', 'matchFunM'], ['yes', 'no']) #print do_lst #MatchFunM(do_lst[0]) pool = Pool(processes = 8) pool.map(MatchFunM, do_lst) SendEmail.SendEmail(Text = 'Match Finish')
WriteImageList(frame_path, frame_lst_name) WriteImageList(pano_download_path, pano_lst_name) command_1 = 'VisualSFM siftgpu %s' % frame_lst_name command_2 = 'VisualSFM siftgpu %s' % pano_lst_name subprocess.call(command_1, shell=True) subprocess.call(command_2, shell=True) command_1 = 'mv %s/*.sift %s' % (frame_path, frame_sift_path) command_2 = 'mv %s/*.sift %s' % (pano_download_path, pano_sift_path) subprocess.call(command_1, shell=True) subprocess.call(command_2, shell=True) GetSiftList(frame_sift_path, frame_sift_lst_name) GetSiftList(pano_sift_path, pano_sift_lst_name) os.remove(frame_lst_name) os.remove(pano_lst_name) if __name__ == '__main__': do_lst = Info.GetStateList( ['reconstruction', 'downloadpano', 'extractsift'], ['yes', 'yes', 'no']) print 'Total %d videos to extract sift' % len(do_lst) #pool = Pool(processes = 1) #pool.map(ExtractSift, do_lst) for ID in do_lst: ExtractSift(ID) #exit() SendEmail.SendEmail(Text='ExtractSift finish!!')
for i in cells: row1.append(i.find(text=True).encode("utf-8")) #removes duplicates for i in row1: if i not in row2: row2.append(i) count = 0 #below code was for personal use, I needed only the slots and the venues #the list row2 has the timetable in the format of [coursecode-coursetype-venue-slot], use it however """ venueslot=[] venue=[] slot=[] for i in row2: for j in range(0,len(i)-1): if i[j]=='-': count+=1 if count==2: newstr=i[j+2:len(i)] venueslot.append(newstr) count=0 break """ #writes the details to a textfile fout = open("Timetable of " + regno + ".txt", "w") for i in venueslot: fout.write(i + '\n') fout.close() #sends a copy of the text file generated as email SendEmail(regno)
HOST = {3} JobID = {6} Analyzer = {0} Year = {7} Skim = {5} # of Jobs = {4} InputSample = {1} {8} Output sent to : {2} '''.format(args.Analyzer, InputSamples, FinalOutputPath, HOSTNAME, NJobs, args.Skim, str_RandomNumber, args.Year, GetXSECTable(InputSamples, XsecForEachSample)) JobFinishEmail += '''################## Job started at {0} Job finished at {1} '''.format(string_JobStartTime, string_ThisTime) if IsKNU: JobFinishEmail += 'Queue = ' + args.Queue + '\n' EmailTitle = '[' + HOSTNAME + ']' + ' Summary of JobID ' + str_RandomNumber if GotError: JobFinishEmail = "#### ERROR OCCURED ####\n" + JobFinishEmail JobFinishEmail = ErrorLog + "\n------------------------------------------------\n" + JobFinishEmail EmailTitle = '[ERROR] Summary of JobID ' + str_RandomNumber if IsKNU: SendEmailbyGMail(USER, SKFlatLogEmail, EmailTitle, JobFinishEmail) else: SendEmail(USER, SKFlatLogEmail, EmailTitle, JobFinishEmail)
def ExtractFrame(video_info): ID = video_info[0] info = Info.GetVideoInfo(ID) CutFrame = video_info[1] print ID, CutFrame f_name = Info.Config.VIDEO_SOURCE_FOLDER + '/%d.mp4' % int(ID) video = mve.VideoFileClip(f_name) end_second = (CutFrame - 1) / video.fps start_second = end_second - 25 command = 'ffmpeg -i %s -r 5 -qscale:v 1 -ss %f -to %f %s/' % ( f_name, start_second, end_second, info['frame_path']) command += 'image-%5d.jpg' print command subprocess.call(command, shell=True) if __name__ == '__main__': ID_lst = Info.GetAllVideoID() CutFrame_lst = Info.GetAllVideoCutFrame() Loc_lst = Info.GetAllVideoLoc() arg = Info.ArgumentComprass(ID_lst, CutFrame_lst) #print len(ID_lst) #print CutFrame_lst #print Loc_lst pool = Pool(processes=10) pool.map(ExtractFrame, arg) #ExtractFrame(arg[2]) SendEmail.SendEmail(Text='ExtractFrame finish!!')
import subprocess import SendEmail if __name__ == '__main__': command1 = 'python ExtractFrame.py' command2 = 'python RunMatch.py' command3 = 'python RunReconstruct.py' subprocess.call(command1, shell=True) subprocess.call(command2, shell=True) subprocess.call(command3, shell=True) SendEmail.SendEmail(Text='All finish!!!!!!!!!!')
import subprocess import SendEmail command = 'python GetMatchResult.py' subprocess.call(command, shell=True) SendEmail.SendEmail(Text='Run finish!!!')