<commit_before>"""Allows control of parameter values over the network.

Don't use for realtime control unless you think your network is that
fast and reliable. Also, this code has not been optimized for speed,
and I think it is unwise to attempt to change the value of controllers
in realtime.  In other words, do not design an experiment where, on a
remote computer, you have determined that a certain amount of time has
passed, and you require a certain new controller value NOW.  In this
case, it would be better to use parameter=eval_str() with an if
statement involving time.

To control parameters over a network, start a server with an instance
of TCPServer.  The server spawns an instance of SocketListenController
for each connected socket.  (Most commonly you will only want
connection over a single socket.)  The instance of
SocketListenController handles all communication for that connection
and serves as a container and (meta) controller for instances of
TCPController.

This module contains ABSOLUTELY NO SECURITY FEATURES, and could easily
allow arbitrary execution of code on your computer. For this reason,
if you use this module, I recommend operating behind a firewall. This
could be an inexpensive "routing switch" used for cable modems, which
would provide the added benefit that your local network would be
isolated.  This would elimate all traffic not to or from computers on
the switch and therefore reduce/eliminate packet collisions,
incraseing latency, and providing a network performance and
reliability. To address security concerns, you could also write code
that implements IP address checking or other security
features. (Hopefully contributing it back to the Vision Egg!)

Classes:

TCPServer -- TCP server to create SocketListenControllers upon connection
SocketListenController -- Handle connection from remote machine, control TCPControllers
TCPController -- Control a parameter from a network (TCP) connection

"""

# Copyright (c) 2002 <NAME>.  Distributed under the terms
# of the GNU Lesser General Public License (LGPL).

import VisionEgg
import VisionEgg.Core
import socket, select, re, string, types
import Numeric, math # for eval

try:
    import Tkinter
except:
    pass

__version__ = VisionEgg.release_name
__cvs__ = string.split('$Revision$')[1]
__date__ = string.join(string.split('$Date$')[1:3], ' ')
__author__ = '<NAME> <<EMAIL>>'

class TCPServer:
    """TCP server creates SocketListenController upon connection.

    This class is analagous to VisionEgg.PyroHelpers.PyroServer.

    Public methods:

    create_listener_once_connected -- wait and spawn listener

    """
    def __init__(self,
                 hostname="",
                 port=7834,
                 single_socket_but_reconnect_ok=0,
                 dialog_ok=1):
        """Bind to hostname and port, but don't listen yet.

        """
        server_address = (hostname,port)
        self.dialog_ok = dialog_ok
        if not globals().has_key("Tkinter") or (VisionEgg.config.VISIONEGG_TKINTER_OK==0):
            self.dialog_ok = 0
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.bind(server_address)
        except Exception, x:
            if self.dialog_ok:
                import tkMessageBox
                tkMessageBox.showerror(title=str(x.__class__),message="While trying to connect to %s:\n%s"%(server_address,str(x)))
                raise
            else:
                raise
        self.single_socket_but_reconnect_ok = single_socket_but_reconnect_ok

    def create_listener_once_connected(self,eval_frequency=None):
        """Wait for connection and spawn instance of SocketListenController."""
        if eval_frequency is None:
            # Don't listen to socket during go loop -- especially don't want to skip frames then
            eval_frequency = VisionEgg.Core.Controller.EVERY_FRAME | VisionEgg.Core.Controller.NOT_DURING_GO
        host,port = self.server_socket.getsockname()
        fqdn = socket.getfqdn(host)
        VisionEgg.Core.message.add(
            """Awaiting connection to TCP Server at "%s", port %d"""%(fqdn,port),
            level=VisionEgg.Core.Message.INFO)
        self.server_socket.listen(1)
        if self.dialog_ok:
            # Make a Tkinter dialog box
            class WaitingDialog(Tkinter.Frame):
                def __init__(self,server_socket=None,**kw):
                    apply(Tkinter.Frame.__init__,(self,),kw)
                    self.winfo_toplevel().title('Vision Egg TCP Server')
                    self.server_socket = server_socket
                    spacer = Tkinter.Frame(self,borderwidth=30)
                    spacer.pack()
                    Tkinter.Label(spacer,text=
                                  """Awaiting connection to TCP Server at "%s", port %d"""%(fqdn,port)
                                  ).pack()
                    b = Tkinter.Button(self,text="Cancel",command=self.stop_listening)
                    b.pack(side=Tkinter.BOTTOM)
                    b.focus_force()
                    b.bind('<Return>',self.stop_listening)
                    self.winfo_toplevel().protocol("WM_DELETE_WINDOW", self.stop_listening)
                    self.server_socket.setblocking(0)
                    self.after(1,self.idle_func)
                def stop_listening(self,dummy=None):
                    raise SystemExit
                def idle_func(self):
                    try:
                        # This line raises an exception unless there's an incoming connection
                        self.accepted = self.server_socket.accept()
                        self.quit()
                    except socket.error, x:
                        self.after(1,self.idle_func)
            dialog = WaitingDialog(server_socket = self.server_socket)
            dialog.pack()
            dialog.mainloop()
            client, client_address = dialog.accepted
            dialog.winfo_toplevel().destroy()<commit_msg>Bugfix: python 2.1 fix.<commit_after>"""Allows control of parameter values over the network.

Don't use for realtime control unless you think your network is that
fast and reliable. Also, this code has not been optimized for speed,
and I think it is unwise to attempt to change the value of controllers
in realtime.  In other words, do not design an experiment where, on a
remote computer, you have determined that a certain amount of time has
passed, and you require a certain new controller value NOW.  In this
case, it would be better to use parameter=eval_str() with an if
statement involving time.

To control parameters over a network, start a server with an instance
of TCPServer.  The server spawns an instance of SocketListenController
for each connected socket.  (Most commonly you will only want
connection over a single socket.)  The instance of
SocketListenController handles all communication for that connection
and serves as a container and (meta) controller for instances of
TCPController.

This module contains ABSOLUTELY NO SECURITY FEATURES, and could easily
allow arbitrary execution of code on your computer. For this reason,
if you use this module, I recommend operating behind a firewall. This
could be an inexpensive "routing switch" used for cable modems, which
would provide the added benefit that your local network would be
isolated.  This would elimate all traffic not to or from computers on
the switch and therefore reduce/eliminate packet collisions,
incraseing latency, and providing a network performance and
reliability. To address security concerns, you could also write code
that implements IP address checking or other security
features. (Hopefully contributing it back to the Vision Egg!)

Classes:

TCPServer -- TCP server to create SocketListenControllers upon connection
SocketListenController -- Handle connection from remote machine, control TCPControllers
TCPController -- Control a parameter from a network (TCP) connection

"""

# Copyright (c) 2002 <NAME>.  Distributed under the terms
# of the GNU Lesser General Public License (LGPL).

import VisionEgg
import VisionEgg.Core
import socket, select, re, string, types
import Numeric, math # for eval

try:
    import Tkinter
except:
    pass

__version__ = VisionEgg.release_name
__cvs__ = string.split('$Revision$')[1]
__date__ = string.join(string.split('$Date$')[1:3], ' ')
__author__ = '<NAME> <<EMAIL>>'

class TCPServer:
    """TCP server creates SocketListenController upon connection.

    This class is analagous to VisionEgg.PyroHelpers.PyroServer.

    Public methods:

    create_listener_once_connected -- wait and spawn listener

    """
    def __init__(self,
                 hostname="",
                 port=7834,
                 single_socket_but_reconnect_ok=0,
                 dialog_ok=1):
        """Bind to hostname and port, but don't listen yet.

        """
        server_address = (hostname,port)
        self.dialog_ok = dialog_ok
        if not globals().has_key("Tkinter") or (VisionEgg.config.VISIONEGG_TKINTER_OK==0):
            self.dialog_ok = 0
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.bind(server_address)
        except Exception, x:
            if self.dialog_ok:
                import tkMessageBox
                tkMessageBox.showerror(title=str(x.__class__),message="While trying to connect to %s:\n%s"%(server_address,str(x)))
                raise
            else:
                raise
        self.single_socket_but_reconnect_ok = single_socket_but_reconnect_ok

    def create_listener_once_connected(self,eval_frequency=None):
        """Wait for connection and spawn instance of SocketListenController."""
        if eval_frequency is None:
            # Don't listen to socket during go loop -- especially don't want to skip frames then
            eval_frequency = VisionEgg.Core.Controller.EVERY_FRAME | VisionEgg.Core.Controller.NOT_DURING_GO
        host,port = self.server_socket.getsockname()
        fqdn = socket.getfqdn(host)
        VisionEgg.Core.message.add(
            """Awaiting connection to TCP Server at "%s", port %d"""%(fqdn,port),
            level=VisionEgg.Core.Message.INFO)
        self.server_socket.listen(1)
        if self.dialog_ok:
            # Make a Tkinter dialog box
            class WaitingDialog(Tkinter.Frame):
                def __init__(self,server_socket=None,**kw):
                    apply(Tkinter.Frame.__init__,(self,),kw)
                    self.winfo_toplevel().title('Vision Egg TCP Server')
                    self.server_socket = server_socket
                    host,port = self.server_socket.getsockname()
                    fqdn = socket.getfqdn(host)
                    spacer = Tkinter.Frame(self,borderwidth=30)
                    spacer.pack()
                    Tkinter.Label(spacer,text=
                                  """Awaiting connection to TCP Server at "%s", port %d"""%(fqdn,port)
                                  ).pack()
                    b = Tkinter.Button(self,text="Cancel",command=self.stop_listening)
                    b.pack(side=Tkinter.BOTTOM)
                    b.focus_force()
                    b.bind('<Return>',self.stop_listening)
                    self.winfo_toplevel().protocol("WM_DELETE_WINDOW", self.stop_listening)
                    self.server_socket.setblocking(0)
                    self.after(1,self.idle_func)
                def stop_listening(self,dummy=None):
                    raise SystemExit
                def idle_func(self):
                    try:
                        # This line raises an exception unless there's an incoming connection
                        self.accepted = self.server_socket.accept()
                        self.quit()
                    except socket.error, x:
                        self.after(1,self.idle_func)
            dialog = WaitingDialog(server_socket = self.server_socket)
            dialog.pack()
            dialog.mainloop()
            client, client_address = dialog.accepted
            dialog.winfo_toplevel().destroy()
{'fraction_non_alphanumeric': 0.0740649404027949, 'fraction_numerical': 0.0036169338265515825, 'mean_word_length': 2.5090856648399193, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2089988', 'n_tokens_mistral': 3259, 'n_tokens_neox': 3130, 'n_words': 1058}