Beispiel #1
0
    def geneROI(self, imdir, indir, outdir, thre=128):
        ''' geneROI(self, indir, outdir)

                crop the region of interest from the hotmap
                '''
        mytime = timeLog('../timelogs/regionOfInterest')
        make_dir(outdir)
        for k, data in enumerate(self.data):
            print 'Generate region of interests:', data[0], k, '/', len(
                self.data)
            imgname = data[0]
            mytime.start(imgname)

            basename = os.path.splitext(imgname)[0]
            blkname = 'block' + basename + '.png'
            raw = image_load(imgname, imdir)
            img = image_load(blkname, indir)
            bb = image2bb(img, thre)
            bb = bbenlarge(bb, img.shape)
            roi_stack = image2roi(raw, bb)
            pickle_save(roi_stack, basename, outdir)

            mytime.end()
        mail(self.mail_rec, '<Coding Message!!!>, roi generation finished')
        mytime.final('roi generation finished')
        return
Beispiel #2
0
def get_news():
    infosaaa = gethttp()
    oldstatus = read_file("code.txt")
    # 遍历由json数据得到的list
    for info in infosaaa:
        idnum = info["id"]
        if idnum not in oldstatus:
            # 动态内容
            text = info["text"]

            # 动态图片
            picurl = []
            if "pics" in info.keys():
                for pic in info["pics"]:
                    picurl.append(pic["large"]["url"])

            # 转发内容
            retweeted = ''
            if "retweeted_status" in info.keys():
                retweeted = (info["retweeted_status"]["text"])

            # 发送
            print("正文:\n\t" + text + "\n图片:\n\t" + "\n\t".join(picurl) + "\n转发:\n\t" + retweeted)
            append_file('code.txt', idnum)
            mail("正文:\n\t" + text + "\n图片:\n\t" + "\n\t".join(picurl) + "\n转发:\n\t" + retweeted)
Beispiel #3
0
def mailing():

    global today
    global payment
    global seat
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    #cursor.execute('INSERT INTO ticket_cnf VALUES (%s, %s,%s, %s, %s,%s, %s,%s, %s, %s)', (Price,0,Person,Primary_location,time,T_name,movieName,))
    #cursor.execute('insert into ticket_cnf values(%s, %s,%s, %s, %s,%s, %s,%s, %s, %s)', (Price,0,Person,Primary_location,time,T_name,today,movieName,('select user_id from user where username = %s'),('select hall_id from theatre where location = %s ')),(username,T_name))
    cursor.execute(
        "insert into ticket_cnf(total_cost,payment,no_of_tickets,hall_name,show_time,location,date,movie_name,user_id,hall_id) values ('{}','{}','{}','{}','{}','{}','{}','{}',(select user_id from user where email_id = '{}'),(select hall_id from theatre where location = '{}' ))"
        .format(Price, payment, Person, Primary_location, time, T_name, today,
                movieName, email, Primary_location))
    mysql.connection.commit()
    if seat == 1:
        seat_name = "Normal"
    elif seat == 2:
        seat_name = "Silver"
    elif seat == 3:
        seat_name = "Gold"
    elif seat == 4:
        seat_name = "Platinum"
    else:
        seat_name = "Default Normal"

    m.mail(username, movieName, T_name, Primary_location, time, Price, email,
           seat_name, today)
    return "0"
Beispiel #4
0
        def seed2image(self, roidir, imdir, rawdir, outdir):
                '''seed2image(self, indir, outdir)

                convert roi detection to image 
                '''

                mytime = timeLog('../timelogs/regionOfInterest')
                make_dir(outdir)
                for k, data in enumerate(self.data):
                        print 'Generate region of interests:', data[0], k, '/', len(self.data)
                        imgname = data[0]
                        mytime.start(imgname)
                        basename = os.path.splitext(imgname)[0]
                        blkname = 'block' + basename + '.png' # use block plot as hotmap
                        roi = pickle_load(os.path.splitext(imgname)[0], roidir)
                        raw = image_load(imgname, rawdir)
                        img = image_load(blkname, imdir)
                        bb = image2bb(img)
                        bb = bbenlarge(bb, img.shape)
                        img = roi2image(roi, bb, img.shape)
                        image_save(img, imgname, outdir)
                        mytime.end()
                mail(self.mail_rec, '<Coding Message!!!>, roi generation finished')
                mytime.final('roi generation finished')
                return
Beispiel #5
0
    def clf_test(self):
        ''' clf_test(self, clfname)

		test the classifier the features generated
		clfname:_string_ contains filename of the classifier 
		Return (pred, label) 1D_numpy_arrays for prediction and labels '''

        mytime = timeLog('../timelogs/clf_test')
        mytime.start()

        print 'Testing Classifier ...'
        plotdir = '../plot/' + time.ctime()
        make_dir(plotdir)
        # write classifier name to txt file
        open(os.path.join(plotdir, self.mode), 'a').close()
        if not 'decision_function' in dir(self.classifier):
            self.classifier.decision_function = self.classifier.predict

        self.prediction = self.classifier.decision_function(self.feature_test)
        #plot.pplot(self.prediction, self.label_test, plotdir)

        #if self.mode == 'adaboost':
        #	test_score = []
        #        train_score = []
        #	for pred in self.classifier.staged_decision_function(self.feature_test):
        #		test_score.append(self.classifier.loss_(self.label_test, pred))
        #        for pred in self.classifier.staged_decision_function(self.feature):
        #                train_score.append(self.classifier.loss_(self.label, pred))
        #	plot.eplot(test_score, train_score, plotdir)
        # report
        mail(MAIL_REC, '<Coding Message!!!>, clf_test_finished')
        mytime.end()
        mytime.final()
        return
Beispiel #6
0
 def check_new_reports(self):
     '''Check whether a new model evaluation report is present in the target directory.'''
     self.last_report = time.time()
     fn = glob.glob(self.target_dir + '*report*')
     last_10_acc = '\n\nLast 10 accuracy test 50/50, artifact/clean:\n\n'
     last_10_acc += '\n'.join(
         open(path.data + 'test_output.txt').read().split('\n')[::-1][:11])
     new_report = False
     for f in fn:
         if f not in self.fn:
             self.fn.append(f)
             if not self.first_run:
                 cmc = plot_roc.cm_collection(last_n=self.last_n)
                 cmc.plot(plot_type='roc', save=True)
                 cmc.plot(plot_type='mcc', save=True)
                 cmc.plot(plot_type='pr', save=True)
                 cmc.plot(plot_type='f', save=True)
                 self.reports.append(open(f).read())
                 subject = ' '.join(f.split('_')[2:-2])
                 message = self.reports[
                     -1] + '\n\n' + last_10_acc + '\n' + self.perc_message + '\n\n'
                 mail.mail(message,
                           subject=subject,
                           to=self.recipients,
                           attach='roc.png,mcc.png,pr.png,f.png')
                 time.sleep(10)
     self.first_run = False
Beispiel #7
0
def main():
    start_logger()
    logging.debug("SCRIPT: I'm starting to do things!")

    try:

        def store_tweet(item):
            db = dataset.connect('sqlite:///data_wrangling.db')
            table = db['tweets']
            item_json = item._json.copy()
            for k, v in item_json.items():
                if isinstance(v, dict):
                    item_json[k] = str(v)
            table.insert(item_json)

        auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
        auth.set_access_token(TOKEN_KEY, TOKEN_SECRET)

        api = tweepy.API(auth)

        query = '#childlabor'
        cursor = tweepy.Cursor(api.search, q=query, lang="en")

        for page in cursor.pages():
            for item in page:
                store_tweet(item)

        mail.mail("Completed Successfully")

    except Exception:
        logging.exception('SCRIPT: We had a problem!')
        logging.error('SCRIPT: Issue with division in the main() function')
        mail.mail("Program Failed !!!!")

    logging.debug('SCRIPT: About to wrap things up!')
Beispiel #8
0
    def lost_login_post(self):
        data = web.input()
        recaptcha_url = 'http://www.google.com/recaptcha/api/verify'
        recaptcha_data = dict(challenge = data.recaptcha_challenge_field,
                response = data.recaptcha_response_field,
                remoteip = web.ctx.ip,
                privatekey = config.recaptcha_private_key)
        req = urllib2.Request(recaptcha_url, urllib.urlencode(recaptcha_data))
        response = urllib2.urlopen(req)
        page = response.read().split('\n')
        if page[0] == 'false':
            if page[1].strip() == 'incorrect-captcha-sol':
                return util.render().error(error_message = _('INCORRECT_CAPTCHA'), help_context='error')
            else:
                return util.render().error(error_message = _('CAPTCHA_ERROR'), help_context='error')
        found_users = user.get_user_from_email(data.email)
        if not found_users:
            return util.render().error(error_message = _('NO_SUCH_MAIL_ADDRESS'), help_context='error')
        salt_string = ''
        for u in found_users:
            salt = user.get_password_salt(u.uSerial)
            salt_string = salt_string + '* User %s: http://noah.kaist.ac.kr/+recover_password?id=%s&key=%s\n' % (u.uId, u.uId, salt)
        message_title = _('NOAH password recovery')
        message_body = _('''Dear NOAH user,

Some user on IP %s requested new password of your account(s). Following list contains your account(s). Click on the corresponding link for recovering password of account.

%s

If you did not requested password recovery, then please log in into your account. This link will not be vaild after logging into the account.''') % (web.ctx.ip, salt_string)
        mail.mail(data.email, message_title, message_body)
        return util.render().error(error_message = _('Message Sent. Please follow instructions on the message.'),
                error_class = _('Information'))
Beispiel #9
0
	def clf_test(self):
		''' clf_test(self, clfname)

		test the classifier the features generated
		clfname:_string_ contains filename of the classifier 
		Return (pred, label) 1D_numpy_arrays for prediction and labels '''

                mytime = timeLog('../timelogs/clf_test')
                mytime.start()

		print 'Testing Classifier ...'
		plotdir = '../plot/'+time.ctime()
		make_dir(plotdir)
		# write classifier name to txt file
		open(os.path.join(plotdir, self.mode), 'a').close()
                if not 'decision_function' in dir(self.classifier):
                        self.classifier.decision_function = self.classifier.predict

		self.prediction = self.classifier.decision_function(self.feature_test)
                #plot.pplot(self.prediction, self.label_test, plotdir)

                #if self.mode == 'adaboost':
                #	test_score = []
                #        train_score = []
                #	for pred in self.classifier.staged_decision_function(self.feature_test):
                #		test_score.append(self.classifier.loss_(self.label_test, pred))
                #        for pred in self.classifier.staged_decision_function(self.feature):
                #                train_score.append(self.classifier.loss_(self.label, pred))
                #	plot.eplot(test_score, train_score, plotdir)
		# report 
		mail(MAIL_REC, '<Coding Message!!!>, clf_test_finished')
                mytime.end()
                mytime.final()
		return 
Beispiel #10
0
def confirm_buy(driver, passengers):
    try:
        ticket = WebDriverWait(driver, 6).until(
            EC.presence_of_element_located((By.ID, "ticket_tit_id")))
    except Exception as e:
        print(e)

    print("已为您预订:{0}".format(ticket.text))

    js = 'var passengers=' + passengers + ';\
		console.log(passengers);\
		var passengers_list = document.getElementById("normal_passenger_id");\
		var li = passengers_list.children;\
		while(li.length==0);\
		console.log(li);\
		for(var i = 0; i<li.length; i++){\
			console.log(li[i].children[1].textContent);\
			if(passengers.indexOf(li[i].children[1].textContent)==-1){\
				continue;\
			}\
			li[i].children[0].click();\
		}\
		document.getElementById("submitOrder_id").click();\
	'

    driver.execute_script(js)

    driver.find_element_by_id("qr_submit_id").click()

    print("订单已提交,请登录12306完成支付")
    #接下来发送邮件通知
    mail.mail("已为您预订{0},请在半小时之内登录12306完成支付。".format(ticket.text))
Beispiel #11
0
        def on_pushButton_clicked(self):

        	gmail_user  = str(self.lineEdit_4.text())
        	gmail_pwd   = str(self.lineEdit.text())

        	konu 		= str(self.lineEdit_5.text())
        	metin		= str(self.textEdit.toPlainText())

        	kimden		= str(self.lineEdit_6.text())

        	mserver		= str(self.lineEdit_2.text())
        	mport		= int(self.lineEdit_3.text())

        	i = 0
        	while(i < self.listWidget.count()):
        		gonderilcek = str(self.listWidget.item(i).text())
        		self.statusBar().showMessage(unicode("Gonderiliyor: %i\n")%(i+1))        		
        		try:
        			mail(gonderilcek, kimden, konu, metin, gmail_user, gmail_pwd, mserver, mport)
        		except:
		        	a = QtGui.QMessageBox()
		        	a.setWindowTitle("Hata")		
		        	a.setText("Bilgileri kontrol ediniz!")
		        	a.setIcon(a.Warning)
		        	a.exec_()	        			        				
    			i = i +1
    			self.progressBar.setValue(int(i/self.listWidget.count())*100)
    			time.sleep(1)
    		self.statusBar().showMessage(unicode("Hazir\n")) 
Beispiel #12
0
    def geneHotmap(self, indir, outdir):
        '''geneHotmap(self, indir, outdir)

                convert stacks from image_test to hotmaps
                '''
        mytime = timeLog('../timelogs/testHotmap')
        make_dir(outdir)
        for k, data in enumerate(self.data):
            try:
                print 'Generate hotmaps:', data[0], k, '/', len(self.data)
                imgname = data[0]
                mytime.start(imgname)
                imgname = os.path.splitext(imgname)[0]
                s = pickle_load(imgname, indir)
                pnt = stack2image(s[0])
                blk = stack2image(s[1])
                image_save(pnt, 'point' + imgname + '.png', outdir)
                image_save(blk, 'block' + imgname + '.png', outdir)
            except:
                continue
            finally:
                mytime.end()
        mail(self.mail_rec, '<Coding Message!!!>, hotmap generation finished')
        mytime.final('hotmap generation finished')
        return
Beispiel #13
0
    def image_train(self, indir, outdir):
        ''' image_train(self)

		convert image to patch for all images in imdir
		'''
        # loop for every images in directory
        mytime = timeLog('../timelogs/image_train')
        make_dir(outdir)
        for k, data in enumerate(self.data):
            try:
                print 'Image-Train:', data[0], k, '/', len(self.data)
                imgname = data[0]
                coor = data[1]
                img = image_load(imgname, indir)
                mytime.start(imgname)
                patch_stack, label_stack = self.multiscale_patch_ext(img, coor)
                patch_stack, label_stack = stack2array(patch_stack,
                                                       label_stack)
                data_save(patch_stack, label_stack,
                          os.path.splitext(imgname)[0], outdir)
            except:
                continue
            finally:
                mytime.end()
        mail(self.mail_rec, '<Coding Message!!!>, image_train_finished')
        mytime.final('image train finished')
        return
Beispiel #14
0
    def seed2image(self, roidir, imdir, rawdir, outdir):
        '''seed2image(self, indir, outdir)

                convert roi detection to image 
                '''

        mytime = timeLog('../timelogs/regionOfInterest')
        make_dir(outdir)
        for k, data in enumerate(self.data):
            print 'Generate region of interests:', data[0], k, '/', len(
                self.data)
            imgname = data[0]
            mytime.start(imgname)
            basename = os.path.splitext(imgname)[0]
            blkname = 'block' + basename + '.png'  # use block plot as hotmap
            roi = pickle_load(os.path.splitext(imgname)[0], roidir)
            raw = image_load(imgname, rawdir)
            img = image_load(blkname, imdir)
            bb = image2bb(img)
            bb = bbenlarge(bb, img.shape)
            img = roi2image(roi, bb, img.shape)
            image_save(img, imgname, outdir)
            mytime.end()
        mail(self.mail_rec, '<Coding Message!!!>, roi generation finished')
        mytime.final('roi generation finished')
        return
Beispiel #15
0
        def geneROI(self, imdir, indir, outdir, thre = 128):
                ''' geneROI(self, indir, outdir)

                crop the region of interest from the hotmap
                '''
                mytime = timeLog('../timelogs/regionOfInterest')
                make_dir(outdir)
                for k, data in enumerate(self.data):
                        print 'Generate region of interests:', data[0], k, '/', len(self.data)
                        imgname = data[0]
                        mytime.start(imgname)

                        basename = os.path.splitext(imgname)[0]
                        blkname = 'block' + basename + '.png' 
                        raw = image_load(imgname, imdir)
                        img = image_load(blkname, indir)
                        bb = image2bb(img, thre)
                        bb = bbenlarge(bb, img.shape)
                        roi_stack = image2roi(raw, bb)
                        pickle_save(roi_stack, basename, outdir)

                        mytime.end()
                mail(self.mail_rec, '<Coding Message!!!>, roi generation finished')
                mytime.final('roi generation finished')
                return
Beispiel #16
0
def root():
	import subprocess as sp 
	import os
	a=sp.getoutput("cat /etc/shadow | grep root")

	a=a.split(':')
	a=a[1]

	while True:
		var=sp.getoutput("cat /etc/shadow | grep root")
		
		var=var.split(':')
		var1=var[1]
		try:

			if var1!=a:
				os.system("echo 'arpit' | passwd root --stdin ")
				os.system("loginctl lock-session")
				break
				import send_sms
				send_sms.sms()
				import mail
				mail.mail()
				os.system("cal > /dev/pts/0")

				root()

			elif var1==a:
				pass
		except:
			pass
Beispiel #17
0
        def geneHotmap(self, indir, outdir):
                '''geneHotmap(self, indir, outdir)

                convert stacks from image_test to hotmaps
                '''
                mytime = timeLog('../timelogs/testHotmap')
                make_dir(outdir)
                for k, data in enumerate(self.data):
                        try:
                                print 'Generate hotmaps:', data[0], k, '/', len(self.data)
                                imgname = data[0]
                                mytime.start(imgname)
                                imgname = os.path.splitext(imgname)[0]
                                s = pickle_load(imgname, indir)
                                pnt = stack2image(s[0])
                                blk = stack2image(s[1])
                                image_save(pnt, 'point'+imgname+'.png', outdir)
                                image_save(blk, 'block'+imgname+'.png', outdir)
                        except:
                                continue
                        finally:
                                mytime.end()
                mail(self.mail_rec, '<Coding Message!!!>, hotmap generation finished')
                mytime.final('hotmap generation finished')
                return
Beispiel #18
0
	def image_train(self, indir, outdir):
		''' image_train(self)

		convert image to patch for all images in imdir
		'''
		# loop for every images in directory
                mytime = timeLog('../timelogs/image_train')
                make_dir(outdir)
		for k, data in enumerate(self.data):
                        try:
                                print 'Image-Train:', data[0], k,'/',len(self.data)
                                imgname = data[0]
                                coor = data[1]
                                img = image_load(imgname, indir)
                                mytime.start(imgname)
                                patch_stack, label_stack = self.multiscale_patch_ext(img, coor)
                                patch_stack, label_stack = stack2array(patch_stack, label_stack)
                                data_save(patch_stack, label_stack,
                                        os.path.splitext(imgname)[0], outdir)
                        except:
                                continue
                        finally:
                                mytime.end()
		mail(self.mail_rec, '<Coding Message!!!>, image_train_finished')
                mytime.final('image train finished')
		return
Beispiel #19
0
def send_confirmation_email(email, confirmation_code):
    link = 'http://recipe0.pythonanywhere.com/confirm?code=%s' % (
        confirmation_code)
    text = '''Thank you for creating an account on Recipe Site.\n
              Click the following link to confirm your account:\n%s''' % (link)
    mail.mail(to=email,
              subject="[Recipe Site] Confirm Account Creation",
              text=text)
Beispiel #20
0
def home():
    if request.method == 'POST':
        toemail = request.form['toemail']
        subject = request.form['subject']
        content = request.form['content']
        mail(toemail, subject, content)
        return render_template('final.html')
    return render_template('index.html')
def send_mails(info, selections):
    for pair in selections:
        sender = pair[0]
        receiver = pair[1]
        email = info[sender].email()
        wishlist = info[receiver].wishlist()
        mail.mail(sender, receiver, email, wishlist)
        time.sleep(2)
Beispiel #22
0
    def mailResults(self, sendOnlyErrors=False, broadcast=False, sendOutput=False):
        ''' Send mail to the owner of each test with the report of the tests. 
        With sendOnlyErrors you can select only send errors exists, and with broadcast
        you can select send to everyone in the identities dictionary. Otherwise, each
        owner only receive his/her tests report '''
        lib_path = abspath('./script')
        sys.path.append(lib_path)
        import mail
        import config
        
        summaryMessage = self._summaryMessage 
        globalMessage = "Attached you will find the metadata with the report"
        toaddrs = ""
        attach_path = ""
        attachments = []

        path = self._statistics.split('/')
        extension = path[-1].split('.')[-1]
        last = path[-1].split('.')[0:len(path[-1].split('.'))-1]
        laststr = ""

        laststr = ".".join(last)

        if extension == laststr:
            extension = ""
        previous = path[0:len(path)-1]
        
        attach_path = "/".join(previous)

        print attach_path

        if sendOnlyErrors:
            md = self.extractMDWithError(self._statistics)
            if len(previous):
                attach_path += "/"
            attach_path += laststr + "_onlyerrors." + extension
            md.write(attach_path)
        else:
            if len(previous):
                attach_path += "/"
            attach_path += laststr + "." + extension
        
        if broadcast:
            toaddrs = self._identities.get('all')
        else:
            buggers = set(self.getBuggers(self._statistics))
            if len(buggers) != 0:
                for bugger in buggers:
                    toaddrs += "%s, " % self._identities.get(bugger)
        print "sending %s attached in an email..." % attach_path
        attachments.append(attach_path)
        if sendOutput:
            self.packOutput(self._outputTarFile)
            attachments.append(self._outputTarFile)
            print "sending also %s attached in the email..." % self._outputTarFile
            
        mail.mail(toaddrs,config.fromaddr,summaryMessage,globalMessage,attachments)
        print "...done"
def sign_in(uid, pwd):
    # set to no-window
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--no-sandbox")

    # simulate a browser to open the website
    browser = webdriver.Chrome(options=chrome_options)
    # browser = webdriver.Chrome()
    browser.get("https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/first0")

    try:
        # input uid and password
        print("Inputting the UID and Password of User {0}".format(uid))
        browser.find_element_by_xpath("//*[@id='mt_5']/div[1]/div[3]/input").send_keys(uid)
        browser.find_element_by_xpath("//*[@id='mt_5']/div[2]/div[3]/input").send_keys(pwd)

        # click to sign in
        browser.find_element_by_xpath("//*[@id='mt_5']/div[4]/div/input").click()
        time.sleep(2)

        # get middle info
        real_mid_page_url = browser.find_element_by_xpath("//*[@id='zzj_top_6s']").get_attribute("src")
        browser.get(real_mid_page_url)

        print("Checking whether User {0} has signed in".format(uid))
        msg = browser.find_element_by_xpath("//*[@id='bak_0']/div[7]/span").text
        # if msg == "今日您已经填报过了":
        #     return msg

        # click to fill in
        span_text = browser.find_element_by_xpath("//*[@id='bak_0']/div[13]/div[3]/div[4]/span").text
        if span_text == "本人填报":
            browser.find_element_by_xpath("//*[@id='bak_0']/div[13]/div[3]/div[4]").click()
        else:
            browser.find_element_by_xpath("//*[@id='bak_0']/div[13]/div[3]/div[6]").click()

        time.sleep(2)

        # click to submit
        print("Signing in for User {0}".format(uid))
        browser.find_element_by_xpath("//*[@id='bak_0']/div[19]/div[4]").click()
        time.sleep(2)

        if is_element_present(browser, "//*[@id='bak_0']/div[2]/div[2]/div[2]/div[2]"):
            msg = browser.find_element_by_xpath("//*[@id='bak_0']/div[2]/div[2]/div[2]/div[2]").text
        elif is_element_present(browser, "//*[@id='bak_0']/div[2]"):
            msg = browser.find_element_by_xpath("//*[@id='bak_0']/div[2]").text

    except Exception as e:
        msg = "while signing in for user " + uid + " there is an exception: \n" + str(e)
        mail.mail(msg, MAIL_ADMAIN)
    finally:
        browser.quit()

    # quit the browser
    print("Singing in for User {0} is finished".format(uid))
    return msg
Beispiel #24
0
    def monitor_computer(self):
        '''Check wheter cpu and ram is working as expected (does not seem to trigger if its not the case.'''
        self.last_monitor = time.time()
        memory = os.popen('top -l 1 -s 0 | grep PhysMem').read()
        cpu = os.popen('top -l 1 -s 0 | grep CPU\ usage').read()
        mem = memory.split(' ')[1]
        if mem[-1] == 'G': mem = int(mem[:-1]) * 1000
        elif mem[-1] == 'M': mem = int(mem[:-1])
        else: print('could not parse:', mem)

        cpu = cpu.split(' ')[2]
        if cpu[-1] == '%': cpu = float(cpu[:-1])
        else: print('could not parse:', cpu)
        clock = time.strftime("%H:%M:%S\t%b-%d-%Y",
                              time.localtime(time.time()))
        self.cpu.append(str(cpu) + '\t' + clock)
        self.mem.append(str(mem) + '\t' + clock)

        # check cpu
        if cpu < self.cpu_to_low:
            if self.cpu_to_low:
                print('cpu to low')
                if time.time(
                ) - self.start_cpu_to_low > 900 and not self.cpu_send:
                    mail.mail('\n'.join(self.cpu), subject='cpu is to low')
                    self.cpu_send = True
            else:
                self.cpu_to_low = True
                self.start_cpu_to_low = time.time()
                self.cpu_send = False
        else:
            self.cpu_to_low = False
            self.cpu_send = False

        # check memory
        if mem < self.mem_to_low:
            if self.mem_to_low:
                print('mem to low')
                if time.time(
                ) - self.start_mem_to_low > 900 and not self.mem_send:
                    mail.mail('\n'.join(self.mem), subject='mem is to low')
                    self.mem_send = True
            else:
                self.mem_to_low = True
                self.start_mem_to_low = time.time()
                self.mem_send = False
        else:
            self.mem_to_low = False
            self.mem_send = False

        if self.cpu_to_low or self.mem_to_low:
            if not self.short_monitor_interval:
                self.short_monitor_interval = True
                self.monitor_job = 30
        elif self.short_monitor_interval:
            self.sort_monitor_interval = False
            self.monitor_job = self.interval
Beispiel #25
0
def email():
    print("EMAILL")
    data = request.get_json()

    print(data)

    mail.mail(db2.tread(data['tid']))

    return jsonify({'st': 'True'})
Beispiel #26
0
    def run(self):
        global ready
        global datas
        global moviefail
        global pagefail
        global crawdatafail
        global subject
        global tag
        global cursor
        global datasize
        print('data save starting...')
        while True:
            while len(datas) > 0:
                datasize += 1
                data = datas.pop()
                name = data[0]
                img = data[1]
                href = data[2]
                pubdate = data[3]
                # print('name:'+name,'img:'+img,'href:'+str(href),'pubdate:'+pubdate,'tag:'+str(tag))
                try:
                    cursor.execute(
                        'insert into movie_items(name,img,tag,pubdate) values (%s,%s,%s,%s)',
                        (name,img,tag,pubdate))
                    # conn.commit()
                    id = cursor.lastrowid
                    info = [tuple([each, id]) for each in href]
                    cursor.executemany('insert into movie_links(link,item_id) values (%s,%s)',info)
                    conn.commit()
                except Exception as e:
                    conn.rollback()
                    logging.error(str(e))



            if ready == self.threadsize:
                tic = time.strftime("%Y-%m-%d-%H-%M", time.localtime())
                # self.filename = self.filename + tic
                # data_save(self.filename+'-'+tic,datas)
                # data_save(self.filename+'-pagefail-'+tic,pagefail)
                conn.close()
                data_save(self.filename+'-moviefail-'+tic,moviefail)
                data_save(self.filename + '-crawdatafail-' + tic, crawdatafail)
                msg = subject + "本次一共爬取" + str(datasize) + '条数据. ' + tic
                mail.mail(msg)
                # fp = open('./message-'+tic,'w')
                # fp.write(msg)
                # fp.close()
                #print("it is done...")
                # print(datas)
                # print(pagefail)
                # print(moviefail)

                break
            else:
                time.sleep(self.sleeptime)
Beispiel #27
0
def timing(hour, minute, the_users):
    now = datetime.datetime.now()
    if now.hour == hour and now.minute == minute:
        print("\n\n\n")
        print(now)
        for user in the_users:
            msg = sign_in(user.uid, user.pwd)
            msg = user.uid + ": " + msg
            print("Emailing to User {0} for notification".format(user.uid))
            mail.mail(msg, user.email)
            print("Emailing is finished")
Beispiel #28
0
def send_message(request):
    if not request.user.is_authenticated():
        return HttpResponse('Please login first.')
    username = request.session['username']
    name = request.POST['name']
    email = request.POST['email']
    msg = request.POST['message']

    content = 'Name:'+name+'\nE-mail:'+email+'\nContent:'+msg
    mail('*****@*****.**',content)
    return HttpResponse(u"感谢您的反馈!")
Beispiel #29
0
    def get_latest_tweet(self) -> Union[str, None]:
        try:
            get_url = f"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" \
                      f"{self.credentials['twitter-handle']}&count=1&tweet_mode=extended"

            header = {"Authorization": f"Bearer {self.credentials['bearer']}"}

            r = requests.get(url=get_url, headers=header)
            r.raise_for_status()
            try:
                # Get hashtag list
                tweet_tags = r.json()[0]['entities']['hashtags']
                hashtags = self.credentials['hashtags']
                found_not_allowed_tag = True
                print(tweet_tags)

                for each in tweet_tags:
                    # It's  a blocklist and the hashtag is found
                    if self.credentials['is_blocklist'] and each[
                            'text'] in hashtags:
                        found_not_allowed_tag = True
                        continue

                    # It is a list of allowed hashtags and the hashtag was found
                    if not self.credentials['is_blocklist'] and each[
                            'text'] in hashtags:
                        found_not_allowed_tag = False
                        break

                    # it is a list of allowed hashtags and the hash was not fonud
                    if not self.credentials['is_blocklist'] and not each[
                            'text'] in hashtags:
                        found_not_allowed_tag = True
                        continue

                # Is Tweet a reply?
                if self.credentials['omit_replies'] and r.json(
                )[0]['in_reply_to_status_id']:
                    found_not_allowed_tag = True

                if found_not_allowed_tag:
                    exit(0)

            except IndexError:
                # No hashtags, that's fine
                pass

            return r.json()[0]

        except Exception as e:
            message = f"The api call to twitter failed, the server responded:\n'{e}'.\nScript was discontinued."
            mail(message)
            exit(1)
Beispiel #30
0
 def post(self):
     email_address = self.get_argument('email_address', '')
     name = self.get_argument('name', '')
     feedback = self.get_argument('feedback', '')
     text = "Name: %s\n" % name
     text = text + "E-mail: %s\n" % email_address
     text = text + "Feedback: %s\n" % feedback
     to_addr = "*****@*****.**"
     from_addr = "*****@*****.**"
     subject = "[ResumeBoss] [INFO] Feedback" 
     mail.mail(text, from_addr, to_addr, subject)
     self.finish()
Beispiel #31
0
    def send_computer_report(self):
        '''Send a report with cpu and ram usage.'''
        self.last_computer_report = time.time()
        if self.cpu_to_low or self.mem_to_low:
            return 0
        self.monitor_computer()
        message = '\n\nMEMORY\n------\n\n' + '\n'.join(
            self.mem[::-1][:30]) + '\n\nCPU\n---\n\n' + '\n'.join(
                self.cpu[::-1][:30])
        subject = 'PC OK, MEM: ' + self.mem[-1].split(
            '\t')[0] + ' CPU: ' + self.cpu[-1].split('\t')[0]
        mail.mail(message_text=subject + '\n\n' + message, subject=subject)

        self.last_computer_report = time.time()
def gender_lstm():
    X_train = X_train.reshape(-1, 128, 1)
    Y_gender = Y_gender[:samples] - 1
    model = keras.Sequential([LSTM(1024), Dense(1, activation='sigmoid')])
    model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

    model.fit(X_train,
              Y_gender,
              validation_split=0.1,
              epochs=150,
              batch_size=1024)
    mail('train lstm done!')
Beispiel #33
0
def ssh2(ip,username,passwd,cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
            out = stdout.readlines()
            #for o in out:
                #print(o),
        #print('%s\tOK' % (ip))
        ssh.close()
    except :
        #print('%s\tERROR' % (ip))
        mail.mail('TFTP Failed','*****@*****.**',ip,'uploading config file failed.')
Beispiel #34
0
    def insert_score(self, X):
        conn = mysql.connector.connect(host='localhost',
                                       user='******',
                                       password='******',
                                       database='mail')
        cur = conn.cursor()
        for tr in X:
            d = []
            for td in tr:
                d.append(td.text)
            sql = "select * from score where id='%s'" % d[0]
            cur.execute(sql)
            a = cur.fetchall()
            if not a:
                sql = "insert into score(id,course,credit,type,method,quality,score,mark) values('%s','%s','%s','%s','%s','%s','%s','%s')" % (
                    d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7])
                cur.execute(sql)
                conn.commit()
            else:
                if not d[6] in a[0]:
                    sql = "update score set score='%s' where id='%s'" % (d[6],
                                                                         d[0])
                    cur.execute(sql)
                    conn.commit()
                    email = mail()
                    email.textMail('******', '有成绩更新了', tr)

        cur.close()
        conn.close()
Beispiel #35
0
    def insert_score(self, X):
        conn = mysql.connector.connect(
            host='localhost', user='******', password='******', database='mail')
        cur = conn.cursor()
        for tr in X:
            d = []
            for td in tr:
                d.append(td.text)
            sql = "select * from score where id='%s'" % d[0]
            cur.execute(sql)
            a = cur.fetchall()
            if not a:
                sql = "insert into score(id,course,credit,type,method,quality,score,mark) values('%s','%s','%s','%s','%s','%s','%s','%s')" % (
                    d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7])
                cur.execute(sql)
                conn.commit()
            else:
                if not d[6] in a[0]:
                    sql = "update score set score='%s' where id='%s'" % (d[6], d[
                        0])
                    cur.execute(sql)
                    conn.commit()
                    email = mail()
                    email.textMail('******', '有成绩更新了', tr)

        cur.close()
        conn.close()
Beispiel #36
0
 def run(self):
     url = self.url
     item = self.item
     # options = Options()
     # options.headless = True
     # PATH = "chromedriver.exe"
     # driver = webdriver.Chrome(PATH, options=options)
     GOOGLE_CHROME_BIN = os.environ.get('GOOGLE_CHROME_BIN')
     CHROMEDRIVER_PATH = os.environ.get('CHROMEDRIVER_PATH')
     chrome_options = Options()
     chrome_options.binary_location = GOOGLE_CHROME_BIN
     chrome_options.add_argument('--disable-gpu')
     chrome_options.add_argument('--no-sandbox')
     driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
                               chrome_options=chrome_options)
     try:
         driver.get(self.url)
         time.sleep(6)
         is_instock = driver.find_element_by_class_name(
             self.html_class).text
         driver.close()
         driver.quit()
         print(is_instock, self.item)
         if is_instock == self.cart:
             x = mail()
             x.send_mail(self.store_name, self.item)
     except NoSuchElementException:
         print('NoSuchElementException', self.item)
         driver.quit()
Beispiel #37
0
def help():
    form = LoginForm()
    if form.validate_on_submit():
        con = sqlite3.connect('feedback.db')
        cur = con.cursor()
        if form.FeedbackForm.data != "":
            cur.execute("INSERT INTO feedback VALUES (?, ?)", (form.email.data, form.FeedbackForm.data))
            if form.email.data == "":
                mail_for_me(form.FeedbackForm.data)
            if form.email.data != "":
                mail(form.email.data)
                mail_for_me(form.FeedbackForm.data)
        con.commit()
        con.close()

    return render_template('help.html', form=form)
Beispiel #38
0
	def run(self):
		self.logger.info("démarrage du service")
		ip_1 = '0.0.0.0'
		ip_2 = '0.0.0.0'
		try:
			ip_2 = str(myip.myip())
		except:
			self.logger.warning('pas de connexion... tentative de reconnexion dans  1 minute')
			time.sleep(60)
			#ip_2 = '0.0.0.0'
		while not self.arret:
			if ip_1 == ip_2:
				self.logger.info("le processus s'arrete pour %d seconde"%self.tmp)
				time.sleep(self.tmp)
			else:
				self.logger.info( "le processus vas envoyer un email \n")
				#print " ip :  %s"%ip_2
				m = mail.mail(self.emetteur, self.mot_passe, self.recepteur, ip_2)
				m.EnvoyerMail()
				info = "Emetteur : "+str(self.emetteur) + " | recepteur : "+ str(self.recepteur) + " | IP : "+str(ip_2)
				self.logger.warning("un message a été envoyé --> %s "%info)
				ip_1 = ip_2
			try:
				ip_2 = str(myip.myip()) # entourer par try catch en cas de deconnexion , retourne un message pas de conexion
			except:
				#ip_2 = '0.0.0.0'
				self.logger.warning("pas de connexion... tentative apres 1 minute")
				time.sleep(60)
Beispiel #39
0
    def __init__(self):
        self.path = str()
        self.credentials = str()

        if system().lower() == "windows":
            self.path = Path("twitter.json")
        else:
            self.path = Path("/etc/tw2hugo/twitter.json")

        try:
            with self.path.open('r') as fp:
                self.credentials = j_load(fp)

        except FileNotFoundError:
            mail("Could not find bearer token file! Script was discontinued.")
            exit(1)
 def handleData(self, receipt_text):
     try:
         receipt_datetime = receipt_text[:15]
         receipt_split_datetime = receipt_datetime.split('-')
         receipt_date_string = datetime.datetime.strptime(
             receipt_split_datetime[0], "%Y%m%d")
         receipt_date = datetime.datetime.strftime(receipt_date_string,
                                                   "%d.%m.%Y")
         receipt_time_string = datetime.datetime.strptime(
             receipt_split_datetime[1], "%H%M%S")
         receipt_time = datetime.datetime.strftime(receipt_time_string,
                                                   "%H:%M:%S")
         mail.mail().prepareMail(self.invoice_data, receipt_date,
                                 receipt_time)
     except:
         print('no content')
Beispiel #41
0
 def post(self):
     template_name = self.get_argument('template', '')
     profile = self.get_argument('profile', '')
     additional_info = self.get_argument('additional-info', '')
     try:
       profDict = json.loads(profile)
       addinfo_dict = json.loads(additional_info)
       filename = generator.generate(profDict, addinfo_dict, template_name, callback=self.on_generate)
     except Exception as e:
       text = "Error occurred during processing:\n%s\nStacktrace:\n" % e
       text = text + traceback.format_exc()
       to_addr = "*****@*****.**"
       from_addr = "*****@*****.**"
       subject = "[ResumeBoss] [ERROR] Unexpected error"
       mail.mail(text, from_addr, to_addr, subject)
       raise
def mailing():

    global today

    print(Price, 0, Person, Primary_location, time, T_name, today, movieName,
          username, T_name)
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    #cursor.execute('INSERT INTO ticket_cnf VALUES (%s, %s,%s, %s, %s,%s, %s,%s, %s, %s)', (Price,0,Person,Primary_location,time,T_name,movieName,))
    #cursor.execute('insert into ticket_cnf values(%s, %s,%s, %s, %s,%s, %s,%s, %s, %s)', (Price,0,Person,Primary_location,time,T_name,today,movieName,('select user_id from user where username = %s'),('select hall_id from theatre where location = %s ')),(username,T_name))
    cursor.execute(
        "insert into ticket_cnf(total_cost,payment,no_of_tickets,hall_name,show_time,location,date,movie_name,user_id,hall_id) values ('{}','{}','{}','{}','{}','{}','{}','{}',(select user_id from user where email_id = '{}'),(select hall_id from theatre where location = '{}' ))"
        .format(Price, 0, Person, Primary_location, time, T_name, today,
                movieName, email, Primary_location))
    mysql.connection.commit()

    m.mail(username, movieName, T_name, Primary_location, time, Price, email)
    return "0"
Beispiel #43
0
 def display(self):
     for person in self.plist:
         #print(person)
         idx = person['Email Address']
         name = person['First Name']
         self.elist.append(idx)
         print(name)
         context = """Hi,""" + name + """:
             I am a motivated ICT professional who has ever worked for over ten years, with the expertise of java&python development, both front-end, and back-end, 
             software testing(TDD-junit , cucumber, BDD- selenium), continuous integration and delivery.
             
             As a system designer: according to the diverse demands, choose suitable technologies, and set up system framework, then design the architectures, 
             including database, application frameworks, prototype
             As a system developer and tester: familiar with SDLC, develop safe and effective code in financial, mechanical systems, such as CRM system for Nepal telecom, 
             IPTV for Italy media, refactor project structures. 
             And use Junit,cucumber&selenium to validate functions
             As a system maintainer&optimizator: set up developing&delivery environment,manage& parameterize&optimize delivery system
             I am also an active communicator with excellent teamwork and analytical skills used to get the effect in succeeding in a high-pressure situation
             
             technical skill sets
             Front-end: HTML5,CSS3,Bootstrap,JavaScript,Ajax,JQuery,Backbone,AngularJS,XML,JSON,Restful API
             Back-end: Spring, SpringMVC,hibernate,Mybatis,JDBC,Struts,Shiro,WSDL,web interfaces,Swing
             Database: Oracle, Mysql,MongoDB,SQLite,SQL server
             MQ&distributing system:MQTT,Kafka,HBase,Hadoop
             Search engine: Lucene, ElasticSearch, such as splitting words and optimization of the index building
             Python: spiders, machine learning, Django
             Test skills:write test cases,find bugs,PDM,TDD,JUnit,CUCUMBER,and BDD,Selenium
             Servers:Tomcat,JBoss,Weblogic,IIS,NodeJS,Redis,Nginx,FTP,Image,Apache,Maven,docker,kubernate
             Design; power design, Axure RP, UML, Dia
             Control:SVN,Git,Jira,Ant,Maven,Jenkins
             Methodology: Agile-Scrum, Waterfall
             System: Linux, Linux kernel, windows, a deep research in Linux kernel
             IDE:Eclipse,plugins,IDEA,Anaconda
             Android:3Y+ experiences  
             
             More details can be found in my LinkedIn:https://www.linkedin.com/in/alex-wang-63237b39/. 
             My Github is https://github.com/swoec, you can find some of my works there.
             Currently, I am seeking a job in New Zealand .
             I write this letter to you because you may be able to offer me a job opportunity.
             If you have, please contact me.
              
             If you do not want to help me or this letter disturb you, please ignore it.
             My email: [email protected]
             Looking forward to your reply.
             Best Regards
             Alex
                                                                       
          """
         #context = context.encode('utf-8')
         context = context.decode('utf-8').strip()
         self.dir[idx] = {context}
         self.contextlist.append(context)
         #print(person['First Name'])
         #print(person['Email Address'])
         title = name + " " + person['Last Name']
         #print(title)
     mails = mail(self.elist, title, self.dir)
     mails.sendmail()
def motion():

    time.sleep(3)
    print('started')
    cam = cv2.VideoCapture(0)
    i = 0
    first = None
    while True:
        ret, img = cam.read()
        img = cv2.resize(img, (480, 360))
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (21, 21), 0)

        k = cv2.waitKey(500)
        if (k == ord('q')):
            break
        ret1, first = cam.read()
        first = cv2.resize(first, (480, 360))
        gray1 = cv2.cvtColor(first, cv2.COLOR_BGR2GRAY)
        first = cv2.GaussianBlur(gray1, (21, 21), 0)

        a = cv2.absdiff(gray, first)
        b = cv2.countNonZero(a)

        print('\n\n\n\n')
        cv2.imshow('a', img)
        cv2.imshow('ay', first)
        if (b > 60000 and i > 3):
            print(a)
            x = 'img' + str(randint(44343, 432355545)) + '.jpg'
            cv2.imwrite('C:\\Users\\ayush\\Desktop\\pyth\\test\\{}'.format(x),
                        img)
            mail(x)

            break

        k = cv2.waitKey(1)

        i += 1

        if (k == ord('q')):
            break

    del (cam)
    cv2.destroyAllWindows()
def create(request):
	if request.method=='GET':
		return render_to_response('Account/create.html', RequestContext(request))
	elif request.method=='POST':
		try:
			maxid = User.objects.aggregate(Max('id'))
			newUser = User(id=maxid['id__max']+1,first_name=request.POST['firstname'],last_name=request.POST['lastname'],email=request.POST['email'],password=request.POST['password'],username=request.POST['username'])
			newUser.profile=Profile(activated=False,interests=request.POST['interests'], user=newUser,major=request.POST['major'],email_subscribed='wantemails' in request.POST.keys(), gradmonth=request.POST['gradmonth'], gradyear=request.POST['gradyear']);
			newUser.save();
			newUser.profile.save();

			mail(request.POST['email'],"Account Confirmation",genMessage(request.POST,newUser.id));

			return render(request,'Account/create_success.html', {'firstname':request.POST['firstname'],'email':request.POST['email']});
		except IntegrityError:
			return render(request,'Account/create_error.html', {'message':"Username '{0}' is already taken.".format(request.POST['username'])});
		except Exception:
			return render(request,'Account/create_error.html', {'message':'An unexpected exception has occurred. Please try again later. If the problem persists, please contact [email protected].'});
Beispiel #46
0
	def __init__(self):
		
		self._conf = config()
		self._git_list = self._conf.get('git').split(',')
		self._logger = log.getLogger(self.__module__)
		self._patchdir = self._conf.get('patchdir')
		self._git_dir = self._conf.get('gitdir')
		# mail object
		self._mailobj = mail(self._conf)
Beispiel #47
0
	def imageprocess(self, indir, outdir, clf):
                mytime = timeLog('../timelogs/image_test')
                make_dir(outdir)
                # loop for every images in directory
                if not 'decision_function' in dir(clf):
                        clf.decision_function = clf.predict
                        print 'decision function created!'
                for k, data in enumerate(self.data):
                        print 'Image-Process:', data[0], k,'/',len(self.data)
                        imgname = data[0]
                        image = data[1]
                        mytime.start(imgname)
                        img = image_load(imgname, indir)
                        res_stack = self.multiscale_test2(img, image)
                        pickle_save(res_stack, os.path.splitext(imgname)[0], outdir)
                        mytime.end()
                mail(self.mail_rec, '<Coding Message!!!>, image_test_finished!')
                mytime.final('image test finished')
		return
Beispiel #48
0
	def clf_train(self):

		'''  clf_train(self, clfname, mode = 'adaboost')

		train the classifier with feature generated
		clfname: _string_ contains filename of the classifier to save
		mode: {'adaboost', 'SVM', 'vjcascade', 'gridSearch'} _string_, 
			classifier type, where gridSearch is searched over 
			different types of SVM classifiers. '''

                mytime = timeLog('../timelogs/clf_train')
                mytime.start()

		print 'Training Classifier on ',
                print len(self.label), 'Samples'
		self.classifier = self.classifier.fit(self.feature, self.label)
		mail(MAIL_REC, '<Coding Message!!!>, clf_train_finished')
                mytime.end()
                mytime.final()
                return
Beispiel #49
0
        def prepareImg(self, dataStack, indir, outdir):
                ''' image_pretest(self)

                test and show the ground truth label images from the training and testing data
                before we start the training process.	
                '''
                mytime = timeLog('../timelogs/prepare_img')
                make_dir(outdir)
                # loop for every images in directory
                for k, data in enumerate(dataStack):
                        imgname, coor = data
                        print imgname, str(k), '/', len(dataStack)
                        mytime.start(imgname)
                        img = image_load(imgname, indir)
                        img, coor = imsize_reduce((1400, 1400), img, coor)
                        image_save(img, imgname, outdir)
                        dataStack[k] = (imgname, coor)
                        mytime.end()
                mail(MAIL_REC, '<Coding Message!!!>, image_pretest_finished')
                mytime.final('prepare images finished.')
                return dataStack
Beispiel #50
0
        def roi_test2(self, indir, outdir, clf):
		''' roi_test2(self, indir, outdir, clf)

                apply detection on region of interest
		'''
                mytime = timeLog('../timelogs/image_test')
                make_dir(outdir)
                # loop for every images in directory
                if not 'decision_function' in dir(clf):
                        clf.decision_function = clf.predict
                        print 'decision function created!'

                for k, data in enumerate(self.data):
                        print 'Image-Test:', data[0], k,'/',len(self.data)
                        imgname = data[0]
                        mytime.start(imgname)
                        roiname = os.path.splitext(imgname)[0]
                        roistack = pickle_load(roiname, indir)

                        predpnt_stack = []
                        predblk_stack = []
                        for img in roistack:
                                patch = self.image2feat(img,
                                        self.psize, self.ssize,
                                        self.nob, self.codebook,
                                        target = self.featureMode,
                                        edgeMode = self.edgeMode)
                                pred = self.feat2pred(img, patch, clf)
                                predpnt = self.label2image(img, pred, mode = 'point')
                                predblk = self.label2image(img, pred, mode = 'block')
                                predpnt_stack.append(predpnt)
                                predblk_stack.append(predblk)

                        pickle_save((predpnt_stack, predblk_stack), os.path.splitext(imgname)[0], outdir)
                        mytime.end()
                mail(self.mail_rec, '<Coding Message!!!>, image_test_finished!')
                mytime.final('image test finished')
		return
Beispiel #51
0
        def geneROI2(self, imdir, indir, outdir, thre = 128):
                ''' geneROI2(self, indir, outdir)

                crop the region of interest from the stack
                '''
                
                mytime = timeLog('../timelogs/testHotmap')
                make_dir(outdir)
                for k, data in enumerate(self.data):
                        print 'Generate roi:', data[0], k, '/', len(self.data)
                        imgname = data[0]
                        mytime.start(imgname)
                        imgname = os.path.splitext(imgname)[0]
                        s = pickle_load(imgname, indir)[1]
                        roi_stack = []
                        for layer in s:
                                bb = image2bb(img, thre)
                                bb = bbenlarge(bb, img.shape)
                                roi_stack.append(image2roi(raw, bb))
                        pickle_save(roi_stack, basename, outdir)
                        mytime.end()
                mail(self.mail_rec, '<Coding Message!!!>, hotmap generation finished')
                mytime.final('hotmap generation finished')
                return
Beispiel #52
0
        def geneTxt(self, indir, outdir, thre = 128):
                '''geneTxt(self, indir, outdir)

                generate csv file from the hotmaps to be in ICDAR standard format
                '''
                mytime = timeLog('../timelogs/testTxtFile')
                make_dir(outdir)
                for k, data in enumerate(self.data):
                        print 'Generate txt files:', data[0], k, '/', len(self.data)
                        imgname = data[0]
                        mytime.start(imgname)

                        basename = os.path.splitext(imgname)[0]
                        blkname = 'block'+basename+'.png' # use block plot as hotmap
                        txtname = 'res_img_'+basename+'.txt'

                        img = image_load(blkname, indir)
                        bb = image2bb(img, thre)
                        s = bb2string(bb)
                        txt_save(s, txtname, outdir)
                        mytime.end()
                mail(self.mail_rec, '<Coding Message!!!>, txt generation finished')
                mytime.final('txt file generation finished')
                return
Beispiel #53
0
def notify(new_results):
    print "Notifying new courses"
    if config.NOTIFY_SERVICE == 'email':
        client = mail.mail()
    elif config.NOTIFY_SERVICE in ['nma', 'prowl', 'pushover']:
        client = pushnotify.get_client(config.NOTIFY_SERVICE,
                                       application='StudWeb')
        client.add_key(config.NOTIFY_APIKEY)

    text = "New exam results: "
    for result in new_results:
        text = text + "Course: %s, grade: %s; " % \
            (result.get('name', 'Unknown'), result.get('grade', 'Unknown'))
        if config.VERBOSE:
            print "Notiying new course %s" % result['name']
    client.notify(text, "New exam results")
    print ""
Beispiel #54
0
	argv['items'].append({"icon":"link", "itemkey":"监控详情", "itemvalue":httptestid})
	objurl = cmdb + "/object.php?action=show&id=" + orig['objid']
	objid = "<a href=\"" + objurl + "\">" + objurl + "</a>"
	argv['items'].append({"icon":"link", "itemkey":"CMDB详情", "itemvalue":objid})
	argv['items'].append({"icon":"link", "itemkey":"负责人", "itemvalue":orig['admin']})

	return(tpl.mailTemplate(argv))

if __name__ == '__main__':
	try:
		orig = sys.argv[3].replace('"', '#')
		orig = orig.replace('\'', '"')
		orig = orig.replace('ouldn"t', 'ould not')
		data = json.loads(orig)

		itemid = data['itemid']
		subject = sys.argv[2]
		contact = init(itemid)
		print(contact)
		data['httptestid'] = contact['httptestid']
		data['objid'] = contact['objid']
		data['admin'] = contact['email'].replace('@letv.com', '') + "(" + contact['phone'] + ")"
		content = getContent(data)
		mail(contact, subject, content)
		sms_content = subject + ": " + data['itemvalue']
		sms(contact, sms_content)

	except:
		logging.exception("Exception Logged")

Beispiel #55
0
import sys
sys.path.append('../')  

from mail import send as mail

if __name__ == '__main__':
    mail('localhost:25', '*****@*****.**', '*****@*****.**', 'Hellooooooooooooo') 

Beispiel #56
0
    body += "Total Hours: %3.2f\n\n" % total_hours_by_employee[person]
    log_text += "Total Hours: %3.2f\n\n" % total_hours_by_employee[person]

    body += """If this is correct, please reply letting us know! If it's not, please let us know what's wrong!

Thanks!
EM

"""

    person_data = conn.get_person(person)
    email_address = person_data.email_address

    if debug:
        print email_address
        print body
        print log_text
        # for person in people_summary:
    #             for project in people_summary[person]:
    #                 if people_summary[person][project] > 0.0:
    #                     print "%s: %3.2f Hours.\n" % (our_projects[project],people_summary[person][project])

    else:
        print "Sending email to %s" % people[person]
        f = open(os.path.join(repo_dir, people[person].strip().replace(" ", "")) + ".txt", "w")
        f.write(log_text)
        f.close()

        mail(email_address, "Erdos Miller - Payroll - Please Verify", body)
Beispiel #57
0
lastid = lasttweet.get('id',0L)
lastdate = lasttweet.get('date', datetime.datetime.fromtimestamp(0))
lasttext = lasttweet.get('text')
lastkafkaid = long(lasttweet.get('kafkaid',0L))

msg = ""
msg += "livetweet: \t%s\t%s\t%s\n" % (livedate, liveid, livetext)
msg += "lasttweet: %s\t%s\t%s\t%s\n" % (lastkafkaid, lastdate, lastid, lasttext)

print msg

if lastid > 0:
    if lastid != liveid:
        err = "liveid and lastid don't match :(\n"
        print err
        mail.mail("*****@*****.**","tweet failed", err + msg, None)
        sys.exit(1)
    if lasttext != livetext:
        err = "liveitext and lasttext don't match :(\n"
        print err
        mail.mail("*****@*****.**","tweet failed", err + msg, None)
        sys.exit(1)

tweetsfile = open('metamorphosis_tweets.txt')
for line in tweetsfile:
    parts = line.strip().split('\t')
    kafkaid = long(parts[0])
    dt = datetime.datetime.strptime(parts[1], '%Y-%m-%d %H:%M:%S')
    if kafkaid > lastkafkaid and len(parts) > 2:
        text = parts[2]
        break
Beispiel #58
0
        def roi_test(self, indir, rawdir, outdir, clf):
		''' roi_test(self, indir, outdir, clf)

                apply detection on region of interest
		'''
                mytime = timeLog('../timelogs/image_test')
                make_dir(outdir)
                # loop for every images in directory
                if not 'decision_function' in dir(clf):
                        clf.decision_function = clf.predict
                        print 'decision function created!'

                for k, data in enumerate(self.data):
                        try:
                                print 'ROI test:', data[0], k, '/', len(self.data)
                                imgname = data[0]
                                img = data[2] 
                                mytime.start(imgname)
                                raw = image_load(imgname, rawdir)
                                stackname = os.path.splitext(imgname)[0]
                                s = pickle_load(stackname, indir)[1]
                                layer_stack = []
                                for layer in s:
                                        bb = image2bb(layer)
                                        #bb = bbenlarge(bb, layer.shape)
                                        raw = img_resize(raw, layer.shape)
                                        rois = image2roi(raw, bb)
                                        predpnt_stack = []
                                        #predblk_stack = []
                                        for rimg00 in rois:
                                                rimg0 = imreduce(64, rimg00)
                                                predpnt = numpy.zeros_like(rimg0)
                                                for ang in [-6, -4, -2, 0, 2, 4, 6]:
                                                        rimg = rotate(rimg0, ang)
                                                        patch = self.image2feat(rimg,
                                                                self.psize, self.ssize,
                                                                self.nob, self.codebook,
                                                                target = self.featureMode,
                                                                edgeMode = self.edgeMode)
                                                        pred = self.feat2pred(rimg, patch, clf)
                                                        predpnt0 = self.label2image(rimg, pred, mode = 'point')
                                                        predpnt = predpnt + rotate(predpnt0, -ang)
                                                for asp in [0.6, 0.8, 1, 1.2, 1.4]:
                                                        rimg = img_resize(rimg0, [int(rimg0.shape[0]*asp), rimg0.shape[1]])
                                                        patch = self.image2feat(rimg,
                                                                self.psize, self.ssize,
                                                                self.nob, self.codebook,
                                                                target = self.featureMode,
                                                                edgeMode = self.edgeMode)
                                                        pred = self.feat2pred(rimg, patch, clf)
                                                        predpnt0 = self.label2image(rimg, pred, mode = 'point')
                                                        predpnt = predpnt+img_resize(predpnt0, rimg0.shape)
                                                predcc = pnt2cc(rimg0, predpnt)
                                                predcc = img_resize(predcc, rimg00.shape)
                                                #predblk = self.label2image(img, pred, mode = 'block')
                                                predpnt_stack.append(predcc)
                                                #predblk_stack.append(predblk)
                                        layer_stack.append(roi2image(predpnt_stack, bb, layer.shape))
                                img = stack2image(layer_stack, img)
                                pickle_save(layer_stack, stackname, outdir)
                                image_save(img, imgname.split('.')[0]+'.png', outdir)
                                mytime.end()
                        except:
                                mytime.end()
                                continue
                mail(self.mail_rec, '<Coding Message!!!>, hotmap generation finished')
                mytime.final('hotmap generation finished')
                return
Beispiel #59
0
import sys, pygame, pygbutton, operator, time, mail, json, os, threading, thread, math, ConfigParser
pygame.init()
pygame.font.init()

config = ConfigParser.ConfigParser()
config.read('settings.cfg')

pygame.display.set_caption("Project Internet of Hearts")

size = width, height = 480, 320

mailer = mail.mail()

timerStarttime = 0
page = 0
image = 0
view = 1  #which screen we're at
jsonData = []

canvasColor = (255,255,255)

flags = 0
if config.getboolean('Env', 'fullscreen'):
    flags = pygame.FULLSCREEN

surface     = pygame.display.set_mode(size, flags)
drawCanvas  = pygame.surface.Surface((410,260))
drawCanvas.fill(canvasColor)

btnSend = pygbutton.PygButton((10, 10      , width-20, 100), 'Send Message',  (100,100,100), (0,0,0), pygame.font.Font('freesansbold.ttf', 30))
btnRead = pygbutton.PygButton((10, 10 + 110, width-20, 100), 'Read Messages', (100,100,100), (0,0,0), pygame.font.Font('freesansbold.ttf', 30))
Beispiel #60
0
import parse_tests_results
#parse xml files
failed = False
message = ""
subject = "XMIPP compilation "
results = parse_tests_results.parseResults()
for group in results:
    n = len(group.tests)
    if group.failed > 0:
        message += "   [  FAILED  ] Group: %s, failed %d of %d tests.\n" % (group.name, group.failed, n)
        failed = True
    else:
        message += "   [  OK      ] Group: %s, succeed %d tests.\n" % (group.name, n) 
        
if failed:
    subject += "FAILED"
else:
    subject += "OK"
subject += "(" + XMIPP_BRANCH + ")"

#print subject
#print message
#Send notification mail
import mail
from config import toaddrs
from config import fromaddr 
mail.mail(toaddrs, fromaddr, subject, message, filename)