Exemple #1
0
def parse(path, f=None):
    p = Parser(path=path)
    p.parse_file()
    j = Packer(parser=p)
    if f is None:
        return j.pack()
    else:
        j.pack(f=f)
Exemple #2
0
def parse(path, f=None):
    p = Parser(path=path)
    p.parse_file()
    j = Packer(parser=p)
    if f is None:
        return j.pack()
    else:
        j.pack(f=f)
def parse(path, f=None):
    p = Parser(path=path)
    p.parse_file()
    a = Analyzer(parser=p)
    a.analyze()
    j = Packer(analyzer=a)
    if f is None:
        return j.pack()
    else:
        j.pack(f=f)
Exemple #4
0
def processFile(path, f=None):
    p = Parser(path=path)
    p.parseFile()
    a = Analyzer(parser=p)
    a.analyze()
    j = Packer(analyzer=a)
    if f is None:
        return j.pack()
    else:
        j.pack(f=f)
	def __call__(self, ar):
		p = Packer(ar)
		
		for feature, size in self.features:
			p.addRoom(size)
			
		p.pack()
		
		for room, (feature, size) in zip(p.rooms, self.features):
			r = area.Area(room.left, room.top, room.right, room.bottom)
			for cell in feature(r):
				yield cell
Exemple #6
0
def processFile(path):
    try:
        p = Parser(path=path)
        p.parseFile()
        a = Analyzer(parser=p)
        a.analyze()
        j = Packer(analyzer=a)
        return j.pack()
    except:
        print path
        exit(1)
def processFile(path):
    try:
        p = Parser(path=path)
        p.parseFile()
        a = Analyzer(parser=p)
        a.analyze()
        j = Packer(analyzer=a)
        return j.pack()
    except:
        print path
        exit(1)
Exemple #8
0
	def _pack_test(self):
		if len(self.textures) == 0:
			return

		from packer import PackingRectangle, Packer

		# prepare rects
		rects = []
		rects2 = {}
		for texture in self.textures:
			r = PackingRectangle()
			r.size = texture.get("img").size
			rects.append(r)
			rects2[r] = (texture.get("name"), texture.get("img"))

		# pack
		packer = Packer(rects)
		res, area = packer.pack()
		uvs = {}
		w = 0
		h = 0
		for e in res:
			w = max(w, e.right)
			h = max(h, e.bottom)
		for e in res:
			rect = e.rect
			uvs[rects2.get(e)[0]] = (rect[0] / float(w), rect[1] / float(h), rect[2] / float(w), rect[3] / float(h)) # u1, v1, u2, v2
		print("packed into", w, h)

		# generate new image
		img = Image.new('RGBA', (w, h))
		for e in res:
			img.paste(rects2.get(e)[1], e.position)
		self.textures = [{"path": "atlas.png", "name": "texture_atlas", "index": 0, "img": img}]

		for spr in self.sprites:
			uv = uvs.get(spr["texture_name"])
			spr["uv"] = {"u1": float(uv[0]), "v1": float(uv[1]), "u2": float(uv[2]), "v2": float(uv[3])}
			spr["texture_name"] = "texture_atlas"
Exemple #9
0
 def pack(self):
     with self.__progresses_lock__:
         return Packer.pack(self)
Exemple #10
0
class DropboxBackup(BaseBackup):
    __slots__ = ['_logger', '_packer', '_client']

    def __init__(self, client, filenames, key):
        super().__init__(filenames)
        self._logger = logging.getLogger('DropboxBackup')
        self._packer = Packer(key)
        self._client = client

        for f in self._filenames:
            if not os.path.exists(f):
                self.restore(f)

    def __call__(self):
        for f in self._filenames:
            self.backup(f)

    @staticmethod
    def create(token, filenames):
        client = dropbox.Dropbox(token)
        try:
            # Check that the access token is valid
            client.users_get_current_account()
        except AuthError:
            return None

        return DropboxBackup(client, filenames, token)

    def backup(self, filename):
        encrypted_filename = filename + '.enc'
        self._packer.pack(filename, encrypted_filename)

        result = True
        with open(encrypted_filename, 'rb') as f:
            # We use WriteMode=overwrite to make sure that the settings in the file
            # are changed on upload
            self._logger.debug(f'Uploading {encrypted_filename} to Dropbox...')
            try:
                self._client.files_upload(f.read(),
                                          filename,
                                          mode=WriteMode('overwrite'))
            except ApiError as err:
                # This checks for the specific error where a user doesn't have
                # enough Dropbox space quota to upload this file
                if (err.error.is_path() and
                        err.error.get_path().reason.is_insufficient_space()):
                    self._logger.error(
                        'ERROR: Cannot back up; insufficient space.')
                elif err.user_message_text:
                    self._logger.error(err.user_message_text)
                else:
                    self._logger.error(err)
                result = False

        return result

    def restore(self, filename, rev=None):
        encrypted_filename = filename + '.enc'

        # Restore the file on Dropbox to a certain revision
        self._logger.debug(f'Restoring {encrypted_filename} to revision {rev}')
        self._client.files_restore(encrypted_filename, rev)

        # Download the specific revision of the file at BACKUPPATH to LOCALFILE
        self._logger.debug(f'Downloading {encrypted_filename}')
        # self._client.files_download_to_file(LOCALFILE, BACKUPPATH, rev)
        self._client.files_download_to_file(encrypted_filename,
                                            encrypted_filename, rev)

        self._packer.unpack(encrypted_filename, filename)
        return True
Exemple #11
0
def main():
    args = parse_args()
    packer = Packer(512, 512, padding=args.padding)
    load(packer, args.directory)
    packer.pack()
    save(packer, 'test.png')
Exemple #12
0
def main():
    # Inicializa enlace ... variavel com possui todos os metodos e propriedades do enlace, que funciona em threading
    com = Enlace(serialName)
    # Ativa comunicacao
    com.enable()
    com.rx.clearBuffer()

    packer = Packer()
    unpacker = Unpacker()

    # Log

    run = True
    call = True
    response = False
    serverReady_message_get = False
    count = 1

    while (run):

        if not response:

            if call:
                selected = select_file()

                print("-------------------------")
                print("Gerando dados para transmissao :")
                print("-------------------------")

                data = open(selected, "rb").read()
                delivery, total = packer.pack(data,
                                              get_kind(selected),
                                              Protocol.type_package_delivery,
                                              get_total=True)

                print("-------------------------")
                print("Chamando o server para tranferência de dados")
                print("-------------------------")
                message_timeot = time.time()
                call = False

            else:
                if (time.time() - message_timeot) < Protocol.great_timeout:
                    message = packer.pack_message(Protocol.type_client_call,
                                                  total, total,
                                                  Protocol.sever_number)
                    com.sendData(message)
                    while (com.tx.getIsBussy()):
                        pass

                    dataRx = com.getData(Protocol.max_size, time.time())
                    data, code, atual = unpacker.unpack(dataRx)

                    if code == Protocol.type_server_ready:
                        serverReady_message_get = True
                        response = True

                        print("-------------------------")
                        print("Server pronto, começando o envio")
                        print("-------------------------")

                        start = time.time()
                        time_out_time = time.time()
                        count = 1

                else:
                    response = True

        elif not call and serverReady_message_get:

            if count <= total and (time.time() -
                                   time_out_time) < Protocol.great_timeout:

                print("-------------------------")
                print("Envindo pacote {} de {}".format(count, total))
                print("-------------------------")
                com.sendData(delivery[count - 1])
                while (com.tx.getIsBussy()):
                    pass

                dataRx = com.getData(Protocol.max_size, time.time())
                data, code, atual = unpacker.unpack(dataRx)

                if code == Protocol.type_package_ok and atual == count:
                    print("-------------------------")
                    print("Pacote {} de {} enviado com sucesso".format(
                        count, total))
                    print("-------------------------")
                    count += 1
                    time_out_time = time.time()

                else:
                    print("-------------------------")
                    print("Erro")
                    print("-------------------------")

                    if 1 <= atual <= total:
                        count = atual

            elif count > total:
                end = time.time() - start

                print("-------------------------")
                print("Pacotes enviados com sucesso")
                print("Taxa de recepção: {:02}".format(
                    total * Protocol.max_size / end))
                print("-------------------------")

                print("-------------------------")
                go_on = input(
                    "Se desejar um novo envio digite sim, caso contrário outro caractere: "
                )
                print("-------------------------")

                call = True
                serverReady_message_get = False
                response = False
                count = 1

                if go_on != "sim":
                    print("-------------------------")
                    print("Até mais!")
                    print("-------------------------")
                    run = False

            else:
                print("-------------------------")
                print("O server não respondeu e um timeout ocorreu")
                print("-------------------------")

                print("-------------------------")
                go_on = input(
                    "Se desejar um novo envio digite sim, caso contrário outro caractere: "
                )
                print("-------------------------")

                call = True
                serverReady_message_get = False
                response = False
                count = 1

                if go_on != "sim":
                    print("-------------------------")
                    print("Até mais!")
                    print("-------------------------")
                    run = False

        else:
            print("-------------------------")
            print("O server não respondeu e um timeout ocorreu")
            print("-------------------------")

            print("-------------------------")
            go_on = input(
                "Se desejar um novo envio digite sim, caso contrário outro caractere: "
            )
            print("-------------------------")

            call = True
            serverReady_message_get = False
            response = False
            count = 1

            if go_on != "sim":
                print("-------------------------")
                print("Até mais!")
                print("-------------------------")
                run = False