• Facebook
  • Twitter
  • Reddit
  • StumbleUpon
  • Digg
  • email

All Samples(15306)  |  Call(14688)  |  Derive(0)  |  Import(618)
Unpack the string containing packed C structure data, according to fmt.
Requires len(string) == calcsize(fmt).

src/c/r/crapvine-HEAD/exchange_samples/read_bin_test.py   crapvine(Download)
from __future__ import with_statement
from struct import unpack, calcsize
 
def read_string(file):
	strlen = unpack('<h', file.read(2))[0]
	return unpack("%ds" % strlen, file.read(strlen))[0]
 
	print("%s" % (f.read(4)))
	f.read(18)
	s_number_of_creatures = f.read(2)
	number_of_creatures = unpack("<h", s_number_of_creatures)[0]
	print('number of creatures %d' % number_of_creatures)
	s_creature_type = f.read(2)
	creature_type = unpack("<h", s_creature_type)[0]

src/p/y/pycarrara-HEAD/V0.6-alpha/Samples/midi.py   pycarrara(Download)
import copy
import time
from cStringIO import StringIO
from struct import unpack, pack
from math import sqrt
 
##
        # next two bytes specify the number of tracks
        # next two bytes specify the resolution/PPQ/Parts Per Quarter
        # (in other words, how many ticks per quater note)
        data = unpack(">LHHH", self.instream.read(10))
        hdrsz = data[0]
        self.midistream.format = data[1]
        self.midistream.trackcount = data[2]
    def parse_track_header(self):
        # First four bytes are Track header
        magic = self.instream.read(4)
        if magic != 'MTrk':
            raise TypeError, "Bad track header in MIDI file: " + magic
        # next four bytes are header size
        trksz = unpack(">L", self.instream.read(4))[0]

src/p/y/pycarrara-HEAD/V0.5-alpha/Samples/midi.py   pycarrara(Download)
import copy
import time
from cStringIO import StringIO
from struct import unpack, pack
from math import sqrt
 
##
        # next two bytes specify the number of tracks
        # next two bytes specify the resolution/PPQ/Parts Per Quarter
        # (in other words, how many ticks per quater note)
        data = unpack(">LHHH", self.instream.read(10))
        hdrsz = data[0]
        self.midistream.format = data[1]
        self.midistream.trackcount = data[2]
    def parse_track_header(self):
        # First four bytes are Track header
        magic = self.instream.read(4)
        if magic != 'MTrk':
            raise TypeError, "Bad track header in MIDI file: " + magic
        # next four bytes are header size
        trksz = unpack(">L", self.instream.read(4))[0]

src/p/y/pycarrara-HEAD/trunk/Samples/midi.py   pycarrara(Download)
import copy
import time
from cStringIO import StringIO
from struct import unpack, pack
from math import sqrt
 
##
        # next two bytes specify the number of tracks
        # next two bytes specify the resolution/PPQ/Parts Per Quarter
        # (in other words, how many ticks per quater note)
        data = unpack(">LHHH", self.instream.read(10))
        hdrsz = data[0]
        self.midistream.format = data[1]
        self.midistream.trackcount = data[2]
    def parse_track_header(self):
        # First four bytes are Track header
        magic = self.instream.read(4)
        if magic != 'MTrk':
            raise TypeError, "Bad track header in MIDI file: " + magic
        # next four bytes are header size
        trksz = unpack(">L", self.instream.read(4))[0]

src/p/y/pycarrara-HEAD/Samples/midi.py   pycarrara(Download)
import copy
import time
from cStringIO import StringIO
from struct import unpack, pack
from math import sqrt
 
##
        # next two bytes specify the number of tracks
        # next two bytes specify the resolution/PPQ/Parts Per Quarter
        # (in other words, how many ticks per quater note)
        data = unpack(">LHHH", self.instream.read(10))
        hdrsz = data[0]
        self.midistream.format = data[1]
        self.midistream.trackcount = data[2]
    def parse_track_header(self):
        # First four bytes are Track header
        magic = self.instream.read(4)
        if magic != 'MTrk':
            raise TypeError, "Bad track header in MIDI file: " + magic
        # next four bytes are header size
        trksz = unpack(">L", self.instream.read(4))[0]

src/q/d/qdisper-HEAD/switcher/edid.py   qdisper(Download)
 
### FIXME recheck endianness for these structs
 
from struct import pack, unpack
 
### EDID Header Magic
EDID_HEADER = "\0\xFF\xFF\xFF\xFF\xFF\xFF\0" 
		### Check the checksum 
		sum = 0
		for i in range(128):
			sum = (sum + int(unpack('B', edid[i])[0])) & 0xFF
		if sum != 0:
#			print "Checksum failed, result should be 0, instead it's:", sum
			self.valid = 0
			edid = "\0" * 128
 
		self.edid = edid
 
	### ID String
	def get_id_string(self):
		name = unpack('>H',self.edid[8:10])[0]
	def get_serial_number(self):
		return unpack('>I', self.edid[12:16])[0]
 
	### Tupple of week, year from EDID
	def get_date(self):
		date = unpack('BB', self.edid[16:18])
		return [date[0], date[1] + 1990]
 
	### EDID version, revision
	def get_edid_ver(self):
		return unpack('BB', self.edid[18:20])
	def get_video_input_def(self):
		vid_in = {}
		v = unpack('B', self.edid[20])[0]
		vid_in['digital'] = (v >> 7) & 1
		if vid_in['digital']:
			vid_in['DFP1x'] = (v & 1)	
		else:
	def get_size(self):
		return unpack('BB', self.edid[21:23])
 
	### Gamma
	def get_gamma(self):
		return (unpack('B', self.edid[23])[0] / 100.0) + 1.0
 
	### Feature Support
	def get_feature_support(self):
		fs = {}
		f = unpack('B', self.edid[24])[0]
	def get_color_characteristics(self):
		cc = {}
		c = unpack('10B', self.edid[25:35])
		### Check the / 1024 value... (is this right?)
		cc['red_x'] = ((c[2] << 2) + ((c[0] >> 6) & 3)) / 1024.0
		cc['red_y'] = ((c[3] << 2) + ((c[0] >> 4) & 3)) / 1024.0
		cc['green_x'] = ((c[4] << 2) + ((c[0] >> 2) & 3)) / 1024.0
		my_timing = []
 
		### Established timings
		est = unpack('BB', self.edid[35:37])
		### This is what the field is set to if not used	
		if est[0] == "\x01":
			est[0] = 0
					my_timing.append(timing[i])
 
		### Add the "standard" timings into the timing array
		std = unpack('>8H', self.edid[38:54])
		man = unpack('B', self.edid[37])[0]
 
		for i in range(8):
	def get_range_dt(self, tag):
		sync = {}
		### If possible, we get the range limit from the range limit tag
		sync['v_min'] = unpack('B',tag[5])[0]
		sync['v_max'] = unpack('B',tag[6])[0]
		sync['h_min'] = unpack('B',tag[7])[0]
		sync['h_max'] = unpack('B',tag[8])[0]
		return sync
 
	### Detailed Timing (from monitor details)
	def get_timing_dt(self, info):
		### Search for detailed timing info
		timing = {}
		timing['pixel_clock'] = unpack(">H",info[:2])[0]
	def get_timing_dt(self, info):
		### Search for detailed timing info
		timing = {}
		timing['pixel_clock'] = unpack(">H",info[:2])[0]
 
		timing['horizontal_active'] = unpack("B",info[2])[0] + ((unpack("B",info[4])[0] >> 4) << 8)
		timing['horizontal_blanking'] = unpack("B",info[3])[0] + ((unpack("B",info[4])[0] & 0xF) << 8)
 
		timing['vertical_active'] = unpack("B",info[5])[0] + (((unpack("B",info[7])[0] >> 4) & 0xF) << 8)
		timing['vertical_blanking'] = unpack("B",info[6])[0] + ((unpack("B",info[7])[0] & 0xF) << 8)
 
		timing['hsync_offset'] = unpack("B",info[8])[0] + (((unpack("B", info[11])[0] >> 6) & 3) << 8)
		timing['hsync_pulse_width'] = unpack("B",info[9])[0] + (((unpack("B", info[11])[0] >> 4) & 3) << 8)
		timing['vsync_offset'] = (unpack("B",info[10])[0] >> 4) + (((unpack("B", info[11])[0] >> 2) & 3) << 8)
		timing['hsync_offset'] = unpack("B",info[8])[0] + (((unpack("B", info[11])[0] >> 6) & 3) << 8)
		timing['hsync_pulse_width'] = unpack("B",info[9])[0] + (((unpack("B", info[11])[0] >> 4) & 3) << 8)
		timing['vsync_offset'] = (unpack("B",info[10])[0] >> 4) + (((unpack("B", info[11])[0] >> 2) & 3) << 8)
		timing['vsync_pulse_width'] = (unpack("B",info[10])[0] & 0xF) + ((unpack("B", info[11])[0] & 3) << 8)
 
		timing['himage_size'] = unpack("B",info[12])[0] + ((unpack("B",info[14])[0] >> 4) << 8)
		timing['vimage_size'] = unpack("B",info[13])[0] + ((unpack("B",info[14])[0] & 0xF) << 8)
 
		timing['hborder'] = unpack("B",info[15])[0]
		timing['vborder'] = unpack("B",info[16])[0]
 
		timing['interlaced'] = (unpack("B", info[17])[0] >> 7) & 1
		timing['stereo'] = (unpack("B", info[17])[0] >> 5) & 3
		timing['digital_composite'] = (unpack("B", info[17])[0] >> 3) & 3
		timing['interlaced'] = (unpack("B", info[17])[0] >> 7) & 1
		timing['stereo'] = (unpack("B", info[17])[0] >> 5) & 3
		timing['digital_composite'] = (unpack("B", info[17])[0] >> 3) & 3
		timing['variant'] = (unpack("B", info[17])[0] >> 1) & 3
		return timing
 
	### Parse Monitor Details
						i = i - 1
						break
				size = str(i + 1) + "s"
				details.append(["Serial", unpack(size, tag[5:i + 6])[0]])
			elif tag[:5] == ASCII_DT:
				for i in range(13):
					if tag[i + 5] == "\x0A" or tag[i + 5] == "\x00":
						i = i - 1
						break
				size = str(i + 1) + "s"
				details.append(["ASCII", unpack(size, tag[5:i + 6])[0]])
						i = i - 1
						break
				size = str(i + 1) + "s"
				details.append(["Name", unpack(size, tag[5:i + 6])[0]])
			elif tag[:3] == "\0\0\0" and (0 < unpack('B', tag[3])[0] < 16):
				details.append(["Manufacturer", str(unpack("13B", tag[5:18]))])
			elif tag[:2] != "\0\0":
	def has_extension(self):
		return unpack("B", self.edid[126])[0]
 

src/p/i/pilgrim-HEAD/pilgrim/codecs/blp.py   pilgrim(Download)
"""
 
from PIL import Image, ImageFile
from struct import pack, unpack, error as StructError
from cStringIO import StringIO
 
from . import JPEG
	string = StringIO(data)
	while True:
		try:
			palette.append(unpack("<4B", string.read(4)))
		except StructError:
			break
	return palette
	def __decode_blp1(self):
		header = StringIO(self.fp.read(28 + 16*4 + 16*4))
 
		magic, compression = unpack("<4si", header.read(8))
		encoding, alphaDepth, alphaEncoding, hasMips = unpack("<4b", header.read(4))
		self.size = unpack("<II", header.read(8))
		encoding, subtype = unpack("<ii", header.read(8))
		offsets = unpack("<16I", header.read(16*4))
		lengths = unpack("<16I", header.read(16*4))
 
		if compression == 0:
			jpegHeaderSize, = unpack("<I", self.fp.read(4))
				self.tile = []
				while True:
					try:
						offset, = unpack("<B", _data.read(1))
						a, = unpack("<B", alpha_data.read(1))
					except StructError:
						break
				self.tile = []
				while True:
					try:
						offset, = unpack("<B", _data.read(1))
					except StructError:
						break
					b, g, r, a = palette[offset]
	def __decode_blp2(self):
		header = StringIO(self.fp.read(20 + 16*4 + 16*4))
 
		magic, compression = unpack("<4si", header.read(8))
		encoding, alphaDepth, alphaEncoding, hasMips = unpack("<4b", header.read(4))
		self.size = unpack("<II", header.read(8))
		offsets = unpack("<16I", header.read(16*4))
		lengths = unpack("<16I", header.read(16*4))
				_data = StringIO(self.fp.read(lengths[0]))
				while True:
					try:
						offset, = unpack("<B", _data.read(1))
					except StructError:
						break
					b, g, r, a = palette[offset]

src/p/y/pyexcelerator-HEAD/trunk/pyExcelerator/ImportXLS.py   pyexcelerator(Download)
import UnicodeUtils
import CompoundDoc
import ExcelMagic
from struct import pack, unpack
 
 
def parse_xls(filename, encoding = None):
 
    ##########################################################################
 
    def process_BOUNDSHEET(biff8, rec_data):
        sheet_stream_pos, visibility, sheet_type = unpack('<I2B', rec_data[:6])
    def process_BOUNDSHEET(biff8, rec_data):
        sheet_stream_pos, visibility, sheet_type = unpack('<I2B', rec_data[:6])
        sheet_name = rec_data[6:]
 
        if biff8:
            chars_num, options = unpack('2B', sheet_name[:2])
 
            has_format_runs = (options & 0x08) != 0
 
            if has_format_runs:
                runs_num , = unpack('<H', sheet_name[chars_start:chars_start+2])
                chars_start += 2
            if has_asian_phonetic:
                asian_phonetic_size , = unpack('<I', sheet_name[chars_start:chars_start+4])
    def unpack2str(biff8, label_name): # 2 bytes length str
        if biff8:
            chars_num, options = unpack('<HB', label_name[:3])
 
            chars_start = 3
            runs_num = 0
            asian_phonetic_size = 0
            has_format_runs = (options & 0x08) != 0
 
            if has_format_runs:
                runs_num , = unpack('<H', label_name[chars_start:chars_start+2])
                chars_start += 2
            if has_asian_phonetic:
                asian_phonetic_size , = unpack('<I', label_name[chars_start:chars_start+4])
    def process_LABEL(biff8, rec_data):
        row_idx, col_idx, xf_idx = unpack('<3H', rec_data[:6])
        label_name = rec_data[6:]
        result = unpack2str(biff8, label_name)
        return (row_idx, col_idx, result)
 
 
    def process_LABELSST(rec_data):
        row_idx, col_idx, xf_idx, sst_idx = unpack('<3HI', rec_data)
    def process_RSTRING(biff8, rec_data):
        if biff8:
            return process_LABEL(biff8, rec_data)
        else:
            row_idx, col_idx, xf_idx, length = unpack('<4H', rec_data[:8])
            result = rec_data[8:8+length].decode(encoding, 'replace')
 
        return (row_idx, col_idx, result)
 
 
    def decode_rk(encoded):
        b0, b1, b2, b3 = unpack('4B', encoded)
    def decode_rk(encoded):
        b0, b1, b2, b3 = unpack('4B', encoded)
        is_multed_100 = (b0 & 0x01) != 0
        is_integer = (b0 & 0x02) != 0
 
        if is_integer:
            result , = unpack('<i', encoded)
            result >>= 2
        else:
            ieee754 = struct.pack('8B', 0, 0, 0, 0, b0 & 0xFC, b1, b2, b3)
            result , = unpack('<d', ieee754)
    def process_RK(rec_data):
        row_idx, col_idx, xf_idx, encoded = unpack('<3H4s', rec_data)
        result = decode_rk(encoded)
        return (row_idx, col_idx, result)
 
 
    def process_MULRK(rec_data):
        row_idx, first_col_idx = unpack('<2H', rec_data[:4])
        last_col_idx , = unpack('<H', rec_data[-2:])
        xf_rk_num = last_col_idx - first_col_idx + 1
 
        results = []
        for i in range(xf_rk_num):
            xf_idx, encoded = unpack('<H4s', rec_data[4+6*i : 4+6*(i+1)])
    def process_NUMBER(rec_data):
        row_idx, col_idx, xf_idx, result = unpack('<3Hd', rec_data)
        return (row_idx, col_idx, result)
 
 
    def process_SST(rec_data, sst_continues):
        # 0x00FC
        total_refs, total_str = unpack('<2I', rec_data[:8])
                curr_block = sst_continues[curr_block_num]
                pos = 0
 
            chars_num, options = unpack('<HB', curr_block[pos:pos+3])
            #print chars_num, options
            pos += 3
 
            asian_phonetic_size = 0
            runs_num = 0
            has_asian_phonetic = (options & 0x04) != 0
            has_format_runs = (options & 0x08) != 0
            if has_format_runs:
                runs_num , = unpack('<H', curr_block[pos:pos+2])
                runs_num , = unpack('<H', curr_block[pos:pos+2])
                pos += 2
            if has_asian_phonetic:
                asian_phonetic_size , = unpack('<I', curr_block[pos:pos+4])
                pos += 4
 
            curr_char = 0
    # In addition, if record size grows to some limit
    # Excel writes CONTINUE records
    while stream_pos < workbook_stream_len and EOFs <= ws_num:
        rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
        stream_pos += 4
 
        rec_data = workbook_stream[stream_pos:stream_pos+data_size]
        stream_pos += data_size
 
        if rec_id == 0x0809: # BOF
            #print 'BOF', 
            BOFs += 1
            ver, substream_type = unpack('<2H', rec_data[:4])
                pass
            else: # skip chart stream or unknown stream
            # stream offsets may be used from BOUNDSHEET record
                rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                while rec_id != 0x000A: # EOF
                    #print 'SST CONTINUE'
                    stream_pos += 4
                    stream_pos += data_size
                    rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                values = {}
            EOFs += 1
        elif rec_id == 0x0042: # CODEPAGE
            cp ,  = unpack('<H', rec_data)
            #print 'CODEPAGE', hex(cp)
            if not encoding:
                encoding = encodings[cp]
            #print 'SST'
            sst_data = rec_data
            sst_continues = []
            rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
            while rec_id == 0x003C: # CONTINUE
                #print 'SST CONTINUE'
                stream_pos += 4
                rec_data = workbook_stream[stream_pos:stream_pos+data_size]
                sst_continues.extend([rec_data])
                stream_pos += data_size
                rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
            #print r, c, b
        elif rec_id == 0x0006: # FORMULA
            #print 'FORMULA',
            r, c, x = unpack('<3H', rec_data[0:6])
            if rec_data[12] == '\xFF' and rec_data[13] == '\xFF':
                if rec_data[6] == '\x00':
                    got_str = False
                    if ord(rec_data[14]) & 8:
                        # part of shared formula
                        rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                        elif rec_id not in (0x0221, 0x04BC, 0x0236, 0x0037, 0x0036):
                            raise Exception("Expected ARRAY, SHRFMLA, TABLEOP* or STRING record")
                    if not got_str:
                        rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                        stream_pos += 4                      
                        rec_data = workbook_stream[stream_pos:stream_pos+data_size]
                        stream_pos += data_size
                    raise Exception("Unknown value for formula result")
            else:
                # 64-bit float
                d, = unpack("<d", rec_data[6:14])
                values[(r, c)] = d
 
    encoding = None

src/p/y/pyexcelerator-HEAD/pyExcelerator/ImportXLS.py   pyexcelerator(Download)
import UnicodeUtils
import CompoundDoc
import ExcelMagic
from struct import pack, unpack
 
 
def parse_xls(filename, encoding = None):
 
    ##########################################################################
 
    def process_BOUNDSHEET(biff8, rec_data):
        sheet_stream_pos, visibility, sheet_type = unpack('<I2B', rec_data[:6])
    def process_BOUNDSHEET(biff8, rec_data):
        sheet_stream_pos, visibility, sheet_type = unpack('<I2B', rec_data[:6])
        sheet_name = rec_data[6:]
 
        if biff8:
            chars_num, options = unpack('2B', sheet_name[:2])
 
            has_format_runs = (options & 0x08) != 0
 
            if has_format_runs:
                runs_num , = unpack('<H', sheet_name[chars_start:chars_start+2])
                chars_start += 2
            if has_asian_phonetic:
                asian_phonetic_size , = unpack('<I', sheet_name[chars_start:chars_start+4])
    def unpack2str(biff8, label_name): # 2 bytes length str
        if biff8:
            chars_num, options = unpack('<HB', label_name[:3])
 
            chars_start = 3
            runs_num = 0
            asian_phonetic_size = 0
            has_format_runs = (options & 0x08) != 0
 
            if has_format_runs:
                runs_num , = unpack('<H', label_name[chars_start:chars_start+2])
                chars_start += 2
            if has_asian_phonetic:
                asian_phonetic_size , = unpack('<I', label_name[chars_start:chars_start+4])
    def process_LABEL(biff8, rec_data):
        row_idx, col_idx, xf_idx = unpack('<3H', rec_data[:6])
        label_name = rec_data[6:]
        result = unpack2str(biff8, label_name)
        return (row_idx, col_idx, result)
 
 
    def process_LABELSST(rec_data):
        row_idx, col_idx, xf_idx, sst_idx = unpack('<3HI', rec_data)
    def process_RSTRING(biff8, rec_data):
        if biff8:
            return process_LABEL(biff8, rec_data)
        else:
            row_idx, col_idx, xf_idx, length = unpack('<4H', rec_data[:8])
            result = rec_data[8:8+length].decode(encoding, 'replace')
 
        return (row_idx, col_idx, result)
 
 
    def decode_rk(encoded):
        b0, b1, b2, b3 = unpack('4B', encoded)
    def decode_rk(encoded):
        b0, b1, b2, b3 = unpack('4B', encoded)
        is_multed_100 = (b0 & 0x01) != 0
        is_integer = (b0 & 0x02) != 0
 
        if is_integer:
            result , = unpack('<i', encoded)
            result >>= 2
        else:
            ieee754 = struct.pack('8B', 0, 0, 0, 0, b0 & 0xFC, b1, b2, b3)
            result , = unpack('<d', ieee754)
    def process_RK(rec_data):
        row_idx, col_idx, xf_idx, encoded = unpack('<3H4s', rec_data)
        result = decode_rk(encoded)
        return (row_idx, col_idx, result)
 
 
    def process_MULRK(rec_data):
        row_idx, first_col_idx = unpack('<2H', rec_data[:4])
        last_col_idx , = unpack('<H', rec_data[-2:])
        xf_rk_num = last_col_idx - first_col_idx + 1
 
        results = []
        for i in range(xf_rk_num):
            xf_idx, encoded = unpack('<H4s', rec_data[4+6*i : 4+6*(i+1)])
    def process_NUMBER(rec_data):
        row_idx, col_idx, xf_idx, result = unpack('<3Hd', rec_data)
        return (row_idx, col_idx, result)
 
 
    def process_SST(rec_data, sst_continues):
        # 0x00FC
        total_refs, total_str = unpack('<2I', rec_data[:8])
                curr_block = sst_continues[curr_block_num]
                pos = 0
 
            chars_num, options = unpack('<HB', curr_block[pos:pos+3])
            #print chars_num, options
            pos += 3
 
            asian_phonetic_size = 0
            runs_num = 0
            has_asian_phonetic = (options & 0x04) != 0
            has_format_runs = (options & 0x08) != 0
            if has_format_runs:
                runs_num , = unpack('<H', curr_block[pos:pos+2])
                runs_num , = unpack('<H', curr_block[pos:pos+2])
                pos += 2
            if has_asian_phonetic:
                asian_phonetic_size , = unpack('<I', curr_block[pos:pos+4])
                pos += 4
 
            curr_char = 0
    # In addition, if record size grows to some limit
    # Excel writes CONTINUE records
    while stream_pos < workbook_stream_len and EOFs <= ws_num:
        rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
        stream_pos += 4
 
        rec_data = workbook_stream[stream_pos:stream_pos+data_size]
        stream_pos += data_size
 
        if rec_id == 0x0809: # BOF
            #print 'BOF', 
            BOFs += 1
            ver, substream_type = unpack('<2H', rec_data[:4])
                pass
            else: # skip chart stream or unknown stream
            # stream offsets may be used from BOUNDSHEET record
                rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                while rec_id != 0x000A: # EOF
                    #print 'SST CONTINUE'
                    stream_pos += 4
                    stream_pos += data_size
                    rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                values = {}
            EOFs += 1
        elif rec_id == 0x0042: # CODEPAGE
            cp ,  = unpack('<H', rec_data)
            #print 'CODEPAGE', hex(cp)
            if not encoding:
                encoding = encodings[cp]
            #print 'SST'
            sst_data = rec_data
            sst_continues = []
            rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
            while rec_id == 0x003C: # CONTINUE
                #print 'SST CONTINUE'
                stream_pos += 4
                rec_data = workbook_stream[stream_pos:stream_pos+data_size]
                sst_continues.extend([rec_data])
                stream_pos += data_size
                rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
            #print r, c, b
        elif rec_id == 0x0006: # FORMULA
            #print 'FORMULA',
            r, c, x = unpack('<3H', rec_data[0:6])
            if rec_data[12] == '\xFF' and rec_data[13] == '\xFF':
                if rec_data[6] == '\x00':
                    got_str = False
                    if ord(rec_data[14]) & 8:
                        # part of shared formula
                        rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                        elif rec_id not in (0x0221, 0x04BC, 0x0236, 0x0037, 0x0036):
                            raise Exception("Expected ARRAY, SHRFMLA, TABLEOP* or STRING record")
                    if not got_str:
                        rec_id, data_size = unpack('<2H', workbook_stream[stream_pos:stream_pos+4])
                        stream_pos += 4                      
                        rec_data = workbook_stream[stream_pos:stream_pos+data_size]
                        stream_pos += data_size
                    raise Exception("Unknown value for formula result")
            else:
                # 64-bit float
                d, = unpack("<d", rec_data[6:14])
                values[(r, c)] = d
 
    encoding = None

src/p/y/pypes-HEAD/ui/trunk/pypesvds/lib/extras/pdflib/pdffont.py   pypes(Download)
#!/usr/bin/env python
import sys
stderr = sys.stderr
from struct import pack, unpack
try:
  from cStringIO import StringIO
except ImportError:
    code = self.ucs2_cmap.tocode(cid)
    if not code:
      raise PDFUnicodeNotDefined(None, cid)
    chars = unpack('>%dH' % (len(code)/2), code)
    return ''.join( unichr(c) for c in chars )
 
 
  def __init__(self, name, fp):
    self.name = name
    self.fp = fp
    self.tables = {}
    fonttype = fp.read(4)
    (ntables, _1, _2, _3) = unpack('>HHHH', fp.read(8))
    for i in xrange(ntables):
      (name, tsum, offset, length) = unpack('>4sLLL', fp.read(16))
  def create_cmap(self):
    if 'cmap' not in self.tables:
      raise TrueTypeFont.CMapNotFound
    (base_offset, length) = self.tables['cmap']
    fp = self.fp
    fp.seek(base_offset)
    (version, nsubtables) = unpack('>HH', fp.read(4))
    subtables = []
    for i in xrange(nsubtables):
      subtables.append(unpack('>HHL', fp.read(8)))
    # Only supports subtable type 0, 2 and 4.
    for (_1, _2, st_offset) in subtables:
      fp.seek(base_offset+st_offset)
      (fmttype, fmtlen, fmtlang) = unpack('>HHH', fp.read(6))
      if fmttype == 0:
        char2gid.update(enumerate(unpack('>256B', fp.read(256))))
      elif fmttype == 2:
        subheaderkeys = unpack('>256H', fp.read(512))
        nhdrs = max(subheaderkeys)/8 + 1
        hdrs = []
        for i in xrange(nhdrs):
          (firstcode,entcount,delta,offset) = unpack('>HHhH', fp.read(8))
          hdrs.append((i,firstcode,entcount,delta,fp.tell()-2+offset))
        for (i,firstcode,entcount,delta,pos) in hdrs:
          if not entcount: continue
          first = firstcode + (firstbytes[i] << 8)
          fp.seek(pos)
          for c in xrange(entcount):
            gid = unpack('>H', fp.read(2))
              gid += delta
            char2gid[first+c] = gid
      elif fmttype == 4:
        (segcount, _1, _2, _3) = unpack('>HHHH', fp.read(8))
        segcount /= 2
        ecs = unpack('>%dH' % segcount, fp.read(2*segcount))
        fp.read(2)
        scs = unpack('>%dH' % segcount, fp.read(2*segcount))
        idds = unpack('>%dh' % segcount, fp.read(2*segcount))
        pos = fp.tell()
        idrs = unpack('>%dH' % segcount, fp.read(2*segcount))
          if idr:
            fp.seek(pos+idr)
            for c in xrange(sc, ec+1):
              char2gid[c] = (unpack('>H', fp.read(2))[0] + idd) & 0xffff
          else:
            for c in xrange(sc, ec+1):
              char2gid[c] = (c + idd) & 0xffff
  def to_unicode(self, cid):
    if not self.ucs2_cmap:
      raise PDFUnicodeNotDefined(self.cidcoding, cid)
    code = self.ucs2_cmap.tocode(cid)
    if not code:
      raise PDFUnicodeNotDefined(self.cidcoding, cid)
    chars = unpack('>%dH' % (len(code)/2), code)

  1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9  Next