<commit_before>"""
	a small, turn-based game in which players try to kill
			other players!
"""

import time, random, os, sys

sys.path.insert(0, os.path.join("..", "every", "common"))

# locals
from game import Game
from screen import Screen
from asciipixel import AsciiPixel
from stevent import Stevent

from display import Display

class Thing:
	"""
		all things are things.  a thing can be seen on the screen
	"""
	def __init__(self, ascii='?', asciiColor=None):
		if asciiColor == None:
			asciiColor = AsciiPixel.WHITE
		self.ascii = ascii
		self.asciiColor = asciiColor

class Event:
	"""
		an event to tell the users WTF
	"""
	#TODO: events are currently for a news feed
	#	i think events should eventually be how all state-changes happen
	#	such as movement etc.
	NOTHING_TYPE = 0
	ATTACK_TYPE = 1
	HIT_TYPE = 2
	MISS_TYPE = 3
	DEATH_TYPE = 4
	TURN_TYPE = 5
	MOVE_TYPE = 6
	def __init__(self, type=None, participants=None):
		if type == None:
			type = Event.NOTHING_TYPE
		self.type = type
		self.participants = participants

	def __repr__(self):
		if self.type == Event.NOTHING_TYPE:
			return "Nothing happens!"
		elif self.type == Event.ATTACK_TYPE:
			return "%s attacks %s!" % (
					self.participants[0], self.participants[1])
		elif self.type == Event.HIT_TYPE:
			return "%s hits %s for %d damage!" % (
					self.participants[0], self.participants[1],
					self.participants[2])
		elif self.type == Event.MISS_TYPE:
			return "%s swings and misses %s" %(
					self.participants[0], self.participants[1])
		elif self.type == Event.DEATH_TYPE:
			return "%s has died!" % self.participants
		elif self.type == Event.TURN_TYPE:
			return "It is now %d's turn." % self.participants
		elif self.type == Event.MOVE_TYPE:
			return "player%d has moved %s" % (
					self.participants[0],
					self.participants[1])
		else:
			return "OH NO!  WHAT KIND OF EVENT IS THIS?  FREAK OUT!"

	def __str__(self):
		return repr(self)

class Cell(Thing):
	WALL = 'W', AsciiPixel.WHITE
	FLOOR = '.', AsciiPixel.WHITE
	def __init__(self, type = None):
		if type == None:
			type = Cell.WALL
		Thing.__init__(self, type[0], type[1])
		self.creature = None
		self.objects = []
		self.type = type

	def render(self):
		"""
			return an ascii-pixel representation of yourself
		"""
		ret = None
		if self.creature != None:
			ret = AsciiPixel(self.creature.ascii, self.creature.asciiColor)
		elif len(self.objects) > 0:
			#TODO: implement called data members
			ret = AsciiPixel(self.objects[-1].ascii, self.objects[-1].asciiColor)
		else:
			# if there's no player there, and
			# there aren't any objects on the ground
			# then print the kind of cell
			ret = AsciiPixel(self.ascii, self.asciiColor)
		return ret

class Move:
	UP = 'up'
	DOWN = 'down'
	LEFT = 'left'
	RIGHT = 'right'

class Creature(Thing):
	"""
		eventually i'll have non-player participants!
	"""
	def __init__(self, x, y, type, maxHp):
		self.x = x
		self.y = y
		self.type = type
		self.dead = False
		self.maxHp = maxHp
		self.hp = maxHp

class Player(Creature):
	def __init__(self, id, x, y):
		Creature.__init__(self, x, y, 'player', 10)
		self.id = id
		self.nextMove = None
		self.dodge = 5
		self.ascii = '@'
		self.asciiColor = AsciiPixel.BLUE

class Arena(Game):
	WIDTH = 10
	HEIGHT = 10
	SECONDS_PER_TURN = 2
	EVENT_LIMIT = 30
	def __init__(self):
		self.creatures = []
		self.board = [[Cell() for j in range(Arena.WIDTH)]
				for i in range(Arena.HEIGHT)]
		for i in range(2, 8):
			for j in range(2, 8):
				self.board[i][j].type = Cell.FLOOR
				self.board[i][j].ascii = Cell.FLOOR[0]
				self.board[i][j].asciiColor = Cell.FLOOR[1]
		self.startTime = time.time()
		self.lastIterated = self.startTime
		self.curCreatureIndex = 0
		self.events = []

	def iterate(self):
		curTime = time.time()
		if len(self.events) > Arena.EVENT_LIMIT:
			self.events = self.events[(-1 * Arena.EVENT_LIMIT):]
		if curTime - self.lastIterated > Arena.SECONDS_PER_TURN:
			self.handleTurn()
			print "New Turn!  Current player=%d" % self.curCreatureIndex
			print "*** EVENT LOG ***"
			print repr(self.events)
			print "*** END EVENT LOG ***"
			print "current # of creatures: %d" % len(self.creatures)
			self.lastIterated = curTime

	def handleTurn(self):
		# then we process the next player's move
		if len(self.creatures) == 0:
			return
		# at the last minute we update the index just in case someone quit
		self.curCreatureIndex = self.curCreatureIndex % len(self.creatures)
		creature = self.creatures[self.curCreatureIndex]
		if creature.type != 'player':
			creature.getNextMove()
		if creature.nextMove == None:
			print 'The current player did not move!'
			nothingEvent = Event()
			self.events.append(nothingEvent)
			self.incrementTurn()
			return
		xOffset = 0
		yOffset = 0
		if creature.nextMove == Move.LEFT:
			xOffset = -1
			yOffset = 0
		elif creature.nextMove == Move.RIGHT:
			xOffset = 1
			yOffset = 0
		elif creature.nextMove == Move.UP:
			xOffset = 0
			yOffset = -1
		elif creature.nextMove == Move.DOWN:
			xOffset = 0
			yOffset = 1
		newX = creature.x + xOffset
		newY = creature.y + yOffset
		if newX >= 0 and newX < len(self.board[0]) and (
				newY >= 0 and newY < len(self.board) and
				self.board[newY][newX].type == Cell.FLOOR):
			if self.board[newY][newX].creature == None:
				# if no one's there, we move there
				print "creature move %s accepted!" % creature.nextMove
				moveEvent = Event(Event.MOVE_TYPE,
						(creature.id, creature.nextMove))
				self.events.append(moveEvent)
				self.board[creature.y][creature.x].creature = None
				self.board[newY][newX].creature = creature
				creature.x = newX
				creature.y = newY
			else:
				# we attack that player standing there!
				attacker = creature
				attackee = self.board[newY][newX].creature
				self.handleAttack(attacker, attackee)
		else:
			print "creature move of %s not accepted!" % creature.nextMove
		creature.nextMove = None
		self.incrementTurn()
		creature = self.creatures[self.curCreatureIndex]
		#TODO: does python really not have a do-while?
		while creature.dead:
			self.incrementTurn()
			creature = self.creatures[self.curCreatureIndex]

	def incrementTurn(self):
		self.curCreatureIndex += 1
		self.curCreatureIndex = self.curCreatureIndex % len(self.creatures)
		turnEvent = Event(Event.TURN_TYPE, (self.curCreatureIndex))
		self.events.append(turnEvent)

	def handleAttack(self, attacker, attackee):
		self.events.append(Event(Event.ATTACK_TYPE, (
				("player%d" % attacker.id),
				("player%d" % attackee.id))))

		hitRoll = random.randint(0, 9)
		damageRoll = random.randint(0, 9)
		if hitRoll >= attackee.dodge:
			self.events.append(Event(Event.HIT_TYPE, (
					("player%d" % attacker.id),
					("player%d" % attackee.id),
					hitRoll)))
			attackee.hp -= hitRoll
			if attackee.hp < 0:
				# atackee dies
				self.removePC(attackee)
				self.events.append(Event(
						Event.DEATH_TYPE, "player%d" % attackee.id))
		else:
			self.events.append(Event(Event.MISS_TYPE, (
					("player%d" % attacker.id),
					("player%d" % attackee.id))))

	def addPlayer(self, playerId):
		targetX = random.randint(0, 9)
		targetY = random.randint(0, 9)
		targetCell = self.board[targetY][targetX]
		while targetCell.creature != None or targetCell.type != Cell.FLOOR:
			targetX = random.randint(0, 9)
			targetY = random.randint(0, 9)
			targetCell = self.board[targetY][targetX]
		newPlayer = Player(playerId, targetX, targetY)
		targetCell.creature = newPlayer
		self.creatures.append(newPlayer)

	def removePlayer(self, playerId):
		targetPlayer = None
		found = False
		targetPlayer = None
		for creature in self.creatures:
			if creature.type == 'player' and creature.id == playerId:
				found = True
				targetPlayer = creature
				break
		if targetPlayer == None:
			print 'unable to find player to remove'
			return
		self.creatures.remove(targetPlayer)
		if not targetPlayer.dead:
			targetCell = self.board[targetPlayer.y][targetPlayer.x]
			targetCell.creature = None
		return

	def removePC(self, player):
		"""
			the player is still present, but their PC has died
			TODO: also add checking for this having happened
			inside removePlayer

			either playerId or player are sufficient arguments
		"""
		# is player a playerId?  if so, we need to find the actual player
		if isinstance(player, int):
			for creature in self.creatures:
				if creature.type == 'player' and creature.id == playerId:
					player = creature
		if player == None:
			print 'could not find PC to remove'
		else:
			player.dead = True
			targetCell = self.board[player.y][player.x]
			targetCell.creature = None

	def getPlayer(self, playerId):
		for creature in self.creatures:
			if creature.type == 'player' and creature.id == playerId:
				return creature
		print 'unable to find player'
		return None

	def handleInput(self, stevent, playerId):
		curPlayer = self.getPlayer(playerId)
		if curPlayer == None or curPlayer.dead:
			return
		if stevent.type == Stevent.QUIT:
			print "###ATTEMPTING TO REMOVE PLAYER %d" % playerId
			self.removePlayer(playerId)
			return
		if stevent.type != Stevent.KEYDOWN:
			return
		if stevent.key == ord('a') or stevent.key == ord('h'):
			curPlayer.nextMove = Move.LEFT
		elif stevent.key == ord('d') or stevent.key == ord('l'):
			curPlayer.nextMove = Move.RIGHT
		elif stevent.key == ord('s') or stevent.key == ord('j'):
			curPlayer.nextMove = Move.DOWN
		elif stevent.key == ord('w') or stevent.key == ord('k'):
			curPlayer.nextMove = Move.UP
		print "player %d's next move is currently %s" % (
				curPlayer.id, curPlayer.nextMove)

	def getScreen(self, playerId):
		player = self.getPlayer(playerId)
		display = Display(self.board, self.events)
		player = self.getPlayer(playerId)
		curScreen = display.getScreen(player)
		return curScreen

	"""
	def getScreen(self, playerId):
		rowList = []
		curRow = []
		for row in self.board:
			for cell in row:
				if cell.creature == None:
					curRow.append(AsciiPixel(ord(cell.ascii), cell.asciiColor))
				else:
					curRow.append(AsciiPixel(ord(cell.creature.ascii), cell.creature.asciiColor))
			rowList.append(curRow)
			curRow = []
		screen = Screen(rowList)
		return screen
	"""

<commit_msg>fixed that bug!  this is kind of a game now.  although i do not like the way you can move before your turn.  i should probably change that.  i also need an HP indicator if i am really going to stick with this HP business.  i will eventually need to decide who gets what events.  every player should eventually have their own personalized event ticker.  but for arena, one event ticker will suffice<commit_after>"""
	a small, turn-based game in which players try to kill
			other players!
"""

import time, random, os, sys

sys.path.insert(0, os.path.join("..", "every", "common"))

# locals
from game import Game
from screen import Screen
from asciipixel import AsciiPixel
from stevent import Stevent

from display import Display

class Thing:
	"""
		all things are things.  a thing can be seen on the screen
	"""
	def __init__(self, ascii='?', asciiColor=None):
		if asciiColor == None:
			asciiColor = AsciiPixel.WHITE
		self.ascii = ascii
		self.asciiColor = asciiColor

class Event:
	"""
		an event to tell the users WTF
		it is not used for game logic purposes,
		just for news items in the event ticker
	"""
	#TODO: events are currently for a news feed
	#	i think events should eventually be how all state-changes happen
	#	such as movement etc.
	NOTHING_TYPE = 0
	ATTACK_TYPE = 1
	HIT_TYPE = 2
	MISS_TYPE = 3
	DEATH_TYPE = 4
	TURN_TYPE = 5
	MOVE_TYPE = 6
	def __init__(self, type=None, participants=None):
		if type == None:
			type = Event.NOTHING_TYPE
		self.type = type
		self.participants = participants

	def __repr__(self):
		if self.type == Event.NOTHING_TYPE:
			return "Nothing happens!"
		elif self.type == Event.ATTACK_TYPE:
			return "%s attacks %s!" % (
					self.participants[0], self.participants[1])
		elif self.type == Event.HIT_TYPE:
			return "%s hits %s for %d damage!" % (
					self.participants[0], self.participants[1],
					self.participants[2])
		elif self.type == Event.MISS_TYPE:
			return "%s swings and misses %s" %(
					self.participants[0], self.participants[1])
		elif self.type == Event.DEATH_TYPE:
			return "%s has died!" % self.participants
		elif self.type == Event.TURN_TYPE:
			return "It is now %d's turn." % self.participants
		elif self.type == Event.MOVE_TYPE:
			return "player%d has moved %s" % (
					self.participants[0],
					self.participants[1])
		else:
			return "OH NO!  WHAT KIND OF EVENT IS THIS?  FREAK OUT!"

	def __str__(self):
		return repr(self)

class Cell(Thing):
	WALL = 'W', AsciiPixel.WHITE
	FLOOR = '.', AsciiPixel.WHITE
	def __init__(self, type = None):
		if type == None:
			type = Cell.WALL
		Thing.__init__(self, type[0], type[1])
		self.creature = None
		self.objects = []
		self.type = type

	def render(self):
		"""
			return an ascii-pixel representation of yourself
		"""
		ret = None
		if self.creature != None:
			ret = AsciiPixel(self.creature.ascii, self.creature.asciiColor)
		elif len(self.objects) > 0:
			#TODO: implement called data members
			ret = AsciiPixel(self.objects[-1].ascii, self.objects[-1].asciiColor)
		else:
			# if there's no player there, and
			# there aren't any objects on the ground
			# then print the kind of cell
			ret = AsciiPixel(self.ascii, self.asciiColor)
		return ret

class Move:
	UP = 'up'
	DOWN = 'down'
	LEFT = 'left'
	RIGHT = 'right'

class Creature(Thing):
	"""
		eventually i'll have non-player participants!
	"""
	def __init__(self, x, y, type, maxHp):
		self.x = x
		self.y = y
		self.type = type
		self.dead = False
		self.maxHp = maxHp
		self.hp = maxHp

class Player(Creature):
	def __init__(self, id, x, y):
		Creature.__init__(self, x, y, 'player', 10)
		self.id = id
		self.nextMove = None
		self.dodge = 5
		self.ascii = '@'
		self.asciiColor = AsciiPixel.BLUE

class Arena(Game):
	WIDTH = 10
	HEIGHT = 10
	SECONDS_PER_TURN = 2
	EVENT_LIMIT = 30
	def __init__(self):
		self.creatures = []
		self.board = [[Cell() for j in range(Arena.WIDTH)]
				for i in range(Arena.HEIGHT)]
		for i in range(2, 8):
			for j in range(2, 8):
				self.board[i][j].type = Cell.FLOOR
				self.board[i][j].ascii = Cell.FLOOR[0]
				self.board[i][j].asciiColor = Cell.FLOOR[1]
		self.startTime = time.time()
		self.lastIterated = self.startTime
		self.curCreatureIndex = 0
		self.events = []

	def iterate(self):
		curTime = time.time()
		if len(self.events) > Arena.EVENT_LIMIT:
			self.events = self.events[(-1 * Arena.EVENT_LIMIT):]
		if curTime - self.lastIterated > Arena.SECONDS_PER_TURN:
			self.handleTurn()
			print "New Turn!  Current player=%d" % self.curCreatureIndex
			print "*** EVENT LOG ***"
			print repr(self.events)
			print "*** END EVENT LOG ***"
			print "current # of creatures: %d" % len(self.creatures)
			self.lastIterated = curTime

	def handleTurn(self):
		# then we process the next player's move
		if len(self.creatures) == 0:
			return
		# at the last minute we update the index just in case someone quit
		self.curCreatureIndex = self.curCreatureIndex % len(self.creatures)
		creature = self.creatures[self.curCreatureIndex]
		if creature.type != 'player':
			creature.getNextMove()
		if creature.nextMove == None:
			print 'The current player did not move!'
			nothingEvent = Event()
			self.events.append(nothingEvent)
			self.incrementTurn()
			return
		xOffset = 0
		yOffset = 0
		if creature.nextMove == Move.LEFT:
			xOffset = -1
			yOffset = 0
		elif creature.nextMove == Move.RIGHT:
			xOffset = 1
			yOffset = 0
		elif creature.nextMove == Move.UP:
			xOffset = 0
			yOffset = -1
		elif creature.nextMove == Move.DOWN:
			xOffset = 0
			yOffset = 1
		newX = creature.x + xOffset
		newY = creature.y + yOffset
		if newX >= 0 and newX < len(self.board[0]) and (
				newY >= 0 and newY < len(self.board) and
				self.board[newY][newX].type == Cell.FLOOR):
			if self.board[newY][newX].creature == None:
				# if no one's there, we move there
				print "creature move %s accepted!" % creature.nextMove
				moveEvent = Event(Event.MOVE_TYPE,
						(creature.id, creature.nextMove))
				self.events.append(moveEvent)
				self.board[creature.y][creature.x].creature = None
				self.board[newY][newX].creature = creature
				creature.x = newX
				creature.y = newY
			else:
				# we attack that player standing there!
				attacker = creature
				attackee = self.board[newY][newX].creature
				self.handleAttack(attacker, attackee)
		else:
			print "creature move of %s not accepted!" % creature.nextMove
		creature.nextMove = None
		self.incrementTurn()

	def incrementTurn(self):
		curCreature = None
		while curCreature == None or curCreature.dead:
			self.curCreatureIndex += 1
			self.curCreatureIndex = self.curCreatureIndex % len(self.creatures)
			curCreature = self.creatures[self.curCreatureIndex]
		turnEvent = Event(Event.TURN_TYPE, curCreature.id)
		self.events.append(turnEvent)

	def handleAttack(self, attacker, attackee):
		self.events.append(Event(Event.ATTACK_TYPE, (
				("player%d" % attacker.id),
				("player%d" % attackee.id))))

		hitRoll = random.randint(0, 9)
		damageRoll = random.randint(0, 9)
		if hitRoll >= attackee.dodge:
			self.events.append(Event(Event.HIT_TYPE, (
					("player%d" % attacker.id),
					("player%d" % attackee.id),
					hitRoll)))
			attackee.hp -= hitRoll
			if attackee.hp < 0:
				# atackee dies
				self.removePC(attackee)
				self.events.append(Event(
						Event.DEATH_TYPE, "player%d" % attackee.id))
		else:
			self.events.append(Event(Event.MISS_TYPE, (
					("player%d" % attacker.id),
					("player%d" % attackee.id))))

	def addPlayer(self, playerId):
		targetX = random.randint(0, 9)
		targetY = random.randint(0, 9)
		targetCell = self.board[targetY][targetX]
		while targetCell.creature != None or targetCell.type != Cell.FLOOR:
			targetX = random.randint(0, 9)
			targetY = random.randint(0, 9)
			targetCell = self.board[targetY][targetX]
		newPlayer = Player(playerId, targetX, targetY)
		targetCell.creature = newPlayer
		self.creatures.append(newPlayer)

	def removePlayer(self, playerId):
		targetPlayer = None
		found = False
		targetPlayer = None
		for creature in self.creatures:
			if creature.type == 'player' and creature.id == playerId:
				found = True
				targetPlayer = creature
				break
		if targetPlayer == None:
			print 'unable to find player to remove'
			return
		self.creatures.remove(targetPlayer)
		if not targetPlayer.dead:
			targetCell = self.board[targetPlayer.y][targetPlayer.x]
			targetCell.creature = None
		return

	def removePC(self, player):
		"""
			the player is still present, but their PC has died
			TODO: also add checking for this having happened
			inside removePlayer

			either playerId or player are sufficient arguments
		"""
		# is player a playerId?  if so, we need to find the actual player
		if isinstance(player, int):
			for creature in self.creatures:
				if creature.type == 'player' and creature.id == playerId:
					player = creature
		if player == None:
			print 'could not find PC to remove'
		else:
			player.dead = True
			targetCell = self.board[player.y][player.x]
			targetCell.creature = None

	def getPlayer(self, playerId):
		for creature in self.creatures:
			if creature.type == 'player' and creature.id == playerId:
				return creature
		print 'unable to find player'
		return None

	def handleInput(self, stevent, playerId):
		curPlayer = self.getPlayer(playerId)
		if curPlayer == None:
			return
		if stevent.type == Stevent.QUIT:
			print "###ATTEMPTING TO REMOVE PLAYER %d" % playerId
			self.removePlayer(playerId)
			return
		if curPlayer.dead:
			return
		if stevent.type != Stevent.KEYDOWN:
			return
		if stevent.key == ord('a') or stevent.key == ord('h'):
			curPlayer.nextMove = Move.LEFT
		elif stevent.key == ord('d') or stevent.key == ord('l'):
			curPlayer.nextMove = Move.RIGHT
		elif stevent.key == ord('s') or stevent.key == ord('j'):
			curPlayer.nextMove = Move.DOWN
		elif stevent.key == ord('w') or stevent.key == ord('k'):
			curPlayer.nextMove = Move.UP
		print "player %d's next move is currently %s" % (
				curPlayer.id, curPlayer.nextMove)

	def getScreen(self, playerId):
		player = self.getPlayer(playerId)
		display = Display(self.board, self.events)
		player = self.getPlayer(playerId)
		curScreen = display.getScreen(player)
		return curScreen

	"""
	def getScreen(self, playerId):
		rowList = []
		curRow = []
		for row in self.board:
			for cell in row:
				if cell.creature == None:
					curRow.append(AsciiPixel(ord(cell.ascii), cell.asciiColor))
				else:
					curRow.append(AsciiPixel(ord(cell.creature.ascii), cell.creature.asciiColor))
			rowList.append(curRow)
			curRow = []
		screen = Screen(rowList)
		return screen
	"""

<|endoftext|>


<commit_before>import socket

class Connection(object):
    def __init__(self, host='127.0.0.1', port=11300, decode_yaml=True):
        if decode_yaml:
            global yaml
            import yaml
        self.host = host
        self.port = port
        self.decode_yaml = decode_yaml
        self.connect()

    def connect(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((self.host, self.port))
        self.socket_file = self.socket.makefile('rb')

    def close(self):
        self.socket.close()

    def interact(self, command, expected):
        self.socket.send(command)
        return self.check_response(expected)

    def check_response(self, expected):
        word, vals = self.read_response()
        if word in expected:
            return vals
        else:
            raise 'unexpected-response' # @@

    def read_response(self):
        response = self.socket_file.readline().split()
        return response[0], response[1:]

    def read_body(self, size):
        body = self.socket_file.read(size)
        self.socket_file.read(2) # trailing crlf
        return body

    def interact_job(self, command, expected):
        [jid, size] = self.interact(command, expected)
        body = self.read_body(int(size))
        return jid, size, body

    def interact_yaml(self, command, expected):
        [size] = self.interact(command, expected)
        body = self.read_body(int(size))
        return yaml.load(body) if self.decode_yaml else body

    # -- public interface --

    def put(self, body, priority=2147483648, delay=0, ttr=120):
        [jid] = self.interact(
                'put %d %d %d %d\r\n%s\r\n' %
                    (priority, delay, ttr, len(body), body),
                ['INSERTED', 'BURIED'])
        return int(jid)

    def reserve(self, timeout=None):
        if timeout:
            command = 'reserve-with-timeout %d\r\n' % timeout
        else:
            command = 'reserve\r\n'
        jid, size, body = self.interact_job(command, 'RESERVED')
        return Job(self, int(jid), body, True)

    def tubes(self):
        return self.interact_yaml('list-tubes\r\n', 'OK')

    def using(self):
        return self.interact('list-tube-used\r\n', 'USING')[0]

    def use(self, name):
        return self.interact('use %s\r\n' % name, 'USING')[0]

    def watching(self):
        return self.interact_yaml('list-tubes-watched\r\n', 'OK')

    def watch(self, name):
        return int(self.interact('watch %s\r\n' % name, 'WATCHING')[0])

    def ignore(self, name):
        r = self.interact('ignore %s\r\n' % name, ['WATCHING', 'NOT_IGNORED'])
        return r[0] if r else 1

    def stats(self):
        return self.interact_yaml('stats\r\n', 'OK')

    # -- job interactors --

    def delete(self, jid):
        self.interact('delete %d\r\n' % jid, 'DELETED')

class Job:
    def __init__(self, conn, jid, body, reserved=True):
        self.conn = conn
        self.jid = jid
        self.body = body
        self.reserved = reserved

    # -- public interface --

    def delete(self):
        if self.reserved:
            self.conn.delete(self.jid)
            self.reserved = False
<commit_msg>Added reserve-with-timeout<commit_after>import socket

class Connection(object):
    def __init__(self, host='127.0.0.1', port=11300, decode_yaml=True):
        if decode_yaml:
            global yaml
            import yaml
        self.host = host
        self.port = port
        self.decode_yaml = decode_yaml
        self.connect()

    def connect(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((self.host, self.port))
        self.socket_file = self.socket.makefile('rb')

    def close(self):
        self.socket.close()

    def interact(self, command, expected):
        self.socket.send(command)
        return self.check_response(expected)

    def check_response(self, expected):
        status, results = self.read_response()
        if status in expected:
            return status, results
        else:
            raise 'unexpected-response', status # @@

    def read_response(self):
        response = self.socket_file.readline().split()
        return response[0], response[1:]

    def read_body(self, size):
        body = self.socket_file.read(size)
        self.socket_file.read(2) # trailing crlf
        return body

    def interact_value(self, command, expected):
        _, results = self.interact(command, expected)
        return results[0]

    def interact_job(self, command, expected_ok, expected_err):
        status, results = self.interact(command, [expected_ok] + expected_err)
        if status in expected_ok:
            jid, size = results
            body = self.read_body(int(size))
            return status, (jid, size, body)
        else:
            return status, results

    def interact_yaml(self, command, expected):
        size = self.interact_value(command, expected)
        body = self.read_body(int(size))
        return yaml.load(body) if self.decode_yaml else body

    # -- public interface --

    def put(self, body, priority=2147483648, delay=0, ttr=120):
        jid = self.interact_value(
                'put %d %d %d %d\r\n%s\r\n' %
                    (priority, delay, ttr, len(body), body),
                ['INSERTED', 'BURIED'])
        return int(jid)

    def reserve(self, timeout=None):
        if timeout is not None:
            command = 'reserve-with-timeout %d\r\n' % timeout
        else:
            command = 'reserve\r\n'
        status, results = self.interact_job(command,
                                            'RESERVED',
                                            ['DEADLINE_SOON', 'TIMED_OUT'])
        if status == 'TIMED_OUT':
            return None
        elif status == 'DEADLINE_SOON':
            raise 'deadline-soon', results # @@
        else:
            jid, size, body = results
            return Job(self, int(jid), body, True)

    def tubes(self):
        return self.interact_yaml('list-tubes\r\n', 'OK')

    def using(self):
        return self.interact_value('list-tube-used\r\n', 'USING')

    def use(self, name):
        return self.interact_value('use %s\r\n' % name, 'USING')

    def watching(self):
        return self.interact_yaml('list-tubes-watched\r\n', 'OK')

    def watch(self, name):
        return int(self.interact_value('watch %s\r\n' % name, 'WATCHING'))

    def ignore(self, name):
        status, results = self.interact('ignore %s\r\n' % name,
                                        ['WATCHING', 'NOT_IGNORED'])
        return int(results[0]) if status == 'WATCHING' else 1

    def stats(self):
        return self.interact_yaml('stats\r\n', 'OK')

    # -- job interactors --

    def delete(self, jid):
        self.interact('delete %d\r\n' % jid, 'DELETED')

class Job:
    def __init__(self, conn, jid, body, reserved=True):
        self.conn = conn
        self.jid = jid
        self.body = body
        self.reserved = reserved

    # -- public interface --

    def delete(self):
        if self.reserved:
            self.conn.delete(self.jid)
            self.reserved = False
<|endoftext|>


<commit_before>"""Append module search paths for third-party packages to sys.path.

****************************************************************
* This module is automatically imported during initialization, *
* if you add the setuptools egg to PYTHONPATH (to support the  *
* simple non-root installation mode)                           *
****************************************************************

In earlier versions of Python (up to 1.5a3), scripts or modules that
needed to use site-specific modules would place ``import site''
somewhere near the top of their code.  Because of the automatic
import, this is no longer necessary (but code that does it still
works).

This will append site-specific paths to the module search path.  On
Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
appends lib/python<version>/site-packages as well as lib/site-python.
On other platforms (mainly Mac and Windows), it uses just sys.prefix
(and sys.exec_prefix, if different, but this is unlikely).  The
resulting directories, if they exist, are appended to sys.path, and
also inspected for path configuration files.

A path configuration file is a file whose name has the form
<package>.pth; its contents are additional directories (one per line)
to be added to sys.path.  Non-existing directories (or
non-directories) are never added to sys.path; no directory is added to
sys.path more than once.  Blank lines and lines beginning with
'#' are skipped. Lines starting with 'import' are executed.

For example, suppose sys.prefix and sys.exec_prefix are set to
/usr/local and there is a directory /usr/local/lib/python1.5/site-packages
with three subdirectories, foo, bar and spam, and two path
configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
following:

  # foo package configuration
  foo
  bar
  bletch

and bar.pth contains:

  # bar package configuration
  bar

Then the following directories are added to sys.path, in this order:

  /usr/local/lib/python1.5/site-packages/bar
  /usr/local/lib/python1.5/site-packages/foo

Note that bletch is omitted because it doesn't exist; bar precedes foo
because bar.pth comes alphabetically before foo.pth; and spam is
omitted because it is not mentioned in either path configuration file.

After these path manipulations, an attempt is made to import a module
named sitecustomize, which can perform arbitrary additional
site-specific customizations.  If this import fails with an
ImportError exception, it is silently ignored.

"""

import sys
import os
import __builtin__

def makepath(*paths):
    dir = os.path.abspath(os.path.join(*paths))
    return dir, os.path.normcase(dir)

def abs__file__():
    """Set all module' __file__ attribute to an absolute path"""
    for m in sys.modules.values():
        try:
            m.__file__ = os.path.abspath(m.__file__)
        except AttributeError:
            continue

def removeduppaths():
    """ Remove duplicate entries from sys.path along with making them
    absolute"""
    # This ensures that the initial path provided by the interpreter contains
    # only absolute pathnames, even if we're running from the build directory.
    L = []
    known_paths = {}
    for dir in sys.path:
        # Filter out duplicate paths (on case-insensitive file systems also
        # if they only differ in case); turn relative paths into absolute
        # paths.
        dir, dircase = makepath(dir)
        if not dircase in known_paths:
            L.append(dir)
            known_paths[dircase] = 1
    sys.path[:] = L
    return known_paths

# XXX This should not be part of site.py, since it is needed even when
# using the -S option for Python.  See http://www.python.org/sf/586680
def addbuilddir():
    """Append ./build/lib.<platform> in case we're running in the build dir
    (especially for Guido :-)"""
    from distutils.util import get_platform
    s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
    s = os.path.join(os.path.dirname(sys.path[-1]), s)
    sys.path.append(s)

def _init_pathinfo():
    """Return a set containing all existing directory entries from sys.path"""
    d = {}
    for dir in sys.path:
        try:
            if os.path.isdir(dir):
                dir, dircase = makepath(dir)
                d[dircase] = 1
        except TypeError:
            continue
    return d

def addpackage(sitedir, name, known_paths):
    """Add a new path to known_paths by combining sitedir and 'name' or execute
    sitedir if it starts with 'import'"""
    if known_paths is None:
        known_paths = _init_pathinfo()
        reset = 1
    else:
        reset = 0
    fullname = os.path.join(sitedir, name)
    try:
        f = open(fullname, "rU")
    except IOError:
        return
    try:
        for line in f:
            if line.startswith("#"):
                continue
            if line.startswith("import"):
                exec line
                continue
            line = line.rstrip()
            dir, dircase = makepath(sitedir, line)
            if not dircase in known_paths and os.path.exists(dir):
                sys.path.append(dir)
                known_paths[dircase] = 1
    finally:
        f.close()
    if reset:
        known_paths = None
    return known_paths

def addsitedir(sitedir, known_paths=None):
    """Add 'sitedir' argument to sys.path if missing and handle .pth files in
    'sitedir'"""
    if known_paths is None:
        known_paths = _init_pathinfo()
        reset = 1
    else:
        reset = 0
    sitedir, sitedircase = makepath(sitedir)
    if not sitedircase in known_paths:
        sys.path.append(sitedir)        # Add path component
    try:
        names = os.listdir(sitedir)
    except os.error:
        return
    names.sort()
    for name in names:
        if name.endswith(os.extsep + "pth"):
            addpackage(sitedir, name, known_paths)
    if reset:
        known_paths = None
    return known_paths

def addsitepackages(known_paths):
    """Add site-packages (and possibly site-python) to sys.path"""
    prefixes = [sys.prefix]
    if sys.exec_prefix != sys.prefix:
        prefixes.append(sys.exec_prefix)
    for prefix in prefixes:
        if prefix:
            if sys.platform in ('os2emx', 'riscos'):
                sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
            elif os.sep == '/':
                sitedirs = [os.path.join(prefix,
                                         "lib",
                                         "python" + sys.version[:3],
                                         "site-packages"),
                            os.path.join(prefix, "lib", "site-python")]
            else:
                sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
            if sys.platform == 'darwin':
                # for framework builds *only* we add the standard Apple
                # locations. Currently only per-user, but /Library and
                # /Network/Library could be added too
                if 'Python.framework' in prefix:
                    home = os.environ.get('HOME')
                    if home:
                        sitedirs.append(
                            os.path.join(home,
                                         'Library',
                                         'Python',
                                         sys.version[:3],
                                         'site-packages'))
            for sitedir in sys.path:
                if sitedir and os.path.isdir(sitedir):
                    addsitedir(sitedir, known_paths)
    return None

def setBEGINLIBPATH():
    """The OS/2 EMX port has optional extension modules that do double duty
    as DLLs (and must use the .DLL file extension) for other extensions.
    The library search path needs to be amended so these will be found
    during module import.  Use BEGINLIBPATH so that these are at the start
    of the library search path.

    """
    dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
    libpath = os.environ['BEGINLIBPATH'].split(';')
    if libpath[-1]:
        libpath.append(dllpath)
    else:
        libpath[-1] = dllpath
    os.environ['BEGINLIBPATH'] = ';'.join(libpath)

def setquit():
    """Define new built-ins 'quit' and 'exit'.
    These are simply strings that display a hint on how to exit.

    """
    if os.sep == ':':
        exit = 'Use Cmd-Q to quit.'
    elif os.sep == '\\':
        exit = 'Use Ctrl-Z plus Return to exit.'
    else:
        exit = 'Use Ctrl-D (i.e. EOF) to exit.'
    __builtin__.quit = __builtin__.exit = exit

class _Printer(object):
    """interactive prompt objects for printing the license text, a list of
    contributors and the copyright notice."""

    MAXLINES = 23

    def __init__(self, name, data, files=(), dirs=()):
        self.__name = name
        self.__data = data
        self.__files = files
        self.__dirs = dirs
        self.__lines = None

    def __setup(self):
        if self.__lines:
            return
        data = None
        for dir in self.__dirs:
            for filename in self.__files:
                filename = os.path.join(dir, filename)
                try:
                    fp = file(filename, "rU")
                    data = fp.read()
                    fp.close()
                    break
                except IOError:
                    pass
            if data:
                break
        if not data:
            data = self.__data
        self.__lines = data.split('\n')
        self.__linecnt = len(self.__lines)

    def __repr__(self):
        self.__setup()
        if len(self.__lines) <= self.MAXLINES:
            return "\n".join(self.__lines)
        else:
            return "Type %s() to see the full %s text" % ((self.__name,)*2)

    def __call__(self):
        self.__setup()
        prompt = 'Hit Return for more, or q (and Return) to quit: '
        lineno = 0
        while 1:
            try:
                for i in range(lineno, lineno + self.MAXLINES):
                    print self.__lines[i]
            except IndexError:
                break
            else:
                lineno += self.MAXLINES
                key = None
                while key is None:
                    key = raw_input(prompt)
                    if key not in ('', 'q'):
                        key = None
                if key == 'q':
                    break

def setcopyright():
    """Set 'copyright' and 'credits' in __builtin__"""
    __builtin__.copyright = _Printer("copyright", sys.copyright)
    if sys.platform[:4] == 'java':
        __builtin__.credits = _Printer(
            "credits",
            "Jython is maintained by the Jython developers (www.jython.org).")
    else:
        __builtin__.credits = _Printer("credits", """\
    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information.""")
    here = os.path.dirname(os.__file__)
    __builtin__.license = _Printer(
        "license", "See http://www.python.org/%.3s/license.html" % sys.version,
        ["LICENSE.txt", "LICENSE"],
        [os.path.join(here, os.pardir), here, os.curdir])

class _Helper(object):
    """Define the built-in 'help'.
    This is a wrapper around pydoc.help (with a twist).

    """

    def __repr__(self):
        return "Type help() for interactive help, " \
               "or help(object) for help about object."
    def __call__(self, *args, **kwds):
        import pydoc
        return pydoc.help(*args, **kwds)

def sethelper():
    __builtin__.help = _Helper()

def aliasmbcs():
    """On Windows, some default encodings are not provided by Python,
    while they are always available as "mbcs" in each locale. Make
    them usable by aliasing to "mbcs" in such a case."""
    if sys.platform == 'win32':
        import locale, codecs
        enc = locale.getdefaultlocale()[1]
        if enc.startswith('cp'):            # "cp***" ?
            try:
                codecs.lookup(enc)
            except LookupError:
                import encodings
                encodings._cache[enc] = encodings._unknown
                encodings.aliases.aliases[enc] = 'mbcs'

def setencoding():
    """Set the string encoding used by the Unicode implementation.  The
    default is 'ascii', but if you're willing to experiment, you can
    change this."""
    encoding = "ascii" # Default value set by _PyUnicode_Init()
    if 0:
        # Enable to support locale aware default string encodings.
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0:
        # Enable to switch off string to Unicode coercion and implicit
        # Unicode to string conversion.
        encoding = "undefined"
    if encoding != "ascii":
        # On Non-Unicode builds this will raise an AttributeError...
        sys.setdefaultencoding(encoding) # Needs Python Unicode build !

def execsitecustomize():
    """Run custom site specific code, if available."""
    try:
        import sitecustomize
    except ImportError:
        pass

def main():
    abs__file__()
    paths_in_sys = removeduppaths()
    if (os.name == "posix" and sys.path and
        os.path.basename(sys.path[-1]) == "Modules"):
        addbuilddir()
    paths_in_sys = addsitepackages(paths_in_sys)
    if sys.platform == 'os2emx':
        setBEGINLIBPATH()
    setquit()
    setcopyright()
    sethelper()
    aliasmbcs()
    setencoding()
    execsitecustomize()
    # Remove sys.setdefaultencoding() so that users cannot change the
    # encoding after initialization.  The test for presence is needed when
    # this module is run as a script, because this code is executed twice.
    if hasattr(sys, "setdefaultencoding"):
        del sys.setdefaultencoding

main()

def _test():
    print "sys.path = ["
    for dir in sys.path:
        print "    %r," % (dir,)
    print "]"

if __name__ == '__main__':
    _test()
<commit_msg>Fix a typo in patched site.py.<commit_after>"""Append module search paths for third-party packages to sys.path.

****************************************************************
* This module is automatically imported during initialization, *
* if you add the setuptools egg to PYTHONPATH (to support the  *
* simple non-root installation mode)                           *
****************************************************************

In earlier versions of Python (up to 1.5a3), scripts or modules that
needed to use site-specific modules would place ``import site''
somewhere near the top of their code.  Because of the automatic
import, this is no longer necessary (but code that does it still
works).

This will append site-specific paths to the module search path.  On
Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
appends lib/python<version>/site-packages as well as lib/site-python.
On other platforms (mainly Mac and Windows), it uses just sys.prefix
(and sys.exec_prefix, if different, but this is unlikely).  The
resulting directories, if they exist, are appended to sys.path, and
also inspected for path configuration files.

A path configuration file is a file whose name has the form
<package>.pth; its contents are additional directories (one per line)
to be added to sys.path.  Non-existing directories (or
non-directories) are never added to sys.path; no directory is added to
sys.path more than once.  Blank lines and lines beginning with
'#' are skipped. Lines starting with 'import' are executed.

For example, suppose sys.prefix and sys.exec_prefix are set to
/usr/local and there is a directory /usr/local/lib/python1.5/site-packages
with three subdirectories, foo, bar and spam, and two path
configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
following:

  # foo package configuration
  foo
  bar
  bletch

and bar.pth contains:

  # bar package configuration
  bar

Then the following directories are added to sys.path, in this order:

  /usr/local/lib/python1.5/site-packages/bar
  /usr/local/lib/python1.5/site-packages/foo

Note that bletch is omitted because it doesn't exist; bar precedes foo
because bar.pth comes alphabetically before foo.pth; and spam is
omitted because it is not mentioned in either path configuration file.

After these path manipulations, an attempt is made to import a module
named sitecustomize, which can perform arbitrary additional
site-specific customizations.  If this import fails with an
ImportError exception, it is silently ignored.

"""

import sys
import os
import __builtin__

def makepath(*paths):
    dir = os.path.abspath(os.path.join(*paths))
    return dir, os.path.normcase(dir)

def abs__file__():
    """Set all module' __file__ attribute to an absolute path"""
    for m in sys.modules.values():
        try:
            m.__file__ = os.path.abspath(m.__file__)
        except AttributeError:
            continue

def removeduppaths():
    """ Remove duplicate entries from sys.path along with making them
    absolute"""
    # This ensures that the initial path provided by the interpreter contains
    # only absolute pathnames, even if we're running from the build directory.
    L = []
    known_paths = {}
    for dir in sys.path:
        # Filter out duplicate paths (on case-insensitive file systems also
        # if they only differ in case); turn relative paths into absolute
        # paths.
        dir, dircase = makepath(dir)
        if not dircase in known_paths:
            L.append(dir)
            known_paths[dircase] = 1
    sys.path[:] = L
    return known_paths

# XXX This should not be part of site.py, since it is needed even when
# using the -S option for Python.  See http://www.python.org/sf/586680
def addbuilddir():
    """Append ./build/lib.<platform> in case we're running in the build dir
    (especially for Guido :-)"""
    from distutils.util import get_platform
    s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
    s = os.path.join(os.path.dirname(sys.path[-1]), s)
    sys.path.append(s)

def _init_pathinfo():
    """Return a set containing all existing directory entries from sys.path"""
    d = {}
    for dir in sys.path:
        try:
            if os.path.isdir(dir):
                dir, dircase = makepath(dir)
                d[dircase] = 1
        except TypeError:
            continue
    return d

def addpackage(sitedir, name, known_paths):
    """Add a new path to known_paths by combining sitedir and 'name' or execute
    sitedir if it starts with 'import'"""
    if known_paths is None:
        known_paths = _init_pathinfo()
        reset = 1
    else:
        reset = 0
    fullname = os.path.join(sitedir, name)
    try:
        f = open(fullname, "rU")
    except IOError:
        return
    try:
        for line in f:
            if line.startswith("#"):
                continue
            if line.startswith("import"):
                exec line
                continue
            line = line.rstrip()
            dir, dircase = makepath(sitedir, line)
            if not dircase in known_paths and os.path.exists(dir):
                sys.path.append(dir)
                known_paths[dircase] = 1
    finally:
        f.close()
    if reset:
        known_paths = None
    return known_paths

def addsitedir(sitedir, known_paths=None):
    """Add 'sitedir' argument to sys.path if missing and handle .pth files in
    'sitedir'"""
    if known_paths is None:
        known_paths = _init_pathinfo()
        reset = 1
    else:
        reset = 0
    sitedir, sitedircase = makepath(sitedir)
    if not sitedircase in known_paths:
        sys.path.append(sitedir)        # Add path component
    try:
        names = os.listdir(sitedir)
    except os.error:
        return
    names.sort()
    for name in names:
        if name.endswith(os.extsep + "pth"):
            addpackage(sitedir, name, known_paths)
    if reset:
        known_paths = None
    return known_paths

def addsitepackages(known_paths):
    """Add site-packages (and possibly site-python) to sys.path"""
    prefixes = [sys.prefix]
    if sys.exec_prefix != sys.prefix:
        prefixes.append(sys.exec_prefix)
    for prefix in prefixes:
        if prefix:
            if sys.platform in ('os2emx', 'riscos'):
                sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
            elif os.sep == '/':
                sitedirs = [os.path.join(prefix,
                                         "lib",
                                         "python" + sys.version[:3],
                                         "site-packages"),
                            os.path.join(prefix, "lib", "site-python")]
            else:
                sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
            if sys.platform == 'darwin':
                # for framework builds *only* we add the standard Apple
                # locations. Currently only per-user, but /Library and
                # /Network/Library could be added too
                if 'Python.framework' in prefix:
                    home = os.environ.get('HOME')
                    if home:
                        sitedirs.append(
                            os.path.join(home,
                                         'Library',
                                         'Python',
                                         sys.version[:3],
                                         'site-packages'))
            for sitedir in sys.path+sitedirs:
                if sitedir and os.path.isdir(sitedir):
                    addsitedir(sitedir, known_paths)
    return None

def setBEGINLIBPATH():
    """The OS/2 EMX port has optional extension modules that do double duty
    as DLLs (and must use the .DLL file extension) for other extensions.
    The library search path needs to be amended so these will be found
    during module import.  Use BEGINLIBPATH so that these are at the start
    of the library search path.

    """
    dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
    libpath = os.environ['BEGINLIBPATH'].split(';')
    if libpath[-1]:
        libpath.append(dllpath)
    else:
        libpath[-1] = dllpath
    os.environ['BEGINLIBPATH'] = ';'.join(libpath)

def setquit():
    """Define new built-ins 'quit' and 'exit'.
    These are simply strings that display a hint on how to exit.

    """
    if os.sep == ':':
        exit = 'Use Cmd-Q to quit.'
    elif os.sep == '\\':
        exit = 'Use Ctrl-Z plus Return to exit.'
    else:
        exit = 'Use Ctrl-D (i.e. EOF) to exit.'
    __builtin__.quit = __builtin__.exit = exit

class _Printer(object):
    """interactive prompt objects for printing the license text, a list of
    contributors and the copyright notice."""

    MAXLINES = 23

    def __init__(self, name, data, files=(), dirs=()):
        self.__name = name
        self.__data = data
        self.__files = files
        self.__dirs = dirs
        self.__lines = None

    def __setup(self):
        if self.__lines:
            return
        data = None
        for dir in self.__dirs:
            for filename in self.__files:
                filename = os.path.join(dir, filename)
                try:
                    fp = file(filename, "rU")
                    data = fp.read()
                    fp.close()
                    break
                except IOError:
                    pass
            if data:
                break
        if not data:
            data = self.__data
        self.__lines = data.split('\n')
        self.__linecnt = len(self.__lines)

    def __repr__(self):
        self.__setup()
        if len(self.__lines) <= self.MAXLINES:
            return "\n".join(self.__lines)
        else:
            return "Type %s() to see the full %s text" % ((self.__name,)*2)

    def __call__(self):
        self.__setup()
        prompt = 'Hit Return for more, or q (and Return) to quit: '
        lineno = 0
        while 1:
            try:
                for i in range(lineno, lineno + self.MAXLINES):
                    print self.__lines[i]
            except IndexError:
                break
            else:
                lineno += self.MAXLINES
                key = None
                while key is None:
                    key = raw_input(prompt)
                    if key not in ('', 'q'):
                        key = None
                if key == 'q':
                    break

def setcopyright():
    """Set 'copyright' and 'credits' in __builtin__"""
    __builtin__.copyright = _Printer("copyright", sys.copyright)
    if sys.platform[:4] == 'java':
        __builtin__.credits = _Printer(
            "credits",
            "Jython is maintained by the Jython developers (www.jython.org).")
    else:
        __builtin__.credits = _Printer("credits", """\
    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information.""")
    here = os.path.dirname(os.__file__)
    __builtin__.license = _Printer(
        "license", "See http://www.python.org/%.3s/license.html" % sys.version,
        ["LICENSE.txt", "LICENSE"],
        [os.path.join(here, os.pardir), here, os.curdir])

class _Helper(object):
    """Define the built-in 'help'.
    This is a wrapper around pydoc.help (with a twist).

    """

    def __repr__(self):
        return "Type help() for interactive help, " \
               "or help(object) for help about object."
    def __call__(self, *args, **kwds):
        import pydoc
        return pydoc.help(*args, **kwds)

def sethelper():
    __builtin__.help = _Helper()

def aliasmbcs():
    """On Windows, some default encodings are not provided by Python,
    while they are always available as "mbcs" in each locale. Make
    them usable by aliasing to "mbcs" in such a case."""
    if sys.platform == 'win32':
        import locale, codecs
        enc = locale.getdefaultlocale()[1]
        if enc.startswith('cp'):            # "cp***" ?
            try:
                codecs.lookup(enc)
            except LookupError:
                import encodings
                encodings._cache[enc] = encodings._unknown
                encodings.aliases.aliases[enc] = 'mbcs'

def setencoding():
    """Set the string encoding used by the Unicode implementation.  The
    default is 'ascii', but if you're willing to experiment, you can
    change this."""
    encoding = "ascii" # Default value set by _PyUnicode_Init()
    if 0:
        # Enable to support locale aware default string encodings.
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0:
        # Enable to switch off string to Unicode coercion and implicit
        # Unicode to string conversion.
        encoding = "undefined"
    if encoding != "ascii":
        # On Non-Unicode builds this will raise an AttributeError...
        sys.setdefaultencoding(encoding) # Needs Python Unicode build !

def execsitecustomize():
    """Run custom site specific code, if available."""
    try:
        import sitecustomize
    except ImportError:
        pass

def main():
    abs__file__()
    paths_in_sys = removeduppaths()
    if (os.name == "posix" and sys.path and
        os.path.basename(sys.path[-1]) == "Modules"):
        addbuilddir()
    paths_in_sys = addsitepackages(paths_in_sys)
    if sys.platform == 'os2emx':
        setBEGINLIBPATH()
    setquit()
    setcopyright()
    sethelper()
    aliasmbcs()
    setencoding()
    execsitecustomize()
    # Remove sys.setdefaultencoding() so that users cannot change the
    # encoding after initialization.  The test for presence is needed when
    # this module is run as a script, because this code is executed twice.
    if hasattr(sys, "setdefaultencoding"):
        del sys.setdefaultencoding

main()

def _test():
    print "sys.path = ["
    for dir in sys.path:
        print "    %r," % (dir,)
    print "]"

if __name__ == '__main__':
    _test()
<|endoftext|>


<commit_before>#!/usr/bin/env python

"""
Sith attacks (and helps debugging) Jedi.

Randomly search Python files and run Jedi on it.  Exception and used
arguments are recorded to ``./record.json`` (specified by --record)::

    ./sith.py random /path/to/sourcecode

Redo recorded exception::

    ./sith.py redo

Show recorded exception::

    ./sith.py show

Run a specific operation

    ./sith.py run <operation> </path/to/source/file.py> <line> <col>

Where operation is one of completions, goto_assignments, goto_definitions,
usages, or call_signatures.

Note: Line numbers start at 1; columns start at 0 (this is consistent with
many text editors, including Emacs).

Usage:
  sith.py [--pdb|--ipdb|--pudb] [-d] [-n=<nr>] [-f] [--record=<file>] random [<path>]
  sith.py [--pdb|--ipdb|--pudb] [-d] [-f] [--record=<file>] redo
  sith.py [--pdb|--ipdb|--pudb] [-d] [-f] run <operation> <path> <line> <column>
  sith.py show [--record=<file>]
  sith.py -h | --help

Options:
  -h --help             Show this screen.
  --record=<file>       Exceptions are recorded in here [default: record.json].
  -f, --fs-cache        By default, file system cache is off for reproducibility.
  -n, --maxtries=<nr>   Maximum of random tries [default: 100]
  -d, --debug           Jedi print debugging when an error is raised.
  --pdb                 Launch pdb when error is raised.
  --ipdb                Launch ipdb when error is raised.
  --pudb                Launch pudb when error is raised.
"""

from __future__ import print_function, division, unicode_literals
from docopt import docopt

import json
import os
import random
import sys
import traceback

import jedi

class SourceFinder(object):
    _files = None

    @staticmethod
    def fetch(file_path):
        for root, dirnames, filenames in os.walk(file_path):
            for name in filenames:
                if name.endswith('.py'):
                    yield os.path.join(root, name)

    @classmethod
    def files(cls, file_path):
        if cls._files is None:
            cls._files = list(cls.fetch(file_path))
        return cls._files

class TestCase(object):
    def __init__(self, operation, path, line, column, traceback=None):
        if operation not in self.operations:
            raise ValueError("%s is not a valid operation" % operation)
        self.operation = operation
        self.path = path
        self.line = line
        self.column = column
        self.traceback = traceback

    @classmethod
    def from_cache(cls, record):
        with open(record) as f:
            dct = json.load(f)
        return cls(**dct)

    operations = [
        'completions', 'goto_assignments', 'goto_definitions', 'usages',
        'call_signatures']

    @classmethod
    def generate(cls, file_path):
        operation = random.choice(cls.operations)

        path = random.choice(SourceFinder.files(file_path))
        with open(path) as f:
            source = f.read()
            lines = source.splitlines()

        if not lines:
            lines = ['']
        line = random.randint(1, len(lines))
        column = random.randint(0, len(lines[line - 1]))
        return cls(operation, path, line, column)

    def run(self, debugger, record=None, print_result=False):
        try:
            with open(self.path) as f:
                self.file = f.read()
            self.script = jedi.Script(self.file, self.line, self.column,
                self.path)
            self.completions = getattr(self.script, self.operation)()
            if print_result:
                self.show_location(self.line, self.column)
                self.show_operation()
        except jedi.NotFoundError:
            pass
        except Exception:
            self.traceback = traceback.format_exc()
            if record is not None:
                with open(record, 'w') as f:
                    json.dump(self.__dict__, f)
            self.show_errors()
            if debugger:
                einfo = sys.exc_info()
                pdb = __import__(debugger)
                if debugger == 'pudb':
                    pdb.post_mortem(einfo[2], einfo[0], einfo[1])
                else:
                    pdb.post_mortem(einfo[2])
            exit(1)

    def show_location(self, lineno, column, show=3):
        # Three lines ought to be enough
        lower = lineno - show if lineno - show > 0 else 0
        for i, line in enumerate(self.file.split('\n')[lower:lineno]):
            print(lower + i + 1, line)
        print(' ' * (column + len(str(lineno))), '^')

    def show_operation(self):
        print("%s:\n" % self.operation.capitalize())
        getattr(self, 'show_' + self.operation)()

    def show_completions(self):
        for completion in self.completions:
            print(completion.name)

    # TODO: Support showing the location in other files

    # TODO: Move this printing to the completion objects themselves
    def show_usages(self):
        for completion in self.completions:
            print(completion.description)
            if os.path.abspath(completion.module_path) == os.path.abspath(self.path):
                self.show_location(completion.line, completion.column)

    def show_call_signatures(self):
        for completion in self.completions:
            # This is too complicated to print. It really should be
            # implemented in str() anyway.
            print(completion)
            # Can't print the location here because we don't have the module path

    def show_goto_definitions(self):
        for completion in self.completions:
            print(completion.desc_with_module)
            if os.path.abspath(completion.module_path) == os.path.abspath(self.path):
                self.show_location(completion.line, completion.column)

    show_goto_assignments =  show_goto_definitions

    def show_errors(self):
        print(self.traceback)
        print(("Error with running Script(...).{operation}() with\n"
              "\tpath:   {path}\n"
              "\tline:   {line}\n"
              "\tcolumn: {column}").format(**self.__dict__))

def main(arguments):
    debugger = 'pdb' if arguments['--pdb'] else \
               'ipdb' if arguments['--ipdb'] else \
               'pudb' if arguments['--pudb'] else None
    record = arguments['--record']

    jedi.settings.use_filesystem_cache = arguments['--fs-cache']
    if arguments['--debug']:
        jedi.set_debug_function()

    if  arguments['redo'] or arguments['show']:
        t = TestCase.from_cache(record)
        if arguments['show']:
            t.show_errors()
        else:
            t.run(debugger)
    elif arguments['run']:
            TestCase(arguments['<operation>'], arguments['<path>'],
                int(arguments['<line>']), int(arguments['<column>'])
                ).run(debugger, print_result=True)
    else:
        for _ in range(int(arguments['--maxtries'])):
            t = TestCase.generate(arguments['<path>'] or '.')
            t.run(debugger, record)
            print('.', end='')
            sys.stdout.flush()
        print()

if __name__ == '__main__':
    arguments = docopt(__doc__)
    main(arguments)
<commit_msg>fix unicode problems in sith.py<commit_after>#!/usr/bin/env python

"""
Sith attacks (and helps debugging) Jedi.

Randomly search Python files and run Jedi on it.  Exception and used
arguments are recorded to ``./record.json`` (specified by --record)::

    ./sith.py random /path/to/sourcecode

Redo recorded exception::

    ./sith.py redo

Show recorded exception::

    ./sith.py show

Run a specific operation

    ./sith.py run <operation> </path/to/source/file.py> <line> <col>

Where operation is one of completions, goto_assignments, goto_definitions,
usages, or call_signatures.

Note: Line numbers start at 1; columns start at 0 (this is consistent with
many text editors, including Emacs).

Usage:
  sith.py [--pdb|--ipdb|--pudb] [-d] [-n=<nr>] [-f] [--record=<file>] random [<path>]
  sith.py [--pdb|--ipdb|--pudb] [-d] [-f] [--record=<file>] redo
  sith.py [--pdb|--ipdb|--pudb] [-d] [-f] run <operation> <path> <line> <column>
  sith.py show [--record=<file>]
  sith.py -h | --help

Options:
  -h --help             Show this screen.
  --record=<file>       Exceptions are recorded in here [default: record.json].
  -f, --fs-cache        By default, file system cache is off for reproducibility.
  -n, --maxtries=<nr>   Maximum of random tries [default: 100]
  -d, --debug           Jedi print debugging when an error is raised.
  --pdb                 Launch pdb when error is raised.
  --ipdb                Launch ipdb when error is raised.
  --pudb                Launch pudb when error is raised.
"""

from __future__ import print_function, division, unicode_literals
from docopt import docopt

import json
import os
import random
import sys
import traceback

import jedi

class SourceFinder(object):
    _files = None

    @staticmethod
    def fetch(file_path):
        for root, dirnames, filenames in os.walk(file_path):
            for name in filenames:
                if name.endswith('.py'):
                    yield os.path.join(root, name)

    @classmethod
    def files(cls, file_path):
        if cls._files is None:
            cls._files = list(cls.fetch(file_path))
        return cls._files

class TestCase(object):
    def __init__(self, operation, path, line, column, traceback=None):
        if operation not in self.operations:
            raise ValueError("%s is not a valid operation" % operation)
        self.operation = operation
        self.path = path
        self.line = line
        self.column = column
        self.traceback = traceback

    @classmethod
    def from_cache(cls, record):
        with open(record) as f:
            dct = json.load(f)
        return cls(**dct)

    operations = [
        'completions', 'goto_assignments', 'goto_definitions', 'usages',
        'call_signatures']

    @classmethod
    def generate(cls, file_path):
        operation = random.choice(cls.operations)

        path = random.choice(SourceFinder.files(file_path))
        with open(path) as f:
            source = f.read()
            lines = source.splitlines()

        if not lines:
            lines = ['']
        line = random.randint(1, len(lines))
        column = random.randint(0, len(lines[line - 1]))
        return cls(operation, path, line, column)

    def run(self, debugger, record=None, print_result=False):
        try:
            with open(self.path) as f:
                self.script = jedi.Script(f.read(), self.line, self.column, self.path)
            self.completions = getattr(self.script, self.operation)()
            if print_result:
                self.show_location(self.line, self.column)
                self.show_operation()
        except jedi.NotFoundError:
            pass
        except Exception:
            self.traceback = traceback.format_exc()
            if record is not None:
                with open(record, 'w') as f:
                    json.dump(self.__dict__, f)
            self.show_errors()
            if debugger:
                einfo = sys.exc_info()
                pdb = __import__(debugger)
                if debugger == 'pudb':
                    pdb.post_mortem(einfo[2], einfo[0], einfo[1])
                else:
                    pdb.post_mortem(einfo[2])
            exit(1)

    def show_location(self, lineno, column, show=3):
        # Three lines ought to be enough
        lower = lineno - show if lineno - show > 0 else 0
        for i, line in enumerate(self.script.source.split('\n')[lower:lineno]):
            print(lower + i + 1, line)
        print(' ' * (column + len(str(lineno))), '^')

    def show_operation(self):
        print("%s:\n" % self.operation.capitalize())
        getattr(self, 'show_' + self.operation)()

    def show_completions(self):
        for completion in self.completions:
            print(completion.name)

    # TODO: Support showing the location in other files

    # TODO: Move this printing to the completion objects themselves
    def show_usages(self):
        for completion in self.completions:
            print(completion.description)
            if os.path.abspath(completion.module_path) == os.path.abspath(self.path):
                self.show_location(completion.line, completion.column)

    def show_call_signatures(self):
        for completion in self.completions:
            # This is too complicated to print. It really should be
            # implemented in str() anyway.
            print(completion)
            # Can't print the location here because we don't have the module path

    def show_goto_definitions(self):
        for completion in self.completions:
            print(completion.desc_with_module)
            if os.path.abspath(completion.module_path) == os.path.abspath(self.path):
                self.show_location(completion.line, completion.column)

    show_goto_assignments =  show_goto_definitions

    def show_errors(self):
        print(self.traceback)
        print(("Error with running Script(...).{operation}() with\n"
              "\tpath:   {path}\n"
              "\tline:   {line}\n"
              "\tcolumn: {column}").format(**self.__dict__))

def main(arguments):
    debugger = 'pdb' if arguments['--pdb'] else \
               'ipdb' if arguments['--ipdb'] else \
               'pudb' if arguments['--pudb'] else None
    record = arguments['--record']

    jedi.settings.use_filesystem_cache = arguments['--fs-cache']
    if arguments['--debug']:
        jedi.set_debug_function()

    if  arguments['redo'] or arguments['show']:
        t = TestCase.from_cache(record)
        if arguments['show']:
            t.show_errors()
        else:
            t.run(debugger)
    elif arguments['run']:
            TestCase(arguments['<operation>'], arguments['<path>'],
                int(arguments['<line>']), int(arguments['<column>'])
                ).run(debugger, print_result=True)
    else:
        for _ in range(int(arguments['--maxtries'])):
            t = TestCase.generate(arguments['<path>'] or '.')
            t.run(debugger, record)
            print('.', end='')
            sys.stdout.flush()
        print()

if __name__ == '__main__':
    arguments = docopt(__doc__)
    main(arguments)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Application serveur JPO IUT Auxerre
#
# Le programme "serveur" accepte les connexions d'une liste prédéfinie de clients possibles
# et leur donne la main à tour de rôle, un peu comme un jeton dans un "token ring".
#
# (c)2010eB@uB

# python JPOsrvr.py port_number

import socket # Module réseau local TCP/IP
import thread # Module de gestion des sous-processus
import sys
from Tkinter import *
from time import sleep

# Message de bienvenue...
print "Bienvenue dans l'application JPO Auxerre: coté serveur"

# set up Internet TCP socket
lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

port = int(sys.argv[1])  # server port number
# bind lstn socket to this port
lstn.bind(('', port))
# start listening for contacts from clients
lstn.listen(5)

# Liste des IP des clients
hosts = []

# Nombre de clients requis
N=2

# Clients connectés
chosts = []
clock = thread.allocate_lock()

# Ecoute des demandes de connexion des clients tant que tous ne sont
# pas connectés

liste_client = {}

while len(hosts)<N:
	(clnt,ap) = lstn.accept()
	client = clnt.getpeername()
	print "Demande de connexion ",client
	hosts.append( client )
	# Teste si le client est un client autorisé
	if client in hosts:
		print( 'Demande de connexion de {}:{}'.format( *client ) )
		# Teste si le client est déjà connecté
		if client in chosts:
			print "Client déjà connecté"
			print "Demande de connexion rejetée"
		else:
			print "Demande acceptée sur Port %s" % client[1]
			liste_client[client]=clnt
	else:
		print "Tentative de connexion d'un poste inconnu "+client[0]
		print "Demande de connexion rejetée"

print "Tous les clients sont connectés, l'application est opérationelle"

# Fermeture du port d'écoute principal
lstn.close()

root = Tk()
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
# test
print "screen width  =", sw
print "screen height =", sh

# initialisation des coordonnées, des vitesses et du témoin d'animation :
x, y, v, dx, dv = 50, 50, 0, 12, 5
sh = sh - 100 - 30

while 1:
#   print "Calcul de l'itération suivante"
   xp, yp = x, y            # mémorisation des coord. précédentes
   # déplacement horizontal :
   if x > N*sw or x < 0 :     # rebond sur les parois latérales :
      dx = -dx             # on inverse le déplacement
   x = x + dx
   # variation de la vitesse verticale (toujours vers le bas):
   v = v + dv
   # déplacement vertical (proportionnel à la vitesse)
   y = y + v
   if y > sh:              # niveau du sol à 240 pixels :
      y = sh             #  défense d'aller + loin !
      v = -v               # rebond : la vitesse s'inverse
   n=0
   for chost in hosts:
      print( 'Coordonnées ({},{}) envoyées à {}:{}'.format( x, y, *chost ) )
      clnt=liste_client[chost]
      clnt.send("%d,%d.\n" % (x-n*sw,y))
      n=n+1
   sleep(0.03)

# Attente de la déconnexion de tous les clients
while len(chosts) > 0: pass
print "Done"
<commit_msg>Remove Tkinter dependency from the server side.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Application serveur JPO IUT Auxerre
#
# Le programme "serveur" accepte les connexions d'une liste prédéfinie de clients possibles
# et leur donne la main à tour de rôle, un peu comme un jeton dans un "token ring".
#
# (c)2010eB@uB

# python JPOsrvr.py port_number

import socket # Module réseau local TCP/IP
import thread # Module de gestion des sous-processus
import sys
from time import sleep

# Message de bienvenue...
print "Bienvenue dans l'application JPO Auxerre: coté serveur"

# set up Internet TCP socket
lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

port = int(sys.argv[1])  # server port number
# bind lstn socket to this port
lstn.bind(('', port))
# start listening for contacts from clients
lstn.listen(5)

# Liste des IP des clients
hosts = []

# Nombre de clients requis
N=2

# Clients connectés
chosts = []
clock = thread.allocate_lock()

# Ecoute des demandes de connexion des clients tant que tous ne sont
# pas connectés

liste_client = {}

while len(hosts)<N:
	(clnt,ap) = lstn.accept()
	client = clnt.getpeername()
	print "Demande de connexion ",client
	hosts.append( client )
	# Teste si le client est un client autorisé
	if client in hosts:
		print( 'Demande de connexion de {}:{}'.format( *client ) )
		# Teste si le client est déjà connecté
		if client in chosts:
			print "Client déjà connecté"
			print "Demande de connexion rejetée"
		else:
			print "Demande acceptée sur Port %s" % client[1]
			liste_client[client]=clnt
	else:
		print "Tentative de connexion d'un poste inconnu "+client[0]
		print "Demande de connexion rejetée"

print "Tous les clients sont connectés, l'application est opérationelle"

# Fermeture du port d'écoute principal
lstn.close()

sw = 1920
sh = 1200
# test
print "screen width  =", sw
print "screen height =", sh

# initialisation des coordonnées, des vitesses et du témoin d'animation :
x, y, v, dx, dv = 50, 50, 0, 12, 5
sh = sh - 100 - 30

while 1:
#   print "Calcul de l'itération suivante"
   xp, yp = x, y            # mémorisation des coord. précédentes
   # déplacement horizontal :
   if x > N*sw or x < 0 :     # rebond sur les parois latérales :
      dx = -dx             # on inverse le déplacement
   x = x + dx
   # variation de la vitesse verticale (toujours vers le bas):
   v = v + dv
   # déplacement vertical (proportionnel à la vitesse)
   y = y + v
   if y > sh:              # niveau du sol à 240 pixels :
      y = sh             #  défense d'aller + loin !
      v = -v               # rebond : la vitesse s'inverse
   n=0
   for chost in hosts:
      print( 'Coordonnées ({},{}) envoyées à {}:{}'.format( x, y, *chost ) )
      clnt=liste_client[chost]
      clnt.send("%d,%d.\n" % (x-n*sw,y))
      n=n+1
   sleep(0.03)

# Attente de la déconnexion de tous les clients
while len(chosts) > 0: pass
print "Done"
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (c) 2017, Geoffrey M. Poore
# All rights reserved.
#
# Licensed under the BSD 3-Clause License:
# http://opensource.org/licenses/BSD-3-Clause
#

'''
Abstract syntax tree (AST) elements.
'''

# pylint: disable=C0103
from __future__ import (division, print_function, absolute_import,
                        unicode_literals)

from . import erring
import sys

# pylint: disable=E0602, W0622
if sys.version_info.major == 2:
    str = unicode
    __chr__ = chr
    chr = unichr
# pylint: enable=E0602, W0622

_astobj_common_slots = ['ast',
                        'cat', 'tag',
                        'depth', 'parent', 'index',
                        'indent', 'at_line_start', 'inline', 'inline_indent',
                        'first_lineno', 'first_column',
                        'last_lineno', 'last_column',
                        'finalized', 'final_val', 'extra_dependents']

_astobj_stringlike_slots = ['delim', 'block']

_astobj_collection_slots = ['keypath_parent', 'keypath_traversable',
                            'open', 'unresolved_children',
                            'check_append_scalar_key',
                            'check_append_scalar_val',
                            'check_append_collection',
                            'check_append_keypath']

_astobj_dictlike_slots = ['next_key', 'awaiting_val']

_astobj_tag_slots = ['type', 'mutable', 'placeholder_obj',
                     'label', 'newline',
                     'collection_config_type', 'collection_config_args']
<commit_msg>working on ast<commit_after># -*- coding: utf-8 -*-
#
# Copyright (c) 2017, Geoffrey M. Poore
# All rights reserved.
#
# Licensed under the BSD 3-Clause License:
# http://opensource.org/licenses/BSD-3-Clause
#

'''
Abstract syntax tree (AST) elements.
'''

# pylint: disable=C0301

from __future__ import (division, print_function, absolute_import,
                        unicode_literals)

from . import erring
import sys
import collections

# pylint: disable=E0602, W0622
if sys.version_info.major == 2:
    str = unicode
    __chr__ = chr
    chr = unichr
# pylint: enable=E0602, W0622

_astobj_common_slots = ['basetype',
                        'indent', 'at_line_start',
                        'inline', 'inline_indent',
                        'first_lineno', 'first_column',
                        'last_lineno', 'last_column']

_astobj_scalar_or_collection_slots = ['tag', 'parent', 'index',
                                      'resolved', 'final_val',
                                      'extra_dependents']

_astobj_scalar_slots = ['delim', 'block', 'implicit_type']

_astobj_collection_slots = ['keypath_parent', 'keypath_traversable',
                            'open', 'unresolved_child_count',
                            'check_append_scalar_key',
                            'check_append_scalar_val',
                            'check_append_collection',
                            'check_append_keypath']

_astobj_dict_slots = ['next_key', 'awaiting_val']

_astobj_tag_slots = ['type', 'compatible_basetypes', 'label', 'newline',
                     'collection_config_type', 'collection_config_val'
                     'resolved']

_astobj_root_slots = ['source']

class SourceAstObj(object):
    '''
    The highest-level node in the AST, representing the string, file, or
    stream in which bespon data is embedded.

    In some cases, it would be possible to collapse the functionality of the
    source node and the root node into a single node.  The two are separated
    because this makes the handling of a tag for the root node more parallel
    with normal tags (the tag is external to the node).  Having a source
    node also makes it convenient to distinguish between where bespon content
    begins and ends, versus where the actual data begins and ends
    (for example, there may be comments before or after the data).
    '''
    basetype = 'source'

    def __init__(self, state):
        self.source = state.source
        self.source_depth = state.source_depth
        self.full_ast = state.full_ast

        self.indent = state.indent
        self.at_line_start = state.at_line_start
        self.inline = state.inline
        self.inline_indent = state.inline_indent
        self.first_lineno = state.first_lineno
        self.first_column = state.first_column
        self.last_lineno = state.last_lineno
        self.last_column = state.last_column

        self.root = None

    def check_append_root(self, root):
        if self.root is not None:
            raise erring.Bug('Only a single root-level node is allowed')
        root.parent = self
        self.root = root
        self.last_lineno = root.last_lineno
        self.last_column = root.last_column

class RootAstObj(list):
    '''
    Lowest level in the AST except for the source node.  A list subclass that
    must ultimately contain only a single element.
    '''
    basetype = 'root'

    def __init__(self, state):
        list.__init__(self)

        self.tag = state.root_tag
        self.closing_tag = None
        self.unresolved_child_count = 0

        self.indent = state.indent
        self.at_line_start = state.at_line_start
        self.inline = state.inline
        self.inline_indent = state.inline_indent
        self.first_lineno = state.first_lineno
        self.first_column = state.first_column
        self.last_lineno = state.last_lineno
        self.last_column = state.last_column

    def check_append_scalar_key(self, obj):
        raise erring.Bug('Only a single scalar or collection object is allowed at root level', obj)

    def check_append_scalar_val(self, obj, full_ast=False):
        if len(self) == 1:
            raise erring.ParseError('Only a single scalar or collection object is allowed at root level', obj)
        # May need to revise consistency checks once add full support for
        # embedded parsing
        if not obj.external_indent.startswith(self.indent):
            raise erring.IndentationError(obj)
        if obj.resolved and not full_ast:
            self.append(obj.final_val)
        else:
            obj.parent = self
            obj.index = len(self)
            self.append(obj)
            if not obj.resolved:
                self.unresolved_child_count += 1
        self.last_lineno = obj.last_lineno
        self.last_column = obj.last_column

    def check_append_collection(self, obj):
        if len(self) == 1:
            raise erring.ParseError('Only a single scalar or collection object is allowed at root level', obj)
        # May need to revise consistency checks once add full support for
        # embedded parsing
        if not obj.external_indent.startswith(self.indent):
            raise erring.IndentationError(obj)
        obj.parent = self
        obj.index = len(self)
        self.append(obj)
        self.unresolved_child_count += 1
        self.last_lineno = obj.last_lineno
        self.last_column = obj.last_column

def _init_common(self, state):
    '''
    Shared initialization for all AST nodes below root level.
    '''
    self.tag = state.tag
    state.tag = None

    self.indent = state.indent
    self.at_line_start = state.at_line_start
    self.inline = state.inline
    self.inline_indent = state.inline_indent
    self.first_lineno = state.first_lineno
    self.first_column = state.first_column
    self.last_lineno = state.last_lineno
    self.last_column = state.last_column

    if self.tag is None:
        # If there is no tag, the external appearance of the object is
        # identical to that of the object itself.  There is no need to
        # perform indentation checks, since these will be done when the
        # object is appended to the AST.
        self.external_indent = self.indent
        self.external_at_line_start = self.at_line_start
        self.external_first_lineno = self.first_lineno
    else:
        # If there is a tag, it sets the external appearance of the object.
        # The tag's indentation will be checked upon appending to the AST,
        # so it doesn't need to be checked.  But the object itself needs to
        # be checked here for consistency with the tag.
        #
        # In checking indentation, don't need to consider the case of
        # `.at_line_start = False` due to a leading inline comment.  In
        # non-inline mode, the comment parser automatically produces an error
        # for that case.
        #
        # For non-inline collections, there is no need to check for a first
        # element that is on the same line as the tag.  In a list, the `*`
        # will check for `.at_line_start = True`.  In a dict, a key will
        # perform the same check.  It is necessary to make sure that the tag
        # is at the beginning of the line, though.
        tag = self.tag
        if self.basetype not in tag.compatible_basetypes:
            raise erring.TagError(tag)
        if self.inline:
            if not self.indent.startswith(self.inline_indent):
                raise erring.IndentationError(self)
        elif tag.at_line_start:
            if not self.indent.startswith(tag.indent):
                raise erring.IndentationError(self)
        else:
            if self.at_line_start and (len(self.indent) <= len(tag.indent) or not self.indent.startswith(tag.indent)):
                raise erring.IndentationError(self)
            if self.basetype in ('dict', 'list'):
                raise erring.ParseError('The tag for a non-inline collection must be at the start of a line', tag)
        self.external_indent = tag.indent
        self.external_at_line_start = tag.at_line_start
        self.external_first_lineno = tag.first_lineno

    self.resolved = False
    self.extra_dependents = None
    # Some attributes are not given default values, to ensure that any
    # incorrect attempt to access them results in an error.  `.parent`
    # and `.index` exist for all objects except for dict keys.  `.final_val`
    # should only ever be accessed after a check of `.resolved`.

class ScalarAstObj(object):
    '''
    Scalar object, including quoted (delim, block) and unquoted strings,
    none, bool, int, and float.
    '''
    basetype = 'scalar'
    __slots__ = (_astobj_common_slots + _astobj_scalar_or_collection_slots +
                 _astobj_scalar_slots)

    def __init__(self, state, init_common=_init_common,
                 delim=None, block=None, implicit_type=None):
        init_common(self, state)
        self.delim = delim
        self.block = block
        self.implicit_type = implicit_type

    def __hash__(self):
        # The only time a scalar will need a hash is when it is used as a
        # dict key, and in that case it must already be resolved.
        return hash(self.final_val)

    def __eq__(self, other):
        return self.final_val == other.final_val

# Individual element in a keypath
KeypathElement = collections.namedtuple('KeypathElement', ['type', 'val'])

class Keypath(ScalarAstObj):
    '''
    Abstract keypath.

    Used as dict keys or in sections for assigning in nested objects; in
    tag for representing collection config; and (with a tag) to represent
    alias, copy, and deepcopy.
    '''
    basetype = 'keypath'
    __slots__ = ['keypath']

class ListlikeAstObj(list):
    '''
    List-like collection.
    '''
    basetype = 'list'
    __slots__ = (_astobj_common_slots + _astobj_scalar_or_collection_slots +
                 _astobj_collection_slots +
                 ['internal_indent_immediate, internal_indent_later'])

    def __init__(self, state, init_common=_init_common,
                 keypath_parent=None, keypath_traversable=False):
        list.__init__(self)

        self.keypath_parent = keypath_parent
        self.keypath_travesable = keypath_traversable
        self.unresolved_child_count = 0
        if keypath_traversable:
            # A collection created implicitly as part of a keypath lacks most
            # standard attributes, so they are never created.  There is no
            # need to check for an unused `state.tag`, because the only way
            # to create an implicit collection is with a keypath, and a
            # keypath would resolve any existing tag.  An implicit collection
            # is always open.
            self.open = True
        else:
            init_common(self, state)
            self.open = False
            if not self.inline:
                self.internal_indent_immediate = None
                self.internal_indent_later = None

        if self.inline:
            self.check_append_scalar_val = self._check_append_scalar_val_inline
            self.check_append_collection = self._check_append_collection_inline
        else:
            self.check_append_scalar_val = self._check_append_scalar_val_noninline
            self.check_append_collection = self._check_append_collection_noninline

    def check_append_scalar_key(self, obj, full_ast=False):
        raise erring.ParseError('Cannot append a key-value pair directly to a list-like object', obj)

    def _check_append_scalar_val_inline(self, obj, full_ast=False):
        if not self.open:
            raise erring.ParseError('Cannot append to a list-like object that was not open for appending', obj)
        if not obj.external_indent.startswith(self.inline_indent):
            raise erring.IndentationError(obj)
        if obj.resolved and not full_ast:
            self.append(obj.final_val)
        else:
            obj.parent = self
            obj.index = len(self)
            self.append(obj)
            if not obj.resolved:
                self.unresolved_child_count += 1
        self.last_lineno = obj.last_lineno
        self.last_column = obj.last_column
        self.open = False

    def _check_append_collection_inline(self, obj):
        if not self.open:
            raise erring.ParseError('Cannot append to a list-like object that was not open for appending', obj)
        if not obj.external_indent.startswith(self.inline_indent):
            raise erring.IndentationError(obj)
        obj.parent = self
        obj.index = len(self)
        self.append(obj)
        self.unresolved_child_count += 1
        self.last_lineno = obj.last_lineno
        self.last_column = obj.last_column
        self.open = False

    def _set_internal_indent(self, obj):
        if len(obj.external_indent) <= len(self.indent) or not obj.external_indent.startswith(self.indent):
            raise erring.IndentationError(obj)
        extra_indent = obj.external_indent[len(self.indent):]
        if obj.external_first_lineno == self.last_lineno:
            # The non-inline list opener `*` does not affect `at_line_start`
            # and is treated as a space for the purpose of calculating the
            # overall indent of objects following it on the same line.  If
            # the `*` (which will be represented by a space in `self.indent`)
            # is adjacent to tabs on both sides, then it is not counted
            if self.indent.endswith('\t') and extra_indent[1:2] == '\t':
                self.internal_indent_immediate = obj.external_indent
                self.internal_indent_later = self.indent + extra_indent[1:]
            else:
                self.internal_indent_immediate = self.internal_indent_later = obj.external_indent
        else:
            if self.indent.endswith('\t') and extra_indent[:1] == '\t':
                self.internal_indent_immediate = self.indent + '\x20' + extra_indent
                self.internal_indent_later = obj.external_indent
            else:
                self.internal_indent_immediate = self.internal_indent_later = obj.external_indent

    def _check_append_scalar_val_noninline(self, obj, full_ast=False):
        if not self.open:
            raise erring.ParseError('Cannot append to a list-like object that was not open for appending', obj)
        if self.internal_indent_immediate is None:
            self._set_internal_indent(obj)
        if obj.first_lineno == self.last_lineno:
            if obj.external_indent != self.internal_indent_immediate:
                raise erring.IndentationError(obj)
        elif obj.external_indent != self.internal_indent_later:
            raise erring.IndentationError(obj)
        if obj.resolved and not full_ast:
            self.append(obj.final_val)
        else:
            obj.parent = self
            obj.index = len(self)
            self.append(obj)
            if not obj.resolved:
                self.unresolved_child_count += 1
        self.last_lineno = obj.last_lineno
        self.last_column = obj.last_column
        self.open = False

    def _check_append_collection_noninline(self, obj):
        if not self.open:
            raise erring.ParseError('Cannot append to a list-like object that was not open for appending', obj)
        if self.internal_indent_immediate is None:
            self._set_internal_indent(obj)
        if obj.first_lineno == self.last_lineno:
            if obj.external_indent != self.internal_indent_immediate:
                raise erring.IndentationError(obj)
        elif obj.external_indent != self.internal_indent_later:
            raise erring.IndentationError(obj)
        obj.parent = self
        obj.index = len(self)
        self.append(obj)
        self.unresolved_child_count += 1
        self.last_lineno = obj.last_lineno
        self.last_column = obj.last_column
        self.open = False

class DictlikeAstObj(collections.OrderedDict):
    '''
    Dict-like collection.
    '''
    basetype = 'dict'
    __slots__ = (_astobj_common_slots + _astobj_scalar_or_collection_slots +
                 _astobj_collection_slots + ['awaiting_val', 'next_key'])

    def __init__(self, state, init_common=_init_common,
                 keypath_parent=None, keypath_traversable=False):
        collections.OrderedDict.__init__(self)

        self.keypath_parent = keypath_parent
        self.keypath_travesable = keypath_traversable
        self.unresolved_child_count = 0
        if keypath_traversable:
            # A collection created implicitly as part of a keypath lacks most
            # standard attributes, so they are never created.  There is no
            # need to check for an unused `state.tag`, because the only way
            # to create an implicit collection is with a keypath, and a
            # keypath would resolve any existing tag.  An implicit collection
            # is always open.
            self.open = True
        else:
            init_common(self, state)
            self.open = False
        self.awaiting_key = False
        self.next_key = None

        if self.inline:
            self.check_append_scalar_key = self._check_append_scalar_key_inline
            self.check_append_scalar_val = self._check_append_scalar_val_inline
            self.check_append_collection = self._check_append_collection_inline
        else:
            self.check_append_scalar_key = self._check_append_scalar_key_noninline
            self.check_append_scalar_val = self._check_append_scalar_val_noninline
            self.check_append_collection = self._check_append_collection_noninline

    def _check_append_scalar_key_inline(self, obj, full_ast=False):
        if not obj.external_indent.startswith(self.inline_indent):
            raise erring.IndentationError(obj)
        if not self.open:
            raise erring.ParseError('Cannot add a key to a closed object; perhaps a comma is missing', obj)
        if self.awaiting_key:
            raise erring.ParseError('Cannot add a key until the previous key has been given a value', obj)
        if obj.basetype != 'scalar':
            raise erring.ParseError('Dict-like objects only take scalar types as keys', obj)
        if obj.final_val in self:
            raise erring.ParseError('Duplicate keys are prohibited', obj)
        self.awaiting_key = True
        if full_ast:
            self.next_key = obj
        else:
            self.next_key = obj.final_val

_astobj_tag_slots = ['type', 'label', 'newline',
                     'collection_config_type', 'collection_config_val'
                     'resolved']

class DictlikeAstObj(collections.OrderedDict):
    __slots__ = (_astobj_common_slots + _astobj_scalar_or_collection_slots +
                 _astobj_collection_slots + _astobj_dict_slots)
    def __init__(self, state):
        pass

class TagAstObj(object):
    __slots__ = _astobj_common_slots + _astobj_tag_slots
    def __init__(self, state):
        pass

<|endoftext|>


<commit_before>#add shebang here

#BlackHat Python Ch 3, p 37; bhpsniffer.py

import os, socket, sys #the OS module will enumerate OS's.  Added sys to allow arguments.

host = "Target IP"  #enter the target IP address.  consider adding an argument to enter any IP

#create a raw socket and bind it to the public interface
if os.name == "nt":
	socket_protocol = socket.IPPROTO_IP
else
	socket_protocol = socket.IPPROTO_ICMP

sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
sniffer.bind = ((host, 0))

#We want the IP headers included in the cpature.
sniffer.setsockopt(socket.IPPROTO_IP, socket_IP_HDRINCL, 1)

#IF you're using windows you'll need to send an IOCTL for promiscuous mode

if os.name == "nt":
	sniffer.IOCTL(socket.SIO_RCVALL, socket.RCVALL_ON)
#read in a single packet
print sniffer.recvfrom(65565)
#if you're using windows, turn off promiscuous mode

if os.name == "nt":
	sniffer.IOCTL(socket.SIO_RCVALL, socket.RCVALL_OFF)<commit_msg>TODO: FINISH WRITING THIS PROGRAM.  ADD FUNCTIONS<commit_after>#!/usr/bin/env python

#BlackHat Python Ch 3, p 37; bhpsniffer.py

import os, socket, sys 		#Added sys module to allow arguments.

host = "Target IP"  											#Consider adding an argument to enter any IP

if os.name == "nt":
	socket_protocol = socket.IPPROTO_IP
else
	socket_protocol = socket.IPPROTO_ICMP

sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
sniffer.bind = ((host, 0))

sniffer.setsockopt(socket.IPPROTO_IP, socket_IP_HDRINCL, 1)			#Include IP headers in the cpature.

if os.name == "nt":													#IF you're using windows you'll need to send an IOCTL for promiscuous mode
	sniffer.IOCTL(socket.SIO_RCVALL, socket.RCVALL_ON)
#read in a single packet
print sniffer.recvfrom(65565)										#if you're using windows, turn off promiscuous mode

if os.name == "nt":
	sniffer.IOCTL(socket.SIO_RCVALL, socket.RCVALL_OFF)

<|endoftext|>