def fullyAssociativeRead(self, address): block = Block(self.blockWord, Address(address)) line = self.cacheHit(block) if line != -1: if self.replacementPolicy == 2: self.queue.put(line) if self.replacementPolicy == 3: self.frequency[line] += 1 return 'CACHE HIT linha ' + str(line) + '\n' else: emptyLine = self.cacheHit(Block(self.blockWord, Address(None))) if emptyLine != -1: if self.replacementPolicy == 2: self.queue.put(emptyLine) if self.replacementPolicy == 3: self.frequency[emptyLine] += 1 oldBlock = self.lines[emptyLine].blockId self.lines[emptyLine] = block return 'CACHE MISS -> alocado na linha ' + str( emptyLine) + ' -> bloco ' + str( oldBlock) + ' substituido\n' if self.replacementPolicy == 1: line, oldBlock = self.randomReplacement(block) return 'CACHE MISS -> alocado na linha ' + str( line) + ' -> bloco ' + str(oldBlock) + ' substituido\n' if self.replacementPolicy == 2: line, oldBlock = self.fifoReplacement(block) return 'CACHE MISS -> alocado na linha ' + str( line) + ' -> bloco ' + str(oldBlock) + ' substituido\n' if self.replacementPolicy == 3: line, oldBlock = self.lfuReplacement(block) return 'CACHE MISS -> alocado na linha ' + str( line) + ' -> bloco ' + str(oldBlock) + ' substituido\n'
def creatAreaPeople(): allBlock = [] #用于存放格子 allPeople = [] #用于存放行人 '''将所有格子全部存入列表''' for i in range(10, 14): for j in range(7, 13): b = Block.Block(1) b.x = i b.y = j if j > Data.ROOM_N / 2: b.isInGrend = 2 b.isNewDefine = 1 # else: # b.type=True b.type = False allBlock.append(b) b3 = Block.Block(1) b3.x = 8 b3.y = 10 b3.debug = 1 b3.type = False allBlock.append(b3) '''随机排序''' # random.shuffle(allBlock) '''取前N个''' '''可有效防止无限产生随机数''' allPeople = allBlock[:Data.PEOPLE_NUMBER] return allPeople
def splitBlocks(self, event=None): """splitBlocks""" if not self._items: return # all_items = self._items sel_items = list(map(int, self.curselection())) change = True # newblocks = [] for bid in sel_items: n_bl = Block.Block(self.gcode[bid].name()) for line in self.gcode[bid]: if line == "( ---------- cut-here ---------- )": # newblocks.append(bl) # self.insertBlock(bl) self.gcode.addUndo(self.gcode.addBlockUndo(bid + 1, n_bl)) n_bl = Block.Block(self.gcode[bid].name()) else: n_bl.append(line) self.gcode.addUndo(self.gcode.addBlockUndo(bid + 1, n_bl)) # newblocks.append(bl) # self.gcode.extend(newblocks) if change: self.fill() self.deleteBlock() self.winfo_toplevel().event_generate("<<Modified>>")
def creatAppointPeo(self): allPeople=[] b1=Block.Block(1) b1.x=3 b1.y=5 b1.type=True allPeople.append(b1) b2=Block.Block(1) b2.x=4 b2.y=5 b2.type=False allPeople.append(b2) b3 = Block.Block(1) b3.x = 5 b3.y = 5 b3.type = False allPeople.append(b3) b4 = Block.Block(1) b4.x = 6 b4.y = 5 b4.type = False allPeople.append(b4) return allPeople
def __init__(self, disk_name="Sorted.cbd", indexBy=[]): self.disk_name = disk_name self.r_block = Block(disk_name) self.w_block = Block(disk_name) self.indexes = {} for i in indexBy: self.indexes.update({i: open(i+"_"+disk_name, "w+")})
def creatAppointPeo(self): allPeople = [] # b1=Block.Block(1) # b1.x=3 # b1.y=5 # b1.type=True # allPeople.append(b1) # # b2=Block.Block(1) # b2.x=4 # b2.y=5 # b2.type=False # allPeople.append(b2) b3 = Block.Block(1) b3.x = 6 b3.y = 10 b3.type = True allPeople.append(b3) b4 = Block.Block(1) b4.x = 2 b4.y = 10 b4.type = False allPeople.append(b4) return allPeople
def get_game_objects(self): list_blocks = [] list_obstacles = [] count_blocks = 0 count_obstacles = 0 arr = Arrow(ARROW_DIR) start = Block(START_DIR, type_block=TYPE_5) end = Block(END_DIR, type_block=TYPE_5) for i in range(DIM): for j in range(DIM): if self.map_data[i][j] > 0 and self.map_data[i][j] < 100: list_blocks.append( Block(BLOCKS_DIR[self.map_data[i][j] - 1], type_block=self.map_data[i][j] - 1)) count_blocks += 1 self.map_data[i][j] = count_blocks elif self.map_data[i][j] < 0: list_obstacles.append( Block(OBSTACLES_DIR[-self.map_data[i][j] - 1])) count_obstacles += 1 self.map_data[i][j] = -count_obstacles elif self.map_data[i][j] == 100: arr.set_map_pos((i, j)) elif self.map_data[i][j] == 200: start.map_pos = (i, j) elif self.map_data[i][j] == 300: end.map_pos = (i, j) return list_blocks, list_obstacles, arr, start, end
def creatTable(): allTable = [] for i in range(5, 37, 2): for j in range(6, 19): t1 = Block.Block(10) t1.x = i t1.y = j t1.type = True allTable.append(t1) for k in range(22, 35): t1 = Block.Block(10) t1.x = i t1.y = k t1.type = True allTable.append(t1) return allTable # def creatWall(): # allWall=[] # for i in range(40): # for ii in range(8): # D=[i,0] # U=[ii,0] # L=[0,i] # R=[Data.ROOM_M,i]
def create_level(self): for l in self.levelFile: newStr = l if newStr.endswith("\n"): newStr = newStr[:-1] self.levelLines.append(stripTrailingSpaces(newStr)) self.readHeaders() #print self.messages x = 0 y = 0 #an enemy port tells the game where to spawn enemies for row in self.levelLines: for col in row: if col == "X": obstacle = Block(x, y, "world/blocks/cinder.png") self.world.append(obstacle) self.all_sprite.add(self.world) if col == "C": obstacle = Block(x, y, "level/tutorial/sign.png") obstacle.solid = False self.world.append(obstacle) self.all_sprite.add(self.world) if col in LevelTutorial.DIGITS: obstacle = InfoBlock(x, y, self.messages[int(col)]) self.world.append(obstacle) self.all_sprite.add(self.world) if col == "P": self.crashman = CrashmanTutorial(x, y, self, self.character) self.all_sprite.add(self.crashman) if col == "L": pep = Pipe(x, y - 75, "world/pipes/leftpipe.png", "left") self.world.append(pep) self.all_sprite.add(self.world) self.enemy_ports.append((x, y, "left")) if col == "R": pep = Pipe(x - 125, y - 75, "world/pipes/rightpipe.png", "right") self.world.append(pep) self.all_sprite.add(self.world) self.enemy_ports.append((x, y, "right")) if col == "l": pep = Pipe(x + 25, y - 75, "world/pipes/leftpipe.png", "left") self.world.append(pep) self.all_sprite.add(self.world) if col == "r": pep = Pipe(x - 125, y - 75, "world/pipes/rightpipe.png", "right") self.world.append(pep) self.all_sprite.add(self.world) x += 25 y += 25 x = 0
def loadLevel(self, lev): file = open(lev, 'r') lines = file.readlines() file.close() blockSize = 100 newlines = [] for line in lines: newline = "" for c in line: if c != '\n': newline += c newlines += [newline] lines = newlines previousLine = 0 chars = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#' ] buttons = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'p'] for y, line in enumerate(lines): #print y,line for x, c in enumerate(line): #print "--->",x,c if c in chars: if c == '#': Block( "Pictures/Blocks, and background/Crates/obj_crate002.png", "#", [ blockSize * x + blockSize / 2, blockSize * y + (blockSize / 2) - 9 * 100 ], [blockSize, blockSize]) #print "don made a reg block" else: Block( "Pictures/Blocks, and background/Letter_Blocks_01/Letter_Blocks_01/Letter_Blocks_01_Set_4_" + c + "_64x64.png", c, [ blockSize * x + blockSize / 2, blockSize * y + (blockSize / 2) - 9 * 100 ], [blockSize, blockSize]) previousLine = line #print "don made a letter block" elif c in buttons: Button( "Pictures/Blocks, and background/Letter_Blocks_01/" + c + ".png", c, previousLine, [ blockSize * x + blockSize / 2, blockSize * y + (blockSize / 2) - 9 * 100 ], [blockSize, blockSize])
def __init__(self, width, height): self.wallColor = (200, 200, 200) self.grid = [] self.width = width self.height = height for i in range(-1, height + 1): row = [] for j in range(-1, width + 1): if (j == -1 or j == width or i == -1 or i == height): row.append(Block.Block(self.wallColor, False, True)) else: row.append(Block.Block((0, 0, 0), False, False)) self.grid.append(row)
def __init__(self, disk_name="Heap.cbd", indexBy=[], indexBTree=True, indexBPlusTree=False): maxDegreeBTree = 10 self.r_block = Block(disk_name) self.w_block = Block(disk_name) self.indexes = {} self.indexBTree = indexBTree self.indexBPlusTree = indexBPlusTree for i in indexBy: if indexBPlusTree: self.indexes.update({i:BPlusTree(getcwd()+"\\"+i+".index",serializer=StrSerializer(),key_size=128)}) else: if indexBTree: self.indexes.update({i:BTree(maxDegreeBTree)}) else: self.indexes.update({i:{}})
def Genesis(self): #generate some walets Coinbase1 = wlt.Wallet() self.Coinbase = wlt.Wallet() #send 10000 coins to coinbase genesisTransaction = txn.Transaction( Coinbase1.PEMPublicKey.decode(), self.Coinbase.PEMPublicKey.decode(), 100000, 0, None) genesisTransaction.GenerateTransactionSignature(Coinbase1.PrivateKey) self.GenesisTransaction = genesisTransaction #give the transaction a manual hash genesisTransaction.TransactionHash = "0" genesisTransaction.TransactionOutputs.append( outs.TransactionOutput(genesisTransaction.Recipient, genesisTransaction.Value, genesisTransaction.TransactionHash, 0)) self.UTXOs[genesisTransaction.TransactionOutputs[0].Id] = { "Transaction": genesisTransaction.TransactionOutputs[0] } print("create and mine genesis block") genesis = bl.Block("0") genesis.AddTransaction(genesisTransaction, self) self.AddBlock(genesis)
def creatPeople(): allBlock = [] # 用于存放格子 allPeople = [] # 用于存放行人 normal_x = np.arange(0, 1, 1 / Data.PEOPLE_NUMBER) normal_y = norm() normal_y_result = Data.PEOPLE_FORCE * (normal_y.pdf(normal_x)) random.shuffle(normal_y_result) '''将所有格子全部存入列表''' for i in range(1, Data.ROOM_M): for j in range(1, Data.ROOM_N): b = Block.Block(1) b.x = i b.y = j b.force = Data.PEOPLE_FORCE if j > Data.ROOM_N / 2: b.type = False else: b.type = True allBlock.append(b) '''随机排序''' random.shuffle(allBlock) for i in range(len(allPeople)): allPeople[i].force = normal_y_result[i] '''取前N个''' '''可有效防止无限产生随机数''' allPeople = allBlock[:Data.PEOPLE_NUMBER] return allPeople
def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) settings.multiplayer = False self.fpsDisplay = pyglet.clock.ClockDisplay() self.clear() self.startScreen = True self.startScreenDisplay = StartScreen() self.pauseScreenDisplay = PauseScreen() self.saveScreenDisplay = SaveScreen() self.loadScreenDisplay = LoadScreen() self.helpScreenDisplay = HelpScreen() self.stlSelectionScreenDisplay = StlSelectionScreen() self.playTypeScreenDisplay = PlayTypeScreen() self.ipSelectionScreenDisplay = IpSelectionScreen() self.stlCompleteScreenDisplay = StlCompleteScreen() self.stlConversion = stlConvert() self.player = Player(29,29) self.blocks = Block() self.save= SaveMap() self.load = LoadMap() self.keys = key.KeyStateHandler() self.push_handlers(self.keys) self.set_exclusive_mouse(False) self.mouse = [0,0] self.loadScreen = False self.playing= False self.pauseScreen = False self.saveScreen=False self.helpScreen = False self.stlSelectionScreen = False self.playTypeScreen = False self.ipSelectionScreen = False self.stlCompleteScreen=False pyglet.clock.schedule_interval(self.update,1/settings.FPS)
def save(self, pcb, program): position = self.next_post_free() size = program.size() block = Block(size, pcb.pid, position, position + size) self.save_block(block) for instruction in program.getInstrucciones(): self.memory.write(self.next_post_free(), instruction)
def process(self): for i in range(6): for j in range(6): c = self.state[i][j] if c is not ' ': block = next( (block for block in self.block_list if block.name == c), None) if block is not None: block.length += 1 if block.direction is None: if block.coord[1] is i: block.direction = Direction.HORIZONTAL else: block.direction = Direction.VERTICAL else: self.block_list.append( Block(name=c, coord=[j, i], position=[ self.pos[0] + j * 100, self.pos[1] + i * 100 ], length=1))
def test_blockchain_python(): block = Block.Block() # Create the blockchain and add the genesis block blockchain = [block.create_genesis_block()] previous_block = blockchain[0] num_of_blocks_to_add = 5 # Add blocks to the chain for i in range(0, num_of_blocks_to_add): block_to_add = block.next_block(previous_block) blockchain.append(block_to_add) previous_block = block_to_add # Prints the entire blockchain in JSON form for i in range(0, blockchain.__len__()): print(json.dumps(blockchain[i].__dict__)) print("########################################") # Printing the original block print(json.dumps(blockchain[2].__dict__)) # Tampering with the block data blockchain[2].data = "Modified" # Re-hashing the block blockchain[2].hash = Block.Block.hash_block(blockchain[2]) # Printing the tampered block print(json.dumps(blockchain[2].__dict__)) print("########################################")
def mine(): # Get the miner information including the answer informationMiner = request.get_json() miner_information_dict[ informationMiner['miner_address']] = informationMiner answer = informationMiner['answer'] # Get a random number, upto 10, transactions filled out from the transaction server for _ in range(random.randint(2, 11)): [new_sender, new_reciever, amount] = get_transactions() this_nodes_transactions.append({ "from": new_sender, "to": new_reciever, "amount": amount }) print "NEW TRANSACTIONS :" print this_nodes_transactions # Check if the Challenge and Answer are truly equal if (len(this_nodes_transactions) != 0 and answer == challenge): # Create a new global challenge, since challenge has already been solved global challenge [challenge, d_level] = refresh_challenge(miner_information_dict, h) print str(challenge) + " new challenge" # Add the transaction where this server has given a coin to the miner this_nodes_transactions.append({ "from": "network", "to": informationMiner['miner_address'], "amount": 1 }) # Now we can gather the data needed to create the new block last_block = blockchain[len(blockchain) - 1] new_block_data = {"transactions": list(this_nodes_transactions)} new_block_index = last_block.index + 1 new_block_timestamp = this_timestamp = date.datetime.now() last_block_hash = last_block.hash # Empty transaction list and create a new block this_nodes_transactions[:] = [] mined_block = Block(new_block_index, new_block_timestamp, new_block_data, last_block_hash) blockchain.append(mined_block) # Let the client know we mined a block return "\n" + json.dumps({ "index": new_block_index, "timestamp": str(new_block_timestamp), "data": new_block_data, "hash": last_block_hash }) + "\n" # In the case where there is nothing to mine (no transactions) # Note: As of now, this part of the condition should never be invoked else: #print "Spam Miner" return "Try Again"
def insertBlock(self, event=None): """Insert New Block""" active = self.index(Tk.ACTIVE) if self._items: bid, lid = self._items[active] bid += 1 else: bid = 0 block = Block.Block() block.expand = True block.append("G0 X0 Y0") block.append("G1 Z0") block.append(CNC.zsafe()) self.gcode.addUndo(self.gcode.addBlockUndo(bid, block)) self.selection_clear(0, Tk.END) self.fill() # find location of new block while active < self.size(): if self._items[active][0] == bid: break active += 1 self.selection_set(active) self.see(active) self.activate(active) self.edit() self.winfo_toplevel().event_generate("<<Modified>>")
def readBucket(bucketID, maxDataLength): if not os.path.exists(home + bucketLoc): os.makedirs(home + bucketLoc) inputFile = open(home + bucketLoc + str(bucketID), "rb") # rb = read binary #bytesIn = inputFile.read() bytesIn = pickle.load(inputFile) inputFile.close() if encrypt: bytesIn = Encryptor.decrypt(bytesIn, key) result = [] while True: leafBytes = bytesIn[:4] bytesIn = bytesIn[4:] if leafBytes == b"": break # break if end of file segIDBytes = bytesIn[:4] bytesIn = bytesIn[4:] dataLength = int.from_bytes(bytesIn[:4], byteorder="little") bytesIn = bytesIn[4:] data = bytesIn[:dataLength] bytesIn = bytesIn[maxDataLength:] result.append( Block.Block(int.from_bytes(leafBytes, byteorder="little"), int.from_bytes(segIDBytes, byteorder="little"), data)) return result
def ConstructBlock(self): # # timer = Thread(target = self.ConstructMode) # timer.start() newBlock = bl.Block(self.Blockchain[len(self.Blockchain) - 1].BlockHash) newBlock.validator = self.mainWallet.PEMPublicKey # might not need this? addedTransactions = [] timeout = time.time() + 10 while time.time() <= timeout: if len(self.TransactionQue) > 0: for i in self.TransactionQue: if i not in addedTransactions: newBlock.AddTransaction(i) addedTransactions.append(i) if len(addedTransactions) > 0: for i in addedTransactions: self.TransactionQue.remove(i) return newBlock
def load_map(self): counter = str(self.counter) for letter in counter: self.map = MAP_level[letter] file = open(self.map, 'r') for i, line in enumerate(file): # y for j, letter in enumerate(line): # x if letter in MAP_KEYS.keys(): block_temp = Block(j * TILE_SIZE, i * TILE_SIZE, MAP_KEYS[letter]) block_temp.add(self.allBlocks) if letter in SOLID_BLOCKS: block_temp.add(self.solidBlocks) if letter in LOOT_BLOCKS: block_temp.add(self.lootBlocks) if letter in Enemy: block_temp.add(self.enemy) if letter in HEAL_BLOCKS: block_temp.add(self.heal) if letter in DOORS: block_temp.add(self.door) if letter in KEYS: block_temp.add(self.keys) if letter == 'G': self.monster.g_x = j * TILE_SIZE self.monster.g_y = i * TILE_SIZE if letter == 's': self.player.start_x = j * TILE_SIZE self.player.start_y = i * TILE_SIZE self.m_counter = self.counter self.BACKGROUND = background_key[str(self.m_counter)] self.background = pygame.image.load(self.BACKGROUND["texture"]) self.background = pygame.transform.scale(self.background, (63*48,19*48)) self.background.convert()
def loadLevel(levelFile): f = open(levelFile, 'r') lines = f.readlines() f.close() level = [] #Block Size is 50x50 newLines = [] for line in lines: newLine = "" for character in line: if not (character == '\n'): newLine += character newLines += [newLine] lines = newLines for line in lines: print line for y, line in enumerate(lines): for x, character in enumerate(line): if character == '#': level += [Block([x * 50 + 25, y * 50 + 25])] if character == '$': level += [BlackBlock([x * 50 + 25, y * 50 + 25])] return level
def initCoin(self): #generate some walets Coinbase = wlt.Wallet() walletA = wlt.Wallet() #send 100 coins to walleta genesisTransaction = txn.Transaction(Coinbase.PublicKey, walletA.PublicKey, 100, 0, None) genesisTransaction.GenerateTransactionSignature(Coinbase.PrivateKey) #give the transaction a manual hash genesisTransaction.TransactionHash = "0" genesisTransaction.TransactionOutputs.append( outs.TransactionOutput(genesisTransaction.Recipient, genesisTransaction.Value, genesisTransaction.TransactionHash)) self.UTXOs[genesisTransaction.TransactionOutputs[0].Id] = { "Transaction": genesisTransaction.TransactionOutputs[0] } print("create and mine genesis block") genesis = bl.Block("0") genesis.AddTransaction(genesisTransaction, self) self.AddBlock(genesis)
def latest_blocks(): """ GET: Return the latest block in JSON format PUT: Adda block to the blockchain """ if request.method == 'GET': response = blockchain.getLastBlock() response = json.dumps(response, default=lambda o: o.__dict__) return response return render_template("response.html", response=response) elif request.method == 'PUT': # Take in the request inputJSON = request.json # Create a block for the request blockToAdd = Block.Block() blockToAdd.index = inputJSON["index"] blockToAdd.previousHash = inputJSON["previousHash"] blockToAdd.timestamp = inputJSON["timestamp"] blockToAdd.nonce = inputJSON["nonce"] blockToAdd.transactions = [ Transaction.createTransaction(transaction) for transaction in inputJSON["transactions"] ] blockToAdd.hash = blockToAdd.toHash() # Add block response = blockchain.addBlock(blockToAdd) response = json.dumps(response, default=lambda o: o.__dict__, indent=4, separators=(',', ': ')) return render_template("response.html", response=response)
def DistributeFunds(self): block1 = bl.Block(self.Blockchain[len(self.Blockchain) - 1].BlockHash) for i in self.KnowAddresses: block1.AddTransaction(self.Coinbase.SendFunds(i, 1000, self), self) self.AddBlock(block1) self.LastBlock = block1
def readStash(maxDataLength ): # returns a list where each element is a block in the stash if not os.path.exists(home + "/Dropbox/stash"): return "new ORAM" inputFile = open(home + "/Dropbox/stash", "rb") result = [] # Same problem as in readBucket(). Try to read it less times. while True: #print ("loop") leafBytes = inputFile.read(4) if leafBytes == b"": #print ("true") break # break if end of file segIDBytes = inputFile.read(4) dataLength = int.from_bytes(inputFile.read(4), byteorder="little") data = inputFile.read(dataLength) #print ("loop") inputFile.read(maxDataLength - dataLength) result.append( Block.Block(int.from_bytes(leafBytes, byteorder="little"), int.from_bytes(segIDBytes, byteorder="little"), data)) inputFile.close() return result
def session_breaker(): global session session = 0 sys.stdout.flush() if (len(txStack) % 2 == 1): sk, pk = util.generateKeyPair() dummy = ac.Voter("Lorem Ipsum", "1000-10-10", pk.to_string()) dummy.sk = sk.to_string() pty = ac.Party(0, "dummy party") empTx = Tx.Transaction(dummy, pty) empTx.is_proc = True empTx.txoutput = TxOut.TxOutput(pty, empTx.txid) txStack.append(empTx) tempbl = Block.Block(txStack[-2:len(txStack):1]) season.addBlock(tempbl) #for i in VoterList: # del(i) print("\nALL RECORDS DELETED") print("\t\tRESULTS:\n") for party in partyList: print(party.name + " : " + str(party.countVotes(season))) sys.exit()
def __init__(self, map_x_coord, map_y_coord, x_dim, y_dim, x_block_dim, y_block_dim, path, name): self.x_dim = x_dim self.y_dim = y_dim self.x_block_dim = x_block_dim self.y_block_dim = y_block_dim self.max_x_index = x_dim / x_block_dim self.max_y_index = y_dim / y_block_dim self.map_x_coord = map_x_coord self.map_y_coord = map_y_coord self.path = path self.name = name self.csv_path = path + '/' + name + '/' + name + '.csv' self.image_path = path + '/' + name + '/' + name + '.jpg' self.image = pygame.image.load(self.image_path).convert() self.is_active = False self.npcs = [] print 'max_x_index:' + str(self.max_x_index) print 'max_y_index:' + str(self.max_y_index) # create room array self.room = [] # array of block objects for i in xrange(self.max_x_index): # print 'room i:' + str(i) self.room.append([]) for j in xrange(self.max_y_index): # print 'room i,j:' + str((i,j)) self.room[i].append(Block.Block(i, j)) self.syncCSV(self.csv_path)