def __init__(self, qubits, observable=Observable.Z()): """ - qubit (int): The index of the qubit - observable=Observable.Z() (matrix, tuple, or QNN-Gen Observable object): The observable to meausre with respect to - If matrix it should be a list or numpy.ndarray - If tuple, it should be of the form ("name": matrix) """ if isinstance(qubits, int): self.qubits = [qubits] else: self.qubits = qubits # just single-qubit for now if isinstance(observable, (list, np.ndarray)): self.observable = Observable(observable) elif isinstance(observable, tuple): self.observable = Observable(matrix=observable[1], name=observable[0]) elif isinstance(observable, Observable): self.observable = observable else: raise ValueError( "Observable argument is not a correct type. Check the __init__ docstring." ) if self.observable.name == "Z": requires_rotation = False else: requires_rotation = True super().__init__(qubits=self.qubits, rotate=requires_rotation)
def __init__(self, ip='0.0.0.0', port=0, username='', password='', autoReconnect=True): self.loginId = C_LLONG() self.client = NetClient() self.client.InitEx(fDisConnect(self.disconnectCallback)) autoReconnect and self.client.SetAutoReconnect( fHaveReConnect(self.reconnectCallback)) self.clientInfo = None self.ip = ip self.port = port self.username = username self.password = password ## 通道(channel) self.channel = 0 ## 码流类型(0:主码流; 1:辅码流) self.streamtype = 0 self.onConnect = Observable() self.onDisconnect = Observable() self.onReconnect = Observable() self.onError = Observable()
def __init__(self, **kwargs): super().__init__(**kwargs) self.playId = C_LLONG() self.m_RealDataCallBack = fRealDataCallBackEx2(self.realDataCallback) self.onRealData = Observable() self.onRealPlay = Observable() self.onRealStop = Observable()
def checkVictory(self):#If all the non clicked buttons are mines, the user wins the game and all the mines become checked. countRightPointsClicked = 0 for i in range(self._model.getLenModelsGridButtons()): if not(self._model.getItemModelsGridButtons(i).isMine) and self._model.getItemModelsGridButtons(i).isClicked: countRightPointsClicked += 1 if countRightPointsClicked == self._model.W * self._model.H - self._model.mines: self._model.isWin = True if self._ui.lcdTime.value() == 0: totalTime = 0 else: if self._ui.lcdTime.value() == 99999: totalTime = 99999 else: totalTime = self._ui.lcdTime.value() + (time.time() - self._model.gameTime) for i in range(self._model.getLenModelsGridButtons()): self._model.getItemModelsGridButtons(i).isActive = False if self._model.getItemModelsGridButtons(i).isMine: self._model.getItemModelsGridButtons(i).isChecked = True self._model.getItemModelsGridButtons(i).isClicked = True self._ui.statusbar.setStyleSheet("color:green; font-size: 14pt;") self._ui.statusbar.showMessage("You Win!") self._model.counterMines = 0 #The maximum number of rankings positions are 20. So if the considered ranking is not already full, the user can insert his record; else if his game time is less than the last position one, the user does a new record; else the user does not have the possibility to insert his game time on the ranking. if self._model.rankingType != 3: if self._model.getLenRanking(self._model.rankingType) < 20 or totalTime < self._model.getMaxRanking(self._model.rankingType): isRecord = Observable(False) nameRecord = Observable(None) # A dialog gives the possibility to a user who does a new record to insert his name. dialog = RecordDialog(totalTime, isRecord, nameRecord) dialog.exec_() #If there is a new record in the ranking, the rankings-related file is updated. if isRecord.value: self._model.setItemRanking(self._model.rankingType, [nameRecord.value, totalTime]) if os.path.exists("DataSaved/Rankings/Rankings.pkl"): os.remove("DataSaved/Rankings/Rankings.pkl") vectorToSave = [[], [], []] for i in range(3): for j in range(self._model.getLenRanking(i)): vectorToSave[i].append(self._model.getItemRanking(i, j)) with open("DataSaved/Rankings/Rankings.pkl", "wb") as output: pickle.dump(vectorToSave, output) self.makeRankings(self._model.rankingType) return True else: return False
def callingSaveOperation(self): if len(self._ui.nameGame.text()) == 0: if self._ui.scrollAreaWidgetContents.layout().count() == 3: #"scrollAreaWidgetContents" is the dialog main area. self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Insert a game name.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") else: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setText("Insert a game name.") else: if not(self._ui.nameGame.text().isalnum()): if self._ui.scrollAreaWidgetContents.layout().count() == 3: self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Insert a name without character special or spaces.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") else: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setText("Insert a name without character special or spaces.") else: if self._ui.scrollAreaWidgetContents.layout().count() == 4: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setParent(None) count = 0 for i in range(self._model.getLenSavedGames()): if self._ui.nameGame.text() == self._model.getItemSavedGames(i): isReplacing = Observable(False) #If the user inserts a same name of another saved game, a dialog appears: he can replace this saved game or change the typed name. dialog = WarningSaveDialog(isReplacing) dialog.exec_() if isReplacing.value: self._model.gameObservable.value = self._ui.nameGame.text() self.close() break else: count += 1 if count == self._model.getLenSavedGames(): self._model.gameObservable.value = self._ui.nameGame.text() self.close()
def callingDeleteOperation(self): if self._model.getLenSavedGames() == 0: if self._ui.scrollAreaWidgetContents.layout().count() == 3: #"scrollAreaWidgetContents" is the dialog main area. self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Select at least one game to delete.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") else: countGameChecked = 0 for i in reversed(range(self._ui.savedGamesArea.layout().count())): if self._ui.savedGamesArea.layout().itemAt(i).widget().isChecked(): if self._ui.scrollAreaWidgetContents.layout().count() == 4: self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setParent(None) countGameChecked += 1 if countGameChecked == 1: isDelete = Observable(False) # A dialog asks to the user if he wants the imminent elimination of some selected games. dialog = WarningDeleteDialog(isDelete) dialog.exec_() if not(isDelete.value): break self.deleteGame(self._model.getItemSavedGames(i)) self._model.delItemSavedGames(i) self._ui.savedGamesArea.layout().itemAt(i).widget().setParent(None) if self._ui.scrollAreaWidgetContents.layout().count() == 3 and countGameChecked == 0: self._ui.scrollAreaWidgetContents.layout().addWidget(QLabel("Select at least one game to delete.")) self._ui.scrollAreaWidgetContents.layout().itemAt(self._ui.scrollAreaWidgetContents.layout().count() - 1).widget().setStyleSheet("color:red; font-size:11pt;") if self._model.getLenSavedGames() == 0: self._ui.savedGamesArea.layout().addWidget(QLabel("No Games Saved.")) self._ui.savedGamesArea.layout().itemAt(0).widget().setStyleSheet("font-size:11pt;")
def search(): observable = Observable() query = request.get_json() py_client(host="localhost", port_expose=server_port, top_k=100).search(input_fn=read_query_data(query["searchQuery"]), output_fn=lambda x: observable.callback(x)) results = observable.format_response() return jsonify(results)
def __init__(self, id, x, y, w, h, text): super() self.Text = text self.Location = Point(x, y) self.Height = w self.Width = h self.observable = Observable(id) self.Click += self.buttonPressed
def search(): observable = Observable() query = request.get_json() query = query["data"] answer = requests.post(f"http://0.0.0.0:{server_port}/api/search", json={"data": query, "top_k": 10}).text answer = json.loads(answer) observable.result = answer results = observable.format_response() return jsonify(results)
def openLoadDialog(self):#The user can load a saved game with this dialog. blockedValue = self._model.isBlocked self._model.isBlocked = True gameToLoad = Observable(None) self.setEnabled(False) self.setHidden(True) dialog = LoadDialog(gameToLoad) dialog.exec_() self.setEnabled(True) self.setHidden(False) if gameToLoad.value is not None: self.loadGame("DataSaved/SavedGames/" + gameToLoad.value + ".pkl") self._model.isBlocked = blockedValue
def openNewGameDialog(self): #If the user wants to create a new grid, the application refreshes the grid and all the related widgets. isChangedAnything = Observable(False) blockedValue = self._model.isBlocked self._model.isBlocked = True self.setEnabled(False) self.setHidden(True) dialog = NewDialog(self._model, isChangedAnything) dialog.exec_() self.setEnabled(True) self.setHidden(False) if isChangedAnything.value: self.refreshGrid() else: self._model.isBlocked = blockedValue
def openSaveAsDialog(self):#The user can save a game with this dialog. blockedValue = self._model.isBlocked self._model.isBlocked = True gameToSave = Observable(None) self.setEnabled(False) self.setHidden(True) dialog = SaveAsDialog(gameToSave) dialog.exec_() if gameToSave.value is not None: self.saveGameAs("DataSaved/SavedGames/" + gameToSave.value + ".pkl", blockedValue) dialog = SuccessSaveDialog() dialog.exec_() self._model.isBlocked = blockedValue self.setEnabled(True) self.setHidden(False)
def __init__(self): super().__init__() self.ui = Ui_PhotoGlue() self.ui.setupUi(self) self.ui.refreshButton.clicked.connect(self.insertPhotoConf) self.countPhotos = Observable(0) self.countPhotos.observe(self.updateStatusBar) self.ui.imageChoice.clicked.connect(self.setBackgroundChoice) self.ui.imageChoice.clicked.connect(self.updateStatusBar) self.ui.customChoice.clicked.connect(self.setBackgroundChoice) self.ui.customChoice.clicked.connect(self.updateStatusBar) self.ui.makeCollageButton.clicked.connect(self.makeCollageControl)
def __init__(self, num): """ Initilizes the model to represent a start board - A board of the given size with only one randomly placed block of value 2 Will throw TypeError if num is not an integer greater than or equal to 2 """ if num < 2: raise TypeError('Arugment number must be larger than 2') self.size = int(num) self.unoccupied_squares = [] l = [] # build the grid of empty squares, and add all to the list of unoccupied squares for i in range(num): m = [] for j in range(num): coordinate = i, j self.unoccupied_squares.append(coordinate) m.append(EMPTY_SQUARE_VALUE) l.append(m) # the grid is observable, so the controller can listen for changes self.grid = l self.last_move = Observable(None)
def setBackgroundChoice(self): for i in reversed(range(self.ui.chosenBackgroundLayout.count())): self.ui.chosenBackgroundLayout.itemAt(i).widget().setParent(None) if self.ui.imageChoice.isChecked(): self.ui.chosenBackgroundLayout.addWidget(BackgroundImageConf()) self.ui.chosenBackgroundLayout.itemAt( 0).widget().ui.backgroundImagePath.textChanged.connect( self.backgroundControlForStatusBar) if self.ui.customChoice.isChecked(): self.countColors = Observable(0) self.countColors.observe(self.colorBackgroundControlForStatusBar) self.ui.chosenBackgroundLayout.addWidget( BackgroundCustomConf(self.countColors)) self.ui.chosenBackgroundLayout.itemAt( 0).widget().ui.colorChoice.clicked.connect( self.updateStatusBar) self.ui.chosenBackgroundLayout.itemAt( 0).widget().ui.gradientChoice.clicked.connect( self.updateStatusBar)
from Observable import Observable from Observer import Observer ''' here, the Observable represents a parent process that notifies it's children about it's current state ''' if __name__ == "__main__": print("Running Tests") parent = Observable() child_1 = Observer() child_2 = Observer() child_3 = Observer() print("Children Added") assert(parent.state == "ready") parent.add_observer(child_1) parent.add_observer(child_2) parent.add_observer(child_3) parent.notify_observers() assert(parent.state == "ready") assert(child_1.parent_state == "ready") assert(child_2.parent_state == "ready") assert(child_3.parent_state == "ready")
def __init__(self, appIsAliveObservable, W=None, H=None, mines=None, rankingType=None, buttons=None, parameters=None): #This function is used both for the creation of a new game grid and for the loading of a saved one. super().__init__() #If a rankings-related file exists, this file is loaded. Else there are no rankings yet for the application. if os.path.exists("DataSaved/Rankings/Rankings.pkl"): with open("DataSaved/Rankings/Rankings.pkl", "rb") as input: rankings = pickle.load(input) else: rankings = None if W is None and H is None and mines is None and rankingType is None and buttons is None and parameters is None: #When the application is started, it tries to find a file containing an autosave of the last played game. if os.path.exists("DataSaved/AutoSavedGames/AutoSave.pkl"): isAutoLoading = Observable(False) #If the file exixts, a dialog appears and the user has the possibility to choice between the loading of the last played game and the creation of a new game grid. dialog = AutoSaveDialog(isAutoLoading) dialog.exec_() if isAutoLoading.value: with open("DataSaved/AutoSavedGames/AutoSave.pkl", "rb") as input: vectorLoaded = pickle.load(input) W = vectorLoaded[0][0] H = vectorLoaded[0][1] mines = vectorLoaded[0][2] rankingType = vectorLoaded[0][3] buttons = vectorLoaded[2] parameters = vectorLoaded[1] else: os.remove("DataSaved/AutoSavedGames/AutoSave.pkl") if W is None and H is None and mines is None and rankingType is None: #By default, the ranking type is the Intermediate type. self._model = MinesweeperCloneModel(appIsAliveObservable, 1, rankings=rankings) else: self._model = MinesweeperCloneModel(appIsAliveObservable, rankingType, W, H, mines, rankings=rankings) self._ui = Ui_MinesweeperClone() self._ui.setupUi(self) for i in range(3): self.makeRankings(i) self.makeGrid() self._model.observeCounterMinesUpdate(lambda counterMines: self._ui.lcdMines.display(counterMines)) self._model.counterMines = self._model.mines self._ui.refreshButton.clicked.connect(self.refreshGrid) self._ui.actionNew.triggered.connect(self.openNewGameDialog) self._ui.actionSaveAs.triggered.connect(self.openSaveAsDialog) self._ui.actionLoad.triggered.connect(self.openLoadDialog) self._ui.actionDelete.triggered.connect(self.openDeleteDialog) self._ui.actionControls.triggered.connect(self.openControlsDialog) if buttons is not None: for i in range(len(buttons)): self._model.getItemModelsGridButtons(buttons[i][1] * self._model.W + buttons[i][0]).loadButton(buttons[i][2], buttons[i][3], buttons[i][4], buttons[i][5], buttons[i][6]) if parameters is None: threadTimer = threading.Thread(target=self.timerUp, args=[0]) threadTimer.start() self.setGeometry(0, 0, 1280, 720) else: self._model.counterMines = parameters[1] threadTimer = threading.Thread(target=self.timerUp, args=[parameters[0]]) threadTimer.start() while self._ui.lcdTime.value() != parameters[0]: pass if not(parameters[2]) and not(parameters[3]): self._model.isBlocked = parameters[4] else: if parameters[2]: self._ui.statusbar.setStyleSheet("color:green; font-size: 14pt;") self._ui.statusbar.showMessage("You Win!") self._model.isWin = True else: self._ui.statusbar.setStyleSheet("color:red; font-size: 14pt;") self._ui.statusbar.showMessage("You Loose!") self._model.isLos = True self.setGeometry(parameters[5][0], parameters[5][1], parameters[5][2], parameters[5][3]) threadAutoSave = threading.Thread(target=self.autosave) threadAutoSave.start()
def setUp(self): self.undOb = Observable() self.bot1 = TestObserver() self.bot2 = TestObserver()
print(key,":",value) class ObserverB(BaseClass): '''A type of observerA class''' def __init__(self): '''Observer A constructor''' def update(self, *args, **kwargs): '''update callback which would be invoked''' print("ObserverB update invoked") for arg in args: print(arg) for key,value in kwargs.items(): print(key,":",value) if __name__ == "__main__": underObservation = Observable() bot1 = ObserverA() bot2 = ObserverB() underObservation.register(bot1) underObservation.register(bot2) underObservation.update_observers(('SMA indicates SELL', 'Bollinger Resistance', 'SELL'), {"Lotsize": 37, "TakeProfit": 300, "SL": 50})
from PyQt5.QtWidgets import QApplication import sys from MinesweeperClone import MinesweeperClone from Observable import Observable app = QApplication(sys.argv) appIsAlive = Observable( True ) #This Observable is used to communicate to the background threads when the application is closed by the user. window = MinesweeperClone(appIsAlive) window.show() app.exec_() appIsAlive.value = False
def __init__(self): self.myMoney = Observable(0)
from Observable import Observable from observer import Observer class AmericanStockMarket(Observer): def update(self, *args, **kwargs): print("American stock market received: {0}\n{1}".format(args, kwargs)) class EuropeanStockMarket(Observer): def update(self, *args, **kwargs): print("European stock market received: {0}\n{1}".format(args, kwargs)) if __name__ == "__main__": observable = Observable() american_observer = AmericanStockMarket() observable.register(american_observer) european_observer = EuropeanStockMarket() observable.register(european_observer) observable.update_observers('Market Rally', something='Hello World')