示例#1
0
 def on_uiready(self, ui):
   self.ui = ui
   # Restore window size
   width = Settings.get('MainWindowWidth')
   height = Settings.get('MainWindowHeight')
   self.logger('Load window size (%dx%d)' % (width, height))
   self.ui.winMain.set_default_size(width, height)
示例#2
0
 def on_uiready(self, ui):
     self.ui = ui
     # Restore window size
     left = Settings.get("MainWindowLeft")
     top = Settings.get("MainWindowTop")
     self.logger("Load window position (%d,%d)" % (left, top))
     self.ui.set_position("%dx%d" % (left, top))
    def write_to_file_item(self, res):
        """
        Function makes proper string from information got from item xml tags
        and poe.trade information and writes it to a file
        :param res: item_container_html
        :return: returns nothing
        """
        parsed_item_container_dict = self.poe_trade_response_handler.item_container_parser(res)
        if parsed_item_container_dict:
            string_for_file_writing = self.get_string_for_file_writing()
            string_for_file_writing += ">>>> From Poe.trade <<<<\n"
            for item_container_tag in sorted(parsed_item_container_dict):
                value = parsed_item_container_dict[item_container_tag]
                string_for_file_writing += "{item_cont}: {value}\n".format(
                    item_cont=item_container_tag, value=value)

            # Check if file exists
            if os.path.isfile(Settings.items_file_name_if_found()):
                # Check if already exists in file
                already_exists = string_for_file_writing in open(Settings.items_file_name_if_found()).read()
                if not already_exists:
                    self.write_to_file_string(string_for_file_writing)
            # File not exists. Can write
            else:
                self.write_to_file_string(string_for_file_writing)
示例#4
0
def generate_xml():
	tree = ET.parse(Settings.local_base_xml_filename())
	root = tree.getroot()
	channel = root.find('channel')

	# Alter the title of this podcast to append ' (Cached)'
	title = channel.find('title')
	title.text += ' (Cached)'

	# Remove any existing items from the channel tag in the base XML file
	items = channel.findall("item")
	for item in items:
		channel.remove(item)

	# Now... add every episode we've got
	for number in range(1, Settings.get_highest_episode()+1):
		print "Processing " + str(number)
		try:
			channel.append(process_episode(number))
		except Exception as e:
			print "Something bad happened while processing episode " + str(number)
			print "{0}".format(e)
			print "{0}".format(sys.exc_info()[0])
			print "{0}".format(sys.exc_info()[1])
			traceback.print_tb(sys.exc_info()[2])
	
	#output = prettify(root).encode('utf-8')
	#output = prettify(channel).encode('utf-8')
	
	#with open(LOCAL_RSS_FILE, "w") as f:
	#	f.write(output)
	tree.write(Settings.local_xml_filename())
	print "You can download the mirrored podcast from:"
	print "   " + Settings.local_xml_url()
示例#5
0
 def __find_remote_desklets(self):
     self.notify_observers("FETCH", "Fetching remote desklets")
     self.remote_desklets = {}
     for (base_url, d_list, d_path, c_list, c_path) in Settings.get_setting('repositories'):
         rds = remote.get_desklets(base_url, d_list, 
                                   Settings.get_setting('cache_dir'))
         self.remote_desklets.update(rds)
         
         for d_key in rds:
             d_data = rds[d_key]
             d = Desklet(d_data['name'], d_data['description'], d_data['category'], d_data['authors'])
             d.remote_domain = base_url
             d.set_available_remotely(True)
             d.preview = d_data['preview']
             d.add_observer(self.update)
             for version_number in d_data['versions']:
                 version_object = d_data['versions'][version_number]
                 # make dependencies point to control objects
                 for dep in d_data['versions'][version_number]['dependencies']:
                     dep_object = version_object['dependencies'][dep]
                     control_object = self.get_control( dep_object['name'] )
                     d_data['versions'][version_number]['dependencies'][dep]['object'] = control_object
                     # logging.info( "added to %s dependency %s" % (d.name, control_object.name) )
                 d.add_version(version_number, d_data['versions'][version_number])
                 
             #for ver in d_data['versions']:
              #   d.add_version(ver)
             self.add_desklet(d)
示例#6
0
 def on_uiready(self, ui):
   self.ui = ui
   # Restore window size
   left = Settings.get('MainWindowLeft')
   top = Settings.get('MainWindowTop')
   self.logger('Load window position (%d,%d)' % (left, top))
   self.ui.set_position('%dx%d' % (left, top))
示例#7
0
def createListItem(title,banner,description,duration,date,channel,videourl,playable,folder, backdrop,pluginhandle,subtitles=None,blacklist=False):
    if description == '':
        description = Settings.localizedString(30008).encode("utf-8")
    liz=xbmcgui.ListItem(title, iconImage=banner, thumbnailImage=banner)
    liz.setInfo( type="Video", infoLabels={ "Title": title } )
    liz.setInfo( type="Video", infoLabels={ "Tvshowtitle": title } )
    liz.setInfo( type="Video", infoLabels={ "Sorttitle": title } )
    liz.setInfo( type="Video", infoLabels={ "Plot": description } )
    liz.setInfo( type="Video", infoLabels={ "Plotoutline": description } )
    liz.setInfo( type="Video", infoLabels={ "Aired": date } )
    liz.setInfo( type="Video", infoLabels={ "Studio": channel } )
    liz.setProperty('fanart_image',backdrop)
    liz.setProperty('IsPlayable', str(playable))
        
    if not folder:
        videoStreamInfo = {'codec': 'h264', 'aspect': 1.78}
        try:
            videoStreamInfo.update({'duration': int(duration)})
        except:
            pass
        if videourl.lower().endswith('_q8c.mp4') or '_q8c' in videourl.lower():
            videoStreamInfo.update({'width': 1280, 'height': 720})
        elif videourl.lower().endswith('_q6a.mp4') or '_q6a' in videourl.lower():
            videoStreamInfo.update({'width': 960, 'height': 540})
        elif videourl.lower().endswith('_q4a.mp4') or '_q4a' in videourl.lower():
            videoStreamInfo.update({'width': 640, 'height': 360})
        else:
            videoStreamInfo.update({'width': 320, 'height': 180})
        liz.addStreamInfo('video', videoStreamInfo)

        liz.addStreamInfo('audio', {"codec": "aac", "language": "de", "channels": 2})
        if subtitles != None and Settings.subtitles():
            if len(subtitles) > 0 and subtitles[0].endswith('.srt'):
                subtitles.pop(0)
            liz.addStreamInfo('subtitle', {"language": "de"})
            liz.setSubtitles(subtitles)   
    
    if blacklist:
        match = re.search(r'( - \w\w, \d\d.\d\d.\d\d\d\d)',title)
        if match != None:
            bltitle = title.split(" - ")
            bltitle = bltitle[0].split(": ")
            
            bl_title = bltitle[0].replace("+"," ").strip()
        else:
            bl_title = title.replace("+"," ").strip()
        
        
        blparameters = {"mode" : "blacklistShow", "title": bl_title}
        blurl = sys.argv[0] + '?' + urllib.urlencode(blparameters)
        commands = []
        commands.append(('%s %s %s' % (Settings.localizedString(30038).encode("utf-8"), bl_title, Settings.localizedString(30042).encode("utf-8")), 'XBMC.RunPlugin(%s)' % blurl))
        liz.addContextMenuItems( commands )
        if not checkBlacklist(bl_title):
            xbmcplugin.addDirectoryItem(pluginhandle, url=videourl, listitem=liz, isFolder=folder)
            return liz
    else:
        xbmcplugin.addDirectoryItem(pluginhandle, url=videourl, listitem=liz, isFolder=folder)
        return liz
示例#8
0
def main():
    # pygame initialization
    pygame.init()
    pygame.mixer.music.load('sounds/menu.mp3')
    pygame.mixer.music.play(-1)

    pygame.display.set_caption('PyFighters')
    pygame.mouse.set_visible(1)
    clock = pygame.time.Clock()
    
    
    
    
    # code for our menu 
    ourMenu = ("Play Online",
               "How to play",
               "Statistics",
               "Exit")
    myMenu = Menu(ourMenu)
    myMenu.drawMenu()
    pygame.display.flip()
    # main loop for event handling and drawing
    while 1:
        clock.tick(60)

    # Handle Input Events
        for event in pygame.event.get():
            myMenu.handleEvent(event)
            # quit the game if escape is pressed
            if event.type == QUIT:
                sys.exit(0)
            elif event.type == Menu.MENUCLICKEDEVENT:    
                if event.text == "Play Online":
                    time.sleep(1)
                    character = CharSelect.charselect()
                    print "Just Waiting..."
                    InitScript.main(socketInit(), character)
                elif event.text == "How to play":
                    Settings.settings()
                elif event.text == "Local Play":
                    Script.main()
                elif event.text == "Exit":
                    sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                myMenu.activate()
                sys.exit(0)

                
        if myMenu.isActive():
            myMenu.drawMenu()
               
        
        pygame.display.flip()
示例#9
0
 def on_uiready(self, ui):
   # Play welcome message if PlayWelcomeText is set
   if Settings.get('PlayWelcomeText'):
     if Settings.get('UseCustomWelcome'):
       # Play customized welcome message
       message = Settings.get('WelcomeText')
     else:
       # Play default welcome message
       message = Settings.default('WelcomeText')
     self.logger('Play welcome message: %s' % message)
     ui.proxy['text.set'](message, 0)
     ui.proxy['espeak.play'](None, None)
示例#10
0
    def __init__(self, library):
        Source.__init__(self, library, SourceType.LOCAL)
        self.watched = []
        self.watched_file = Settings.pathman["profile"] + "_watched"
        Settings.add_path_file("watched", self.watched_file)

        print "Watched file:", self.watched_file

        if os.stat(self.watched_file).st_size > 0:
            filer = open(self.watched_file, 'r')
            self.watched = pickle.load(filer)
            filer.close()
示例#11
0
文件: main.py 项目: Neopibox/MDD
def changeKey(keyName):        
        while not isData():     # Tant qu'il n'y a pas d'autres touche de rentrée
                Menu.setButtonSelected(menu, "state", True)
                Menu.showButtons(menu)
                
        Menu.setButtonSelected(menu, "state", False)
        read = sys.stdin.read(1)  
        canChange = True
        for key in settings:
                if read == settings[key] or read == 'p':
                        canChange = False
        if canChange:
                Settings.setKey(settings,keyName,read)
                Menu.setButtonName(menu, read)
        Menu.showButtons(menu)
示例#12
0
	def __init__(self):
		self.initScreen()
		
		self.clock = pygame.time.Clock()

		pygame.font.init()

		self.font = os.path.join("resources","LiberationSans-Bold.ttf")

		self.text = pygame.font.Font(self.font, 16)
		self.text2 = pygame.font.Font(self.font, 42)
		self.text3 = pygame.font.Font(self.font, 32)
		self.text4 = pygame.font.Font(self.font, 12)

		self.messageBox = Messages.MessageBox()
		self.infoOverlay = Messages.InfoOverlay()

		if Settings.settings["Sound"]["enabled"]:
			self.sound = Sound.Sound(self)
		
		self.inGame = False
		
		self.mapSettings = Settings.getMapMetadata(Settings.settings["Rules"]["map"])

		self.mainMenu = Menus.MainMenu(self)
示例#13
0
文件: test.py 项目: armsky/QuantHoops
def main(argv):
    gender = ''
    process = ''
    season = ''
    try:
        opts, args = getopt.getopt(argv, "g:p:s:", ["gender", "process=", "season="])
    except getopt.GetoptError:
        print 'test.py -g <gender> -p <process> -s <season>'
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-g", "--gender"):
            gender = arg
            if gender != "men" and gender != "women":
                print "Gender wrong, please only use 'Men' or 'Women'."
                sys.exit()
        elif opt in ("-p", "--process"):
            process = arg
        elif opt in ("-s", "--season"):
            season = arg

    engine = Settings.create_engine(gender)

    if process == "team_stat" or process == "check_team_stat":
        check_team_stat(engine, season)
    elif process == "player_stat" or process == "check_player_stat":
        check_player_stat(engine, season)
    else:
        print "Process name not exists... Quit"
        sys.exit()
示例#14
0
文件: Damas.py 项目: mbaez/pydamas
	def __init__(self):
		self.width, self.height=600, 700
		pygame.init()
		self.screen = pygame.display.set_mode((self.width, self.height))
		#se cargan las imagenes de las fichas
		self.ficha_negra=self.cargar_imagen("img/ficha_negra.png")
		self.ficha_blanca=self.cargar_imagen("img/ficha_blanca.png")
		self.ficha_dama_negra=self.cargar_imagen("img/dama_negra.png")
		self.ficha_dama_blanca=self.cargar_imagen("img/dama_blanca.png")
		#Se cargan las imagenes de las celdas
		self.celda_negra=self.cargar_imagen("img/celda_negra.png")
		self.celda_blanca=self.cargar_imagen("img/celda_blanca.png")
		self.celda_selecionada= self.cargar_imagen("img/ficha_seleccionada.png")
		#se cargan las imagenes de los botones
		self.cancel_button= self.cargar_imagen("img/cancel.png")
		self.ok_button=self.cargar_imagen("img/aceptar.png")
		self.button_clicked=self.cargar_imagen("img/clicked.png")

		self.new_game_button=self.cargar_imagen("img/new_game.png")
		self.settings_button=self.cargar_imagen("img/settings.png")
		#carga la imagen de fondo
		self.fondo=self.cargar_imagen("img/fondo.png")
		self.toolbar=self.cargar_imagen("img/fondo_toolbar.png")
		pygame.display.set_caption("Damas")

		'''
		se instancia la interfaz de comunicacion con la inteligencia artificial
		'''
		self.game=Game()
		self.settings=Settings(self.screen,self.fondo,self.width,self.height)
		self.settings.set_ia_game(self.game)
		self.settings.set_gui_fuctions(self.cargar_imagen, self.dibujar_imagen,self.print_text)
示例#15
0
    def __init__(self, parent):
        print '[+] Building GUI environment...'
        # Inherit from Tkinter's parent class
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.settings = Settings()
        self.comm = Communicator()
        # helper class for creating widgets
        # send self as desired frame to store widgets into
        self.widgets = Widgets(frame=self)
        # Create the GUI application
        # Initialize label references
        self.TitleLabel = Tkinter.StringVar()
        self.FileLabel = Tkinter.StringVar()
        # Initialize text entry references
        self.apiEntry = None
        # Initialize button references
        self.fileBtn = None
        self.sfBtn = None
        self.rfBtn = None
        self.rptBtn = None
        self.gearBtn = None
        # Initialize icon references
        self.gear_raised = None
        self.gear_sunken = None

        self.initializeGUI(self.settings)
示例#16
0
def getGroupWide(folder='../test/patents/US_out/full/'):
    """Return a set of terms used across an entire set of files."""
    parser = NPParser.NPParser()
    filters = Settings.getDocumentFilters()
    if 'stops' in filters:
        filters.remove('stops')
    termlist = []
    filenames = [f for f in os.listdir(folder) if f[-4:]=='.txt']
    filtfname = os.path.join(folder, 'filter.save')
    if os.path.exists(filtfname):
            Filter._get_stemdict(filtfname)
    for f in filenames:
        nps = parser.getTerms(os.path.join(folder,f), filters)
        termlist.append(nps)
#    if not os.path.exists(filtfname):
#        Filter._save_stemdict(filtfname)
    all_terms = set()
    for termset in termlist:
        all_terms.update(termset)
    retlist = set()
    for term in all_terms:
        count = 0
        for termset in termlist:
            if term in termset:
                count += 1
        if count > len(filenames)*0.2:
            if 'stem' in filters:
                retlist.update(Filter.unstem(term))
            else:
                retlist.add(term)
    return retlist
示例#17
0
 def __init__(self, name, description, category, authors):
     super(Desklet, self).__init__(name, description, authors)
     self._install_parent_dir = Settings.get_setting('display_install_dir')
     self.__preview = None
     self.__category = category
     self.__is_active = False
     self.__displays = {}
示例#18
0
 def on_btnRefresh_clicked(self, widget, data=None):
   "Reload mbrola languages from the selected folder"
   self.modelMbrola.clear()
   selectedFolder = self.chooserLanguagePath.get_filename()
   if not selectedFolder:
     # Calling before the dialog is shown results in None path
     selectedFolder = Settings.get('VoicesmbPath')
   mbrolaVoices = self.espeak.loadMbrolaVoices(selectedFolder)
   voicesFound = 0
   for voice in mbrolaVoices:
     if voice[2]:
       voicesFound += 1
     self.modelMbrola.append((
       widget.render_icon(voice[2] and gtk.STOCK_YES or gtk.STOCK_NO, 
       gtk.ICON_SIZE_BUTTON), voice[0], voice[1],
       voice[2] and _('Installed') or _('Not installed')))
   # lblLanguagesDetected
   self.lblLanguagesDetected.set_text(_("%d languages of %d detected") % (
     voicesFound, len(mbrolaVoices)))
   # Check if mbrola exists
   status = self.espeak.mbrolaExists(Settings.cmdMbrola)
   self.imgExecutableMbrola.set_from_stock(size=gtk.ICON_SIZE_BUTTON,
     stock_id=status and gtk.STOCK_YES or gtk.STOCK_NO)
   self.lblExecutableMbrolaStatus.set_label('<b>%s</b>' % (status and 
     _('Package mbrola installed') or _('Package mbrola not installed')))
示例#19
0
def get_poe_trade_main_lowest_timestamp(
        poe_trade_main_handler_classes_list):
    """
    Function gets lowest checked_timestamp in list
    :param poe_trade_main_handler_classes_list: list with instances of PoeTradeMainHandler
    :return: position in list which has lowest checked_timestamp or
            None if no one is ready to work (checked_timestamp is lower than THREAD_SLEEP_DELAY_BETWEEN_CHECKS_SEC)
    """
    position = None

    for index in range(0, len(poe_trade_main_handler_classes_list)):
        # Is class already working?
        if not poe_trade_main_handler_classes_list[index].working:
            if position is None:
                position = index
                continue
            # Class not working at this moment. Lets check timestamp
            current_class_timestamp = poe_trade_main_handler_classes_list[position].checked_timestamp
            index_class_timestamp = poe_trade_main_handler_classes_list[index].checked_timestamp

            if index_class_timestamp < current_class_timestamp:
                position = index

    if position is not None:
        class_timestamp = poe_trade_main_handler_classes_list[position].checked_timestamp
        timestamp_diff = time.time() - class_timestamp

        if timestamp_diff > Settings.thread_sleep_delay_between_checks_sec():
            return position

    return None
示例#20
0
def create_first_chart():
    print("log file not found: try to fetch")
    strategy = settings["Strategy"]
    deltaDays = settings['deltaDays']
    filename = gsettings['configFilename']
    configjs = Settings.get_configjs(filename)
    watch = settings["watch"]
    dateset = gekkoWrapper.getAvailableDataset(watch)
    daterange = coreFunctions.getRandomDateRange(dateset, deltaDays=deltaDays)
    config = evolution_bayes.compressing_flatten_dict(configjs[strategy], strategy)
    config["watch"] = watch
    gekko_config = gekkoWrapper.createConfig(config, daterange)
    res = evolution_bayes.EvaluateRaw(watch, daterange, configjs[strategy], strategy)
    score = res['report']['relativeProfit']

    filename = "_".join([watch["exchange"], watch["currency"], watch["asset"], strategy, datetime.datetime.now().strftime('%Y%m%d_%H%M%S'), str(score)])
    save_dir = gsettings["save_dir"]
    json_filename = os.path.join(save_dir, filename) + "_config.json"
    json2_filename = os.path.join(save_dir, filename) + "_response.json"
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)
    f = open(json_filename, "w")
    f.write(json.dumps(gekko_config, indent=2))
    f.close()
    print("Saved: " + json_filename)
    f = open(json2_filename, "w")
    f.write(json.dumps(res, indent=2))
    f.close()
    print("Saved: " + json2_filename)
示例#21
0
 def install_http(self, url):
     ''' install a widget directly from a http address '''
     dest_temp_dir = tempfile.mkdtemp()
     remote.download(url, dest_temp_dir)
     package_file = os.path.join(dest_temp_dir, os.path.basename(url))
     # FIXME a weak check on whether we're dealing with a control
     if "files/controls" in url: install_dir = Settings.get_setting('control_install_dir')
     else: install_dir = Settings.get_setting('display_install_dir')
     
     # FIXME another reliance to the naming scheme on gd.de
     widget_name = os.path.basename(url).rsplit('-')[0]
     final_destination = local.unpack(package_file, install_dir, widget_name)
     
     # self.local_path = final_destination
     self.notify_observers("INSTALLED", uri)
     self.__find_local_desklets()
     return True
示例#22
0
 def set_reset_currency_thread(self, delay_in_seconds):
     """
     Function resets currencies to this class dictionaries and waits for a delay in seconds
     :param delay_in_seconds: delay to wait between next reset
     :return: returns nothing
     """
     while Settings.get_reset_currency_working():
         time.sleep(delay_in_seconds)
         self.set_currencies()
示例#23
0
 def __find_remote_controls(self):
     self.notify_observers("FETCH", "Fetching remote controls")
     self.remote_controls = {}
     for (base_url, d_list, d_path, c_list, c_path) in Settings.get_setting('repositories'):
         rds = remote.get_controls(base_url, c_list, 
                                   Settings.get_setting('cache_dir'))
         self.remote_controls.update(rds)
         
         for d_key in rds:
             d_data = rds[d_key]
             d = Control(d_data['name'], d_data['description'], d_data['authors'])
             d.remote_domain = base_url
             
             d.set_available_remotely(True)
             for version_number in d_data['versions']:
                 d.add_version(version_number, d_data['versions'][version_number])
             #for ver in d_data['versions']:
              #   d.add_version(ver)
             self.add_control(d)
示例#24
0
 def __init__(self, parent, id, title, size, pos):
     wx.Frame.__init__(self, parent, id, title, pos, size)
     self.VERSION_TYPE = "Version: Alpha - 0.3.1"
     self.addMenu()
     self.HotKeyMachine = HotKeys()
     self.mySettings = Settings(self, "Settings - More options coming soon")
     self.url = ""
     # Hook the new game selection option prior to loading the game
     self.Panel = MyPanel(self, "http://www.transformice.com/TransformiceChargeur.swf")
     self.Show(True)
示例#25
0
 def ShowSettings(self, sender, args):
     self.key_map.setKILLAll(True)
     self.kill = True
     self.controls_entry = Settings()
     if sender.Text == "&Controls":
         self.controls_entry.initializeGUI(self.key_map,0)
     else:
         self.controls_entry.initializeGUI(self.key_map,1)
     self.controls_entry.Show()
     self.controls_entry.FormClosing += FormClosingEventHandler(self.Controls_Closing_Event)
 def write_to_file_string(self, string_to_write):
     """
     Function writes a string to a file which name is defined in Settings.py
     :param string_to_write: string to write
     :return: returns nothing
     """
     filename = Settings.items_file_name_if_found()
     with threading.Lock():
         file_ = codecs.open("./" + filename, 'a', "utf-8")
         file_.write(str(string_to_write + "\n"))
         file_.close()
示例#27
0
 def on_imgmenuEditResetSettings_activate(self, widget, confirm=True):
   "Restore default settings"
   if confirm:
     dialog = DialogYesNo(
       message=_('Do you want to reset the default settings?'),
       default_button=gtk.RESPONSE_NO
     )
     dialog.set_icon_from_file(handlepaths.get_app_logo())
     dialog.show()
   # Reset if confirm was not requested or if the user gave response
   if not confirm or dialog.responseIsYes():
     if self.defaultLanguageIndex:
       self.cboLanguages.set_active(self.defaultLanguageIndex)
     print 'restored default settings'
     if os.path.exists(Settings.conffile):
       os.remove(Settings.conffile)
       print 'removed user settings file: %s' % Settings.conffile
     # Reload default settings
     Settings.load()
     self.loadSettings(True)
示例#28
0
文件: IntroScene.py 项目: PGcpp/Game
    def prepare(self):
        self.screen.fill((0,0,0));

        self.introImage = pygame.image.load('resources/intro.png')
        self.introImage = self.introImage.convert()

        self.introImage.set_alpha(0)

        introSound = pygame.mixer.Sound("resources/intro.wav")
        introSound.set_volume( Settings.getMusicLevel() )
        introSound.play()
示例#29
0
def startup():
    global procs
    global pipes
    global param
    global running
    
    # Settings
    cfg = Settings.CSettings()
    param['CSettings'] = cfg
    
    # Logfile
    if cfg.getSetting('logpath').startswith('.'):
        # relative to current path
        logpath = sys.path[0] + sep + cfg.getSetting('logpath')
    else:
        # absolute path
        logpath = cfg.getSetting('logpath')
    
    param['LogFile'] = logpath + sep + 'PlexNMT.log'
    param['LogLevel'] = cfg.getSetting('loglevel')
    dinit('PlexNMT', param, True)  # init logging, new file, main process
    
    dprint('PlexNMT', 0, "Version: {0}", __VERSION__)
    dprint('PlexNMT', 0, "Python: {0}", sys.version)
    dprint('PlexNMT', 0, "Host OS: {0}", sys.platform)
    
    # more Settings
    param['IP_self'] = getIP_self()
#    param['HostToIntercept'] = cfg.getSetting('hosttointercept')
#    param['baseURL'] = 'http://'+ param['HostToIntercept']
    
    running = True
    
    # init WebServer
    if running:
        master, slave = Pipe()  # endpoint [0]-PlexNMT, [1]-WebServer
        proc = Process(target=WebServer.Run, args=(slave, param))
        proc.start()
        
        time.sleep(0.1)
        if proc.is_alive():
            procs['WebServer'] = proc
            pipes['WebServer'] = master
        else:
            dprint('PlexNMT', 0, "WebServer not alive. Shutting down.")
            running = False
    
    # not started successful - clean up
    if not running:
        cmdShutdown()
        shutdown()
    
    return running
示例#30
0
def generateSettings():
    t, p, m = 0, 4, False
    if len(sys.argv) > 1:
        for i in range(1, len(sys.argv)):
            if sys.argv[i][0] == "-":
                if sys.argv[i][1] == "t":
                    t = sys.argv[i][2]
                elif sys.argv[i][1] == "p":
                    p = sys.argv[i][2]
                elif sys.argv[i][1] == "m":
                    m = True
    return Settings(t, p, m)
示例#31
0
def dummy_settings():
    return Settings(**dict(
        listen_port=fake.pyint(),
        listen_host=fake.ipv4(),
        db_name=fake.slug(),
        db_max_con=fake.pyint(),
        db_user=fake.user_name(),
        db_password=fake.password(),
        db_host=fake.hostname(),
        db_port=fake.pyint(),
        log_level=random.choice(list(logging._nameToLevel))
        ))
示例#32
0
def main():
    log.LogPrint('Working at:{}'.format(os.getcwd()))
    settings = Settings.Settings(INTERVAL_SETTING_FILE)
    settings.load_settings()
    interval = settings.Interval

    threadTimer = thTimer(interval)
    threadTimer.Start()

    while (True):
        log.LogPrint('Watching Thread:{}'.format(str(threading.activeCount())))
        time.sleep(60)
示例#33
0
 def getNextForce(self):
     length = len(self.force_values)
     if (length == 0):
         print(
             "ERROR(Forces.getNextForce:1): No force values have been loaded!"
         )
         Settings.quit_prog()
     else:
         #Check if we reached the end of the lists containing the force values, restart if that is the case
         if (self.index < length):
             self.index += 1
             if (Settings.DEBUG):
                 print("Fetched the next force value: " +
                       str(self.force_values[self.index - 1]))
             return int(self.force_values[self.index - 1])
         else:
             self.index = 1
             if (Settings.DEBUG):
                 print("Fetched the next force value: " +
                       str(self.force_values[0]))
             return int(self.force_values[0])
示例#34
0
def PluginInit():
 tarr = []
 filenames = glob.glob('_P*.py')
 filenames.sort()
 for fname in filenames:
  tarr = [0,0,0]
  tarr[0] = fname
  with open(fname,"r",encoding="utf8") as fcont:
   for line in fcont:
    if "PLUGIN_ID" in line:
     tarr[1] = line[line.find("=")+1:].strip().replace('"',"")
    if "PLUGIN_NAME" in line:
     tarr[2] = line[line.find("=")+1:].strip().replace('"',"")
     break
  tarr[0] = tarr[0].replace(".py","")
  rpieGlobals.deviceselector.append(tarr) # create list for form select

 print("Load devices from file")
 Settings.loadtasks()

 return 0
示例#35
0
    def load_credentials(self):
        print "Loading credentials..."
        filer = open(Settings.pathman["profile"], 'r')
        try:
            enc_cred = pickle.load(filer)
        except EOFError:
            return []
        filer.close()

        j = json.loads(Settings.decode(self.enc_key, enc_cred))
        print j
        return j
示例#36
0
    def __init__(self):
        pygame.init()
        if platform.system() == 'Windows':
            user32 = ctypes.windll.user32
            user32.SetProcessDPIAware()
            width = user32.GetSystemMetrics(0)
            height = user32.GetSystemMetrics(1)
        else:
            display_info = pygame.display.Info()
            width = display_info.current_w
            height = display_info.current_h

        Settings.set_scale_factor(height / 1000)
        os.environ['SDL_VIDEO_WINDOW_POS'] = "0,50"
        self.events = None
        self.left_mouse_button_clicked = False
        self.right_mouse_button_clicked = False
        self.current_screen = MainMenuScreen()
        self.window = pygame.display.set_mode(
            (width, height - 50))  #, pygame.FULLSCREEN)
        pygame.display.set_caption("Plumber")
示例#37
0
    def __init__(self, directory=None, include_vague=True):
        if directory == None:
            s = Settings.Settings()
            directory = s.data_directory + "CoralBleaching\\"

        self.directory = directory
        logging.log(logging.INFO,
                    "GWData: Processing Data from directory \n\t'%s'",
                    directory)

        #Properties
        # list of all docs
        self.documents = []
        # list of codes for each doc
        # list of sets, size is the same as number of docs
        self.codes_per_document = []

        #CODES

        self.count_per_sm_code = defaultdict(int)

        #INDICES FOR CODE TYPE (over all codes for that type, not by code)
        self.sm_code_indices = []
        self.sm_codes = set()
        #self.text_code_indices = []

        self.causal_per_document = []

        #LOAD SOURCE TEXT
        dataLines = self.__loadLines__("CbDatabase.csv")
        dictLineToIndex = {}

        to_replace = ["-", ";", ",", "  "]

        for line in dataLines[1:]:  # skip header
            splt = line.split("|")
            if len(splt) == 4:
                essay, sentence_num, sentence, codes_str = splt
                compiled = ""
            elif len(splt) == 5:
                essay, sentence_num, sentence, codes_str, compiled = splt
            else:
                raise Exception("Bad Data")

            for repl_str in to_replace:
                codes_str = codes_str.replace(repl_str, " ")

            codes = self.__collapse_codes__(compact(codes_str.split(" ")))
            self.__process_line__(dictLineToIndex, codes, codes_str, sentence)

        self.allCodes = self.sm_codes.copy()
        logging.log(logging.INFO, "\tProcessed %i documents for %i codes",
                    len(self.documents), len(self.allCodes))
示例#38
0
文件: chart.py 项目: GO1984/japonicus
def show_chart():
    strategy = settings["Strategy"]
    deltaDays = settings['deltaDays']
    filename = settings['configFilename']
    configjs = Settings.get_configjs(filename)
    watch = settings["watch"]
    dateset = gekkoWrapper.getAvailableDataset(watch)
    daterange = resultInterface.getRandomDateRange(dateset, deltaDays=deltaDays)
    res = evolution_bayes.EvaluateRaw(watch, daterange, configjs[strategy], strategy)
    #res = gekkoWrapper.httpPost(URL, gekkoConfig)

    show_candles(res, configjs[strategy])
示例#39
0
 def webform_save(self,params):
   submit = webserver.arg("Submit",params)
   setbtn = webserver.arg("set",params)

   devlist = get_ftdi_devices(2)
   if len(devlist)>0:
    try:
     d = int(webserver.arg("newdev",params))
    except:
     d = -1
    if d>-1 and d<len(devlist):
       devcount = len(get_ftdi_configured_devices())
       self.createdevpinout(devlist[d][0],devlist[d][1],devcount)
   if (submit=='Submit'):
    devcount = len(get_ftdi_configured_devices())
    for i in range(0,devcount):
     wset = webserver.arg("i2c"+str(i),params)
     wset2 = webserver.arg("spi"+str(i),params)
     if wset=="on":
      self.disable_spi(i)
      self.enable_i2c(i)
     elif wset2=="on":
      cenum = webserver.arg("i2c"+str(i)+"ce",params)
      self.enable_spi(i,cenum)
     else:
      self.disable_i2c(i)
      self.disable_spi(i) # revert to gpio mode
    for p in range(len(Settings.Pinout)):
     pins = webserver.arg("pinstate"+str(p),params).strip()
     if pins and pins!="" and p!= "":
      try:
       self.setpinstate(p,int(pins))
      except Exception as e:
       misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,"Pin "+str(p)+" "+str(e))
    try:
     Settings.savepinout()
    except Exception as e:
     misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Pinout "+str(e))

   return True
示例#40
0
def linked_slider_change(self):
    self.core_spinBox.blockSignals(True)
    self.frame_spinBox.blockSignals(True)
    self.core_verticalSlider.blockSignals(True)
    self.frame_verticalSlider.blockSignals(True)

    if (Settings.frame_RPM != self.frame_verticalSlider.sliderPosition() / 10):
        Settings.frame_RPM = self.frame_verticalSlider.sliderPosition() / 10
        Settings.core_RPM = Settings.frame_RPM
        self.core_verticalSlider.setValue(Settings.core_RPM * 10)
        self.core_spinBox.setValue(Settings.core_RPM)
        self.frame_spinBox.setValue(Settings.frame_RPM)
    else:
        Settings.core_RPM = self.core_verticalSlider.sliderPosition() / 10
        Settings.frame_RPM = Settings.core_RPM
        self.frame_verticalSlider.setValue(Settings.frame_RPM * 10)
        self.core_spinBox.setValue(Settings.core_RPM)
        self.frame_spinBox.setValue(Settings.frame_RPM)

    CMD = "2~" + Settings.getInterval(Settings.frame_RPM)
    Settings.sendCMD(Settings.frame_addr, CMD)
    sleep(0.02)
    CMD = "2~" + Settings.getInterval(Settings.core_RPM)
    Settings.sendCMD(Settings.core_addr, CMD)

    self.core_spinBox.blockSignals(False)
    self.frame_spinBox.blockSignals(False)
    self.core_verticalSlider.blockSignals(False)
    self.frame_verticalSlider.blockSignals(False)
示例#41
0
 def on_closing(self):
     # Save window size
     sizes = self.ui.winMain.get_size()
     self.logger('Save window size (%dx%d)' % (sizes[0], sizes[1]))
     Settings.set('MainWindowWidth', sizes[0])
     Settings.set('MainWindowHeight', sizes[1])
     Settings.set('SettingsExpander', self.ui.expSettings.get_expanded())
示例#42
0
def get_unbalanced_dataset(in_memory=False):
    assert in_memory == False

    # prep to move the dataset to >> /cluster/work/igp_psr/ruzickav <<
    # instead of loading indiv files, load batches in h5 files

    from ActiveLearning.LargeDatasetHandler_AL import LargeDatasetHandler_AL
    import Settings

    # init structures
    import mock
    args = mock.Mock()
    args.name = "test"

    settings = Settings.Settings(args)
    WholeDataset = LargeDatasetHandler_AL(settings)

    # load paths of our favourite dataset!
    import DataLoader, DataPreprocesser, Debugger
    import DatasetInstance_OurAerial

    dataLoader = DataLoader.DataLoader(settings)
    debugger = Debugger.Debugger(settings)

    datasetInstance = DatasetInstance_OurAerial.DatasetInstance_OurAerial(
        settings, dataLoader, "256_cleanManual")

    # ! this one loads them all (CHECK: would some be deleted?)
    paths = datasetInstance.load_dataset_ONLY_PATHS_UPDATE_FROM_THE_OTHER_ONE_IF_NEEDED(
    )
    lefts_paths, rights_paths, labels_paths = paths
    print("Paths: L,R,Y ", len(lefts_paths), len(rights_paths),
          len(labels_paths))

    WholeDataset.initialize_from_just_paths(paths)

    if in_memory:
        WholeDataset.keep_it_all_in_memory()

    npy_path = settings.large_file_folder + "datasets/OurAerial_preloadedImgs_unBALCLASS.npy"

    I_WANT_TO_RECOMPUTE_THE_LABELS = False
    if I_WANT_TO_RECOMPUTE_THE_LABELS:
        assert False  # don't want to mistakenly recompute these ...
        WholeDataset.compute_per_tile_class_in_batches()
        WholeDataset.save_per_tile_class(npy_path)

    WholeDataset.load_per_tile_class(npy_path)

    WholeDataset.report()

    return WholeDataset
示例#43
0
    def align(self):        
        if self.seq_input_frame.text_is_empty(): # No sequences were provided
            self.host.set_status("No sequences were provided to align!", "#FF0000")
            return
        print ("    Alignment construction started...")
        (muscle_name, muscle_path) = Settings.get_program_name(self.host.settings.muscle_dir, "muscle")
        unaligned_filename = os.path.join(self.host.settings.work_dir, "%s.fasta" % self.host.temp_name)
        Aln_basic.write_widget_into_file(self.seq_input_frame.text_widget, unaligned_filename)
        aligned_filename = os.path.join(self.host.settings.work_dir, "%s.aln" % self.host.temp_name)

        self.host.set_status("Alignment")
        maxiters_option = ""
        if self.maxiters.get() != "":
            try:
                maxiters_option = "-maxiters %i" % int(self.maxiters.get())
            except TypeError:
                print ("Option -maxiters is not an integer and is ignored!")
        gapopen_option = ""
        if self.gapopen.get() != "":
            if Aln_basic.is_negative_float(self.gapopen.get(), "-gapopen"):
                gapopen_option = "-gapopen %s" % self.gapopen.get()
        gapextend_option = ""
        if self.gapextend.get() != "":
            if Aln_basic.is_negative_float(self.gapextend.get(), "-gapextend"):
                gapextend_option = "-gapextend %s" % self.gapextend.get()
        muscle_command = "%s -in %s -out %s %s %s %s" % (muscle_path, unaligned_filename, aligned_filename, maxiters_option, gapopen_option, gapextend_option)
        print ("Muscle command to be ran:")
        print (muscle_command)        
        if self.host.verbose.get():                     
            os.system(muscle_command)
        else:
            os.system("%s 1> nul 2> nul" % muscle_command)

        Aln_basic.read_widget_from_file(self.aln_input_frame.text_widget, aligned_filename)
        if self.insert_blocks.get(): # Empty sequence >BLOCKS should be added
            curr_seqs = Aln_basic.read_fasta_from_strings(self.aln_input_frame.get_strings())
            self.aln_input_frame.text_widget.delete(1.0, tkinter.END)
            upd_aln_file = open(aligned_filename, "w")            
            upd_aln_file.write(">BLOCKS\n")
            upd_aln_file.write("%s\n\n" % ("-" * len(curr_seqs[0].sequence)))
            upd_aln_file.write(">SITE\n")
            upd_aln_file.write("%s\n\n" % ("-" * len(curr_seqs[0].sequence)))
            for s in curr_seqs:
                s.print_fasta(upd_aln_file, 60)
            upd_aln_file.close()
            Aln_basic.read_widget_from_file(self.aln_input_frame.text_widget, aligned_filename)            
                    
        self.host.set_status("Ready")

        os.remove(unaligned_filename)
        os.remove(aligned_filename)
        print ("    [..DONE..]")
示例#44
0
 def dragEnterEvent(self, event):
     """
     Drag enter event
     """
     if event.mimeData().hasFormat(
             'application/x-%s-help-item' %
             Settings.instance().readValue(key='Common/acronym').lower()):
         event.accept()
     elif event.mimeData().hasFormat(
             'application/x-%s-parameter-item' %
             Settings.instance().readValue(key='Common/acronym').lower()):
         event.accept()
     elif event.mimeData().hasFormat(
             'application/x-%s-agent-item' %
             Settings.instance().readValue(key='Common/acronym').lower()):
         event.accept()
     elif event.mimeData().hasFormat(
             'application/x-%s-description-item' %
             Settings.instance().readValue(key='Common/acronym').lower()):
         event.accept()
     else:
         QsciScintilla.dragEnterEvent(self, event)
示例#45
0
def create():
    game = dict()
    game["dungeon"] = Dungeon.create("forest")

    settings = Settings.create()
    game["keyManager"] = settings
    #for keyName in settings:
    #dataKey = dict()
    #dataKey.update({"key": settings[keyName]})
    #game["keyManager"].update({keyName: dataKey})

    Dungeon.generate(game["dungeon"])
    return game
示例#46
0
def doCleanup():
  rulesProcessing("System#Shutdown",rpieGlobals.RULE_SYSTEM)
  if (len(Settings.Tasks)>1) or ( (len(Settings.Tasks)==1) and (Settings.Tasks[0] != False) ):
   Settings.savetasks()
  procarr = []
  for x in range(0,len(Settings.Tasks)):
   if (Settings.Tasks[x]) and type(Settings.Tasks[x]) is not bool: # device exists
    try:
     if (Settings.Tasks[x].enabled): # device enabled
      t = threading.Thread(target=Settings.Tasks[x].plugin_exit)
      t.daemon = True
      procarr.append(t)
      t.start()
    except:
     pass
  if len(procarr)>0:
   for process in procarr:
     process.join(1)
  try:
   for t in range(0,rpieGlobals.RULES_TIMER_MAX):
    rpieTime.Timers[t].pause()
   for t in range(0,rpieGlobals.SYSTEM_TIMER_MAX):
    rpieTime.SysTimers[t].pause()
  except:
   pass
  procarr = []
  for y in range(0,len(Settings.Controllers)):
   if (Settings.Controllers[y]):
    if (Settings.Controllers[y].enabled):
      t = threading.Thread(target=Settings.Controllers[y].controller_exit)
      t.daemon = True
      procarr.append(t)
      t.start()
  if int(Settings.NetMan.WifiDevNum)>=0 and int(Settings.NetMan.APMode>-1):
    apdev = int(Settings.NetMan.WifiDevNum)
    Network.AP_stop(apdev) # try to stop AP mode if needed
  if len(procarr)>0:
   for process in procarr:
     process.join()
示例#47
0
def main(args):
    #Init settings
    Settings.init()
    Settings.enableDebug = args.debug
    print(args.debug)
    print(Settings.enableDebug)

    executor = Executor()
    validationDataPath = os.path.abspath("ValidationData")
    #Load validation data
    with open(validationDataPath + '/validator.json') as json_file:
        validationData = json.load(json_file)
    validationData = validationData['exams']

    #load labels
    label_file = executor.input.modelPath + '/yolo-obj.names'
    labels = open(label_file).read().strip().split('\n')

    #init result rate which means % success rate of each label
    resultRate = {}
    for label in labels:
        resultRate[label] = 0

    #star validation
    for item in validationData:
        #execute detection
        executeResult = executor.execute(validationDataPath + '/' +
                                         item['image'])

        #validate and get result
        validationResult = validateResult(item['data'], executeResult, labels)

        #add validation result to final result
        for label in labels:
            resultRate[label] = resultRate[label] + validationResult[label]

    showResult(resultRate, validationData)

    return
示例#48
0
def main():
    #initialization
    speedratio = 0
    text = []
    pygame.init()
    Setting = st.Settings()
    screen = pygame.display.set_mode(
        (Setting.screen_width, Setting.screen_height))
    pygame.display.set_caption("Time Dilation")
    screen.blit(Setting.bg_main, [0, 0])

    #music set up
    bg_music = Setting.bg_music_main
    bg_music.set_volume(0.9)
    bg_music.play(-1)

    #text and button set up
    text = sf.initialize_main_text(text, screen)

    for i in text:
        i.draw_button()

    #main loop

    while True:
        speedratio = sf.check_event_main(Setting, text, speedratio)
        speedratio = sf.round_half_up(speedratio, 2)
        text_3_settings = st.txt(40, 40, (255, 252, 252), (0, 0, 0), 25,
                                 "times new roman", 250, 160)
        text[2] = textprep.text(text_3_settings, screen, str(speedratio))
        text[2].draw_button()
        pygame.display.flip()
        if Setting.status == 1:
            pygame.quit()
            Setting.changestatus(0)
            run_simulation(speedratio)
        elif Setting.status == 2:
            Setting.changestatus(0)
            graph(speedratio)
示例#49
0
 def delete_old_withdrawals(self, block_from):
     """ Deletes all withdrawal transactions not needed anymore """
     # Delete transactions older than 15 min
     for transaction_to in list(self.transactions_to):
         exchange_processing_time = (
             transaction_to["time"] -
             block_from[0]["blocktime"]).total_seconds()
         if exchange_processing_time > Settings.get_exchange_time_upper_bound(
                 None):
             # Delete transactions older than X min
             self.transactions_to.remove(transaction_to)
         else:
             break
示例#50
0
 def stopPlaying(self):
   self.espeak.stop()
   # Disable buttons and menus
   self.setStopCheck(False)
   self.imgmenuEditPlay.set_sensitive(True)
   self.imgmenuEditStop.set_sensitive(False)
   self.imgmenuEditPause.set_sensitive(False)
   self.imgmenuFileRec.set_sensitive(True)
   self.btnPause.set_sensitive(False)
   self.btnPlayStop.set_label('gtk-media-play')
   if Settings.get('SingleRecord'):
     self.tlbRecord.set_active(False)
   self.tlbRecord.set_sensitive(True)
示例#51
0
def show_chart():
    strategy = settings["Strategy"]
    deltaDays = settings['deltaDays']
    filename = settings['configFilename']
    configjs = Settings.get_configjs(filename)
    watch = settings["watch"]
    dateset = gekkoWrapper.getAvailableDataset(watch)
    daterange = coreFunctions.getRandomDateRange(dateset, deltaDays=deltaDays)
    res = evolution_bayes.EvaluateRaw(watch, daterange, configjs[strategy],
                                      strategy)
    #res = gekkoWrapper.httpPost(URL, gekkoConfig)

    show_candles(res, configjs[strategy])
示例#52
0
 def playText(self, text):
   if text:
     # Save buffer text on temporary filename and play it
     tmpFile = open(self.tempFilename, mode='w')
     tmpFile.write(text)
     tmpFile.close()
     # Replace espeak's arguments with dialog values
     language = self.listLanguages[self.cboLanguages.get_active()][COL_NAME]
     isMbrola = self.listLanguages[self.cboLanguages.get_active()][COL_MBROLA]
     # Apply variant and voice to non-mbrola voices
     if not isMbrola:
       # Choose voice variant
       if self.cboVariants.get_active() == 0:
         # Default voice
         if self.radioVoiceFemale.get_active():
           language += '+12'
       else:
         language += '+%s' % self.listVariants[self.cboVariants.get_active()][0]
     args = {
       '%v': str(int(self.hscVolume.get_value())), 
       '%p': str(int(self.hscPitch.get_value())),
       '%s': str(int(self.hscSpeed.get_value())),
       '%d': str(int(self.hscDelay.get_value())),
       '%l': language,
       '%f': self.tempFilename
     }
     cmd = [Settings.cmdEspeak] + [
       args.get(p, p) for p in Settings.argsEspeak.split()]
     # Enable stop buttons on menu and toolbar
     self.imgmenuEditPlay.set_sensitive(False)
     self.imgmenuEditStop.set_sensitive(True)
     self.imgmenuEditPause.set_sensitive(True)
     self.imgmenuFileRec.set_sensitive(False)
     self.btnPause.set_sensitive(True)
     self.btnPlayStop.set_label('gtk-media-stop')
     self.tlbRecord.set_sensitive(False)
     if not isMbrola:
       self.espeak.play(cmd, self.cmdPlayer, self.recordToFile)
     else:
       args = {
         '%v': str(int(self.hscVolume.get_value())/100.), 
         '%l': '%s/%s/%s' % (
           Settings.get('VoicesmbPath'), 
           language.replace('mb-', '', 1),
           language.replace('mb-', '', 1))
       }
       cmdMbrola = [Settings.cmdMbrola] + [
         args.get(p, p) for p in Settings.argsMbrola.split()]
       self.espeak.playMbrola(cmd, self.cmdPlayer, cmdMbrola, self.recordToFile)
     # Enable check for running processes
     self.setStopCheck(True)
示例#53
0
    def addStep(self,
                text,
                color="#A5A2A5",
                width=400,
                height=40,
                data=None,
                textBold=False,
                textItalic=False,
                timestamp="00:00:00"):
        """
        Add step
        """
        # take the last one
        if len(self.steps):
            latestBlock = self.steps[-1:][0]
        else:
            latestBlock = None

        newBlock = BlockItem(self,
                             text,
                             blockColor=color,
                             width=width,
                             height=height,
                             data=data,
                             bold=textBold,
                             italic=textItalic)
        if width == 100:
            newBlock.setPos(400 / 2 - 100 / 2, len(self.steps) * 80)
        elif width == 300:
            newBlock.setPos(400 / 2 - 300 / 2, len(self.steps) * 80)
        else:
            newBlock.setPos(0, len(self.steps) * 80)

        self.steps.append(newBlock)
        self.diagramScene.addItem(newBlock)

        newTimestampBlock = TimestampItem(self, timestamp)
        newTimestampBlock.setPos(-200, len(self.timestamps) * 80)

        self.timestamps.append(newTimestampBlock)
        self.diagramScene.addItem(newTimestampBlock)

        if latestBlock is not None:
            newArrow = LineItem(latestBlock, newBlock)
            self.diagramScene.addItem(newArrow)
            self.arrows.append(newArrow)

        if QtHelper.str2bool(Settings.instance().readValue(
                key='TestRun/auto-scrolling-graph')):
            self.view.centerOn(newBlock)
        return newBlock
示例#54
0
    def __init__(self, videofile='', jsonfile=''):
        QMainWindow.__init__(self)
        self.settings = Settings.loadSettings()

        # play state
        self.playStat = GuiWindow.V_PAUSE

        self.videofile = videofile
        self.jsonfile = jsonfile
        self.txtfile = ''
        self.imgSource = ImageSource(self.videofile, self.jsonfile)
        self.plugin = Plugin(self.imgSource)
        self.lastPluginFnum = -1

        self.frameW = self.settings['frameW']
        self.frameH = self.settings[
            'frameH']  # will be updated when open video file
        self.scale = 1.0
        self.offset = [0, 0]
        self.zoomed = False

        self.holdShift = False
        self.holdControl = False
        self.holdAlt = False

        self.labelfile = ''
        #
        self.rate = 30
        self.fnum = 0
        self.focusRoiId = -1
        self.selRoiId = -1
        self.fcnt = self.imgSource.getFrameCount()
        self.roiLabels = (
            # name, editable
            ("label_name", False),
            ("label_id", False),
            ("roi_score", False),
            ("roi_x", True),
            ("roi_y", True),
            ("roi_w", True),
            ("roi_h", True),
            ("roi_id", False))

        # setup timer tick
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.tick)
        self.timer.start(1000 / self.rate)
        self.liftPressed = False
        # init gui
        self.guiInit()
        self.updateImage(self.fnum, True)
示例#55
0
    def get_reward(self, action: Action, driver_num: int) -> float:
        """
        Return the reward to an agent for a given (feasible) action.

        (Feasibility is not checked!)
        Defined in Environment class because of Reinforcement Learning
        convention in literature.
        """

        if Settings.get_value("value_num") == 8:
            profit = Util.change_profit(self, action)
            entropy = Util.change_entropy(self, action, driver_num)
            lamb = Settings.get_value("lambda")

            if np.isfinite(entropy):
                return profit - lamb * entropy
            else:
                return profit
        elif Settings.get_value("value_num") == 10:
            profit = Util.change_profit(self, action)
            variance = Util.change_variance(self, action, driver_num)
            lamb = Settings.get_value("lambda")

            return profit - lamb * variance
        elif Settings.get_value("value_num") == 12:
            profit = Util.change_profit(self, action)
            entropy = Util.change_entropy_rider(self, action, driver_num)
            lamb = Settings.get_value("lambda")
            if np.isfinite(entropy):
                return profit - lamb * entropy
            else:
                return profit
        elif Settings.get_value("value_num") == 14:
            profit = Util.change_profit(self, action)
            variance = Util.change_variance_rider(self, action, driver_num)
            lamb = Settings.get_value("lambda")

            return profit - lamb * variance
        elif Settings.get_value("value_num") == 15:
            profit = Util.change_profit(self, action)
            return profit
        else:
            return sum([request.value for request in action.requests])
示例#56
0
 def import__(self, inputs):
     """
     Import test config, dispatch to local, remote or other 
     """
     # import from local repo
     self.localConfigured = Settings.instance().readValue( key = 'Repositories/local-repo' )
     if self.localConfigured != "Undefined":
         buttons = QMessageBox.Yes | QMessageBox.No
         answer = QMessageBox.question(self, Settings.instance().readValue( key = 'Common/name' ), 
                         self.tr("Import Test Config from local repository") , buttons)
         if answer == QMessageBox.Yes:
             self.loadFromLocal(inputs=inputs) # load local test config file
         else:
             if RCI.instance().isAuthenticated: # no then perhaps in remo repo if connected?
                 self.loadFromRemote(inputs=inputs) # load remote test config file
             else:
                 QMessageBox.warning(self, "Save" , "Connect to the test center first!")
     
     # import from remote repo
     elif RCI.instance().isAuthenticated: # no then perhaps in remo repo if connected?
         self.loadFromRemote(inputs=inputs) # load remote test config file
     else:
         QMessageBox.warning(self, "Save" , "Connect to the test center first!")        
示例#57
0
    def __init__(self, alarmThread, shutdownCallback):
        threading.Thread.__init__(self)

        self.shutdownCallback = shutdownCallback
        self.alarmThread = alarmThread
        self.settings = Settings.Settings()
        self.media = MediaPlayer.MediaPlayer()

        self.menuPointer = None
        self.menuTimeout = 0
        self.menuActive = False
        self.tmp = 0
        self.active = False
        self.stopping = False
示例#58
0
 def killTest(self):
     """
     Kill the test
     """
     if not (Settings.instance().readValue(key='TestRun/ask-before-kill')
             == 'True'):
         RCI.instance().killTask(taskId=self.TID)
     else:
         reply = QMessageBox.warning(
             self, "Kill test",
             "Are you sure you want to stop the execution of the test?",
             QMessageBox.Yes | QMessageBox.No)
         if reply == QMessageBox.Yes:
             RCI.instance().killTask(taskId=self.TID)
示例#59
0
def init(scriptConfig,
         engineConfig,
         userPreferences,
         customGraphicPrefs,
         loadingScreenGUI=None):
    global g_settings
    if not config_consts.SEND_CONSTS_TO_CLIENT:
        import db.DBLogic
        db.DBLogic.initDB(False, IGNORE_CACHE_TAG not in sys.argv)
    BigWorld.gameLoadingScreenSetProgress(0.965)
    import gc
    gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES
                 | gc.DEBUG_SAVEALL)
    if consts.IS_DEBUG_IMPORTED:
        debug.init()
    Settings.g_instance = Settings.Settings(scriptConfig, engineConfig,
                                            userPreferences,
                                            customGraphicPrefs)
    g_settings = Settings.g_instance
    BigWorld.gameLoadingScreenSetProgress(0.992)
    ClientLog.g_instance.init(
        Settings.g_instance.userPrefs[Settings.KEY_CLIENT_LOGGING])
    ClientLog.g_instance.general('Client start.')
    for x in GUI.roots():
        GUI.delRoot(x)

    BigWorld.worldDrawEnabled(False)
    BigWorld.setRedefineKeysMode(True)
    CompoundSystem.setCompoundAlphaAnimSpeed(COMPOUND_ALPHA_ANIM_SPEED)
    g_windowsManager.start()
    if loadingScreenGUI:
        loadingScreenGUI.script.removeAllCallbacks()
        loadingScreenGUI.script.active(False)
    BigWorld.setScreenshotNotifyCallback(screenshotNotifyCallback)
    from account_helpers import ClanEmblemsCache
    ClanEmblemsCache.ClanEmblemsCache()
    import CameraZoomStatsCollector
    CameraZoomStatsCollector.CameraZoomStatsCollector()
    days = engineConfig.readInt('debug/logDayLimit', -1)
    if days >= 0:
        deleteOldFiles(BigWorld.getAppLogsDirectory(), days, '.log')
        deleteOldFiles(BigWorld.getAppLogsDirectory(), days, '.dmp')
    import BattleReplay
    BattleReplay.g_replay = BattleReplay.BattleReplay()
    BattleReplay.g_replay.deleteOldReplays()
    RSSDownloader.init()
    connectionManager.onConnected += onConnected
    connectionManager.onDisconnected += onDisconnected
    g_waitingInfoHelper.addWaitingInfo(WAITING_INFO_TYPE.BOOTSTRAP,
                                       time.time() - _bwPersonalityStarted)