def stop(self): if self.ardui_dash is not None: self.ardui_dash.stop() self.clear_ui() if self.m_connected: Debug.notice('Closing UDP socket') self.m_parser.close_socket()
def exit_gracefully(self, signum, frame): try: Debug.warn('Process killed (%s). Exiting gracefully' % signum) self.finish() sys.exit(0) except Exception as e: Debug.warn(e)
def func4(severity): try: lst = [] print lst['name'] except: data = {'list': lst} Debug.log(project='Test', sub_system='sub', severity=severity, data=data)
def func2(severity): try: dic = {} print dic['name'] except: data = {'dic': dic} Debug.log(project='Test', sub_system='sub', severity=severity, data=data)
def start(self): if self.m_connected: return if self.arduino_auto_start is True: self.ardui_dash.start(self.arduino_com_port, self.arduino_baud_rate) Debug.notice('Start UDP socket') self.m_parser.open_socket()
def func1(severity): try: a = 12 b = 0 print a / b except: data = {'a': a, 'b': b} Debug.log(project='Test', sub_system='sub', severity=severity, data=data)
def game_changed(self, action): game = action.data() if game: Debug.notice('Game changed: %s' % game['name']) self.m_game = game if self.m_connected: self.stop() self.m_parser.game = game self.clear_ui()
def fill_games_menu(self): games_menu = self.m_window.menu_settings.addMenu('&Game') games_group = QtWidgets.QActionGroup(games_menu) for game in Games(): act = QtWidgets.QAction(game['name'], games_group) act.setCheckable(True) act.setData(game) games_menu.addAction(act) if game == self.m_game: Debug.notice('Current game: %s' % self.m_game['name']) act.setChecked(True) games_group.triggered.connect(self.game_changed) games_group.setExclusive(True)
def __init__(self, game=Games.DIRT_RALLY, udp_host=UDP_IP, udp_port=UDP_PORT, callback=None): Thread.__init__(self) Debug.set_log_level(LogLevel(2)) Debug.toggle(True) self.finished = False self.callback = callback self.game = game self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.settimeout(1) self.sock.bind((udp_host, udp_port)) signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) signal.signal(signal.SIGABRT, self.exit_gracefully)
def run(self): try: index = 1 value = None last_update = datetime.now() found = False Debug.head("Car Scanner") Debug.log('ID | Idle RPM | Max RPM | Max Gears') if self.callback is not None: self.callback("Car Scanner") self.callback('ID | Idle RPM | Max RPM | Max Gears') while not self.finished: if last_update is not None: delta = datetime.now() - last_update if delta.seconds >= 30: Debug.notice('New track') found = False last_update = datetime.now() try: data, address = self.sock.recvfrom(512) except socket.timeout: continue except socket.error: break if not data: continue if found: continue stats = struct.unpack('66f', data[0:264]) new_value = "%.14f;%.14f;%d" % \ (stats[Telemetry.IDLE_RPM], stats[Telemetry.MAX_RPM], int(stats[Telemetry.MAX_GEARS])) if new_value != value: value = new_value Debug.log(value, '%d' % index) if self.callback is not None: self.callback('%d;%s' % (index, value)) index += 1 found = True except Exception as e: Debug.warn(e)
def post(self, *args, **kwargs): try: dict = json.loads(self.get_argument('dict', 'empty')) # print(dict) # print('OK SIR') # print(dict) # print(dict['person']) obj = Domain() obj.name = dict['domain'] # obj.name = 'domain.ir' obj.last_updated = dict['last_updated'][14:] obj.expire_date = dict['expire_date'][13:] obj.person = dict['person'][9:] obj.email = dict['email'][9:] obj.address = dict['address'][9:] obj.phone = dict['phone'][8:] obj.fax = dict['fax'][9:] # Debug.cprint(text='All set' , color=Debug.BLUE) Debug.log(name='add_domain', data='All Set') #TODO Check for existing domain, If necessary update it obj.save() except Exception, e: Debug.log(name='add_domain', data='Error:' + e.message)
def update_connection_status(self, status): self.m_connected = status self.m_window.centralWidget().setEnabled(self.m_connected) self.m_window.speed_view.setEnabled(self.m_connected) self.m_window.gear_view.setEnabled(self.m_connected) if self.m_connected: Debug.notice("Socket opened") self.m_window.menu_action_connect.setText("Dis&connect") self.m_window.action_Connect.setIconText("Dis&connect") self.m_window.action_Connect.setToolTip("Disconnect") self.m_window.action_Connect.setIcon( QtGui.QIcon.fromTheme("offline")) self.m_window.statusbar\ .showMessage("Listening for data on %s:%d " % (self.m_parser.UDP_IP, self.m_parser.UDP_PORT)) self.ardui_dash.setup(2) self.ardui_dash.change_mode(1) else: Debug.notice("Socket closed") self.m_window.menu_action_connect.setText("&Connect") self.m_window.action_Connect.setIconText("&Connect") self.m_window.action_Connect.setToolTip("Connect") self.m_window.action_Connect.setIcon( QtGui.QIcon.fromTheme("online")) self.m_window.statusbar.clearMessage()
def main(game=Games.DIRT_RALLY, udp_host=UDP_IP, udp_port=UDP_PORT, callback=None): Debug.set_log_level(LogLevel(2)) Debug.toggle(True) try: scan = Scan(game, udp_host, udp_port, callback) scan.start() return scan except Exception as e: Debug.err(e)
def main(args): # Load configuration file and check configPath = args.configPaths[args.currentConfigIdx] configuration = Configuration(configPath) configuration.check_all() # Init a model from the configuration. model = Model(configuration) #initial population organism = Organism(args, model.task_list, args.numChrom, shuffleTaskPriority=True, elitePercent=args.ESCperc[0], selectionPercent=args.ESCperc[1], crossOverPercent=args.ESCperc[2], mutationRate=args.mutRate) #Run genetic algorithm for gen in range(args.numGen): organism.checkValid() logger.log(15, "\n---------------\n" + \ f"Running generation {gen+1}..") runStartTime = time.time() for chromosome in organism.chromList: #set chromosome for model to use model = Model(configuration) model.scheduler.initializeChromosome(chromosome) # Execute the simulation. logger.log( 3, Debug.getTaskListStr(chromosome.taskNameToPriority, name='Chromosome Task Priorities')) model.run_model() chromosome.fitness.updateAllFitnessMetrics(model) del model runEndTime = time.time() logger.log( 15, f"..Gen {gen+1} running complete. (Time: {runEndTime-runStartTime:.2f} secs).\n" ) ## After all chromosomes in organism has run... # Record statistics via logging and internally bestChromList = organism.getSortedChromList() totFS, totMig, totPre, totNL, totEC, totChrom = 0.0, 0.0, 0.0, 0.0, 0.0, args.numChrom for rank, chrom in enumerate(bestChromList): chrom.addRank(rank) if rank < PRINTTOP: logger.log(15, f"Rank {rank+1} - Fitness: {chrom.fitness.getFitnessScore()}," \ f" Migrations: {chrom.fitness.getMigrations()}," \ f" Preemptions: {chrom.fitness.getPreemptions()}," \ f" NL: {chrom.fitness.getNormalizedLaxity():.4f}," \ f" Exceeded Count: {chrom.fitness.getExceededCount()}") totFS += chrom.fitness.getFitnessScore() totMig += chrom.fitness.getMigrations() totPre += chrom.fitness.getPreemptions() totNL += chrom.fitness.getNormalizedLaxity() totEC += chrom.fitness.getExceededCount() logger.log(15, f"AVERAGE - Fitness: {totFS/totChrom}," \ f" Migrations: {totMig/totChrom:.1f}," \ f" Preemptions: {totPre/totChrom:.1f}," \ f" NL: {totNL/totChrom:.4f}," \ f" Exceeded Count: {totEC/totChrom:.1f}") organism.avgFitnessDict['FitnessScore'].append(totFS / totChrom) organism.avgFitnessDict['Migrations'].append(totMig / totChrom) organism.avgFitnessDict['Preemptions'].append(totPre / totChrom) organism.avgFitnessDict['NormalizedLaxity'].append(totNL / totChrom) organism.avgFitnessDict['ExceededCount'].append(totEC / totChrom) #Perform the selection, crossover, and mutation organism.checkValid() organism.goNextGen(bestChromList=bestChromList) logger.log( 15, f"\n(Organism & Chromosome overhead: {time.time()-runEndTime:.2f} secs)" ) Results.outputStatsForRun(organism, args)
def run(self): try: if self.game['db_file'] is None: return app_root = os.path.dirname(os.path.realpath(__file__)) data_path = '/../data/' if getattr(sys, 'frozen', False): data_path = '/data/' conn = sqlite3.connect(app_root + data_path + self.game['db_file']) db = conn.cursor() index = 1 value = None last_update = datetime.now() found = False Debug.head("Track Scanner") Debug.log('ID | Name | Track Length | Z POS | Laps') if self.callback is not None: self.callback("Track Scanner") self.callback('ID | Name | Track Length | Z POS | Laps') while not self.finished: if last_update is not None: delta = datetime.now() - last_update if delta.seconds >= 10: found = False last_update = datetime.now() try: data, address = self.sock.recvfrom(512) except socket.timeout: continue except socket.error: break if not data: print('no data') continue if found: print('found') continue stats = struct.unpack('66f', data[0:264]) new_value = "%.14f;%d;%d" % \ ( stats[Telemetry.TRACK_LENGTH], int(stats[Telemetry.Z_POSITION]), int(stats[Telemetry.TOTAL_LAPS]) ) if new_value != value: value = new_value index += 1 db.execute( 'SELECT id,name FROM Tracks WHERE length = ? AND (start_z = "" OR round(start_z) = ?)', (stats[Telemetry.TRACK_LENGTH], stats[Telemetry.Z_POSITION])) res = db.fetchall() track_name = 'unknown' track_index = -1 if len(res) >= 1: for (index, name) in res: track_index = index track_name = name break Debug.log('%d;%s;%s' % (track_index, track_name, value)) if self.callback is not None: self.callback('%d;%s;%s' % (track_index, track_name, value)) found = True Debug.notice('Scan loop ended') if db is not None: db.close() if conn is not None: conn.close() except sqlite3.Error as e: Debug.err("Database connection error") Debug.err(e) except Exception as e: Debug.warn(e)
dest='gui', action='store_false', help='Console mode') argument_parser.set_defaults(gui=True) argument_parser.add_argument( '--log_level', '-V', type=int, default=LogLevel.warn, help='Set debug verbosity from 0 (only errors) to 2 (full output)', choices=range(0, 3)) flags = argument_parser.parse_args() if flags.debug: DEBUG = True if flags.log_level is not None: Debug.set_log_level(LogLevel(flags.log_level)) if flags.gui is not None: if flags.gui is False: Debug.notice('No gui') DEBUG = True Debug.set_log_level(LogLevel(2)) GUI = flags.gui Debug.toggle(DEBUG) # noinspection PyUnusedLocal def exit_gracefully(signum, frame): Debug.warn('Process killed (%s). Exiting gracefully' % signum) app.stop() sys.exit(0)
def finish(self): self.finished = True Debug.notice('Stopping track scanner') if self.sock is not None: self.sock.close()
def on_close(self): Debug.notice('Main window closed') self.stop()
redis_username = '' redis_password = '' elif redis_server == 'customs_remote': #TODO: not set redis_host = '82.115.26.202' redis_port = 6379 redis_username = '' redis_password = '******' elif redis_server == 'office': redis_host = '192.168.1.173' redis_port = 6379 redis_password = '******' # elif redis_server == 'customs_remote_lan': # redis_host = '192.1.8.13' # redis_port = 6379 # redis_username = '' # redis_password = '' # Debug.dprint(text='Redis port') # Debug.dprint(text=redis_port, type='data') Debug.dprint(text='Mongo host') Debug.dprint(text=mongo_host, type='data') Debug.dprint(text='Redis host') Debug.dprint(text=redis_host, type='data') redis_instance = redis.StrictRedis(host=redis_host, port=redis_port, db=0) # redis_instance = redis.StrictRedis(host=redis_host, port=redis_port, db=0, password=redis_password) # redisInstance = redis.StrictRedis(host=redis_host, port=redis_port, db=0, password=redis_password) # client = MongoClient('127.0.0.1', 27017) client = MongoClient('192.1.8.14', 27017) db = client.Customs
def add(cls, id='', s_date='', m_date='', file_no='', kootaj='', cert_no='', s_date_1='', s_date_2='', policy_1=False, policy_2=False, policy_3=False, policy_4=False, policy_5=False, policy_6=False, policy_7=False, ezharname=0, person_type=False, full_name='', card_no='', code_no='', company='', ez_full_name='', ez_owner='', ez_agent='', ez_card_no='', ez_code_no='', tr_full_name='', tr_code_no='', tr_reg_no='', tr_nationality='', tr_manager='', tr_type=False, item_name='', tariff_no='', paid=0, different=0, fine=0, diff_paid=0, vi_type_1=False, vi_type_2=False, vi_type_3=False, vi_type_4=False, vi_type_5=False, vi_type_6=False, vi_type_7=False, vi_type_other='', stated_tariff=0, stated_value=0, stated_weight=0, deducted_tariff=0, deducted_value=0, deducted_weight=0, law='', detector=0, detector_other='', results='', commitment=False, receip_no='', details='', locked=False): #TODO Something for this vi_type_1 = True if vi_type_1 == 'on' else False vi_type_2 = True if vi_type_2 == 'on' else False vi_type_3 = True if vi_type_3 == 'on' else False vi_type_4 = True if vi_type_4 == 'on' else False vi_type_5 = True if vi_type_5 == 'on' else False vi_type_6 = True if vi_type_6 == 'on' else False vi_type_7 = True if vi_type_7 == 'on' else False policy_1 = True if policy_1 == 'on' else False policy_2 = True if policy_2 == 'on' else False policy_3 = True if policy_3 == 'on' else False policy_4 = True if policy_4 == 'on' else False policy_5 = True if policy_5 == 'on' else False policy_6 = True if policy_6 == 'on' else False policy_7 = True if policy_7 == 'on' else False print('stated_weight: ' + str(stated_weight)) print('deducted_weight: ' + str(deducted_weight)) if id != '': obj = Model.objects(Kootaj=id).first() else: obj = Model() if obj != None: vi_type_1 = True obj.s_date = s_date #TODO it should use s_date obj.m_date = datetime.now() obj.file_no = file_no obj.kootaj = kootaj obj.cert_no = cert_no obj.s_date_1 = s_date_1 obj.s_date_2 = s_date_2 obj.policy_1 = policy_1 obj.policy_2 = policy_2 obj.policy_3 = policy_3 obj.policy_4 = policy_4 obj.policy_5 = policy_5 obj.policy_6 = policy_6 obj.policy_7 = policy_7 obj.ezharname = ezharname obj.person_type = person_type obj.full_name = full_name obj.card_no = card_no obj.code_no = code_no obj.company = company obj.ez_full_name = ez_full_name obj.ez_owner = ez_owner obj.ez_agent = ez_agent obj.ez_card_no = ez_card_no obj.ez_code_no = ez_code_no obj.tr_full_name = tr_full_name obj.tr_code_no = tr_code_no obj.tr_reg_no = tr_reg_no obj.tr_nationality = tr_nationality obj.tr_manager = tr_manager obj.tr_type = tr_type obj.item_name = item_name obj.tariff_no = tariff_no obj.paid = paid obj.different = different obj.fine = fine obj.diff_paid = diff_paid obj.vi_type_1 = vi_type_1 obj.vi_type_2 = vi_type_2 obj.vi_type_3 = vi_type_3 obj.vi_type_4 = vi_type_4 obj.vi_type_5 = vi_type_5 obj.vi_type_6 = vi_type_6 obj.vi_type_7 = vi_type_7 obj.vi_type_other = vi_type_other obj.stated_tariff = stated_tariff obj.stated_value = stated_value obj.stated_weight = stated_weight obj.deducted_tariff = deducted_tariff obj.deducted_value = deducted_value obj.deducted_weight = deducted_weight obj.law = law obj.detector = detector obj.detector_other = detector_other obj.results = results obj.commitment = commitment obj.receip_no = receip_no obj.details = details obj.m_rec_date = datetime.now() #TODO: Hard Code! convert not to shanmsi obj.s_rec_date = '1393-05-17' obj.locked = locked Debug.dprint(vi_type_1) obj.save() print('Controller.add inside is executed')
# a = Personnel() # a.name = 'ehsan' # a.create() # from controllers.violation import Violation as Controller # print Controller.find() # print Controller.find() # from connections import db import json from pymongo import MongoClient from tools.debug import Debug client = MongoClient('192.1.8.14', 27017) db = client.Customs collection = db.violation records = list(collection.find()) # records = list(collection.find()) # records = json.dumps(list(collection.find())) # records = collection.find().count() # for item in records: # Debug.dprint(item['full_name']) # from controllers.violation import Violation as Controller from models.violation import Violation as Model Debug.dprint(text=list(Model.objects()), type='custom') # Debug.dprint(text=list(Model.objects(__raw__={'file_no': '123456'})), type='custom') # Debug.dprint(text=str(Controller.find(_filter=filter)), type='custom') # f = {'file_no': '123456'} # Debug.dprint(text=str(f), type='error') # Debug.dprint(text=str(Controller.find(_filter=f)), type='msg')
def exit_gracefully(signum, frame): Debug.warn('Process killed (%s). Exiting gracefully' % signum) app.stop() sys.exit(0)