def writeCsv(): time = int(getTime.getTime()) #print(time) p_outputFilePath = "results/" + str(time) + ".csv" global p_df if not os.path.exists('results/'): os.makedirs('results/') if not (os.path.exists(p_outputFilePath)): p_df.to_csv('maruhan/results/' + str(time) + '.csv', encoding='utf_8_sig')
def run(self, src , dst , user, project): self.document = Document(src) self.user = getTime(user) self.colorDict = getColorStyle() #针对modifyDate dateList = self.user.modifyDate self.user.modifyDate = List2Dot(self.user.modifyDate) #获取项目对象 self.project = project if self.project != None: event = self.project.ServiceProcess.Event #受理事件数 self.accepted = event.S1 + event.S2 + event.S3 + event.S4 #重大事件比率 self.criticalRate = event.S1 / self.accepted #事件关闭率 self.closeRate = self.accepted / event.closed #更新目录 element_updatefields = lxml.etree.SubElement( self.document.settings.element, "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"+"updateFields" ) element_updatefields.set("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"+"val", "true") threadList = [] threadList.append(threading.Thread(target=self.findAndReplaceFootAndHead)) threadList.append(threading.Thread(target=self.findAndReplaceTables)) threadList.append(threading.Thread(target=self.findAndReplaceParagraphs)) #一层SM文件有职责表 if re.search( "(.*)-SM-(.*)" , src ): self.replaceDepartmentTable() for t in threadList: t.start() for t in threadList: t.join() print('成功生成 '+dst ) #针对modifyDate self.user.modifyDate = dateList return self.document
def getSlump(id): time = int(getTime.getTime()) #print(time) url = 'https://nifmbapi.maruhan.co.jp/api/v1.4/machine/slump' query = {'hall_code': 1061, 'machine_id': id, 'date': time} #1クエリストリングの作成 url_with_query = "{}?{}".format(url, urllib.parse.urlencode(query)) #print(url_with_query) response = urllib.request.urlopen(url_with_query) content = json.loads(response.read().decode('utf_8_sig')) #pprint.pprint(content) if (content["datas"]): for item in content["datas"][0]["items"]: result = item["value"] #print(result) return result else: return 0
def getInfo(cstr): #print(cstr) time = int(getTime.getTime()) #print(time) url='https://nifmbapi.maruhan.co.jp/api/v1.4/machine/info' query={ 'hall_code' : 1061, 'machine_id' : cstr, 'date' : '[\"'+str(time)+'\"]' } #1クエリストリングの作成 url_with_query = "{}?{}".format(url, urllib.parse.urlencode(query)) #print(url_with_query) response = urllib.request.urlopen(url_with_query) content = json.loads(response.read().decode('utf8')) #pprint.pprint(content) if (content["datas"]): #print(content['datas'][0]['number_of_all_starts']) return content['datas'][0]['number_of_all_starts'] , content['datas'][0]['number_of_bbs'] , content['datas'][0]['number_of_rbs'] else: return 0,0,0
import requests from datetime import datetime import hashlib import base64 from xml.sax.saxutils import escape from chardet.universaldetector import UniversalDetector import random import SystemMain import pandas as pd import getTime import numpy as np USER_NAME = 'katey_que' BLOG_NAME = 'katey-que.hatenablog.com' PASSWORD = '******' TITLE = ' {0} 今日の苗穂マルハン'.format(getTime.getTime()) FILE_NAME = 'maruhan/templeates/test_article.txt' def create_hatena_text(title, name, body, updated, categories, is_draft): is_draft = 'yes' if is_draft else 'no' categories_text = '' for category in categories: categories_text = categories_text + '<category term="{}" />\n'.format(category) template = """<?xml version="1.0" encoding="utf-8"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app"> <title>{0}</title> <author><name>{1}</name></author> <content type="text/html">{2}</content> <updated>{3}</updated>
os.system("rm -rf %s/npx4-*/%s.*" % (prefix, jobID)) continue # Check the error file for any lines that aren't harmless isGood = True errFile = "%s/npx4-error/%s.error" % (prefix, jobID) with open(errFile, "r") as f: err = f.readlines() err = [line.strip() for line in err] # Remove non-error-related I3Tray output err = [l for l in err if l.split(" ")[0] not in oks] if any([line not in safeErrors for line in err]): isGood = False # Check to make sure timing calculation works t0 = getTime("%s/npx4-logs/%s.log" % (prefix, jobID)) # Append run number to good or bad run list if isGood and t0: goodRuns.append(jobID) t += t0 tList += [t0] else: badRuns.append(jobID) if len(goodRuns) != 0: print "Average time per job for good runs:", t / len(goodRuns), "seconds" tList.sort() print "Min time:", tList[0] print "Max time:", tList[-1]
def drawContours(image_original, image_thresh, count, states, t, time_capon, time_capoff): image_contour, contours, hierarchy = cv2.findContours(image_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print("Number of Contours found = " + str(len(contours))) #putText(image_original, "Number of object: " + str(number_of_objects_in_image), 500, 350) for cnt in contours: # Skip if the contour area is small area = cv2.contourArea(cnt) if area < 700: continue # Draw the contour #cv2.drawContours(image_original, [cnt], -1, (0, 255, 0), 2) # Find the center M = cv2.moments(cnt) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) if cX < 750 or cX > 875: continue rect = cv2.boundingRect(cnt) if rect[2]*rect[3] < 1000: continue a,b,w,h = rect cv2.rectangle(image_original,(a,b),(a+w,b+h),(0,255,0),2) s = rect[2]*rect[3] # Draw the center cv2.circle(image_original, (cX, cY), 3, (0, 0, 255), -1) if s > 6000: count = count + 1 states = "OK" t = getTime() time_capon = time_capon + 1 #putText(image_original, "OK", 1000, 750) #putText(image_original, t, 1000, 800) if s < 4000: count = count + 1 states = "NG" t = getTime() time_capoff = time_capoff + 1 NG_image = image_original.copy() putText(NG_image, states, 1100, 650) putText(NG_image, "Time: "+t, 1100, 700) putText(NG_image, "Number of tests: " + str(count), 1100, 750) putText(NG_image, "Number of OK: " + str(time_capon), 1100, 800) putText(NG_image, "Number of NG: " + str(time_capoff), 1100, 850) name = './NG_' + str(time_capoff) + '.jpg' cv2.imwrite(name, NG_image) return count, states, t, time_capon, time_capoff
print('{} is empty!'.format(outFile)) continue #if lines[-1].strip() != 'Fin': # continue # If it doesn't have an error file, remove orphan files errFile = '{}/npx4-error/{}.error'.format(args.npxdir, jobID) if not os.path.isfile(errFile): os.system('rm -rf %s/npx4-*/%s.*' % (args.npxdir, jobID)) continue # Check the error file for any lines that aren't harmless isGood = goodFile(errFile, args.strictError) # Append run number to good or bad run list t0 = getTime('%s/npx4-logs/%s.log' % (args.npxdir, jobID)) if isGood and t0: goodRuns.append(jobID) t += t0 tList += [t0] #if isGood and not t0: # Job still running? # continue else: badRuns.append(jobID) # Print information on state of npx4 files nFinished = len(goodRuns) + len(badRuns) nRunning = len(jobIDs) - nFinished if nRunning != 0: print('Running (%i file(s)):' % nRunning) for jobID in jobIDs:
# coding=utf-8 import ReadAndWrite import getTime thisTime = getTime.getTime() # 这次修改的时间 print(thisTime) print(getTime.getFileSize("C:\VideoSample")) # ReadAndWrite.write('time.txt', str(thisTime)) # lastTime = ReadAndWrite.read('time.txt')
GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) # set initial hardware actions hardwareactions.setfan(False) # arudino interrupt - from battery watchdog hasBWInterrupted = False # interrupt state variable #GPIO.setup(11, GPIO.IN ) GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #GPIO.add_event_detect(11, GPIO.RISING, callback=arduino_callback) # add rising edge detection on a channel #GPIO.add_event_detect(11, GPIO.RISING) # add rising edge detection on a channel # set time from arduino RTC getTime.getTime("main", 1) scheduler = Scheduler() job = scheduler.add_cron_job(powerdatacollect.datacollect5minutes, minute="*/5", args=['main', 0]) job = scheduler.add_cron_job(watchdogdatacollect.watchdogdatacollect, minute="1,6,11,16,21,26,31,36,41,46,51,56", args=['main', 0]) job = scheduler.add_cron_job(environdatacollect.environdatacollect, minute="*/15", args=['main', 10]) job = scheduler.add_cron_job(systemstatistics.systemstatistics15minutes, minute="*/15", args=['main', 50]) # new task for the Fram Arduino Weather Log job = scheduler.add_cron_job(getFramArduinoLog.getFramArduinoLog, minute="34", args=['main', 10]) # start system monitoring job = scheduler.add_cron_job(monitorSystem.monitorSystem, minute="3,8,13,18,23,28,33,38,43,49,53,57", args=['main', 0])
os.system('rm -rf %s/npx4-*/%s.*' % (prefix, jobID)) continue # Check the error file for any lines that aren't harmless isGood = True errFile = '%s/npx4-error/%s.error' % (prefix, jobID) with open(errFile, 'r') as f: err = f.readlines() err = [line.strip() for line in err] # Remove non-error-related I3Tray output err = [l for l in err if l.split(' ')[0] not in oks] if any([line not in safeErrors for line in err]): isGood = False # Check to make sure timing calculation works t0 = getTime('%s/npx4-logs/%s.log' % (prefix, jobID)) # Append run number to good or bad run list if isGood and t0: goodRuns.append(jobID) t += t0 tList += [t0] else: badRuns.append(jobID) if len(goodRuns) != 0: print 'Average time per job for good runs:', t / len( goodRuns), 'seconds' tList.sort() print 'Min time:', tList[0] print 'Max time:', tList[-1]
def process(activity): # print activity # activity_list = activity.split() punctuation = set(string.punctuation) plainTerms = ["a", "e", "i", "o", "u", "y", "me", "you", "of", "in", "for", "at", "the", "an"] locSearchTerms = ["find", "locate", "located", "location", "where", "search for"] ISSterms = ["international space station", "the space station", "space station", "iss"] googleMapsTerms = ["map", "maps", "google"] aboutMeQuestions = ["who are you?", "who are you", "what is your name?", "what is your name", "explain yourself", "tell me about yourself"] doneTerms = ["quit", "done", "nevermind", "leave", "leave me alone", "shutdown", "no"] doneMatchTerms = ["quit", "done", "leave", "peace", "bye", "goodbye", "shutdown", "shut down", "turn off", "off"] gratefulTerms = ["thanks", "thank you", "i appreciate", "please"] shutdownTerms = ["shutdown", "shut down", "off", "turn off"] welcomeResponses = ["You're very welcome, sir.", "My pleasure.", "Of course."] doneTerms = doneTerms + doneMatchTerms + shutdownTerms activityClean = stripPunc(activity, punctuation, []) activityPosNeg = stripPunc(activity, punctuation, ["+", "-"]) activity_list = activityClean.split() activity_list_pos_neg = activityPosNeg.split() # print activity_list_pos_neg if activity[:len("mdfind")].lower() == "mdfind": # print os.system(activity) search_results = str(os.system(activity)) # print search_results # print type(search_results) line_count = 0 # while line_count < 5: # print search_results[line_count] # line_count += 1 return True """The following for loop checks if gratefulTerms[x] in IN the activity string, or if it IS the activity string. Once it finds a match, either it leaves the function, or it leaves the for loop and continues throught the function""" for term in gratefulTerms: if term in activity: x = random.randrange(0,len(welcomeResponses)) respond(welcomeResponses[x]) if term == activity: return True else: break for term in aboutMeQuestions: if activity == term: aboutMe.iAmBeeker() return True if activity[:len('wiki')] == "wiki" or activity[:len('wikipedia')] == "wikipedia": # respond(wikipedia.summary(activity[len('wiki'):])) searchWiki.getWiki(activity) return True if activity[:len('summarize')] == "summarize" or activity[:len('summary')] == "summary": # respond(wikipedia.summary(activity[len('summarize'):], sentences = 2)) searchWiki.getWiki(activity) return True if 'question' in activity: respond("What would you like to know?") question = raw_input("\n ") question = question.lower() print '\n' if question == 'quit()' or 'done' in question or 'nevermind' in question: greetings.anyMoreQuestions() else: ask(question) return True if 'time' in activity and 'in' not in activity: if getTime(activity) == False: respond("That didn't make sense") return True if "weather" in activity or "forecast" in activity: # pattern = re.compile("\\b(of|the|in|for|at|weather|check|find|how|how's|is|tell|me|check|out|about)\\W", re.I) # string = re.sub(pattern, "", activity) # string = string.replace(" ", "") if "forecast" in activity: weatherCheck.getForecast(activity) else: # weatherCheck.getWeather(activity) checkWeather() respond("Finished weather check") return True for term in ISSterms: if term in activity.lower(): # print "Found:", term for word in locSearchTerms: if word in activity: # print "Found:", word locateISS() return True # for term in acivity: # term = term.lower() # if term in locSearchTerms and term in ISSterms: # locateISS() # elif term in locSearchTerms and term in googleMapsTerms: for term in googleMapsTerms: if term in activity_list_pos_neg: try: latitude = float(activity_list_pos_neg[1]) longitude = float(activity_list_pos_neg[2]) # print latitude, longitude googleMaps(latitude, longitude, True) except: respond("If you're trying to use Google Maps, make sure to use two numbers") return True grateful = False for term in doneTerms: if term in activity: # print "Found a doneTerms item:",activity if 'off' in activity or 'down' in activity or 'shut' in activity: for item in shutdownTerms: if item == activity: greetings.shutdownGoodbye() sys.exit(0) if 'piss off' in activity or 'f**k off' in activity: greetings.madGoodbye() sys.exit(0) if activity[len(activity)-len(term):] == term or activity[:len(term)] == term: # print "Found a doneTerms item at end of string:", activity for term in gratefulTerms: if term in activity: grateful = True if grateful == False: respond("Very well, sir.") greetings.goodbye() sys.exit(0) return False
while (i==0): #id_list != [] -> repray recommendation try: timeline=api.mentions_timeline(count=10) except tweepy.RateLimitError: print "ERROR" for status in timeline: status_id=status.id if status_id not in id_list: screen_name=status.author.screen_name.encode("UTF-8") cate = categolaze.getCategory(status.text) time = getTime.getTime(status.created_at) date = getTime.getDate(status.created_at) #senti = convert_senti(status.text) #senti = (u"POSITIVE") print "mentiontext:"+status.text print status.id print screen_name """user全部tweet""" text=[] text= get_user_tweet(api,screen_name) text.append(status.text) # print text # for t in text: # print t senti=convert_multitude_senti(text)
""" testModule.py JCS 9/10/2013 Version 1.0 This program runs the data collection, graph preperation, housekeeping and actions """ from datetime import datetime, timedelta import sys import time sys.path.append('./datacollect') sys.path.append('./graphprep') sys.path.append('./hardware') sys.path.append('./housekeeping') import getTime getTime.getTime("test",1)