예제 #1
0
class Function(UrthWidget):
    """
    A Widget for invoking a function on the kernel.
    """
    function_name = Unicode('', sync=True)
    limit = Integer(100, sync=True)

    def __init__(self, **kwargs):
        self.log.info("Created a new Function widget.")

        self.on_msg(self._handle_custom_event_msg)
        self.shell = get_ipython()
        self.serializer = Serializer()
        super(Function, self).__init__(**kwargs)

    def _function_name_changed(self, old, new):
        try:
            self.log.info("Binding to function name {}...".format(new))
            self._sync_state()
            self.ok()
        except Exception as e:
            self.error(str(e))

    def _handle_custom_event_msg(self, wid, content, buffers):
        event = content.get('event', '')
        if event == 'invoke':
            self._invoke(content.get('args', {}))
        elif event == 'sync':
            self._sync_state()

    def _the_function(self):
        if self.function_name in self.shell.user_ns:
            return self.shell.user_ns[self.function_name]
        else:
            raise UrthException("Invalid function name {}".format(
                self.function_name))

    def _invoke(self, args):
        self.log.info("Invoking function {} with args {}...".format(
            self.function_name, args))
        try:
            result = apply_with_conversion(self._the_function(), args)
            serialized_result = self.serializer.serialize(result,
                                                          limit=self.limit)
            self._send_update("result", serialized_result)
            self.ok()
        except Exception as e:
            self.error("Error while invoking function: {}".format(str(e)))

    def _sync_state(self):
        try:
            signature = signature_spec(self._the_function())
            self._send_update("signature", signature)
        except Exception as e:
            self.error("Error while getting function signature: {}".format(
                str(e)))
class Channels(UrthWidget):
    """ A widget that provides an API for setting bound channel variables. """

    def __init__(self, value=None, **kwargs):
        self.log.info("Created a new Channels widget.")
        self.serializer = None
        global the_channels
        the_channels = self

        self.on_msg(self._handle_change_msg)

        # maps channel name to a map of variable name to handler function
        self.watch_handlers = defaultdict(dict)

        super(Channels, self).__init__(**kwargs)

    def set(self, key, value, chan='default', **kwargs):

        # Need to lazy import Serializers to avoid issue with matplotlib.
        # The Kernel errors if the inline magic runs
        # after the modules get imported.
        if self.serializer is None:
            from urth.util.serializer import Serializer
            self.serializer = Serializer()

        attr = "{}:{}".format(chan, key)
        serialized = self.serializer.serialize(value, **kwargs)
        self._send_update(attr, serialized)

    def watch(self, key, handler, chan='default'):
        self.watch_handlers[chan][key] = handler

    def _handle_change_msg(self, _, content):
        if content.get('event', '') == 'change':
            data = content.get('data', {})
            if 'channel' in data and data['channel'] in self.watch_handlers:
                chan_handlers = self.watch_handlers[data['channel']]
                if 'name' in data and data['name'] in chan_handlers:
                    handler = chan_handlers[data['name']]
                    old = data.get('old_val', None)
                    new = data.get('new_val', None)
                    handler(old, new)
                else:
                    print("No watch handler for name field in {}".format(data))
            else:
                print("No watch handler for channel field in {}".format(data))

    def _send_update(self, attribute, value):
        msg = {
            "method": "update",
            "state": {
                attribute: value
            }
        }
        self._send(msg)
class Function(UrthWidget):
    """
    A Widget for invoking a function on the kernel.
    """
    function_name = Unicode('', sync=True)
    limit = Integer(100, sync=True)

    def __init__(self, **kwargs):
        self.log.info("Created a new Function widget.")

        self.on_msg(self._handle_custom_event_msg)
        self.shell = get_ipython()
        self.serializer = Serializer()
        super(Function, self).__init__(**kwargs)

    def _function_name_changed(self, old, new):
        try:
            self.log.info("Binding to function name {}...".format(new))
            self._sync_state()
            self.ok()
        except Exception as e:
            self.error(str(e))

    def _handle_custom_event_msg(self, wid, content, buffers):
        event = content.get('event', '')
        if event == 'invoke':
            self._invoke(content.get('args', {}))
        elif event == 'sync':
            self._sync_state()

    def _the_function(self):
        if self.function_name in self.shell.user_ns:
            return self.shell.user_ns[self.function_name]
        else:
            raise UrthException("Invalid function name {}".format(
                self.function_name))

    def _invoke(self, args):
        self.log.info("Invoking function {} with args {}...".format(
            self.function_name, args))
        try:
            result = apply_with_conversion(self._the_function(), args)
            serialized_result = self.serializer.serialize(
                result, limit=self.limit)
            self._send_update("result", serialized_result)
            self.ok()
        except Exception as e:
            self.error("Error while invoking function: {}".format(str(e)))

    def _sync_state(self):
        try:
            signature = signature_spec(self._the_function())
            self._send_update("signature", signature)
        except Exception as e:
            self.error("Error while getting function signature: {}".format(str(e)))
class Channels(UrthWidget):
    """ A widget that provides an API for setting bound channel variables. """

    def __init__(self, value=None, **kwargs):
        self.log.info("Created a new Channels widget.")
        self.serializer = None
        global the_channels, channel_data, channel_watchers
        the_channels = self

        self.on_msg(self._handle_change_msg)

        # Watchers may have been requested prior to the Channels model creation.
        self.watch_handlers = channel_watchers

        super(Channels, self).__init__(**kwargs)

        # Set any channel data that was specified prior to Channels model creation.
        for channel, data in channel_data.items():
            for key, params in data.items():
                self.set(key, params['value'], channel, **params['args'])

    def set(self, key, value, chan='default', **kwargs):

        # Need to lazy import Serializers to avoid issue with matplotlib.
        # The Kernel errors if the inline magic runs
        # after the modules get imported.
        if self.serializer is None:
            from urth.util.serializer import Serializer
            self.serializer = Serializer()

        attr = "{}:{}".format(chan, key)
        serialized = self.serializer.serialize(value, **kwargs)
        self._send_update(attr, serialized)

    def watch(self, key, handler, chan='default'):
        self.watch_handlers[chan][key] = handler

    def _handle_change_msg(self, wid, content, buffers):
        if content.get('event', '') == 'change':
            data = content.get('data', {})
            if 'channel' in data and data['channel'] in self.watch_handlers:
                chan_handlers = self.watch_handlers[data['channel']]
                if 'name' in data and data['name'] in chan_handlers:
                    handler = chan_handlers[data['name']]
                    old = data.get('old_val', None)
                    new = data.get('new_val', None)
                    try:
                        handler(old, new)
                        self.ok()
                    except Exception as e:
                        self.error("Error executing watch handler for {} on "
                                   "channel {}: {}".format(
                                    data['name'], data['channel'], str(e)))
class Function(UrthWidget):
    """
    A Widget for invoking a function on the kernel.
    """
    function_name = Unicode('', sync=True)
    limit = Integer(100, sync=True)

    def __init__(self, **kwargs):
        self.log.info("Created a new Function widget.")

        self.on_msg(self._handle_custom_event_msg)
        self.shell = get_ipython()
        self.serializer = Serializer()
        super(Function, self).__init__(**kwargs)

    def _function_name_changed(self, old, new):
        self.log.info("Binding to function name {}...".format(new))
        self._sync_state()

    def _handle_custom_event_msg(self, _, content):
        event = content.get('event', '')
        if event == 'invoke':
            self._invoke(content.get('args', {}))
        elif event == 'sync':
            self._sync_state()

    def _the_function(self):
        return self.shell.user_ns[self.function_name]

    def _invoke(self, args):
        self.log.info("Invoking function {} with args {}...".format(
            self.function_name, args))
        result = apply_with_conversion(self._the_function(), args)
        serialized_result = self.serializer.serialize(result, limit=self.limit)
        self._send_update("result", serialized_result)

    def _send_update(self, attribute, value):
        msg = {
            "method": "update",
            "state": {
                attribute: value
            }
        }
        self._send(msg)

    def _sync_state(self):
        signature = signature_spec(self._the_function())
        self._send_update("signature", signature)
예제 #6
0
class Channels(UrthWidget):
    """ A widget that provides an API for setting bound channel variables. """

    def __init__(self, value=None, **kwargs):
        self.log.info("Created a new Channels widget.")
        self.serializer = None
        global the_channels
        the_channels = self

        self.on_msg(self._handle_change_msg)

        # maps channel name to a map of variable name to handler function
        self.watch_handlers = defaultdict(dict)

        super(Channels, self).__init__(**kwargs)

    def set(self, key, value, chan='default', **kwargs):

        # Need to lazy import Serializers to avoid issue with matplotlib.
        # The Kernel errors if the inline magic runs
        # after the modules get imported.
        if self.serializer is None:
            from urth.util.serializer import Serializer
            self.serializer = Serializer()

        attr = "{}:{}".format(chan, key)
        serialized = self.serializer.serialize(value, **kwargs)
        self._send_update(attr, serialized)

    def watch(self, key, handler, chan='default'):
        self.watch_handlers[chan][key] = handler

    def _handle_change_msg(self, wid, content, buffers):
        if content.get('event', '') == 'change':
            data = content.get('data', {})
            if 'channel' in data and data['channel'] in self.watch_handlers:
                chan_handlers = self.watch_handlers[data['channel']]
                if 'name' in data and data['name'] in chan_handlers:
                    handler = chan_handlers[data['name']]
                    old = data.get('old_val', None)
                    new = data.get('new_val', None)
                    try:
                        handler(old, new)
                        self.ok()
                    except Exception as e:
                        self.error("Error executing watch handler for {} on "
                                   "channel {}: {}".format(
                                    data['name'], data['channel'], str(e)))
class DataFrame(UrthWidget):
    """
    A widget for retrieving the value of a DataFrame in the kernel.
    """
    variable_name = Unicode('', sync=True)
    limit = Integer(100, sync=True)
    query = Unicode('[]', sync=True)

    def __init__(self, value=None, **kwargs):
        self.log.info("Created a new DataFrame widget.")

        self.on_msg(self._handle_state_msg)
        self.shell = get_ipython()
        self.serializer = Serializer()
        super(DataFrame, self).__init__(**kwargs)

    def _variable_name_changed(self, old, new):
        self.log.info("Binding to variable name {}...".format(new))

    def _limit_changed(self, old, new):
        self.log.info("Changed value of limit to {}...".format(new))

    def _query_changed(self, old, new):
        self.log.info("Changed value of query to {}...".format(new))

    def _the_dataframe(self):
        if self.variable_name in self.shell.user_ns:
            return self.shell.user_ns[self.variable_name]
        else:
            raise UrthException("Invalid DataFrame variable name {}".format(
                self.variable_name))

    def _handle_state_msg(self, wid, content, buffers):
        if content.get("event", "") == "sync":
            self._sync_state()

    def _sync_state(self):
        try:
            val = self._the_dataframe()
            serialized_result = self.serializer.serialize(apply_query(val, json.loads(self.query)), limit=self.limit, query=self.query)
            self._send_update("value", serialized_result)
            self.ok()
        except Exception as e:
            self.error(str(e))
class DataFrame(UrthWidget):
    """
    A widget for retrieving the value of a DataFrame in the kernel.
    """
    variable_name = Unicode('', sync=True)
    limit = Integer(100, sync=True)

    def __init__(self, value=None, **kwargs):
        self.log.info("Created a new DataFrame widget.")

        self.on_msg(self._handle_state_msg)
        self.shell = get_ipython()
        self.serializer = Serializer()
        super(DataFrame, self).__init__(**kwargs)

    def _variable_name_changed(self, old, new):
        self.log.info("Binding to variable name {}...".format(new))

    def _limit_changed(self, old, new):
        self.log.info("Changed value of limit to {}...".format(new))

    def _the_dataframe(self):
        if self.variable_name in self.shell.user_ns:
            return self.shell.user_ns[self.variable_name]
        else:
            raise UrthException("Invalid DataFrame variable name {}".format(
                self.variable_name))

    def _handle_state_msg(self, wid, content, buffers):
        if content.get("event", "") == "sync":
            self._sync_state()

    def _sync_state(self):
        try:
            val = self._the_dataframe()
            serialized_result = self.serializer.serialize(val,
                                                          limit=self.limit)
            self._send_update("value", serialized_result)
            self.ok()
        except Exception as e:
            self.error(str(e))
class DataFrame(UrthWidget):
    """
    A widget for retrieving the value of a DataFrame in the kernel.
    """
    variable_name = Unicode('', sync=True)
    limit = Integer(100, sync=True)

    def __init__(self, value=None, **kwargs):
        self.log.info("Created a new DataFrame widget.")

        self.on_msg(self._handle_state_msg)
        self.shell = get_ipython()
        self.serializer = Serializer()
        super(DataFrame, self).__init__(**kwargs)

    def _variable_name_changed(self, old, new):
        self.log.info("Binding to variable name {}...".format(new))

    def _limit_changed(self, old, new):
        self.log.info("Changed value of limit to {}...".format(new))

    def _the_dataframe(self):
        return self.shell.user_ns[self.variable_name]

    def _handle_state_msg(self, _, content):
        if content.get("event", "") == "sync":
            self._sync_state()

    def _sync_state(self):
        val = self._the_dataframe()
        serialized_result = self.serializer.serialize(val, limit=self.limit)
        self._send({
            "method": "update",
            "state": {
                "value": serialized_result
            }
        })