How to use header method in mountebank

Best JavaScript code snippet using mountebank

testCQCMessages.py

Source:testCQCMessages.py Github

copy

Full Screen

1#2# Copyright (c) 2018, Stephanie Wehner and Axel Dahlberg3# All rights reserved.4#5# Redistribution and use in source and binary forms, with or without6# modification, are permitted provided that the following conditions are met:7# 1. Redistributions of source code must retain the above copyright8# notice, this list of conditions and the following disclaimer.9# 2. Redistributions in binary form must reproduce the above copyright10# notice, this list of conditions and the following disclaimer in the11# documentation and/or other materials provided with the distribution.12# 3. All advertising materials mentioning features or use of this software13# must display the following acknowledgement:14# This product includes software developed by Stephanie Wehner, QuTech.15# 4. Neither the name of the QuTech organization nor the16# names of its contributors may be used to endorse or promote products17# derived from this software without specific prior written permission.18#19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY20# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED21# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE22# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY23# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES24# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;25# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND26# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29import json30import unittest31import os32from SimulaQron.cqc.backend.cqcLogMessageHandler import CQCLogMessageHandler33from SimulaQron.cqc.pythonLib.cqc import CQCConnection, qubit, CQCUnsuppError, QubitNotActiveError34from SimulaQron.cqc.backend.cqcHeader import (35 CQCCmdHeader,36 CQC_CMD_SEND,37 CQC_CMD_EPR,38 CQC_CMD_CNOT,39 CQC_CMD_CPHASE,40 CQC_CMD_ROT_X,41 CQC_CMD_ROT_Y,42 CQC_CMD_ROT_Z,43 CQC_TP_COMMAND,44 CQC_TP_FACTORY,45 CQC_CMD_I,46 CQC_CMD_X,47 CQC_CMD_Y,48 CQC_CMD_Z,49 CQC_CMD_T,50 CQC_CMD_H,51 CQC_CMD_K,52 CQC_CMD_NEW,53 CQC_CMD_MEASURE,54 CQC_CMD_MEASURE_INPLACE,55 CQC_CMD_RESET,56 CQC_CMD_RECV,57 CQC_CMD_EPR_RECV,58 CQC_CMD_ALLOCATE,59 CQC_CMD_RELEASE,60 CQCCommunicationHeader,61 CQCXtraQubitHeader,62 CQCRotationHeader,63 CQCFactoryHeader,64 CQC_CMD_HDR_LENGTH,65)66def get_last_entries(amount):67 file = "{}/logFile.json".format(CQCLogMessageHandler.dir_path)68 with open(file, "r") as outfile:69 logData = json.load(outfile)70 return logData[-amount:]71class CQCMessageTest(unittest.TestCase):72 # Only tests cqc_commands at the moment.73 # So no messages that are send back (notifications)74 @classmethod75 def setUpClass(cls):76 try:77 os.remove("{}/logFile.json".format(CQCLogMessageHandler.dir_path))78 except OSError:79 pass80 @classmethod81 def tearDownClass(cls):82 try:83 os.remove("{}/logFile.json".format(CQCLogMessageHandler.dir_path))84 except OSError:85 pass86 def testNewQubit(self):87 with CQCConnection("Alice", appID=1) as alice:88 qubit(alice, block=False, notify=False)89 lastEntry = get_last_entries(1)[0]90 cmd_header = lastEntry["cmd_header"]91 self.assertEqual(lastEntry["node_name"], "Alice")92 self.assertEqual(cmd_header["instruction"], CQC_CMD_NEW)93 self.assertEqual(cmd_header["block"], False)94 self.assertEqual(cmd_header["notify"], False)95 cqc_header = lastEntry["cqc_header"]96 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)97 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)98 self.assertEqual(cqc_header["app_id"], 1)99 def testI(self):100 with CQCConnection("Alice", appID=1) as alice:101 q1 = qubit(alice)102 q1.I()103 lastEntry = get_last_entries(1)[0]104 self.assertEqual(lastEntry["node_name"], "Alice")105 cmd_header = lastEntry["cmd_header"]106 self.assertEqual(cmd_header["instruction"], CQC_CMD_I)107 self.assertEqual(cmd_header["block"], True)108 self.assertEqual(cmd_header["notify"], True)109 cqc_header = lastEntry["cqc_header"]110 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)111 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)112 self.assertEqual(cqc_header["app_id"], 1)113 def testX(self):114 with CQCConnection("Alice", appID=1) as alice:115 q1 = qubit(alice)116 q1.X()117 lastEntry = get_last_entries(1)[0]118 self.assertEqual(lastEntry["node_name"], "Alice")119 cmd_header = lastEntry["cmd_header"]120 self.assertEqual(cmd_header["instruction"], CQC_CMD_X)121 self.assertEqual(cmd_header["block"], True)122 self.assertEqual(cmd_header["notify"], True)123 cqc_header = lastEntry["cqc_header"]124 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)125 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)126 self.assertEqual(cqc_header["app_id"], 1)127 def testY(self):128 with CQCConnection("Alice", appID=1) as alice:129 q1 = qubit(alice)130 q1.Y()131 lastEntry = get_last_entries(1)[0]132 self.assertEqual(lastEntry["node_name"], "Alice")133 cmd_header = lastEntry["cmd_header"]134 self.assertEqual(cmd_header["instruction"], CQC_CMD_Y)135 self.assertEqual(cmd_header["block"], True)136 self.assertEqual(cmd_header["notify"], True)137 cqc_header = lastEntry["cqc_header"]138 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)139 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)140 self.assertEqual(cqc_header["app_id"], 1)141 def testZ(self):142 with CQCConnection("Alice", appID=1) as alice:143 q1 = qubit(alice)144 q1.Z()145 lastEntry = get_last_entries(1)[0]146 self.assertEqual(lastEntry["node_name"], "Alice")147 cmd_header = lastEntry["cmd_header"]148 self.assertEqual(cmd_header["instruction"], CQC_CMD_Z)149 self.assertEqual(cmd_header["block"], True)150 self.assertEqual(cmd_header["notify"], True)151 cqc_header = lastEntry["cqc_header"]152 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)153 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)154 self.assertEqual(cqc_header["app_id"], 1)155 def testH(self):156 with CQCConnection("Alice", appID=1) as alice:157 q1 = qubit(alice)158 q1.H()159 lastEntry = get_last_entries(1)[0]160 self.assertEqual(lastEntry["node_name"], "Alice")161 cmd_header = lastEntry["cmd_header"]162 self.assertEqual(cmd_header["instruction"], CQC_CMD_H)163 self.assertEqual(cmd_header["block"], True)164 self.assertEqual(cmd_header["notify"], True)165 cqc_header = lastEntry["cqc_header"]166 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)167 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)168 self.assertEqual(cqc_header["app_id"], 1)169 def testT(self):170 with CQCConnection("Alice", appID=1) as alice:171 q1 = qubit(alice)172 q1.T()173 lastEntry = get_last_entries(1)[0]174 self.assertEqual(lastEntry["node_name"], "Alice")175 cmd_header = lastEntry["cmd_header"]176 self.assertEqual(cmd_header["instruction"], CQC_CMD_T)177 self.assertEqual(cmd_header["block"], True)178 self.assertEqual(cmd_header["notify"], True)179 cqc_header = lastEntry["cqc_header"]180 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)181 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)182 self.assertEqual(cqc_header["app_id"], 1)183 def testK(self):184 with CQCConnection("Alice", appID=1) as alice:185 q1 = qubit(alice)186 q1.K()187 lastEntry = get_last_entries(1)[0]188 self.assertEqual(lastEntry["node_name"], "Alice")189 cmd_header = lastEntry["cmd_header"]190 self.assertEqual(cmd_header["instruction"], CQC_CMD_K)191 self.assertEqual(cmd_header["block"], True)192 self.assertEqual(cmd_header["notify"], True)193 cqc_header = lastEntry["cqc_header"]194 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)195 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)196 self.assertEqual(cqc_header["app_id"], 1)197 def testRotX(self):198 with CQCConnection("Alice", appID=1) as alice:199 q1 = qubit(alice)200 q1.rot_X(200)201 lastEntry = get_last_entries(1)[0]202 self.assertEqual(lastEntry["node_name"], "Alice")203 cmd_header = lastEntry["cmd_header"]204 self.assertEqual(cmd_header["instruction"], CQC_CMD_ROT_X)205 self.assertEqual(cmd_header["block"], True)206 self.assertEqual(cmd_header["notify"], True)207 cqc_header = lastEntry["cqc_header"]208 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)209 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH + CQCRotationHeader.HDR_LENGTH)210 self.assertEqual(cqc_header["app_id"], 1)211 xtra_header = lastEntry["xtra_header"]212 self.assertEqual(xtra_header["step"], 200)213 def testRotY(self):214 with CQCConnection("Alice", appID=1) as alice:215 q1 = qubit(alice)216 q1.rot_Y(200)217 lastEntry = get_last_entries(1)[0]218 self.assertEqual(lastEntry["node_name"], "Alice")219 cmd_header = lastEntry["cmd_header"]220 self.assertEqual(cmd_header["instruction"], CQC_CMD_ROT_Y)221 self.assertEqual(cmd_header["block"], True)222 self.assertEqual(cmd_header["notify"], True)223 cqc_header = lastEntry["cqc_header"]224 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)225 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH + CQCRotationHeader.HDR_LENGTH)226 self.assertEqual(cqc_header["app_id"], 1)227 xtra_header = lastEntry["xtra_header"]228 self.assertEqual(xtra_header["step"], 200)229 def testRotZ(self):230 with CQCConnection("Alice", appID=1) as alice:231 q1 = qubit(alice)232 q1.rot_Z(200)233 lastEntry = get_last_entries(1)[0]234 self.assertEqual(lastEntry["node_name"], "Alice")235 cmd_header = lastEntry["cmd_header"]236 self.assertEqual(cmd_header["instruction"], CQC_CMD_ROT_Z)237 self.assertEqual(cmd_header["block"], True)238 self.assertEqual(cmd_header["notify"], True)239 cqc_header = lastEntry["cqc_header"]240 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)241 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH + CQCRotationHeader.HDR_LENGTH)242 self.assertEqual(cqc_header["app_id"], 1)243 xtra_header = lastEntry["xtra_header"]244 self.assertEqual(xtra_header["step"], 200)245 def testRotXFail(self):246 with CQCConnection("Alice", appID=1) as alice:247 q1 = qubit(alice)248 with self.assertRaises(ValueError):249 q1.rot_X(256)250 def testRotXFailNone(self):251 with CQCConnection("Alice", appID=1) as alice:252 q1 = qubit(alice)253 with self.assertRaises(ValueError):254 q1.rot_X(None)255 def testRotXFailNaN(self):256 with CQCConnection("Alice", appID=1) as alice:257 q1 = qubit(alice)258 with self.assertRaises(ValueError):259 q1.rot_X("four")260 def testRotXFailNegative(self):261 with CQCConnection("Alice", appID=1) as alice:262 q1 = qubit(alice)263 with self.assertRaises(ValueError):264 q1.rot_X(-1)265 def testRotXFailFloat(self):266 with CQCConnection("Alice", appID=1) as alice:267 q1 = qubit(alice)268 with self.assertRaises(ValueError):269 q1.rot_X(1.1)270 def testCNot(self):271 with CQCConnection("Alice", appID=1) as alice:272 q1 = qubit(alice)273 q2 = qubit(alice)274 q1.cnot(q2)275 lastEntry = get_last_entries(1)[0]276 self.assertEqual(lastEntry["node_name"], "Alice")277 cmd_header = lastEntry["cmd_header"]278 self.assertEqual(cmd_header["instruction"], CQC_CMD_CNOT)279 self.assertEqual(cmd_header["block"], True)280 self.assertEqual(cmd_header["notify"], True)281 cqc_header = lastEntry["cqc_header"]282 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)283 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH + CQCXtraQubitHeader.HDR_LENGTH)284 self.assertEqual(cqc_header["app_id"], 1)285 xtra_header = lastEntry["xtra_header"]286 self.assertEqual(xtra_header["qubit_id"], cmd_header["qubit_id"] + 1)287 def testCNotRemote(self):288 with CQCConnection("Alice", appID=1) as alice:289 # The appId in xtra_header['app_id'] is not 2 when testing.290 # In fact, doing this code in a real application result in an error as of 2018-03-12291 with CQCConnection("Bob", appID=2) as bob:292 q1 = qubit(alice)293 q2 = qubit(bob)294 with self.assertRaises(CQCUnsuppError):295 q1.cnot(q2)296 def testCPhase(self):297 with CQCConnection("Alice", appID=1) as alice:298 q1 = qubit(alice)299 q2 = qubit(alice)300 q1.cphase(q2)301 lastEntry = get_last_entries(1)[0]302 self.assertEqual(lastEntry["node_name"], "Alice")303 cmd_header = lastEntry["cmd_header"]304 self.assertEqual(cmd_header["instruction"], CQC_CMD_CPHASE)305 self.assertEqual(cmd_header["block"], True)306 self.assertEqual(cmd_header["notify"], True)307 cqc_header = lastEntry["cqc_header"]308 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)309 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH + CQCXtraQubitHeader.HDR_LENGTH)310 self.assertEqual(cqc_header["app_id"], 1)311 xtra_header = lastEntry["xtra_header"]312 self.assertEqual(xtra_header["qubit_id"], cmd_header["qubit_id"] + 1)313 def testSend(self):314 with CQCConnection("Alice", appID=1) as alice:315 q1 = qubit(alice)316 alice.sendQubit(q1, "Bob", remote_appID=2)317 lastEntry = get_last_entries(1)[0]318 self.assertEqual(lastEntry["node_name"], "Alice")319 cmd_header = lastEntry["cmd_header"]320 self.assertEqual(cmd_header["instruction"], CQC_CMD_SEND)321 self.assertEqual(cmd_header["block"], True)322 self.assertEqual(cmd_header["notify"], True)323 cqc_header = lastEntry["cqc_header"]324 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)325 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH + CQCCommunicationHeader.HDR_LENGTH)326 self.assertEqual(cqc_header["app_id"], 1)327 xtra_header = lastEntry["xtra_header"]328 self.assertEqual(xtra_header["remote_app_id"], 2)329 self.assertNotEqual(xtra_header["remote_node"], 0)330 self.assertNotEqual(xtra_header["remote_port"], 0)331 def testSendSelf(self):332 with CQCConnection("Alice", appID=1) as alice:333 # Should not work in a real application334 q1 = qubit(alice)335 alice.sendQubit(q1, "Alice", remote_appID=1)336 lastEntry = get_last_entries(1)[0]337 self.assertEqual(lastEntry["node_name"], "Alice")338 cmd_header = lastEntry["cmd_header"]339 self.assertEqual(cmd_header["instruction"], CQC_CMD_SEND)340 self.assertEqual(cmd_header["block"], True)341 self.assertEqual(cmd_header["notify"], True)342 cqc_header = lastEntry["cqc_header"]343 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)344 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH + CQCCommunicationHeader.HDR_LENGTH)345 self.assertEqual(cqc_header["app_id"], 1)346 xtra_header = lastEntry["xtra_header"]347 self.assertEqual(xtra_header["remote_app_id"], 1)348 self.assertNotEqual(xtra_header["remote_node"], 0)349 self.assertNotEqual(xtra_header["remote_port"], 0)350 def testRecv(self):351 with CQCConnection("Alice", appID=1) as alice:352 alice.recvQubit()353 lastEntry = get_last_entries(1)[0]354 self.assertEqual(lastEntry["node_name"], "Alice")355 cmd_header = lastEntry["cmd_header"]356 self.assertEqual(cmd_header["instruction"], CQC_CMD_RECV)357 self.assertEqual(cmd_header["block"], True)358 self.assertEqual(cmd_header["notify"], True)359 cqc_header = lastEntry["cqc_header"]360 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)361 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)362 self.assertEqual(cqc_header["app_id"], 1)363 def testEPRSend(self):364 with CQCConnection("Alice", appID=1) as alice:365 alice.createEPR("Bob", remote_appID=2)366 entries = get_last_entries(5)367 cmd_header_epr = entries[0]["cmd_header"]368 self.assertEqual(entries[0]["node_name"], "Alice")369 self.assertEqual(cmd_header_epr["instruction"], CQC_CMD_EPR)370 self.assertEqual(cmd_header_epr["block"], True)371 self.assertEqual(cmd_header_epr["notify"], True)372 cqc_header_epr = entries[0]["cqc_header"]373 self.assertEqual(cqc_header_epr["type"], CQC_TP_COMMAND)374 for i in range(5):375 self.assertEqual(376 entries[i]["cqc_header"]["header_length"], CQC_CMD_HDR_LENGTH + CQCCommunicationHeader.HDR_LENGTH377 )378 self.assertEqual(cqc_header_epr["app_id"], 1)379 xtra_header_epr = entries[0]["xtra_header"]380 self.assertEqual(xtra_header_epr["remote_app_id"], 2)381 self.assertNotEqual(xtra_header_epr["remote_node"], 0)382 self.assertNotEqual(xtra_header_epr["remote_port"], 0)383 # Check if the qubits are created correctly384 # The protocol already knows what do to on EPR, so no new headers are made,385 # This means that the header of createEPR() is send into new(),386 # New headers have to be made for H() and CNOT() for the qubit ids,387 # but the instruction is not needed, defaults to 0388 self.assertEqual(entries[1]["cmd_header"]["instruction"], CQC_CMD_EPR)389 self.assertEqual(entries[3]["cmd_header"]["instruction"], 0)390 self.assertEqual(entries[4]["cmd_header"]["instruction"], 0)391 self.assertEqual(entries[4]["cmd_header"]["qubit_id"] + 1, entries[4]["xtra_header"]["qubit_id"])392 def testEPRRecv(self):393 with CQCConnection("Alice", appID=1) as alice:394 alice.recvEPR()395 lastEntry = get_last_entries(1)[0]396 self.assertEqual(lastEntry["node_name"], "Alice")397 cmd_header = lastEntry["cmd_header"]398 self.assertEqual(cmd_header["instruction"], CQC_CMD_EPR_RECV)399 self.assertEqual(cmd_header["block"], True)400 self.assertEqual(cmd_header["notify"], True)401 cqc_header = lastEntry["cqc_header"]402 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)403 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)404 self.assertEqual(cqc_header["app_id"], 1)405 def testMeasure(self):406 with CQCConnection("Alice", appID=1) as alice:407 q1 = qubit(alice)408 m1 = q1.measure()409 # We've set that for this testing purposes, the measurement outcome is410 # always 2411 self.assertEqual(m1, 2)412 lastEntry = get_last_entries(1)[0]413 self.assertEqual(lastEntry["node_name"], "Alice")414 cmd_header = lastEntry["cmd_header"]415 self.assertEqual(cmd_header["instruction"], CQC_CMD_MEASURE)416 self.assertEqual(cmd_header["block"], True)417 self.assertEqual(cmd_header["notify"], False)418 cqc_header = lastEntry["cqc_header"]419 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)420 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)421 self.assertEqual(cqc_header["app_id"], 1)422 self.assertFalse(q1._active)423 def testMeasureInplace(self):424 with CQCConnection("Alice", appID=1) as alice:425 q1 = qubit(alice)426 m1 = q1.measure(inplace=True)427 # We've set that for this testing purposes, the measurement outcome is428 # always 2429 self.assertEqual(m1, 2)430 lastEntry = get_last_entries(1)[0]431 self.assertEqual(lastEntry["node_name"], "Alice")432 cmd_header = lastEntry["cmd_header"]433 self.assertEqual(cmd_header["instruction"], CQC_CMD_MEASURE_INPLACE)434 self.assertEqual(cmd_header["block"], True)435 self.assertEqual(cmd_header["notify"], False)436 cqc_header = lastEntry["cqc_header"]437 self.assertEqual(cqc_header["type"], CQC_TP_COMMAND)438 self.assertEqual(cqc_header["header_length"], CQC_CMD_HDR_LENGTH)439 self.assertEqual(cqc_header["app_id"], 1)440 self.assertTrue(q1._active)441 def testFactoryZero(self):442 with CQCConnection("Alice", appID=1) as alice:443 q1 = qubit(alice)444 alice.set_pending(True)445 q1.X()446 alice.flush_factory(0, do_sequence=False)447 alice.set_pending(False)448 q1.measure(inplace=True)449 # Checking the factory and the measure, factory should not log any commands450 lastEntries = get_last_entries(2)451 factoryEntry = lastEntries[0]452 self.assertEqual(factoryEntry["node_name"], "Alice")453 factory_cqc_header = factoryEntry["cqc_header"]454 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)455 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH456 self.assertEqual(factory_cqc_header["header_length"], expected_length)457 self.assertEqual(factoryEntry["factory_iterations"], 0)458 measureEntry = lastEntries[1]459 self.assertEqual(measureEntry["node_name"], "Alice")460 self.assertEqual(measureEntry["cmd_header"]["instruction"], CQC_CMD_MEASURE_INPLACE)461 self.assertEqual(measureEntry["cmd_header"]["qubit_id"], q1._qID)462 q1.measure()463 def testFactoryOnce(self):464 with CQCConnection("Alice", appID=1) as alice:465 q1 = qubit(alice)466 alice.set_pending(True)467 q1.X()468 alice.flush_factory(1, do_sequence=False)469 alice.set_pending(False)470 q1.measure(inplace=True)471 # Doing a factory once is equal to doing a sequence, so the factory header is not send472 lastEntries = get_last_entries(2)473 xEntry = lastEntries[0]474 self.assertEqual(xEntry["node_name"], "Alice")475 x_cmd_cmd_header = xEntry["cmd_header"]476 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_X)477 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)478 # cqc header is the same as the first.479 measureEntry = lastEntries[1]480 self.assertEqual(measureEntry["node_name"], "Alice")481 self.assertEqual(measureEntry["cmd_header"]["instruction"], CQC_CMD_MEASURE_INPLACE)482 self.assertEqual(measureEntry["cmd_header"]["qubit_id"], q1._qID)483 def testFactoryN(self):484 with CQCConnection("Alice", appID=1) as alice:485 q1 = qubit(alice)486 alice.set_pending(True)487 q1.X()488 alice.flush_factory(10, do_sequence=False)489 alice.set_pending(False)490 q1.measure(inplace=True)491 # Checking the factory and the measure, factory should not log any commands492 lastEntries = get_last_entries(12)493 factoryEntry = lastEntries[0]494 self.assertEqual(factoryEntry["node_name"], "Alice")495 factory_cqc_header = factoryEntry["cqc_header"]496 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)497 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH498 self.assertEqual(factory_cqc_header["header_length"], expected_length)499 self.assertEqual(factoryEntry["factory_iterations"], 10)500 for i in range(1, 11):501 xEntry = lastEntries[i]502 x_cmd_cmd_header = xEntry["cmd_header"]503 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_X)504 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)505 # cqc header is the same as the first.506 measureEntry = lastEntries[11]507 self.assertEqual(measureEntry["cmd_header"]["instruction"], CQC_CMD_MEASURE_INPLACE)508 self.assertEqual(measureEntry["cmd_header"]["qubit_id"], q1._qID)509 def testFactoryCNOTFalse(self):510 with CQCConnection("Alice", appID=1) as alice:511 q1 = qubit(alice)512 qubit(alice)513 with self.assertRaises(CQCUnsuppError):514 alice.set_pending(True)515 q1.cnot(q1)516 alice.flush_factory(10, do_sequence=False)517 alice.set_pending(False)518 def testFactoryCNOT(self):519 with CQCConnection("Alice", appID=1) as alice:520 q1 = qubit(alice)521 q2 = qubit(alice)522 alice.set_pending(True)523 q1.cnot(q2)524 alice.flush_factory(10, do_sequence=False)525 alice.set_pending(False)526 entries = get_last_entries(11)527 factoryEntry = entries[0]528 self.assertEqual(factoryEntry["node_name"], "Alice")529 factory_cqc_header = factoryEntry["cqc_header"]530 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)531 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH + CQCXtraQubitHeader.HDR_LENGTH532 self.assertEqual(factory_cqc_header["header_length"], expected_length)533 self.assertEqual(factoryEntry["factory_iterations"], 10)534 for i in range(1, 11):535 xEntry = entries[i]536 x_cmd_cmd_header = xEntry["cmd_header"]537 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_CNOT)538 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)539 x = xEntry["xtra_header"]540 self.assertEqual(x["qubit_id"], q2._qID)541 def testFactoryCPHASE(self):542 with CQCConnection("Alice", appID=1) as alice:543 q1 = qubit(alice)544 q2 = qubit(alice)545 alice.set_pending(True)546 q1.cphase(q2)547 alice.flush_factory(10, do_sequence=False)548 alice.set_pending(False)549 entries = get_last_entries(11)550 factoryEntry = entries[0]551 self.assertEqual(factoryEntry["node_name"], "Alice")552 factory_cqc_header = factoryEntry["cqc_header"]553 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)554 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH + CQCXtraQubitHeader.HDR_LENGTH555 self.assertEqual(factory_cqc_header["header_length"], expected_length)556 self.assertEqual(factoryEntry["factory_iterations"], 10)557 for i in range(1, 11):558 xEntry = entries[i]559 x_cmd_cmd_header = xEntry["cmd_header"]560 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_CPHASE)561 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)562 x = xEntry["xtra_header"]563 self.assertEqual(x["qubit_id"], q2._qID)564 def testFactoryROTX(self):565 with CQCConnection("Alice", appID=1) as alice:566 q1 = qubit(alice)567 alice.set_pending(True)568 q1.rot_X(step=5)569 alice.flush_factory(10, do_sequence=False)570 alice.set_pending(False)571 q1.measure(inplace=True)572 # Checking the factory and the measure, factory should not log any commands573 lastEntries = get_last_entries(12)574 factoryEntry = lastEntries[0]575 self.assertEqual(factoryEntry["node_name"], "Alice")576 factory_cqc_header = factoryEntry["cqc_header"]577 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)578 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH + CQCRotationHeader.HDR_LENGTH579 self.assertEqual(factory_cqc_header["header_length"], expected_length)580 self.assertEqual(factoryEntry["factory_iterations"], 10)581 for i in range(1, 11):582 xEntry = lastEntries[i]583 x_cmd_cmd_header = xEntry["cmd_header"]584 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_ROT_X)585 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)586 xtra_header = xEntry["xtra_header"]587 self.assertEqual(xtra_header["step"], 5)588 # cqc header is the same as the first.589 measureEntry = lastEntries[11]590 self.assertEqual(measureEntry["cmd_header"]["instruction"], CQC_CMD_MEASURE_INPLACE)591 self.assertEqual(measureEntry["cmd_header"]["qubit_id"], q1._qID)592 def testFactoryNew(self):593 with CQCConnection("Alice", appID=1) as alice:594 # Should return a list of qubits with consecutive qubit ids595 alice.set_pending(True)596 qubit(alice)597 qubits = alice.flush_factory(10, do_sequence=False)598 # It is preferable to use the following however:599 # qubits = alice.allocate_qubits(10)600 alice.set_pending(False)601 # Checking the factory and the measure, factory should not log any commands602 lastEntries = get_last_entries(11)603 factoryEntry = lastEntries[0]604 self.assertEqual(factoryEntry["node_name"], "Alice")605 factory_cqc_header = factoryEntry["cqc_header"]606 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)607 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH608 self.assertEqual(factory_cqc_header["header_length"], expected_length)609 self.assertEqual(factoryEntry["factory_iterations"], 10)610 for i in range(1, 11):611 xEntry = lastEntries[i]612 x_cmd_cmd_header = xEntry["cmd_header"]613 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_NEW)614 curID = qubits[0]._qID615 for q in qubits[1:]:616 self.assertEqual(q._qID, curID + 1)617 curID = q._qID618 def testFactoryMeasure(self):619 with CQCConnection("Alice", appID=1) as alice:620 # this one will go wrong in actual environment621 q1 = qubit(alice)622 alice.set_pending(True)623 q1.measure(inplace=False)624 # with self.assertRaises(QubitNotActiveError):625 measurements = alice.flush_factory(10, do_sequence=False)626 alice.set_pending(False)627 # All measurements should be equal to 2628 self.assertTrue(all(x == 2 for x in measurements))629 lastEntries = get_last_entries(11)630 factoryEntry = lastEntries[0]631 self.assertEqual(factoryEntry["node_name"], "Alice")632 factory_cqc_header = factoryEntry["cqc_header"]633 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)634 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH635 self.assertEqual(factory_cqc_header["header_length"], expected_length)636 self.assertEqual(factoryEntry["factory_iterations"], 10)637 for i in range(1, 11):638 xEntry = lastEntries[i]639 x_cmd_cmd_header = xEntry["cmd_header"]640 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_MEASURE)641 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)642 def testFactoryMeasureInplace(self):643 with CQCConnection("Alice", appID=1) as alice:644 # should give the same results as inplace = false645 q1 = qubit(alice)646 alice.set_pending(True)647 q1.measure(inplace=True)648 measurements = alice.flush_factory(10, do_sequence=False)649 alice.set_pending(False)650 # All measurements should be equal to 2651 self.assertTrue(all(x == 2 for x in measurements))652 lastEntries = get_last_entries(11)653 factoryEntry = lastEntries[0]654 self.assertEqual(factoryEntry["node_name"], "Alice")655 factory_cqc_header = factoryEntry["cqc_header"]656 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)657 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH658 self.assertEqual(factory_cqc_header["header_length"], expected_length)659 self.assertEqual(factoryEntry["factory_iterations"], 10)660 for i in range(1, 11):661 xEntry = lastEntries[i]662 x_cmd_cmd_header = xEntry["cmd_header"]663 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_MEASURE_INPLACE)664 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)665 def testFactoryReset(self):666 with CQCConnection("Alice", appID=1) as alice:667 q1 = qubit(alice)668 alice.set_pending(True)669 q1.reset()670 res = alice.flush_factory(10, do_sequence=False)671 alice.set_pending(False)672 self.assertListEqual(res, [])673 lastEntries = get_last_entries(11)674 factoryEntry = lastEntries[0]675 self.assertEqual(factoryEntry["node_name"], "Alice")676 factory_cqc_header = factoryEntry["cqc_header"]677 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)678 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH679 self.assertEqual(factory_cqc_header["header_length"], expected_length)680 self.assertEqual(factoryEntry["factory_iterations"], 10)681 for i in range(1, 11):682 xEntry = lastEntries[i]683 x_cmd_cmd_header = xEntry["cmd_header"]684 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_RESET)685 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)686 def testFactorySend(self):687 with CQCConnection("Alice", appID=1) as alice:688 q1 = qubit(alice)689 alice.set_pending(True)690 alice.sendQubit(q1, name="Bob", remote_appID=5)691 res = alice.flush_factory(10, do_sequence=False)692 alice.set_pending(False)693 self.assertListEqual(res, [])694 lastEntries = get_last_entries(11)695 factoryEntry = lastEntries[0]696 self.assertEqual(factoryEntry["node_name"], "Alice")697 factory_cqc_header = factoryEntry["cqc_header"]698 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)699 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH + CQCCommunicationHeader.HDR_LENGTH700 self.assertEqual(factory_cqc_header["header_length"], expected_length)701 self.assertEqual(factoryEntry["factory_iterations"], 10)702 for i in range(1, 11):703 xEntry = lastEntries[i]704 x_cmd_cmd_header = xEntry["cmd_header"]705 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_SEND)706 self.assertEqual(x_cmd_cmd_header["qubit_id"], q1._qID)707 xtra_header = xEntry["xtra_header"]708 self.assertEqual(xtra_header["remote_app_id"], 5)709 self.assertGreater(xtra_header["remote_node"], 1)710 self.assertGreater(xtra_header["remote_port"], 1)711 def testFactoryRecv(self):712 with CQCConnection("Alice", appID=1) as alice:713 alice.set_pending(True)714 alice.recvQubit()715 qubits = alice.flush_factory(10, do_sequence=False)716 alice.set_pending(False)717 curID = qubits[0]._qID718 for q in qubits[1:]:719 self.assertEqual(q._qID, curID + 1)720 curID = q._qID721 lastEntries = get_last_entries(11)722 factoryEntry = lastEntries[0]723 self.assertEqual(factoryEntry["node_name"], "Alice")724 factory_cqc_header = factoryEntry["cqc_header"]725 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)726 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH727 self.assertEqual(factory_cqc_header["header_length"], expected_length)728 self.assertEqual(factoryEntry["factory_iterations"], 10)729 for i in range(1, 11):730 xEntry = lastEntries[i]731 x_cmd_cmd_header = xEntry["cmd_header"]732 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_RECV)733 def testFactoryEPR(self):734 with CQCConnection("Alice", appID=1) as alice:735 alice.set_pending(True)736 alice.createEPR(name="Bob", remote_appID=5)737 qubits = alice.flush_factory(10, do_sequence=False)738 alice.set_pending(False)739 lastEntries = get_last_entries(51)740 factoryEntry = lastEntries[0]741 self.assertEqual(factoryEntry["node_name"], "Alice")742 factory_cqc_header = factoryEntry["cqc_header"]743 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)744 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH + CQCCommunicationHeader.HDR_LENGTH745 self.assertEqual(factory_cqc_header["header_length"], expected_length)746 self.assertEqual(factoryEntry["factory_iterations"], 10)747 # Check if the qubits are created correctly748 # The protocol already knows what do to on EPR, so no new headers are made,749 # This means that the header of createEPR() is send into new(),750 # New headers have to be made for H() and CNOT() for the qubit ids,751 # but the instruction is not needed, defaults to 0752 curID = [qubits[0]._qID]753 for q in qubits[1:]:754 self.assertEqual(q._qID, curID[-1] + 2)755 curID.append(q._qID)756 for i in range(10):757 xEntry = lastEntries[5 * i + 1]758 x_cmd_cmd_header = xEntry["cmd_header"]759 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_EPR)760 xtra_header = xEntry["xtra_header"]761 self.assertEqual(xtra_header["remote_app_id"], 5)762 self.assertGreater(xtra_header["remote_node"], 0)763 self.assertGreater(xtra_header["remote_port"], 0)764 xEntry = lastEntries[5 * i + 2]765 x_cmd_cmd_header = xEntry["cmd_header"]766 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_EPR)767 xEntry = lastEntries[5 * i + 3]768 x_cmd_cmd_header = xEntry["cmd_header"]769 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_EPR)770 xEntry = lastEntries[5 * i + 4]771 x_cmd_cmd_header = xEntry["cmd_header"] # H Header772 self.assertEqual(x_cmd_cmd_header["instruction"], 0)773 id1 = x_cmd_cmd_header["qubit_id"]774 # Let's see the qubit id is in agreement with the received ones775 self.assertEqual(id1, curID[i])776 xEntry = lastEntries[5 * i + 5]777 x_cmd_cmd_header = xEntry["cmd_header"] # CNOT Header778 self.assertEqual(x_cmd_cmd_header["instruction"], 0)779 self.assertEqual(id1, x_cmd_cmd_header["qubit_id"])780 self.assertEqual(id1 + 1, xEntry["xtra_header"]["qubit_id"])781 def testFactoryEPR_RECV(self):782 with CQCConnection("Alice", appID=1) as alice:783 alice.set_pending(True)784 alice.recvEPR()785 qubits = alice.flush_factory(10, do_sequence=False)786 alice.set_pending(False)787 curID = qubits[0]._qID788 for q in qubits[1:]:789 self.assertEqual(q._qID, curID + 1)790 curID = q._qID791 lastEntries = get_last_entries(11)792 factoryEntry = lastEntries[0]793 self.assertEqual(factoryEntry["node_name"], "Alice")794 factory_cqc_header = factoryEntry["cqc_header"]795 self.assertEqual(factory_cqc_header["type"], CQC_TP_FACTORY)796 expected_length = CQCFactoryHeader.HDR_LENGTH + CQC_CMD_HDR_LENGTH797 self.assertEqual(factory_cqc_header["header_length"], expected_length)798 self.assertEqual(factoryEntry["factory_iterations"], 10)799 for i in range(1, 11):800 xEntry = lastEntries[i]801 x_cmd_cmd_header = xEntry["cmd_header"]802 self.assertEqual(x_cmd_cmd_header["instruction"], CQC_CMD_EPR_RECV)803 def testAllocate0(self):804 with CQCConnection("Alice", appID=1) as alice:805 qubits = alice.allocate_qubits(0)806 self.assertEqual(qubits, [])807 entry = get_last_entries(1)[0]808 self.assertEqual(entry["node_name"], "Alice")809 cqc_hdr = entry["cqc_header"]810 self.assertEqual(cqc_hdr["type"], CQC_TP_COMMAND)811 self.assertEqual(cqc_hdr["header_length"], CQCCmdHeader.HDR_LENGTH)812 cmd_hdr = entry["cmd_header"]813 self.assertEqual(cmd_hdr["instruction"], CQC_CMD_ALLOCATE)814 self.assertEqual(cmd_hdr["qubit_id"], 0)815 def testAllocate10(self):816 with CQCConnection("Alice", appID=1) as alice:817 qubits = alice.allocate_qubits(10)818 self.assertEqual(len(qubits), 10)819 curID = qubits[0]._qID820 for q in qubits[1:]:821 self.assertTrue(q._active)822 self.assertEqual(q._qID, curID + 1)823 curID = q._qID824 entry = get_last_entries(1)[0]825 self.assertEqual(entry["node_name"], "Alice")826 cqc_hdr = entry["cqc_header"]827 self.assertEqual(cqc_hdr["type"], CQC_TP_COMMAND)828 self.assertEqual(cqc_hdr["header_length"], CQCCmdHeader.HDR_LENGTH)829 cmd_hdr = entry["cmd_header"]830 self.assertEqual(cmd_hdr["instruction"], CQC_CMD_ALLOCATE)831 self.assertEqual(cmd_hdr["qubit_id"], 10)832 def testRelease(self):833 with CQCConnection("Alice", appID=1) as alice:834 qubits = alice.allocate_qubits(10)835 alice.release_qubits(qubits)836 for q in qubits:837 self.assertFalse(q._active)838 entries = get_last_entries(10)839 for i in range(10):840 entry = entries[i]841 self.assertEqual(entry["node_name"], "Alice")842 cqc_hdr = entry["cqc_header"]843 self.assertEqual(cqc_hdr["type"], CQC_TP_COMMAND)844 self.assertEqual(cqc_hdr["header_length"], 10 * CQCCmdHeader.HDR_LENGTH)845 cmd_hdr = entry["cmd_header"]846 self.assertEqual(cmd_hdr["instruction"], CQC_CMD_RELEASE)847 self.assertEqual(cmd_hdr["qubit_id"], qubits[i]._qID)848 def testReleaseWhenAlreadyReleased(self):849 with CQCConnection("Alice", appID=1) as alice:850 qubits = alice.allocate_qubits(10)851 qubits[0].measure()852 with self.assertRaises(QubitNotActiveError):853 alice.release_qubits(qubits)854 self.assertTrue(qubits[1]._active)855if __name__ == "__main__":...

Full Screen

Full Screen

personal.js

Source:personal.js Github

copy

Full Screen

1 // start header2 function getScrollAmountForStickyHeader() {3 return void 0 !== qodeGlobalVars.vars.page_scroll_amount_for_sticky && "" !== qodeGlobalVars.vars.page_scroll_amount_for_sticky ? amount = qodeGlobalVars.vars.page_scroll_amount_for_sticky : $(".carousel.full_screen").length ? amount = $(".carousel").height() : amount = scroll_amount_for_sticky, amount4 }5 6 function qodeBrowserDetection() {7 var e = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor),8 t = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor),9 o = navigator.userAgent.toLowerCase().indexOf("firefox") > -1,10 n = window.navigator.userAgent.indexOf("MSIE ");11 e && qode_body.addClass("qode-chrome"), t && qode_body.addClass("qode-safari"), o && qode_body.addClass("qode-firefox"), (n > 0 || navigator.userAgent.match(/Trident.*rv\:11\./)) && qode_body.addClass("qode-ms-explorer"), /Edge\/\d./i.test(navigator.userAgent) && qode_body.addClass("qode-edge")12 }13 14 function headerSize(e) {15 "use strict";16 //if ($("header.page_header").hasClass("scroll_top") && $("header.page_header").hasClass("has_top") && ($("header.page_header").hasClass("fixed") || $("header.page_header").hasClass("fixed_hiding")) && (e >= 0 && e <= 34 ? ($("header.page_header").css("top", -e), $("header.page_header").css("margin-top", 0), $(".header_top").show()) : e > 34 && ($("header.page_header").css("top", "-34px"), $("header.page_header").css("margin-top", 34), $(".header_top").hide())), sticky_amount = getScrollAmountForStickyHeader(), $("header").hasClass("regular") && (header_height - logo_height >= 10 ? $(".q_logo a").height(logo_height) : $(".q_logo a").height(header_height - 10), $(".q_logo a img").css("height", "100%")), $("header.page_header").hasClass("fixed") && ($top_header_height = $("header.page_header").hasClass("scroll_top") ? 34 : 0, header_height - e + $top_header_height >= min_header_height_scroll && e >= $top_header_height ? ($("header.page_header").removeClass("scrolled"), $("header:not(.centered_logo.centered_logo_animate) nav.main_menu > ul > li > a").css("line-height", header_height - e + $top_header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .side_menu_button").css("height", header_height - e + $top_header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .shopping_cart_inner").css("height", header_height - e + $top_header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .header_bottom .qode-login-register-widget.qode-user-logged-in .qode-logged-in-user").css("height", header_height - e + $top_header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .logo_wrapper").css("height", header_height - e + $top_header_height + "px"), header_height - logo_height > 0 ? $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", logo_height + "px") : $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", header_height - e + $top_header_height - 10 + "px")) : e < $top_header_height ? ($("header.page_header").removeClass("scrolled"), $("header:not(.centered_logo.centered_logo_animate) nav.main_menu > ul > li > a").css("line-height", header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .side_menu_button").css("height", header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .shopping_cart_inner").css("height", header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .header_bottom .qode-login-register-widget.qode-user-logged-in .qode-logged-in-user").css("height", header_height + "px"), $("header:not(.centered_logo.centered_logo_animate) .logo_wrapper").css("height", header_height + "px"), header_height - logo_height > 0 ? $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", logo_height + "px") : $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", header_height - 10 + "px")) : header_height - e + $top_header_height < min_header_height_scroll && ($("header.page_header").addClass("scrolled"), $("header:not(.centered_logo.centered_logo_animate) nav.main_menu > ul > li > a").css("line-height", min_header_height_scroll + "px"), $("header:not(.centered_logo.centered_logo_animate) .side_menu_button").css("height", min_header_height_scroll + "px"), $("header:not(.centered_logo.centered_logo_animate) .shopping_cart_inner").css("height", min_header_height_scroll + "px"), $("header:not(.centered_logo.centered_logo_animate) .header_bottom .qode-login-register-widget.qode-user-logged-in .qode-logged-in-user").css("height", min_header_height_scroll + "px"), $("header:not(.centered_logo.centered_logo_animate) .logo_wrapper").css("height", min_header_height_scroll + "px"), min_header_height_scroll - logo_height > 0 ? $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", logo_height + "px") : $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", min_header_height_scroll - 10 + "px")), $("header.page_header").hasClass("centered_logo") && $("header.page_header").hasClass("centered_logo_animate") ? header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height >= min_header_height_scroll && logo_height > min_header_height_scroll - 10 && e >= $top_header_height ? $(".q_logo a").height(header_height - e + $top_header_height - 10) : header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height >= min_header_height_scroll && logo_height > min_header_height_scroll - 10 && e < $top_header_height ? $(".q_logo a").height(header_height - 10) : header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height < min_header_height_scroll && logo_height > min_header_height_scroll - 10 ? $(".q_logo a").height(min_header_height_scroll - 10) : header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height < min_header_height_scroll && logo_height < min_header_height_scroll - 10 ? $(".q_logo a").height(logo_height) : (e + $top_header_height === 0 && header_height, $(".q_logo a").height(logo_height)) : $("header.page_header").hasClass("centered_logo") ? ($(".q_logo a").height(logo_height), $(".q_logo img").height("auto")) : $(".q_logo img").height("100%"), setLeftPostionedMenuPadding()), $("header.page_header").hasClass("fixed_hiding") && (e < scroll_amount_for_fixed_hiding ? $("header.page_header").removeClass("scrolled") : $("header.page_header").addClass("scrolled"), $(".q_logo a").height(logo_height / 2), $(".q_logo img").height("100%")), $("header.page_header").hasClass("stick") || $("header.page_header").hasClass("stick_with_left_right_menu")) {17 if ($("header.page_header").hasClass("scroll_top") && $("header.page_header").hasClass("has_top") && ($("header.page_header").hasClass("fixed") || $("header.page_header").hasClass("fixed_hiding")) && (e >= 0 && e <= 34 ? ($("header.page_header").css("top", -e),18 $("header.page_header").css("margin-top", 0),19 $(".header_top").show()) : e > 34 && ($("header.page_header").css("top", "-34px"),20 $("header.page_header").css("margin-top", 34),21 $(".header_top").hide())),22 sticky_amount = getScrollAmountForStickyHeader(),23 $("header").hasClass("regular") && (header_height - logo_height >= 10 ? $(".q_logo a").height(logo_height) : $(".q_logo a").height(header_height - 10),24 $(".q_logo a img").css("height", "100%")),25 $("header.page_header").hasClass("fixed") && ($top_header_height = $("header.page_header").hasClass("scroll_top") ? 34 : 0,26 header_height - e + $top_header_height >= min_header_height_scroll && e >= $top_header_height ? ($("header.page_header").removeClass("scrolled"),27 $("header:not(.centered_logo.centered_logo_animate) nav.main_menu > ul > li > a").css("line-height", header_height - e + $top_header_height + "px"),28 $("header:not(.centered_logo.centered_logo_animate) .side_menu_button").css("height", header_height - e + $top_header_height + "px"),29 $("header:not(.centered_logo.centered_logo_animate) .shopping_cart_inner").css("height", header_height - e + $top_header_height + "px"),30 $("header:not(.centered_logo.centered_logo_animate) .header_bottom .qode-login-register-widget.qode-user-logged-in .qode-logged-in-user").css("height", header_height - e + $top_header_height + "px"),31 $("header:not(.centered_logo.centered_logo_animate) .logo_wrapper").css("height", header_height - e + $top_header_height + "px"), header_height - logo_height > 0 ? $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", logo_height + "px") : $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", header_height - e + $top_header_height - 10 + "px")) : e < $top_header_height ? ($("header.page_header").removeClass("scrolled"),32 $("header:not(.centered_logo.centered_logo_animate) nav.main_menu > ul > li > a").css("line-height", header_height + "px"),33 $("header:not(.centered_logo.centered_logo_animate) .side_menu_button").css("height", header_height + "px"),34 $("header:not(.centered_logo.centered_logo_animate) .shopping_cart_inner").css("height", header_height + "px"),35 $("header:not(.centered_logo.centered_logo_animate) .header_bottom .qode-login-register-widget.qode-user-logged-in .qode-logged-in-user").css("height", header_height + "px"),36 $("header:not(.centered_logo.centered_logo_animate) .logo_wrapper").css("height", header_height + "px"),37 header_height - logo_height > 0 ? $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", logo_height + "px") : $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", header_height - 10 + "px")) : header_height - e + $top_header_height < min_header_height_scroll && ($("header.page_header").addClass("scrolled"),38 $("header:not(.centered_logo.centered_logo_animate) nav.main_menu > ul > li > a").css("line-height", min_header_height_scroll + "px"),39 $("header:not(.centered_logo.centered_logo_animate) .side_menu_button").css("height", min_header_height_scroll + "px"),40 $("header:not(.centered_logo.centered_logo_animate) .shopping_cart_inner").css("height", min_header_height_scroll + "px"),41 $("header:not(.centered_logo.centered_logo_animate) .header_bottom .qode-login-register-widget.qode-user-logged-in .qode-logged-in-user").css("height", min_header_height_scroll + "px"),42 $("header:not(.centered_logo.centered_logo_animate) .logo_wrapper").css("height", min_header_height_scroll + "px"), min_header_height_scroll - logo_height > 0 ? $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", logo_height + "px") : $("header:not(.centered_logo.centered_logo_animate) .q_logo a").css("height", min_header_height_scroll - 10 + "px")),43 $("header.page_header").hasClass("centered_logo") && $("header.page_header").hasClass("centered_logo_animate") ? header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height >= min_header_height_scroll && logo_height > min_header_height_scroll - 10 && e >= $top_header_height ? $(".q_logo a").height(header_height - e + $top_header_height - 10) : header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height >= min_header_height_scroll && logo_height > min_header_height_scroll - 10 && e < $top_header_height ? $(".q_logo a").height(header_height - 10) : header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height < min_header_height_scroll && logo_height > min_header_height_scroll - 10 ? $(".q_logo a").height(min_header_height_scroll - 10) : header_height - e + $top_header_height < logo_height && header_height - e + $top_header_height < min_header_height_scroll && logo_height < min_header_height_scroll - 10 ? $(".q_logo a").height(logo_height) : (e + $top_header_height === 0 && header_height,44 $(".q_logo a").height(logo_height)) : $("header.page_header").hasClass("centered_logo") ? ($(".q_logo a").height(logo_height),45 $(".q_logo img").height("auto")) : $(".q_logo img").height("100%"),46 setLeftPostionedMenuPadding()),47 $("header.page_header").hasClass("fixed_hiding") && (e < scroll_amount_for_fixed_hiding ? $("header.page_header").removeClass("scrolled") : $("header.page_header").addClass("scrolled"),48 $(".q_logo a").height(logo_height / 2),49 $(".q_logo img").height("100%")),50 $("header.page_header").hasClass("stick") || $("header.page_header").hasClass("stick_with_left_right_menu")) { 51 if (e > sticky_amount) {52 if (!$("header.page_header").hasClass("sticky")) {53 $top_header_height = $("header.page_header").hasClass("has_top") ? 34 : 0;54 var t = $("header.page_header").hasClass("centered_logo") ? $("header.page_header").height() : header_height + $top_header_height;55 $("header.page_header").hasClass("menu_bottom") && (t = header_height + 60), $("header.page_header").addClass("sticky"), $(".content").css("padding-top", t), window.clearTimeout(sticky_animate), sticky_animate = window.setTimeout(function() {56 $("header.page_header").addClass("sticky_animate")57 }, 100), min_header_height_sticky - logo_height >= 10 ? $(".q_logo a").height(logo_height) : $(".q_logo a").height(min_header_height_sticky - 10), $("header.page_header").hasClass("menu_bottom") && initDropDownMenu()58 }59 min_header_height_sticky - logo_height >= 10 ? $(".q_logo a").height(logo_height) : $(".q_logo a").height(min_header_height_sticky - 10)60 } else $("header.page_header").hasClass("sticky") && ($("header").removeClass("sticky_animate"), $("header").removeClass("sticky"), $(".content").css("padding-top", "0px"), $("header.page_header").hasClass("menu_bottom") && initDropDownMenu()), setMargingsForLeftAndRightMenu(), $("header.page_header").hasClass("centered_logo") ? ($(".q_logo a").height(logo_height), $(".q_logo img").height("auto")) : header_height - logo_height >= 10 ? $(".q_logo a").height(logo_height) : $(".q_logo a").height(header_height - 10), $(".q_logo a img").css("height", "100%");61 setLeftPostionedMenuPadding()62 }63 }64 65 function qodeMobileHeaderBehavior() {66 if ($("header").hasClass("sticky_mobile")) {67 var e = $(".page_header"),68 t = (e.find(".mobile_menu_button"), e.outerHeight()),69 o = $("#wpadminbar").length ? $("#wpadminbar").height() : 0,70 n = t,71 i = $scroll,72 a = function() {73 if (e.find(".header_inner").css("padding-top", 0), $window_width < 1e3) {74 var a = $scroll;75 a > n ? (e.addClass("qode-animate-mobile-header"), $(".content").css("padding-top", t)) : (e.removeClass("qode-animate-mobile-header"), $(".content").css("padding-top", 0)), a > i && a >= n || a <= n ? (e.removeClass("mobile-header-appear"), e.find(".header_inner").css("padding-top", 0)) : (e.addClass("mobile-header-appear"), e.find(".header_inner").css("padding-top", o)), i = $scroll76 }77 };78 qode_window.on("scroll resize", function() {79 a()80 })81 }82 }83 84 function setMargingsForLeftAndRightMenu() {85 "use strict";86 if ($("header.page_header").hasClass("stick_with_left_right_menu") && !$("header.page_header").hasClass("left_right_margin_set")) {87 var e = $(".q_logo a img").width() / 2;88 0 == $scroll && 0 != e && $("header.page_header").addClass("left_right_margin_set"), $(".logo_wrapper").width(2 * e), $("nav.main_menu.left_side > ul > li:last-child").css("margin-right", e), $("nav.main_menu.right_side > ul > li:first-child").css("margin-left", e), $(".rtl nav.main_menu.left_side > ul > li:first-child").css("margin-right", e), $(".rtl nav.main_menu.left_side > ul > li:last-child").css("margin-right", 0), $(".rtl nav.main_menu.right_side > ul > li:last-child").css("margin-left", e), $(".rtl nav.main_menu.right_side > ul > li:first-child").css("margin-left", 0)89 }90 }91 92 function setLeftPostionedMenuPadding() {93 "use strict";94 var e = $("header:not(.centered_logo) nav.main_menu");95 if (e.length && e.hasClass("left")) {96 var t = $(".q_logo a img").filter(function() {97 return "1" == $(this).css("opacity")98 });99 e.css("left", t.width())100 }101 }102 103 function logoSizeOnSmallScreens() {104 "use strict";105 80 < logo_height ? $(".q_logo a").height(80) : $(".q_logo a").height(logo_height), $(".q_logo a img").css("height", "100%"), $("header.page_header").removeClass("sticky_animate sticky"), $(".content").css("padding-top", "0px")106 }107 108 function contentMinHeight() {109 "use strict";110 if ($("header .header_bottom").length || $("header .bottom_header").length) {111 if ($("header .header_bottom").length) var e = $("header .header_bottom").css("background-color");112 if ($("header .bottom_header").length) var e = $("header .bottom_header").css("background-color");113 var t = e.substring(e.indexOf("(") + 1, e.lastIndexOf(")")).split(/,\s*/)[3],114 o = void 0 != t || $("header.page_header").hasClass("transparent") ? 0 : $("header.page_header").height();115 $("body .content").css("min-height", $window_height - o - $("footer:not(.uncover)").height())116 }117 }118 function contentMinHeightWithPaspartu() {119 "use strict";120 if ($(".paspartu_enabled").length) {121 var e, t = 0,122 o = $window_width * paspartu_width,123 n = $("footer").height();124 if ($(".disable_footer").length && (n = 0), $(".vertical_menu_enabled").length ? $(".paspartu_top").length && $(".paspartu_middle_inner").length && (t += o) : $(".paspartu_top").length && (t += o), !$(".paspartu_bottom").length && $(".disable_bottom_paspartu").length || (t += o), $(".vertical_menu_enabled").length) e = $window_height - t - n;125 else {126 if ($("header .header_bottom").length) var i = $("header .header_bottom").css("background-color");127 if ($("header .bottom_header").length) var i = $("header .bottom_header").css("background-color");128 if (void 0 !== i) var a = i.substring(i.indexOf("(") + 1, i.lastIndexOf(")")).split(/,\s*/)[3];129 var r = void 0 != a || $("header.page_header").hasClass("transparent") ? 0 : $("header.page_header").height();130 e = $window_height - r - t - n131 }132 $(".content").length && $(".content").css("min-height", e)133 }134 }135 function checkTitleToShowOrHide() {136 if ($(".title_outer.animate_title_area").length) {137 var e = $(".title_outer").data("height");138 $scroll > $(".title").height() && $(".title_outer").css({139 height: e,140 opacity: "1",141 overflow: "visible"142 })143 }144 }145 function contentMenuPosition() {146 "use strict";147 if ($("nav.content_menu").length) {148 if (content_menu_position > sticky_amount) var e = min_header_height_sticky;149 else var e = 0;150 content_menu_position - e - content_menu_top_add - $scroll <= 0 && ($("header").hasClass("stick") || $("header").hasClass("stick_with_left_right_menu")) ? (content_menu_position < sticky_amount ? $scroll > sticky_amount ? $("nav.content_menu").css({151 position: "fixed",152 top: min_header_height_sticky + content_menu_top_add153 }).addClass("fixed") : $("nav.content_menu").css({154 position: "fixed",155 top: 0,156 transition: "none"157 }).addClass("fixed") : $("nav.content_menu").css({158 position: "fixed",159 top: min_header_height_sticky + content_menu_top_add160 }).addClass("fixed"), $("header.sticky").addClass("no_shadow"), $(".content > .content_inner > .container > .container_inner").css("margin-top", content_line_height), $(".content > .content_inner > .full_width").css("margin-top", content_line_height)) : content_menu_position - content_menu_top - content_menu_top_add - $scroll <= 0 && !$("header").hasClass("stick") ? ($("nav.content_menu").css({161 position: "fixed",162 top: content_menu_top + content_menu_top_add163 }).addClass("fixed"), $(".content > .content_inner > .container > .container_inner").css("margin-top", content_line_height), $(".content > .content_inner > .full_width").css("margin-top", content_line_height)) : ($("nav.content_menu").css({164 position: "relative",165 top: "0px"166 }).removeClass("fixed"), $("header.sticky").removeClass("no_shadow"), $(".content > .content_inner > .container > .container_inner").css("margin-top", "0px"), $(".content > .content_inner > .full_width").css("margin-top", "0px")), $(".content .in_content_menu").waypoint(function(e) {167 var t = $(this),168 o = t.data("q_id");169 $("nav.content_menu.fixed li a").each(function() {170 $(this).attr("href") === o ? $(this).parent().addClass("active") : $(this).parent().removeClass("active")171 })172 }, {173 offset: "150"174 })175 }176 }177 function initMobileMenu() {178 "use strict";179 $(".mobile_menu_button > span").on("tap click", function(e) {180 e.preventDefault(), $(".mobile_menu > ul").is(":visible") ? $(".mobile_menu > ul").slideUp(200) : $(".mobile_menu > ul").slideDown(200)181 }), initInsideMobileMenu()182 }183 184 function initInsideMobileMenu() {185 "use strict";186 $(".mobile_menu > ul > li.has_sub > span.mobile_arrow, .mobile_menu > ul > li.has_sub > h3, .mobile_menu > ul > li.has_sub > a[href*='#']").on("tap click", function(e) {187 e.preventDefault(), $(this).closest("li.has_sub").find("> ul.sub_menu").is(":visible") ? ($(this).closest("li.has_sub").find("> ul.sub_menu").slideUp(200), $(this).closest("li.has_sub").removeClass("open_sub")) : ($(this).closest("li.has_sub").addClass("open_sub"), $(this).closest("li.has_sub").find("> ul.sub_menu").slideDown(200))188 }), $(".mobile_menu > ul > li.has_sub > ul.sub_menu > li.has_sub > span.mobile_arrow, .mobile_menu > ul > li.has_sub > ul.sub_menu > li.has_sub > h3, .mobile_menu > ul > li.has_sub > ul.sub_menu > li.has_sub > a[href*='#']").on("tap click", function(e) {189 e.preventDefault(), $(this).parent().find("ul.sub_menu").is(":visible") ? ($(this).parent().find("ul.sub_menu").slideUp(200), $(this).parent().removeClass("open_sub")) : ($(this).parent().addClass("open_sub"), $(this).parent().find("ul.sub_menu").slideDown(200))190 }), $(".mobile_menu ul li > a, .q_logo a").on("click", function() {191 "http://#" !== $(this).attr("href") && "#" !== $(this).attr("href") && $(".mobile_menu > ul").slideUp()192 })193 }194 //var $ = jQuery.noConflict();195window.qode = {}, qode.modules = {};196var common = {};197qode.modules.common = common;198var $scroll = 0,199 qode_body = $("body"),200 qode_document = $("document"),201 qode_window = $(window),202 $window_width = $(window).width();203qode.windowWidth = $window_width;204var $window_height = $(window).height();205qode.windowHeight = $window_height;206var logo_height, menu_dropdown_height_set = !1,207 sticky_amount = 0,208 qode_grid_width = 1100,209 content_menu_position, content_menu_top, content_menu_top_add = 0,210 src, next_image, prev_image, $top_header_height, min_w = 1500,211 video_width_original = 1280,212 video_height_original = 720,213 vid_ratio = 1280 / 720,214 skrollr_slider, paspartu_width;215if (void 0 === paspartu_width_init) var paspartu_width_init = .02;216var min_header_height_fixed_hidden = 50;217var scroll_amount_for_sticky = 85;218var scroll_amount_for_fixed_hiding = 200;219var qodeGlobalVars = {"vars":{"page_scroll_amount_for_sticky":""}};220//common.getLoadMoreData = getLoadMoreData, common.setLoadMoreAjaxData = setLoadMoreAjaxData, common.qodeOwlSlider = qodeOwlSlider, qode.animationEnd = animationEventEnd(), qode.transitionEnd = transitionEventEnd(), 221$(document).ready(function() {222 "use strict";223 if ($("header").hasClass("regular") && (content_menu_top = 0), $("header").hasClass("fixed_top_header") && (content_menu_top = header_height), $("header").hasClass("fixed") && (content_menu_top = min_header_height_scroll), $("header").hasClass("fixed_hiding") && (content_menu_top = min_header_height_fixed_hidden + 40), ($("header").hasClass("stick") || $("header").hasClass("stick_with_left_right_menu")) && (content_menu_top = 0), !$("header.page_header").hasClass("scroll_top") && $("header.page_header").hasClass("has_top") && $("header.page_header").hasClass("fixed") && (content_menu_top_add = 34), $("body").hasClass("vertical_menu_enabled")) {224 content_menu_top = 0, content_menu_top_add = 0225 }226 paspartu_width = $window_width < 1024 ? .02 : paspartu_width_init, contentMinHeight(), contentMinHeightWithPaspartu(),227 initMobileMenu()228 //qodeGridWidth(), setDropDownMenuPosition(), initDropDownMenu(), initVerticalMenu(), initVerticalMobileMenu(), initQodeSlider(), initSideMenu(), initPopupMenu(), initMessageHeight(), initToCounter(), initCounter(), $(".vertical_split_slider").length || initCountdown(), initProgressBars(), initListAnimation(), initPieChart(), initPieChartWithIcon(), initServiceAnimation(), initParallaxTitle(), initSideAreaScroll(), initVerticalAreaMenuScroll(), loadMore(), prettyPhoto(), initFlexSlider(), fitVideo(), fitAudio(), initAccordion(), initAccordionContentLink(), qodeInitAccordions(), initMessages(), initProgressBarsIcon(), initMoreFacts(), placeholderReplace(), backButtonShowHide(), backToTop(), initSteps(), showGoogleMap(), initProgressBarsVertical(), initElementsAnimation(), updateShoppingCart(), initHashClick(), initIconWithTextAnimation(), initVideoBackground(), initCheckSafariBrowser(), initSearchButton(), initCoverBoxes(), createContentMenu(), contentMenuScrollTo(), createSelectContentMenu(), initButtonHover(), initEnlargeButton(), initSocialIconHover(), initPageTitleAnimation(), initIconShortcodeHover(), qodeIcon().init(), initIconWithTextHover(), parallaxLayers(), initHorizontalMarquee(), qodeHorizontalMarqueeLoop(), initTextMarquee(), initExpandingImages(), qodeLazyImages(), initItemShowcase(), qodeCTASection().init(), qodeInitInteractiveIconShowcase(), qodeInitSendContactForm(), qodeWorkflow(), qodeCustomFontTypeOut(), qodeMobileHeaderBehavior(), initElementsHolderResponsiveStyle(), 229 $(".widget #searchform").mousedown(function() {230 $(this).addClass("form_focus")231 }).focusout(function() {232 $(this).removeClass("form_focus")233 }), $scroll = $(window).scrollTop(), checkTitleToShowOrHide()234 //, checkVerticalMenuTransparency(), 235 $(window).width() > 1e3 ? headerSize($scroll) : logoSizeOnSmallScreens()236 , $(window).width() > 768 && contentMenuPosition()237 //, contentMenuCheckLastSection(), $("header:not(.stick_with_left_right_menu) .q_logo a").css("visibility", "visible"), initFullScreenTemplate(), showHideVerticalMenu(), initMasonryGallery(), initLoadNextPostOnBottom(), initBlogMasonryGallery(), initBlogGallery(), qodeV2Button().init(), qodeCardsSlider().init(), qodeCardsGallery(), qodeInitEllipticalSlider(), qodeInitPricingCalculator(), qodeSlidingImageHolder(), qodeOwlSlider(), qodeScrollingImage()238}), $(window).on("load", function() {239 "use strict";240 // qodeBrowserDetection(), $(".touchevents .main_menu li:has(div.second)").doubleTapToGo(), setLeftPostionedMenuPadding(), initSmallImageBlogHeight(), setDropDownMenuPosition(), initDropDownMenu(), initPortfolio(), initPortfolioZIndex(), initPortfolioSingleInfo(), initTestimonials(), initTestimonialsCarousel(), initVideoBackgroundSize(), initBlog(), initBlogMasonryFullWidth(), initQBlog(), initPortfolioJustifiedGallery(), initPortfolioMasonry(), initPortfolioMasonryFilter(), initTabs(), qodeInitAdvancedTabs(), qodeInitAdvancedTabsIcons(), countClientsPerRow(), animatedTextIconHeight(), countAnimatedTextIconPerRow(), initTitleAreaAnimation(), setContentBottomMargin(), footerWidth(), $("nav.content_menu").length > 0 && (content_menu_position = $("nav.content_menu").offset().top, contentMenuPosition()), contentMenuCheckLastSection(), initQodeCarousel(), initPortfolioSlider(), initBlogSlider(), qodeInitBlogCarouselTitled(), initPreviewSlider(), initInDeviceSlider(), initTabsActiveBorder(), setActiveTabBorder(), initImageHover(), $("header.stick_with_left_right_menu .q_logo a").css("visibility", "visible"), setMargingsForLeftAndRightMenu(), initImageGallerySliderNoSpace(), initVerticalSplitSlider(), initParallax(), initQodeElementAnimationSkrollr(), qodeBlogCompundMasonryGallery().init(), qodeInitStickyWidget(), qodeBlogHeadlines(), qodeCardsSlider().load(), initContentSlider(), qodePageTransitionEffect(), qodeContactPageAcceptance(), setTimeout(function() {241 // checkAnchorOnScroll(), qodeBlogGalleryAnimation(), checkAnchorOnLoad(), checkHeaderStyleOnScroll(), $(".no-touchevents .carousel").length && skrollr_slider.refresh()242 // }, 700), qodePanelArea(), initDropDownAfterWPMLReplaceMenu()243}), $(window).scroll(function() {244 "use strict";245 $scroll = $(window).scrollTop(), $(window).width() > 1e3 && headerSize($scroll)246 , $(window).width() > 768 && contentMenuPosition()247 //, contentMenuCheckLastSection(), checkVerticalMenuTransparency(), qodeLazyImages(), $(".touchevents .drop_down > ul > li").mouseleave(), $(".touchevents .drop_down > ul > li").blur()248}), $(window).resize(function() {249 "use strict";250 $(window).width() > 1e3 ? headerSize($scroll) : logoSizeOnSmallScreens()251 //$window_width = $(window).width(), $window_height = $(window).height(), paspartu_width = $window_width < 1024 ? .02 : paspartu_width_init, $(window).width() > 1e3 ? headerSize($scroll) : logoSizeOnSmallScreens(), initMessageHeight(), qodeNumberOfTestimonialsItemsResize(), fitAudio(), initSmallImageBlogHeight(), initBlog(), initBlogMasonryFullWidth(), initQBlog(), animatedTextIconHeight(), countAnimatedTextIconPerRow(), initVideoBackgroundSize(), countClientsPerRow(), setContentBottomMargin(), footerWidth(), calculateHeights(), $(".vertical_split_slider").height($window_height), initMasonryGallery(), initPortfolioMasonry(), contentMinHeight(), contentMinHeightWithPaspartu(), qodeInitStickyWidget()252});253 // end header254 /* function bridgeQodeAjaxSubmitCommentForm() {255 "use strict";256 var options = {257 success: function() {258 $("#commentform textarea").val("");259 $("#commentform .success p").text("Comment has been sent!");260 }261 };262 $('#commentform').submit(function() {263 $(this).find('input[type="submit"]').next('.success').remove();264 $(this).find('input[type="submit"]').after('<div class="success"><p></p></div>');265 $(this).ajaxSubmit(options);266 return false;267 });268 }269 var header_height = 100;270 var min_header_height_scroll = 57;271 var min_header_height_fixed_hidden = 50;272 var min_header_height_sticky = 60;273 var scroll_amount_for_sticky = 85;274 var content_line_height = 60;275 var header_bottom_border_weight = 1;276 var scroll_amount_for_fixed_hiding = 200;277 var paspartu_width_init = 0.02;278 var add_for_admin_bar = jQuery('body').hasClass('admin-bar') ? 32 : 0;279 min_header_height_fixed_hidden = 50;280 paspartu_width_init = 0.02;281 var logo_height = 130;282 var logo_width = 280;283 logo_height = 138;284 logo_width = 478;285 header_top_height = 0;286 var loading_text;287 loading_text = 'Loading new posts...';288 var finished_text;289 finished_text = 'No more posts';290 var piechartcolor;291 piechartcolor = "#1abc9c";292 piechartcolor = "#000000";293 var geocoder;294 var map;295 296 function initialize() {297 "use strict";298 var mapStyles = [{299 stylers: [{300 hue: "#324156"301 }, {302 saturation: "-60"303 }, {304 lightness: "-20"305 }, {306 gamma: 1.51307 }]308 }];309 var qodeMapType = new google.maps.StyledMapType(mapStyles, {310 name: "Qode Map"311 });312 geocoder = new google.maps.Geocoder();313 var latlng = new google.maps.LatLng(-34.397, 150.644);314 var myOptions = {315 zoom: 12,316 scrollwheel: false,317 center: latlng,318 zoomControl: true,319 zoomControlOptions: {320 style: google.maps.ZoomControlStyle.SMALL,321 position: google.maps.ControlPosition.RIGHT_CENTER322 },323 scaleControl: false,324 scaleControlOptions: {325 position: google.maps.ControlPosition.LEFT_CENTER326 },327 streetViewControl: false,328 streetViewControlOptions: {329 position: google.maps.ControlPosition.LEFT_CENTER330 },331 panControl: false,332 panControlOptions: {333 position: google.maps.ControlPosition.LEFT_CENTER334 },335 mapTypeControl: false,336 mapTypeControlOptions: {337 mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'qode_style'],338 style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,339 position: google.maps.ControlPosition.LEFT_CENTER340 },341 mapTypeId: 'qode_style'342 };343 map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);344 map.mapTypes.set('qode_style', qodeMapType);345 }346 347 function codeAddress(data) {348 "use strict";349 if (data === '')350 return;351 var contentString = '<div id="content">' +352 '<div id="siteNotice">' +353 '</div>' +354 '<div id="bodyContent">' +355 '<p>' + data + '</p>' +356 '</div>' +357 '</div>';358 var infowindow = new google.maps.InfoWindow({359 content: contentString360 });361 geocoder.geocode({362 'address': data363 }, function(results, status) {364 if (status === google.maps.GeocoderStatus.OK) {365 map.setCenter(results[0].geometry.location);366 var marker = new google.maps.Marker({367 map: map,368 position: results[0].geometry.location,369 icon: 'https://bridge358.qodeinteractive.com/wp-content/themes/bridge/img/pin.png',370 title: data['store_title']371 });372 google.maps.event.addListener(marker, 'click', function() {373 infowindow.open(map, marker);374 });375 }376 });377 }378 var $ = jQuery.noConflict();379 $(document).ready(function() {380 "use strict";381 showContactMap();382 });383 384 function showContactMap() {385 "use strict";386 if ($("#map_canvas").length > 0) {387 initialize();388 codeAddress("");389 codeAddress("");390 codeAddress("");391 codeAddress("");392 codeAddress("");393 }394 }395 var no_ajax_pages = [];396 var qode_root = 'https://bridge358.qodeinteractive.com/';397 var theme_root = 'https://bridge358.qodeinteractive.com/wp-content/themes/bridge/';398 var header_style_admin = "";399 if (typeof no_ajax_obj !== 'undefined') {400 no_ajax_pages = no_ajax_obj.no_ajax_pages;...

Full Screen

Full Screen

base.py

Source:base.py Github

copy

Full Screen

...144 f" but expected {encode_hex(parent.hash)}"145 )146 vm = self.get_vm(child)147 try:148 vm.validate_header(child, parent)149 except ValidationError as exc:150 raise ValidationError(151 f"{child} is not a valid child of {parent}: {exc}"152 ) from exc153 if index in indices_to_check_seal:154 vm.validate_seal(child)155 def validate_chain_extension(self, headers: Tuple[BlockHeaderAPI, ...]) -> None:156 for index, header in enumerate(headers):157 vm = self.get_vm(header)158 # pass in any parents that are not already in the database159 parents = headers[:index]160 vm.validate_seal_extension(header, parents)161class Chain(BaseChain):162 logger = logging.getLogger("eth.chain.chain.Chain")163 gas_estimator: StaticMethod[Callable[[StateAPI, SignedTransactionAPI], int]] = None164 chaindb_class: Type[ChainDatabaseAPI] = ChainDB165 consensus_context_class: Type[ConsensusContextAPI] = ConsensusContext166 def __init__(self, base_db: AtomicDatabaseAPI) -> None:167 if not self.vm_configuration:168 raise ValueError(169 "The Chain class cannot be instantiated with an empty `vm_configuration`"170 )171 else:172 validate_vm_configuration(self.vm_configuration)173 self.chaindb = self.get_chaindb_class()(base_db)174 self.consensus_context = self.consensus_context_class(self.chaindb.db)175 self.headerdb = HeaderDB(base_db)176 if self.gas_estimator is None:177 self.gas_estimator = get_gas_estimator()178 #179 # Helpers180 #181 @classmethod182 def get_chaindb_class(cls) -> Type[ChainDatabaseAPI]:183 if cls.chaindb_class is None:184 raise AttributeError("`chaindb_class` not set")185 return cls.chaindb_class186 #187 # Chain API188 #189 @classmethod190 def from_genesis(cls,191 base_db: AtomicDatabaseAPI,192 genesis_params: Dict[str, HeaderParams],193 genesis_state: AccountState = None) -> 'BaseChain':194 genesis_vm_class = cls.get_vm_class_for_block_number(BlockNumber(0))195 pre_genesis_header = BlockHeader(difficulty=0, block_number=-1, gas_limit=0)196 chain_context = ChainContext(cls.chain_id)197 state = genesis_vm_class.build_state(base_db, pre_genesis_header, chain_context)198 if genesis_state is None:199 genesis_state = {}200 # mutation201 apply_state_dict(state, genesis_state)202 state.persist()203 if 'state_root' not in genesis_params:204 # If the genesis state_root was not specified, use the value205 # computed from the initialized state database.206 genesis_params = assoc(genesis_params, 'state_root', state.state_root)207 elif genesis_params['state_root'] != state.state_root:208 # If the genesis state_root was specified, validate that it matches209 # the computed state from the initialized state database.210 raise ValidationError(211 "The provided genesis state root does not match the computed "212 f"genesis state root. Got {state.state_root!r}. "213 f"Expected {genesis_params['state_root']!r}"214 )215 genesis_header = genesis_vm_class.create_genesis_header(**genesis_params)216 return cls.from_genesis_header(base_db, genesis_header)217 @classmethod218 def from_genesis_header(cls,219 base_db: AtomicDatabaseAPI,220 genesis_header: BlockHeaderAPI) -> 'BaseChain':221 chaindb = cls.get_chaindb_class()(base_db)222 chaindb.persist_header(genesis_header)223 return cls(base_db)224 #225 # VM API226 #227 def get_vm(self, at_header: BlockHeaderAPI = None) -> VirtualMachineAPI:228 header = self.ensure_header(at_header)229 vm_class = self.get_vm_class_for_block_number(header.block_number)230 chain_context = ChainContext(self.chain_id)231 return vm_class(232 header=header,233 chaindb=self.chaindb,234 chain_context=chain_context,235 consensus_context=self.consensus_context236 )237 #238 # Header API239 #240 def create_header_from_parent(self,241 parent_header: BlockHeaderAPI,242 **header_params: HeaderParams) -> BlockHeaderAPI:243 return self.get_vm_class_for_block_number(244 block_number=BlockNumber(parent_header.block_number + 1),245 ).create_header_from_parent(parent_header, **header_params)246 def get_block_header_by_hash(self, block_hash: Hash32) -> BlockHeaderAPI:247 validate_word(block_hash, title="Block Hash")248 return self.chaindb.get_block_header_by_hash(block_hash)249 def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeaderAPI:250 return self.chaindb.get_canonical_block_header_by_number(block_number)251 def get_canonical_head(self) -> BlockHeaderAPI:252 return self.chaindb.get_canonical_head()253 def get_score(self, block_hash: Hash32) -> int:254 return self.headerdb.get_score(block_hash)255 def ensure_header(self, header: BlockHeaderAPI = None) -> BlockHeaderAPI:256 """257 Return ``header`` if it is not ``None``, otherwise return the header258 of the canonical head.259 """260 if header is None:261 head = self.get_canonical_head()262 return self.create_header_from_parent(head)263 else:264 return header265 #266 # Block API267 #268 def get_ancestors(self, limit: int, header: BlockHeaderAPI) -> Tuple[BlockAPI, ...]:269 ancestor_count = min(header.block_number, limit)270 # We construct a temporary block object271 vm_class = self.get_vm_class_for_block_number(header.block_number)272 block_class = vm_class.get_block_class()273 block = block_class(header=header, uncles=[], transactions=[])274 ancestor_generator = iterate(compose(275 self.get_block_by_hash,276 operator.attrgetter('parent_hash'),277 operator.attrgetter('header'),278 ), block)279 # we peel off the first element from the iterator which will be the280 # temporary block object we constructed.281 next(ancestor_generator)282 return tuple(take(ancestor_count, ancestor_generator))283 def get_block(self) -> BlockAPI:284 return self.get_vm().get_block()285 def get_block_by_hash(self, block_hash: Hash32) -> BlockAPI:286 validate_word(block_hash, title="Block Hash")287 block_header = self.get_block_header_by_hash(block_hash)288 return self.get_block_by_header(block_header)289 def get_block_by_header(self, block_header: BlockHeaderAPI) -> BlockAPI:290 vm = self.get_vm(block_header)291 return vm.get_block()292 def get_canonical_block_by_number(self, block_number: BlockNumber) -> BlockAPI:293 validate_uint256(block_number, title="Block Number")294 return self.get_block_by_hash(self.chaindb.get_canonical_block_hash(block_number))295 def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32:296 return self.chaindb.get_canonical_block_hash(block_number)297 def build_block_with_transactions(298 self,299 transactions: Sequence[SignedTransactionAPI],300 parent_header: BlockHeaderAPI = None301 ) -> Tuple[BlockAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]:302 base_header = self.ensure_header(parent_header)303 vm = self.get_vm(base_header)304 new_header, receipts, computations = vm.apply_all_transactions(transactions, base_header)305 new_block = vm.set_block_transactions(vm.get_block(), new_header, transactions, receipts)306 return new_block, receipts, computations307 #308 # Transaction API309 #310 def get_canonical_transaction_index(self, transaction_hash: Hash32) -> Tuple[BlockNumber, int]:311 return self.chaindb.get_transaction_index(transaction_hash)312 def get_canonical_transaction(self, transaction_hash: Hash32) -> SignedTransactionAPI:313 (block_num, index) = self.chaindb.get_transaction_index(transaction_hash)314 transaction = self.get_canonical_transaction_by_index(block_num, index)315 if transaction.hash == transaction_hash:316 return transaction317 else:318 raise TransactionNotFound(319 f"Found transaction {encode_hex(transaction.hash)} "320 f"instead of {encode_hex(transaction_hash)} in block {block_num} at {index}"321 )322 def get_canonical_transaction_by_index(self,323 block_number: BlockNumber,324 index: int) -> SignedTransactionAPI:325 VM_class = self.get_vm_class_for_block_number(block_number)326 return self.chaindb.get_transaction_by_index(327 block_number,328 index,329 VM_class.get_transaction_builder(),330 )331 def create_transaction(self, *args: Any, **kwargs: Any) -> SignedTransactionAPI:332 return self.get_vm().create_transaction(*args, **kwargs)333 def create_unsigned_transaction(self,334 *,335 nonce: int,336 gas_price: int,337 gas: int,338 to: Address,339 value: int,340 data: bytes) -> UnsignedTransactionAPI:341 return self.get_vm().create_unsigned_transaction(342 nonce=nonce,343 gas_price=gas_price,344 gas=gas,345 to=to,346 value=value,347 data=data,348 )349 def get_transaction_receipt(self, transaction_hash: Hash32) -> ReceiptAPI:350 transaction_block_number, transaction_index = self.chaindb.get_transaction_index(351 transaction_hash,352 )353 return self.get_transaction_receipt_by_index(transaction_block_number, transaction_index)354 def get_transaction_receipt_by_index(self,355 block_number: BlockNumber,356 index: int) -> ReceiptAPI:357 vm = self.get_vm_class_for_block_number(block_number)358 receipt = self.chaindb.get_receipt_by_index(359 block_number,360 index,361 vm.get_receipt_builder(),362 )363 return receipt364 #365 # Execution API366 #367 def get_transaction_result(368 self,369 transaction: SignedTransactionAPI,370 at_header: BlockHeaderAPI) -> bytes:371 with self.get_vm(at_header).in_costless_state() as state:372 computation = state.costless_execute_transaction(transaction)373 computation.raise_if_error()374 return computation.output375 def estimate_gas(376 self,377 transaction: SignedTransactionAPI,378 at_header: BlockHeaderAPI = None) -> int:379 if at_header is None:380 at_header = self.get_canonical_head()381 with self.get_vm(at_header).in_costless_state() as state:382 return self.gas_estimator(state, transaction)383 def import_block(self,384 block: BlockAPI,385 perform_validation: bool = True386 ) -> BlockImportResult:387 try:388 parent_header = self.get_block_header_by_hash(block.header.parent_hash)389 except HeaderNotFound:390 raise ValidationError(391 f"Attempt to import block #{block.number}. "392 f"Cannot import block {block.hash!r} before importing "393 f"its parent block at {block.header.parent_hash!r}"394 )395 base_header_for_import = self.create_header_from_parent(parent_header)396 # Make a copy of the empty header, adding in the expected amount of gas used. This397 # allows for richer logging in the VM.398 annotated_header = base_header_for_import.copy(gas_used=block.header.gas_used)399 block_result = self.get_vm(annotated_header).import_block(block)400 imported_block = block_result.block401 # Validate the imported block.402 if perform_validation:403 try:404 validate_imported_block_unchanged(imported_block, block)405 except ValidationError:406 self.logger.warning("Proposed %s doesn't follow EVM rules, rejecting...", block)407 raise408 persist_result = self.persist_block(imported_block, perform_validation)409 return BlockImportResult(*persist_result, block_result.meta_witness)410 def persist_block(411 self,412 block: BlockAPI,413 perform_validation: bool = True) -> BlockPersistResult:414 if perform_validation:415 self.validate_block(block)416 (417 new_canonical_hashes,418 old_canonical_hashes,419 ) = self.chaindb.persist_block(block)420 self.logger.debug(421 'Persisted block: number %s | hash %s',422 block.number,423 encode_hex(block.hash),424 )425 new_canonical_blocks = tuple(426 self.get_block_by_hash(header_hash)427 for header_hash428 in new_canonical_hashes429 )430 old_canonical_blocks = tuple(431 self.get_block_by_hash(header_hash)432 for header_hash433 in old_canonical_hashes434 )435 return BlockPersistResult(436 imported_block=block,437 new_canonical_blocks=new_canonical_blocks,438 old_canonical_blocks=old_canonical_blocks,439 )440 #441 # Validation API442 #443 def validate_receipt(self, receipt: ReceiptAPI, at_header: BlockHeaderAPI) -> None:444 VM_class = self.get_vm_class(at_header)445 VM_class.validate_receipt(receipt)446 def validate_block(self, block: BlockAPI) -> None:447 if block.is_genesis:448 raise ValidationError("Cannot validate genesis block this way")449 vm = self.get_vm(block.header)450 parent_header = self.get_block_header_by_hash(block.header.parent_hash)451 vm.validate_header(block.header, parent_header)452 vm.validate_seal(block.header)453 vm.validate_seal_extension(block.header, ())454 self.validate_uncles(block)455 def validate_seal(self, header: BlockHeaderAPI) -> None:456 vm = self.get_vm(header)457 vm.validate_seal(header)458 def validate_uncles(self, block: BlockAPI) -> None:459 has_uncles = len(block.uncles) > 0460 should_have_uncles = block.header.uncles_hash != EMPTY_UNCLE_HASH461 if not has_uncles and not should_have_uncles:462 # optimization to avoid loading ancestors from DB, since the block has no uncles463 return464 elif has_uncles and not should_have_uncles:465 raise ValidationError("Block has uncles but header suggests uncles should be empty")466 elif should_have_uncles and not has_uncles:467 raise ValidationError("Header suggests block should have uncles but block has none")468 # Check for duplicates469 uncle_groups = groupby(operator.attrgetter('hash'), block.uncles)470 duplicate_uncles = tuple(sorted(471 hash for hash, twins in uncle_groups.items() if len(twins) > 1472 ))473 if duplicate_uncles:474 raise ValidationError(475 "Block contains duplicate uncles:\n"476 f" - {' - '.join(duplicate_uncles)}"477 )478 recent_ancestors = tuple(479 ancestor480 for ancestor481 in self.get_ancestors(MAX_UNCLE_DEPTH + 1, header=block.header)482 )483 recent_ancestor_hashes = {ancestor.hash for ancestor in recent_ancestors}484 recent_uncle_hashes = _extract_uncle_hashes(recent_ancestors)485 for uncle in block.uncles:486 if uncle.hash == block.hash:487 raise ValidationError("Uncle has same hash as block")488 # ensure the uncle has not already been included.489 if uncle.hash in recent_uncle_hashes:490 raise ValidationError(491 f"Duplicate uncle: {encode_hex(uncle.hash)}"492 )493 # ensure that the uncle is not one of the canonical chain blocks.494 if uncle.hash in recent_ancestor_hashes:495 raise ValidationError(496 f"Uncle {encode_hex(uncle.hash)} cannot be an ancestor "497 f"of {encode_hex(block.hash)}"498 )499 # ensure that the uncle was built off of one of the canonical chain500 # blocks.501 if uncle.parent_hash not in recent_ancestor_hashes or (502 uncle.parent_hash == block.header.parent_hash):503 raise ValidationError(504 f"Uncle's parent {encode_hex(uncle.parent_hash)} "505 f"is not an ancestor of {encode_hex(block.hash)}"506 )507 # Now perform VM level validation of the uncle508 self.validate_seal(uncle)509 try:510 uncle_parent = self.get_block_header_by_hash(uncle.parent_hash)511 except HeaderNotFound:512 raise ValidationError(513 f"Uncle ancestor not found: {uncle.parent_hash!r}"514 )515 uncle_vm_class = self.get_vm_class_for_block_number(uncle.block_number)516 uncle_vm_class.validate_uncle(block, uncle, uncle_parent)517@to_set518def _extract_uncle_hashes(blocks: Iterable[BlockAPI]) -> Iterable[Hash32]:519 for block in blocks:520 for uncle in block.uncles:521 yield uncle.hash522class MiningChain(Chain, MiningChainAPI):523 header: BlockHeaderAPI = None524 def __init__(self, base_db: AtomicDatabaseAPI, header: BlockHeaderAPI = None) -> None:525 super().__init__(base_db)526 self.header = self.ensure_header(header)527 def apply_transaction(self,528 transaction: SignedTransactionAPI529 ) -> Tuple[BlockAPI, ReceiptAPI, ComputationAPI]:530 vm = self.get_vm(self.header)531 base_block = vm.get_block()532 receipt, computation = vm.apply_transaction(base_block.header, transaction)533 header_with_receipt = vm.add_receipt_to_header(base_block.header, receipt)534 # since we are building the block locally, we have to persist all the incremental state535 vm.state.persist()536 new_header: BlockHeaderAPI = header_with_receipt.copy(state_root=vm.state.state_root)537 transactions = base_block.transactions + (transaction, )538 receipts = base_block.get_receipts(self.chaindb) + (receipt, )539 new_block = vm.set_block_transactions(base_block, new_header, transactions, receipts)540 self.header = new_block.header541 return new_block, receipt, computation542 def import_block(self,543 block: BlockAPI,544 perform_validation: bool = True545 ) -> BlockImportResult:546 result = super().import_block(547 block, perform_validation)548 self.header = self.ensure_header()549 return result550 def set_header_timestamp(self, timestamp: int) -> None:551 self.header = self.header.copy(timestamp=timestamp)552 @staticmethod553 def _custom_header(base_header: BlockHeaderAPI, **kwargs: Any) -> BlockHeaderAPI:554 header_fields = {'coinbase'}555 header_params = {k: v for k, v in kwargs.items() if k in header_fields}556 return base_header.copy(**header_params)557 def mine_all(558 self,559 transactions: Sequence[SignedTransactionAPI],560 *args: Any,561 parent_header: BlockHeaderAPI = None,562 **kwargs: Any,563 ) -> Tuple[BlockImportResult, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]:564 if parent_header is None:565 base_header = self.header566 else:567 base_header = self.create_header_from_parent(parent_header)568 custom_header = self._custom_header(base_header, **kwargs)569 vm = self.get_vm(custom_header)570 new_header, receipts, computations = vm.apply_all_transactions(transactions, base_header)571 filled_block = vm.set_block_transactions(vm.get_block(), new_header, transactions, receipts)572 block_result = vm.mine_block(filled_block, *args, **kwargs)573 imported_block = block_result.block574 block_persist_result = self.persist_block(imported_block)575 block_import_result = BlockImportResult(*block_persist_result, block_result.meta_witness)576 self.header = self.create_header_from_parent(imported_block.header)577 return (block_import_result, receipts, computations)578 def mine_block(self, *args: Any, **kwargs: Any) -> BlockAPI:579 """580 Mine whatever transactions have been incrementally applied so far.581 """582 return self.mine_block_extended(*args, **kwargs).block583 def mine_block_extended(self, *args: Any, **kwargs: Any) -> BlockAndMetaWitness:584 custom_header = self._custom_header(self.header, **kwargs)585 vm = self.get_vm(custom_header)586 current_block = vm.get_block()587 mine_result = vm.mine_block(current_block, *args, **kwargs)588 mined_block = mine_result.block589 self.validate_block(mined_block)590 self.chaindb.persist_block(mined_block)591 self.header = self.create_header_from_parent(mined_block.header)592 return mine_result593 def get_vm(self, at_header: BlockHeaderAPI = None) -> VirtualMachineAPI:594 if at_header is None:595 at_header = self.header...

Full Screen

Full Screen

cqcLogMessageHandler.py

Source:cqcLogMessageHandler.py Github

copy

Full Screen

...69 def parse_data(cls, header, cmd, xtra, comment, node_name):70 subdata = {}71 subdata["node_name"] = node_name72 subdata["comment"] = comment73 subdata["cqc_header"] = cls.parse_header(header)74 subdata["cmd_header"] = cls.parse_cmd(cmd)75 if xtra:76 subdata["xtra_header"] = cls.parse_xtra(xtra)77 cls.logData.append(subdata)78 with open(cls.file, "w") as outfile:79 json.dump(cls.logData, outfile)80 @classmethod81 def parse_handle_data(cls, header, data, comment, node_name):82 cmd_l = CQC_CMD_HDR_LENGTH83 xtra_l = CQC_CMD_XTRA_LENGTH84 subdata = {}85 subdata["node_name"] = node_name86 subdata["comment"] = comment87 subdata["cqc_header"] = cls.parse_header(header)88 if len(data) >= cmd_l:89 subdata["cmd_header"] = cls.parse_cmd(CQCCmdHeader(data[:cmd_l]))90 if len(data) >= cmd_l + xtra_l:91 subdata["xtra_header"] = cls.parse_xtra(CQCXtraHeader(data[cmd_l: cmd_l + xtra_l]))92 cls.logData.append(subdata)93 with open(cls.file, "w") as outfile:94 json.dump(cls.logData, outfile)95 @classmethod96 def parse_handle_factory(cls, header, data, comment, node_name):97 subdata = {}98 subdata["node_name"] = node_name99 subdata["comment"] = comment100 subdata["cqc_header"] = cls.parse_header(header)101 fact_hdr = CQCFactoryHeader(data[: CQCFactoryHeader.HDR_LENGTH])102 subdata["factory_iterations"] = fact_hdr.num_iter103 subdata["notify"] = fact_hdr.notify104 cls.logData.append(subdata)105 with open(cls.file, "w") as outfile:106 json.dump(cls.logData, outfile)107 @classmethod108 def parse_header(cls, header):109 header_data = {}110 header_data["type"] = header.tp111 header_data["app_id"] = header.app_id112 header_data["header_length"] = header.length113 header_data["is_set"] = header.is_set114 return header_data115 @classmethod116 def parse_cmd(cls, cmd):117 cmd_data = {}118 cmd_data["notify"] = cmd.notify119 cmd_data["block"] = cmd.block120 cmd_data["action"] = cmd.action121 cmd_data["is_set"] = cmd.is_set122 cmd_data["qubit_id"] = cmd.qubit_id...

Full Screen

Full Screen

HeaderButtons.js

Source:HeaderButtons.js Github

copy

Full Screen

1/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions, react/prop-types */2import React from 'react';3import { storiesOf } from '@storybook/react-native';4import { View } from 'react-native';5import * as HeaderButton from '../../app/containers/HeaderButton';6import Header from '../../app/containers/Header';7import { ThemeContext } from '../../app/theme';8const stories = storiesOf('Header Buttons', module);9const HeaderExample = ({ left, right }) => (10 <Header11 headerLeft={left}12 headerTitle={() => <View style={{ flex: 1 }} />}13 headerRight={right}14 />15);16stories.add('title', () => (17 <>18 <HeaderExample19 left={() => (20 <HeaderButton.Container left>21 <HeaderButton.Item title='threads' />22 </HeaderButton.Container>23 )}24 right={() => (25 <HeaderButton.Container>26 <HeaderButton.Item title='threads' />27 </HeaderButton.Container>28 )}29 />30 <HeaderExample31 left={() => (32 <HeaderButton.Container left>33 <HeaderButton.Item title='threads' />34 <HeaderButton.Item title='search' />35 </HeaderButton.Container>36 )}37 right={() => (38 <HeaderButton.Container>39 <HeaderButton.Item title='threads' />40 <HeaderButton.Item title='search' />41 </HeaderButton.Container>42 )}43 />44 </>45));46stories.add('icons', () => (47 <>48 <HeaderExample49 left={() => (50 <HeaderButton.Container left>51 <HeaderButton.Item iconName='threads' />52 </HeaderButton.Container>53 )}54 right={() => (55 <HeaderButton.Container>56 <HeaderButton.Item iconName='threads' />57 </HeaderButton.Container>58 )}59 />60 <HeaderExample61 left={() => (62 <HeaderButton.Container left>63 <HeaderButton.Item iconName='threads' />64 <HeaderButton.Item iconName='search' />65 </HeaderButton.Container>66 )}67 right={() => (68 <HeaderButton.Container>69 <HeaderButton.Item iconName='threads' />70 <HeaderButton.Item iconName='search' />71 </HeaderButton.Container>72 )}73 />74 </>75));76stories.add('badge', () => (77 <>78 <HeaderExample79 left={() => (80 <HeaderButton.Container left>81 <HeaderButton.Item iconName='threads' badge={() => <HeaderButton.Badge tunread={[1]} />} />82 <HeaderButton.Item iconName='threads' badge={() => <HeaderButton.Badge tunread={[1]} tunreadUser={[1]} />} />83 <HeaderButton.Item iconName='threads' badge={() => <HeaderButton.Badge tunread={[1]} tunreadGroup={[1]} />} />84 </HeaderButton.Container>85 )}86 />87 </>88));89const ThemeStory = ({ theme }) => (90 <ThemeContext.Provider91 value={{ theme }}92 >93 <HeaderExample94 left={() => (95 <HeaderButton.Container left>96 <HeaderButton.Item iconName='threads' />97 </HeaderButton.Container>98 )}99 right={() => (100 <HeaderButton.Container>101 <HeaderButton.Item title='Threads' />102 <HeaderButton.Item iconName='threads' badge={() => <HeaderButton.Badge tunread={[1]} />} />103 </HeaderButton.Container>104 )}105 />106 </ThemeContext.Provider>107);108stories.add('themes', () => (109 <>110 <ThemeStory theme='light' />111 <ThemeStory theme='dark' />112 <ThemeStory theme='black' />113 </>114));115stories.add('common', () => (116 <>117 <HeaderExample118 left={() => (119 <HeaderButton.Drawer />120 )}121 />122 <HeaderExample123 left={() => (124 <HeaderButton.CloseModal />125 )}126 />127 <HeaderExample128 left={() => (129 <HeaderButton.CancelModal />130 )}131 />132 <HeaderExample133 right={() => (134 <HeaderButton.More />135 )}136 />137 <HeaderExample138 right={() => (139 <HeaderButton.Download />140 )}141 />142 <HeaderExample143 right={() => (144 <HeaderButton.Preferences />145 )}146 />147 <HeaderExample148 right={() => (149 <HeaderButton.Legal />150 )}151 />152 </>...

Full Screen

Full Screen

cardHeaderStyle.jsx

Source:cardHeaderStyle.jsx Github

copy

Full Screen

1import {2 warningCardHeader,3 successCardHeader,4 dangerCardHeader,5 infoCardHeader,6 primaryCardHeader,7 roseCardHeader8} from "assets/jss/material-dashboard-react.jsx";9const cardHeaderStyle = {10 cardHeader: {11 padding: "0.75rem 1.25rem",12 marginBottom: "0",13 borderBottom: "none",14 background: "transparent",15 zIndex: "3 !important",16 "&$cardHeaderPlain,&$cardHeaderIcon,&$cardHeaderStats,&$warningCardHeader,&$successCardHeader,&$dangerCardHeader,&$infoCardHeader,&$primaryCardHeader,&$roseCardHeader": {17 margin: "0 15px",18 padding: "0",19 position: "relative",20 color: "#FFFFFF"21 },22 "&:first-child": {23 borderRadius: "calc(.25rem - 1px) calc(.25rem - 1px) 0 0"24 },25 "&$warningCardHeader,&$successCardHeader,&$dangerCardHeader,&$infoCardHeader,&$primaryCardHeader,&$roseCardHeader": {26 "&:not($cardHeaderIcon)": {27 borderRadius: "3px",28 marginTop: "-20px",29 padding: "15px"30 }31 },32 "&$cardHeaderStats svg": {33 fontSize: "36px",34 lineHeight: "56px",35 textAlign: "center",36 width: "36px",37 height: "36px",38 margin: "10px 10px 4px"39 },40 "&$cardHeaderStats i,&$cardHeaderStats .material-icons": {41 fontSize: "36px",42 lineHeight: "56px",43 width: "56px",44 height: "56px",45 textAlign: "center",46 overflow: "unset",47 marginBottom: "1px"48 },49 "&$cardHeaderStats$cardHeaderIcon": {50 textAlign: "right"51 }52 },53 cardHeaderPlain: {54 marginLeft: "0px !important",55 marginRight: "0px !important"56 },57 cardHeaderStats: {58 "& $cardHeaderIcon": {59 textAlign: "right"60 },61 "& h1,& h2,& h3,& h4,& h5,& h6": {62 margin: "0 !important"63 }64 },65 cardHeaderIcon: {66 "&$warningCardHeader,&$successCardHeader,&$dangerCardHeader,&$infoCardHeader,&$primaryCardHeader,&$roseCardHeader": {67 background: "transparent",68 boxShadow: "none"69 },70 "& i,& .material-icons": {71 width: "33px",72 height: "33px",73 textAlign: "center",74 lineHeight: "33px"75 },76 "& svg": {77 width: "24px",78 height: "24px",79 textAlign: "center",80 lineHeight: "33px",81 margin: "5px 4px 0px"82 }83 },84 warningCardHeader: {85 color: "#FFFFFF",86 "&:not($cardHeaderIcon)": {87 ...warningCardHeader88 }89 },90 successCardHeader: {91 color: "#FFFFFF",92 "&:not($cardHeaderIcon)": {93 ...successCardHeader94 }95 },96 dangerCardHeader: {97 color: "#FFFFFF",98 "&:not($cardHeaderIcon)": {99 ...dangerCardHeader100 }101 },102 infoCardHeader: {103 color: "#FFFFFF",104 "&:not($cardHeaderIcon)": {105 ...infoCardHeader106 }107 },108 primaryCardHeader: {109 color: "#FFFFFF",110 "&:not($cardHeaderIcon)": {111 ...primaryCardHeader112 }113 },114 roseCardHeader: {115 color: "#FFFFFF",116 "&:not($cardHeaderIcon)": {117 ...roseCardHeader118 }119 }120};...

Full Screen

Full Screen

header.js

Source:header.js Github

copy

Full Screen

1const header = document.querySelector('[data-element="header"]')2export function headerExport() {3 if (header) setTimeout(headerInit, 0)4}5function headerInit() {6 const headerNav = header.querySelector('[data-element="header__nav"]')7 const headerButtonBurger = header.querySelector('[data-element="header__button_burger"]')8 const headerLayer = header.querySelector('[data-element="header__layer"]')9 headerButtonBurger.addEventListener('click', toggleMenu)10 headerLayer.addEventListener('click', closeMenu)11 const headerSearchButton = header.querySelector('[data-element="header__button_search"]')12 const headerSearchForm = header.querySelector('[data-element="header__search-form"]')13 const headerLayerSearch = header.querySelector('[data-element="header__layer-search"]')14 const headerSearchBtnClose = header.querySelector('[data-element="header__search-btn_close"]')15 const headerSearchInput = headerSearchForm.getElementsByClassName("header__search-input")[0]16 headerSearchButton.addEventListener("click", openSearch)17 headerLayerSearch.addEventListener("click", closeSearch)18 headerSearchBtnClose.addEventListener("click", closeSearch)19 function openSearch() {20 headerSearchForm.classList.add("header__search-form_active")21 headerLayerSearch.classList.add("header__layer-search_active")22 headerSearchInput.focus()23 }24 function closeSearch() {25 headerSearchForm.classList.remove("header__search-form_active")26 headerLayerSearch.classList.remove("header__layer-search_active")27 }28 function closeMenu() {29 headerButtonBurger.classList.remove("header__button_burger-active")30 headerNav.classList.remove("header__nav_active")31 headerLayer.classList.remove("header__layer_active")32 }33 function toggleMenu() {34 if (headerButtonBurger.classList.contains("header__button_burger-active")) {35 closeMenu()36 } else {37 headerButtonBurger.classList.add("header__button_burger-active")38 headerNav.classList.add("header__nav_active")39 headerLayer.classList.add("header__layer_active")40 }41 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposter = {3 {4 {5 equals: {6 }7 }8 {9 is: {10 headers: {11 },12 body: JSON.stringify({ "status": "success" })13 }14 }15 }16};17mb.create(imposter, function (error, imposter) {18 console.log(imposter.port);19});20var request = require('supertest');21 .get('/test')22 .set('Accept', 'application/json')23 .expect('Content-Type', /json/)24 .expect(200)25 .end(function (err, res) {26 if (err) throw err;27 });28var mb = require('mountebank');29var imposter = {30 {31 {32 equals: {33 }34 }35 {36 is: {37 headers: {38 },39 body: JSON.stringify({ "status": "success" })40 }41 }42 }43};44mb.create(imposter, function (error, imposter) {45 console.log(imposter.port);46});47var request = require('supertest');48 .get('/test')49 .set('Accept', 'application/json')50 .expect('Content-Type', /json/)51 .expect(200)52 .end(function (err, res) {53 if (err)

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposter = mb.create({3 {4 {5 is: {6 }7 }8 }9});10imposter.then(function (server) {11 console.log('Server running at %s', server.url);12});13var request = require('supertest');14var app = require('../app');15describe('GET /', function() {16 it('respond with Hello world!', function(done) {17 request(app)18 .get('/')19 .expect('Hello world!', done);20 });21});22var request = require('supertest');23var app = require('../app');24describe('GET /', function() {25 it('respond with Hello world!', function(done) {26 request(app)27 .get('/')28 .expect('Hello world!', done);29 });30});31var request = require('supertest');32var app = require('../app');33describe('GET /', function() {34 it('respond with Hello world!', function(done) {35 request(app)36 .get('/')37 .expect('Hello world!', done);38 });39});40var request = require('supertest');41var app = require('../app');42describe('GET /', function() {43 it('respond with Hello world!', function(done) {44 request(app)45 .get('/')46 .expect('Hello world!', done);47 });48});49var request = require('supertest');50var app = require('../app');51describe('GET /', function() {52 it('respond with Hello world!', function(done) {53 request(app)54 .get('/')55 .expect('Hello world!', done);56 });57});58var request = require('supertest');59var app = require('../app');60describe('GET /', function() {61 it('respond with Hello world!', function(done) {62 request(app)63 .get('/')64 .expect('Hello world!', done);65 });66});67var request = require('supertest');

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposter = mb.create({3 {4 {5 equals: {6 }7 }8 {9 is: {10 }11 }12 }13});14imposter.then(function () {15 console.log('Imposter created');16});17var mb = require('mountebank');18var imposter = mb.create({19 {20 {21 equals: {22 }23 }24 {25 is: {26 }27 }28 }29});30imposter.then(function () {31 console.log('Imposter created');32});33var mb = require('mountebank');34var imposter = mb.create({35 {36 {37 equals: {38 }39 }40 {41 is: {42 }43 }44 }45});46imposter.then(function () {47 console.log('Imposter created');48});49var mb = require('mountebank');50var imposter = mb.create({51 {52 {53 equals: {54 }55 }56 {57 is: {58 }59 }60 }61});62imposter.then(function () {63 console.log('Imposter created');64});

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposter = {2 {3 {4 is: {5 }6 }7 }8};9var mb = require('mountebank');10mb.create(imposter, function (error, imposters) {11 console.log('Imposter created at %s', imposters[0].url);12});13var request = require('request');14request({15 headers: {16 }17}, function (error, response, body) {18});19var superagent = require('superagent');20 .set('X-Test', 'true')21 .end(function (error, response) {22 });23var axios = require('axios');24 headers: {25 }26}).then(function (response) {27});28var fetch = require('node-fetch');29 headers: {30 }31}).then(function (response) {32});33var got = require('got');34 headers: {35 }36}).then(function (response) {37});38var rp = require('request-promise');39rp({40 headers: {41 }42}).then(function (response) {43});

Full Screen

Using AI Code Generation

copy

Full Screen

1var header = require('mb-header');2var request = require('request');3var options = {4 headers: header('localhost', 8080, '/test'),5 json: {6 {7 {8 is: {9 headers: {10 },11 body: JSON.stringify({name: 'test'})12 }13 }14 }15 }16};17request(options, function (error, response, body) {18 if (!error && response.statusCode == 201) {19 console.log(body);20 }21});22var request = require('request');23var options = {24};25request(options, function (error, response, body) {26 if (!error && response.statusCode == 200) {27 console.log(body);28 }29});30var request = require('request');31var options = {32};33request(options, function (error, response, body) {34 if (!error && response.statusCode == 200) {35 console.log(body);36 }37});38var request = require('request');39var options = {40};41request(options, function (error, response, body) {42 if (!error && response.statusCode == 404) {43 console.log(body);44 }45});46var request = require('request');47var options = {48};49request(options, function (error, response, body) {50 if (!error && response.statusCode == 200) {51 console.log(body);52 }53});54var request = require('request');55var options = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var response = {2 headers: {3 },4};5var server = http.createServer(function (req, res) {6 res.writeHead(response.statusCode, response.headers);7 res.end(response.body);8});9server.listen(3000);10var mb = require('mountebank');11var mbHelper = require('mountebank-helper');12var port = 2525;13var host = 'localhost';14var protocol = 'http';15var imposterPort = 3000;16var imposterProtocol = 'http';17 {18 {19 is: {20 headers: {21 },22 }23 }24 }25];26mb.create(port, host, protocol)27 .then(function () {28 return mbHelper.createImposter(imposterPort, imposterProtocol, stubs);29 })30 .then(function () {31 return mbHelper.get('/test', imposterPort);32 })33 .then(function (response) {34 console.log(response.body);35 })36 .catch(function (error) {37 console.log('Error: ' + error);38 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createServer } = require('http');2const { createImposter, deleteImposter } = require('mountebank');3const { stubs } = require('./stubs');4const PORT = 3000;5const IMPOSTER_PORT = 3001;6const HOST = 'localhost';7const imposter = {8};9const startServer = () => {10 createServer((req, res) => {11 res.writeHead(200, { 'Content-Type': 'application/json' });12 res.end(JSON.stringify({ message: 'Hello World' }));13 }).listen(PORT, HOST, () => {14 });15};16const startImposter = () => {17 createImposter(imposter).then(() => {18 });19};20const stopImposter = () => {21 deleteImposter(IMPOSTER_PORT).then(() => {22 });23};24startServer();25startImposter();26stopImposter();27const { response } = require('mountebank');28 {29 {30 equals: {31 },32 },33 response({34 headers: {35 },36 body: {37 },38 }),39 },40];41module.exports = {42};43const { createServer } = require('http');44const { createImposter, deleteImposter } = require('mountebank');45const { stubs } = require('./stubs');46const PORT = 3000;47const IMPOSTER_PORT = 3001;48const HOST = 'localhost';49const imposter = {50};51const startServer = () => {52 createServer((req, res) => {53 res.writeHead(200, { 'Content-Type': 'application/json' });54 res.end(JSON

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var port = 2525;3var server = mb.create({4});5server.then(function () {6 return server.post('/imposters', {7 {8 {9 is: {10 headers: {11 },12 body: JSON.stringify({13 "cars": {14 }15 })16 }17 }18 }19 });20});21var http = require('http');22var options = {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful