def getStatus(session_id, host_id): """Returns a dictionary describing the status of the host""" # Get some basic info hostname = getHostName(session_id, host_id) hoststatus = getHostStatus(hostname) # Get the host's CFengine status status = getCfengineHostStatus(session_id, hoststatus.host._properties) # Get state information status["reachable"] = hoststatus.reachable status["operating_rev"] = hoststatus.operatingRevision status["operating_rev_status"] = hoststatus.operatingRevisionStatus status["operating_rev_text"] = hoststatus.operatingRevisionText status["operating_rev_hint"] = hoststatus.operatingRevisionHint status["active_rev"] = hoststatus.activeRevision status["generated_rev"] = hoststatus.generatedRevision status["current_load"] = hoststatus.currentLoad status["uptime"] = hoststatus.uptime status["infoUpdatedAt"] = time.strftime("%d/%m/%Y %H:%M:%S", \ time.localtime(hoststatus.infoUpdatedAt)) status["lastCheckedAt"] = time.strftime("%d/%m/%Y %H:%M:%S", \ time.localtime(hoststatus.lastCheckedAt)) return status
def Update(self): saat = str(config.plugins.TimeSet.UTCTim.value[0]) if len(saat) < 2: saat = '0' + saat minuti = str(config.plugins.TimeSet.UTCTim.value[1]) if len(minuti) < 2: minuti = '0' + minuti sekunde = strftime('%S', localtime()) pp = config.plugins.TimeSet.NDate.value import time TimeString = time.strftime('%Y%m%d', time.gmtime(pp)) + saat + minuti + sekunde RTCString = time.strftime('%Y.%m.%d', time.gmtime(pp)) + '-' + saat + ':' + minuti + ':' + sekunde TimeZoneS = config.timezone.val.value ipos1 = TimeZoneS.find('(GMT') ipos2 = TimeZoneS.find(')') tmp = TimeZoneS[ipos1 + 4:ipos2] if len(tmp) == 0: tmp = '+00' tzpredznak = tmp[:1] tzvalue = str(int(tmp[1:3])) TimeString = TimeString + tzpredznak + tzvalue import os as os cmd = 'echo "' + str(TimeString) + '" > /proc/settime' os.system(cmd) cmd = 'date -u -s "' + str(RTCString) + '"' os.system(cmd) self.session.openWithCallback(self.callback, MessageBox, _('RTC Update done! \n\nGUI Clock Update done!'), type = 1, timeout = 5)
def pushMovementReadings(interval=1, print_results=True): while (True): try: Acceleration = sense.get_accelerometer_raw() Orientation = sense.get_orientation() north = sense.get_compass() time_sense = time.strftime('%H:%M:%S') date_sense = time.strftime('%d/%m/%Y') data = { "MAC": MacAddress, "Date": date_sense, "Time": time_sense, "Acceleration": Acceleration, "Orientation": Orientation, "Compass": north } db.child("/Movement").push(data) if print_results == True: x = Acceleration['x'] y = Acceleration['y'] z = Acceleration['z'] pitch = Orientation["pitch"] roll = Orientation["roll"] yaw = Orientation["yaw"] print("Time: {0}\tMacAddress: {1}".format( time_sense, MacAddress)) print("\tX={0}, Y={1}, Z={2}".format(x, y, z)) print("\tPitch {0} Roll {1} Yaw {2}\n\n".format( pitch, roll, yaw)) except Exception as e: raise sleep(interval)
def pushEnvironmentalReadings(interval=10, print_results=True): #Take readings from all three sensors and ound the values to one decimal place while (True): try: Temperature = sense.get_temperature() Pressure = sense.get_pressure() Humidity = sense.get_humidity() time_sense = time.strftime('%H:%M:%S') date_sense = time.strftime('%d/%m/%Y') data = { "MAC": MacAddress, "Date": date_sense, "Time": time_sense, "Temperature": Temperature, "Humidity": Humidity, "Pressure": Pressure } db.child("/Environment").push(data) if print_results == True: print("Time: {0}\tMacAddress: {1}".format( time_sense, MacAddress)) print( "\tTemperature: {0}C\tPressure: {1}Mb\tHumidity: {2}%\n\n". format(Temperature, Pressure, Humidity)) except Exception as e: raise sleep(interval)
def InsertKeyWordToDB(fromSubDir,toSubDir): db = DB() parser = Parser() for index in range(fromSubDir,toSubDir): for root,dirs,files in os.walk('test/keyword/'+str(index)+"/"): #each subdir: 1000record start = time.time() for afile in files: if afile == '.DS_Store': continue words = afile.split('_') aExpert = Expert(words[0].strip(),words[1].strip(),words[2].replace(".html","").strip()) aExpert.setKeyword(parser.parseKeyword(root,afile)) aExpert.ChangeKeywordsToString() #print aExpert.keywordsList if not db.isExpertExist(aExpert): db.insertExpert(aExpert) end = time.time() db.conn.commit() print ("KeywordSubDir %d is Done!"%index), print time.strftime('%m-%d %H:%M:%S',time.localtime(time.time())),"total:",end-start f = open("KeywordsToDB.log","a") f.write(time.strftime('%m-%d %H:%M:%S',time.localtime(time.time()))+" keywordSubDir"+str(index)+" is Done! "+"total"+str(end-start) ) f.close() db.close()
def InsertPaperToDB(fromSubDir,toSubDir): db = DB() parser = Parser() for index in range(fromSubDir,toSubDir): for root,dirs,files in os.walk('test/paper/'+str(index)+"/"): n = 1000*index start = time.time() for afile in files: if afile == '.DS_Store': continue words = afile.split('_') papers = (parser.parsePaper(root,afile)) for eachPapaer in papers: if not db.isPaperExist(eachPapaer): db.insertPaper(eachPapaer) print "n:",n, print "Expert_ID %s is done"%words[0] n = n + 1 db.conn.commit() end = time.time() print ("PaperSubDir %d is Done!"%index), print time.strftime('%m-%d %H:%M:%S',time.localtime(time.time())),"time:",end-start, f = open("PaperToDB.log","a") f.write(time.strftime('%m-%d %H:%M:%S',time.localtime(time.time()))+" paperSubDir"+str(index)+" is Done! "+"total"+str(end-start) ) f.close() db.close()
def get_menu(): try: a = randint(1, 5) for m in range(a): d.swipe(500, 1000, 500, 300) time.sleep(1) takeout_name = d(resourceId="com.yiwosi.kbb:id/tVTitle")[a].get_text() logger.info('点击的外卖是{}'.format(takeout_name)) d(resourceId="com.yiwosi.kbb:id/tVTitle")[a].click() takeout_get_menu_time = time.time() while not d(resourceId="com.yiwosi.kbb:id/tv_price").exists: h_appear_time = time.time() h_cost_time = h_appear_time - takeout_get_menu_time if h_cost_time > 15: logger.warning('等待店铺商品超15s,返回上个页面重新操作') d.app_stop(app_name) takeout_get_menu_time = time.time() break logger.info('外卖店铺商品详情页耗时{}'.format(h_cost_time)) e = EexeclData(file=target_file, sheet_name='详情页') e.write_cell(i + 1, 1, i) e.write_cell(i + 1, 2, h_cost_time) now_time = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) e.write_cell(i + 1, 3, now_time) logger.info('外卖店铺商品详情页表格数据更新成功') except BaseException as e: logger.error('外卖店铺商品详情页出错{}'.format(e)) send_msg(takeout_webhook, '外卖店铺商品详情页出错') now_time = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) d.screenshot(t_screenshot_path + '{}.jpg'.format(now_time)) get_adb_all_process(now_time) time.sleep(1) d.app_stop(app_name)
def get_takeout_list(): """ 获取外卖首页列表数据 """ try: takeout_click_time = time.time() while not d(resourceId="com.yiwosi.kbb:id/tVTitle").exists: h_appear_time = time.time() h_cost_time = h_appear_time - takeout_click_time if h_cost_time > 15: logger.warning('等待外卖列表超10s,返回上个页面重新操作') d.app_stop(app_name) takeout_click_time = time.time() break logger.info('外卖列表页耗时{}'.format(h_cost_time)) e = EexeclData(file=target_file, sheet_name='列表页') e.write_cell(i + 1, 1, i) e.write_cell(i + 1, 2, h_cost_time) now_time = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) e.write_cell(i + 1, 3, now_time) logger.info('外卖列表页表格数据更新成功') except BaseException as e: logger.error('外卖列表页出错{}'.format(e)) send_msg(takeout_webhook, '外卖列表页出错') now_time = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) d.screenshot(t_screenshot_path + '{}.jpg'.format(now_time)) get_adb_all_process(now_time) time.sleep(1) d.app_stop(app_name)
def friendtime(dt,format='%Y-%m-%d %H:%M'): '''时间友好显示化''' t = time.localtime(time.time()) today = time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00', t),'%Y-%m-%d %H:%M:%S')) yestoday = today - 3600*24 if dt > today: return u'今天' + time.strftime('%H:%M',time.localtime(dt)) if dt > yestoday and dt < today: return u'昨天' + time.strftime('%H:%M',time.localtime(dt)) return time.strftime(format,time.localtime(dt))
def procdt(self,args=None): view=self.view edit=self.edit dicdt={'dt':'TM_TH_DTTM','date':'TM_TH_DATE','time':'TM_TH_TIME'} ctime=time.localtime(time.time()) dicvl={'dt':time.strftime('%Y/%m/%d %H:%M:%S',ctime),'date':time.strftime('%Y/%m/%d',ctime),'time':time.strftime('%H/%M/%S',ctime)} if not args==None: mcdt='#'+dicdt[args] reg_bb=view.find(mcdt,0) view.replace(edit, reg_bb, dicvl[args])
def Page(self): plugin_path = '/usr/lib/enigma2/python/RTiTeam/TimeSet' print plugin_path before = 'Before: Local=' + strftime('%H:%M', localtime()) + ', UTC=' + strftime('%H:%M', gmtime()) cmd = str(plugin_path + '/ntpdate -t 20 0.debian.pool.ntp.org') res = popen(cmd).read() if res == '': cmd = 'ls -l %s%s' % (plugin_path, '/ntpdate') res = popen(cmd).read() if res[3] != 'x': cmd = 'chmod 755 %s%s' % (plugin_path, '/ntpdate') res = popen(cmd).read() self.session.open(MessageBox, _('ntpdate problem: attributes for ntpdate have not been correct! Fixed now! Try again!\n%s' % res), MessageBox.TYPE_INFO) else: self.session.open(MessageBox, _('ntpdate problem: Internet connection ok? Time server ok?'), MessageBox.TYPE_INFO) else: z1 = mktime(datetime.utcnow().timetuple()) config.plugins.TimeSet.NDate = ConfigDateTime(default = z1, formatstring = _('%d.%B %Y'), increment = 86400) config.plugins.TimeSet.UTCTim = ConfigClock(default = z1) self.list1 = [] self.list1.append(getConfigListEntry(_('UTC Time'), config.plugins.TimeSet.UTCTim)) self.list1.append(getConfigListEntry(_('Date'), config.plugins.TimeSet.NDate)) self['config'].setList(self.list1) self.selectionChanged() saat = str(config.plugins.TimeSet.UTCTim.value[0]) if len(saat) < 2: saat = '0' + saat minuti = str(config.plugins.TimeSet.UTCTim.value[1]) if len(minuti) < 2: minuti = '0' + minuti sekunde = strftime('%S', localtime()) pp = config.plugins.TimeSet.NDate.value import time TimeString = time.strftime('%Y%m%d', time.gmtime(pp)) + saat + minuti + sekunde RTCString = time.strftime('%Y.%m.%d', time.gmtime(pp)) + '-' + saat + ':' + minuti + ':' + sekunde TimeZoneS = config.timezone.val.value ipos1 = TimeZoneS.find('(GMT') ipos2 = TimeZoneS.find(')') tmp = TimeZoneS[ipos1 + 4:ipos2] if len(tmp) == 0: tmp = '+00' tzpredznak = tmp[:1] tzvalue = str(int(tmp[1:3])) TimeString = TimeString + tzpredznak + tzvalue import os cmd = 'echo "' + str(TimeString) + '" > /proc/settime' os.system(cmd) cmd = 'date -u -s "' + str(RTCString) + '"' os.system(cmd) self.session.openWithCallback(self.callback, MessageBox, _('RTC Update done! \n\nGUI Clock Update done!\n\n' + before + '\n\nntpdate done! ' + res + '\nAfter: Local=' + strftime('%H:%M', localtime()) + ', UTC=' + strftime('%H:%M', gmtime())), type = 1, timeout = 15)
def add_menu(): try: time.sleep(1) if d(resourceId="com.yiwosi.kbb:id/car_badge").exists: # 情况购物车 d(resourceId="com.yiwosi.kbb:id/iv_shop_car").click() time.sleep(1) d(resourceId="com.yiwosi.kbb:id/tViewClear").click() time.sleep(1) d(text='清空').click() time.sleep(2) for m in range(4): d.swipe(500, 1500, 500, 300) time.sleep(1) # 点击加入购物车按钮 d(resourceId="com.yiwosi.kbb:id/addbutton")[m].click() time.sleep(1) if d(resourceId="com.yiwosi.kbb:id/tViewOK").exists: d(resourceId="com.yiwosi.kbb:id/tViewOK").click() time.sleep(1) m+=1 logger.info('购物车数据添加成功') time.sleep(1) # 点击去结算按钮 d(resourceId="com.yiwosi.kbb:id/car_limit").click() takeout_add_menu_time = time.time() while not d(resourceId="com.yiwosi.kbb:id/text_show_time").exists: # 判断送达时间是否存在 h_appear_time = time.time() h_cost_time = h_appear_time - takeout_add_menu_time if h_cost_time > 15: logger.warning('等待提交订单页面超15s,返回上个页面重新操作') takeout_add_menu_time = time.time() break logger.info('提交订单页面耗时{}'.format(h_cost_time)) e = EexeclData(file=target_file, sheet_name='提交订单页') e.write_cell(i + 1, 1, i) e.write_cell(i + 1, 2, h_cost_time) now_time = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) e.write_cell(i + 1, 3, now_time) logger.info('提交订单页面表格数据更新成功') time.sleep(1) except BaseException as e: logger.error('提交订单页面出错{}'.format(e)) send_msg(takeout_webhook, '提交订单页面出错') now_time = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) d.screenshot(t_screenshot_path + '{}.jpg'.format(now_time)) get_adb_all_process(now_time) time.sleep(1) d.app_stop(app_name)
def svcL2(punish, max_iter,multi_class, featuresList, labelList): from sklearn.svm import LinearSVC t0 = time() print ("-------------Begin SVC Train!------------") svc = LinearSVC(penalty = "l2", C=punish, max_iter = max_iter, multi_class = multi_class) #(penalty, loss='squared_hinge', dual=True, tol=0.0001, C=punish, multi_class='ovr' , #fit_intercept=True, intercept_scaling=1, class_weight=None, verbose=0, random_state=None, max_iter=5000) svc_model = svc.fit(featuresList, labelList) print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) tt = time() - t0 print ("SVC Classifier trained in {} seconds".format(round(tt,3))) return svc_model
def menu(): import time, getpass, platform, os, sys user = getpass.getuser() os = platform.system() procesador = platform.machine() fecha = time.strftime("%d/%m/%y") #dia = time.strftime("%a") hora = time.strftime("%H : %M : %S") print(""" PRIVIET, MY LITTLE SCRIPT **************************************************************** SI ESTAS USANDO ESTE SCRIPT DIVIERTETE!!! **************************************************************** """) print(""" ***************************************** *** **************************** *** *** 1) C *** *** 2) D *** *** 0)Salir *** *** *** *** **************************** *** *** *************** *** *** ************************* *** ***************************************** *** Usuario: """+ user + """ *** \n""" """ *** Fecha actual: """ + fecha + """ *** \n""" """ *** Hora actual: """ + hora + """ *** \n""" """ *** Sistema operativo: """ + os + """ ***\n""" """ *** Procesador: """ + procesador + """ ***\n ***************************************** """ """ """ """ """ ) opcion = input("#~ ") if opcion == '1': cifrar() elif opcion == '2': decifrar() elif opcion == '0': sys.exit(0)
def click_bookdate(start_date, end_date): """ int类型 预订日期函数,预订日期开始日期start_date,结束日期end_date """ try: d(resourceId="com.yiwosi.kbb:id/tv_total_day").click() time.sleep(1) d.swipe(500, 1600, 500, 500) time.sleep(1) # temp_date = datetime.datetime.now() # start_date = (temp_date + datetime.timedelta(days=+start_date)).strftime("%d") # if int(start_date)>27: # print(0) # start_date = '27' # if start_date.startswith('0'): # start_date = start_date.replace('0', '') # end_date = (temp_date + datetime.timedelta(days=+end_date)).strftime("%d") # if end_date.startswith('0'): # end_date = end_date.replace('0', '') d(text=start_date).click() time.sleep(1) d(text=end_date).click() time.sleep(1) logger.info('选择的预订起止日期:{}号-{}号'.format(start_date, end_date)) except BaseException as e: send_msg(hotel_webhook, '预订日期选择出错') logger.error('预订日期选择出错{}'.format(e)) now_time = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) d.screenshot(h_screenshot_path + '{}.jpg'.format(now_time)) get_adb_all_process(now_time) time.sleep(1) d.app_stop(app_name)
def event(self): # get counter time time = datetime.fromtimestamp(self.__counter) # format time string time = time.strftime(Timer.__TIME_PATTERN) # check timer return match(self.__pattern, time)
def user_portal(): user_group = {} if (current_user.status == 'matched'): all_groups = mongo.db.groups.find({}); all_groups = list(all_groups) for group in all_groups: if current_user.email in group['emails']: user_group["emails"] = group['emails'] user_group["restaurant"] = group['restaurant'] user_group["time"] = group["time"] time = datetime.utcfromtimestamp(user_group["time"]) user_group["time"] = time.strftime("%I:%M %p") print("The other user's emails are: ", user_group["emails"]) profiles = [] for email in user_group["emails"]: profiles.append(mongo.db.users.find_one({"email": email})) user_group["emails"] = profiles print(user_group) return render_template("user-portal.html", status=current_user.status, user=getUserDict(), user_group=user_group)
def get_file_by_date(*arg): """ 以文件的修改时间获取文件 :param arg: :return: """ for dir_path, dir_names, file_names in os.walk(arg[0]): for filename in file_names: # ================1.过滤文件,规则buckFileText,还有就是除去临时文件========== absolute_file_name = os.path.join(dir_path, filename) date = time.strftime( '%Y%m%d%H%M%S', time.localtime(os.path.getctime(absolute_file_name))) if arg[1] > date: # 进行时间的过滤 continue try: # 这里预防文件过大,排除一些文件 file_split = os.path.splitext(filename) # 分离文件名中的名称和后缀 if (file_split[1].lower() not in [ '.pdf', '.txt', '.doc', '.html', '.docx', '.ppt' ]) or ('~$' in file_split[1]): continue except Exception as e: print(e) # ================2.文件的名称的构造==================== absolute_file_name = os.path.join(dir_path, filename) will_copy_file = get_will_dest_name(arg[2], absolute_file_name) print(absolute_file_name) # ================3.文件的复制=========================== if not os.path.isfile(will_copy_file): GetFile.do_copy(old=absolute_file_name, new=will_copy_file)
def getFormattedDate(self, dt): """ returns a formatted date string @summary: returns either the formatted datestring defined by DATE_FORMAT_STRING or it defaults to '%Y-%m-%d %H:%M:%S'. @type dt: datetime @param dt: datetime object to format @rtype: string @return: formatted date string """ if DATE_FORMAT_STRING == '': return time.strftime('%Y-%m-%d %H:%M:%S', dt.timetuple()) else: return time.strftime(DATE_FORMAT_STRING, dt.timetuple())
def preferences(): if request.method == 'POST': now = datetime.utcnow() tempTimeString = now.strftime( "%d%m%Y") + " " + request.form['lunch-time'] tempTime = datetime.strptime(tempTimeString, "%d%m%Y %I:%M %p") timeDiff = (tempTime-datetime(1970, 1, 1)).total_seconds() mongo.db.being_matched.insert({'email': current_user.email, 'first_name': current_user.first_name, 'last_name': current_user.last_name, 'addr': current_user.addr, 'interest_prefs': current_user.interest_prefs, 'food_prefs': request.form.getlist('food'), 'time_pref': timeDiff, 'lat': current_user.lat, 'long': current_user.long}) mongo.db.users.update({'email': current_user.email}, { '$set': {'status': "being_matched"}}) value = form_groups( mongo.db.users, mongo.db.being_matched, mongo.db.groups) print(value) if(value): # Return to bryan's page return redirect(url_for('user_portal')) else: return redirect(url_for('matching', time_pref=round(timeDiff))) time = datetime.utcfromtimestamp(current_user.time_pref) time_string = time.strftime("%I:%M %p") time_string2 = "'" + time_string + "'" print("time_string", time_string) print("time_string2", time_string2) return render_template('preferences.html', preference_list=current_user.food_prefs, time_pref=time_string2, foods=getFoods())
def do_sync_adcs_sequence(self): ''' synchronize the ADCs ''' print("SYNCHRONIZING ADCS") self.sync_adcs_sequence_result["text"] = "SYNCHRONIZING ADCS - IN PROGRESS" self.update_idletasks() self.test_result = 0 now = time.strftime("%Y%m%dT%H%M%S", time.localtime(time.time())) start_time = time.time() resolved = self.runner(**self.params, datasubdir="sync_adcs", executable="femb_sync_adcs", test_start_time = self.now, outlabel = "{datasubdir}-{test_start_time}", chip_list = self.chiplist, argstr="{paramfile}", save_results = self.save_sync_results) #look to see if any chips failed the configuration and skip over them for the future tests for chip_name in self.chiplist: file_name = os.path.join(resolved['datadir'],chip_name[1],"sync_adcs","results.json") print("file_name for sync results check: {}".format(file_name)) if os.path.isfile(file_name): with open(file_name, 'r') as f: jsondata = json.load(f) self.params['config_list'] = jsondata['config_list']
def ind_horario(self, horario): import time # se consulta horario de dia actual dweek = time.strftime("%a", time.localtime()) dsem = dweek[0:2].capitalize() if dsem.find("Lu") != -1 or dsem.find("Mo") != -1: ind = horario.find("Mo") elif dsem.find("Ma") != -1 or dsem.find("Tu") != -1: ind = horario.find("Tu") elif dsem.find("Mi") != -1 or dsem.find("We") != -1: ind = horario.find("We") elif dsem.find("Ju") != -1 or dsem.find("Th") != -1: ind = horario.find("Th") elif dsem.find("Vi") != -1 or dsem.find("Fr") != -1: ind = horario.find("Fr") elif dsem.find("Sa") != -1 or dsem.find("Sa") != -1: ind = horario.find("Sa") elif dsem.find("Do") != -1 or dsem.find("Su") != -1: ind = horario.find("Su") else: ind = -1 return ind
def create_temporary_path(self): import time from sct_utils import slash_at_the_end path_tmp = slash_at_the_end("tmp." + time.strftime("%y%m%d%H%M%S"), 1) sct.run("mkdir " + path_tmp, self.verbose) return path_tmp
def parse_chejiahao_comments(more_url): html = parse_art(more_url) if html: tree = etree.HTML(html) title = tree.xpath('//div[@class="all_com_title"]/span/a/text()')[0] bbsname = None for index, each in enumerate(tree.xpath('//dl[@class="rev_dl"]//dt')): try: username = each.xpath('.//span[@class="rmembername-span"]/text()')[0] try: pushtime = each.xpath('./span[1]/text()[3]')[0].strip() except: pushtime = each.xpath('./span[1]/text()[2]')[0].strip() pushtime = parse_time(pushtime) if pushtime < START_TIME: break comtstr = tree.xpath('//dl[@class="rev_dl"]//dd[{}]/p/text()'.format(index+1))[0] item = {} item['title'] = title item['bbs_name'] = '汽车之家' item['sonbbs_name'] = bbsname item['username'] = username item['comment_detail'] = comtstr item['comment_url'] = more_url item['push_time'] = pushtime item['catch_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) item['car_type'] = None item['collection'] = "(汽车之家文章)自动驾驶" # 设置存入表名 item['usergender'] = None item['userlocation'] = None item['userage'] = None save_to_db(item) except Exception as e: print(e.__traceback__.tb_lineno,e)
def create_scan(tenable_client): import time timestr = time.strftime("%Y%m%d-%H%M%S") scan_name = u"scanjob_" + timestr scan = tenable_client().scan_helper.create( name=scan_name, text_targets='[input ip_address]', template='basic') return scan
def dayActivity_RepoFormat(ansSit, ansStand): #"%Y-%m-%d %H:%M:%S" return { "stand_cum_time": int(ansStand), "sit_cum_time": int(ansSit), "record_time": time.strftime("%Y-%m-%d") }
def messbox(): global msgbox if msgbox == 1: pop = Toplevel(root) pop.title("ALERT!") pop.geometry("300x100") # wxh pop.maxsize(300, 100) global pop_label label_1 = Label(pop, text="Suspicious Activity Detected!", fg='red', font=("helvetica", 12)) label_1.pack(pady=5) f1 = Frame(pop) f1.pack(pady=10) time_text = Label(f1, text='Time:', font=("helvetica", 11)) time_text.grid(row=2, column=1) pop_label = Label(f1, text="", font=("helvetica", 10)) pop_label.grid(row=2, column=2) t = time.localtime() current_time = time.strftime("%H:%M:%S", t) pop_label.config(text=current_time) msgbox = 0
def wrapper(*args, **kargs): t1 = time.time() res = func(*args, **kargs) tel = time.time()-t1 timeformated = time.strftime( "%H:%M:%S",time.gmtime(tel)) print '-'*5 + '%s took %0.3f ms' % (func.func_name + str(kargs) + str(args), (tel)*1000.0) + '|' + timeformated + '|'+ '-'*10 return res
def logRunningTime(self): startTime = time.strftime("%a, %d %b %Y %H:%M:%S -0007", self.startTime) currTime = time.gmtime() totalJobs = self.mgr.getJobCount() self.logprint('Spice Server running since ' + startTime + ". Total Jobs:%d" % totalJobs)
def to_sql(self): event_attr = [ "event_id", "plugin_id", "plugin_sid", "protocol", "src_ip", "src_port", "dst_ip", "dst_port", "date", "log", "binary_data" ] self.event['event_id'] = Event.__get_uuid() self.event['date'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) query = 'INSERT INTO event (' for attr in event_attr: query += '%s,' % attr query = query.rstrip(',') query += ') VALUES (' for attr in event_attr: value = '' if self.event[attr] is not None: if attr == "log": value = b64encode(self.event[attr]) else: value = self.event[attr] print self.event[attr] else: value = "" query += "'%s'," % value query = query.rstrip(',') query += ');' #debug(query) return query
def print_exception_message(self, message_orientation="horizontal"): """ print full exception message :param message_orientation: horizontal or vertical :return None """ try: exc_type, exc_value, exc_tb = sys.exc_info() file_name, line_number, procedure_name, line_code = traceback.extract_tb( exc_tb)[-1] time_stamp = " [Time Stamp]: " + str( time.strftime(" %Y-%m-%d %I:%M:%S %p")) file_name = " [File Name]: " + str(file_name) procedure_name = " [Procedure Name]: " + str(procedure_name) error_message = " [Error Message]: " + str(exc_value) error_type = " [Error Type]: " + str(exc_type) line_number = " [Line Number]: " + str(line_number) line_code = " [Line Code]: " + str(line_code) if (message_orientation == config.HORIZONTAL): print("An error occurred:{};{};{};{};{};{}; {}".format( time_stamp, file_name, procedure_name, error_message, error_type, line_number, line_code)) elif (message_orientation == config.VERTICAL): print("An error occurred:\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format( time_stamp, file_name, procedure_name, error_message, error_type, line_number, line_code)) else: pass except: exception_message = sys.exc_info()[0] print("An error occurred. {}".format(exception_message))
def output_latex_code(self, result): import time evaluate_index = list(result.keys()) values = list(result.values()) print(evaluate_index) print(values) index = [] tmp_values = [] c_control = [] for i in range(len(evaluate_index)): index += ' & ' index += evaluate_index[i] tmp_values += ' & $' tmp_values += str(values[i]) tmp_values += '$' c_control += 'c' index = ''.join(index) tmp_values = ''.join(tmp_values) c_control = ''.join(c_control) text = '\\begin{tabular}{l|' + c_control + '}\n\t\hline\n\tEvaluation metrics' + index + ' \\\\\n\t\hline\n\t\hline\n\t' + self.config[ 'model'] + tmp_values + ' \\\\\n\t\hline\n\end{tabular}' save_path = self.config['model'] + '_' + time.strftime( "%Y-%m-%d", time.localtime()) + '_latex_code.tex' file_handle = open(save_path, mode='w') file_handle.write(text)
def listener(q): '''listens for messages on the q, writes to file. ''' #sys.stdout.write('Starting listener\n') f = open( os.path.join(options.outdir, "TelomereCounts_" + time.strftime("%d_%m_%Y") + ".txt"), 'wb') f.write('\t'.join( ["#Sample", "TotalReads", "TelomericReads", "NormalisedFraction"]) + '\n') f.flush() while 1: m = q.get() #print(m) if m == 'kill': if not q.empty(): # received kill signal without finishing all the processes sys.stdout.write('ERROR\n') break # received kill signal, finished all the processes, done sys.stdout.write('DONE\n') break f.write('\t'.join(m) + '\n') f.flush() f.close()
def parse_time(pushtime): if re.search(r"天前", pushtime): num = int(re.search(r"\d+", pushtime).group()) sec = num*86400 pushtime = time.strftime("%Y-%m-%d", time.localtime(time.time() - sec)) if re.search('小时前', pushtime): NUM = int(re.search('\d+', pushtime).group()) sec = NUM * 60 * 60 today = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - sec)) pushtime = today if re.search('分钟前', pushtime): NUM = int(re.search('\d+', pushtime).group()) sec = NUM * 60 today = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - sec)) pushtime = today return pushtime
def upload_s3(dirpath: str) -> None: import boto3, time real_filepath = '' compressed_filepath = compress_backup(dirpath) if c.S3_GPG_ENCRYPT and not c.NOGPG: real_filepath = gpg_encrypt_file(compressed_filepath) real_filepath = compressed_filepath if not real_filepath else real_filepath datepart = time.strftime("%Y%m%d%H%M%S") remote_filename = os.path.split(real_filepath)[1] + '.' + datepart with open(real_filepath, 'rb') as data: message('Uploading file to Amazon S3') if not c.DRY_RUN: s3 = boto3.client('s3', aws_access_key_id=c.S3_ACCESS_KEY, aws_secret_access_key=c.S3_SECRET_KEY) s3.upload_fileobj(data, c.S3_BUCKET, remote_filename) if not c.DRY_RUN: if c.S3_GPG_ENCRYPT: # Remove the local encrupted file os.unlink(real_filepath) os.unlink(compressed_filepath) message('File uploaded to S3 bucket "{}" as key "{}"'.format( c.S3_BUCKET, remote_filename))
def parse_news_comments(url): html = parse_art(url) if html: tree = etree.HTML(html) title = tree.xpath('//h1/a[1]/text()')[0] bbsname = None for index, each in enumerate(tree.xpath('//dl[@id="reply-list"]//dt')): try: username = each.xpath('./span[1]/a[1]/text()')[0] pushtime = each.xpath('./span[2]/text()[1]')[0].replace("[", '') pushtime = parse_time(pushtime) if pushtime < START_TIME: break comtstr = tree.xpath('//dl[@id="reply-list"]//dd[{}]/@datacontent'.format(index+1))[0] item = {} item['title'] = title item['bbs_name'] = '汽车之家' item['sonbbs_name'] = bbsname item['username'] = username item['comment_detail'] = comtstr item['comment_url'] = url item['push_time'] = pushtime item['catch_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) item['car_type'] = None item['collection'] = "(汽车之家文章)自动驾驶" # 设置存入表名 item['usergender'] = None item['userlocation'] = None item['userage'] = None save_to_db(item) except Exception as e: print(e.__traceback__.tb_lineno,e)
def get_gld_info(self, name): temp_type = request.env['syt.oa.gld'].sudo().search([('name', '=', name.lstrip())]) copy_users = request.env['syt.oa.gld'].sudo().search([ ('copy_users.user_id', '=', request.session['uid']) ]) temp_type_list = [] if temp_type: for value in temp_type: temp_item = {} temp_item['name'] = value.name # 单号 temp_item['company_name'] = value.company_id.name # 公司 temp_item['dept'] = value.dept # 部门 temp_item['id'] = value.create_uid.id # 创建员工ID temp_item['user_name'] = value.create_uid.name # 创建员工姓名 timeArray = time.strptime(str(value.create_date), "%Y-%m-%d %H:%M:%S") timeStamp = int(time.mktime(timeArray)) create_time = timeStamp + 8 * 60 * 60 # 加8个小时 timeArray = time.localtime(create_time) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) temp_item['write_date'] = otherStyleTime # 创建更新时间 temp_item['state'] = value.state # 状态 temp_item['subject'] = value.subject # 标题 temp_item['content'] = value.content # 正文 if copy_users: temp_item['copy_users'] = 'yes' # 区别 判断是抄送人还是审批人 else: temp_item['copy_users'] = 'no' # 区别 判断是抄送人还是审批人 temp_type_list.append(temp_item) return JSONEncoder().encode(temp_type_list)
def get_sns(self, gld_name): temp_list = [] gld = request.env['syt.oa.gld'].sudo().search([('name', '=', gld_name) ]) message = request.env['mail.message'].sudo().search([ ('res_id', '=', gld.id), ('model', '=', 'syt.oa.gld') ]) if message: for value in message: temp_item = {} employee = request.env['hr.employee'].sudo().search([ ('user_id', '=', int(value.create_uid)) ]) # temp_item['operator'] = employee.name # 操作人 temp_item['id'] = employee.id # 员工id temp_item['name'] = employee.name # 操作人 temp_item['email'] = employee.work_email # 员工邮箱 temp_item['body'] = str(value.body).replace("<p>", "").replace( "</p>", "") # 内容 timeArray = time.strptime(str(value.create_date), "%Y-%m-%d %H:%M:%S") timeStamp = int(time.mktime(timeArray)) create_time = timeStamp + 8 * 60 * 60 # 加8个小时 timeArray = time.localtime(create_time) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) temp_item['time'] = otherStyleTime # 更新时间 temp_list.append(temp_item) return JSONEncoder().encode(temp_list)
def selectionChanged(self): self['introduction'].setText(_('Your time = UTC Time + Your Time Zone')) self['vreme'].setText(_('*Current Your Time: ' + str(datetime.now().strftime('%H:%M:%S')))) saat = str(config.plugins.TimeSet.UTCTim.value[0]) if len(saat) < 2: saat = '0' + saat minuti = str(config.plugins.TimeSet.UTCTim.value[1]) if len(minuti) < 2: minuti = '0' + minuti sekunde = strftime('%S', localtime()) pp = config.plugins.TimeSet.NDate.value import time TimeString = time.strftime('%Y%m%d', time.gmtime(pp)) + saat + minuti + sekunde TimeZoneS = config.timezone.val.value ipos1 = TimeZoneS.find('(GMT') ipos2 = TimeZoneS.find(')') tmp = TimeZoneS[ipos1 + 4:ipos2] if len(tmp) == 0: tmp = '+00' tzpredznak = tmp[:1] tzvalue = str(int(tmp[1:3])) TimeString = TimeString + tzpredznak + tzvalue self['timez'].setText(_('Time Zone : ' + str(TimeZoneS))) self['poraka'].setText(_('TimeString : ' + str(TimeString))) novovreme = str(int(saat) + int(tzpredznak + tzvalue)) if len(novovreme) < 2: novovreme = '0' + novovreme novovreme = novovreme + ':' + minuti self['vreme'].setText(_('Your Time (After Setting): ' + str(novovreme)))
def train(solver_proto_path, snapshot_solver_path=None, init_weights=None, GPU_ID=0): """ Train the defined net. While we did not use this function for our final net, we used the caffe executable for multi-gpu use, this was used for prototyping """ import time t0 = time.time() caffe.set_mode_gpu() caffe.set_device(GPU_ID) solver = caffe.get_solver(solver_proto_path) if snapshot_solver_path is not None: solver.solve(snapshot_solver_path) # train from previous solverstate else: if init_weights is not None: solver.net.copy_from( init_weights ) # for copying weights from a model without solverstate solver.solve() # train form scratch t1 = time.time() print 'Total training time: ', t1 - t0, ' sec' model_dir = "calc_" + time.strftime("%d-%m-%Y_%I%M%S") moveModel(model_dir=model_dir) # move all the model files to a directory print "Moved model to model/" + model_dir
def backup_db(self): '''Backup/archive esget.db''' arcname = os.path.join(self.dbarchivedir, os.path.split(self.dbname)[1] + "."+time.strftime("%Y-%m-%d_%H-%M")) shutil.copy(self.dbname, arcname) self._log.info("Archived {0}".format(self.dbname)) return()
def run(self): t0 = (2013, 3, 26, 23, 0, 0, 0, 1, -1) t0 = calendar.timegm(t0) t1 = time.time() announcement_frequency = 60*60 if t1 - self.last_run < announcement_frequency: return print 't1 - self.last_run:',t1 - self.last_run print 'self.last_run:',self.last_run self.last_run = int(t1- (int(t1) % announcement_frequency)) t = int(t1 - t0) days = t // (3600 * 24) #move it back one day days -= 1 date = time.gmtime(t0 + (days * (3600 * 24))) next_date = time.gmtime(t0 + ((days+1) * (3600 * 24))) response = 'NOTICE: Sefira for \x031,9YESTERDAY\x03, {date}: *{count}* Days of the omer.' \ + ' You can count until sunset on {next_date}.' \ + ' WARNING: THIS IS ALPHA, DOUBLE CHECK THIS YOURSELF (http://goo.gl/hzY2v)' response = response.format(date=time.strftime("%a NIGHT, %d %b %I:%M %p",date), next_date=time.strftime("%a",next_date), count=(days+1)) for bot in self.bot_factory.bots: bot.msg(bot.factory.channel, response)
def runTest(self): driver = self.getDriver() param = self.param tool = utils driver.refresh() # 左上方公共节点 driver.find_element_by_class_name('lebra-navbar-left-icon').click() sleep(3) # 进入财务管理 driver.find_element_by_xpath('//*[text()="财务管理"]').click() sleep(3) # 进入一级节点 menu2 = driver.find_element_by_css_selector('span[title="总账"]') actions = ActionChains(driver) actions.move_to_element(menu2) actions.click(menu2) actions.perform() sleep(3) # 进入二级节点 menu3 = driver.find_element_by_css_selector( 'li[class="bottomBar"][title="辅助余额表"]') actions.move_to_element(menu3) actions.click(menu3) actions.perform() sleep(6) titleName = driver.find_element_by_css_selector( '#home_header > div > div.tab--38iB- > ul > li > p').get_attribute( 'title') assert u"辅助余额表" in titleName, u"页面源码中不存在该关键字!" sleep(5) iframe = driver.find_element_by_id('help-balance') driver.switch_to.frame(iframe) # 查询 driver.find_element_by_xpath( '//label[text()="账簿"]/..//span[@class="ant-select-arrow"]/i' ).click() driver.find_element_by_xpath('//li[text()="yontest云创股份"]').click() nowtime = time.strftime('%Y-%m', time.localtime(time.time())) driver.find_element_by_xpath( '//span[text()="至"]/../div[2]//span[@class="ant-select-arrow"]' ).click() driver.find_element_by_xpath( '//li[text()="{}"]'.format(nowtime)).click() driver.find_element_by_xpath( '//span[text()="至"]/../div[3]//span[@class="ant-select-arrow"]' ).click() driver.find_element_by_xpath( '//div[6]//li[text()="{}"]'.format(nowtime)).click() search_button = driver.find_element_by_xpath('//*[text()="查 询"]') driver.execute_script("arguments[0].click();", search_button) driver.switch_to.default_content() driver.find_element_by_class_name('u-button').click() sleep(3) driver.find_element_by_class_name('u-dropdown-menu-item').click() sleep(3)
def hoy_mun(cod,name): import datetime import time import json #Conexion BBDD conexion = conexion_bbdd() db = conexion.othesoluciones1 #Redireccion en la paginacion de la pagina de reportes if (cod=='reporte'): return reporte(name) #Busqueda de datos en coleccion: prediccionesAEMET collection1 = db.prediccionesAEMET print elimina_tildes(name.decode('utf-8')) name2 = elimina_tildes(name.decode('utf-8')) print name2 print cod cursorHoyM1 = collection1.find_one({"Municipio": name2}) print time.strftime("%Y-%m-%d") busquedaAEMET = cursorHoyM1[time.strftime("%Y-%m-%d")] #Carga de imagenes del municipio collection2 = db.imagenes cursorHoyM2 = collection2.find_one({'municipio':name2}) print cursorHoyM2['filename_img_municipio'] print cursorHoyM2['filename_img_municipio_cam'] f1 = gridfs.GridFS(db,"images").get_version(cursorHoyM2['filename_img_municipio']) plot_url_img = base64.b64encode(f1.read()) f2 = gridfs.GridFS(db,"images").get_version(cursorHoyM2['filename_img_municipio_cam']) plot_url_img_cam = base64.b64encode(f2.read()) #Busqueda de datos en coleccion:calidad_aire_por_municipio collection3= db.calidad_aire_por_municipio cursor3 = collection3.find_one({'Municipio':name2}) #Carga de las noticias del dia noticias_del_dia=cargaNoticias() #Conexion BBDD conexion.close() return template("views/p_hoy_mun.tpl",name=name, busquedaAEMET=busquedaAEMET,plot_url_img=plot_url_img, plot_url_img_cam=plot_url_img_cam, noticias_del_dia=noticias_del_dia, cursor3=cursor3)
def getTimeOClockOfToday(year, month, day): import time t = time.localtime(time.time()) time1 = time.mktime( time.strptime(time.strftime('%Y-%m-%d 00:00:00', t), '%Y-%m-%d %H:%M:%S')) return int(time1)
def getHostStatusSummary(session_id, host_name): """Returns an overall status for the host""" status = {} try: hoststatus = getHostStatus(host_name) except: status = {"status":STATUS_UNKNOWN,"status_text":"UNKNOWN", \ "status_hint":"No status information available"} return status status["infoUpdatedAt"] = time.strftime("%d/%m/%Y %H:%M:%S", \ time.localtime(hoststatus.infoUpdatedAt)) status["lastCheckedAt"] = time.strftime("%d/%m/%Y %H:%M:%S", \ time.localtime(hoststatus.lastCheckedAt)) status["status"] = STATUS_OK status["status_text"] = "UP" status["status_hint"] = "Last checked at %s" % status["lastCheckedAt"] if not hoststatus.reachable: status["status"] = STATUS_CRITICAL status["status_text"] = "Down" status["status_hint"] = "Not seen since %s" % status["infoUpdatedAt"] return status if hoststatus.operatingRevisionStatus != STATUS_OK: status["status"] = hoststatus.operatingRevisionStatus status["status_text"] = hoststatus.operatingRevisionText status["statux_hint"] = hoststatus.operatingRevisionHint return status cstatus = getCfengineHostStatus(session_id, hoststatus.host._properties) if cstatus["ssh_key_status"] != STATUS_OK: status["status"] = cstatus["ssh_key_status"] status["status_text"] = "SSH Key Error" status["status_hint"] = cstatus["ssh_key_text"] return status if cstatus["cfengine_key_status"] != STATUS_OK: status["status"] = cstatus["cfengine_key_status"] status["status_text"] = "CFengine Key Error" status["status_hint"] = cstatus["cfengine_key_text"] return status return status
def d_print(*args): import time if MDEBUG: if MDEBUG_TIMESTAMP: s = '%s - ' % time.strftime('%H:%M:%S',time.localtime()) else: s = '' for arg in args: s += str(arg) print s
def insertExpert(self,expert): sql = "insert into GeniusExpert(Expert_ID,Expert_name,Expert_keywords) values('%s','%s','%s')" %(expert.expertID,expert.name,str(expert.keywordsList)) try: #print sql self.cursor.execute(sql) except Exception, e: f = open("ExpertError.log","a") f.write(str(e)+"\n") f.write(sql+"\n") f.write(time.strftime('%m-%d %H:%M:%S',time.localtime(time.time()))) f.close()
def insertPaper(self,paper): sql = "insert into Paper(Expert_ID,Paper_ID,Paper_Title,Paper_Authorslist,Paper_Url,Paper_Origin,Paper_Pubtime,Paper_Database,Paper_Citation) values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" %(paper.expertID,paper.paperID,paper.title,paper.authorsList,paper.url,paper.origin,paper.pubtime,paper.database,paper.citation) try: #print sql self.cursor.execute(sql) except Exception, e: f = open("PaperError.log","a") f.write(str(e)+"\n") f.write(sql+"\n") f.write(time.strftime('%m-%d %H:%M:%S',time.localtime(time.time()))) f.close()
def procautoflush(self): view=self.view edit=self.edit curtime=time.strftime('%Y/%m/%d %H:%M:%S',time.localtime(time.time())) sel=view.sel()[0] reg=r"^>{3}[^>][\r\n\S\s]*?[^<]<{3}\d{4}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2}" reg_bb=view.find(reg,0) while not reg_bb.empty(): if reg_bb.begin()<sel.begin() and reg_bb.end()>sel.end(): treg=sublime.Region(reg_bb.end()-19,reg_bb.end()) view.replace(edit,treg,curtime) reg_bb=view.find(reg,reg_bb.end())
def setup_debug_folder(self): """ Sets up the folder for the step by step files for this algorithm The folder's absolute path can be found in the self.debug_folder property :return: None """ if self.produce_output: import time from sct_utils import slash_at_the_end folder = slash_at_the_end('scad_output_'+time.strftime('%y%m%d%H%M%S'), 1) sct.run('mkdir '+folder, self.verbose) self.debug_folder = os.path.abspath(folder) conv.convert(str(self.input_image.absolutepath), str(self.debug_folder)+'/raw.nii.gz')
def produce_output_files(self): """ Method used to output all debug files at the same time. To be used after the algorithm is executed :return: """ import time from sct_utils import slash_at_the_end path_tmp = slash_at_the_end("scad_output_" + time.strftime("%y%m%d%H%M%S"), 1) sct.run("mkdir " + path_tmp, self.verbose) # getting input image header img = self.input_image.copy() # saving body symmetry img.data = self.raw_symmetry img.change_orientation(self.raw_orientation) img.file_name += "body_symmetry" img.save() # saving minimum paths img.data = self.minimum_path_data img.change_orientation(self.raw_orientation) img.file_name = "min_path" img.save() img.data = self.J1_min_path img.change_orientation(self.raw_orientation) img.file_name = "J1_min_path" img.save() img.data = self.J2_min_path img.change_orientation(self.raw_orientation) img.file_name = "J2_min_path" img.save() # saving minimum path powered img.data = self.minimum_path_powered img.change_orientation(self.raw_orientation) img.file_name = "min_path_powered_" + str(self.minimum_path_exponent) img.save() # saving smoothed min path img = self.smoothed_min_path.copy() img.change_orientation(self.raw_orientation) img.file_name = "min_path_power_" + str(self.minimum_path_exponent) + "_smoothed" img.save() # save symmetry_weighted_minimal_path img.data = self.spine_detect_data img.change_orientation(self.raw_orientation) img.file_name = "symmetry_weighted_minimal_path" img.save()
def uploadwrite(state, sonars, theta, temp, ldr): fin = open('C:\Users\HanWei\Dropbox\SUTDNotes\SUTDTerm3\\2D\DW2DShenanigans.txt', 'a') now = time.strftime('%H:%M:%S') + '|' + time.strftime('%d/%m/%Y') othernow = time.strftime('<%H:%M:%S>') + '||' + time.strftime('<%d/%m/%Y>' + '||') if state[3][0] == 'A': fin.write(othernow + 'Expose Plates at A\n') firebase.put('/stationA/', 'ldr', ldr) firebase.put('/stationA/', 'temp', temp) firebase.put('/stationA/', 'time', now) elif state[3][0] == 'B': fin.write(othernow + 'Expose Plates at B\n') firebase.put('/stationB/', 'ldr', ldr) firebase.put('/stationB/', 'temp', temp) firebase.put('/stationB/', 'time', now) elif state[3][0] == 'C': fin.write(othernow + 'Expose Plates at C\n') firebase.put('/stationC/', 'ldr', ldr) firebase.put('/stationC/', 'temp', temp) firebase.put('/stationC/', 'time', now) elif state[3][0] == 'D': fin.write(othernow + 'Expose Plates at D\n') firebase.put('/stationD/', 'ldr', ldr) firebase.put('/stationD/', 'temp', temp) firebase.put('/stationD/', 'time', now) elif state[3][0] == 'X': if len(state[3][0]) == 1: fin.write(othernow + 'Finished, and arrived at X\n') elif len(state[3][0]) != 1: fin.write(othernow + 'Collect Plates at X\n') firebase.put('/station/', 'ldr', ldr) firebase.put('/stationA/', 'temp', temp) firebase.put('/stationA/', 'time', now) else: print 'Not a station' global checked checked = True fin.close() return state, io.Action(fvel=0, rvel=0)
def loop_inter (): kill_all_trexes() cnt=0; while True: print (time.strftime("%H:%M:%S")), print "Iter",cnt ret=run_one_iter () if ret==1: break; cnt=cnt+1; if is_any_core (): print "stop due to core file" break;
def formattime(dt,format='%Y-%m-%d %H:%M'): mins = int(time.time())-dt if mins < 60: return u'%s 秒前' % mins elif mins < 3600: return u'%s 分钟前' % (mins / 60) elif mins < 24*3600: return u'%s 小时前' % (mins/3600) elif mins < 3*24*3600: return u'%s 天前' % (mins/(3600*24)) _time = time.localtime(dt) _now = time.localtime(time.time()) if _time.tm_year == _now.tm_year: format='%m-%d %H:%M' return time.strftime(format,time.localtime(dt))
def update(self, *args): time_hour = time.strftime("%I") #time_hour if time_hour[0] == "0": #one digit format time_hour = " "+time_hour[1] time_minute = time.strftime("%M") #time_minute time_now = time_hour+":"+time_minute #create sting format (hour:minute) if clock == 1: self.font_size = 60 self.pos = (0,190) self.text = time_now if clock == 0: self.font_size = 60 self.pos = (0,190) self.text = " " if clock == 2: self.font_size = 140 self.text = time_now self.pos = (-200,150)
def individuals_observer(population, num_generations, num_evaluations, args): try: individuals_file = args['individuals_file'] except KeyError: individuals_file = open('inspyred-individuals-file-{0}.csv'.format(time.strftime('%m%d%Y-%H%M%S')), 'w') if num_generations == 0: individuals_file.write('{0},{1},{2},{3}\n'.format('generation', 'id', 'fitness', 'candidate')) population = sorted(enumerate(population), key=lambda x: x[1].fitness) for id, p in population: individuals_file.write('{0},{1},{2},{3}\n'.format(num_generations, id, p.fitness, str(p.candidate).replace(',', '').replace('[', '').replace(']', ''))) individuals_file.flush()
def buildSessionID(ifname): """Returns a new Acct-Session-Id for the specified interface The session ID consists of the last 8 characters of the interface MAC address followed by '-' followed by the time in the format YYMMDDHHMMSS """ global _accountingInfo # Build the macstr macstr = _accountingInfo[ifname]["called"].replace("-", "")[-8:] # Build the time str timestr = time.strftime("%y%m%d%H%M%S") # Combine and return return "%s-%s" % (macstr, timestr)
def _gen_headers(self, code): """ Generates HTTP response Headers. Ommits the first line! """ # determine response code h = '' # if (code == 200): h = 'HTTP/1.1 200 OK\n' # elif(code == 404): # h = 'HTTP/1.1 404 Not Found\n' # write further headers current_date = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) h += 'Date: ' + current_date +'\n' h += 'Server: Roku UPnP/1.0 MiniUPnPd/1.4\n' h += 'Connection: close\n\n' # signal that the conection wil be closed after complting the request return h
def currentThreadResults(self): if self.outfile != " ": appendLineToFile('[+]'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),self.outfile) for connection in self.connections: connection.join() if connection.status == 1: print "[#] TargetIp: %s " % connection.targetIp print "[#] Username: %s " % connection.userName print "[#] Password: %s " % connection.passWord if self.outfile != " ": appendLineToFile("ip: %s username: %s password: %s " % (connection.targetIp,connection.userName,connection.passWord), self.outfile) appendLineToFile(" ",self.outfile) if self.singleMode: self.completed() else: pass self.clearOldThreads()