def __launch(delegate):
   ''' 
   Runs the given (no-argument) delegate method in a 'safe' script environment.
   This environment will take care of all error handling, logging/debug stream,
   and other standard initialization behaviour before delegate() is called, and
   it will take care of cleaning everything up afterwards.
   ''' 
   try:
      # initialize the application resources (import directories, etc)
      Resources.initialize()
      
      # fire up the debug logging system
      log.install(ComicRack.MainWindow)
      
      # install a handler to catch uncaught Winforms exceptions
      def exception_handler(sender, event):
         log.handle_error(event.Exception)
      Application.ThreadException \
         += ThreadExceptionEventHandler(exception_handler)
         
      # fire up the localization/internationalization system
      i18n.install(ComicRack)
      
      # see if we're in a valid environment
      if __validate_environment():
         delegate()
         
   except Exception, ex:
      log.handle_error(ex)
   def __init__(self):
      ''' Creates a _PictureBoxPanel.  Call set_image after initialization. '''
      
      # the left and right arrow Image objects
      self.__left_arrow = Resources.createArrowIcon(True, False)
      self.__full_left_arrow = Resources.createArrowIcon(True, True)
      self.__right_arrow = Resources.createArrowIcon(False, False)
      self.__full_right_arrow = Resources.createArrowIcon(False, True)
      
      # the vertical line boundary between the full_left and left arrow's
      # 'clickable columns' and the full_right and right arrow's.
      self.__left_bound = 0;
      self.__right_bound = 0;

      # the image attributes to use for drawing non-alpha blended images      
      self.__hovered_image_atts = None
      
      # the image attributes to use for drawing alpha blended images      
      self.__normal_image_atts = None
      
      # a string indicating whether the mouse is hovered over the full 
      # left ('FL'), left ('L'), right ('R'), or full right ('FR') side of 
      # this panel, or None if the mouse isn't over the panel at all.  
      self.__mouse_hovered_state = None
      
      # our PictureBox object, which we center and stretch as needed 
      self._picbox = None
      
      Panel.__init__(self)
      self.__build_gui()
Exemple #3
0
    def create_tribe(name, user, carte):
        """
        Initialise une tribe (à utiliser après la création d'un compte)

        """
        tribe = Tribe(name=name, leader=user)
        tribe.save()

        resources_initiales = Resources(
                wood=INIT_TRIBE_RESOURCES['wood'],
                food=INIT_TRIBE_RESOURCES['food'],
                silex=INIT_TRIBE_RESOURCES['silex'],
                skin=INIT_TRIBE_RESOURCES['skin']
                )

        resources_initiales.save()
        village = Village.create_village(tribe, first=True)

        inhabitants = Group.objects.create(
                position=village.position,
                village=village,
                )
        village.inhabitants = inhabitants
        for key in INIT_TRIBE_UNITS:
            new_pile = UnitStack(
                    unit_type=UnitType.objects.get(identifier__iexact=key),
                    group=inhabitants,
                    number=INIT_TRIBE_UNITS[key],
                    )
            new_pile.save()
        village.update_income()

        return tribe
Exemple #4
0
 def receive_resources(self, resources):
     """
     add the resources to the village
     create a new object resources with this values and return it
     """
     max_resources = self.max_resources_storage()
     transfered_resources = Resources(
         food=min(
             resources.food,
             max_resources.food - int(self.resources.food),
             ),
         wood=min(
             resources.wood,
             max_resources.wood - int(self.resources.wood),
             ),
         silex=min(
             resources.silex,
             max_resources.silex - int(self.resources.silex),
             ),
         skin=min(
             resources.skin,
             max_resources.skin - int(self.resources.skin),
             ),
     )
     #need to create a new instance of resources to remember for the report
     transfered_resources.pk = None
     transfered_resources.save()
     self.resources += transfered_resources
     self.resources.save()
     self.plan_next_starvation()
     return transfered_resources
Exemple #5
0
def select_oldest(cloud, args):
    if cloud and args is not None:
        resources = Resources(cloud)
        age_resources = SelectAgeRelatedResources(cloud)
        age_resources.select_old_instances(
            datetime.timedelta(hours=args.old_active),
            datetime.timedelta(hours=args.old_inactive),
            datetime.timedelta(days=args.old_permanent),
            datetime.timedelta(hours=args.old_inerrror)
        )
        old_resources = age_resources.get_selection()
        new_search_prefix = None
        oldest = None
        if 'instances' in old_resources:
            for instance in old_resources['instances']:
                rec = old_resources['instances'][instance]
                if rec is None:
                    continue
                if oldest is None or oldest > rec['created_on']:
                    oldest = rec['created_on']
                    new_search_prefix = rec['name']
                logging.info('Found Old instance [{}] created on [{}] age [{}]'
                             .format(rec['name'],
                                     rec['created_on'],
                                     str(rec['age'])))

        if oldest is not None:
            substring = get_substr_from_name(new_search_prefix)
            resources.select_resources(substring)
        return resources
    return None
Exemple #6
0
class PlannerFrame(wx.Frame):
      def __init__(self, parent, id=wx.ID_ANY, title="", pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "PlannerFrame"):
            super(PlannerFrame, self).__init__(parent, id, title, pos, size, style, name)
            self._parent = parent
            self._title = title
            self._resources = Resources(_plannerDataDir+_ResourcesFileName)
            self._fundingSources = FundingSources(_plannerDataDir+_FundingSourcesFileName)
            self._allocations = AllocationSet(_plannerDataDir+_Allocations)

# Create MenuBar
            menuBar = wx.MenuBar()

# Create File Menu
            fileMenu = wx.Menu()
            menuExit = fileMenu.Append(wx.ID_EXIT, "E&xit"," Terminate the program")
            menuSave = fileMenu.Append(wx.ID_SAVE, "&Save", "Save Resources and Funding Sources")
            fileMenu.AppendSeparator()


# Create View Menu
            viewMenu = wx.Menu()

            PLN_RESOURCES = wx.NewId()
            PLN_FUNDINGSOURCES = wx.NewId()
            
            menuResources = viewMenu.Append(PLN_RESOURCES, "&Resources", "Bring up Resources Panel")
            menuFundingSources = viewMenu.Append(PLN_FUNDINGSOURCES, "F&unding Sources", "Bring up Funding Sources Panel")

            menuBar.Append(fileMenu, "&File")
            menuBar.Append(viewMenu, "&View")
            
            self.SetMenuBar(menuBar)
            self.CreateStatusBar()

# File Menu Items
            self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
            self.Bind(wx.EVT_MENU, self.OnSave, menuSave)

# View Menu Items            
            self.Bind(wx.EVT_MENU, self.OnResources, menuResources)
            self.Bind(wx.EVT_MENU, self.OnFundingSources, menuFundingSources)
            
            self.Show(True)

      def OnExit(self, e):
            sys.exit()

      def OnSave(self, e):
            self._resources.write()
            print "Resources Saved"
            self._fundingSources.write()
            print "Funding Sources Saved"
            
      def OnResources(self, e):
            self._resourcesWindow = SelectionListbox(self, self._resources)

      def OnFundingSources(self, e):
            self._fundingSourcesWindow = SelectionListbox(self, self._fundingSources)
    def updateEncryptionLock(self, msgid, encryption=None):
        if encryption is None:
            return

        if encryption == '':
            lock_icon_path = Resources.get('unlocked-darkgray.png')
        else:
            lock_icon_path = Resources.get('locked-green.png' if encryption == 'verified' else 'locked-red.png')
        script = "updateEncryptionLock('%s','%s')" % (msgid, lock_icon_path)
        self.executeJavaScript(script)
Exemple #8
0
 def __init__(self, window):
     QWebView.__init__(self)
     self.window = window
     with open(Resources.get_path("leftpane.js"), "r") as f:
         self.js = f.read()
     self.setFixedWidth(0)
     self.setVisible(False)
     # We don't want plugins for this simple pane
     self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
     self.setUrl(QUrl.fromLocalFile(Resources.get_path("leftpane.html")))
     self.page().currentFrame().addToJavaScriptWindowObject("leftPane", self)
     self.page().currentFrame().evaluateJavaScript(self.js)
 def word_sim(self, w1, w2, simtype):
     if (w1, w2) in AlignAndPenalize.word_cache:
         return AlignAndPenalize.word_cache[(w1, w2)]
     # context-free similarity
     if w1 == w2 or Resources.is_num_equivalent(w1, w2) or Resources.is_pronoun_equivalent(w1, w2):
         AlignAndPenalize.word_cache[(w1, w2)] = 1
         AlignAndPenalize.word_cache[(w2, w1)] = 1
         return 1
     sim = self.similarities[simtype].word_sim(w1, w2)
     if sim is None and self.fallback_similarity:
         sim = self.fallback_similarity.word_sim(w1, w2)
     elif sim is None:
         sim = 0.0
     return sim
Exemple #10
0
 def __init__(self, parent = None, settings_path = ""):
     super(ScudCloud, self).__init__(parent)
     self.setWindowTitle('ScudCloud')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('scudcloud.png'))
     self.settings = QSettings(self.settings_path + '/scudcloud.cfg', QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("scudcloud.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     self.stackedWidget = QtGui.QStackedWidget()
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.startURL = Resources.SIGNIN_URL
     if self.identifier is not None:
         self.startURL = self.domain()
     self.addWrapper(self.startURL)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(ScudCloud.minimized)
     self.installEventFilter(self)
     self.statusBar().showMessage('Loading Slack...')
Exemple #11
0
 def __init__(self, parent = None, settings_path = ""):
     super(zcswebapp, self).__init__(parent)
     self.setWindowTitle('zcswebapp')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('zcswebapp.png'))
     self.settings = QSettings(self.settings_path + '/zcswebapp.cfg', QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("zcswebapp.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     self.stackedWidget = QtGui.QStackedWidget()
     self.stackedWidget.addWidget(webView)
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(zcswebapp.minimized)
     self.installEventFilter(self)
     if self.identifier is None:
         webView.load(QtCore.QUrl(Resources.SIGNIN_URL))
     else:
         webView.load(QtCore.QUrl(self.domain()))
     webView.show()
 def set_image(self, image):
    '''
    Sets a new image for this _PictureBoxPanel to display.   If this image is
    None, a default logo will be displayed.  Any previous image that was set
    will have its Dispose() method called before it is discarded.
    '''
    
    if not image:
       image = Resources.createComicVineLogo()
    
    self._ratio = 0;
    if image and float(image.Height):
       self._ratio = float(image.Width) / float(image.Height)
    if not self._ratio:
       self._ratio =1.55
       
    # dispose the old image, if need be
    if self._picbox.Image:
       self._picbox.Image.Dispose()
       
    self._picbox.Image = image
    self.OnResize(None)
    
    # update our mouse cursor
    comicform = self.Parent
    if comicform != None:
       self.Cursor = Cursors.Hand if comicform._can_change_page(True) or \
         comicform._can_change_page(False) else None
Exemple #13
0
    def __init__(self, title, resources=None, other=None):
        self.title = title
        self.parent = None

        if resources is None:
            self.resources = Resources()
        else:
            self.resources = resources

        self.other = other

        self.wid_delete_btn = widgets.Button(description='Delete', margin="8px")
        self.wid_delete_btn._gem_ctx = self

        def yes_cb(model):
            parent = model.parent_get()
            parent.model_del(model)

        def no_cb(model):
            return

        def model_delete_cb(model_delete_cb):
            metys_confirm("Delete '%s' model, confirm it ?" % self.title, yes_cb, no_cb, self)
            return

        self.wid_delete_btn.on_click(model_delete_cb)
        wid_label = widgets.Label(value="Model:")
        self.widget = widgets.VBox(children=[
            self.resources.widget_get(), wid_label, self.wid_delete_btn])
Exemple #14
0
 def achieve_mission_found(self):
     if not self.group.resources or\
             self.group.position.village_set.count() >= NB_VILLAGES_PER_TILE\
             or self.group.resources <\
             Resources.dict_to_resources(VILLAGE_CREATION_NEEDED_RESOURCES):
         self.come_back()
         self.group.log_report(
                 type=11,
                 subject='Impossible de créer le village',
                 body='Tous les emplacements de la case'
                     ' sélectionnée sont occupés ou bien '
                     'vous ne disposez pas de suffisamment de ressources',
                 )
     v = Village(
             name="New village",
             inhabitants=self.group,
             resources=Resources.objects.create(),
             tribe=self.group.village.tribe,
             position=self.group.position,
             )
     v.resources.save()
     v.save()
     v.update_income()
     self.group.village = v
     self.group.save()
     update_resources = v.receive_resources(self.group.resources)
     update_resources.save()
     self.group.resources = update_resources
     self.group.resources -= v.receive_resources(self.group.ressources)
     self.group.resources.save()
Exemple #15
0
 def __init__(self, window):
     QWebView.__init__(self)
     self.window = window
     with open(Resources.get_path("leftpane.js"), "r") as f:
         self.js = f.read()
     # We don't want plugins for this simple pane
     self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
     self.reset()
Exemple #16
0
 def calcadjvals(self):
   self.setadjpoints()
   adjvals = []
   if self.scentview:
     for point in self.adjpoints:
       shortestdist = Resources.calcdistance(point, self.scentview[0].rect.center)
       normalizeddist = shortestdist/(self.current_scent_dist * math.sqrt(2))
       adjvals.append(1 - normalizeddist)
   return adjvals
Exemple #17
0
 def __init__(self, window):
     self.configure_proxy()
     QWebView.__init__(self)
     self.window = window
     with open(Resources.get_path("scudcloud.js"), "r") as f:
         self.js = f.read()
     self.setZoomFactor(self.window.zoom)
     self.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
     self.connect(self, SIGNAL("urlChanged(const QUrl&)"), self.urlChanged)
     self.connect(self, SIGNAL("linkClicked(const QUrl&)"), self.linkClicked)
     self.addActions()
Exemple #18
0
 def urlChanged(self, qUrl):
     url = qUrl.toString()
     # Some integrations/auth will get back to /services with no way to get back to chat
     if Resources.SERVICES_URL_RE.match(url):
         self.systemOpen(url)
         self.load(QUrl("https://"+qUrl.host()+"/messages/general"))
     else:
         self.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(Resources.get_path("login.css")))
         self.inject()
         # Save the loading team as default
         if url.endswith("/messages"):
             self.window.settings.setValue("Domain", 'https://'+qUrl.host())
Exemple #19
0
 def filter_tokens(self, tokens):
     new_tok = []
     for token in tokens:
         word = token['token']
         if self.conf.getboolean('global', 'remove_stopwords') and word in Resources.stopwords:
             continue
         if self.conf.getboolean('global', 'remove_punctuation') and word in Resources.punctuation:
             continue
         if self.conf.getboolean('global', 'filter_frequent_adverbs') and Resources.is_frequent_adverb(word, token['pos']):
             continue
         new_tok.append(token)
     return new_tok
Exemple #20
0
    def play_hangup(self):
        settings = SIPSimpleSettings()

        if settings.audio.silent:
            return

        if time.time() - self.last_hangup_tone_time > HANGUP_TONE_THROTLE_DELAY:
            hangup_tone = WavePlayer(SIPApplication.voice_audio_mixer, Resources.get('hangup_tone.wav'), volume=30)
            NotificationCenter().add_observer(self, sender=hangup_tone, name="WavePlayerDidEnd")
            SIPApplication.voice_audio_bridge.add(hangup_tone)
            hangup_tone.start()
            self.last_hangup_tone_time = time.time()
    def showMessage(self, call_id, msgid, direction, sender, icon_path, text, timestamp, is_html=False, state='', recipient='', is_private=False, history_entry=False, media_type='chat', encryption=None):
        lock_icon_path = ''
        if encryption is not None:
            if encryption == '':
                lock_icon_path = Resources.get('unlocked-darkgray.png')
            else:
                lock_icon_path = Resources.get('locked-green.png' if encryption == 'verified' else 'locked-red.png')

        if not history_entry and not self.delegate.isOutputFrameVisible():
            self.delegate.showChatViewWhileVideoActive()

        # keep track of rendered messages to toggle the smileys or search their content later
        rendered_message = ChatMessageObject(call_id, msgid, text, is_html, timestamp, media_type)
        self.rendered_messages.append(rendered_message)

        if timestamp.date() != datetime.date.today():
            displayed_timestamp = time.strftime("%F %T", time.localtime(calendar.timegm(timestamp.utctimetuple())))
        else:
            displayed_timestamp = time.strftime("%T", time.localtime(calendar.timegm(timestamp.utctimetuple())))

        text = processHTMLText(text, self.expandSmileys, is_html)
        private = 1 if is_private else "null"

        if is_private and recipient:
            label = 'Private message to %s' % cgi.escape(recipient) if direction == 'outgoing' else 'Private message from %s' % cgi.escape(sender)
        else:
            if hasattr(self.delegate, "sessionController"):
                label = cgi.escape(self.delegate.sessionController.nickname or self.account.display_name or self.account.id) if sender is None else cgi.escape(sender)
            else:
                label = cgi.escape(self.account.display_name or self.account.id) if sender is None else cgi.escape(sender)

        script = """renderMessage('%s', '%s', '%s', '%s', "%s", '%s', '%s', %s, '%s')""" % (msgid, direction, label, icon_path, text, displayed_timestamp, state, private, lock_icon_path)

        if self.finishedLoading:
            self.executeJavaScript(script)
        else:
            self.messageQueue.append(script)

        if hasattr(self.delegate, "chatViewDidGetNewMessage_"):
            self.delegate.chatViewDidGetNewMessage_(self)
Exemple #22
0
    def init_configurations(self):
        account_manager = AccountManager()
        settings = SIPSimpleSettings()

        self.notification_center.add_observer(self, sender=settings)

        # fixup default account
        self._selected_account = account_manager.default_account
        if self._selected_account is None:
            self._selected_account = account_manager.get_accounts()[0]

        default_ca = open(Resources.get('ca.crt'), "r").read().strip()
        self.set_default_certificate_authority(default_ca)
Exemple #23
0
 def filter_tokens(self, tokens):
     new_tok = []
     for token in tokens:
         word = token["token"]
         if self.conf.getboolean("global", "remove_stopwords") and word in Resources.stopwords:
             continue
         if self.conf.getboolean("global", "remove_punctuation") and word in Resources.punctuation:
             continue
         if self.conf.getboolean("global", "filter_frequent_adverbs") and Resources.is_frequent_adverb(
             word, token["pos"]
         ):
             continue
         new_tok.append(token)
     return new_tok
Exemple #24
0
	def __init__( self, name, parent ):
		StateNode.__init__( self, name, parent, initialState = System.STATE_STOPPED )
		self.log = Logger().get_instance( self.__class__.__name__ )

		self.config = Configuration( 'config', self )
		self.config.addListener( self )

		self.network = MessageAdapter( 'msg_net', self )
		self.network.addListener( self )

		self.resources = Resources( 'resources', self )
		self.resources.addListener( self )

		self.addListener( parent )
Exemple #25
0
 def __init__(self, window):
     self.configure_proxy()
     QWebView.__init__(self)
     self.window = window
     with open(Resources.get_path("scudcloud.js"), "r") as f:
         self.js = f.read()
     self.setZoomFactor(self.window.zoom)
     self.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
     self.urlChanged.connect(self._urlChanged)
     self.loadStarted.connect(self._loadStarted)
     self.loadFinished.connect(self._loadFinished)
     self.linkClicked.connect(self._linkClicked)
     self.page().featurePermissionRequested.connect(self.permissionRequested)
     self.addActions()
Exemple #26
0
 def take_resources(self, village_or_group, resources_dict):
     """
     Substract the max resources up to resources_dict content to the
     village_or_group’s resources and set it in a new resources object
     which is returned
     """
     for key in resources_dict:
         resources_dict[key] = max(resources_dict[key], 0)
     available_resources = village_or_group.resources
     wanted_resources = Resources.dict_to_resources(resources_dict)
     if available_resources >= wanted_resources:
         available_resources -= wanted_resources
         available_resources.save()
         wanted_resources.save()
         return wanted_resources
     else:
         received_resources = Resources()
         for key in wanted_resources:
             amount = min(wanted_resources[key], available_resources[key])
             received_resources[key] = amount
             available_resources -= amount
         available_resources.save()
         received_resources.save()
         return received_resources()
Exemple #27
0
def main():
      
      root = Tk()
      root.geometry("250x150+300+300")
      sl = Resources("/users/swiftb/dev/Planner/data/testresources.txt")
      res = Resource("{'UID': '1', 'First Name': 'Brian', 'Last Name': 'Swift', 'Location': 'CHI'}")
      sl.add(res)
      res = Resource("{'UID': '2', 'First Name': 'John', 'Last Name': 'DeValk', 'Location': 'CHI'}")
      sl.add(res)
      sl.write()
      print sl._resources
      
      mc = SelectionListbox(root, sl)
      root.mainloop()
Exemple #28
0
    def init_configurations(self):
        account_manager = AccountManager()
        settings = SIPSimpleSettings()

        # fixup default account
        self._selected_account = account_manager.default_account
        if self._selected_account is None:
            self._selected_account = account_manager.get_accounts()[0]

        # save default ca if needed
        ca = open(Resources.get('ca.crt'), "r").read().strip()
        try:
            X509Certificate(ca)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid Certificate Authority: %s" % e)
            return
Exemple #29
0
def main():
      
      app = wx.App()

      ress = Resources("/users/swiftb/dev/Planner/data/testresources.txt")
      res = Resource("{'UID': '1', 'First Name': 'Brian', 'Last Name': 'Swift', 'Location': 'CHI'}")
      ress.add(res)
      res = Resource("{'UID': '2', 'First Name': 'John', 'Last Name': 'DeValk', 'Location': 'CHI'}")
      ress.add(res)
      ress.write()
      print ress._resources
      
      mc = SelectionFrame(None, ress)
      app.MainLoop()
Exemple #30
0
 def urlChanged(self, qUrl):
     url = qUrl.toString()
     # Some integrations/auth will get back to /services with no way to get back to chat
     if Resources.SERVICES_URL_RE.match(url):
         self.systemOpen(url)
         self.load(QUrl("https://"+qUrl.host()+"/messages/general"))
     else:
         self.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(Resources.get_path("login.css")))
         self.page().currentFrame().addToJavaScriptWindowObject("desktop", self)
         boot_data = self.page().currentFrame().evaluateJavaScript(self.js)
         self.window.quicklist(boot_data['channels'])
         self.window.teams(boot_data['teams'])
         self.window.enableMenus(self.isConnected())
         # Save the loading team as default
         if url.endswith("/messages"):
             self.window.settings.setValue("Domain", 'https://'+qUrl.host())
Exemple #31
0
class House(Building):
    cost = Resources({Wood: 100})
    size = (2, 2)
    letter_abbreviation = 'H'
    kind = 'house'
    time_to_build = 30
Exemple #32
0
            cleanup_resources(cloud, cleanup, dry_run=False)


if __name__ == '__main__':

    parser = create_parser()
    args = parser.parse_args()

    pp = pprint.PrettyPrinter(indent=4)
    now = datetime.datetime.now(pytz.utc)

    set_logging(args.debug)

    cloud = initialize_cloud(args.cloud)

    resources = Resources(cloud)

    if args.floatingips:
        resources.select_floatingips_unattached()
        cleanup = resources.get_selection()
        do_cleanup(cloud, cleanup, pp, args)
        resources = Resources(cloud)

    if args.old_instances:
        resources = select_oldest(cloud, args)
        cleanup = resources.get_selection()
        do_cleanup(cloud, cleanup, pp, args)
        resources = Resources(cloud)

    if args.unused:
        resources.select_resources('')
Exemple #33
0
        print("  " + str(mech))
        mech_list.append(mech)

# sort list alphabetically by name
mech_list = sorted(mech_list, key=lambda x: x.name)

# director must be initialized before any cocos elements can be created
director.init(width=1024, height=768, resizable=True, autoscale=False)
director.show_FPS = True

# initialize the audio mixer
pygame.mixer.init(44100, -16, 2, 2048)
pygame.mixer.set_num_channels(32)

# preload all sound and image resources
Resources.preload()


# setup custom mouse cursor
cursor = pyglet.window.ImageMouseCursor(Resources.mouse_pointer, 1, 17)
director.window.set_mouse_cursor(cursor)

board = Board()
battle = Battle()
ui = Interface()
battle.setBoard(board)
key_events = events.KeyboardEvents(battle)
mouse_events = events.MouseEvents(battle)

# set up test players
player = Player("Human", team=0)
Exemple #34
0
class Area:
    def __init__(self):
        self.resources = Resources()
        self.number_of_tiles = 10
        self.tile_size = self.resources.floor_size
        self.size = self.tile_size * self.number_of_tiles
        self.tiles = []
        self.floors = []
        self.walls = []
        self.turn_count = 0

    def create_map(self):
        self.random_map()
        self.tiles = []
        for i in range(self.number_of_tiles):
            for j in range(self.number_of_tiles):
                tile = []
                position = j * self.number_of_tiles + i
                if position in self.walls:
                    tile.append(Wall())
                else:
                    tile.append(Floor())
                tile.append(position)
                x = self.tile_size * j
                y = self.tile_size * i
                tile[0].x = x
                tile[0].y = y
                tile.append([x, y])
                self.tiles.append(tile)

    def draw_map(self, canvas):
        self.create_map()
        for tile in self.tiles:
            if isinstance(tile[0], Floor):
                img = self.resources.get_image('floor')
            elif isinstance(tile[0], Wall):
                img = self.resources.get_image('wall')
            canvas.create_image(tile[2][1], tile[2][0], anchor=NW, image=img)

    def draw_character(self, canvas, character):
        if isinstance(character, Monster):
            img = self.resources.get_image(character.__class__.__name__)
        else:
            img = self.resources.get_image(character.direction)
        y = character.y
        x = character.x
        canvas.create_image(x, y, anchor=NW, image=img, tag=character.name)

    def increase_turn_count(self):
        self.turn_count += 1

    def random_map(self):
        self.floors = []
        self.walls = []
        self.floors.append(0)
        for i in range(1, self.number_of_tiles**2):
            random = randrange(0, 10)
            if random < randrange(3, 7):  # varying wall count
                self.walls.append(i)
            else:
                self.floors.append(i)
        self.connect_map()

    def connect_map(self):
        unseen = self.walls + self.floors
        seen = [0]
        been = [0]
        unseen.remove(0)
        self.see_neighbours(0, unseen, seen)
        self.check_seen(unseen, seen, been)
        while len(set(self.floors)) != len(set(been)):
            self.check_unseen(unseen, seen, been)
            self.check_seen(unseen, seen, been)
        if len(self.floors) < 6:  # max characters
            self.random_map()

    def see_neighbours(self, tile, unseen, seen):
        if tile - 1 in unseen and tile % self.number_of_tiles != 0:
            self.see(tile - 1, unseen, seen)
        if tile + 1 in unseen and (tile + 1) % self.number_of_tiles != 0:
            self.see(tile + 1, unseen, seen)
        if tile - self.number_of_tiles in unseen:
            self.see(tile - self.number_of_tiles, unseen, seen)
        if tile + self.number_of_tiles in unseen:
            self.see(tile + self.number_of_tiles, unseen, seen)

    def see(self, tile, unseen, seen):
        seen.append(tile)
        unseen.remove(tile)

    def check_seen(self, unseen, seen, been):
        for tile in seen:
            if tile in self.floors and tile not in been:
                been.append(tile)
                self.see_neighbours(tile, unseen, seen)

    def check_unseen(self, unseen, seen, been):
        unseen_floors = list(set(unseen).intersection(set(self.floors)))
        counter = 1
        for tile in unseen_floors:
            if (tile - 2 in been and tile - 1 in self.walls
                    and tile - 1 in seen):
                self.break_wall(tile - 1)
                return
            elif (tile - (2 * self.number_of_tiles) in been
                  and tile - self.number_of_tiles in self.walls
                  and tile - self.number_of_tiles in seen):
                self.break_wall(tile - self.number_of_tiles)
                return
            elif (tile + 2 in been and tile + 1 in self.walls
                  and tile + 1 in seen):
                self.break_wall(tile + 1)
                return
            elif (tile + (2 * self.number_of_tiles) in been
                  and tile + self.number_of_tiles in self.walls
                  and tile + self.number_of_tiles in seen):
                self.break_wall(tile + self.number_of_tiles)
                return
            elif (tile - 1 - self.number_of_tiles in been
                  and tile - 1 in self.walls
                  and tile - self.number_of_tiles in self.walls
                  and tile - 1 in seen):
                self.break_wall(tile - 1)
                return
            elif (tile - 1 + self.number_of_tiles in been
                  and tile - 1 in self.walls
                  and tile + self.number_of_tiles in self.walls
                  and tile - 1 in seen):
                self.break_wall(tile - 1)
                return
            elif (tile + 1 - self.number_of_tiles in been
                  and tile + 1 in self.walls
                  and tile - self.number_of_tiles in self.walls
                  and tile + 1 in seen):
                self.break_wall(tile + 1)
                return
            elif (tile + 1 + self.number_of_tiles in been
                  and tile + 1 in self.walls
                  and tile + self.number_of_tiles in self.walls
                  and tile + 1 in seen):
                self.break_wall(tile + 1)
                return
            else:
                if counter == len(unseen_floors):
                    self.make_wall(tile)
                    return
                else:
                    counter += 1
                    continue

    def break_wall(self, tile_between):
        self.walls.remove(tile_between)
        self.floors.append(tile_between)

    def make_wall(self, tile):
        self.walls.append(tile)
        self.floors.remove(tile)
    def start(self, screen):
        if not self.already_loaded:
            PenData.load_all_pens(Resources.get("all_pens"))

            width = screen.get_width()
            height = screen.get_height()

            self.back_btn = Button(
                pygame.Rect(10, 10, 60, 40), "Back", {
                    Options.BORDER_WIDTH: 0,
                    Options.BACKGROUND: (20, 61, 89),
                    Options.FOREGROUND: (244, 180, 26),
                    Options.HOVERED_BACKGROUND: (10, 30, 45),
                    Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
                })

            label_options = {
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.BORDER_WIDTH: 0,
            }
            self.header = Label(pygame.Rect(width / 2 - 200, 10, 400, 30),
                                "Select your weapon!", label_options)
            self.coins_text = Label(
                pygame.Rect(width - 110, height - 55, 100, 40), "0",
                label_options)

            label_options = {
                Options.BACKGROUND: (82, 173, 200),
                Options.FOREGROUND: (20, 61, 89),
                Options.BORDER_WIDTH: 0,
                Options.FONT: pygame.font.SysFont("Comic Sans MS", 18)
            }
            self.density_text = Label(pygame.Rect(width / 5, 110, 100, 20),
                                      "Density: ", label_options)
            self.restitution_text = Label(pygame.Rect(width / 5, 130, 100, 20),
                                          "Restitution: ", label_options)

            self.name_text = Label(
                pygame.Rect(width / 2 - 45, height - 125, 90, 50), "",
                label_options)
            self.description_lines = [
                Label(pygame.Rect(width * 2 / 3, 100 + i * 25, 100, 20), "",
                      label_options) for i in range(0, 3)
            ]

            self.coins_image = Image(
                pygame.Rect(width - 175, height - 60, 50, 50),
                Resources.get("coin"), {Options.BACKGROUND: (82, 173, 200)})

            btn_options = {
                Options.BORDER_WIDTH: 0,
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.FONT: pygame.font.SysFont("Comic Sans MS", 25)
            }
            self.left_btn = Button(pygame.Rect(10, height / 2 - 20, 20, 30),
                                   "<", btn_options)
            self.right_btn = Button(
                pygame.Rect(width - 30, height / 2 - 20, 20, 30), ">",
                btn_options)
            self.select_btn = Button(
                pygame.Rect(width / 2 - 45, height - 75, 90, 50), "Select",
                btn_options)
            self.purchase_btn = Button(
                pygame.Rect(width / 2 - 125, height - 75, 250, 40), "",
                btn_options)

            self.center_pos = pygame.Rect(width / 2 - 50, height / 2 - 50, 100,
                                          100)
            for pen in PenData.all_pens:
                self.pen_images.append(
                    Image(self.center_pos, Resources.get(pen.image_file),
                          {Options.BACKGROUND: (82, 173, 200)}))

            self.already_loaded = True

        self.reposition_images()
        self.update_shop_data()
        self.reset_coin_text()
    def showMessage(self,
                    call_id,
                    msgid,
                    direction,
                    sender,
                    icon_path,
                    content,
                    timestamp,
                    is_html=False,
                    state='',
                    recipient='',
                    is_private=False,
                    history_entry=False,
                    media_type='chat',
                    encryption=None):
        lock_icon_path = Resources.get('unlocked-darkgray.png')
        if encryption is not None:
            if encryption == '':
                lock_icon_path = Resources.get('unlocked-darkgray.png')
            else:
                lock_icon_path = Resources.get(
                    'locked-green.png' if encryption ==
                    'verified' else 'locked-red.png')

        if self.last_sender == sender:
            icon_path = "null"
        else:
            icon_path = "'%s'" % icon_path

        self.last_sender = sender

        if not history_entry and not self.delegate.isOutputFrameVisible():
            self.delegate.showChatViewWhileVideoActive()

        # keep track of rendered messages to toggle the smileys or search their content later
        rendered_message = ChatMessageObject(call_id, msgid, content, is_html,
                                             timestamp, media_type)
        self.rendered_messages.append(rendered_message)

        if timestamp.date() != datetime.date.today():
            displayed_timestamp = time.strftime(
                "%F %H:%M",
                time.localtime(calendar.timegm(timestamp.utctimetuple())))
        else:
            displayed_timestamp = time.strftime(
                "%H:%M",
                time.localtime(calendar.timegm(timestamp.utctimetuple())))

        content = processHTMLText(content, self.expandSmileys, is_html)
        private = 1 if is_private else "null"

        if is_private and recipient:
            label = NSLocalizedString(
                "Private message to %s", "Label") % html.escape(
                    recipient
                ) if direction == 'outgoing' else NSLocalizedString(
                    "Private message from %s", "Label") % html.escape(sender)
        else:
            if hasattr(self.delegate, "sessionController"):
                label = html.escape(
                    self.delegate.sessionController.nickname
                    or self.account.display_name or
                    self.account.id) if sender is None else html.escape(sender)
            else:
                label = html.escape(
                    self.account.display_name or
                    self.account.id) if sender is None else html.escape(sender)

        try:
            script = """renderMessage('%s', '%s', '%s', %s, "%s", '%s', '%s', %s, '%s', '%s')""" % (
                msgid, direction, label, icon_path, content,
                displayed_timestamp, state, private, lock_icon_path,
                self.previous_msgid)
        except UnicodeDecodeError:
            script = """renderMessage('%s', '%s', '%s', %s, "%s", '%s', '%s', %s, '%s', '%s')""" % (
                msgid, direction, label, icon_path, content.decode('utf-8'),
                displayed_timestamp, state, private, lock_icon_path,
                self.previous_msgid)
        except Exception as e:
            self.delegate.showSystemMessage(
                "Chat message id %s rendering error: %s" % (msgid, e),
                ISOTimestamp.now(), True)
            return

        if self.finishedLoading:
            self.executeJavaScript(script)
        else:
            self.messageQueue.append(script)

        if hasattr(self.delegate, "chatViewDidGetNewMessage_"):
            self.delegate.chatViewDidGetNewMessage_(self)

        self.previous_msgid = msgid
Exemple #37
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        Resources.load(os.getcwd(), ["icons", "xhtml"],
                       icon_driver=QtGui.QIcon)

        self.tabs = dict()
        """:type: dict from str to QtGui.QWidget"""

        self.tabs_stack = None
        """:type: QStackedWidget"""

        self.window_layout = None
        """:type: QtGui.QLayout"""

        self.controls_view = None
        """:type: ControlsView"""

        self.about_window = None
        """:type: AboutWindow"""

        self.dbparser = None
        """:type: GenericParser"""

        self.appdb = None
        """:type: database.ApplicationDatabase"""

        self.plugins = None
        """:type: plugins.Container"""

        self.my_state = None
        self.my_geometry = None

        self.resize(1080, 760)
        self.center()

        try:
            config.openLayerMapConfig(config.Configuration.layer_map_path)
        except config.LayerMapConfig.ParseError:
            ErrorBox(
                self, "Can't parse '%s' GDSII layer mapping file!" %
                config.Configuration.layer_map_path)
            sys.exit(-1)

        self.configure_dbparser()
        self.configure_database()
        self.configure_plugins()
        self.configure_windows()

        self.appconfig = AppConfigurationView(self)

        # Create initial options object
        self.options = options.Options.default()

        self.core = core.Core(self.options)

        connect(self.options.changed, self.setApplicationTitle)
        self.setApplicationTitle()
        self.setWindowIcon(QtGui.QIcon("icons/Logo.png"))

        self.configure_controls()
        self.configure_window_state()

        logging.info("Configure status bar")
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)
        self.statusBar().showMessage("Ready")

        self.state_changed = False

        logging.info("Configuration done")

        logging.info("Loading options")
        if len(sys.argv) > 1:
            path = sys.argv[1]
            self._open_options(path)

        self.show()
Exemple #38
0
    # Generate a textual FST
    txt_fst = make_bigram_lm_fst(kaldi_seq, **kwargs)
    txt_fst_file = tempfile.NamedTemporaryFile(delete=False)
    txt_fst_file.write(txt_fst)
    txt_fst_file.close()

    hclg_filename = tempfile.mktemp(suffix='_HCLG.fst')
    try:
        devnull = open(os.devnull, 'wb')
        subprocess.check_output(
            [MKGRAPH_PATH, proto_langdir, txt_fst_file.name, hclg_filename],
            stderr=devnull)
    except Exception, e:
        try:
            os.unlink(hclg_filename)
        except:
            pass
        raise e
    finally:
        os.unlink(txt_fst_file.name)

    return hclg_filename


if __name__ == '__main__':
    import sys
    make_bigram_language_model(
        open(sys.argv[1]).read(),
        Resources().proto_langdir)
Exemple #39
0
from resources import Resources
from activity.draw import DrawActivity
from activity.wish import WishActivity
from activity.consecrate import ConsecrateActivity
from shop import Shop
from common import *
import numpy as np

if __name__ == "__main__":
    res = Resources()
    res.whiteTadpole = 10000
    res.drawVoucher = 350
    res.wishCoin = 90
    res.consecrateTime = time(6, 0, 0)
    res.consecrateTimeSpeedUpRatio = time(0, 6, 30) / time(0, 8, 0)

    shop = Shop()
    drawAct = DrawActivity()
    wishAct = WishActivity()
    consecrateAct = ConsecrateActivity()

    activities = [drawAct, wishAct, consecrateAct]

    # DP
    dp_dict = dict() # code -> (res, score)

    idx = 0
    for act in activities:
        idx += 1
        print("--------------------------", idx, "--------------------------")
Exemple #40
0
async def consumer_handler(websocket, _path):
    async for message in websocket:
        try:
            data = json.loads(message,
                              object_hook=lambda d: SimpleNamespace(**d))
            if hasattr(data, "myColor"):
                global PLAYER_COLOR
                PLAYER_COLOR = data.myColor
            elif hasattr(data, "tileState"):  # Board information
                global BOARD
                BOARD = Board(data)
                BOT = NaiveBot(BOARD, PLAYER_COLOR, QUEUE)
            elif hasattr(data, "currentTurnState"):  # Game state information
                global GAME_STATE

                if data.currentTurnState == 1 and data.currentTurnPlayerColor != PLAYER_COLOR:
                    GAME_STATE = GameState.OPPONENT_TURN

                if data.currentTurnPlayerColor == PLAYER_COLOR:
                    # need to be outside the currentTurnState ifs,
                    # because it can happen in both turnstate 1 and 2
                    if data.currentActionState == 23:
                        BOT.move_robber()
                    elif data.currentActionState == 27:
                        asyncio.create_task(BOT.use_road_building())
                    # elif data.currentActionState == 28:
                    #     BOT.handle_event(ColEvents.ROAD_BUILDING)
                    elif data.currentActionState == 29:
                        asyncio.create_task(BOT.use_year_of_plenty())
                    elif data.currentActionState == 30:
                        asyncio.create_task(BOT.use_monopoly())

                    if data.currentTurnState == 0:
                        if data.currentActionState == 1 and \
                           GAME_STATE == GameState.SETUP_SETTLEMENT:
                            BOT.build_setup_settlement()
                            GAME_STATE = GameState.SETUP_ROAD
                        if data.currentActionState == 3 and GAME_STATE == GameState.SETUP_ROAD:
                            BOT.build_setup_road()
                            if len(BOARD.own_settlements) < 2:
                                GAME_STATE = GameState.SETUP_SETTLEMENT
                            else:
                                GAME_STATE = GameState.OPPONENT_TURN
                    if data.currentTurnState == 1:
                        if data.currentActionState == 0 and GAME_STATE == GameState.OPPONENT_TURN:
                            GAME_STATE = GameState.START_TURN
                            asyncio.create_task(BOT.start_turn())
                    if data.currentTurnState == 2:
                        if GAME_STATE == GameState.START_TURN:
                            GAME_STATE = GameState.PLAYER_TURN
                            asyncio.create_task(BOT.play_turn())
            # TODO: remember the player next to tile we place robber on
            # so we can do the logic on the turn logic package
            elif hasattr(data, "allowableActionState"):
                print("hasattr(data, \"allowableActionState\"")
                if data.allowableActionState == 24:
                    print("data.allowableActionState == 24")
                    BOT.rob(data.playersToSelect)
            elif hasattr(data, "selectCardFormat"):
                amount = data.selectCardFormat.amountOfCardsToSelect
                BOT.discard_cards(amount)
            elif hasattr(data, "givingPlayer"):  # Trade information
                if data.givingPlayer == PLAYER_COLOR:
                    for card in data.givingCards:
                        BOARD.resources[Resources(card)] -= 1
                    for card in data.receivingCards:
                        BOARD.resources[Resources(card)] += 1
                if data.receivingPlayer == PLAYER_COLOR:
                    for card in data.givingCards:
                        if card >= 1 and card <= 5:
                            BOARD.resources[Resources(card)] += 1
                        else:
                            BOARD.own_dev_cards[DevCards(card)] += 1
                    for card in data.receivingCards:
                        BOARD.resources[Resources(card)] -= 1
                BOT.handle_event(ColEvents.RECEIVED_CARDS)
            elif hasattr(data, "offeredResources"):  # Active trade offer
                # Check if we're allowed to take this trade and have to respond
                for player_actions in data.actions:
                    if player_actions.player == PLAYER_COLOR:
                        if len(player_actions.allowedTradeActions) > 1:
                            # Respond to trade offer
                            BOT.respond_to_trade(data)
                        break
            elif hasattr(data, "resourceCards"):
                for resource in Resources:
                    BOARD.bank_resources[resource] = data[
                        "resourceCards"].count(resource.value)
            # Settlement update (probably upgrading to a city works the same)
            elif isinstance(data, list) and hasattr(data[0], "hexCorner"):
                update_vertex(data[0])
                BOT.handle_event(ColEvents.VERTEX_CHANGED)
            elif isinstance(data, list) and hasattr(data[0], "hexEdge"):
                update_edge(data[0])
                BOT.handle_event(ColEvents.EDGE_CHANGED)
            # Cards being handed out
            elif isinstance(data, list) and hasattr(data[0], "owner"):
                for entry in data:
                    if entry.owner == PLAYER_COLOR:
                        # TODO: fix for cities, probably can just increment with distribitionType
                        BOARD.resources[Resources(entry.card)] += 1
            # Robber move information
            elif isinstance(data, list) and hasattr(data[0], "tilePieceTypes"):
                new_robber_tile = data[1]
                loc = new_robber_tile.hexFace
                BOARD.robber_tile = BOARD.find_tile_index_by_coordinates(
                    loc.x, loc.y)
                print("New robber_tile: {0}".format(BOARD.robber_tile))
                BOT.handle_event(ColEvents.ROBBER_MOVED)
        except:
            pass
Exemple #41
0
def main():
    Resources()
    game = Game((1280, 720), "Triggered")
    game.run()
Exemple #42
0
 def loadStarted(self):
     # Some custom CSS to clean/fix UX
     self.settings().setUserStyleSheetUrl(
         QUrl.fromLocalFile(Resources.get_path("resources.css")))
Exemple #43
0
    def load_assets(self):
        # Load the circle loading animation
        Resources.add("loading", pygame.image.load("assets/loading.png"))
        self.circle_image = Resources.get("loading")

        # Load the settings gear icon
        Resources.add("gear", pygame.image.load("assets/gear.png"))

        # Load the close icon
        Resources.add("close", pygame.image.load("assets/close.png"))

        # Load the coin image
        Resources.add("coin", pygame.image.load("assets/coin.png"))

        # Load the random pen image
        Resources.add("random_pen", pygame.image.load("assets/random_pen.png"))

        # Load the pen data and images
        Resources.add("all_pens", Resources.load_text("assets/pens.json"))
        Resources.add("pencil", pygame.image.load("assets/pencil.png"))
        Resources.add("ball_pen", pygame.image.load("assets/ball_pen.png"))
        Resources.add("blue_gel_pen", pygame.image.load("assets/blue_gel_pen.png"))
        Resources.add("black_gel_pen", pygame.image.load("assets/black_gel_pen.png"))
        Resources.add("mech_pencil", pygame.image.load("assets/mech_pencil.png"))
        Resources.add("marker", pygame.image.load("assets/marker.png"))

        self.loaded = True
Exemple #44
0
#!/usr/bin/env python
__author__ = 'SuturkinAA'

import os
import sys
from resources import Resources
from config import Config

global res

def setRestPort(resrPort):
    listener = '0.0.0.0:'+str(resrPort)
    if (len(sys.argv)==1):
        sys.argv.append("runserver")
        sys.argv.append(listener)

config = Config();
config.load()

res = Resources(config.resourcesMax);
setRestPort(config.restPort)

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rest.settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

print ("Started.")
Exemple #45
0
                        if sib == action.argv[0]:
                            reentr_dataset.write(str(1) + "\n")
                        else:
                            reentr_dataset.write(str(2) + "\n")


if __name__ == "__main__":
    argparser = argparse.ArgumentParser()
    argparser.add_argument("-t", "--train", help="Training set", required=True)
    argparser.add_argument("-v",
                           "--valid",
                           help="Validation set",
                           required=True)
    argparser.add_argument(
        "-m",
        "--modeldir",
        help="Directory used to save the model being trained",
        required=True)
    argparser.add_argument("-l", "--lang", help="Language", default="en")

    try:
        args = argparser.parse_args()
    except:
        argparser.error("Invalid arguments")
        sys.exit(0)

    Resources.init_table(args.modeldir, False)
    create(args.train, "train", args.lang, args.modeldir)
    create(args.valid, "valid", args.lang, args.modeldir)
    print "Done"
Exemple #46
0
    def configure_controls(self):
        logging.info("Configure window controls")
        controls_data = [
            ControlsView.ControlData(
                name="File",
                text="&File",
                actions=[
                    ControlBar.ActionData(name="New",
                                          text="&New",
                                          icon=Resources("icons/NewFile"),
                                          callback=self.new_options,
                                          status_tip="Create a new document",
                                          shortcut="Ctrl+N"),
                    ControlBar.ActionData(
                        name="Open",
                        text="&Open",
                        icon=Resources("icons/Open"),
                        callback=self.load_options,
                        status_tip="Open an existing document",
                        shortcut="Ctrl+O"),
                    ControlBar.ActionData(
                        name="Save",
                        text="&Save",
                        icon=Resources("icons/Save"),
                        callback=self.save_options,
                        status_tip="Save the active document"),
                    ControlBar.ActionData(
                        name="SaveAs",
                        text="Save As ...",
                        callback=self.save_options_as,
                        status_tip="Save the active document with a new name"),
                    None,
                    ControlBar.ActionData(
                        name="Preferences",
                        text="&Preferences",
                        callback=self.appconfig.exec_,
                        icon=Resources("icons/Preferences"),
                        status_tip="Edit preferences settings"),
                    None,
                    ControlBar.ActionData(
                        name="Print",
                        text="Print...",
                        callback=self.onPrint,
                        status_tip="Print the active document",
                        shortcut="Ctrl+P"),
                    ControlBar.ActionData(
                        name="PrintPreview",
                        text="Print Preview",
                        callback=self.onPrintPreview,
                        status_tip="Display a preview of the report"),
                    ControlBar.ActionData(
                        name="PrintSetup",
                        text="Print Setup...",
                        # callback=self.onPageSetup,
                        status_tip="Change the printer and printing options"),
                    None,
                    ControlBar.ActionData(
                        name="Exit",
                        text="&Exit",
                        icon=Resources("icons/Exit"),
                        callback=self.close,
                        status_tip=
                        "Quit the application; prompts to save document",
                        shortcut="Ctrl+Q")
                ]),
            ControlsView.ControlData(
                name="View",
                text="&View",
                actions=[
                    ControlBar.ActionData(name="Database",
                                          text="&Database",
                                          icon=Resources("icons/Database"),
                                          callback=self.changeStackView,
                                          status_tip="%s database storage" %
                                          config.APPLICATION_NAME),
                    ControlBar.ActionData(
                        name="Queue",
                        text="&Queue",
                        icon=Resources("icons/Queue"),
                        status_tip="Show the sim_region queue window"),
                    ControlBar.ActionData(
                        name="Warnings",
                        text="&Warnings",
                        status_tip="Show the warning list window")
                ]),
            ControlsView.ControlData(
                name="Parameters",
                text="&Parameters",
                actions=[
                    ControlBar.ActionData(name="Numerics",
                                          text="&Numerics",
                                          icon=Resources("icons/Numerics"),
                                          callback=self.changeStackView,
                                          status_tip="Numerics"),
                    ControlBar.ActionData(name="WaferProcesses",
                                          text="&Wafer Processes",
                                          icon=Resources("icons/WaferStack"),
                                          callback=self.changeStackView,
                                          status_tip="Wafer Processes"),
                    ControlBar.ActionData(name="Resist",
                                          text="&Resist",
                                          icon=Resources("icons/Resist"),
                                          callback=self.changeStackView,
                                          status_tip="Resist"),
                    ControlBar.ActionData(name="CoatAndPrebake",
                                          text="&Coat and prebake",
                                          callback=self.changeStackView,
                                          status_tip="Coat and prebake"),
                    ControlBar.ActionData(name="Mask",
                                          text="&Mask",
                                          icon=Resources("icons/Mask"),
                                          callback=self.changeStackView,
                                          status_tip="Mask"),
                    ControlBar.ActionData(name="ImagingTool",
                                          text="&Imaging Tool",
                                          icon=Resources("icons/ImagingTool"),
                                          callback=self.changeStackView,
                                          status_tip="Imaging Tool"),
                    ControlBar.ActionData(
                        name="ExposureAndFocus",
                        text="&Exposure and Focus",
                        icon=Resources("icons/ExposureAndFocus"),
                        callback=self.changeStackView,
                        status_tip="Exposure and Focus"),
                    ControlBar.ActionData(name="PostExposureBake",
                                          text="&Post Exposure Bake",
                                          icon=Resources("icons/PEB"),
                                          callback=self.changeStackView,
                                          status_tip="Post Exposure Bake"),
                    ControlBar.ActionData(name="Development",
                                          text="&Development",
                                          icon=Resources("icons/Development"),
                                          callback=self.changeStackView,
                                          status_tip="Development"),
                    ControlBar.ActionData(name="Metrology",
                                          text="M&etrology",
                                          icon=Resources("icons/Metrology"),
                                          callback=self.changeStackView,
                                          status_tip="Metrology"),
                    ControlBar.ActionData(name="Summary",
                                          text="&Summary",
                                          icon=Resources("icons/Summary"),
                                          callback=self.changeStackView,
                                          status_tip="Summary")
                ]),
            ControlsView.ControlData(
                name="Simulation",
                text="&Simulations",
                actions=[
                    ControlBar.ActionData(
                        name="DiffractionPattern",
                        text="&Diffraction Pattern",
                        icon=Resources("icons/DiffractionPattern"),
                        callback=self.changeStackView,
                        status_tip="Diffraction Pattern"),
                    ControlBar.ActionData(name="AerialImage",
                                          text="&Aerial Image",
                                          icon=Resources("icons/AerialImage"),
                                          callback=self.changeStackView,
                                          status_tip="Aerial Image"),
                    ControlBar.ActionData(
                        name="ImageInResist",
                        text="&Image in Resist",
                        icon=Resources("icons/ImageInResist"),
                        callback=self.changeStackView,
                        status_tip="Image in Resist"),
                    ControlBar.ActionData(name="ExposedLatentImage",
                                          text="&Exposed Latent Image",
                                          icon=Resources("icons/LatentImage"),
                                          callback=self.changeStackView,
                                          status_tip="Exposed Latent Image"),
                    ControlBar.ActionData(
                        name="PEBLatentImage",
                        text="&PEB Latent Image",
                        icon=Resources("icons/PostBakeImage"),
                        callback=self.changeStackView,
                        status_tip="PEB Latent Image"),
                    ControlBar.ActionData(
                        name="DevelopTimeContours",
                        text="&Develop Time Contours",
                        icon=Resources("icons/DevelopTimeContours"),
                        callback=self.changeStackView,
                        status_tip="Develop Time Contours"),
                    ControlBar.ActionData(
                        name="ResistProfile",
                        text="&Resist Profile",
                        icon=Resources("icons/ResistProfile"),
                        callback=self.changeStackView,
                        status_tip="Resist Profile"), None,
                    ControlBar.ActionData(
                        name="SimulationSets",
                        text="&Simulation Sets",
                        icon=Resources("icons/SimulationSets"),
                        callback=self.changeStackView,
                        status_tip="Simulation Sets")
                ]),
            ControlsView.ControlData(
                name="Help",
                text="&Help",
                actions=[
                    ControlBar.ActionData(
                        name="Manual",
                        text="&Manual",
                        icon=Resources("icons/Help"),
                        status_tip="Application manual of %s" %
                        config.APPLICATION_NAME),
                    ControlBar.ActionData(
                        name="About",
                        text="&About %s" % config.APPLICATION_NAME,
                        icon=Resources("icons/About"),
                        callback=self.about_window.show,
                        status_tip=
                        "Display program information, version, copyright and etc"
                    ),
                    ControlBar.ActionData(
                        name="Warnings",
                        text="%s website" % config.APPLICATION_NAME,
                        icon=Resources("icons/Website"),
                        callback=self.onWebsiteOpen,
                        status_tip="Launch browser to %s project website" %
                        config.APPLICATION_NAME)
                ]),
        ]

        controls_group = [("View", "Parameters", "Simulation")]

        logging.info("Create controls view")
        self.controls_view = ControlsView(self, controls_data, controls_group)

        logging.info("Create database view")
        self.tabs["View.Database"] = DatabaseView(self, self.appdb)

        logging.info("Create numerics view")
        self.tabs["Parameters.Numerics"] = NumericsView(self, self.options)

        logging.info("Create wafer processes view")
        self.tabs["Parameters.WaferProcesses"] = WaferProcessView(
            self, self.options.wafer_process, self.appdb)

        logging.info("Create resist view")
        self.tabs["Parameters.Resist"] = ResistView(self,
                                                    self.options.wafer_process,
                                                    self.options.peb.temp,
                                                    self.appdb)

        logging.info("Create mask view")
        self.tabs["Parameters.Mask"] = MaskView(self, self.options, self.appdb)

        logging.info("Create imaging tool view")
        self.tabs["Parameters.ImagingTool"] = ImagingView(
            self, self.options, self.appdb)

        logging.info("Create exposure and focus view")
        self.tabs["Parameters.ExposureAndFocus"] = ExposureFocusView(
            self, self.options.exposure_focus, self.options.wafer_process)

        logging.info("Create post exposure bake view")
        self.tabs["Parameters.PostExposureBake"] = PostExposureBakeView(
            self, self.options)

        logging.info("Create development view")
        self.tabs["Parameters.Development"] = DevelopmentView(
            self, self.options.development, self.options.wafer_process)

        logging.info("Create metrology view")
        self.tabs["Parameters.Metrology"] = MetrologyView(self, self.options)

        logging.info("Create summary view")
        self.tabs["Parameters.Summary"] = SummaryView(self, self.options)

        logging.info("Create diffraction pattern simulation view")
        self.tabs["Simulation.DiffractionPattern"] = DiffractionPatternView(
            self, self.core)

        logging.info("Create aerial image simulation view")
        self.tabs["Simulation.AerialImage"] = AerialImageView(
            self, self.core.aerial_image, self.options)

        logging.info("Create image in resist simulation view")
        self.tabs["Simulation.ImageInResist"] = ImageInResistView(
            self, self.core.image_in_resist, self.options)

        logging.info("Create exposed latent image simulation view")
        self.tabs["Simulation.ExposedLatentImage"] = LatentImageView(
            self, self.core.latent_image, self.options)

        logging.info("Create peb latent image simulation view")
        self.tabs["Simulation.PEBLatentImage"] = PebLatentImageView(
            self, self.core.peb_latent_image, self.options)

        logging.info("Create develop time contours simulation view")
        self.tabs["Simulation.DevelopTimeContours"] = \
            DevelopContoursView(self, self.core.develop_contours, self.options)

        logging.info("Create resist profile simulation view")
        self.tabs["Simulation.ResistProfile"] = ResistProfileView(
            self, self.core.resist_profile, self.options)

        logging.info("Create simulation sets view")
        self.tabs["Simulation.SimulationSets"] = SimulationSets(
            self, self.core)

        logging.info("Configure stack widget")
        window = QtGui.QWidget()
        self.setCentralWidget(window)
        self.tabs_stack = QStackedWidget(window)

        self.window_layout = QtGui.QHBoxLayout(window)
        self.window_layout.addWidget(self.tabs_stack)

        # self.scroll_widget = QtGui.QScrollArea()
        # self.scroll_widget.setWidget(window)
        # self.scroll_widget.setWidgetResizable(True)

        for control in self.tabs.values():
            self.tabs_stack.addWidget(control)
Exemple #47
0
import flask
from flask import Flask
from flask import request
from flask import render_template
from flask import url_for
from flask import redirect
from resources import Resources

app = Flask(__name__)
resources = Resources()
resources.init()

@app.route("/about")
def about():
    # return render_template("about.html")
    post = resources.get_about()
    return render_template("post.html", post=post, title="about")

@app.route("/archives/")
def archives():
    return render_template("archives.html", posts=resources.posts(), title="archives")

@app.route("/archives/<string:archive_id>")
def archive(archive_id):
    post = resources.get(archive_id)
    return render_template("post.html", post=post, title=post.title)

@app.route("/construct")
def construct():
    return render_template("construct.html")
Exemple #48
0
See the License for the specific language governing permissions and
limitations under the License
"""
import json
from locust import HttpLocust, TaskSet, task
import uuid
from resources import Resources

# Inventory base url
# [todo] This should be defined from environment properties
global inventory_url
inventory_url = 'http://localhost:8080/hawkular/inventory'

# Resource types initialization should be independent of any client activity
global resources
resources = Resources()
Resources.add_resource_types(inventory_url, Resources.create_resource_types())

global headers
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

class AgentLifeCycle(TaskSet):
    def on_start(self):
        self.feed_id = "feed-" + str(uuid.uuid4())
        print "New Agent [%s]" %  self.feed_id,
        # Simulating 1 server with 99 children resources each one with 20 metrics, so 100 resources per agent
        self.agent_resources = resources.create_large_inventory(self.feed_id, 1, 99, 20)
        self.client.post("/import", json.dumps(self.agent_resources), headers=headers)
        print "Agent [%s] - full auto-discovery" % self.feed_id,

    @task
Exemple #49
0
    def __init__(self, context, editor):
        PanelView.__init__(self, context)
        self._log.debug("init")

        self._editor = editor
        self._handlers = {}
        self._preferences = Preferences()

        self._preferences.connect("preferences-changed", self._on_preferences_changed)
        self._show_tasks = self._preferences.get("issues-show-tasks")
        self._show_warnings = self._preferences.get("issues-show-warnings")

        self._icons = { Issue.SEVERITY_WARNING : GdkPixbuf.Pixbuf.new_from_file(Resources().get_icon("warning.png")),
                        Issue.SEVERITY_ERROR : GdkPixbuf.Pixbuf.new_from_file(Resources().get_icon("error.png")),
                        Issue.SEVERITY_INFO : None,
                        Issue.SEVERITY_TASK : GdkPixbuf.Pixbuf.new_from_file(Resources().get_icon("task.png")) }

        grid = Gtk.Grid()
        self.add(grid)

        self._store = Gtk.ListStore(GdkPixbuf.Pixbuf, str, str, object)

        self._view = Gtk.TreeView(model=self._store)

        column = Gtk.TreeViewColumn()
        column.set_title(_("Message"))

        pixbuf_renderer = Gtk.CellRendererPixbuf()
        column.pack_start(pixbuf_renderer, False)
        column.add_attribute(pixbuf_renderer, "pixbuf", 0)

        text_renderer = Gtk.CellRendererText()
        column.pack_start(text_renderer, True)
        column.add_attribute(text_renderer, "markup", 1)

        self._view.append_column(column)

        column = Gtk.TreeViewColumn()
        column.set_title(_("File"))
        text_renderer2 = Gtk.CellRendererText()
        column.pack_start(text_renderer2, True)
        column.add_attribute(text_renderer2, "markup", 2)
        self._view.insert_column(column, -1)
        self._handlers[self._view] = self._view.connect("row-activated", self._on_row_activated)

        self._scr = Gtk.ScrolledWindow()

        self._scr.add(self._view)
        self._scr.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        self._scr.set_shadow_type(Gtk.ShadowType.IN)
        self._scr.set_hexpand(True)
        self._scr.set_vexpand(True)

        grid.add(self._scr)

        # toolbar
        self._button_warnings = Gtk.ToggleToolButton()
        self._button_warnings.set_tooltip_text(_("Show/Hide Warnings"))
        image = Gtk.Image()
        image.set_from_file(Resources().get_icon("warning.png"))
        self._button_warnings.set_icon_widget(image)
        self._button_warnings.set_active(self._show_warnings)
        self._handlers[self._button_warnings] = self._button_warnings.connect("toggled", self.__on_warnings_toggled)

        self._button_tasks = Gtk.ToggleToolButton()
        self._button_tasks.set_tooltip_text(_("Show/Hide Tasks"))
        imageTask = Gtk.Image()
        imageTask.set_from_file(Resources().get_icon("task.png"))
        self._button_tasks.set_icon_widget(imageTask)
        self._button_tasks.set_active(self._show_tasks)
        self._handlers[self._button_tasks] = self._button_tasks.connect("toggled", self.__on_tasks_toggled)

        toolbar = Gtk.Toolbar()
        toolbar.set_orientation(Gtk.Orientation.VERTICAL)
        toolbar.set_style(Gtk.ToolbarStyle.ICONS)
        toolbar.set_icon_size(Gtk.IconSize.MENU)
        toolbar.insert(self._button_warnings, -1)
        toolbar.insert(self._button_tasks, -1)
        toolbar.set_vexpand(True)

        grid.add(toolbar)

        # theme like gtk3
        ctx = self._scr.get_style_context()
        ctx.set_junction_sides(Gtk.JunctionSides.RIGHT)

        ctx = toolbar.get_style_context()
        ctx.set_junction_sides(Gtk.JunctionSides.LEFT | Gtk.JunctionSides.RIGHT)
        ctx.add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR)

        self._issues = []

        self.show_all()

        self._log.debug("init finished")
Exemple #50
0
 def deploy_app(self):
     self.client.post("/import", json.dumps(Resources.create_app_resource(self.feed_id, self.feed_id + "-NewApp.war")), headers=headers)
     print "Agent [%s] - deploys NewApp.war" % self.feed_id,
Exemple #51
0
    def update_ringtones(self, account=None):
        settings = SIPSimpleSettings()

        if account is None:
            account = AccountManager().default_account

        app = SIPApplication()

        def change_tone(name, new_tone):
            current = getattr(self, name)
            if current and current.is_active:
                current.stop()
                if new_tone:
                    new_tone.start()
            setattr(self, name, new_tone)

        change_tone(
            "initial_hold_tone",
            WavePlayer(app.voice_audio_mixer,
                       Resources.get('hold_tone.wav'),
                       volume=10))
        app.voice_audio_bridge.add(self.initial_hold_tone)
        change_tone(
            "secondary_hold_tone",
            WavePlayer(app.voice_audio_mixer,
                       Resources.get('hold_tone.wav'),
                       loop_count=0,
                       pause_time=45,
                       volume=10,
                       initial_delay=45))
        app.voice_audio_bridge.add(self.secondary_hold_tone)

        if account:
            audio_primary_ringtone = account.sounds.audio_inbound.sound_file if account.sounds.audio_inbound is not None else None
        else:
            audio_primary_ringtone = None

        if audio_primary_ringtone and not settings.audio.silent:
            # Workaround not to use same device from two bridges. -Saul
            if settings.audio.alert_device is not None and app.alert_audio_mixer.real_output_device == app.voice_audio_mixer.real_output_device:
                new_tone = WavePlayer(app.voice_audio_mixer,
                                      audio_primary_ringtone.path,
                                      loop_count=0,
                                      pause_time=6)
                app.voice_audio_bridge.add(new_tone)
            else:
                new_tone = WavePlayer(app.alert_audio_mixer,
                                      audio_primary_ringtone.path,
                                      loop_count=0,
                                      pause_time=6)
                app.alert_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("audio_primary_ringtone", new_tone)

        if audio_primary_ringtone and not settings.audio.silent:
            new_tone = WavePlayer(app.voice_audio_mixer,
                                  Resources.get('ring_tone.wav'),
                                  loop_count=0,
                                  pause_time=6)
            app.voice_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("audio_secondary_ringtone", new_tone)

        if audio_primary_ringtone and not settings.audio.silent:
            # Workaround not to use same device from two bridges. -Saul
            if settings.audio.alert_device is not None and app.alert_audio_mixer.real_output_device == app.voice_audio_mixer.real_output_device:
                new_tone = WavePlayer(app.voice_audio_mixer,
                                      Resources.get('ring_tone.wav'),
                                      loop_count=0,
                                      pause_time=6)
                app.voice_audio_bridge.add(new_tone)
            else:
                new_tone = WavePlayer(app.alert_audio_mixer,
                                      Resources.get('ring_tone.wav'),
                                      loop_count=0,
                                      pause_time=6)
                app.alert_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("chat_primary_ringtone", new_tone)

        if audio_primary_ringtone and not settings.audio.silent:
            new_tone = WavePlayer(app.voice_audio_mixer,
                                  Resources.get('ring_tone.wav'),
                                  loop_count=0,
                                  pause_time=6)
            app.voice_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("chat_secondary_ringtone", new_tone)

        chat_message_outgoing_sound = settings.sounds.message_sent
        if chat_message_outgoing_sound and not settings.audio.silent:
            new_tone = WavePlayer(app.voice_audio_mixer,
                                  chat_message_outgoing_sound.path,
                                  volume=chat_message_outgoing_sound.volume)
            app.voice_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("chat_message_outgoing_sound", new_tone)

        chat_message_incoming_sound = settings.sounds.message_received
        if chat_message_incoming_sound and not settings.audio.silent:
            new_tone = WavePlayer(app.voice_audio_mixer,
                                  chat_message_incoming_sound.path,
                                  volume=chat_message_incoming_sound.volume)
            app.voice_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("chat_message_incoming_sound", new_tone)

        file_transfer_outgoing_sound = settings.sounds.file_sent
        if file_transfer_outgoing_sound and not settings.audio.silent:
            new_tone = WavePlayer(app.voice_audio_mixer,
                                  file_transfer_outgoing_sound.path,
                                  volume=file_transfer_outgoing_sound.volume)
            app.voice_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("file_transfer_outgoing_sound", new_tone)

        file_transfer_incoming_sound = settings.sounds.file_received
        if file_transfer_incoming_sound and not settings.audio.silent:
            new_tone = WavePlayer(app.voice_audio_mixer,
                                  file_transfer_incoming_sound.path,
                                  volume=file_transfer_incoming_sound.volume)
            app.voice_audio_bridge.add(new_tone)
        else:
            new_tone = None
        change_tone("file_transfer_incoming_sound", new_tone)
Exemple #52
0
# -*- coding: utf-8 -*-

import os
import sys

from flask import Flask, request, session, g, redirect, url_for, abort, render_template, Blueprint, jsonify
from resources import Resources
from settings import RESOURCES_PATH, SETTINGS_PATH

blueprint_api = Blueprint('api', __name__)
resource = Resources(RESOURCES_PATH, SETTINGS_PATH)


@blueprint_api.route('/api')
def home():
    global resource
    lang = request.args.get('l') or 'bg'
    print resource.get_navigations(lang)
    content = {
        "navigation": resource.get_navigations(lang),
        "pages": resource.get_pages(lang)
    }

    return jsonify(content)


@blueprint_api.route('/api/publish')
def publish():
    global resource

    resource.publish()
Exemple #53
0
    def start(self, screen):
        if not self.already_loaded:
            PenData.load_all_pens()

            width = screen.get_width()
            height = screen.get_height()

            self.back_btn = Button(
                pygame.Rect(10, 10, 60, 40), "Back", {
                    Options.BORDER_WIDTH: 0,
                    Options.BACKGROUND: (20, 61, 89),
                    Options.FOREGROUND: (244, 180, 26),
                    Options.HOVERED_BACKGROUND: (10, 30, 45),
                    Options.FONT: pygame.font.SysFont("Comic Sans MS", 15)
                })

            self.header = Label(
                pygame.Rect(width / 2 - 200, 10, 400, 30),
                "Choose your opponent!", {
                    Options.BACKGROUND: (20, 61, 89),
                    Options.FOREGROUND: (244, 180, 26),
                    Options.BORDER_WIDTH: 0,
                })

            self.name_text = Label(
                pygame.Rect(width / 2 - 45, height - 125, 90, 50), "", {
                    Options.BACKGROUND: (82, 173, 200),
                    Options.FOREGROUND: (20, 61, 89),
                    Options.BORDER_WIDTH: 0,
                    Options.FONT: pygame.font.SysFont("Comic Sans MS", 18)
                })

            btn_options = {
                Options.BORDER_WIDTH: 0,
                Options.BACKGROUND: (20, 61, 89),
                Options.FOREGROUND: (244, 180, 26),
                Options.HOVERED_BACKGROUND: (10, 30, 45),
                Options.FONT: pygame.font.SysFont("Comic Sans MS", 25)
            }
            self.left_btn = Button(pygame.Rect(10, height / 2 - 20, 20, 30),
                                   "<", btn_options)
            self.right_btn = Button(
                pygame.Rect(width - 30, height / 2 - 20, 20, 30), ">",
                btn_options)
            self.select_btn = Button(
                pygame.Rect(width / 2 - 45, height - 75, 90, 50), "Select",
                btn_options)

            btn_options[Options.TOGGLED_BACKGROUND] = (5, 20, 30)
            self.random_diff_btn = ToggleButton(
                pygame.Rect(width * 1 / 5 - 50, 100, 100, 30), "Random",
                btn_options)
            self.easy_btn = ToggleButton(
                pygame.Rect(width * 2 / 5 - 50, 100, 100, 30), "Easy",
                btn_options)
            self.normal_btn = ToggleButton(
                pygame.Rect(width * 3 / 5 - 50, 100, 100, 30), "Normal",
                btn_options)
            self.hard_btn = ToggleButton(
                pygame.Rect(width * 4 / 5 - 50, 100, 100, 30), "Hard",
                btn_options)
            toggle_group = [
                self.random_diff_btn, self.easy_btn, self.normal_btn,
                self.hard_btn
            ]
            for elt in toggle_group:
                elt.set_group(toggle_group)
            self.easy_btn.toggle()

            self.center_pos = pygame.Rect(width / 2 - 50, height / 2 - 50, 100,
                                          100)
            self.random_pen_data = PenData.dict_to_pen({
                "name":
                "Random",
                "image_file":
                "random_pen"
            })
            for pen in [self.random_pen_data] + PenData.all_pens:
                self.pen_images.append(
                    Image(self.center_pos, Resources.get(pen.image_file),
                          {Options.BACKGROUND: (82, 173, 200)}))

            self.already_loaded = True

        self.reposition_images()
        self.update_enemy_data()
Exemple #54
0
 def reset(self):
     self.setFixedWidth(0)
     self.setVisible(False)
     self.setUrl(QUrl.fromLocalFile(Resources.get_path("leftpane.html")))
     self.page().currentFrame().addToJavaScriptWindowObject("leftPane", self)
     self.page().currentFrame().evaluateJavaScript(self.js)
Exemple #55
0
class Cities(object):
    '''
    classdocs
    '''
    def __init__(self, town_name="", wood=0, oil=0, water=0, discontent=100):
        '''
        Constructor
        '''
        self.__town_name = town_name
        self.town_resources = Resources(wood, oil, water)
        self.__discontent = discontent

    def __str__(self):

        data =  "Wood: " + str(self.town_resources.getWood()) \
        + "\n" \
        + "Oil: " + str(self.town_resources.getOil()) \
        + "\n" \
        + "Water: " + str(self.town_resources.getWater()) \
        + "\n" \
        + "Discontent: " +  str(self.__discontent)

        return data

    def setTownName(self, town_name):
        self.__town_name = town_name

    def getTownName(self):
        return self.__town_name

    def setDiscontent(self, discontent):
        self.__discontent = discontent

    def getDiscontent(self):
        return self.__discontent

    def consuming_resources(self):

        rate = random.randrange(10, 41) / 100.0
        self.town_resources.setWood(self.town_resources.getWood() - rate)
        self.town_resources.setOil(self.town_resources.getOil() - rate)

    def discontent_modifier(self):

        if self.town_resources.getWood() <= 0 or self.town_resources.getOil(
        ) <= 0:
            self.__discontent -= 1
        if self.__discontent < 1:
            return "gameover"
Exemple #56
0
def main():
    res = Resources()
    app = Application((800, 600), "Editor", resizable=True)
    app.process(Editor())
    app.run()
Exemple #57
0
 def clear_pys(self):
     try:
         if os.path.exists(Resources.path('dist/log.txt')):
             os.remove(Resources.path('dist/log.txt'))
     except Exception:
         ...
Exemple #58
0
            if event.value == EncoderEvent.CW_ROTATION:
                self._owner.enter_choosing(True, self.track_nb + 1)
            elif event.value == EncoderEvent.CCW_ROTATION:
                self._owner.enter_choosing(True, self.track_nb - 1)
        return

    def cleanup(self):
        self.logger.debug("PlayingState cleaned up")
        self._random_msg_display.stop()
        self._name_display.stop()
        self._title_display.stop()


if __name__ == "__main__":
    # Resourcecs initialization
    rsc = Resources("/home/pi/python/webradio/conf.txt")
    # lcd initialization
    lcd = CharLCD(i2c_expander='PCF8574',
                  address=0x3f,
                  port=1,
                  cols=20,
                  rows=4,
                  dotsize=8,
                  charmap='A02',
                  auto_linebreaks=True,
                  backlight_enabled=True)
    lcd.backlight_enabled = True
    wifi = (0b00000, 0b11111, 0b00000, 0b01110, 0b00000, 0b00100, 0b00100,
            0b00000)
    lcd.create_char(0, wifi)
Exemple #59
0
def main():
    user = Kozo()
    Resources.login(user)
    Resources.get_commands(user)
import random
from worker import Worker
from resources import Resources

V_FACTOR = .2

if __name__ == "__main__":
    resources = Resources()
    trees = Worker("Forest", {}, {"Trees": 10})
    stone = Worker("Mts", {}, {"Stone": 5})

    lumberjack = Worker("Lumberjack", {"Trees": 1}, {"Wood": 10})
    mason = Worker("Mason", {"Stone": 1}, {"Brick": 5})
    axe_maker = Worker("Axe Maker", {"Wood": 1, "Stone": 1}, {"Axe": 1})

    worker_list = []
    worker_list.extend([trees, stone, lumberjack, mason, axe_maker])

    for i in range(100):
        random.shuffle(worker_list)
        for worker in worker_list:
            resources = worker.make(resources)
            #print(resources)

    print(resources)