<s> import sys <EOL> import socket <EOL> import pickle <EOL> import threading <EOL> import collections <EOL> import SocketServer <EOL> class NetworkMigrator ( SocketServer . ThreadingMixIn , SocketServer . TCPServer ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , server_address , client_addresses , max_migrants = <NUM_LIT:1> ) : <EOL> self . _lock = threading . Lock ( ) <EOL> SocketServer . TCPServer . __init__ ( self , server_address , None ) <EOL> self . client_addresses = client_addresses <EOL> self . migrants = collections . deque ( maxlen = max_migrants ) <EOL> t = threading . Thread ( target = self . serve_forever ) <EOL> t . setDaemon ( True ) <EOL> t . start ( ) <EOL> self . __name__ = self . __class__ . __name__ <EOL> def finish_request ( self , request , client_address ) : <EOL> try : <EOL> rbufsize = - <NUM_LIT:1> <EOL> wbufsize = <NUM_LIT:0> <EOL> rfile = request . makefile ( '<STR_LIT:rb>' , rbufsize ) <EOL> wfile = request . makefile ( '<STR_LIT:wb>' , wbufsize ) <EOL> pickle_data = rfile . readline ( ) . strip ( ) <EOL> migrant = pickle . loads ( pickle_data ) <EOL> with self . _lock : <EOL> self . migrants . append ( migrant ) <EOL> if not wfile . closed : <EOL> wfile . flush ( ) <EOL> wfile . close ( ) <EOL> rfile . close ( ) <EOL> finally : <EOL> sys . exc_traceback = None <EOL> def __call__ ( self , random , population , args ) : <EOL> """<STR_LIT>""" <EOL> evaluate_migrant = args . setdefault ( '<STR_LIT>' , False ) <EOL> client_address = random . choice ( self . client_addresses ) <EOL> migrant_index = random . randint ( <NUM_LIT:0> , len ( population ) - <NUM_LIT:1> ) <EOL> pickle_data = pickle . dumps ( population [ migrant_index ] ) <EOL> sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) <EOL> try : <EOL> sock . connect ( client_address ) <EOL> sock . send ( pickle_data + '<STR_LIT:\n>' ) <EOL> finally : <EOL> sock . close ( ) <EOL> migrant = None <EOL> with self . _lock : <EOL> if len ( self . migrants ) > <NUM_LIT:0> : <EOL> migrant = self . migrants . popleft ( ) <EOL> if migrant is not None : <EOL> if evaluate_migrant : <EOL> fit = args . _ec . evaluator ( [ migrant ] , args ) <EOL> migrant . fitness = fit [ <NUM_LIT:0> ] <EOL> args . _ec . num_evaluations += <NUM_LIT:1> <EOL> population [ migrant_index ] = migrant <EOL> return population <EOL> def __str__ ( self ) : <EOL> return str ( self . migrants ) </s>
