def _open(self):

        # Screen
        s = self.fp.read(13)
        if s[:6] not in ["GIF87a", "GIF89a"]:
            raise SyntaxError, "not a GIF file"

        self.info["version"] = s[:6]

        self.size = i16(s[6:]), i16(s[8:])

        self.tile = []

        flags = ord(s[10])

        bits = (flags & 7) + 1

        if flags & 128:
            # get global palette
            self.info["background"] = ord(s[11])
            # check if palette contains colour indices
            p = self.fp.read(3 << bits)
            for i in range(0, len(p), 3):
                if not (chr(i / 3) == p[i] == p[i + 1] == p[i + 2]):
                    p = ImagePalette.raw("RGB", p)
                    self.global_palette = self.palette = p
                    break

        self.__fp = self.fp  # FIXME: hack
        self.__rewind = self.fp.tell()
        self.seek(0)  # get ready to read first frame
Example #2
0
def decode_pair(s, pos=0):
    """
    Decodes a name/value pair.

    The number of bytes decoded as well as the name/value pair
    are returned.
    """
    nameLength = ord(s[pos])
    if nameLength & 128:
        nameLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
        pos += 4
    else:
        pos += 1

    valueLength = ord(s[pos])
    if valueLength & 128:
        valueLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
        pos += 4
    else:
        pos += 1

    name = s[pos:pos+nameLength]
    pos += nameLength
    value = s[pos:pos+valueLength]
    pos += valueLength

    return (pos, (name, value))
Example #3
0
 def __init__(self, screen, args):
     self.log = logging.getLogger(__name__)
     self.log.debug("Initializing screen.")
     self.args = args
     self.interactive = not args.non_interactive
     if self.interactive:
         res, ret = unicurses.KEY_RESIZE, unicurses.KEY_ENTER
         self.ctrlchars = (res, ret, ord('\n'), ord('\x1b'))
         self.msg = None
         self.screen = screen
         self.h, self.w = 22, 78
         self.wrap = textwrap.TextWrapper(width=self.w - 1)
         self.initattrs()
         self.frame = unicurses.newwin(self.h + 2, self.w + 2, 0, 0)
         unicurses.wborder(self.frame)
         self.win = unicurses.newwin(self.h, self.w, 0, 0)
         unicurses.keypad(self.win, 1)
     self.sslnoverify = sys.version_info >= (2, 7, 9) and args.ssl_no_verify
     self.loadst, self.savest = True, True
     self.state = DataTree(self, {})
     self.oldstate = DataTree(self, {})
     self.validate = Validate(self)
     self.format = Format(self)
     self.nexus = Nexus(self)
     self.artifactory = Artifactory(self)
     self.initstate(args.load_file)
     self.log.debug("Screen initialized.")
Example #4
0
    def AppendToFile(self, filename, n_line_breaks=0):
        '''Appends user-friendly description of this time result object to
           a specified text file. If line breaks are desired, they will be
           appended to the file before the data.'''
        # Guard conditions
        if n_line_breaks < 0:
            n_line_breaks = 0
        
        # Open binary file in append mode
        filehandler = OpenAppendByteDataFile(filename)

        # If line breaks are desired, append them before the data
        lineBreak = tuple(os.linesep)
        if n_line_breaks > 0:
            lineBreakBytes = bytearray()
            for i in range(n_line_breaks):
                lineBreakBytes.extend(ord(char) for char in lineBreak)
            filehandler.write(lineBreakBytes)
        
        # Append byte format of string representation of self to file
        filehandler.write(bytes(str(self).encode("utf-8")))

        # Insert a newline to prepare for readable format considering future
        # data appending
        filehandler.write(bytearray(ord(char) for char in lineBreak))

        # Close file
        filehandler.close()
Example #5
0
    def __init__(self, my_map, my_total):
        self.STUDENT = ord('S')
        self.GROCERY = ord('G')
        self.PIZZA = ord('P')
        self.WALL = ord('W')

        self.FORWARD = 0
        self.RIGHT = 1
        self.LEFT = 2
        self.STAY = 3
        self.NORMAL = 5
        
        self.NORTH = 0
        self.EAST = 1
        self.SOUTH = 2
        self.WEST = 3

        self.row = 6
        self.col = 2
        self.time = 0
        self.alpha = 1
        self.total = float(my_total)
        self.map = my_map

        self.groceries = True
        self.pizzas = False

        self.lookup = np.array([
            [[-1, 0], [0, 1], [0, -1], [0, 0]],
            [[0, 1], [1, 0], [-1, 0], [0, 0]],
            [[1, 0], [0, -1], [0, 1], [0, 0]],
            [[0, -1], [-1, 0], [1, 0], [0, 0]]
        ])
Example #6
0
	def read(self, type, oaddr):
		"""Decode result from read1 or read2 commands.

		type: "1" or "2"
		oaddr: probe address

		Return:
		float: if result is valid.
		"underread" or "overread": if result is out of range.

		raises exception if device type is unknown by the driver.
		"""

		info = self.probes[oaddr-1]
		command = "read%s" % type
		result = self.execute(command, oaddr)

		response = ord(result[2])
		if response == 33:
			status = ord(result[3])
			if status == 18:
				return "underread"
			if status == 19:
				return "overread"

		value = struct.unpack(self.reply_format[command], result)[1]

		if info["moduletype"] == "DP":
			return float(value)/16384 * info["stroke"]

		raise NotImplementedError("Reading calculation not implemented for this module.")
Example #7
0
def main(verbose=False):
    message = get_data(59).split(',')

    message = [int(char) for char in message]

    possible_keys = []
    for ascii1 in range(97, 123):
        for ascii2 in range(97, 123):
            for ascii3 in range(97, 123):
                possible_keys.append([ascii1, ascii2, ascii3])

    for key in possible_keys:
        curr = translate(message, key)
        if (curr.upper().find('THE') != -1
                and curr.upper().find('IS') != -1
                and curr.upper().find('AND') != -1
                and curr.upper().find('OF') != -1
                and curr.upper().find('ARE') != -1):
            break

    key_as_word = ''.join(chr(val) for val in key)
    result = '\n\nActual Message:\n%s\n\nThe key is: %s or %s.' % (
        curr, key_as_word, key)

    if verbose:
        return '%s%s' % (sum(ord(letter) for letter in curr), result)
    else:
        return sum(ord(letter) for letter in curr)
Example #8
0
File: IRC.py Project: Peping/Lal
    def parse_line(self, nick, hostname, remainder):
        (argsstr, message) = remainder.split(" :",1) if " :" in remainder else (remainder.strip(),"")
        args = argsstr.split(" ")
        command = args[0]
        args = args[1:]

        if command=="PRIVMSG":
            if ord(message[0])==1 and ord(message[-1])==1:
                stripped = message[1:-1]
                first_space = stripped.find(" ")
                ctcp_command = stripped[:first_space] if first_space!=-1 else stripped
                ctcp_message = stripped[first_space+1:] if first_space!=-1 else ""
                self.raise_event("ctcp", is_request=True, origin=nick, message=ctcp_message, command=ctcp_command)
            elif len(args)==1:
                if args[0] == self.nickname:
                    self.raise_event("query",origin=nick, message=message)
                else: self.raise_event("channel message", origin=nick, channel=args[0], message=message)
        elif command=="NOTICE":
            if ord(message[0])==1 and ord(message[-1])==1:
                stripped = message[1:-1]
                first_space = stripped.find(" ")
                ctcp_command = stripped[:first_space] if first_space!=-1 else stripped
                ctcp_message = stripped[first_space+1:] if first_space!=-1 else ""
                self.raise_event("ctcp", is_request=False, origin=nick, message=ctcp_message, command=ctcp_command)
            elif len(args)==1:
                if args[0] == self.nickname:
                    self.raise_event("notice",origin=nick, message=message)
                else: self.raise_event("channel notice", origin=nick, channel=args[0], message=message)
        elif command=="JOIN":
            self.raise_event("joined", nick=nick, channel=message)
        elif command=="PART":
            self.raise_event("left", nick=nick, channel=message)
        elif command=="NICK":
            self.raise_event("nick", nick=nick, new_nick=message)
Example #9
0
def get_nsa_class (ipInfo=None, ip=None, conn=None, long_lat=None):
    
    if long_lat:
        (longitude, latitude) = long_lat

    else:
        if not ipInfo:
            ipInfo = get_ip_addr_info (ip, conn)

        longitude = ipInfo['long']
        latitude = ipInfo['lat']

    if not conn:
        conn = ixmaps.DBConnect.getConnection()

    all_chotels = ixmaps.CHotels(conn)
    chotels_in_city_list = all_chotels.all_within (longitude, latitude, 
                                                   MAX_NSA_DIST)
    chotels_in_city = ixmaps.CHotels (chotels=chotels_in_city_list)
    nsa_posts_in_city_list = chotels_in_city.get_type('NSA')
    

    # chotel = all_chotels.nsa_in_city (float(longitude), float(latitude),
                                      # (MAX_CHOTEL_DIST*20))

    if not nsa_posts_in_city_list:
        nsa_type = None

    else:
        nsa_type = 'Z'
        for nsa in nsa_posts_in_city_list:
            if ( ord(nsa['nsa']) < ord(nsa_type) ):
                nsa_type = nsa['nsa']

    return nsa_type
Example #10
0
def _check_end_after_start(start, end) -> None:
    reverse_start = start[::-1]
    reverse_end = end[::-1]
    e = sum((26 ** i) * ord(c) for i, c in enumerate(reverse_end))
    s = sum((26 ** i) * ord(c) for i, c in enumerate(reverse_start))
    if s > e:
        raise ValueError("start value {0} before end value {1}".format(start, end))
Example #11
0
    def is_animated_gif(self, data):
        if data[:6] not in [b"GIF87a", b"GIF89a"]:
            return False
        i = 10  # skip header
        frames = 0

        def skip_color_table(i, flags):
            if flags & 0x80:
                i += 3 << ((flags & 7) + 1)
            return i

        flags = ord(data[i])
        i = skip_color_table(i + 3, flags)
        while frames < 2:
            block = data[i]
            i += 1
            if block == b'\x3B':
                break
            if block == b'\x21':
                i += 1
            elif block == b'\x2C':
                frames += 1
                i += 8
                i = skip_color_table(i + 1, ord(data[i]))
                i += 1
            else:
                return False
            while True:
                j = ord(data[i])
                i += 1
                if not j:
                    break
                i += j
        return frames > 1
Example #12
0
def check_update (neighbor, raw):
	from exabgp.logger import Logger

	logger = Logger()
	logger._parser = True
	logger.parser('\ndecoding routes in configuration')

	n = neighbor[neighbor.keys()[0]]
	p = Peer(n,None)

	path = {}
	for f in known_families():
		if n.add_path:
			path[f] = n.add_path

	capa = Capabilities().new(n,False)
	capa[Capability.CODE.ADD_PATH] = path
	capa[Capability.CODE.MULTIPROTOCOL] = n.families()

	routerid_1 = str(n.router_id)
	routerid_2 = '.'.join(str((int(_)+1) % 250) for _ in str(n.router_id).split('.',-1))

	o1 = Open(4,n.local_as,routerid_1,capa,180)
	o2 = Open(4,n.peer_as,routerid_2,capa,180)
	negotiated = Negotiated(n)
	negotiated.sent(o1)
	negotiated.received(o2)
	# grouped = False

	while raw:
		if raw.startswith('\xff'*16):
			kind = ord(raw[18])
			size = (ord(raw[16]) << 16) + (ord(raw[17]))

			injected,raw = raw[19:size],raw[size:]

			if kind == 2:
				logger.parser('the message is an update')
				decoding = 'update'
			else:
				logger.parser('the message is not an update (%d) - aborting' % kind)
				return False
		else:
			logger.parser('header missing, assuming this message is ONE update')
			decoding = 'update'
			injected,raw = raw,''

		try:
			# This does not take the BGP header - let's assume we will not break that :)
			update = Update.unpack_message(injected,negotiated)
		except KeyboardInterrupt:
			raise
		except Notify,exc:
			logger.parser('could not parse the message')
			logger.parser(str(exc))
			return False
		except Exception,exc:
			logger.parser('could not parse the message')
			logger.parser(str(exc))
			return False
Example #13
0
def get_coord(character):
    width = 5
    assert 'a' <= character <= 'z', "invalid character"
    ref = ord('a')
    x = (ord(character) - ref) % width
    y = (ord(character) - ref) / width
    return (x, y)
Example #14
0
def main():
    files = glob.glob("./scans/*.jpg")
    files += glob.glob("./scans/*.jpeg")
    for f in files:
        reset_stats()
        print "Processing: " + f.split("/")[len(f.split("/")) - 1]

        schedule = Schedule()
        schedule.load_data()
        if schedule.get_has_schedule():
            scan_image(f, schedule)

            print "Sheet ok? ",
            while True:
                cv2.imshow("image", cv2.resize(img, (446, 578)))
                cv2.moveWindow("image", 0, 0)
                # user_in = raw_input()
                key = cv2.waitKey(-1)
                if key == ord("y"):
                    print "Sheet ok... Dumping data"
                    dump_stats()
                    os.remove(f)
                    break
                elif key == ord("n"):
                    print "Marking to redo"
                    #os.rename(f, "./scans/redo/" + f.split("/")[len(f.split("/")) - 1])
                    break
                elif key == ord("q"):
                    exit(0)
                else:
                    continue
            cv2.destroyAllWindows()
        else:
            print "Unable to load schedule... Aborting"
Example #15
0
def test_random_addition_and_slicing():
    seed = random.randrange(10000)
    print seed
    random.seed(seed)
    st = "abc"
    curr = LiteralStringNode(st)
    last = None
    all = []
    for i in range(1000):
        a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
                random.randrange(500))
        last = curr
        all.append(curr)
        c = random.choice([0, 1, 2])
        if c == 0:
            curr = curr + LiteralStringNode(a)
            st = st + a
        elif c == 1:
            curr = LiteralStringNode(a) + curr
            st = a + st
        else:
            if len(st) < 10:
                continue
            # get a significant portion of the string
            #import pdb; pdb.set_trace()
            start = random.randrange(len(st) // 3)
            stop = random.randrange(len(st) // 3 * 2, len(st))
            curr = getslice_one(curr, start, stop)
            st = st[start: stop]
        assert curr.flatten_string() == st
    curr = curr.rebalance()
    assert curr.flatten_string() == st
Example #16
0
File: test.py Project: rkm3/gspread
    def test_findall(self):
        list_len = 10
        range_label = 'A1:A%s' % list_len
        cell_list = self.sheet.range(range_label)
        value = gen_value()

        for c in cell_list:
            c.value = value
        self.sheet.update_cells(cell_list)

        result_list = self.sheet.findall(value)

        self.assertEqual(list_len, len(result_list))

        for c in result_list:
            self.assertEqual(c.value, value)

        cell_list = self.sheet.range(range_label)

        value = gen_value()
        for c in cell_list:
            char = chr(random.randrange(ord('a'), ord('z')))
            c.value = "%s%s_%s%s" % (c.value, char, char.upper(), value)

        self.sheet.update_cells(cell_list)

        o_O_re = re.compile('[a-z]_[A-Z]%s' % value)

        result_list = self.sheet.findall(o_O_re)

        self.assertEqual(list_len, len(result_list))
Example #17
0
def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated
Example #18
0
    def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
        """
        Render the text
        """
        if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying')

        if ismath:
            return self.draw_mathtext(gc, x, y, s, prop, angle)

        flags = get_hinting_flag()
        font = self._get_agg_font(prop)
        if font is None: return None
        if len(s) == 1 and ord(s) > 127:
            font.load_char(ord(s), flags=flags)
        else:
            # We pass '0' for angle here, since it will be rotated (in raster
            # space) in the following call to draw_text_image).
            font.set_text(s, 0, flags=flags)
        font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
        d = font.get_descent() / 64.0
        # The descent needs to be adjusted for the angle
        xo, yo = font.get_bitmap_offset()
        xo /= 64.0
        yo /= 64.0
        xd = -d * np.sin(np.deg2rad(angle))
        yd = d * np.cos(np.deg2rad(angle))

        #print x, y, int(x), int(y), s
        self._renderer.draw_text_image(
            font, np.round(x - xd + xo), np.round(y + yd + yo) + 1, angle, gc)
Example #19
0
File: uuid.py Project: 0xa-cc/pupy
def _netbios_getnode():
    """Get the hardware address on Windows using NetBIOS calls.
    See http://support.microsoft.com/kb/118623 for details."""
    import win32wnet, netbios
    ncb = netbios.NCB()
    ncb.Command = netbios.NCBENUM
    ncb.Buffer = adapters = netbios.LANA_ENUM()
    adapters._pack()
    if win32wnet.Netbios(ncb) != 0:
        return
    adapters._unpack()
    for i in range(adapters.length):
        ncb.Reset()
        ncb.Command = netbios.NCBRESET
        ncb.Lana_num = ord(adapters.lana[i])
        if win32wnet.Netbios(ncb) != 0:
            continue
        ncb.Reset()
        ncb.Command = netbios.NCBASTAT
        ncb.Lana_num = ord(adapters.lana[i])
        ncb.Callname = '*'.ljust(16)
        ncb.Buffer = status = netbios.ADAPTER_STATUS()
        if win32wnet.Netbios(ncb) != 0:
            continue
        status._unpack()
        bytes = map(ord, status.adapter_address)
        return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) +
                (bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5])
Example #20
0
def checksum(source_string):
    """
    I'm not too confident that this is right but testing seems
    to suggest that it gives the same answers as in_cksum in ping.c
    """
    sum = 0
    countTo = (len(source_string)/2)*2
    count = 0
    while count<countTo:
        thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
        sum = sum + thisVal
        sum = sum & 0xffffffff # Necessary?
        count = count + 2
 
    if countTo<len(source_string):
        sum = sum + ord(source_string[len(source_string) - 1])
        sum = sum & 0xffffffff # Necessary?
 
    sum = (sum >> 16)  +  (sum & 0xffff)
    sum = sum + (sum >> 16)
    answer = ~sum
    answer = answer & 0xffff
 
    # Swap bytes. Bugger me if I know why.
    answer = answer >> 8 | (answer << 8 & 0xff00)
 
    return answer
Example #21
0
def single_block_test_sha512x(block, mode, ser):
    # Write block to SHA-512.
    for i in range(len(block) / 4):
        message = [SOC, WRITE_CMD, SHA512_ADDR_PREFIX,] + [sha512_block_addr[i]] +\
                  block[(i * 4) : ((i * 4 ) + 4)] + [EOC]
        write_serial_bytes(message, ser)

    # Start initial block hashing, wait and check status.
    mode_cmd = chr(ord(SHA512_CTRL_INIT_CMD) + (ord(mode) << SHA512_CTRL_MODE_LOW))
    write_serial_bytes([SOC, WRITE_CMD, SHA512_ADDR_PREFIX, SHA512_ADDR_CTRL,
                        '\x00', '\x00', '\x00', mode_cmd, EOC], ser)
    time.sleep(PROC_DELAY_TIME)
    write_serial_bytes([SOC, READ_CMD, SHA512_ADDR_PREFIX, SHA512_ADDR_STATUS, EOC], ser)

    # Select the correct number of digest addresses to read.
    if (mode == MODE_SHA_512_224):
        mode_digest_addr = sha512_digest_addr[0 : 7]
    elif (mode == MODE_SHA_512_256):
        mode_digest_addr = sha512_digest_addr[0 : 8]
    elif (mode == MODE_SHA_384):
        mode_digest_addr = sha512_digest_addr[0 : 12]
    elif (mode == MODE_SHA_512):
        mode_digest_addr = sha512_digest_addr

    # Extract the digest.
    for digest_addr in mode_digest_addr:
        message = [SOC, READ_CMD, SHA512_ADDR_PREFIX] + [digest_addr] + [EOC]
        write_serial_bytes(message, ser)
    print""
Example #22
0
 def __init__(self, data, sensors, model):
     """
     Initializes packet data. Sets the global battery value.
     Updates each sensor with current sensor value from the packet data.
     """
     global g_battery
     self.raw_data = data
     self.counter = ord(data[0])
     self.battery = g_battery
     if self.counter > 127:
         self.battery = self.counter
         g_battery = battery_values[str(self.battery)]
         self.counter = 128
     self.sync = self.counter == 0xe9
     self.gyro_x = ord(data[29]) - 106
     self.gyro_y = ord(data[30]) - 105
     sensors['X']['value'] = self.gyro_x
     sensors['Y']['value'] = self.gyro_y
     for name, bits in sensor_bits.items():
         #Get Level for sensors subtract 8192 to get signed value
         value = get_level(self.raw_data, bits) - 8192
         setattr(self, name, (value,))
         sensors[name]['value'] = value
     self.old_model = model
     self.handle_quality(sensors)
     self.sensors = sensors
Example #23
0
 def getSizeOfTrailingDataEntry(data):
         num = 0
         for v in data[-4:]:
                 if ord(v) & 0x80:
                         num = 0
                 num = (num << 7) | (ord(v) & 0x7f)
         return num
Example #24
0
def html_escape(text):
  escaped_chars = ""
  for c in text:
    if (ord(c) < 32) or (ord(c) > 126):
      c = '&{};'.format(htmlentitydefs.codepoint2name[ord(c)])
    escaped_chars = escaped_chars + c
  return escaped_chars
Example #25
0
def check_key(key, key_extra_len=0):
    """Checks sanity of key.  Fails if:
        Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength).
        Contains control characters  (Raises MemcachedKeyCharacterError).
        Is not a string (Raises MemcachedStringEncodingError)
        Is an unicode string (Raises MemcachedStringEncodingError)
        Is not a string (Raises MemcachedKeyError)
        Is None (Raises MemcachedKeyError)
    """

    return # Short-circuit this expensive method

    if type(key) == types.TupleType: key = key[1]
    if not key:
        raise Client.MemcachedKeyNoneError, ("Key is None")
    if isinstance(key, unicode):
        raise Client.MemcachedStringEncodingError, ("Keys must be str()'s, not "
                "unicode.  Convert your unicode strings using "
                "mystring.encode(charset)!")
    if not isinstance(key, str):
        raise Client.MemcachedKeyTypeError, ("Key must be str()'s")

    if isinstance(key, basestring):
        if len(key) + key_extra_len > SERVER_MAX_KEY_LENGTH:
             raise Client.MemcachedKeyLengthError, ("Key length is > %s"
                     % SERVER_MAX_KEY_LENGTH)
        for char in key:
            if ord(char) < 32 or ord(char) == 127:
                raise Client.MemcachedKeyCharacterError, "Control characters not allowed"
Example #26
0
def test_prompt_y_or_n(terminal, stdscr):

    stdscr.getch.side_effect = [ord('y'), ord('N'), terminal.ESCAPE, ord('a')]
    attr = Color.CYAN | curses.A_BOLD
    text = 'hi'.encode('ascii')

    # Press 'y'
    assert terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert not curses.flash.called

    # Press 'N'
    assert not terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert not curses.flash.called

    # Press Esc
    assert not terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert not curses.flash.called

    # Press an invalid key
    assert not terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert curses.flash.called
Example #27
0
def encode_pinyin(pinyin):
    if pinyin == None or pinyin == "":
        return 0
    e = 0
    for c in pinyin:
        e = (e << 5) + (ord(c) - ord('a') + 1)
    return e
Example #28
0
def caeser_cypher(key, action, data):

    result_str = ""
    if action == 'decode':
        key = -key

    for sym in data:
        if sym.isalpha():
            num = ord(sym)
            num += key
            if sym.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            else:
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            result_str += chr(num)
        else:
            result_str += sym
    logging.info("OUTPUT: {}".format(result_str))
Example #29
0
    def _escape_text(self, text):
        # empty strings, should give a small performance improvment
        if not text:
            return ''

        # escape text
        text = self._escape(text)
        if self.encoding in ('utf-8', 'utf-16', 'utf-32'):
            encoding = 'iso-8859-15'
        else:
            encoding = self.encoding or 'iso-8859-15'

        buf = []
        for c in text:
            if ord(c) > 128:
                ansic = c.encode(encoding, 'ignore') or '?'
                if ord(ansic) > 128:
                    ansic = '\\\'%x' % ord(ansic)
                else:
                    ansic = c
                buf.append(r'\ud{\u%d%s}' % (ord(c), ansic))
            else:
                buf.append(str(c))

        return ''.join(buf).replace('\n', '\\par\n')
def _obfuscate(name, key):
    if name is None:
        return ''
    s = []
    for i in range(len(name)):
        s.append(chr(ord(name[i]) ^ ord(key[i % 13])))
    return base64.b64encode(''.join(s))