def notify(self): "send out all the different emails" if self.email is None: return self.post(self.email) Notifier.notify(self) # send all the queued messages out! self.flushQueue() # just in case. If queue is empty, does nothing.
def notify(self): "send out all the different emails" # notify the obs; subject = "Your GBT Project has been # scheduled..." Because each observer will get a custom # 'subject' line with the pcode appended, each must get a # separate email. for i in self.getAddresses("observer"): try: pcodes = " - ".join(self.emailProjectMap[i]) except KeyError: # You WILL get a key error if scheduler # changes observer email addresses pcodes = None email = self.cloneTemplate("observer") if pcodes: subject = "%s (%s)" % (email.GetSubject(), pcodes) else: subject = email.GetSubject() email.SetRecipients(i) email.SetSubject(subject) self.post(email) # now let the people who aren't observing know, but who # might have been in scheduled in the past if len(self.getAddresses("changed")) != 0: email = self.cloneTemplate("changed") self.post(email) # now let the staff know - "GBT schedule for ..." if len(self.getAddresses("staff")) != 0: email = self.cloneTemplate("staff") self.post(email) Notifier.notify(self) # send all the queued messages out! self.flushQueue() # just in case. If queue is empty, does nothing.
class GoogleTranslatorApplet(BasePlasmoid): def __init__(self,parent,args=None): self.parent = parent BasePlasmoid.__init__(self, parent) def init(self): debug("GoogleTranslatorApplet: init().") BasePlasmoid.init(self) self._widget = None self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget debug("GoogleTranslatorApplet: Creating main widget.") self._widget = GoogleTranslator(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) # Tool tip for panel self.metadata = self.package().metadata() self.tooltipdata = Plasma.ToolTipContent() self.tooltipdata.setMainText(self.metadata.name()) self.tooltipdata.setSubText(self.metadata.description()) self.tooltipdata.setImage(KIcon(self.metadata.pluginName())) Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata) # Only register the tooltip in panels #if (self.formFactor() != Plasma.Planar): if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)): print("GoogleTranslatorApplet: In Panel") Plasma.ToolTipManager.self().registerWidget(self.applet) else: Plasma.ToolTipManager.self().unregisterWidget(self.applet) print("GoogleTranslatorApplet: Not in Panel") self.configChanged() def configChanged(self): debug("GoogleTranslator: configChanged") # TODO: # Clear ComboBoxes # Add languages # Select languages # Translate defaultSize = QVariant(QSize (0,0)) size = self.cfg.readEntry("size", defaultSize ).toSize() if (size != defaultSize) : self._widget.setPreferredSize(size.width(), size.height()) else: self._widget.setPreferredSize(400 ,200) self.connect(self._widget, SIGNAL("resized()"), self.dialog_resized) @QtCore.pyqtSlot(name="dialog_resized") def dialog_resized(self): if self.isPopupShowing(): self.config().writeEntry("size", QVariant(self.widget.size())) @QtCore.pyqtSlot(bool, name="netstate_changed") def netstate_changed(self, connected): print "GoogleTranslatorApplet: Network status changed! %i" % connected if connected: debug("GoogleTranslatorApplet: Connected!") self._widget.setEnabled(True) self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self._widget.setEnabled(False) debug("GoogleTranslatorApplet: Not connected!") self.setBusy(True)
class CurrencyConverterApplet(base.BaseApplet): def __init__(self,parent,args=None): base.BaseApplet.__init__(self,parent) def init(self): base.BaseApplet.init(self, needsversion="4.5") if self.hasFailedToLaunch(): return KGlobal.locale().insertCatalog(self.metadata.pluginName()) lang = KGlobal.locale().language() print "Language:", lang print "Translated?", KGlobal.locale().isApplicationTranslatedInto(lang) self._widget = None self.dialog = None self.has_tooltip = False self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget print("CurrencyConverterApplet: Creating main widget.") self._widget = CurrencyConverter(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) #self.setup_tooltip() self.configChanged() self._widget.updated.connect(self.setup_tooltip) def createConfigurationInterface(self, dialog): self.ui = CurrencyConverterConfig(self.dialog) p = dialog.addPage(self.ui, i18n("General") ) p.setIcon( KIcon("currency-converter") ) #self.notify_widget = KCModuleProxy("kcmnotify", dialog, ["currency-converter",]) #real_module = self.notify_widget.realModule() ##print "Module:", real_module #p = dialog.addPage(self.notify_widget, i18n("Notifications") ) #p.setIcon( KIcon("dialog-information") ) dialog.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Apply))) dialog.showButton(KDialog.Apply, False) #self.connect(dialog, SIGNAL("applyClicked()"), self, SLOT("configAccepted()")) #self.connect(dialog, SIGNAL("okClicked()"), self, SLOT("configAccepted()")) dialog.applyClicked.connect(self.configAccepted) dialog.okClicked.connect(self.configAccepted) self.ui.update_interval.setValue(self._widget.update_interval) #@pyqtSignature("configAccepted()") @pyqtSlot(name="configAccepted") def configAccepted(self): print "CurrencyConverterApplet::configAccepted" self._widget.update_interval = self.ui.update_interval.value() self.cfg.writeEntry("update_interval", QVariant(self._widget.update_interval)) self.constraintsEvent(Plasma.SizeConstraint) self.update() self._widget.start_timer() self.emit(SIGNAL("configNeedsSaving()")) #self.configNeedsSaving.emit() def contextualActions(self): # Add custom context menus print "CurrencyConverterApplet::contextualActions" actions = [] ac_update = QAction(KIcon("view-refresh"), i18n("Update now"), self) #checkNow = QAction(KIcon(self.package().path() + "contents/icons/check.svg"), "Check email now", self) #self.connect(ac_update, SIGNAL("triggered()"), self._widget.do_convert) if hasattr(self, '_widget') and self._widget is not None: ac_update.triggered.connect(self._widget.do_convert) actions.append(ac_update) print actions return actions # Never called..? def updateToolTipContent(self): print "CurrencyConverterApplet::updateToolTipContent" @QtCore.pyqtSlot(name="setup_tooltip") def setup_tooltip(self): print "setup_tooltip: Last updated:", self._widget.lastUpdated() # Tool tip for panel if self.has_tooltip: Plasma.ToolTipManager.self().clearContent(self.applet) self.metadata = self.package().metadata() self.tooltipdata = Plasma.ToolTipContent() self.tooltipdata.setAutohide(False) self.tooltipdata.setMainText(self.metadata.name()) #self.tooltipdata.setSubText(self.metadata.description()) tooltip_txt = str(i18nc("From code From Amount = To code To Amount - Last updated", "%s %s = %s %s<br /><br />Last updated:<br />%s")) tooltip_txt= tooltip_txt % (self._widget.fromCurrency(), self._widget.fromAmount(), self._widget.toCurrency(), self._widget.toAmount(), self._widget.lastUpdated()) #print tooltip_txt self.tooltipdata.setSubText(tooltip_txt) self.tooltipdata.setImage(KIcon(self.metadata.pluginName())) Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata) # Only register the tooltip in panels #if (self.formFactor() != Plasma.Planar): if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)): #print("CurrencyConverterApplet: In Panel") Plasma.ToolTipManager.self().registerWidget(self.applet) self.has_tooltip = True else: Plasma.ToolTipManager.self().clearContent(self.applet) Plasma.ToolTipManager.self().unregisterWidget(self.applet) #print("CurrencyConverterApplet: Not in Panel") self.has_tooltip = False def configChanged(self): print("CurrencyConverterApplet: configChanged") # TODO: # Clear ComboBoxes # Add currencies # Select currencies # Convert @QtCore.pyqtSlot(bool, name="netstate_changed") def netstate_changed(self, connected): print "CurrencyConverterApplet: Network status changed!", connected if connected: print("CurrencyConverterApplet: Connected!") self._widget.setEnabled(True) self._widget.start_timer() self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self._widget.setEnabled(False) print("CurrencyConverterApplet: Not connected!") self.setBusy(True) # Whys isn't this called? @QtCore.pyqtSlot(name="toolTipAboutToShow") def toolTipAboutToShow(self): print "CurrencyConverterApplet:toolTipAboutToShow"
class Player(): def __init__(self, name: str): self.deck = [ ] # remaining cards available for the game (32 at the very beginning) self.hand_cards = [ ] # cards in the hand (max 4 according to the rules) self.archive_cards = [] # cards that have been played self.name = name self.score = 0 self.notifier = Notifier() # return how many cards should be taken, min: 0, max: 4 @property def cards_to_take(self): return 4 - len(self.hand_cards) # reset some values def endOfGame(self): self.archive_cards = [] self.score = 0 def takeCardsFromDeck(self, n: int): if (len(self.deck) < n): raise IndexError("There is not enough cards in the deck") for i in range(n): self.hand_cards.append(self.deck.pop()) def takeToFull(self, first: bool): # if this players draws as first then the required count of cards in deck is double (because the second one needs them as well) required_deck_length = self.cards_to_take * 2 if first else self.cards_to_take if len(self.deck) >= required_deck_length: self.takeCardsFromDeck(self.cards_to_take) else: if first: # if players draws first, then the deck length is always even self.takeCardsFromDeck(len(self.deck) // 2) else: self.takeCardsFromDeck(len(self.deck)) def collectFromStack(self, stack: list): """ empty the stack and put the cards to archive """ self.score += assessCards(stack) # put the cards from current stack to archive self.archive_cards.extend(stack) stack = [] def cardRepeatingAbility(self, card: int): _count = 0 for _card in self.hand_cards: if _card == 0 or _card == card: _count += 1 return _count def takeBestCard(self, cards: list, mapping_function, **map_fn_args): """ assess each card with mapping function and get the one with the highest score """ best_val = -1 best_index = -1 self.notifier.notify("{}'s cards:".format(self.name), 2) for i in range(len(cards)): result = mapping_function(cards[i], **map_fn_args) self.notifier.notify( "score({})={}".format(translateCodeToCard(cards[i]), result), 2) if (result > best_val): best_val = result best_index = i if (best_val == -1): return None best_card = cards[best_index] del cards[best_index] return best_card def playCardStarting(self): return self.takeBestCard(self.hand_cards, self.startingStrategy) def playCardResponding(self, stack: list): return self.takeBestCard(self.hand_cards, self.respondingStrategy, stack=stack) def playCardRepeating(self, stack: list, is_winning: bool): if (len(self.hand_cards) == 0 or self.stopRepeatingCondition(stack, is_winning)): return None return self.takeBestCard(self.hand_cards, self.repeatingStrategy, stack=stack) """ following methods are going to be overridden by child classes and return value always for ONE particular card """ def startingStrategy(self, card: int): return 0 def respondingStrategy(self, card: int, stack): return 0 def repeatingStrategy(self, card: int, stack): if (card == stack[0]): return 1 return -1 def stopRepeatingCondition(self, stack: list, is_winning: bool): return False
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from os import path import tensorflow as tf import tensorflow.python.platform from Trainer import Trainer lib_dir = path.abspath(path.join("lib")) sys.path.append(lib_dir) from Notifier import Notifier if __name__ == '__main__': # tf_config = tf.ConfigProto( # gpu_options=tf.GPUOptions( # allow_growth=True # True->必要になったら確保, False->全部 # ) # ) # with tf.Session(config=tf_config) as sess: with tf.Session() as sess: trainer = Trainer(sess) trainer.train() trainer.test() trainer.save() notifier = Notifier() notifier.notify("Finish train", trainer.output())
class Tournament(): def __init__(self, player1: Player, player2: Player, n_games: int): if n_games % 2 == 0: raise ValueError("Error: number of games in tournament must be an odd number!") # initialize an empty deck and join to the players self.deck = [] player1.deck = self.deck player2.deck = self.deck self.player1 = player1 self.player2 = player2 self.starting_player = player1 self.n_games = n_games self.player1_stats = { 'games_won': 0, 'total_points': 0 } self.player2_stats = { 'games_won': 0, 'total_points': 0 } self.notifier = Notifier() @property def responding_player(self): return self.player1 if self.starting_player == self.player2 else self.player2 def playTournament(self): for game in range(self.n_games): generateNewRandomDeck(self.deck) # count total cards available while len(self.deck) + len(self.player1.hand_cards) + len(self.player2.hand_cards) > 0: self.starting_player.takeToFull(True) self.responding_player.takeToFull(False) match = Match(self.starting_player, self.responding_player) # the next starting player will be the one who has won current match self.starting_player = match.playMatch() # the last starting player is the one who won the final match, so he gets 1 extra point self.starting_player.score += 1 if self.player1.score > self.player2.score: self.player1_stats['games_won'] += 1 self.notifier.notify("End of game No.{} Player {} has won with {} points".format( game+1, self.player1.name, self.player1.score )) else: self.player2_stats['games_won'] += 1 self.notifier.notify("End of game No.{} Player {} has won with {} points".format( game+1, self.player2.name, self.player2.score )) self.player1_stats['total_points'] += self.player1.score self.player2_stats['total_points'] += self.player2.score self.player1.endOfGame() self.player2.endOfGame() def getAbsoluteWinner(self): if self.player1_stats['games_won'] > self.player2_stats['games_won']: return self.player1 else: return self.player2