コード例 #1
0
ファイル: test_receiver.py プロジェクト: digitalsatori/Bokeh
def test_binary_content_raises_error():
    r = receiver.Receiver(_proto)

    r.consume(decode_utf8('header'))
    r.consume(decode_utf8('metadata'))
    with pytest.raises(ValidationError):
        r.consume(b'content').result()
コード例 #2
0
def test_validation_success_with_one_buffer():
    r = receiver.Receiver(_proto)

    partial = r.consume(
        decode_utf8('{"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":1}')
    ).result()
    assert partial is None

    partial = r.consume(decode_utf8('{}')).result()
    assert partial is None

    partial = r.consume(decode_utf8('{"bar": 10}')).result()
    assert partial is None

    partial = r.consume(decode_utf8('header')).result()
    assert partial is None

    partial = r.consume(b'payload').result()
    assert partial is not None
    assert partial.msgtype == "PATCH-DOC"
    assert partial.header == {
        "msgtype": "PATCH-DOC",
        "msgid": "10",
        "num_buffers": 1
    }
    assert partial.content == {"bar": 10}
    assert partial.metadata == {}
    assert partial.buffers == [('header', b'payload')]
コード例 #3
0
def test_binary_content_raises_error():
    r = receiver.Receiver(_proto)

    r.consume(decode_utf8('header'))
    r.consume(decode_utf8('metadata'))
    with pytest.raises(ValidationError):
        r.consume(b'content').result()
コード例 #4
0
def test_multiple_validation_success_with_multiple_buffers():
    r = receiver.Receiver(_proto)

    for N in range(10):
        partial = r.consume(
            decode_utf8(
                '{"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":%d}' %
                N)).result()
        partial = r.consume(decode_utf8('{}')).result()
        partial = r.consume(decode_utf8('{"bar": 10}')).result()

        for i in range(N):
            partial = r.consume(decode_utf8('header%d' % i)).result()
            partial = r.consume(b'payload%d' % i).result()

        assert partial is not None
        assert partial.msgtype == "PATCH-DOC"
        assert partial.header == {
            "msgtype": "PATCH-DOC",
            "msgid": "10",
            "num_buffers": N
        }
        assert partial.content == {"bar": 10}
        assert partial.metadata == {}
        assert partial.buffers == [('header%d' % i, b'payload%d' % i)
                                   for i in range(N)]
コード例 #5
0
 def write_file(self, args, filename, doc):
     contents = self.file_contents(args, doc)
     if filename == '-':
         print(decode_utf8(contents))
     else:
         with io.open(filename, "w", encoding="utf-8") as file:
             file.write(decode_utf8(contents))
     self.after_write_file(args, filename, doc)
コード例 #6
0
ファイル: file_output.py プロジェクト: ChunHungLiu/bokeh
 def write_file(self, args, filename, doc):
     contents = self.file_contents(args, doc)
     if filename == "-":
         print(decode_utf8(contents))
     else:
         with io.open(filename, "w", encoding="utf-8") as file:
             file.write(decode_utf8(contents))
     self.after_write_file(args, filename, doc)
コード例 #7
0
ファイル: test_receiver.py プロジェクト: digitalsatori/Bokeh
def test_binary_payload_header_raises_error():
    r = receiver.Receiver(_proto)

    r.consume(decode_utf8('{"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":1}'))
    r.consume(decode_utf8('{}'))
    r.consume(decode_utf8('{}'))
    with pytest.raises(ValidationError):
        r.consume(b'buf_header').result()
コード例 #8
0
def test_binary_payload_header_raises_error():
    r = receiver.Receiver(_proto)

    r.consume(decode_utf8('{"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":1}'))
    r.consume(decode_utf8('{}'))
    r.consume(decode_utf8('{}'))
    with pytest.raises(ValidationError):
        r.consume(b'buf_header').result()
コード例 #9
0
ファイル: svg.py プロジェクト: skraman/bokeh
 def write_file(self, args, filename, doc):
     contents = self.file_contents(args, doc)
     for i, svg in enumerate(contents):
         if filename == '-':
             print(decode_utf8(svg))
         else:
             if i == 0:
                 filename = filename
             else:
                 idx = filename.find(".svg")
                 filename = filename[:idx] + "_{}".format(
                     i) + filename[idx:]
             with io.open(filename, "w", encoding="utf-8") as f:
                 f.write(decode_utf8(svg))
         self.after_write_file(args, filename, doc)
コード例 #10
0
ファイル: test_receiver.py プロジェクト: digitalsatori/Bokeh
def test_validation_success():
    msg = _proto.create('ACK')
    r = receiver.Receiver(_proto)

    partial = r.consume(decode_utf8(msg.header_json)).result()
    assert partial is None

    partial = r.consume(decode_utf8(msg.metadata_json)).result()
    assert partial is None

    partial = r.consume(decode_utf8(msg.content_json)).result()
    assert partial is not None
    assert partial.msgtype == msg.msgtype
    assert partial.header == msg.header
    assert partial.content == msg.content
    assert partial.metadata == msg.metadata
コード例 #11
0
def test_validation_success():
    msg = _proto.create('ACK')
    r = receiver.Receiver(_proto)

    partial = r.consume(decode_utf8(msg.header_json)).result()
    assert partial is None

    partial = r.consume(decode_utf8(msg.metadata_json)).result()
    assert partial is None

    partial = r.consume(decode_utf8(msg.content_json)).result()
    assert partial is not None
    assert partial.msgtype == msg.msgtype
    assert partial.header == msg.header
    assert partial.content == msg.content
    assert partial.metadata == msg.metadata
コード例 #12
0
ファイル: svg.py プロジェクト: crashMOGWAI/bokeh
    def write_file(self, args, filename, doc):
        '''

        '''
        contents = self.file_contents(args, doc)
        for i, svg in enumerate(contents):
            if filename == '-':
                print(decode_utf8(svg))
            else:
                if i == 0:
                    filename = filename
                else:
                    idx = filename.find(".svg")
                    filename = filename[:idx] + "_{}".format(i) + filename[idx:]
                with io.open(filename, "w", encoding="utf-8") as f:
                    f.write(decode_utf8(svg))
            self.after_write_file(args, filename, doc)
コード例 #13
0
ファイル: server_backends.py プロジェクト: xguse/bokeh
 def get(self, key):
     _data = shelve.open('bokeh.server')
     key = encode_utf8(key)
     data = _data.get(key, None)
     if data is None:
         return None
     attrs = json.loads(decode_utf8(data))
     _data.close()
     return attrs
コード例 #14
0
 def test_string_encoding_does_not_affect_session_id_check(self):
     # originates from #6653
     session_id = generate_session_id(signed=True, secret_key="abc")
     assert check_session_id_signature(session_id,
                                       secret_key="abc",
                                       signed=True)
     assert check_session_id_signature(decode_utf8(session_id),
                                       secret_key="abc",
                                       signed=True)
コード例 #15
0
ファイル: test_receiver.py プロジェクト: digitalsatori/Bokeh
def test_multiple_validation_success_with_multiple_buffers():
    r = receiver.Receiver(_proto)

    for N in range(10):
        partial = r.consume(decode_utf8('{"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":%d}' % N)).result()
        partial = r.consume(decode_utf8('{}')).result()
        partial = r.consume(decode_utf8('{"bar": 10}')).result()

        for i in range(N):
            partial = r.consume(decode_utf8('header%d'% i )).result()
            partial = r.consume(b'payload%d' % i).result()

        assert partial is not None
        assert partial.msgtype == "PATCH-DOC"
        assert partial.header == {"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers": N}
        assert partial.content == {"bar":10}
        assert partial.metadata == {}
        assert partial.buffers == [('header%d' % i, b'payload%d' %i) for i in range(N)]
コード例 #16
0
 def get(self, key):
     _data = shelve.open("bokeh.server")
     key = encode_utf8(key)
     data = _data.get(key, None)
     if data is None:
         return None
     attrs = json.loads(decode_utf8(data))
     _data.close()
     return attrs
コード例 #17
0
 def get(self, key):
     _data = self.shelve_module.open('bokeh.server')
     try:
         key = encode_utf8(key)
         data = _data.get(key, None)
         if data is None:
             return None
         attrs = json.loads(decode_utf8(data))
     finally:
         _data.close()
     return attrs
コード例 #18
0
def test_no_border_or_background_fill(output_file_url, selenium, screenshot):

    # Have body background-color that should appear through the no-fill plot
    template = Template("""
    <!doctype html>
    <html lang="en">
    <head>
        {{ bokeh_js }}
        {{ bokeh_css}}
        <style>
            body { background-color: lightblue; }
        </style>
    </head>
    <body>
        {{ plot_script }}
        {{ plot_div }}
    </body>
    </html>
    """)

    plot = Plot(plot_height=HEIGHT,
                plot_width=WIDTH,
                x_range=Range1d(0, 10),
                y_range=Range1d(0, 10),
                toolbar_location=None)

    # This is the no-fill that we're testing
    plot.background_fill_color = None
    plot.border_fill_color = None

    plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff'))
    plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff'))

    plot.add_layout(
        LinearAxis(major_label_text_color='#ffffff',
                   major_label_text_font_size="30pt"), 'left')
    plot.add_layout(
        LinearAxis(major_label_text_color='#ffffff',
                   major_label_text_font_size="30pt"), 'below')

    html = file_html(plot, INLINE, template=template)

    # filename has to match test function + '.html' light
    filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            "test_no_border_or_background_fill.html")

    with io.open(filepath, "w", encoding="utf-8") as f:
        f.write(decode_utf8(html))

    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)
    assert screenshot.is_valid()
コード例 #19
0
 def pull(self, docid, typename=None, objid=None):
     """you need to call this with either typename AND objid
     or leave out both.  leaving them out means retrieve all
     otherwise, retrieves a specific object
     """
     doc_keys = self.smembers(dockey(docid))
     attrs = self.mget(doc_keys)
     data = []
     for k, attr in zip(doc_keys, attrs):
         typename, _, modelid = parse_modelkey(k)
         attr = protocol.deserialize_json(decode_utf8(attr))
         data.append({'type': typename, 'attributes': attr})
     return data
コード例 #20
0
ファイル: test_receiver.py プロジェクト: digitalsatori/Bokeh
def test_validation_success_with_one_buffer():
    r = receiver.Receiver(_proto)

    partial = r.consume(decode_utf8('{"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":1}')).result()
    assert partial is None

    partial = r.consume(decode_utf8('{}')).result()
    assert partial is None

    partial = r.consume(decode_utf8('{"bar": 10}')).result()
    assert partial is None

    partial = r.consume(decode_utf8('header')).result()
    assert partial is None

    partial = r.consume(b'payload').result()
    assert partial is not None
    assert partial.msgtype == "PATCH-DOC"
    assert partial.header == {"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":1}
    assert partial.content == {"bar":10}
    assert partial.metadata == {}
    assert partial.buffers == [('header', b'payload')]
コード例 #21
0
ファイル: serverbb.py プロジェクト: Wombatpm/bokeh
 def pull(self, docid, typename=None, objid=None):
     """you need to call this with either typename AND objid
     or leave out both.  leaving them out means retrieve all
     otherwise, retrieves a specific object
     """
     doc_keys = self.smembers(dockey(docid))
     attrs = self.mget(doc_keys)
     data = []
     for k, attr in zip(doc_keys, attrs):
         typename, _, modelid = parse_modelkey(k)
         attr = protocol.deserialize_json(decode_utf8(attr))
         data.append({'type': typename, 'attributes': attr})
     return data
コード例 #22
0
def test_no_border_or_background_fill(output_file_url, selenium, screenshot):

    # Have body background-color that should appear through the no-fill plot
    template = Template("""
    <!doctype html>
    <html lang="en">
    <head>
        {{ bokeh_js }}
        {{ bokeh_css}}
        <style>
            body { background-color: lightblue; }
        </style>
    </head>
    <body>
        {{ plot_script }}
        {{ plot_div }}
    </body>
    </html>
    """)

    plot = Plot(plot_height=HEIGHT, plot_width=WIDTH,
                x_range=Range1d(0, 10), y_range=Range1d(0, 10),
                toolbar_location=None)

    # This is the no-fill that we're testing
    plot.background_fill_color = None
    plot.border_fill_color = None

    plot.add_glyph(Circle(x=3, y=3, size=50, fill_color='#ffffff'))
    plot.add_glyph(Circle(x=6, y=6, size=50, fill_color='#ffffff'))

    plot.add_layout(LinearAxis(major_label_text_color='#ffffff',
                               major_label_text_font_size="30pt"),
                    'left')
    plot.add_layout(LinearAxis(major_label_text_color='#ffffff',
                               major_label_text_font_size="30pt"),
                    'below')

    html = file_html(plot, INLINE, template=template)

    # filename has to match test function + '.html' light
    filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            "test_no_border_or_background_fill.html")

    with io.open(filepath, "w", encoding="utf-8") as f:
        f.write(decode_utf8(html))

    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)
    screenshot.assert_is_valid()
コード例 #23
0
ファイル: test_session_id.py プロジェクト: HuntJSparra/bokeh
 def test_string_encoding_does_not_affect_session_id_check(self):
     # originates from #6653
     session_id = generate_session_id(signed=True, secret_key="abc")
     assert check_session_id_signature(session_id, secret_key="abc", signed=True)
     assert check_session_id_signature(decode_utf8(session_id), secret_key="abc", signed=True)
コード例 #24
0
ファイル: save.py プロジェクト: bstadlbauer/panel
def save(panel,
         filename,
         title=None,
         resources=None,
         template=None,
         template_variables=None,
         embed=False,
         max_states=1000,
         max_opts=3,
         embed_json=False,
         json_prefix='',
         save_path='./',
         load_path=None,
         progress=True):
    """
    Saves Panel objects to file.

    Arguments
    ---------
    panel: Viewable
      The Panel Viewable to save to file
    filename: string or file-like object
      Filename to save the plot to
    title: string
      Optional title for the plot
    resources: bokeh resources
      One of the valid bokeh.resources (e.g. CDN or INLINE)
    template:
      template file, as used by bokeh.file_html. If None will use bokeh defaults
    template_variables:
      template_variables file dict, as used by bokeh.file_html
    embed: bool
      Whether the state space should be embedded in the saved file.
    max_states: int
      The maximum number of states to embed
    max_opts: int
      The maximum number of states for a single widget
    embed_json: boolean (default=True)
      Whether to export the data to json files
    json_prefix: str (default='')
      Prefix for the randomly json directory
    save_path: str (default='./')
      The path to save json files to
    load_path: str (default=None)
      The path or URL the json files will be loaded from.
    progress: boolean (default=True)
      Whether to report progress
    """
    from ..pane import PaneBase

    if isinstance(panel, PaneBase) and len(panel.layout) > 1:
        panel = panel.layout

    as_png = isinstance(filename, string_types) and filename.endswith('png')

    doc = Document()
    comm = Comm()
    with config.set(embed=embed):
        with swap_html_model(as_png):
            model = panel.get_root(doc, comm)
        if embed:
            embed_state(panel, model, doc, max_states, max_opts, embed_json,
                        json_prefix, save_path, load_path, progress)
        else:
            add_to_doc(model, doc, True)

    if as_png:
        save_png(model, filename=filename)
        return
    elif isinstance(filename, string_types) and not filename.endswith('.html'):
        filename = filename + '.html'

    kwargs = {}
    if title is None:
        title = 'Panel'
    if resources is None:
        resources = CDN
    if template:
        kwargs['template'] = template
    if template_variables:
        kwargs['template_variables'] = template_variables

    html = file_html(doc, resources, title, **kwargs)
    if hasattr(filename, 'write'):
        html = decode_utf8(html)
        if isinstance(filename, io.BytesIO):
            html = html.encode('utf-8')
        filename.write(html)
        return
    with io.open(filename, mode="w", encoding="utf-8") as f:
        f.write(decode_utf8(html))
コード例 #25
0
ファイル: in_memory.py プロジェクト: CaptainAL/Spyder
 def get(self, key):
     data = self._data.get(key, None)
     if data is None:
         return None
     attrs = json.loads(decode_utf8(data))
     return attrs
コード例 #26
0
 def get(self, key):
     data = self.redisconn.get(key)
     if data is None:
         return None
     attrs = json.loads(decode_utf8(data))
     return attrs
コード例 #27
0
ファイル: save.py プロジェクト: shalevy1/panel
def save(panel,
         filename,
         title=None,
         resources=None,
         template=None,
         template_variables={},
         embed=False,
         max_states=1000,
         max_opts=3,
         embed_json=False,
         save_path='./',
         load_path=None):
    """
    Saves Panel objects to file.

    Arguments
    ---------
    panel: Viewable
      The Panel Viewable to save to file
    filename: string or file-like object
      Filename to save the plot to
    title: string
      Optional title for the plot
    resources: bokeh resources
      One of the valid bokeh.resources (e.g. CDN or INLINE)
    embed: bool
      Whether the state space should be embedded in the saved file.
    max_states: int
      The maximum number of states to embed
    max_opts: int
      The maximum number of states for a single widget
    embed_json: boolean (default=True)
      Whether to export the data to json files
    save_path: str (default='./')
      The path to save json files to
    load_path: str (default=None)
      The path or URL the json files will be loaded from.
    """
    doc = Document()
    comm = Comm()
    with config.set(embed=embed):
        model = panel.get_root(doc, comm)
        if embed:
            embed_state(panel, model, doc, max_states, max_opts, embed_json,
                        save_path, load_path)
        else:
            add_to_doc(model, doc, True)

    if isinstance(filename, string_types):
        if filename.endswith('png'):
            save_png(model, filename=filename)
            return
        if not filename.endswith('.html'):
            filename = filename + '.html'

    kwargs = {}
    if title is None:
        title = 'Panel'
    if resources is None:
        resources = CDN
    if template:
        kwargs['template'] = template

    html = file_html(doc, resources, title, **kwargs)
    if hasattr(filename, 'write'):
        filename.write(decode_utf8(html))
        return
    with io.open(filename, mode="w", encoding="utf-8") as f:
        f.write(decode_utf8(html))
コード例 #28
0
ファイル: server_backends.py プロジェクト: xguse/bokeh
 def get(self, key):
     data = self._data.get(key, None)
     if data is None:
         return None
     attrs = json.loads(decode_utf8(data))
     return attrs
コード例 #29
0
ファイル: bokeh_plot.py プロジェクト: waternk/HecHms
    def run(self):

        env = self.state.document.settings.env
        app = env.app

        # filename *or* python code content, but not both
        if self.arguments and self.content:
            raise SphinxError(
                "bokeh-plot:: directive can't have both args and content")

        # process inline examples here
        if self.content:
            app.debug("[bokeh-plot] handling inline example in %r",
                      env.docname)
            source = '\n'.join(self.content)
            # need docname not to look like a path
            docname = env.docname.replace("/", "-")
            js_name = "bokeh-plot-%s-inline-%s.js" % (docname, uuid4().hex)
            # the code runner just needs a real path to cd to, this will do
            path = join(env.bokeh_plot_auxdir, js_name)

            (script, js, js_path,
             source) = _process_script(source, path, env.bokeh_plot_auxdir,
                                       js_name)
            env.bokeh_plot_files[js_name] = (script, js, js_path, source)

        # process example files here
        else:
            example_path = self.arguments[0][:-3]  # remove the ".py"

            # if it's an "internal" example, the python parser has already handled it
            if example_path in env.bokeh_plot_files:
                app.debug("[bokeh-plot] handling internal example in %r: %s",
                          env.docname, self.arguments[0])
                (script, js, js_path,
                 source) = env.bokeh_plot_files[example_path]

            # handle examples external to the docs source, e.g. gallery examples
            else:
                app.debug("[bokeh-plot] handling external example in %r: %s",
                          env.docname, self.arguments[0])
                source = open(self.arguments[0]).read()
                source = decode_utf8(source)
                docname = env.docname.replace("/", "-")
                js_name = "bokeh-plot-%s-external-%s.js" % (docname,
                                                            uuid4().hex)
                (script, js, js_path,
                 source) = _process_script(source, self.arguments[0],
                                           env.bokeh_plot_auxdir, js_name)
                env.bokeh_plot_files[js_name] = (script, js, js_path, source)

        # use the source file name to construct a friendly target_id
        target_id = "%s.%s" % (env.docname, basename(js_path))
        target = nodes.target('', '', ids=[target_id])
        result = [target]

        linenos = self.options.get('linenos', False)
        code = nodes.literal_block(source,
                                   source,
                                   language="python",
                                   linenos=linenos,
                                   classes=[])
        set_source_info(self, code)

        source_position = self.options.get('source-position', 'below')

        if source_position == "above":
            result += [code]

        result += [nodes.raw('', script, format="html")]

        if source_position == "below":
            result += [code]

        return result
コード例 #30
0
def parse_modelkey(key):
    _, typename, docid, modelid = decode_utf8(key).split(":")
    return typename, docid, modelid
コード例 #31
0
ファイル: serverbb.py プロジェクト: Wombatpm/bokeh
def parse_modelkey(key):
    _, typename, docid, modelid = decode_utf8(key).split(":")
    return typename, docid, modelid