rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
nanny.tattle_remove_item(tattle_item, identity)
nanny.tattle_remove_item("outsockets", identity) try: sock.close() except: pass
def _bind_udp_socket(localip, localport, tattle_item): # Conrad: entirely stolen from listenforconnection(). Some of this input # verification stuff especially could probably be combined as a shared # function. Even the rest of the functions are similar enough to be worth # consolidating. # Check the input arguments (...
OPEN_SOCKET_INFO[identity] = (threading.Lock(), sock) return identity
def _bind_udp_socket(localip, localport, tattle_item): # Conrad: entirely stolen from listenforconnection(). Some of this input # verification stuff especially could probably be combined as a shared # function. Even the rest of the functions are similar enough to be worth # consolidating. # Check the input arguments (...
identity = _bind_udp_socket(localip, localport, 'insockets') server_sock = UDPServerSocket(identity) return server_sock
if type(localip) is not str: raise RepyArgumentError("Provided localip must be a string!") if type(localport) is not int: raise RepyArgumentError("Provided localport must be a int!") if not _is_valid_ip_address(localip): raise RepyArgumentError("Provided localip is not valid! IP: '"+localip+"'") if not _is_valid_n...
def listenformessage(localip, localport): """ <Purpose> Sets up a UDPServerSocket to receive incoming UDP messages. <Arguments> localip: The local IP to register the handler on. localport: The port to listen on. <Exceptions> DuplicateTupleError (descends NetworkError) if the port cannot be listened on because some ot...
nanny.tattle_quantity('netsend', 0) nanny.tattle_quantity('netrecv', 0)
if _is_loopback_ipaddr(destip): nanny.tattle_quantity('loopsend', 0) nanny.tattle_quantity('looprecv', 0) else: nanny.tattle_quantity('netsend', 0) nanny.tattle_quantity('netrecv', 0)
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
nanny.tattle_quantity('netsend', 128) nanny.tattle_quantity('netrecv', 64)
if _is_loopback_ipaddr(destip): nanny.tattle_quantity('loopsend', 128) nanny.tattle_quantity('looprecv', 64) else: nanny.tattle_quantity('netsend', 128) nanny.tattle_quantity('netrecv', 64)
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
nanny.tattle_quantity('netrecv', 0) nanny.tattle_quantity('netsend', 0)
if self.on_loopback: nanny.tattle_quantity('looprecv', 0) nanny.tattle_quantity('loopsend', 0) else: nanny.tattle_quantity('netrecv', 0) nanny.tattle_quantity('netsend', 0)
def close(self): """ <Purpose> Closes a socket. Pending remote recv() calls will return with the remaining information. Local recv / send calls will fail after this.
nanny.tattle_quantity('netrecv',64) nanny.tattle_quantity('netsend',128)
if self.on_loopback: nanny.tattle_quantity('looprecv',64) nanny.tattle_quantity('loopsend',128) else: nanny.tattle_quantity('netrecv',64) nanny.tattle_quantity('netsend',128)
def close(self): """ <Purpose> Closes a socket. Pending remote recv() calls will return with the remaining information. Local recv / send calls will fail after this.
def __init__(self, handle): self._commid = handle self._closed = False def getmessage(self): """ <Purpose> Obtains an incoming message that was sent to an IP and port. <Arguments> None. <Exceptions> SocketClosedLocal if UDPServerSocket.close() was called. LocalIPChanged if the local IP address has changed and the...
def __del__(self): # Get the socket lock try: socket_lock = OPEN_SOCKET_INFO[self.identity][0] except KeyError: # Closed, done return
TCP socket. It allows for accepting incoming connections, and closing the socket.
UDP socket. It allows for accepting incoming messages, and closing the socket.
def __del__(self): # Clean up global resources on garbage collection. self.close()
__slots__ = ["identity"]
__slots__ = ["identity", "on_loopback"]
def __del__(self): # Clean up global resources on garbage collection. self.close()
Initializes the TCPServerSocket. The socket should already be established by listenforconnection
Initializes the UDPServerSocket. The socket should already be established by listenformessage
def __init__(self, identity): """ <Purpose> Initializes the TCPServerSocket. The socket should already be established by listenforconnection prior to calling the initializer.
A TCPServerSocket
A UDPServerSocket
def __init__(self, identity): """ <Purpose> Initializes the TCPServerSocket. The socket should already be established by listenforconnection prior to calling the initializer.
def getconnection(self):
def getmessage(self):
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
Accepts an incoming connection to a listening TCP socket.
Obtains an incoming message that was sent to an IP and port.
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
None
None.
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
Raises SocketClosedLocal if close() has been called. Raises SocketWouldBlockError if the operation would block. Raises ResourcesExhaustedError if there are no free outsockets.
SocketClosedLocal if UDPServerSocket.close() was called. Raises SocketWouldBlockError if the operation would block. <Side Effects> None
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
If successful, consumes 128 bytes of netrecv (64 bytes for a SYN and ACK packet) and 64 bytes of netsend (1 ACK packet). Uses an outsocket.
This operation consumes 64 + size of message bytes of netrecv
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
A tuple containing: (remote ip, remote port, socket object)
A tuple consisting of the remote IP, remote port, and message.
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
nanny.tattle_quantity('netrecv',0) nanny.tattle_quantity('netsend',0)
if self.on_loopback: nanny.tattle_quantity('looprecv',0) else: nanny.tattle_quantity('netrecv',0)
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
nanny.tattle_quantity('netrecv', 128) nanny.tattle_quantity('netsend', 64)
if self.on_loopback: nanny.tattle_quantity('looprecv', 128) nanny.tattle_quantity('loopsend', 64) else: nanny.tattle_quantity('netrecv', 128) nanny.tattle_quantity('netsend', 64)
def getconnection(self): """ <Purpose> Accepts an incoming connection to a listening TCP socket.
return socket.gethostbyname(name)
try: return socket.gethostbyname(name) except socket.gaierror: raise NetworkAddressError("The name '%s' could not be resolved." % name) except TypeError: raise ArgumentError("gethostbyname() takes a string as argument.")
def gethostbyname(name): """ <Purpose> Provides information about a hostname. Calls socket.gethostbyname(). Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as '100.50.200.5'. If the host name is an IPv4 address itself it is returned unchanged. <Arguments> name: The host nam...
fileo = open(file,"r")
fileo = myopen(file,"r")
def _process_stat_file(file): # Get the file in proc fileo = open(file,"r") # Read in all the data data = fileo.read() # Close the file object fileo.close() # Strip the newline data = data.strip("\n") # Remove the substring that says "(python)", since it changes the field alignment start_index = data.find("(") if s...
while nonportable.os_api.exists_listening_network_socket(localip, localport, is_tcp): time.sleep(RETRY_INTERVAL)
def _cleanup_socket(identity): """ <Purpose> Internal cleanup method for open sockets. The socket lock for the socket should be acquired prior to calling. <Arguments> identity: An identity tuple for the socket to cleanup <Side Effects> The entry in OPEN_SOCKET_INFO will be removed. The socket will be closed, and a in...
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
def _timed_conn_cleanup_wait(identity, timeout): """ <Purpose> This private function waits until a previous openconn is cleaned up. <Arguments> identity: A tuple to wait for cleanup timeout: Maximum time to wait for cleanup <Exceptions> Raises PortInUseError if there is a conflicting error Raises TimeoutError if we t...
def listenformessage(localip, localport): """ <Purpose> Sets up a UDPServerSocket to receive incoming UDP messages. <Arguments> localip: The local IP to register the handler on. localport: The port to listen on. <Exceptions> PortInUseException (descends NetworkError) if the port cannot be listened on because some oth...
handle = find_outgoing_tcp_commhandle(localip, localport, desthost, destport) message = "Network socket is in use by an external process!" if handle != None: message = " Duplicate handle exists with name: "+str(handle) raise Exception, message
raise PortInUseError("There is a duplicate connection which conflicts with the request!")
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
raise Exception, "Timed out checking for socket cleanup!" if localport: nanny.tattle_check('connport',localport) handle = generate_commhandle()
raise TimeoutError, "Timed out checking for socket cleanup!" def _timed_conn_initialize(identity, timeout): """ <Purpose> Tries to initialize an outgoing socket to match the given identity. <Arguments> identity: The socket to create timeout: Maximum time to try <Exceptions> Raises TimeoutError if we timed out tryin...
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
nanny.tattle_add_item('outsockets',handle) except: gc.collect() nanny.tattle_add_item('outsockets',handle) try: s = _get_tcp_socket(localip,localport) comminfo[handle] = {'type':'TCP','remotehost':None, 'remoteport':None,'localip':localip,'localport':localport,'socket':s, 'outgoing':True, 'closing_lock':threading....
connected = False
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
comminfo[handle]['socket'].connect((desthost,destport))
sock.connect((destip, destport)) connected = True
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
if _is_conn_refused_exception(e): raise ConnectionRefusedError("The connection was refused!")
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
else: connect_exception = e time.sleep(0.2)
time.sleep(RETRY_INTERVAL) if not connected: raise TimeoutError("Timed-out connecting to the remote host!") return sock except: sock.close() raise def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destina...
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
if connect_exception != None: raise connect_exception comminfo[handle]['remotehost']=desthost comminfo[handle]['remoteport']=destport except: _cleanup_socket(handle) raise else: comminfo[handle]['socket'].settimeout(oldtimeout) return thissock
PENDING_SOCKETS.add(identity) finally: PENDING_SOCKETS_LOCK.release() nanny.tattle_quantity('netsend', 0) nanny.tattle_quantity('netrecv', 0) try: gc.collect() nanny.tattle_add_item('outsockets',identity) try: stoptime = timeout + nonportable.getruntime() _timed_conn_cleanup_wait(identity, timeout) sock = _t...
def openconnection(destip, destport,localip, localport, timeout): """ <Purpose> Opens a connection, returning a socket-like object <Arguments> destip: The destination ip to open communications with destport: The destination port to use for communication localip: The local ip to use for the communication localport:...
raise RepyArgumentError("Provided localip is not valid!")
raise RepyArgumentError("Provided localip is not valid! IP: '"+localip+"'")
def listenforconnection(localip, localport): """ <Purpose> Sets up a TCPServerSocket to recieve incoming TCP connections. <Arguments> localip: The local IP to listen on localport: The local port to listen on <Exceptions> Raises PortInUseError if another TCPServerSocket or process has bound to the provided localip and...
raise RepyArgumentError("Provided localport is not valid!")
raise RepyArgumentError("Provided localport is not valid! Port: "+str(localport))
def listenforconnection(localip, localport): """ <Purpose> Sets up a TCPServerSocket to recieve incoming TCP connections. <Arguments> localip: The local IP to listen on localport: The local port to listen on <Exceptions> Raises PortInUseError if another TCPServerSocket or process has bound to the provided localip and...
raise ResourceForbiddenError("Provided localip is not allowed!")
raise ResourceForbiddenError("Provided localip is not allowed! IP: '"+localip+"'")
def listenforconnection(localip, localport): """ <Purpose> Sets up a TCPServerSocket to recieve incoming TCP connections. <Arguments> localip: The local IP to listen on localport: The local port to listen on <Exceptions> Raises PortInUseError if another TCPServerSocket or process has bound to the provided localip and...
raise ResourceForbiddenError("Provided localport is not allowed!")
raise ResourceForbiddenError("Provided localport is not allowed! Port: "+str(localport))
def listenforconnection(localip, localport): """ <Purpose> Sets up a TCPServerSocket to recieve incoming TCP connections. <Arguments> localip: The local IP to listen on localport: The local port to listen on <Exceptions> Raises PortInUseError if another TCPServerSocket or process has bound to the provided localip and...
As from socket.gethostbyname_ex()
InternetConnectivityError is the host is not connected to the internet.
def getmyip(): """ <Purpose> Provides the external IP of this computer. Does some clever trickery. <Arguments> None <Exceptions> As from socket.gethostbyname_ex() <Side Effects> None. <Returns> The localhost's IP address python docs for socket.gethostbyname_ex() """ restrictions.assertisallowed('getmyip') # I go...
python docs for socket.gethostbyname_ex() """ restrictions.assertisallowed('getmyip')
""" nanny.tattle_quantity("netsend", 128) nanny.tattle_quantity("netrecv", 128)
def getmyip(): """ <Purpose> Provides the external IP of this computer. Does some clever trickery. <Arguments> None <Exceptions> As from socket.gethostbyname_ex() <Side Effects> None. <Returns> The localhost's IP address python docs for socket.gethostbyname_ex() """ restrictions.assertisallowed('getmyip') # I go...
raise Exception("Cannot detect a connection to the Internet.")
raise InternetConnectivityError("Cannot detect a connection to the Internet.")
def getmyip(): """ <Purpose> Provides the external IP of this computer. Does some clever trickery. <Arguments> None <Exceptions> As from socket.gethostbyname_ex() <Side Effects> None. <Returns> The localhost's IP address python docs for socket.gethostbyname_ex() """ restrictions.assertisallowed('getmyip') # I go...
class emulated_lock (Object):
class emulated_lock (object):
def getlasterror(): """ <Purpose> Obtains debugging information about the last exception that occured in the current thread. <Arguments> None <Exceptions> None <Returns> A string with details of the last exception in the current thread, or None if there is no such exception. """ # Call down into tracebackrepy return...
if not os.remove(filename): raise InternalRepyException, "os.remove call on '"+filename+"' should have succeeded. Failed."
os.remove(filename)
def removefile(filename): """ <Purpose> Allows the user program to remove a file in their area. <Arguments> filename: the name of the file to remove. It must not contain characters other than 'a-zA-Z0-9.-_' and cannot be '.', '..' or the empty string. <Exceptions> FileNotFoundError is raised if the file does not ex...
def acquire(blocking):
def acquire(self, blocking):
def acquire(blocking): """ <Purpose> Acquires the lock.
def release():
def release(self):
def release(): """ <Purpose> Releases the lock.
xi=((vals0==-1).sum(1)+(vals1==-1).sum(1))/nAll xij=[(vals0==-1).sum(1)/nij[0], (vals1==-1).sum(1)/nij[1]]
xi=((vals0==1).sum(1)+(vals1==1).sum(1))/nAll xij=[(vals0==1).sum(1)/nij[0], (vals1==1).sum(1)/nij[1]]
def fst(vals0, vals1, isNorm=True): nij=np.asarray([vals0.shape[1], vals1.shape[1]], np.float) nAll=nij.sum() xi=((vals0==-1).sum(1)+(vals1==-1).sum(1))/nAll xij=[(vals0==-1).sum(1)/nij[0], (vals1==-1).sum(1)/nij[1]] if isNorm: top=0; bottom=0 for j in range(2): top+=nchoose2(nij[j])*np.sum(2*nij[j]/(nij[j]-1)*xij[j]*(...
r = results()
r = results(e)
def electionTest(self): e = election() v = Vote() v.castVote(1) e.submit(v) assert e[0] == v, 'vote not counted' assert len(e) == 1, '# votes wrong' w = Vote() w.castVote(2) w.castVote(3) e.submit(w) assert e[0] == v, 'vote not counted' assert e[1] == w, 'vote not counted' assert len(e) == 2, '# votes wrong' e.transfer...
class results(list): ''' when given an election object this processes,counts and outputs the results ''' def calculateVotes(self,election): import operator print (election) for f in election: print(f)
def calculatewinner(self): self.calculateVotes() d = self loser = min (d,key = lambda a: d.get(a)) leader = max(d,key = lambda a: d.get(a)) leaderVoteCount = self[leader] if leaderVoteCount > self.NoVotesCast // 2 : print (str(leader) + ' is the winner') return leader else: if loser == 'None': print ('No clear winner...
def electionTest(self): e = election() v = Vote() v.castVote(1) e.submit(v) assert e[0] == v, 'vote not counted' assert len(e) == 1, '# votes wrong' w = Vote() w.castVote(2) w.castVote(3) e.submit(w) assert e[0] == v, 'vote not counted' assert e[1] == w, 'vote not counted' assert len(e) == 2, '# votes wrong' e.transfer...
Vote([3,4,5]), Vote([3,5,4]), Vote([3,5,6]), Vote([4,5,3]),
Vote([1, 4, 5]), Vote([3, 5, 4]), Vote([3, 5, 6]), Vote([4, 5, 3]), Vote([1, 5, 3]),
def calculateVotes(self,election): import operator print (election) for f in election: print(f)
r = results() r = r.calculateVotes(f) print ("done")
r = results(f) r.calculatewinner() ''' produces: [1, 4, 5] [3, 5, 4] [3, 5, 6] [4, 5, 3] [1, 5, 3] 4 is knocked out of the race 5 is knocked out of the race 3 is the winner '''
def calculateVotes(self,election): import operator print (election) for f in election: print(f)
super(election, self).__init__(*args)
def __init__(self,votelist = [],*args): if votelist: for f in votelist: self.submit(f) super(election, self).__init__(*args)
print (r.calculateWinner(e))
def electionTest(self): e = election() v = Vote() v.castVote(1) e.submit(v) assert e[0] == v, 'vote not counted' assert len(e) == 1, '# votes wrong' w = Vote() w.castVote(2) w.castVote(3) e.submit(w) assert e[0] == v, 'vote not counted' assert e[1] == w, 'vote not counted' assert len(e) == 2, '# votes wrong' e.transfer...
self.results = {}
print (election)
def calculateVotes(self,election): import operator self.results = {} for f in election: currentVote = f.getCurrentVote() if self.results.has_key(currentVote): self.results[currentVote] += 1 else: self.results[currentVote] = 1 # convert results to a list of tuples sortedresults = sorted(self.results.iteritems(), key=op...
currentVote = f.getCurrentVote() if self.results.has_key(currentVote): self.results[currentVote] += 1 else: self.results[currentVote] = 1 sortedresults = sorted(self.results.iteritems(), key=operator.itemgetter(1)) return sortedresults def outputResults(self,results):
print(f)
def calculateVotes(self,election): import operator self.results = {} for f in election: currentVote = f.getCurrentVote() if self.results.has_key(currentVote): self.results[currentVote] += 1 else: self.results[currentVote] = 1 # convert results to a list of tuples sortedresults = sorted(self.results.iteritems(), key=op...
for r in results: print (r) def calculateWinner(self,e): print ('start calc') e.output() results = self.calculateVotes(e) winner = results[-1] loser = results[0] while winner[1]<(e.getNumberOfVoters % 2): e.transferVote(loser[0]) results = self.calculateVotes(e) winner = results[-1] loser = results[0] print ('winner, ...
def outputResults(self,results):
r = r.calculateWinner(f)
r = r.calculateVotes(f)
def calculateWinner(self,e): print ('start calc') e.output() results = self.calculateVotes(e) winner = results[-1] loser = results[0] while winner[1]<(e.getNumberOfVoters % 2): e.transferVote(loser[0]) results = self.calculateVotes(e) winner = results[-1] loser = results[0] print ('winner, loser ') print (winner, lose...
x, y = self._location.x, self._location.y w, h = self._image.get_size() surface.blit(self._image, (x-w/2, y-h/2))
surface.blit(self._image, self._location)
def render(self, surface): x, y = self._location.x, self._location.y w, h = self._image.get_size() surface.blit(self._image, (x-w/2, y-h/2))
print location self._ttl = 5
self._ttl = 5
def __init__(self, image, location): GameObject.__init__(self, image, location) print location self._ttl = 5
LEVELS = { 1: { 'aliens': [Alien(110) for x in range(4)],
def instanciate_levels(): return { 1: { 'aliens': [Alien(110) for x in range(4)],
def _calculate_destination(self, mouse_pos): """ Figure out the destination coords for the bullet, starting from the center of the screen through the point the player click, to the edge of the screen. """ dx,dy = mouse_pos
level_dict = LEVELS[level]
levels = instanciate_levels() level_dict = levels[level]
def _calculate_destination(self, mouse_pos): """ Figure out the destination coords for the bullet, starting from the center of the screen through the point the player click, to the edge of the screen. """ dx,dy = mouse_pos
if not level in LEVELS.keys():
if not level in levels.keys():
def _calculate_destination(self, mouse_pos): """ Figure out the destination coords for the bullet, starting from the center of the screen through the point the player click, to the edge of the screen. """ dx,dy = mouse_pos
level_dict = LEVELS[level]
level_dict = levels[level]
def _calculate_destination(self, mouse_pos): """ Figure out the destination coords for the bullet, starting from the center of the screen through the point the player click, to the edge of the screen. """ dx,dy = mouse_pos
dx += step.x dy += step.y
dx += step.x; dy += step.y
def _calculate_destination(self, mouse_pos): """ Figure out the destination coords for the bullet, starting from the center of the screen through the point the player click, to the edge of the screen. """ dx,dy = mouse_pos
player = pygame.Rect(WINDOWWIDTH / 2, WINDOWHEIGHT / 2, 50, 50)
player = pygame.Rect((WINDOWWIDTH / 2)-25, (WINDOWHEIGHT / 2)-25, 50, 50)
def instanciate_levels(): return { 1: { 'aliens': [Alien(110) for x in range(4)], 'spawn_rate': 50, 'multiplier': 1 }, 2: { 'aliens': [Alien(115) for x in range(6)], 'spawn_rate': 45, 'multiplier': 1 }, 3: { 'aliens': [Alien(125) for x in range(10)], 'spawn_rate': 40, 'multiplier': 1 }, 4: { 'aliens': [Alien(135) for x...
aliens.append(Alien())
def instanciate_levels(): return { 1: { 'aliens': [Alien(110) for x in range(4)], 'spawn_rate': 50, 'multiplier': 1 }, 2: { 'aliens': [Alien(115) for x in range(6)], 'spawn_rate': 45, 'multiplier': 1 }, 3: { 'aliens': [Alien(125) for x in range(10)], 'spawn_rate': 40, 'multiplier': 1 }, 4: { 'aliens': [Alien(135) for x...
if score > 5 * level: score -= 5 * level
score -= 5 * level if score < 0: score = 0
def move(obj, time_passed_secords, speed): """ """ destination = Vector2(obj['dx'], obj['dy']) position = Vector2(obj['rect'].x, obj['rect'].y) heading = Vector2.from_points(position, destination) heading.normalize() position += heading * time_passed_seconds * speed obj['rect'].x = position.x obj['rect'].y = position....
gen_py = os.path.dirname(__import__('win32com.gen_py', fromlist=['__name__']).__file__) _EXCEPTIONS.append(gen_py)
win32com_pkg = os.path.dirname(__import__('win32com').__file__) gen_py_pkg = os.path.join(win32com_pkg, 'gen_py') _EXCEPTIONS.append(gen_py_pkg)
def _remap_pair(self,operation,src,dst,*args,**kw): """Called for path pairs like rename, link, and symlink operations""" return ( self._remap_input(operation+'-from',src,*args,**kw), self._remap_input(operation+'-to',dst,*args,**kw) )
if fn and normalize_path(fn).startswith(loc):
if fn and (normalize_path(fn).startswith(loc) or fn.startswith(self.location)):
def check_version_conflict(self): if self.key=='distribute': return # ignore the inevitable setuptools self-conflicts :(
return 'install' in sys.argv[1:] or _easy_install_marker()
if "--help" in sys.argv[1:] or "-h" in sys.argv[1:]: return False return 'install' in sys.argv[1:] or _easy_install_marker()
def _being_installed(): if os.environ.get('DONT_PATCH_SETUPTOOLS') is not None: return False if _buildout_marker(): # Installed by buildout, don't mess with a global setuptools. return False # easy_install marker return 'install' in sys.argv[1:] or _easy_install_marker()
urllib2.urlopen('http://127.0.0.1:%s/' % self.server_port)
try: urllib2.urlopen('http://127.0.0.1:%s/' % self.server_port, None, 5) except urllib2.URLError: pass
def stop(self): """self.shutdown is not supported on python < 2.6""" self._run = False urllib2.urlopen('http://127.0.0.1:%s/' % self.server_port) self.thread.join()
print 'install_dir', self.install_dir
def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" print 'install_dir', self.install_dir instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir,'easy-install.pth')
self.install_egg_scripts(dist)
if not self.editable: self.install_egg_scripts(dist)
def process_distribution(self, requirement, dist, deps=True, *info): self.update_pth(dist) self.package_index.add(dist) self.local_index.add(dist) self.install_egg_scripts(dist) self.installed_projects[dist.key] = dist log.info(self.installation_report(requirement, dist, *info)) if (dist.has_metadata('dependency_links....
__builtin__.open = _file __builtin__.file = _open
__builtin__.open = _open __builtin__.file = _file
def run(self, func): """Run 'func' under os sandboxing""" try: self._copy(self) __builtin__.file = self._file __builtin__.open = self._open self._active = True return func() finally: self._active = False __builtin__.open = _file __builtin__.file = _open self._copy(_os)
elif option == '--user' and USER_SITE is not None: return location.startswith(USER_SITE)
if arg == '--user' and USER_SITE is not None: return location.startswith(USER_SITE)
def _under_prefix(location): if 'install' not in sys.argv: return True args = sys.argv[sys.argv.index('install')+1:] for index, arg in enumerate(args): for option in ('--root', '--prefix'): if arg.startswith('%s=' % option): top_dir = arg.split('root=')[-1] return location.startswith(top_dir) elif arg == option: if len...
if os.path.exists(new_header[2:-1]) or sys.platform!='win32':
if os.path.exists(new_header[2:-1].strip('"')) or sys.platform!='win32':
def get_script_args(dist, executable=sys_executable, wininst=False): """Yield write_script() argument tuples for a distribution's entrypoints""" spec = str(dist.as_requirement()) header = get_script_header("", executable, wininst) for group in 'console_scripts', 'gui_scripts': for name,ep in dist.get_entry_map(group).i...
if dist.location not in self.paths and dist.location not in self.sitedirs: self.paths.append(dist.location); self.dirty = True
if (dist.location not in self.paths and ( dist.location not in self.sitedirs or dist.location == os.getcwd() )): self.paths.append(dist.location) self.dirty = True
def add(self,dist): """Add `dist` to the distribution map""" if dist.location not in self.paths and dist.location not in self.sitedirs: self.paths.append(dist.location); self.dirty = True Environment.add(self,dist)
name = filter(None,urlparse.urlparse(url)[2].split('/'))
name, fragment = egg_info_for_url(url)
def _download_url(self, scheme, url, tmpdir): # Determine download filename # name = filter(None,urlparse.urlparse(url)[2].split('/')) if name: name = name[-1] while '..' in name: name = name.replace('..','.').replace('\\','_') else: name = "__downloaded__" # default if URL has no path contents
name = name[-1]
def _download_url(self, scheme, url, tmpdir): # Determine download filename # name = filter(None,urlparse.urlparse(url)[2].split('/')) if name: name = name[-1] while '..' in name: name = name.replace('..','.').replace('\\','_') else: name = "__downloaded__" # default if URL has no path contents
self._exceptions = exceptions
self._exceptions = [os.path.normcase(os.path.realpath(path)) for path in exceptions]
def __init__(self, sandbox, exceptions=_EXCEPTIONS): self._sandbox = os.path.normcase(os.path.realpath(sandbox)) self._prefix = os.path.join(self._sandbox,'') self._exceptions = exceptions AbstractSandbox.__init__(self)
if (realpath in self._exceptions or realpath == self._sandbox
if (self._exempted(realpath) or realpath == self._sandbox
def _ok(self,path): active = self._active try: self._active = False realpath = os.path.normcase(os.path.realpath(path)) if (realpath in self._exceptions or realpath == self._sandbox or realpath.startswith(self._prefix)): return True finally: self._active = active
urllib2.urlopen('http://127.0.0.1:%s/' % self.server_address[1])
urllib2.urlopen('http://127.0.0.1:%s/' % self.server_port)
def stop(self): """self.shutdown is not supported on python < 2.6""" self._run = False urllib2.urlopen('http://127.0.0.1:%s/' % self.server_address[1]) self.thread.join()
auth = b"Basic " except (AttributeError, SyntaxError):
auth = bytes("Basic ") except AttributeError:
def upload_file(self, filename): content = open(filename, 'rb').read() meta = self.distribution.metadata data = { ':action': 'doc_upload', 'name': meta.get_name(), 'content': (os.path.basename(filename), content), } # set up the authentication credentials = self.username + ':' + self.password try: # base64 only works ...
visit(None, dirname, file)
visit(None, dirname, files)
def visit(z, dirname, names): for name in names: path = os.path.normpath(os.path.join(dirname, name)) if os.path.isfile(path): p = path[len(base_dir)+1:] if not dry_run: z.write(path, p) log.debug("adding '%s'" % p)
('SCRIPTS/', 'EGG-INFO/scripts/')
('SCRIPTS/', 'EGG-INFO/scripts/'), ('DATA/LIB/site-packages', ''),
def get_exe_prefixes(exe_filename): """Get exe->egg path translations for a given .exe file""" prefixes = [ ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''), ('PLATLIB/', ''), ('SCRIPTS/', 'EGG-INFO/scripts/') ] z = zipfile.ZipFile(exe_filename) try: for info in z.infolist(): name = info.filename parts = name.split(...
version=''.join(str(x) for x in version),
version=version_str,
def __init__(self, *args, **kwargs): for src in glob('msgpack/*.pyx'): cython_compiler.compile(glob('msgpack/*.pyx'), cython_compiler.default_options) sdist.__init__(self, *args, **kwargs)
lines = lines[-maxy+1:]
def log(self, msg, indent=0): (maxy, maxx) = self.win1.getmaxyx() assert indent < maxx - 1 #indent = " " * indent if type(msg) is str: pass elif type(msg) is unicode: msg = msg.encode("ascii", "backslashreplace") else: msg = repr(msg) indentSpaces = " " * indent lines = [] for line in msg.split("\n"): if not lines: (fi...
subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, attributes, True, context)) subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, attributes, False, context))
subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, direct_attributes, True, context)) subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, inverse_attributes, False, context))
def get_by_attribute(cls, attributes, context = None): """ Retrieve all `instances` from the data store that have the specified `attributes` and are of `rdf:type` of the resource class
return instances if len(instances) > 0 else []
return instances
def get_by_attribute(cls, attributes, context = None): """ Retrieve all `instances` from the data store that have the specified `attributes` and are of `rdf:type` of the resource class
self.connect()
def sesame2_request(self, method, sesame2_method, sesame2_params = {}, body = '', params = {}, headers = {}):
subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, direct_attributes, True, context)) subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, inverse_attributes, False, context))
if direct_attributes: subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, direct_attributes, True, context)) if inverse_attributes: subjects.update(cls.session[cls.store_key].instances_by_attribute(cls, inverse_attributes, False, context))
def get_by_attribute(cls, attributes, context = None): """ Retrieve all `instances` from the data store that have the specified `attributes` and are of `rdf:type` of the resource class
self.__con.addFile(file, base = base, format = format, context = toSesame(context, self.__f), serverSide = server_side) return True
source = kwargs['source'] if 'source' in kwargs else None base = kwargs['base'] if 'base' in kwargs else None context = kwargs['context'] if 'context' in kwargs else None server_side = kwargs['server_side'] if 'server_side' in kwargs else True if source: self.__con.addFile(source, base = base, format = format, context ...
def load_triples(self, **kwargs): ''' loads triples from supported sources if such functionality is present returns True if operation successfull ''' format = kwargs['format'] if 'format' in kwargs else RDFFormat.RDFXML format = RDFFormat.NTRIPLES if format is 'nt' else RDFFormat.RDFXML self.__con.addFile(file, base = ...
def _instance(cls, subject, vals, context = None, store = None):
def _instance(cls, subject, vals, context = None, store = None, block_auto_load = True):
def _instance(cls, subject, vals, context = None, store = None): """ Create an instance from the `subject` and it's associated `concept` (`vals`) URIs.
block_auto_load = True,
block_auto_load = block_auto_load,
def _instance(cls, subject, vals, context = None, store = None): """ Create an instance from the `subject` and it's associated `concept` (`vals`) URIs.
store = cls.store_key)
store = cls.store_key, block_auto_load = False)
def __instancemaker(cls, params, instance_data): """ Construct resource from `instance_data`, return it. """
return new.classobj(unicode(uri_to_classname(uri)), (), {'uri':uri})
return new.classobj(str(uri_to_classname(uri)), (), {'uri':uri})
def uri_to_class(uri): '''returns a `class object` from the supplied `uri`, used `uri_to_class` to get a valid class name .. code-block:: python >>> print util.uri_to_class('http://mynamespace/ns#some_class') surf.util.Ns1some_class ''' return new.classobj(unicode(uri_to_classname(uri)), (), {'uri':uri})
print "instantiating ", subject
def __instancemaker(cls, params, instance_data): """ Construct resource from `instance_data`, return it. """
else: raise ValueError(str(self.font_resolver==default_font_resolver))
def docinit(self, els): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TTFont
registerFont(font)
pdfmetrics.registerFont(font)
def docinit(self, els): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TTFont
return fname, args
return img, args
def default_image_resolver(node): import urllib from reportlab.lib.utils import ImageReader u = urllib.urlopen(str(node.getAttribute('file'))) s = StringIO.StringIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.hasAttribute(tag): ...
fname, args = self.image_resolver(node)
img, args = self.image_resolver(node)
def _image(self, node): fname, args = self.image_resolver(node) self.canvas.drawImage(img, **args)
def render(self, node): tags = {
def init_tag_handlers(self): self.tag_handlers = {
def render(self, node): tags = { 'drawCentredString': self._drawCenteredString, 'drawRightString': self._drawRightString, 'drawString': self._drawString, 'rect': self._rect, 'ellipse': self._ellipse, 'lines': self._lines, 'grid': self._grid, 'curves': self._curves, 'fill': lambda node: self.canvas.setFillColor(utils.as...
for tag in tags:
for tag in self.tag_handlers:
def render(self, node): tags = { 'drawCentredString': self._drawCenteredString, 'drawRightString': self._drawRightString, 'drawString': self._drawString, 'rect': self._rect, 'ellipse': self._ellipse, 'lines': self._lines, 'grid': self._grid, 'curves': self._curves, 'fill': lambda node: self.canvas.setFillColor(utils.as...
tags[tag](nd)
self.tag_handlers[tag](nd)
def render(self, node): tags = { 'drawCentredString': self._drawCenteredString, 'drawRightString': self._drawRightString, 'drawString': self._drawString, 'rect': self._rect, 'ellipse': self._ellipse, 'lines': self._lines, 'grid': self._grid, 'curves': self._curves, 'fill': lambda node: self.canvas.setFillColor(utils.as...