Exemplo n.º 1
0
 def checkPart1(self, test):
     
     if (test[0] == '"' and test[len(test)-1] == '"'):
         # this is a string literal
         return self.checkStringLiteral(test)
     elif (test[0] == '{' and test[len(test)-1] == '}'):
         # this is a block
         from Block import Block
         #print test[0:len(test)]
         b = Block(test[0:len(test)],self.getParent())
         b.setSyntaxOnly(self.syntax_only)
         if (b.checkSyntax()):
             if(self.syntax_only == False):
                 self.property_list = b.property_list
             return True
         else:
             return False       
     elif (test[0] == '(' and test[len(test)-1] == ')'):
         # this is an expression
         e = Expression(test[1:len(test)-1],self.getParent())
         e.setSyntaxOnly(self.syntax_only)
         if (e.checkSyntax()):
             if(self.syntax_only == False):
                 self.property_list = e.property_list
             return True
         else:
             return False
     elif not (self.checkAsterisk(test)):
         # this is a name with none or multiple *
         print ("This is an invalid Expression: " + test)
         return False
     return True
Exemplo n.º 2
0
 def dump(self):
   Block.dump(self,"FileList")
   print " own_key:    %d" % self.own_key
   print " blk_cnt:    %d" % self.block_count
   print " data blks:  %s" % self.data_blocks
   print " parent:     %d" % self.parent
   print " extension:  %d" % self.extension
Exemplo n.º 3
0
    def getCalcuDoku(self):

        img = self.cutOut(self.img)

        self.calcuDoku = CalcuDoku(self.size)
        self.extractSudoku(img, self.size)
        print self.sudoku
        print self.right
        print self.below

        self.sectors = [[None for i in range(self.size)] for j in range(self.size)]
        for i in range(0, self.size):
            for j in range(0, self.size):
                if not self.sectors[i][j]:
                    if self.sudoku[i][j]:
                        ops = self.sudoku[i][j]
                        b = Block(ops)
                        self.calcuDoku.addBlock(b)
                        b.addLocation(i+1, j+1)
                        self.sectors[i][j] = b
                        self.discover(i, j)
                    else:
                        print "huh"
                        sys.exit(1)

        return self.calcuDoku
Exemplo n.º 4
0
 def create(self, name, create_ts=None, disk_ts=None, mod_ts=None, extension=0, fstype=0):
   Block.create(self)
   # init fresh hash table
   self.hash_size = self.blkdev.block_longs - 56
   self.hash_table = []
   for i in xrange(self.hash_size):
     self.hash_table.append(0)
   
   # timestamps
   self.mod_ts = mod_ts
   self.disk_ts = disk_ts
   self.create_ts = create_ts
   
   # name
   self.name = name
   
   # bitmap: blank 
   self.bitmap_flag = 0xffffffff
   self.bitmap_ptrs = []
   for i in xrange(25):
     self.bitmap_ptrs.append(0)
   self.bitmap_ext_blk = 0
   
   # new stuff for DOS6 and DOS7
   self.fstype = fstype
   self.blocks_used = 0
   
   self.extension = extension
Exemplo n.º 5
0
 def create(self, parent, name, data_blocks, extension, byte_size=0, protect=0, comment=None, mod_ts=None, hash_chain=0):
   Block.create(self)
   self.own_key = self.blk_num
   n = len(data_blocks)
   self.block_count = n
   if n == 0:
     self.first_data = 0
   else:
     self.first_data = data_blocks[0]
   
   self.data_blocks = data_blocks
   self.protect = protect
   self.protect_flags = ProtectFlags(self.protect)
   self.byte_size = byte_size
   if comment == None:
     self.comment = ''
   else:
     self.comment = comment
   self.mod_ts = mod_ts
   self.name = name
   self.hash_chain = hash_chain
   self.parent = parent
   self.extension = extension
   self.valid = True
   return True
Exemplo n.º 6
0
 def __init__(self, image, pos = (0,0), blocksize = [50,50], screensize = [800,600]):
     Block.__init__(self, image, pos, blocksize)
     self.maxSpeed = blocksize[0]/14.0
     self.screensize = screensize
     self.living = True
     self.detectRange = 100
     self.seePlayer = False
     self.headingx = "right"
     self.headingy = "none"
     self.directionCount = 0
     self.realx = pos[0]
     self.realy = pos[1]
     self.x = screensize[0]/2
     self.y = screensize[1]/2
     self.x = pos[0]
     self.y = pos[1]
     self.g = blocksize[0]/10
     self.offsetx = 0
     self.offsety = 0
     self.jumpSpeed = 0
     self.jumpSpeedMax = 50
     self.fallSpeedMax = int(blocksize[0]/2) -2
     self.onfloor = False
     self.floor = screensize[1]
     self.touchFloor = False
     self.turn = 0
Exemplo n.º 7
0
  def _read(self):
    Block.read(self)
    if not self.valid:
      return False
    
    # FileHeader fields
    self.own_key = self._get_long(1)
    self.block_count = self._get_long(2)
    self.first_data = self._get_long(4)
    
    # read (limited) data blocks table
    bc = self.block_count
    mbc = self.blkdev.block_longs - 56
    if bc > mbc:
      bc = mbc
    self.data_blocks = []
    for i in xrange(bc):
      self.data_blocks.append(self._get_long(-51-i))
    
    self.protect = self._get_long(-48)
    self.protect_flags = ProtectFlags(self.protect)
    self.byte_size = self._get_long(-47)
    self.comment = self._get_bstr(-46, 79)
    self.mod_ts = self._get_timestamp(-23)
    self.name = self._get_bstr(-20, 30)
    self.hash_chain = self._get_long(-4)
    self.parent = self._get_long(-3)
    self.extension = self._get_long(-2)

    self.valid = (self.own_key == self.blk_num)
    return self.valid
Exemplo n.º 8
0
 def create(self, hdr_key, seq_num, data, next_data):
   Block.create(self)
   self.hdr_key = hdr_key
   self.seq_num = seq_num
   self.data_size = len(data)
   self.next_data = next_data
   self.contents = data
Exemplo n.º 9
0
  def write(self):
    self._create_data()
    
    # hash table
    self._put_long(3, self.hash_size)
    for i in xrange(self.hash_size):
      self._put_long(6+i, self.hash_table[i])
    
    # bitmap
    self._put_long(-50, self.bitmap_flag)
    for i in xrange(25):
      self._put_long(-49+i, self.bitmap_ptrs[i])
    self._put_long(-24, self.bitmap_ext_blk)
    
    # timestamps
    self._put_timestamp(-23, self.mod_ts)
    self._put_timestamp(-10, self.disk_ts)
    self._put_timestamp(-7, self.create_ts)
    
    # name
    self._put_bstr(-20, 30, self.name)
    self._put_long(-2, self.extension)
    
    # DOS6 and DOS7 stuff
    self._put_long(-11, self.blocks_used)
    self._put_long(-4, self.fstype)

    Block.write(self)
Exemplo n.º 10
0
 def read(self):
   Block.read(self)
   if not self.valid:
     return False
   
   # name hash
   self.hash_size = self._get_long(3)
   self.hash_table = []
   for i in xrange(self.hash_size):
     self.hash_table.append(self._get_long(6+i))
   
   # bitmap
   self.bitmap_flag = self._get_long(-50)
   self.bitmap_ptrs = []
   for i in xrange(25):
     bm_blk = self._get_long(-49+i)
     self.bitmap_ptrs.append(bm_blk)
   self.bitmap_ext_blk = self._get_long(-24)
   
   # timestamps
   self.mod_ts = self._get_timestamp(-23)
   self.disk_ts = self._get_timestamp(-10)
   self.create_ts = self._get_timestamp(-7)
   
   # name
   self.name = self._get_bstr(-20, 30)
   self.extension = self._get_long(-2)
   
   # check validity
   self.valid = True
   #self.valid = (self.bitmap_flag == 0xffffffff)
   return self.valid
Exemplo n.º 11
0
 def dump(self):
   Block.dump(self,"DirCache")
   print " own_key:    %d" % (self.own_key)
   print " parent:     %d" % (self.parent)
   print " num_records:%d" % (self.num_records)
   print " next_cache: %d" % (self.next_cache)
   for r in self.records:
     r.dump()
Exemplo n.º 12
0
def blockCollection2BlockObject(blockCollection):
    b = []
    bSize = blockCollection.blockBitSize
    for blk in blockCollection.blocks:
        bObj = Block(0,0)
        bObj.buildBlockFromProtoBuf(blk.index, blk.data, bSize) 
        b.append(bObj)
    return b
Exemplo n.º 13
0
def blockCollectionDisk2BlockObject(blockCollection):
    b = []
    bSize = blockCollection.blockBitSize
    for i in blockCollection.collection:
        bObj = Block(0,bSize, True)
        bObj.buildBlockFromProtoBufDisk(i.blk)
        b.append(bObj)
    return b
Exemplo n.º 14
0
 def write(self):
   Block._create_data(self)
   self._put_long(1, self.hdr_key)
   self._put_long(2, self.seq_num)
   self._put_long(3, self.data_size)
   self._put_long(4, self.next_data)
   if self.contents != None:
     self.data[24:24+self.data_size] = self.contents
   Block.write(self)
Exemplo n.º 15
0
	def Packet0x23(self, buff):
		Location = buff.readPosition();
		BlockID = buff.readVarInt();
		
		block = Block();
		block.location = Location;
		block.blockID = BlockID;
		self.bot.world.blocks[Location.get()] = block;
		print("block: " + str(BlockID) + " - location: " + str(Location.get()));
Exemplo n.º 16
0
 def create(self, parent, data_blocks, extension):
   Block.create(self)
   self.own_key = self.blk_num
   self.block_count = len(data_blocks)
   self.data_blocks = data_blocks
   self.parent = parent
   self.extension = extension
   self.valid  = True
   return True
Exemplo n.º 17
0
 def __init__(self, blkdev, blk_num=0):
   Block.__init__(self, blkdev, blk_num)
   self.dos_type = None
   self.got_root_blk = None
   self.got_chksum = 0
   self.calc_chksum = 0
   self.boot_code = None
   self.num_extra = self.blkdev.bootblocks - 1
   self.max_boot_code = self.blkdev.bootblocks * self.blkdev.block_bytes - 12
   self.extra_blks = []
Exemplo n.º 18
0
 def __init__(self, gameEngine, base, position, blockId):
     Block.__init__(self, gameEngine, base)
     self._durability = -1
     self._points = 0
     self.loadModel('models/cone_wo2')
     self.setModelTexture('textures/bricks.jpg')
     self.setModelParameters(position)
     self.createHitCollider(blockId)
     self.createRay()
     self.setFallCollideHandling()
Exemplo n.º 19
0
 def dump(self):
   Block.dump(self,"UserDir")
   print " own_key:    %d" % (self.own_key)
   pf = ProtectFlags(self.protect)
   print " protect:    0x%x 0b%s %s" % (self.protect, pf.bin_str(), pf)
   print " comment:    '%s'" % self.comment
   print " mod_ts:     %s" % self.mod_ts
   print " name:       '%s'" % self.name
   print " hash_chain: %d" % self.hash_chain
   print " parent:     %d" % self.parent
Exemplo n.º 20
0
 def parseXml(node):
     district = District()
     district.districtType = int(node.getAttribute("type"))
     for child in node.childNodes:
         if child.tagName == Coordinates.getXmlName():
             district.addBoundary(Coordinates.parseXml(child))
         if child.tagName == Network.getXmlName():
             district.addNetwork(Network.parseXml(child))
         if child.tagName == Block.getXmlName():
             district.addBlock(Block.parseXml(child))
     return district
Exemplo n.º 21
0
 def create(self, dos_type=DOS0, root_blk=None, boot_code=None):
   Block.create(self)
   self._create_data()
   self.dos_type = dos_type
   self.calc_root_blk = int(self.blkdev.num_blocks / 2)
   if root_blk != None:
     self.got_root_blk = root_blk
   else:
     self.got_root_blk = self.calc_root_blk
   self.boot_code = boot_code
   self.valid = True
Exemplo n.º 22
0
  def _read(self):
    Block.read(self)
    if not self.valid:
      return False

    # Comment fields
    self.own_key = self._get_long(1)
    self.header_key = self._get_long(2)
    self.checksum = self._get_long(5)
    self.comment = self._get_bstr(6, 79)
    self.valid = (self.own_key == self.blk_num)
    return self.valid
Exemplo n.º 23
0
def check(path,syntaxOnly):
    with open (path, "r") as myfile:
        data=myfile.read()

    data = removeComments(data)

    #TODO now check Syntax
    
    b = Block(data,None)
    b.setSyntaxOnly(syntaxOnly)
    
    return b.checkSyntax()
Exemplo n.º 24
0
 def write(self):
   Block._create_data(self)
   self._put_long(1, self.own_key)
   self._put_long(-48, self.protect)
   self._write_nac_modts()
   self._put_long(-4, self.hash_chain)
   self._put_long(-3, self.parent)
   self._put_long(-2, self.extension)
   # hash table
   for i in xrange(self.hash_size):
     self._put_long(6+i, self.hash_table[i])
   Block.write(self)
Exemplo n.º 25
0
 def write(self):
   Block._create_data(self)
   self._put_long(1, self.own_key)
   self._put_long(2, self.block_count)
   
   # data blocks
   for i in xrange(len(self.data_blocks)):
     self._put_long(-51-i, self.data_blocks[i])
   
   self._put_long(-3, self.parent)
   self._put_long(-2, self.extension)
   Block.write(self)
Exemplo n.º 26
0
 def write(self):
   Block._create_data(self)
   self._put_long(1, self.own_key)
   self._put_long(2, self.parent)
   self._put_long(3, self.num_records)
   self._put_long(4, self.next_cache)
   
   # put records
   off = 24
   for r in self.records:
     off = r.put(self.data, off)
   
   Block.write(self)
Exemplo n.º 27
0
 def create(self, parent, records=None, next_cache=0):
   Block.create(self)
   self.own_key = self.blk_num
   self.parent = parent
   self.next_cache = next_cache
   if records == None:
     self.num_records = 0
     self.records = []
   else:
     self.num_records = len(records)
     self.records = records
   self.valid = True
   return True
Exemplo n.º 28
0
 def _read(self):
   Block.read(self)
   if not self.valid:
     return False
   
   # FileData fields
   self.hdr_key = self._get_long(1)
   self.seq_num = self._get_long(2)
   self.data_size = self._get_long(3)
   self.next_data = self._get_long(4)
   
   self.valid = True
   return self.valid
Exemplo n.º 29
0
 def write(self):
   Block._create_data(self)
   self._put_long(1, self.own_key)
   self._put_long(-48, self.protect)
   self._put_bstr(-46, 79, self.comment)
   self._put_timestamp(-23, self.mod_ts)
   self._put_bstr(-20, 30, self.name)
   self._put_long(-4, self.hash_chain)
   self._put_long(-3, self.parent)
   # hash table
   for i in xrange(self.hash_size):
     self._put_long(6+i, self.hash_table[i])
   Block.write(self)
Exemplo n.º 30
0
  def dump(self):
    Block.dump(self, "Root")
    print " hash size: %d" % self.hash_size
    print " hash table:%s" % self.hash_table
    print " bmp flag:  0x%08x" % self.bitmap_flag
    print " bmp ptrs:  %s" % self.bitmap_ptrs
    print " bmp ext:   %d" % self.bitmap_ext_blk
    print " mod_ts:    %s" % self.mod_ts
    print " disk_ts:   %s" % self.disk_ts
    print " create_ts: %s" % self.create_ts
    print " disk name: %s" % self.name
    print " extension: %s" % self.extension

     
Exemplo n.º 31
0
 def init(self):
     pygame.mixer.music.load('music/snakeMusic.mp3')
     pygame.mixer.music.play(-1)
     self.bgColor = (255, 255, 255)
     self.gameOver = True
     # Snake
     Snake.init()
     self.snakeGroup = pygame.sprite.Group()
     self.snakeList = []
     # Snake movement
     self.counter = 0
     self.isMoveRight = True
     self.snakeLength = 4
     self.snakeSize = 14
     self.timer = 0
     # Border
     Border.init()
     self.blockGroup = pygame.sprite.Group()
     # Barrier
     Barrier.init()
     self.barrierGroup = pygame.sprite.Group()
     self.collideBarrier = (0, 0)
     self.points = 0
     # Food
     Food.init()
     # Block
     Block.init()
     # Initialize the snakeGroup
     for i in range(self.snakeLength):
         snake = Snake(self.width // 2,
                       self.height // 2 + self.snakeSize * i)
         self.snakeGroup.add(snake)
         self.snakeList.append(snake)
     # Initialize the foodGroup
     self.foodGroup = pygame.sprite.Group()
     # Initialize the borderGroup
     self.borderGroup = pygame.sprite.Group(
         Border(self.width // 2, self.height + 300, self.width,
                self.height))
     # GameOver Image
     self.GGImage = pygame.image.load('images/gameover.png').convert_alpha()
     self.GGImage = pygame.transform.scale(self.GGImage, (1920, 1080))
     self.GGrect = self.GGImage.get_rect()
Exemplo n.º 32
0
    def loadLevel(self, level):
        self.level = level
        levelFile = "maps/" + level + ".lvl"

        f = open(levelFile, "r")
        lines = f.readlines()
        f.close()

        newlines = []

        for line in lines:
            newline = ""
            for c in line:
                if c != "\n":
                    newline += c
            newlines += [newline]

        lines = newlines

        for y, line in enumerate(lines):
            for x, c in enumerate(line):
                if c == "#":
                    Block("maps/sand.png",
                          [x * self.blockSize, y * self.blockSize])
                elif c == "!":
                    Block("maps/grass.png",
                          [x * self.blockSize, y * self.blockSize])
                elif c == "+":
                    Block("maps/grasssand.png",
                          [x * self.blockSize, y * self.blockSize])
                elif c == "-":
                    HardBlock("maps/rock.png",
                              [x * self.hardblockSize, y * self.hardblockSize])
                elif c == "c":
                    HardBlock("maps/sand.png",
                              [x * self.hardblockSize, y * self.hardblockSize])
                elif c == "s":
                    HardBlock("maps/grasssand.png",
                              [x * self.hardblockSize, y * self.hardblockSize])
                elif c == "r":
                    HardBlock("maps/grass.png",
                              [x * self.hardblockSize, y * self.hardblockSize])
                '''elif c =="n":
Exemplo n.º 33
0
    def add_line(self, line):
        """plain addLine method from bCNC
        used by setLinesUndo method and if no postprocessor is detected in
        GCode file
        """
        if line.startswith("(-)"):
            return

        if line.startswith("(Block-name:"):
            self._blocksExist = True
            pat = OCV.RE_BLOCK.match(line)
            if pat:
                value = pat.group(2).strip()
                if not OCV.blocks or len(OCV.blocks[-1]):
                    OCV.blocks.append(Block(value))
                else:
                    OCV.blocks[-1].b_name = value
                return

        if not OCV.blocks:
            OCV.blocks.append(Block("Header"))

        cmds = Heuristic.parse_line(line)
        if cmds is None:
            OCV.blocks[-1].append(line)
            return

        self.cnc.motionStart(cmds)

        # rapid move up = end of block
        if self._blocksExist:
            OCV.blocks[-1].append(line)
        elif self.cnc.gcode == 0 and self.cnc.dz > 0.0:
            OCV.blocks[-1].append(line)
            OCV.blocks.append(Block())
        elif self.cnc.gcode == 0 and len(OCV.blocks) == 1:
            OCV.blocks.append(Block())
            OCV.blocks[-1].append(line)
        else:
            OCV.blocks[-1].append(line)

        self.cnc.motionEnd()
Exemplo n.º 34
0
 def createBlock(self,buffer):
     self.__previousHashPointer=self.lastHashPointer
     if(len(self.__blockChain)==0):
         block=Block(None,None)
     else:
         block=Block(self.__previousHashPointer.pointer,self.__previousHashPointer.previousHash) 
     
     block.addTransactions(buffer)
     block.setBlockHash()
     self.lastHashPointer=HashPointer(block,Hash(block)) 
     #signing
     self.lastHashPointer.Sign(self.scroogeSign(str(self.lastHashPointer)))
     self.__blockChain.append(block)  
Exemplo n.º 35
0
 def add_block(self, data):
     print("Adding block to blockchain...")
     block_to_add = Block.create_next_block(self.previous_block, str(data))
     self.chain.append(block_to_add)
     f = open(self.file, "a")
     f.write(str(block_to_add) + "\n")
     f.close()
     self.previous_block = block_to_add
     print("Block added successfully to blockchain!")
     print("Block detail: ")
     print(str(block_to_add))
Exemplo n.º 36
0
    def addBlock(self, contents):
        if contents == "genesis":
            newBlock = Block(char=self.char, len=self.len, year=self.genYear)
        else:
            c = contents.split("|")

            #format year|institution|accomplishment
            yr = c[0]
            inst = c[1]
            accomp = c[2]

            prev_hash = self.mainchain[len(self.mainchain) - 1].getHash()
            newBlock = Block(prev_hash=prev_hash,
                             year=yr,
                             institution=inst,
                             accomplishment=accomp,
                             char=self.char,
                             len=self.len)

        self.mainchain.append(newBlock)
Exemplo n.º 37
0
    def bopforward_pic_fork_on_h_axis_as_pics(pic):
        """
		Splits a pic into top and bottom and returns both as Block.type_pictures.
		"""
        hh = pic.data.shape[0]
        vv = int(hh / 2)

        top = pic.data[range(vv), :]
        bot = pic.data[range(hh - vv, hh), :]

        return Block.new_pictures((top, bot))
Exemplo n.º 38
0
 def __init__(self, name, serial_number, time_limit, description, auction_type, creator, rules = None):
     self.name = name
     self.serial_number = serial_number
     self.time_limit = time_limit
     self.description = description
     self.auction_type = auction_type
     self.creator = creator
     self.blocks = [Block()]
     self.rules = rules
     self.state = "Open"
     self.chalenge = 1
Exemplo n.º 39
0
    def new_block(self):
        self.current_cords.clear()

        # block = Block.get_block(random.randint(0, 3)) TODO: Check this. Solve problem with random
        block = Block.get_block(0)

        for row_i in range(0, len(block)):
            for col_i in range(0, len(block[row_i])):
                if block[row_i][col_i] == 1:
                    self.current_cords.append([row_i + 2, col_i])
        self.screen.fill((255, 255, 255))
Exemplo n.º 40
0
def run_illegal_nonce_block_test():
    hash_difficulty_value = 15
    bc = BlockChain()

    prev_block = bc.get_target_block()
    timestamp = int(time.time())
    data = str(timestamp)
    new_counter = prev_block.get_counter() + 1

    block = Block(prev_block.get_hash_value(), timestamp, data, new_counter,
                  hash_difficulty_value)

    # set_nonce(block)
    block.set_nonce("wrong nonce value")
    success = bc.add_block(block)
    if success:
        print "Should not have been able to add illegal block !!!"
        raise Exception()

    print "== Successfully ran the run_illegal_nonce_block_test"
Exemplo n.º 41
0
def activar_SaveModo(registro):
    tabla = registro
    genesis_block = Block("0", tabla)
    if l.listaVacia() is True:
        #genesis_block = Block("0", tabla)
        l.agregarLista(str(genesis_block.transaction),
                       str(genesis_block.block_hash))
        #bloque_anterior = bloque_genesis.block_hash
        l.archivo_json()
        l.GraficarConArchivo()
        #print(l.imprimir())
    else:
        tabla1 = registro
        second_block = Block(genesis_block.block_hash, tabla1)
        l.agregarLista(str(second_block.transaction),
                       str(second_block.block_hash))
        #bloque_anterior = bloque.block_hash
    #l.imprimir()
    l.GraficarConArchivo()
    l.archivo_json()
Exemplo n.º 42
0
    def bopforward_pic_autohalves_as_pics(pic):
        """
		Splits a pic on largest axis either left and right or top and bottom.
		"""
        hh, ww = pic.data.shape

        if hh > ww:
            vv = int(hh / 2)

            top = pic.data[range(vv), :]
            bot = pic.data[range(hh - vv, hh), :]

            return Block.new_pictures((top, bot))

        vv = int(ww / 2)

        left = pic.data[:, range(vv)]
        right = pic.data[:, range(ww - vv, ww)]

        return Block.new_pictures((left, right))
Exemplo n.º 43
0
 def createMiningJob(self):
     # Let miner to get the blocktomine, only start next block when the current job/block mined
     if ((self.miningJob == None) & (len(self.pendingTransactions) != 0)):
         miningJobTransactions = self.getSingleAddressOldestTransactionOnlyIntoInProcessList(
         )  ## Very important! While copy job as preparation for txs,
         ##      only one unique to-address in each txs in block
         nextBlockindex = self.lastblock.index + 1
         prevBlockHash = self.lastblock.blockHash
         blockToMine = Block(nextBlockindex, miningJobTransactions,
                             prevBlockHash, self.Difficulty)
         self.miningJob = blockToMine
Exemplo n.º 44
0
    def bopforward_pic_fork_on_v_axis_as_pics(pic):
        """
		Splits a pic into left and right and returns both as Block.type_pictures.
		"""
        ww = pic.data.shape[1]
        vv = int(ww / 2)

        left = pic.data[:, range(vv)]
        right = pic.data[:, range(ww - vv, ww)]

        return Block.new_pictures((left, right))
Exemplo n.º 45
0
    def get_genius_block(self):
        """
        创建创始区块
        :return: 返回<Transaction>对象
        """
        txin = TxInput(None, -1, None, None)
        pubkey_hash = Script.sha160(str(self.get_genisus_pubkey()))
        txoutput = TxOutput(100, pubkey_hash)
        coinbase_tx = Transaction([txin], [txoutput], 1496518102)  # 创世区块的第一笔交易
        transactions = [coinbase_tx]

        merkletrees = MerkleTrees(transactions)
        merkleroot = merkletrees.get_root_leaf()
        nonce = 0

        genish_block_hash = calculate_hash(
            index=0,
            previous_hash=
            '00000000000000000000000000000000000000000000000000000000000000',
            timestamp=1496518102,
            merkleroot=merkleroot,
            nonce=nonce)
        # while genish_block_hash[0:self.difficulty] != '0' * self.difficulty:
        #     genish_block_hash = calculate_hash(index=0,
        #                                        previous_hash='00000000000000000000000000000000000000000000000000000000000000',
        #                                        timestamp=1496518102,
        #                                        merkleroot=merkleroot,
        #                                        nonce=nonce,
        #                                        difficulty=self.difficulty)
        #     nonce += 1
        genius_block = Block(
            index=0,
            previous_hash=
            '00000000000000000000000000000000000000000000000000000000000000',
            timestamp=1496518102,
            nonce=nonce,
            current_hash=genish_block_hash)
        genius_block.merkleroot = merkleroot
        genius_block.transactions = transactions

        return genius_block
Exemplo n.º 46
0
 def synchro_fromDatabase(self):  # 从数据库中提取完整的账本。。。
     #get from database
     #search all block
     #self.blocks.clear()
     self.clean_chain()
     r = self.dbsql.selectAll()
     for i in range(0, len(r)):
         print r[i]
         b = Block(r[i][0], r[i][1], r[i][2], r[i][3])
         #b=json.loads(r[i]
         self.add_block(b)
     return self.blockchain
Exemplo n.º 47
0
 def _create_block(self):
     """Define the method create_block(self) that creates another block (any after genesis_block)"""
     # Assign the current block to the variable prev_block
     prev_block = self.get_current_block()
     # Assign the hash of the current block to the variable prev_hash
     prev_hash = prev_block.get_hash()
     # Get the maximum index in the current list by getting the list length
     index = len(self.blocks)
     # Create a new block by calling the class "Block" and assign it to the variable next_block
     next_block = Block(prev_hash, index)
     # Append the new block to the existing list
     self.blocks.append(next_block)
Exemplo n.º 48
0
 def mine(self):
     if not self.unconfirmed_transactions:
         return False
     last_block = self.last_block
     new_block = Block(index=last_block.index + 1,
                       transactions=self.unconfirmed_transactions,
                       timestamp=time.time(),
                       previous_hash=last_block.hash)
     proof = self.proof_of_work(new_block)
     self.add_block(new_block, proof)
     self.unconfirmed_transactions = []
     return True
Exemplo n.º 49
0
 def place_block(self, pos):
     item = self.get_item_hand()
     if item is not None:
         chunk = (pos[0] // TILE_SIZE // 10) - (self.game.x // TILE_SIZE //
                                                10)
         x = (pos[0] // TILE_SIZE % 10) - (self.game.x // TILE_SIZE % 10)
         y = (pos[1] // (-TILE_SIZE) +
              (self.game.world.decalagey // TILE_SIZE)) + 1
         b = Block(self.game.world, chunk, item.name, x, y, item.image, 50,
                   item.have_hitbox)
         self.game.world.tile_list[str(x) + "_" + str(y) + "_" +
                                   str(chunk)] = b
Exemplo n.º 50
0
    def parseBlock(self, index):
        print('parsing block', index, '. . .')

        with open(self.path,
                  'rb') as block_file:  # open file in read binary mode
            block_file.seek(self.byte_index[index])
            bytes_block = block_file.read(self.block_size[index])
        block_file.closed  # close the file

        block = Block(bytes_block, index)

        return block
Exemplo n.º 51
0
    def bopforward_pic_filter_mostfreq_col(pic):
        """
		Returns an image with anything other than the most frequent color as black.
		"""
        pic = pic.data.copy()

        cc = np.unique(pic, return_counts=True)
        fc = cc[0][np.argmax(cc[1])]

        pic[pic != fc] = 0

        return Block.new_picture(np_arr=pic)
Exemplo n.º 52
0
    def decrypt_ofb(self, IV):
        IV_Block = Block(IV)

        encrypted_IV = copy.deepcopy(self.encrypt_block(IV_Block))

        #print('pre decryption')
        #for block in self.split_text:
        #    block.print_Block()

        for i in range(len(self.split_text)):
            block = copy.deepcopy(self.split_text[i] ^ encrypted_IV)
            self.split_text[i] = copy.deepcopy(block)
Exemplo n.º 53
0
def transform (blockLineal,copia):
    print("Original:    ",blockLineal)
    print("copia: ", copia)
    vec = blockLineal.split(";")
    date = vec[0]
    prevHash = vec[1]
    hashA = vec[2]
    nonce = vec[3]
    Bl = Block(date,copia,prevHash,nonce)
    print("El bloque generado es")
    print(Bl.__repr__)
    return Bl
Exemplo n.º 54
0
 def create_block(self, previous):
     while len(self.protocol.commands_queue) == 0:
         print("SLEEP")
         sleep(0.1)
     commands = self.protocol.commands_queue.pop(0)
     previous_hash = None
     height = 0
     if previous is not None:
         previous_hash = previous.get_hash()
         height = previous.height + 1
     block = Block(commands, height, self.view, previous_hash)
     return block
Exemplo n.º 55
0
def create_new_block(b_idx, l_idx, block_name):
    """Create a new block and move the line starting from l_idx on it"""
    new_block = Block(block_name)
    l_cnt = 0
    l2mov = len(OCV.blocks[b_idx]) - l_idx

    if OCV.DEBUG_HEUR > 2:
        print("New Block Event at Block {0} line {1}".format(b_idx, l_idx))

    while l_cnt < l2mov:

        if OCV.DEBUG_HEUR > 4:  # only for troubleshooting split idx > 4
            print(
                "l2mov = {0} l_cnt = {1} l_idx {2}".format(
                    l2mov, l_cnt, l_idx), OCV.blocks[b_idx][l_idx])

        line = OCV.blocks[b_idx].pop(l_idx)
        new_block.append(line)
        l_cnt += 1

    return new_block
Exemplo n.º 56
0
    def bopforward_pic_fork_color_rest_black_as_pics(pic):
        """
		Works like pic_fork_by_color_as_pics() but keeping the rest as a black background.
		"""
        pics = ()
        for color in range(1, 10):
            mask = pic.data == color

            if np.sum(mask) > 0:
                pics = pics + (pic.data.copy() * mask, )

        return Block.new_pictures(pics)
Exemplo n.º 57
0
 def seek_lastHash(self):
     #数据库操作调出最新的hash,比对其他人的
     # s= str(sql)
     if self.chain.head != None:
         #return self.chain.head.previous_hash
         return self.chain.head.hash()
     else:
         r = database.dbcon.get_last()
         hash = Block(r[0][0], r[0][1], r[0][2], r[0][3]).hash()
         #return database.dbcon.get_lasthash()
         return hash
     return
Exemplo n.º 58
0
    def __init__(self, screen, stack):
        self.state = State(self.input_handler, self.update, self.draw,
                           self.on_delete, screen, stack)
        self.cam = Camera()
        self.floor = Block(name='floor',
                           starting_position=(0, cfg.SCREEN_HEIGHT -
                                              FLOOR_HEIGHT),
                           size=(cfg.SCREEN_WIDTH, FLOOR_HEIGHT),
                           color=cfg.COLOR_BLACK,
                           camera=self.cam)

        self.obstacle = Block(
            name='obstacle',
            starting_position=(500, cfg.SCREEN_HEIGHT - FLOOR_HEIGHT -
                               OBSTACLE_HEIGHT),
            size=(40, OBSTACLE_HEIGHT),
            color=cfg.COLOR_BROWN,
            camera=self.cam)
        self.player = Player()
        self.block_list = [self.floor, self.obstacle]
        self.clock = pg.time.Clock()
Exemplo n.º 59
0
 def construct_block(self, production_no, prev_hash):
     block = Block(
         index=len(self.chain),#lenght of chain
         production_no=production_no,
         prev_hash=prev_hash,
         data=self.current_data)#contains all transactions
     #stores curent data in the list and resets the data
     self.current_data = []
     #adds the data into to the new block
     self.chain.append(block)
     #return block
     return block
Exemplo n.º 60
0
    def getBlock(self):
        '''Postcondition: Implements <block> -> <statement> <block> || <statement>'''
        statements = []
        tok = self.lex.getToken()

        while tok.newtype in (TokenType.IF_TOK, TokenType.ID_TOK,
                              TokenType.WHILE_TOK, TokenType.FOR_TOK,
                              TokenType.PRINT_TOK):
            statements.append(self.getStatement())
            tok = self.lex.getToken()

        return Block(statements)