def on_message(self, message): func.log("New request: %s" % str(message)) data = json.loads(message) if "file" in data: for conf in self.configuration: if conf["file"] == data["file"]: self.parser = filetail.FileTail(conf["file"]) linenum = 0 if "len" not in data else int(data["len"]) self.startTailing(linenum) return None
def check_voltage(): voltage = '' try: resp = send_at('AT+CBC', 'OK', 0.5) #func.log('sim.py', 'check_voltage', 'resp: ' + resp); if "V" in resp: voltage = resp[13:19] except: func.log('sim.py', 'check_voltage', 'error: ' + str(sys.exc_info()[0])) return voltage
def get_voltage(): v = "NA"; try: #result = subprocess.getoutput("echo get battery | nc -q 0 127.0.0.1 8423"); result = subprocess.check_output(['bash','-c', "echo get battery | nc -q 0 127.0.0.1 8423"]); if "battery: " in result: v = "B: " + result[9:11] + "%"; except: func.log('main.py', 'get_voltage', 'Exception (' + str(sys.exc_info()) + ') has been caught.'); return v;
def OnSelect(self, event): index = event.GetIndex() func.log('1', 'Demoname in "All Screenshots": %s' % func.demoname(timed)) try: sshot = wx.Image(self.scrlist[index], wx.BITMAP_TYPE_JPEG).Scale( 544, 452, wx.IMAGE_QUALITY_HIGH).ConvertToBitmap() except: sshot = wx.Image(self.scrlist[index], wx.BITMAP_TYPE_TGA).Scale( 544, 452, wx.IMAGE_QUALITY_HIGH).ConvertToBitmap() self.screenshot.SetBitmap(sshot)
def display_loop(): global currentStats, currentLine1, currentLine2 time_disp = time.time(); while True: try: #func.log('main.py', 'myloop', 'looping...'); #if (time.time() - time_disp > 1): disp.update_disp(currentStats, currentLine1, currentLine2); time_disp = time.time(); except: func.log('main.py', 'display_loop', 'Exception: ' + str(sys.exc_info()[0]) );
def clear_serial(): global ser, mydevice, mybaud, mytimeout try: func.log( 'sim.py', 'clear_serial', 'attempting to reset serial with device: ' + mydevice + ' baud: ' + str(mybaud) + ' timeout: ' + str(mytimeout)) ser = serial.Serial(mydevice, mybaud, timeout=mytimeout) ser.flushInput() except: func.log('sim.py', 'clear_serial', 'error: ' + str(sys.exc_info()))
def get_signal(): resp = '' signal = '' try: resp = send_at('AT+CSQ', 'OK', 0.5) signal = resp[resp.find(': ') + 1:resp.find('||')] except: func.log('sim.py', 'get_signal', 'error: ' + str(sys.exc_info()[0])) #func.log('sim.py', 'get_signal', 'signal: ' + signal); return signal
def get_network(): resp = '' network = '' try: resp = send_at('AT+CPSI?', 'OK', 0.5) network = resp[resp.find(': ') + 1:resp.find(',')] except: func.log('sim.py', 'get_network', 'error: ' + str(sys.exc_info()[0])) #func.log('sim.py', 'get_network', 'network: ' + network); return network
def check_for_msg(): rec_buff = '' time.sleep(0.25) if ser.inWaiting(): time.sleep(0.25) rec_buff = ser.read(ser.inWaiting()) resp = str(rec_buff.decode().replace('\n', '|').replace('\r', '').encode('utf-8')) if len(resp) > 0: func.log('sim.py', 'check_for_msg', 'resp: ' + resp) return resp
def operator(peer, text): #Постучать оператору беседы в личку op = preset._scenr(peer, "operator") if op > 0: try: vkthing.messages.send(peer_id=op, message=text, random_id=randid()) except Exception as er: #TODO: изменить log(str(er)) preset.e_scenr(peer, "operator", 0) vkthing.messages.send( peer_id=peer, message= "@id%s (Оператор) больше не оператор, так как он запретил отправку сообщений в личку от сообщества." % (op), random_id=randid())
def get_call_info(): resp = '' try: resp = send_at('AT+CLCC', 'CLCC', 0.5) except: func.log('sim.py', 'get_call_info', 'error: ' + str(sys.exc_info()[0])) #|+CLCC: 2,1,4,0,0,"+12076192651",145||OK| call_info = '' temp = re.findall('"([^"]*)"', resp) if len(temp) > 0: call_info = temp[0] #func.log('sim.py', 'get_call_info', 'resp: ' + call_info); return call_info
def receive_short_message(msgId): rec_buff = '' send_at('AT+CMGF=1', 'OK', 1) send_at('AT+CPMS=\"SM\",\"SM\",\"SM\"', 'OK', 1) answer = send_at('AT+CMGR=' + msgId, '+CMGR:', 2) if 1 == answer: answer = 0 if 'OK' in rec_buff: answer = 1 func.log('sim.py', 'receive_short_message', 'rec_buff: ' + rec_buff.decode()) else: func.log('sim.py', 'receive_short_message', 'error%d' % answer) return False return True
def send_short_message(phone_number, text_message): func.log('sim.py', 'send_short_message', 'Setting SMS mode...') send_at("AT+CMGF=1", "OK", 1) func.log('sim.py', 'send_short_message', 'Sending Short Message') answer = send_at("AT+CMGS=\"" + phone_number + "\"", ">", 2) if 1 == answer: ser.write(text_message.encode()) ser.write(b'\x1A') answer = send_at('', 'OK', 20) if 1 == answer: func.log('sim.py', 'send_short_message', 'send successfully') else: func.log('sim.py', 'send_short_message', 'error') else: func.log('sim.py', 'send_short_message', 'error%d' % answer)
def __init__(self, parent): wx.Frame.__init__(self, parent, title="UrTDSC - Create demos archive", size=(700, 580)) CreateDemosArchive.SetSizeHints(self, 700, 580, 700, 580) self.panel = wx.Panel(self, -1) self.Bind(wx.EVT_CLOSE, self.OnClose) wx.StaticText( self.panel, -1, "Demos that will be archived are listed on left side. Demos that was completed in 40 minutes range of selected demo in main window are listed on right side.", pos=(5, 5), size=(600, 35)) wtfb = wx.Button(self.panel, -1, "WTF?", pos=(610, 5)) self.Bind(wx.EVT_BUTTON, self.wtf, wtfb) self.dmtoarc = wx.ListBox(self.panel, 26, pos=(15, 55), size=(270, 200), style=wx.LB_SINGLE) self.dmlist = wx.ListBox(self.panel, 26, pos=(415, 55), size=(270, 200), style=wx.LB_SINGLE) wx.Button(self.panel, -1, "<< Add", pos=(307, 54)) wx.Button(self.panel, -1, "Remove >>", pos=(307, 227)) wx.StaticLine(self.panel, -1, pos=(5, 260), size=(690, 5)) wx.StaticLine(self.panel, -1, pos=(350, 265), size=(5, 200), style=wx.LI_VERTICAL) wx.StaticLine(self.panel, -1, pos=(5, 470), size=(690, 5)) wx.StaticText(self.panel, -1, "Ready to create archive...", pos=(5, 480), size=(620, 35)) wx.Gauge(self.panel, -1, 100, pos=(5, 505), size=(690, 15)) wx.Button(self.panel, -1, "Create archive!", pos=(300, 535)) self.CenterOnParent() func.log('1', "Demos Window - success")
def forward_propagation(self, model, X, Y, hyper_dic): activation_str = hyper_dic["activation"] model = self._init_model(hyper_dic, model) W1 = model["W1"] b1 = model["b1"] W2 = model["W2"] b2 = model["b2"] X = self._normalization(X) Z1 = np.dot(X, W1) + b1 a1 = func.activation(Z1, activation_str) logits = np.dot(a1, W2) + b2 prob = func.softmax(logits) correct_probs = prob[range(X.shape[0]), np.argmax(Y, axis=1)] correct_logprobs = -func.log(correct_probs) data_loss = np.sum(correct_logprobs) loss = 1. / X.shape[0] * data_loss pre_Y = np.argmax(prob, axis=1) comp = pre_Y == np.argmax(Y, axis=1) accuracy = len(np.flatnonzero(comp)) / Y.shape[0] return model, prob, a1, Z1, loss, accuracy, comp
def main_loop(): global doLoop, isRunning, simgood global currentStats, currentLine1, currentLine2 turn_off_sim() turn_on_sim() time_updates = time.time() while doLoop: try: #func.log('main.py', 'myloop', 'looping...');s if (time.time() - time_updates > 5): if (simgood): currentStats[0] = sim.check_voltage() currentStats[1] = sim.get_signal() currentStats[2] = sim.get_network() time_updates = time.time() check_sim_notification() except: func.log('main.py', 'main_loop', 'Exception: ' + str(sys.exc_info()))
def check_sim_notification(): try: #func.log('main.py', 'check_sim_notification', 'start'); global inCall, isRinging, currentLine1, currentLine2, simgood msg = sim.check_for_msg() if (len(msg) > 0): func.log('main.py', 'check_sim_notification', 'receive msg:' + msg) if "PB DONE" in msg: simgood = True currentLine1 = "Ready" currentLine2 = "" if "RING" in msg: call_info = sim.get_call_info() currentLine1 = "INCOMING CALL:" currentLine2 = call_info isRinging = True if "MISSED" in msg: # |MISSED_CALL: 02:22AM +12076192651| currentLine1 = "MISSED CALL: " currentLine2 = msg[14:33] isRinging = False if "NO CARRIER" in msg: currentLine1 = "NO CARRIER" currentLine2 = "" inCall = False if "VOICE CALL" in msg: temp = msg.split('|') temp = temp.split(' ') currentLine1 = temp[1] currentLine2 = temp[2] inCall = False #if "ERROR" in msg: #simgood = False; except: func.log('main.py', 'check_sim_notification', 'Exception (' + str(sys.exc_info()[0]) + ') has been caught.')
def check_for_msg(): global ser resp = "" try: rec_buff = '' time.sleep(0.25) if ser.inWaiting(): time.sleep(0.25) rec_buff = ser.read(ser.inWaiting()) resp = str(rec_buff.decode().replace('\n', '|').replace('\r', '').encode('utf-8')) if len(resp) > 0: func.log('sim.py', 'check_for_msg', 'resp: ' + resp) except: resp = "*ERROR*" func.log('sim.py', 'check_for_msg', 'error: ' + str(sys.exc_info())) clear_serial() return resp
def delete_message(msgId): func.log('sim.py', 'delete_message', 'Deleting message') answer = send_at('AT+CMGD=' + msgId, 'OK', 5) if 1 == answer: func.log('sim.py', 'delete_message', 'delete successfully') else: func.log('sim.py', 'delete_message', 'error%d' % answer)
def youtubeDlOne(self, filePath, info, ydl_opts, times=1): filelist = os.listdir(filePath) for i in filelist: if '.part' in i: os.remove(filePath+i) url = info['webpage_url'] isdownload = func.isDone(self.__workspace+'\\log\\log.txt', url) if isdownload == True: func.log(self.__workspace, url+'已下载', 1) return False if self.startTime != 0: if info['upload_date'] <= str(self.startTime) or info['upload_date'] >= str(self.endTime): return False filepath = filePath+self.outtmpl.replace('%(title)s', info['title']).replace( '%(id)s', info['id']).replace('%(url)s', info['url']).replace('%(ext)s', info['ext']) with youtube_dl.YoutubeDL(ydl_opts) as ydl: try: func.tips('正在下载%s' % url) self.statusbarinfo(1, '正在下载%s' % info['title']) self.t1 = threading.Thread( target=ydl.download, args=([url],)) self.t1.start() self.t2 = threading.Thread( target=self.speed, args=(info['filesize'], filepath)) self.t2.start() except youtube_dl.utils.DownloadError as e: if times > 2: func.log(self.__workspace, '下载视频{}时出错,错误信息:{},跳过该视频!'.format(url, str(e)), 1) f = open('异常链接.txt').read() if url in f: pass else: open('异常链接.txt', 'w').write(url) else: times += 1 self.youtubeDlOne(filePath, info, ydl_opts, times) return False return True
def main_loop(): global doLoop, isRunning, simgood, displayUpdateTime, displayUpdateTimeDefault; global currentStats, currentLine1, currentLine2 func.log('main.py', 'myloop', 'turning off sim just in case'); turn_off_sim(); time.sleep(5.00); func.log('main.py', 'myloop', 'turning sim back on'); turn_on_sim(); time_updates = time.time(); while doLoop: try: #func.log('main.py', 'myloop', 'looping...'); if (time.time() - time_updates > displayUpdateTime): currentStats[0] = get_voltage(); if (simgood): currentStats[1] = sim.get_signal(); currentStats[2] = sim.get_network(); time_updates = time.time(); displayUpdateTime = displayUpdateTimeDefault; check_sim_notification(); check_for_input(); except: func.log('main.py', 'main_loop', 'Exception: ' + str(sys.exc_info()));
def check_for_input(): #func.log('main.py', 'check_for_input', 'start'); global inCall, isRinging, currentLine1, currentLine2, displayUpdateTime; rec_buff = ''; try: time.sleep(0.25); if serInput.inWaiting(): time.sleep(0.01); rec_buff = serInput.read(serInput.inWaiting()); resp = str(rec_buff.decode()); if len(resp) > 0: displayUpdateTime = 1; if "S" in rec_buff.decode(): shutdown(); elif "H" in rec_buff.decode(): sim.hangup(); currentLine1 = 'Hangup'; currentLine2 = ''; isRinging = False; inCall = False; elif "C" in rec_buff.decode(): if isRinging: sim.answer_call(); else: sim.make_call(currentLine2); currentLine1 = 'Calling'; isRinging = False; inCall = True; else: currentLine2 = currentLine2 + rec_buff.decode(); if inCall: sim.send_tone(rec_buff.decode()); func.log('main.py', 'check_for_input', 'rec_buff: ' + rec_buff.decode()); except: func.log('main.py', 'check_for_input', 'Exception (' + str(sys.exc_info()[0]) + ') has been caught.'); #func.log('main.py', 'check_for_input', 'end'); return resp;
def OnSelect(self, event): index = event.GetSelection() global timed timed = self.demos.GetString(index) #systimed = func.demorealdate(func.demoname(timed)) a = self.demoname b = self.nickname c = self.sshotaddr d = self.maps maplist = [] func.log('2', "[to func] Sending demo time: %s" % timed) a.SetLabel(label=func.demoname(timed)) b.SetLabel(label=func.demonick(func.demoname(timed))) try: screens = func.demoscreens(func.demoname(timed)) c.SetLabel(label=str(screens[0])) if DEBUG in ('1', '2'): func.log('1', "Screenshot: %s" % str(screens[0])) if str(screens[0]) != None or str(screens[0]) != "None": try: sshot = wx.Image(screens[0], wx.BITMAP_TYPE_JPEG).Scale( 550, 400, wx.IMAGE_QUALITY_HIGH).ConvertToBitmap() except: sshot = wx.Image(screens[0], wx.BITMAP_TYPE_TGA).Scale( 550, 400, wx.IMAGE_QUALITY_HIGH).ConvertToBitmap() self.screenshot.SetBitmap(sshot) else: sshot = wx.EmptyImage(550, 400).ConvertToBitmap() self.screenshot.SetBitmap(sshot) func.log('1', "Failed to set a screenshot!") except: c.SetLabel(label='No screenshot') sshot = wx.EmptyImage(550, 400).ConvertToBitmap() self.screenshot.SetBitmap(sshot) func.log('1', "No reliable screenshot(s) found") for scr in screens: scrs = scr.split("_") if scrs[1] in ('TOHUNGA', 'ORBITAL'): maplist.append(scrs[1] + "_" + scrs[2]) else: maplist.append(scrs[1]) items = ", ".join(maplist).lower() d.SetLabel(items)
def forward_propagation(self, model, X, Y, hyper_dic): activation_str = hyper_dic["activation"] architecture = hyper_dic["architecture"] epsilon = hyper_dic["epsilon"] model = self._init_model(hyper_dic, model) weight_lt = model["weight_lt"] bias_lt = model["bias_lt"] linear_output_lt = [] activation_output_lt = [] model["linear_output_lt"] = linear_output_lt model["activation_output_lt"] = activation_output_lt batch_size = hyper_dic["batch_size"] activation_output_lt.append(X) a = X Z = None for i in range(len(architecture) - 2): Z = np.dot(a, weight_lt[i]) + bias_lt[i] model["linear_output_lt"].append(Z) a = func.activation(Z, activation_str) model["activation_output_lt"].append(a) Z = np.dot(a, weight_lt[len(architecture) - 2]) + bias_lt[len(architecture) - 2] model["linear_output_lt"].append(Z) prob = func.softmax(Z) correct_probs = prob[range(batch_size), np.argmax(Y, axis=1)] correct_logprobs = -func.log(correct_probs) data_loss = np.sum(correct_logprobs) loss = 1. / batch_size * data_loss pre_Y = np.argmax(prob, axis=1) comp = pre_Y == np.argmax(Y, axis=1) accuracy = len(np.flatnonzero(comp)) / Y.shape[0] return model, prob, loss, accuracy, comp
def send_at(command, back, timeout): rec_buff = '' ser.write((command + '\r\n').encode()) time.sleep(timeout) if ser.inWaiting(): time.sleep(0.25) rec_buff = ser.read(ser.inWaiting()) if back not in rec_buff.decode(): func.log('sim.py', 'send_at', command + ' ERROR') func.log('sim.py', 'send_at', command + ' back:\t' + rec_buff.decode()) return 'ERROR' else: resp = str(rec_buff.decode().replace('\n', '|').replace('\r', '')) if len(resp) > 0: func.log('sim.py', 'send_at', resp) return resp
def main(): # 当前时间 now = datetime.datetime.now() func.log('-' * 20) func.log(f'[{now:%Y-%m-%d %H:%M:%S}]') for platform, order_num_requests in conf.platform_order_num_requests.items( ): platform_last_order_num = func.get_platform_last_order_num(platform) platform_order_num = 0 for order_num_request in order_num_requests: try: if 'post_query' not in order_num_request: response = requests.get( order_num_request['url'], headers=order_num_request['request_header']) else: response = requests.post( order_num_request['url'], headers=order_num_request['request_header'], data=order_num_request['post_query']) order_num = re.search(order_num_request['pattern'], response.text).group('order_num') except Exception: func.send_email(f'[{platform}]获取订单数失败,请及时处理', f'[{platform}]获取订单数失败,请及时处理') exit() platform_order_num += int(order_num) func.record_platform_order_num(platform, platform_order_num) func.log( f'[{platform}]总订单数 {platform_order_num} 上次记录总订单数 {platform_last_order_num}' ) if (platform_last_order_num is not None) and (platform_order_num > platform_last_order_num): subject = f'[{platform}]订单增加{platform_order_num - platform_last_order_num}' content = f'{platform}总订单数 {platform_order_num}\n上次记录总订单数 {platform_last_order_num}' func.send_email(subject, content) func.end()
def power_off(): try: send_at('AT+CPOF', 'OK', 1) except: func.log('sim.py', 'power_off', 'error: ' + str(sys.exc_info()[0]))
def answer_call(): try: send_at('ATA', 'OK', 0.5) except: func.log('sim.py', 'answer_call', 'error: ' + str(sys.exc_info()[0]))
def hangup(): global ser try: ser.write('AT+CHUP\r\n'.encode()) except: func.log('sim.py', 'hangup', 'error: ' + str(sys.exc_info()[0]))
def make_call(phone_number): try: send_at('ATD' + phone_number + ';', 'OK', 1) except: func.log('sim.py', 'make_call', 'error: ' + sys.exc_info()[0])
def send_tone(tone): try: send_at('AT+VTS="' + tone + '"', 'OK', 1) except: func.log('sim.py', 'send_tone', 'error: ' + sys.exc_info()[0])
def recall(self,url,data): if(url != -1): func.log("[INFO ][RETURN] url:%s, data: %s" %(url, data)); urllib.urlopen(url + "?%s" % urllib.urlencode(data)).getcode(); else: func.log("[ERROR][CALLBACK] empty callback, data: %s" % data);