def long_poll(self): tag = 'VK - Message LongPoll' from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType long_poll_bot = VkBotLongPoll( self.vk_bot, int(self.config.read(self.settings_tag, "community_id"))) for event in long_poll_bot.listen(): try: if event.type == VkBotEventType.MESSAGE_NEW: Log().info( tag, f'Новое сообщение от \"https://vk.com/id{event.obj.from_id}\".\n' f'Текст сообщения:\t\n{event.obj.text}\n' f'Прикрепленные аттачи:\t\n{event.obj.attachments}\n' f'Пересланные сообщения:\t\n{event.obj.fwd_messages}') self.listener(event) elif event.type == VkBotEventType.MESSAGE_REPLY: Log().info(tag, f'Бот ответил в чате {event.obj.peer_id}.') else: Log().info( tag, f'Обнаружено новое действие: {event.type} от ' f'\"https://vk.com/id{event.obj.from_id}\"') except Exception as e: Log().error(tag, e)
def __init__(self): self.nals = [] self.next_rtp = None self.rtp_con = threading.Condition() self.rtp_buffer = [] self.rtp_end = False self.unpacketLog = Log("unpacketLog.txt")
def prepareOperand(self,operand,inputLeadDataDict,executionStack): from Utils.Log import Log from Utils.TriumphKey import TriumphKey if len(executionStack) > 0: currentAgentDataDict=executionStack[-1].currentIterationData else: currentAgentDataDict=None if operand.opType == TriumphKey.OperandType.LITERAL: return operand.opTag elif operand.opType == TriumphKey.OperandType.FEATURE: if inputLeadDataDict.has_key(operand.opTag) is True: return inputLeadDataDict[operand.opTag] elif currentAgentDataDict is not None: #check for data in current execution stack Log.d(Allocation.TAG,currentAgentDataDict) if currentAgentDataDict.has_key(operand.opTag) is True: return currentAgentDataDict[operand.opTag] return None else: #TODO: Ideally allocation type of feature should be handled here Log.log(Allocation.TAG,'Could not find data for this feature'+str(operand.opTag)) return None elif operand.opType == TriumphKey.OperandType.OPERATION: subRule=operand.subRule[0] subRuleName=subRule.operands[0].opTag subWorkflow=self.workflowManager.getWorkflow(subRuleName,'tech',0,'sanket') if subWorkflow is not None: return self.runWorkflow(subWorkflow,inputLeadDataDict,executionStack) elif operand.opType == TriumphKey.OperandType.VAR: if operand.opTag=='agents': agentDataList=[] for key,agentData in self.inputAgentsData.iteritems(): agentDataList.append(agentData) return agentDataList
def __init__(self): self.dataChannel = None self.ctlChannel = None self.ctlChannel = ClientControl(2, self.freqAssignCB, self.freqReleaseACKCB) self.stateLock = threading.Lock() self.state = Idle self.log = Log('ClientLog.txt') pass
def operate(self): from Utils.TriumphKey import TriumphKey from Utils.Log import Log if self.operation == TriumphKey.Operator.EQUALS: if len(self.operands)==2: return self.operands[0]==self.operands[1] else: return False elif self.operation == TriumphKey.Operator.LT: if len(self.operands)==2: return self.operands[0]<self.operands[1] else: return False elif self.operation == TriumphKey.Operator.GT: if len(self.operands)==2: return self.operands[0]>self.operands[1] else: return False if self.operation == TriumphKey.Operator.LE: if len(self.operands)==2: return self.operands[0]<=self.operands[1] else: return False elif self.operation == TriumphKey.Operator.GE: if len(self.operands)==2: return self.operands[0]>=self.operands[1] else: return False elif self.operation == TriumphKey.Operator.NE: if len(self.operands)==2: return self.operands[0]!=self.operands[1] else: return False elif self.operation == TriumphKey.Operator.AND: if len(self.operands)==2: return self.operands[0] and self.operands[1] else: return False elif self.operation == TriumphKey.Operator.OR: if len(self.operands)==2: return self.operands[0] or self.operands[1] else: return False elif self.operation == TriumphKey.Operator.NOT: if len(self.operands)==2: return self.operands[0] is not None elif self.operation == TriumphKey.Operator.PRODUCT: product=1 if len(self.operands)>=2: for operand in self.operands: product=product*operand return product else: Log.e(Operation.TAG,'Invalid set of inputs'+str(self.operands)+str(self.operation)) return False
def allocate(self): from Utils.Log import Log from AllocationService import AllocationService from Operation import Operation # Save rules in a dictionary with key being the index #Log.log(Allocation.TAG, 'Input leads data is '+str(self.inputLeadsData)) for key,value in self.inputLeadsData.iteritems(): Log.log(Allocation.TAG,'Running loop for '+str(key)) self.workflowManager=AllocationService.getWorkflowManager() workflow=self.workflowManager.getWorkflow(self.workflowName,'tech',0,'sanket') self.runWorkflow(workflow,value,[])
def _run_cases(run, cases): log = Log() log.set_logger(run.get_device()['model'], run.get_path() + '/' + 'client.log') log.i('udid: %s', run.get_device()['udid']) # set cls.path, it must be call before operate on any page path = ReportPath() path.set_path(run.get_path()) # set cls.driver, it must be call before operate on any page base_page = BasePage() if 'ip' in run.get_device(): base_page.set_driver(run.get_device()['ip']) else: base_page.set_driver(run.get_device()['serial']) try: # run cases base_page.set_fastinput_ime() run.run(cases) base_page.set_original_ime() base_page.identify() except AssertionError as e: log.e('AssertionError, %s', e)
def __init__(self, file_name, mtu_size, ssrc, dqID): read_video.file_name = file_name read_video.init_file(read_video.file_name) self.mtu_size = mtu_size self.seq_num = 1 self.ssrc = ssrc self.timestamp = 0 self.nals = [] self.left_nal = "" self.first_byte = 0 self.nal_num = 0 self.accessUnitID = 0 self.dqID = dqID self.packetLog = Log("packetLog.txt") self.packetNumber = 1
def _install_app(run, apkPath): log = Log() # apk_info = get_apk_info(apkPath) base_page = BasePage() device = run.get_device() if 'ip' in run.get_device(): base_page.set_driver(run.get_device()['ip']) else: base_page.set_driver(run.get_device()['serial']) base_page.set_fastinput_ime() d = base_page.get_driver() #安装应用 file_name = os.path.basename(apkPath) dst = '/sdcard/' + file_name print('start push apk.......') d.push(apkPath, dst) print('start install apk ............') d.shell(['pm', 'install', '-r', dst], stream=True) # d.shell(['rm', dst]) # time.sleep(60) base_page.set_original_ime() base_page.identify() time.sleep(45) print('delete apk ...............') d.shell(['rm', dst])
def createExecutionContext(self): from Utils.Log import Log from mongoengine import connect MONGO_DATABASE_NAME='testdb' MONGO_HOST='127.0.0.1' MONGO_PORT=27017 connect('testdb',host=MONGO_HOST,port=MONGO_PORT) self.workflowName='termAllocation' bu='tech' version=0 developer='sanket' from Executor.ExecutionContext import ExecutionContext self.executionContext=ExecutionContext(self.workflowName,bu,version,developer) self.executionContext.prepareDB() self.executionContext.populateFeatureListObj(self.executionContext.workflow) Log.log(Allocation.TAG,'Feature list is '+str(self.executionContext.featureList)) self.fetchLeadsAndAgentsData() self.executionContext.fetchFeatureValueForLeads(self.inputLeadsData,self.inputAgentsData)
class TestServer: def __init__(self, client, dqID): self.dqID = dqID self.fileName = "../Server/svc.file" self.pack = packet.packet(self.fileName, 400, 177, dqID) self.client = client self.serverLog = Log("serverLog.txt") def startSend(self): lossFile = file("lost_" + str(self.dqID) + ".txt") lineContent = lossFile.readline() if lineContent: lossPktNo = int(lineContent) else: lossPktNo = -1 one_packet = self.pack.get_one_packet() curPktNo = 1 self.bEnd = False self.bPause = False while one_packet and not self.bEnd: if curPktNo == lossPktNo: #remove it #print "remove pktno ", curPktNo lineContent = lossFile.readline() if lineContent: try: lossPktNo = int(lineContent) except: lossPktNo = -1 else: lossPktNo = -1 else: #deliver it to client self.client.receive_one_packet(one_packet) if self.dqID == 16: pass elif self.dqID == 1: time.sleep(0.01) else: time.sleep(0.015) self.serverLog.LogStr("pktNo %d len %d" % (curPktNo, len(one_packet))) curPktNo += 1 one_packet = self.pack.get_one_packet() while self.bPause and not self.bEnd: time.sleep(0.1) time.sleep(0.01) def stopSend(self): self.bEnd = True def pauseSend(self): self.bPause = True def resumeSend(self): self.bPause = False
def __init__(self): log_tag = 'VK - init' self.settings_tag = 'VK' self.extractor = URLExtract() self.config = Config() try: self.vk_bot = vk_api.VkApi( token=str(self.config.read(self.settings_tag, 'bot_token'))) self.api_bot_vk = self.vk_bot.get_api() Log().info(log_tag, 'Инициализация токена-бота VK успешна.') except Exception as e: Log().error(log_tag, e) p_name = 'ЛИНКЕР' p_channel = 'hackathon' p_version = '0.0.1' desc = 'Бот, создающий сокращенные vk.cc ссылки прямо в диалоге.' self.info = f'{p_name} {p_version} ({p_channel})\n\n{desc}\n\nбеседа %peer_id%'
def fetchLeadsAndAgentsData(self): from Utils.Log import Log import sys this_function_name = sys._getframe().f_code.co_name Log.log(Allocation.TAG,this_function_name) from Executor.InputDataExtracter import InputDataExtracter inputDataExtracter=InputDataExtracter() inputDataExtracter.setInputLeadsQuery(None) inputDataExtracter.setInputAgentsQuery(None) self.inputLeadsData=inputDataExtracter.fetchInputLeads() self.inputAgentsData=inputDataExtracter.fetchInputAgents() self.leadAssignmentData=[] # Contains pair of lead against Agent if self.inputLeadsData is not None: for leadIdKey in self.inputLeadsData.keys(): self.leadsList.append(leadIdKey) else: Log.log(Allocation.TAG,'Input leads data is None') if self.inputAgentsData is not None: for key in self.inputAgentsData.keys(): pass
def runOperation(self,workflowName,curRule,operandList,executionStack,inputLeadDataDict): #Process Operator on gathered list of operands from Utils.TriumphKey import TriumphKey from Utils.Log import Log result=0 if curRule.operator == TriumphKey.Operator.FEATURE: from FeatureManager.FeatureStore import FeatureStore fs=FeatureStore() allocationFeature=curRule.operands[0].opTag allocOperandList=operandList[1:] allocOperandTuple=tuple(operandList[1:]) featureType=fs.getFeatureType(allocationFeature) if featureType==TriumphKey.FeatureType.ALLOCATION: if self.mCache.getData(allocationFeature,allocOperandList) is None: result=self.executionContext.fetchAllocationFeatureValues(allocationFeature,allocOperandTuple) result=result[0][0][1] self.mCache.saveData(allocationFeature,allocOperandList,result) else: result=self.mCache.getData(allocationFeature,allocOperandList) if result is not None: Log.d(Allocation.TAG,'Found an allocation feature name'+str(allocationFeature)) #result=result[0] elif curRule.operator == TriumphKey.Operator.LOOP: dataList=operandList[0] executionStack.append(ExecutionStackNode(workflowName,curRule.depth,curRule.nextRuleIndex,ExecutionStackNode.STACKNODETYPE.DATALOOP,dataList)) elif curRule.operator == TriumphKey.Operator.SUBRULE: from AllocationService import AllocationService self.workflowManager=AllocationService.getWorkflowManager() if operandList[0] == 'assignA1' or operandList[0] == 'assignA2' or operandList[0] =='assignA3': executionStack[-1].assigned=True newWorkflow=self.workflowManager.getWorkflow(operandList[0],'tech',0,'sanket') if newWorkflow is not None: result=self.runWorkflow(newWorkflow,inputLeadDataDict,executionStack) else: from Executor.Operation import Operation operandListTuple=tuple(operandList) operation=Operation(curRule.operator,operandListTuple) result=operation.operate() return result
def fetchData(self, queryString): if self.dbType == 'REPLICASQL': conn = pyodbc.connect('DSN=MSSQL;UID=PBLive;PWD=PB123Live') cursor = conn.cursor() from Utils.Log import Log #Log.v(dbAdapter.TAG,'Query to be fetched is '+queryString) try: results = cursor.execute(queryString) except: Log.e(dbAdapter.TAG, 'Fetch failed ' + str(queryString)) columns = [column[0] for column in cursor.description] resultList = [] index = 0 for result in results: resultList.append(zip(columns, result)) record = resultList[index] for attribute in record: pass #print str(attribute[0])+' value is '+str(attribute[1]) index = index + 1 #print 'List of attributes of results fetched are : '+str(resultList) return resultList elif self.dbType == 'PRODSQL': conn = pyodbc.connect('DSN=MSSQLPROD;UID=PBLive;PWD=PB123Live') cursor = conn.cursor() results = cursor.execute(queryString) columns = [column[0] for column in cursor.description] resultList = [] index = 0 for result in results: resultList.append(zip(columns, result)) record = resultList[index] for attribute in record: pass #print str(attribute[0])+' value is '+str(attribute[1]) index = index + 1 #print 'List of attributes of results fetched are : '+str(resultList) return resultList
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # LINKER # (c) Oleg Plaxin 2019 # [email protected] # -*- coding: utf-8 -*- from Utils.Log import Log from VK.Vk import VK def main(): Log().debug(tag, 'Корректный запуск.') VK().long_poll() if __name__ == '__main__': tag = 'MAIN' while True: try: main() except Exception as e: Log().error(tag, e)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/20 10:49 # @Author : qingping.niu # @File : Decorator.py # @desc : 装饰器 import time from functools import wraps from PageObject.BasePage import BasePage from Utils.Log import Log from Utils.ReportPath import ReportPath flag = 'IMAGE:' log = Log() # log = Log().set_logger('udid', './log.log') def _screenshot(name): date_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) screenshot = name + '-' + date_time + '.PNG' path = ReportPath().get_path() + '/' + screenshot driver = BasePage().get_driver() driver.screenshot(path) return screenshot def teststep(func):
# !/usr/bin/python # coding=utf-8 # # @Author: LiXiaoYu # @Time: 2013-10-17 # @Info: Util import sys, os, traceback from Utils.Log import Log from Const import * from Config import Config #日志对象 l = Log() def log(msg="", log_type=LOG_SYSTEM, log_level=ERROR, log_file=""): config = Config() if config.get("log_record") == "False": return False if msg == "": #捕获异常信息 msg = traceback.format_exc().splitlines() #写日志 l.write(msg, log_file, log_type, log_level) #调试信息 def debug(msg=""): log(msg, log_level=DEBUG, log_file="info.log")
def fetchFeatureValueForLeads(self, leadsData, agentsData): from FeatureExec import FeatureExec from Utils.Log import Log from Utils.TriumphKey import TriumphKey featureExec = FeatureExec() self.currentLeadsData.actorDataDict = {} leadsList = [] if leadsData is not None: for leadIdKey in leadsData.keys(): leadsList.append(leadIdKey) self.currentLeadsData.actorDataDict[leadIdKey] = leadsData[ leadIdKey] self.currentAgentsData.actorDataDict = agentsData inputProperties = {} inputProperties[TriumphKey.FeatureFetchProperty. dataType] = TriumphKey.FeatureType.LEAD inputProperties[TriumphKey.FeatureFetchProperty. inputDataField] = TriumphKey.LeadInputDataField.leadId inputProperties[TriumphKey.FeatureFetchProperty.data] = leadsList from FeatureManager.FeatureStore import FeatureStore fs = FeatureStore() featureFoundOut = [] Log.d( ExecutionContext.TAG, 'List of all features from workflow to be fetched are ' + str(self.featureList)) for feature in self.featureList: featureType = fs.getFeatureType(feature) if featureType == TriumphKey.FeatureType.AGENT or featureType == TriumphKey.FeatureType.ALLOCATION: continue #To avoid fetching same feature multiple times if feature not in featureFoundOut: featureFoundOut.append(feature) else: #Feature has already been found out for each lead continue #Now beginning to fetch feature data featureValues4AllLeads = featureExec.fetchFeatureValue( feature, inputProperties) #In case sql query failed and no data was fetched if featureValues4AllLeads is None: continue #Processing data lead by lead as data has been fetched for multiple leads for featureValuesPerLead in featureValues4AllLeads: leadPropDict = {} #Saving data for all attributes: first argument being attribute name and second being value for featureValTuple in featureValuesPerLead: if featureValTuple[0] != 'leadId': leadPropDict[str( featureValTuple[0])] = featureValTuple[1] else: leadId = featureValTuple[1] #In case of data being already present for a lead append new attributes to existing dictionaries #else create a dictionary entry for this lead in currentLeadsData #Skipping putting an entry for an attribute of a lead if its already present if self.currentLeadsData.actorDataDict.has_key(leadId) is True: prevDataTemp = self.currentLeadsData.actorDataDict[leadId] for key in leadPropDict.keys(): if prevDataTemp.has_key(key) is False: prevDataTemp[key] = leadPropDict[key] else: Log.d( ExecutionContext.TAG, 'Entry already present in dictionary for this lead so skipping' + str(key)) self.currentLeadsData.actorDataDict[leadId] = prevDataTemp else: self.currentLeadsData.actorDataDict[leadId] = leadPropDict
class unpacket: def __init__(self): self.nals = [] self.next_rtp = None self.rtp_con = threading.Condition() self.rtp_buffer = [] self.rtp_end = False self.unpacketLog = Log("unpacketLog.txt") def get_one_rtp(self): self.rtp_con.acquire() while len(self.rtp_buffer) == 0: if self.rtp_end: self.rtp_con.release() return None #wait will release the contition and acquire it after time expire self.rtp_con.wait(1) one_rtp = self.rtp_buffer[0] self.rtp_buffer = self.rtp_buffer[1:] self.rtp_con.release() return one_rtp def put_one_rtp(self, rtp): self.rtp_con.acquire() self.rtp_buffer.append(rtp) self.rtp_con.notify() self.rtp_con.release() def end_rtp(self): self.rtp_end = True def get_rtp_type(self, rtp_payload): fb = struct.unpack('!B', rtp_payload[0:1])[0] rtp_type = fb & 31 return rtp_type def extract_nal_from_nor_rtp(self, rtp_payload): return rtp_payload def extract_nal_from_fu_a_rtp(self, rtp_payloads, rtps): nal = '' if not check_rtp_fu_as(rtps): self.unpacketLog.LogStr('fu check error') return nal self.unpacketLog.LogStr('fu check succeed') for i in range(len(rtp_payloads)): nal += rtp_payloads[i][2:] return nal def extract_nal_from_stap_a_rtp(self, rtp_payload): rtp_payload = rtp_payload[1:] nals = [] while len(rtp_payload) > 0: now_nal_size = struct.unpack('!H', rtp_payload[0:2])[0] nals.append(rtp_payload[2:now_nal_size + 2]) rtp_payload = rtp_payload[now_nal_size + 2:] self.unpacketLog.LogStr('extract nal from stap, nal number: ' + str(len(nals))) return nals def get_one_nal(self): #pdb.set_trace() if len(self.nals) > 0: res = self.nals[0] self.nals = self.nals[1:] return res else: if self.next_rtp == None: now_rtp = self.get_one_rtp() if now_rtp == None: return None else: now_rtp = self.next_rtp self.next_rtp = None header_len = get_rtp_header_len(now_rtp) now_payload = now_rtp[header_len:] rtp_type = self.get_rtp_type(now_payload) if rtp_type <= 23: self.unpacketLog.LogStr("receive one nor rtp") res = self.extract_nal_from_nor_rtp(now_payload) return res elif rtp_type == 24: self.unpacketLog.LogStr('receive one stap_a rtp') self.nals = self.extract_nal_from_stap_a_rtp(now_payload) res = self.nals[0] self.nals = self.nals[1:] return res elif rtp_type == 28: #pdb.set_trace() self.unpacketLog.LogStr('receive one fu_a rtp') rtp_payloads = [] rtps = [] now_seq_num = get_seq_num(now_rtp) self.unpacketLog.LogStr('fu_a start seq num ' + str(now_seq_num)) fu_a_end = False while now_rtp != None and (not fu_a_end): header_len = get_rtp_header_len(now_rtp) now_payload = now_rtp[header_len:] rtp_type = self.get_rtp_type(now_payload) if rtp_type != 28: self.next_rtp = now_rtp fu_a_end = True else: fu_header = get_fu_a_header(now_payload) if len(rtps) > 0: if fu_header & (1 << 7) > 0: self.next_rtp = now_rtp fu_a_end = True else: rtps.append(now_rtp) rtp_payloads.append(now_payload) if fu_header & (1 << 6) > 0: fu_a_end = True else: now_rtp = self.get_one_rtp() else: rtps.append(now_rtp) rtp_payloads.append(now_payload) now_rtp = self.get_one_rtp() now_seq_num = get_seq_num(rtps[-1]) self.unpacketLog.LogStr('fu_a end seq num ' + str(now_seq_num)) res = self.extract_nal_from_fu_a_rtp(rtp_payloads, rtps) return res else: print "error rtp_type" pass
from jmetal.core.solution import Solution from jmetal.lab.visualization import Plot from jmetal.util.solution import get_non_dominated_solutions from Models.Network import Network from Problem.Evaluation import evaluateNetwork import timeit from itertools import product from Utils.Log import Log fileName = 'AllResults' startTime = timeit.default_timer() ResultLog = Log(fileName) minimumValue = 0 maximumValue = 8 sizeOfLinkBundles = 7 solutions = [] iterationNumber = 0 print("Starting...") Net = Network(folderName="Topologia1") allPossibilities = list(map(list, product(range(minimumValue, maximumValue + 1), repeat=sizeOfLinkBundles))) for individual in allPossibilities: print("Iteration Number: " + str(iterationNumber) + "\tpercentage: " + str(round(float(iterationNumber/len(allPossibilities) * 100), 2)))
from Models.Network import Network import timeit from Problem.CustomStopCriterion import StopByHyperVolume, StoppingByEvaluationsCustom from Problem.ProblemWrapper import OTNProblem from Utils.Log import Log startTime = timeit.default_timer() BestTirf = [] BestInterfaceQuantity = [] solutionsResult = [] frontResult = 0 timesToRun = 1 log_front = Log("front_140_Services") Net = Network(folderName="Topologia2") for executions in range(timesToRun): print("Interation number:", executions) problem = OTNProblem(Net, len(Net.LinkBundles)) max_evaluations = 1000 # stopCriterion = StoppingByEvaluationsCustom(max_evaluations, [200, 2.1]) # To topology 1, 200 is enough algorithm = NSGAII(problem=problem, population_size=20, offspring_population_size=20, mutation=IntegerPolynomialMutation( probability=0.05, distribution_index=20),
def _run_maxim(run, cases, command, actions, widget_black, apkinfo): log = Log() log.set_logger(run.get_device()['model'], os.path.join(run.get_path(), 'client.log')) log.i('udid: %s', run.get_device()['udid']) #取出包名和版本信息 packagename = apkinfo['package'] versionname = apkinfo['versionName'] log.i('packagename: %s, versionname: %s', packagename, versionname) # set cls.path, it must be call before operate on any page path = ReportPath() path.set_path(run.get_path()) # set cls.driver, it must be call before operate on any page base_page = BasePage() if 'ip' in run.get_device(): base_page.set_driver(run.get_device()['ip']) else: base_page.set_driver(run.get_device()['serial']) try: #创建日志存储路径 model = run.get_device()['model'] serial = run.get_device()['serial'] currentTime = time.strftime('%H%M%S', time.localtime(time.time())) monkeyFile = run.get_path( ) + os.path.sep + model + '_Monkey_' + versionname + '_' + currentTime + '.txt' logcatFile = run.get_path( ) + os.path.sep + model + '_Logcat_' + versionname + '_' + currentTime + '.txt' # run cases base_page.d.shell('logcat -c') # 清空logcat if cases: run.run_cases(cases) #格式化monkey命令 # command = command+ '>/sdcard/monkeyLog 2>&1' command = command % (serial) + '>' + monkeyFile + ' 2>&1' log.i('monkey_command: %s', command) #执行monkey命令 subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # base_page.d.shell(command) #执行logcat命令 logcmd = "adb -s %s logcat -v time *:E >%s" % (serial, logcatFile) # logcmd = "adb -s %s logcat -v time AndroidRuntime:* *:E >%s" % (serial, logcatFile) subprocess.Popen(logcmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # # base_page.d.shell(logcmd) # # time.sleep(5) output, exit_code = base_page.d.shell(["ps", "|grep", "logcat"]) # log.i('logcat pid: %s', output) pid = output.split()[1] while True: time.sleep(30) try: m_session = base_page.d.session( 'com.android.commands.monkey', attach=True) if m_session._pid: continue else: break except: kill_process(serial, pid) break log.i('**** monkey finished and logcat process kill sucess ****') # base_page.d.app_start('jp.mmasashi.turnWiFiOnAndEnjoyYouTube') # log.i('start ATX services sucess') # print(run.get_path()) # base_page.d.pull('/data/anr/',run.get_path()+"\\") # base_page.d.shell('adb pull /data/anr %s '%run.get_path()) anrPath = os.path.join(run.get_path(), model) log.i('anrpath==%s ' % anrPath) if not os.path.exists(anrPath): os.mkdir(anrPath) anrCmd = 'adb -s %s pull /data/anr %s' % (serial, anrPath) subprocess.Popen(anrCmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) log.i('pull /data/anr logs success') # 跑完monkey分析日志 crashLogPath = os.path.join(run.get_path(), 'Crash') MonkeyLog.crash_analyze(monkeyFile, crashLogPath, model, versionname, currentTime) MonkeyLog.logcat_analyze(logcatFile, crashLogPath, model, versionname, currentTime) # Maxim().run_monkey(monkey_shell=command, actions=actions, widget_black=widget_black) # # base_page.d.shell('logcat -d > /sdcard/logcat.log') # time.sleep(1) # base_page.d.pull('/sdcard/logcat.log', os.path.join(path.get_path(), 'logcat.log')) # base_page.d.pull('/sdcard/monkeyerr.txt', os.path.join(path.get_path(), 'monkeyerr.txt')) # base_page.d.pull('/sdcard/monkeyout.txt', os.path.join(path.get_path(), 'monkeyout.txt')) base_page.set_original_ime() base_page.identify() except AssertionError as e: log.e('AssertionError, %s', e)
def listener(self, event): tag = "VK - Message Listener" Log().info(tag, 'Обрабатываю сообщение...') from_id = event.obj.from_id peer_id = event.obj.peer_id msg_text = str(event.obj.text) msg_attach = event.obj.attachments msg_fwd = event.obj.fwd_messages Log().info(tag, 'Обработка завершена. ') if self.extractor.has_urls(msg_text) or msg_attach or msg_fwd: response_links = [] if self.extractor.has_urls(msg_text): links = self.extractor.find_urls(msg_text) Log().info(tag, 'Найдены объекты типа ссылка.') if len(links) > 1: for i in range(len(links)): response_links.append( self.get_cc_link(links[i], 0)['short_url']) else: response_links.append( self.get_cc_link(links, 0)['short_url']) if msg_attach: for i in range(len(msg_attach)): attach_type = msg_attach[i]['type'] if attach_type == 'link': ath_url = msg_attach[i][attach_type]['url'] response_links.append( str(self.get_cc_link(ath_url, 0)['short_url'])) if msg_fwd: for i_fwd in range(len(msg_fwd)): fwd_text = msg_fwd[i_fwd]['text'] fwd_attaches = msg_fwd[i_fwd]['attachments'] for i_ath in range(len(fwd_attaches)): fwd_ath_type = fwd_attaches[i_ath]['type'] if fwd_ath_type == 'link': fwd_ath_link = msg_fwd[i_fwd]['attachments'][ i_ath][fwd_ath_type]['url'] response_links.append( str( self.get_cc_link(fwd_ath_link, 0)['short_url'])) if self.extractor.find_urls(fwd_text): response_links.append( str(self.get_cc_link(fwd_text, 0)['short_url'])) response_links_wd = list(dict.fromkeys(response_links)) if len(response_links_wd) > 1: response_str = '🔗 Вот твои ссылки из сообщения:\n\n' for i_link in range(len(response_links_wd)): response_str += response_links_wd[i_link] + '\n' else: response_str = '🔗 Была найдена лишь одна ссылка в сообщении: ' + response_links_wd[ 0] self.send_message(peer_id, response_str) elif (from_id == 140830142) and \ (msg_text.__contains__('info') or msg_text.__contains__('инфо') or msg_text.__contains__('i')) or \ (msg_text.__contains__('ping') or msg_text.__contains__('пинг')): Log().info(tag, 'Инфо о боте.') self.send_message(peer_id, 'понг') self.send_message(peer_id, self.info.replace("%peer_id%", str(peer_id))) else: Log().info(tag, 'Неизвестная команда.') self.send_message(event.obj.peer_id, '🐸 Ссылок нет.')
#!/usr/bin/env python3 # Needed to set the sys.path to allow imports from sibling directories import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from WiiUProLib.WiiUPro import WiiUPro from Utils.Log import Log from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B, SpeedPercent, MoveTank log = Log() log.msg("starting") controller = WiiUPro() controller.Setup(log.msg) controller.Connect() controller.Start() m = LargeMotor(OUTPUT_A) def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. val: float or int src: tuple dst: tuple
class packet: def __init__(self, file_name, mtu_size, ssrc, dqID): read_video.file_name = file_name read_video.init_file(read_video.file_name) self.mtu_size = mtu_size self.seq_num = 1 self.ssrc = ssrc self.timestamp = 0 self.nals = [] self.left_nal = "" self.first_byte = 0 self.nal_num = 0 self.accessUnitID = 0 self.dqID = dqID self.packetLog = Log("packetLog.txt") self.packetNumber = 1 def end(self): read_video.close_file() def extractNalsBydqID(self, nals): res = [] for nal in nals: self.packetLog.LogStr('get one nal with dqID %d' % nal.nal_dqID) if nal.nal_dqID <= self.dqID: res.append(nal) return res def get_one_packet(self): self.packetLog.LogStr( '************* packet id %d **********************' % self.packetNumber) self.packetNumber += 1 consume_nal_num = 0 header = self.build_rtp_header() left_space = self.mtu_size - len(header) #deal with fu_a if len(self.left_nal) != 0: (consume_size, payload) = self.build_fu_a_payload(self.left_nal, left_space, 0) self.left_nal = self.left_nal[consume_size:] return header + payload #deal with new nal while len(self.nals) == 0: self.packetLog.LogStr('read one access unit access unit id ' + str(self.accessUnitID)) self.accessUnitID += 1 au = read_video.read_one_access_unit() if au == None: return None self.packetLog.LogStr('access unit id ' + str(self.accessUnitID) + ' nals number: ' + str(len(au.nals))) self.nals += self.extractNalsBydqID(au.nals) self.nal_num = len(self.nals) curr_nal = self.nals[0] if len(curr_nal.video_byte) > left_space: self.packetLog.LogStr('one large nal: nal size ' + str(len(curr_nal.video_byte))) self.left_nal = curr_nal.video_byte self.first_byte = struct.unpack('!B', self.left_nal[0:1])[0] (consume_size, payload) = self.build_fu_a_payload(self.left_nal, left_space, 1) self.left_nal = self.left_nal[consume_size:] consume_nal_num = 1 else: num = self.cal_stap_a_nal_num(self.nals, left_space) if num <= 1: payload = self.build_nor_payload(curr_nal) consume_nal_num = 1 else: consume_nal_num = num payload = self.build_stap_a_payload(self.nals[0:num]) self.nals = self.nals[consume_nal_num:] return header + payload def cal_stap_a_nal_num(self, au_left_nals, left_space): num = 0 left_space -= 1 next_id = 0 while left_space >= 0 and next_id < len(au_left_nals): left_space -= len(au_left_nals[next_id].video_byte) + 2 next_id += 1 num += 1 if left_space < 0: num -= 1 return num def build_stap_a_payload(self, nals): fb = 0 for i in range(len(nals)): fb |= struct.unpack('!B', nals[i].video_byte[0:1])[0] fb &= 255 - 31 fb |= 24 payload = "" payload += struct.pack("!B", fb) for i in range(len(nals)): self.packetLog.LogStr('stap_a one nal size:' + str(len(nals[i].video_byte))) payload += struct.pack("!H", len(nals[i].video_byte)) payload += nals[i].video_byte return payload def build_fu_a_payload(self, left_nal, left_space, start): self.packetLog.LogStr('fu_a start ' + str(start)) left_space -= 2 payload = '' fb = self.first_byte fb = fb & (255 - 31) fb = fb | 28 sb = start << 7 if len(left_nal) <= left_space: left_space = len(left_nal) sb |= 1 << 6 sb = sb | (self.first_byte & 31) self.packetLog.LogStr('fu_header ' + str(sb)) payload = struct.pack('!BB', fb, sb) payload += left_nal[0:left_space] self.packetLog.LogStr('fu_a consume size ' + str(left_space)) return (left_space, payload) def build_nor_payload(self, nal): self.packetLog.LogStr('nor consume size ' + str(len(nal.video_byte))) return nal.video_byte def build_rtp_header(self): fb = 0 v = 2 p = 0 x = 0 cc = 0 fb += cc + (x << 4) + (p << 5) + (v << 6) sb = 0 M = 0 pt = 0 sb += pt + (M << 7) header = "" self.packetLog.LogStr('seq num ' + str(self.seq_num)) header += struct.pack('!BBHII', fb, sb, self.seq_num, self.timestamp, self.ssrc) self.seq_num += 1 return header
def __init__(self, client, dqID): self.dqID = dqID self.fileName = "../Server/svc.file" self.pack = packet.packet(self.fileName, 400, 177, dqID) self.client = client self.serverLog = Log("serverLog.txt")
class Client(object): def __init__(self): self.dataChannel = None self.ctlChannel = None self.ctlChannel = ClientControl(2, self.freqAssignCB, self.freqReleaseACKCB) self.stateLock = threading.Lock() self.state = Idle self.log = Log('ClientLog.txt') pass def startDataChannel(self, dataWidth, dqID): self.log.LogStr("start data channel") if fake: self.dataChannel = ClientDataFake(dataWidth, dqID) else: self.dataChannel = ClientData(dataWidth, dqID) self.dataChannel.start() def endDataChannel(self): if self.dataChannel: self.log.LogStr("stop data channel") self.dataChannel.stop() self.dataChannel.deconstruction() del self.dataChannel self.dataChannel = None else: self.log.LogStr("endDataChannel but dataChannel is none") def freqAssignThreadCB(self, width): self.log.LogStr("freqAssignThread call callback width %d" % width) self.stateLock.acquire() self.log.LogStr("the state is %d" % (self.state)) if width == 1: dataWidth = 80 dqID = 16 elif width == 2: dataWidth = 64 dqID = 1 else: dataWidth = 48 dqID = 0 if self.state == GetFreq: self.endCtlChannel() self.startDataChannel(dataWidth, dqID) self.state = StartData self.stateLock.release() def freqReleaseACKCB(self, payload): print "receive freq release ack" self.stateLock.acquire() if self.state == FreqRelease: self.endCtlChannel() self.ctlChannel.finishFreqReq() self.state = Idle self.stateLock.release() def userInteractThreadCB(self): while True: command = raw_input("command:") if command == 'start': self.stateLock.acquire() if self.state == Idle: self.startCtlChannel() self.sendCtlChannelRequest() self.state = WaitAssign self.freqReqTimer = Timer(TimerDuration, self.freqReqTimeoutCB) self.freqReqTimer.start() self.stateLock.release() elif command == 'end': self.stateLock.acquire() if self.state == WaitAssign: self.ctlChannel.sendFreqRelease() elif self.state == GetFreq: self.ctlChannel.sendFreqRelease() elif self.state == StartData: self.endDataChannel() time.sleep(3) self.startCtlChannel() self.ctlChannel.sendFreqRelease() else: continue self.state = FreqRelease self.stateLock.release() self.freqReleaseTimer = Timer(TimerDuration, self.freqReleaseTimeoutCB) self.freqReleaseTimer.start() elif command == 'quit': self.stateLock.acquire() if self.state == Idle: self.ctlChannel = None break self.stateLock.release() break elif command == "help": print "start: start control channel and send request" print "end: end control channel and data channel" print "quit: end the client" print "help: show this message" def freqReqTimeoutCB(self): print "freq request timeout" self.stateLock.acquire() if self.state == WaitAssign: self.sendCtlChannelRequest() self.freqReqTimer = Timer(TimerDuration, self.freqReqTimeoutCB) self.freqReqTimer.start() self.stateLock.release() def freqReleaseTimeoutCB(self): print "freq release timeout" self.stateLock.acquire() if self.state == FreqRelease: self.ctlChannel.sendFreqRelease() self.freqReleaseTimer = Timer(TimerDuration, self.freqReleaseTimeoutCB) self.freqReleaseTimer.start() self.stateLock.release() def freqAssignCB(self, width): #1 is big 2 is small self.stateLock.acquire() if self.state == WaitAssign: self.freqAssignThread = threading.Thread( target=self.freqAssignThreadCB, args=[width]) self.freqAssignThread.start() self.state = GetFreq self.stateLock.release() def startCtlChannel(self): print "start ctl channel" self.ctlChannel.construct() self.ctlChannel.start() def sendCtlChannelRequest(self): if self.ctlChannel: print "send control channel request" self.ctlChannel.sendFreqReq() def endCtlChannel(self): print "end ctl channel" self.ctlChannel.stop() self.ctlChannel.deconstruct() def endAll(self): if self.ctlChannel: self.endCtlChannel() self.ctlChannel = None if self.dataChannel: self.endDataChannel() def reqTimeoutCB(self): self.timeoutNumber += 1 if self.state != 1: return if self.timeoutNumber > 10: self.state = 3 else: self.state = 0 self.dealWithStateMachine()
def main(): Log().debug(tag, 'Корректный запуск.') VK().long_poll()
import argparse import unittest import os import glob import uiautomator2 as u2 from monkey.Drivers_monkey import DriversMonkey from case.case import myCase from Utils.Drivers import Drivers from Utils.ftpUtils import ftp_downloadFile, http_downloadFile from Utils.commonUtils import get_apk_info from case.ParametrizedTestCase import ParametrizedTestCase from Utils.Log import Log if __name__ == '__main__': logger = Log() # ap = argparse.ArgumentParser() # ap.add_argument("-d", "--devices", required=False, help="devices") # ap.add_argument("-c","--command",required=False, help="command") # ap.add_argument("-f","--ftp",required=True, help="ftp") # args = vars(ap.parse_args()) # tempDevices = args['devices'] # command = args['command'] # ftpPath = args['ftp'] # ftpPath = '//AGL Video/' devices = [] ftpPath = os.environ["ftp_path"] command = os.environ["command"] requestType = os.environ["requesttype"]