def show(self, variable=None):
        super(IPythonTarget, self).show(variable)
        selected = self.state.get_selected_variable()
        if selected is None:
            raise BaseException(
                'No object is currently selected for viewing in Canvas. Call .show on a GraphLab Create object to show output in IPython Notebook or Jupyter Notebook.'
            )
        (name, view) = selected
        assert (type(name) == tuple)
        assert (isinstance(view, graphlab.canvas.views.base.BaseView))

        data = None
        selected_variable = graphlab.canvas.handlers.expand_selected_variable(
            self.state)
        data = {
            'selected_variable': selected_variable,
            'ipython': True,
        }
        data.update(view.get_staticdata())

        import IPython
        IPython.core.display.display_javascript(
            IPython.core.display.Javascript(
                data=self.__makeJS(_to_json(data), view.get_js_file(),
                                   view.get_js_component()),
                css=[
                    '//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css',
                    self.get_asset_url() + 'css/canvas.css'
                ]))
 def write(self, chunk):
     """
     Make sure we write chunks as valid JSON (by default Tornado does not -- it includes Infinity and NaN)
     """
     if isinstance(chunk, dict):
         chunk = _to_json(chunk)
         self.set_header("Content-Type", "application/json; charset=UTF-8")
     super(JSONResponseHandler, self).write(chunk)
예제 #3
0
 def write(self, chunk):
     """
     Make sure we write chunks as valid JSON (by default Tornado does not -- it includes Infinity and NaN)
     """
     if isinstance(chunk, dict):
         chunk = _to_json(chunk)
         self.set_header("Content-Type", "application/json; charset=UTF-8")
     super(JSONResponseHandler, self).write(chunk)
예제 #4
0
    def show(self, variable=None):
        super(IPythonTarget, self).show(variable)
        selected = self.state.get_selected_variable()
        if selected is None:
            raise BaseException('No object is currently selected for viewing in Canvas. Call .show on a GraphLab Create object to show output in IPython Notebook.')
        (name, view) = selected
        assert(type(name) == tuple)
        assert(isinstance(view, graphlab.canvas.views.base.BaseView))

        data = None
        selected_variable = graphlab.canvas.handlers.expand_selected_variable(self.state)
        data = {
            'selected_variable': selected_variable,
            'ipython': True,
        }
        data.update(view.get_staticdata())

        import IPython
        IPython.core.display.display_javascript(
            IPython.core.display.Javascript(
                data=self.__makeJS(_to_json(data), view.get_js_file(), view.get_js_component()),
                css=['//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css', self.get_asset_url() + 'css/canvas.css']
            )
        )
예제 #5
0
def _encode_value(value):
    """
    This will truncate at 24 characters with ellipses as necessary, will format
    list/dict/array as JSON before truncating, and will replace bad characters
    in non-utf8 strings.

    Parameters
    ----------
    value: string, float, long, int, datetime, list, dict, Image
         object to be recurisvly encoded into JSON

    Returns
    -------
    plain_object: list, dict
         mixed object with all SFrames and SArrays cast into list/dicts

    Called to encode a single value (at row/col) from the SFrame
    or SArray as a JSON string. This will truncate at 24 characters
    with ellipses as necessary, will format list/dict/array as JSON
    before truncating, and will replace bad characters in non-utf8 strings.
    """
    # leave numbers alone
    if isinstance(value, (int, long, float)):
        return value

    # leave Nones alone (they turn into null in JSON)
    if value is None:
        return value

    # convert datetime to str
    if isinstance(value, datetime.datetime):
        # return, don't go through truncation
        return str(value)

    # represent image as base64-encoded bytes
    import binascii
    from graphlab.data_structures.image import Image
    if isinstance(value, Image):
        image_format = None
        if value._format_enum == 0:
            image_format = 'jpeg'
        elif value._format_enum == 1:
            image_format = 'png'
        elif value._format_enum == 2:
            image_format = 'raw'
        if image_format is not None:
            ret = {
                'type': 'image',
                'width': value._width,
                'height': value._height,
                'channels': value._channels,
                'format': image_format,
                'id': id(value)
            }
            if image_format in ('jpeg', 'png'):
                ret.update({
                    'value':
                    'image/%s;base64,%s' %
                    (image_format, binascii.b2a_base64(value._image_data))
                })
            elif image_format == 'raw':
                ret.update({'value': list(value._image_data)})
            return ret

        # fallback case for images the browser does not know how to display
        # just convert to str and treat like any other type
        value = str(value)

    # convert strings to unicode (assumes utf-8 encoding, replaces invalid
    # characters with ?
    if isinstance(value, str) and sys.version_info.major == 2:
        value = unicode(value, encoding='utf-8', errors='replace')

    # get the array into a list so it is JSON serializable
    if isinstance(value, array.array):
        value = value.tolist()

    # truncate to 10 elements first
    if isinstance(value, (array.array, list)):
        value = value[:10]
    elif isinstance(value, dict):
        keys = value.keys()[:10]
        truncated = {}
        for key in keys:
            truncated[key] = value[key]
        value = truncated

    # get dict/list values properly encoded inside before dumping to str
    if isinstance(value, list):
        value = [_encode_value(v) for v in value]
    elif isinstance(value, dict):
        value = {
            _encode_value(k): _encode_value(v)
            for (k, v) in six.iteritems(value)
        }

    # json serialize dict/list types to convert to string
    if isinstance(value, (dict, list)):
        value = _to_json(value)

    # truncate via textwrap (will break on word boundaries if possible)
    wrapped = textwrap.wrap(value, 18)
    if len(wrapped) == 0:
        return ''

    return '%s%s' % (wrapped[0], '' if len(wrapped) == 1 else ' ...')
예제 #6
0
def _encode_value(value):
    """
    This will truncate at 24 characters with ellipses as necessary, will format
    list/dict/array as JSON before truncating, and will replace bad characters
    in non-utf8 strings.

    Parameters
    ----------
    value: string, float, long, int, datetime, list, dict, Image
         object to be recurisvly encoded into JSON

    Return
    ------
    plain_object: list, dict
         mixed object with all SFrames and SArrays cast into list/dicts

    Called to encode a single value (at row/col) from the SFrame
    or SArray as a JSON string. This will truncate at 24 characters
    with ellipses as necessary, will format list/dict/array as JSON
    before truncating, and will replace bad characters in non-utf8 strings.
    """
    # leave numbers alone
    if isinstance(value, (int, long, float)):
        return value

    # leave Nones alone (they turn into null in JSON)
    if value is None:
        return value

    # convert datetime to str
    if isinstance(value, datetime.datetime):
        # return, don't go through truncation
        return str(value)

    # represent image as base64-encoded bytes
    import binascii
    from graphlab.data_structures.image import Image
    if isinstance(value, Image):
        image_format = None
        if value._format_enum == 0:
            image_format = 'jpeg'
        elif value._format_enum == 1:
            image_format = 'png'
        elif value._format_enum == 2:
            image_format = 'raw'
        if image_format is not None:
            ret = {
                'type': 'image',
                'width': value._width,
                'height': value._height,
                'channels': value._channels,
                'format': image_format,
                'id': id(value)
            }
            if image_format in ('jpeg', 'png'):
                ret.update({
                    'value': 'image/%s;base64,%s' % (image_format, binascii.b2a_base64(value._image_data))
                })
            elif image_format == 'raw':
                ret.update({
                    'value': list(value._image_data)
                })
            return ret

        # fallback case for images the browser does not know how to display
        # just convert to str and treat like any other type
        value = str(value)

    # convert strings to unicode (assumes utf-8 encoding, replaces invalid
    # characters with ?
    if isinstance(value, str):
        value = unicode(value, encoding='utf-8', errors='replace')

    # get the array into a list so it is JSON serializable
    if isinstance(value, array.array):
        value = value.tolist()

    # truncate to 10 elements first
    if isinstance(value, (array.array, list)):
        value = value[:10]
    elif isinstance(value, dict):
        keys = value.keys()[:10]
        truncated = {}
        for key in keys:
            truncated[key] = value[key]
        value = truncated

    # get dict/list values properly encoded inside before dumping to str
    if isinstance(value, list):
        value = [_encode_value(v) for v in value]
    elif isinstance(value, dict):
        value = {_encode_value(k): _encode_value(v) for (k,v) in value.iteritems()}

    # json serialize dict/list types to convert to string
    if isinstance(value, (dict, list)):
        value = _to_json(value)

    # truncate via textwrap (will break on word boundaries if possible)
    wrapped = textwrap.wrap(value, 18)
    if len(wrapped) == 0:
        return ''

    return '%s%s' % (
        wrapped[0],
        '' if len(wrapped) == 1 else ' ...'
        )