本文整理汇总了Python中ord函数的典型用法代码示例。如果您正苦于以下问题:Python ord函数的具体用法?Python ord怎么用?Python ord使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ord函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _open
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
示例2: decode_pair
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))
示例3: __init__
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.")
示例4: AppendToFile
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()
示例5: __init__
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]]
])
示例6: read
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.")
示例7: main
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)
示例8: parse_line
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)
示例9: get_nsa_class
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
示例10: _check_end_after_start
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))
示例11: is_animated_gif
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
示例12: check_update
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
示例13: get_coord
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)
示例14: main
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"
示例15: test_random_addition_and_slicing
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