id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
30,400
bokeh/bokeh
bokeh/protocol/receiver.py
Receiver.consume
def consume(self, fragment): ''' Consume individual protocol message fragments. Args: fragment (``JSON``) : A message fragment to assemble. When a complete message is assembled, the receiver state will reset to begin consuming a new message. ''' self._current_consumer(fragment) raise gen.Return(self._message)
python
def consume(self, fragment): ''' Consume individual protocol message fragments. Args: fragment (``JSON``) : A message fragment to assemble. When a complete message is assembled, the receiver state will reset to begin consuming a new message. ''' self._current_consumer(fragment) raise gen.Return(self._message)
[ "def", "consume", "(", "self", ",", "fragment", ")", ":", "self", ".", "_current_consumer", "(", "fragment", ")", "raise", "gen", ".", "Return", "(", "self", ".", "_message", ")" ]
Consume individual protocol message fragments. Args: fragment (``JSON``) : A message fragment to assemble. When a complete message is assembled, the receiver state will reset to begin consuming a new message.
[ "Consume", "individual", "protocol", "message", "fragments", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/receiver.py#L108-L119
30,401
bokeh/bokeh
bokeh/driving.py
bounce
def bounce(sequence): ''' Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): div, mod = divmod(i, N) if div % 2 == 0: return sequence[mod] else: return sequence[N-mod-1] return partial(force, sequence=_advance(f))
python
def bounce(sequence): ''' Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): div, mod = divmod(i, N) if div % 2 == 0: return sequence[mod] else: return sequence[N-mod-1] return partial(force, sequence=_advance(f))
[ "def", "bounce", "(", "sequence", ")", ":", "N", "=", "len", "(", "sequence", ")", "def", "f", "(", "i", ")", ":", "div", ",", "mod", "=", "divmod", "(", "i", ",", "N", ")", "if", "div", "%", "2", "==", "0", ":", "return", "sequence", "[", ...
Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "bounced", "sequence", "of", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L73-L94
30,402
bokeh/bokeh
bokeh/driving.py
cosine
def cosine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values ''' from math import cos def f(i): return A * cos(w*i + phi) + offset return partial(force, sequence=_advance(f))
python
def cosine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values ''' from math import cos def f(i): return A * cos(w*i + phi) + offset return partial(force, sequence=_advance(f))
[ "def", "cosine", "(", "w", ",", "A", "=", "1", ",", "phi", "=", "0", ",", "offset", "=", "0", ")", ":", "from", "math", "import", "cos", "def", "f", "(", "i", ")", ":", "return", "A", "*", "cos", "(", "w", "*", "i", "+", "phi", ")", "+", ...
Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "sequence", "of", "cosine", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L96-L113
30,403
bokeh/bokeh
bokeh/driving.py
linear
def linear(m=1, b=0): ''' Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver ''' def f(i): return m * i + b return partial(force, sequence=_advance(f))
python
def linear(m=1, b=0): ''' Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver ''' def f(i): return m * i + b return partial(force, sequence=_advance(f))
[ "def", "linear", "(", "m", "=", "1", ",", "b", "=", "0", ")", ":", "def", "f", "(", "i", ")", ":", "return", "m", "*", "i", "+", "b", "return", "partial", "(", "force", ",", "sequence", "=", "_advance", "(", "f", ")", ")" ]
Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "sequence", "of", "linear", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L137-L151
30,404
bokeh/bokeh
bokeh/driving.py
repeat
def repeat(sequence): ''' Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): return sequence[i%N] return partial(force, sequence=_advance(f))
python
def repeat(sequence): ''' Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): return sequence[i%N] return partial(force, sequence=_advance(f))
[ "def", "repeat", "(", "sequence", ")", ":", "N", "=", "len", "(", "sequence", ")", "def", "f", "(", "i", ")", ":", "return", "sequence", "[", "i", "%", "N", "]", "return", "partial", "(", "force", ",", "sequence", "=", "_advance", "(", "f", ")", ...
Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "repeated", "of", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L153-L169
30,405
bokeh/bokeh
bokeh/driving.py
sine
def sine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of sine values. .. code-block:: none value = A * sin(w*i + phi) + offset Args: w (float) : a frequency for the sine driver A (float) : an amplitude for the sine driver phi (float) : a phase offset to start the sine driver with offset (float) : a global offset to add to the driver values ''' from math import sin def f(i): return A * sin(w*i + phi) + offset return partial(force, sequence=_advance(f))
python
def sine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of sine values. .. code-block:: none value = A * sin(w*i + phi) + offset Args: w (float) : a frequency for the sine driver A (float) : an amplitude for the sine driver phi (float) : a phase offset to start the sine driver with offset (float) : a global offset to add to the driver values ''' from math import sin def f(i): return A * sin(w*i + phi) + offset return partial(force, sequence=_advance(f))
[ "def", "sine", "(", "w", ",", "A", "=", "1", ",", "phi", "=", "0", ",", "offset", "=", "0", ")", ":", "from", "math", "import", "sin", "def", "f", "(", "i", ")", ":", "return", "A", "*", "sin", "(", "w", "*", "i", "+", "phi", ")", "+", ...
Return a driver function that can advance a sequence of sine values. .. code-block:: none value = A * sin(w*i + phi) + offset Args: w (float) : a frequency for the sine driver A (float) : an amplitude for the sine driver phi (float) : a phase offset to start the sine driver with offset (float) : a global offset to add to the driver values
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "sequence", "of", "sine", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L171-L188
30,406
bokeh/bokeh
bokeh/model.py
collect_filtered_models
def collect_filtered_models(discard, *input_values): ''' Collect a duplicate-free list of all other Bokeh models referred to by this model, or by any of its references, etc, unless filtered-out by the provided callable. Iterate over ``input_values`` and descend through their structure collecting all nested ``Models`` on the go. Args: *discard (Callable[[Model], bool]) a callable which accepts a *Model* instance as its single argument and returns a boolean stating whether to discard the instance. The latter means that the instance will not be added to collected models nor will its references be explored. *input_values (Model) Bokeh models to collect other models from Returns: None ''' ids = set([]) collected = [] queued = [] def queue_one(obj): if obj.id not in ids and not (callable(discard) and discard(obj)): queued.append(obj) for value in input_values: _visit_value_and_its_immediate_references(value, queue_one) while queued: obj = queued.pop(0) if obj.id not in ids: ids.add(obj.id) collected.append(obj) _visit_immediate_value_references(obj, queue_one) return collected
python
def collect_filtered_models(discard, *input_values): ''' Collect a duplicate-free list of all other Bokeh models referred to by this model, or by any of its references, etc, unless filtered-out by the provided callable. Iterate over ``input_values`` and descend through their structure collecting all nested ``Models`` on the go. Args: *discard (Callable[[Model], bool]) a callable which accepts a *Model* instance as its single argument and returns a boolean stating whether to discard the instance. The latter means that the instance will not be added to collected models nor will its references be explored. *input_values (Model) Bokeh models to collect other models from Returns: None ''' ids = set([]) collected = [] queued = [] def queue_one(obj): if obj.id not in ids and not (callable(discard) and discard(obj)): queued.append(obj) for value in input_values: _visit_value_and_its_immediate_references(value, queue_one) while queued: obj = queued.pop(0) if obj.id not in ids: ids.add(obj.id) collected.append(obj) _visit_immediate_value_references(obj, queue_one) return collected
[ "def", "collect_filtered_models", "(", "discard", ",", "*", "input_values", ")", ":", "ids", "=", "set", "(", "[", "]", ")", "collected", "=", "[", "]", "queued", "=", "[", "]", "def", "queue_one", "(", "obj", ")", ":", "if", "obj", ".", "id", "not...
Collect a duplicate-free list of all other Bokeh models referred to by this model, or by any of its references, etc, unless filtered-out by the provided callable. Iterate over ``input_values`` and descend through their structure collecting all nested ``Models`` on the go. Args: *discard (Callable[[Model], bool]) a callable which accepts a *Model* instance as its single argument and returns a boolean stating whether to discard the instance. The latter means that the instance will not be added to collected models nor will its references be explored. *input_values (Model) Bokeh models to collect other models from Returns: None
[ "Collect", "a", "duplicate", "-", "free", "list", "of", "all", "other", "Bokeh", "models", "referred", "to", "by", "this", "model", "or", "by", "any", "of", "its", "references", "etc", "unless", "filtered", "-", "out", "by", "the", "provided", "callable", ...
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L62-L103
30,407
bokeh/bokeh
bokeh/model.py
get_class
def get_class(view_model_name): ''' Look up a Bokeh model class, given its view model name. Args: view_model_name (str) : A view model name for a Bokeh model to look up Returns: Model: the model class corresponding to ``view_model_name`` Raises: KeyError, if the model cannot be found Example: .. code-block:: python >>> from bokeh.model import get_class >>> get_class("Range1d") <class 'bokeh.models.ranges.Range1d'> ''' # in order to look up from the model catalog that MetaModel maintains, it # has to be creates first. These imports ensure that all built-in Bokeh # models are represented in the catalog. from . import models; models from .plotting import Figure; Figure d = MetaModel.model_class_reverse_map if view_model_name in d: return d[view_model_name] else: raise KeyError("View model name '%s' not found" % view_model_name)
python
def get_class(view_model_name): ''' Look up a Bokeh model class, given its view model name. Args: view_model_name (str) : A view model name for a Bokeh model to look up Returns: Model: the model class corresponding to ``view_model_name`` Raises: KeyError, if the model cannot be found Example: .. code-block:: python >>> from bokeh.model import get_class >>> get_class("Range1d") <class 'bokeh.models.ranges.Range1d'> ''' # in order to look up from the model catalog that MetaModel maintains, it # has to be creates first. These imports ensure that all built-in Bokeh # models are represented in the catalog. from . import models; models from .plotting import Figure; Figure d = MetaModel.model_class_reverse_map if view_model_name in d: return d[view_model_name] else: raise KeyError("View model name '%s' not found" % view_model_name)
[ "def", "get_class", "(", "view_model_name", ")", ":", "# in order to look up from the model catalog that MetaModel maintains, it", "# has to be creates first. These imports ensure that all built-in Bokeh", "# models are represented in the catalog.", "from", ".", "import", "models", "models...
Look up a Bokeh model class, given its view model name. Args: view_model_name (str) : A view model name for a Bokeh model to look up Returns: Model: the model class corresponding to ``view_model_name`` Raises: KeyError, if the model cannot be found Example: .. code-block:: python >>> from bokeh.model import get_class >>> get_class("Range1d") <class 'bokeh.models.ranges.Range1d'>
[ "Look", "up", "a", "Bokeh", "model", "class", "given", "its", "view", "model", "name", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L123-L156
30,408
bokeh/bokeh
bokeh/model.py
_visit_immediate_value_references
def _visit_immediate_value_references(value, visitor): ''' Visit all references to another Model without recursing into any of the child Model; may visit the same Model more than once if it's referenced more than once. Does not visit the passed-in value. ''' if isinstance(value, HasProps): for attr in value.properties_with_refs(): child = getattr(value, attr) _visit_value_and_its_immediate_references(child, visitor) else: _visit_value_and_its_immediate_references(value, visitor)
python
def _visit_immediate_value_references(value, visitor): ''' Visit all references to another Model without recursing into any of the child Model; may visit the same Model more than once if it's referenced more than once. Does not visit the passed-in value. ''' if isinstance(value, HasProps): for attr in value.properties_with_refs(): child = getattr(value, attr) _visit_value_and_its_immediate_references(child, visitor) else: _visit_value_and_its_immediate_references(value, visitor)
[ "def", "_visit_immediate_value_references", "(", "value", ",", "visitor", ")", ":", "if", "isinstance", "(", "value", ",", "HasProps", ")", ":", "for", "attr", "in", "value", ".", "properties_with_refs", "(", ")", ":", "child", "=", "getattr", "(", "value", ...
Visit all references to another Model without recursing into any of the child Model; may visit the same Model more than once if it's referenced more than once. Does not visit the passed-in value.
[ "Visit", "all", "references", "to", "another", "Model", "without", "recursing", "into", "any", "of", "the", "child", "Model", ";", "may", "visit", "the", "same", "Model", "more", "than", "once", "if", "it", "s", "referenced", "more", "than", "once", ".", ...
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L822-L833
30,409
bokeh/bokeh
bokeh/model.py
_visit_value_and_its_immediate_references
def _visit_value_and_its_immediate_references(obj, visitor): ''' Recurse down Models, HasProps, and Python containers The ordering in this function is to optimize performance. We check the most comomn types (int, float, str) first so that we can quickly return in the common case. We avoid isinstance and issubclass checks in a couple places with `type` checks because isinstance checks can be slow. ''' typ = type(obj) if typ in _common_types: # short circuit on common base types return if typ is list or issubclass(typ, (list, tuple)): # check common containers for item in obj: _visit_value_and_its_immediate_references(item, visitor) elif issubclass(typ, dict): for key, value in iteritems(obj): _visit_value_and_its_immediate_references(key, visitor) _visit_value_and_its_immediate_references(value, visitor) elif issubclass(typ, HasProps): if issubclass(typ, Model): visitor(obj) else: # this isn't a Model, so recurse into it _visit_immediate_value_references(obj, visitor)
python
def _visit_value_and_its_immediate_references(obj, visitor): ''' Recurse down Models, HasProps, and Python containers The ordering in this function is to optimize performance. We check the most comomn types (int, float, str) first so that we can quickly return in the common case. We avoid isinstance and issubclass checks in a couple places with `type` checks because isinstance checks can be slow. ''' typ = type(obj) if typ in _common_types: # short circuit on common base types return if typ is list or issubclass(typ, (list, tuple)): # check common containers for item in obj: _visit_value_and_its_immediate_references(item, visitor) elif issubclass(typ, dict): for key, value in iteritems(obj): _visit_value_and_its_immediate_references(key, visitor) _visit_value_and_its_immediate_references(value, visitor) elif issubclass(typ, HasProps): if issubclass(typ, Model): visitor(obj) else: # this isn't a Model, so recurse into it _visit_immediate_value_references(obj, visitor)
[ "def", "_visit_value_and_its_immediate_references", "(", "obj", ",", "visitor", ")", ":", "typ", "=", "type", "(", "obj", ")", "if", "typ", "in", "_common_types", ":", "# short circuit on common base types", "return", "if", "typ", "is", "list", "or", "issubclass",...
Recurse down Models, HasProps, and Python containers The ordering in this function is to optimize performance. We check the most comomn types (int, float, str) first so that we can quickly return in the common case. We avoid isinstance and issubclass checks in a couple places with `type` checks because isinstance checks can be slow.
[ "Recurse", "down", "Models", "HasProps", "and", "Python", "containers" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L838-L861
30,410
bokeh/bokeh
bokeh/model.py
Model.js_link
def js_link(self, attr, other, other_attr): ''' Link two Bokeh model properties using JavaScript. This is a convenience method that simplifies adding a CustomJS callback to update one Bokeh model property whenever another changes value. Args: attr (str) : The name of a Bokeh property on this model other (Model): A Bokeh model to link to self.attr other_attr (str) : The property on ``other`` to link together Added in version 1.1 Raises: ValueError Examples: This code with ``js_link``: .. code :: python select.js_link('value', plot, 'sizing_mode') is equivalent to the following: .. code:: python from bokeh.models import CustomJS select.js_on_change('value', CustomJS(args=dict(other=plot), code="other.sizing_mode = this.value" ) ) ''' if attr not in self.properties(): raise ValueError("%r is not a property of self (%r)" % (attr, self)) if not isinstance(other, Model): raise ValueError("'other' is not a Bokeh model: %r" % other) if other_attr not in other.properties(): raise ValueError("%r is not a property of other (%r)" % (other_attr, other)) from bokeh.models.callbacks import CustomJS cb = CustomJS(args=dict(other=other), code="other.%s = this.%s" % (other_attr, attr)) self.js_on_change(attr, cb)
python
def js_link(self, attr, other, other_attr): ''' Link two Bokeh model properties using JavaScript. This is a convenience method that simplifies adding a CustomJS callback to update one Bokeh model property whenever another changes value. Args: attr (str) : The name of a Bokeh property on this model other (Model): A Bokeh model to link to self.attr other_attr (str) : The property on ``other`` to link together Added in version 1.1 Raises: ValueError Examples: This code with ``js_link``: .. code :: python select.js_link('value', plot, 'sizing_mode') is equivalent to the following: .. code:: python from bokeh.models import CustomJS select.js_on_change('value', CustomJS(args=dict(other=plot), code="other.sizing_mode = this.value" ) ) ''' if attr not in self.properties(): raise ValueError("%r is not a property of self (%r)" % (attr, self)) if not isinstance(other, Model): raise ValueError("'other' is not a Bokeh model: %r" % other) if other_attr not in other.properties(): raise ValueError("%r is not a property of other (%r)" % (other_attr, other)) from bokeh.models.callbacks import CustomJS cb = CustomJS(args=dict(other=other), code="other.%s = this.%s" % (other_attr, attr)) self.js_on_change(attr, cb)
[ "def", "js_link", "(", "self", ",", "attr", ",", "other", ",", "other_attr", ")", ":", "if", "attr", "not", "in", "self", ".", "properties", "(", ")", ":", "raise", "ValueError", "(", "\"%r is not a property of self (%r)\"", "%", "(", "attr", ",", "self", ...
Link two Bokeh model properties using JavaScript. This is a convenience method that simplifies adding a CustomJS callback to update one Bokeh model property whenever another changes value. Args: attr (str) : The name of a Bokeh property on this model other (Model): A Bokeh model to link to self.attr other_attr (str) : The property on ``other`` to link together Added in version 1.1 Raises: ValueError Examples: This code with ``js_link``: .. code :: python select.js_link('value', plot, 'sizing_mode') is equivalent to the following: .. code:: python from bokeh.models import CustomJS select.js_on_change('value', CustomJS(args=dict(other=plot), code="other.sizing_mode = this.value" ) )
[ "Link", "two", "Bokeh", "model", "properties", "using", "JavaScript", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L449-L504
30,411
bokeh/bokeh
bokeh/model.py
Model.js_on_change
def js_on_change(self, event, *callbacks): ''' Attach a ``CustomJS`` callback to an arbitrary BokehJS model event. On the BokehJS side, change events for model properties have the form ``"change:property_name"``. As a convenience, if the event name passed to this method is also the name of a property on the model, then it will be prefixed with ``"change:"`` automatically: .. code:: python # these two are equivalent source.js_on_change('data', callback) source.js_on_change('change:data', callback) However, there are other kinds of events that can be useful to respond to, in addition to property change events. For example to run a callback whenever data is streamed to a ``ColumnDataSource``, use the ``"stream"`` event on the source: .. code:: python source.js_on_change('streaming', callback) ''' if len(callbacks) == 0: raise ValueError("js_on_change takes an event name and one or more callbacks, got only one parameter") # handle any CustomJS callbacks here from bokeh.models.callbacks import CustomJS if not all(isinstance(x, CustomJS) for x in callbacks): raise ValueError("not all callback values are CustomJS instances") if event in self.properties(): event = "change:%s" % event if event not in self.js_property_callbacks: self.js_property_callbacks[event] = [] for callback in callbacks: if callback in self.js_property_callbacks[event]: continue self.js_property_callbacks[event].append(callback)
python
def js_on_change(self, event, *callbacks): ''' Attach a ``CustomJS`` callback to an arbitrary BokehJS model event. On the BokehJS side, change events for model properties have the form ``"change:property_name"``. As a convenience, if the event name passed to this method is also the name of a property on the model, then it will be prefixed with ``"change:"`` automatically: .. code:: python # these two are equivalent source.js_on_change('data', callback) source.js_on_change('change:data', callback) However, there are other kinds of events that can be useful to respond to, in addition to property change events. For example to run a callback whenever data is streamed to a ``ColumnDataSource``, use the ``"stream"`` event on the source: .. code:: python source.js_on_change('streaming', callback) ''' if len(callbacks) == 0: raise ValueError("js_on_change takes an event name and one or more callbacks, got only one parameter") # handle any CustomJS callbacks here from bokeh.models.callbacks import CustomJS if not all(isinstance(x, CustomJS) for x in callbacks): raise ValueError("not all callback values are CustomJS instances") if event in self.properties(): event = "change:%s" % event if event not in self.js_property_callbacks: self.js_property_callbacks[event] = [] for callback in callbacks: if callback in self.js_property_callbacks[event]: continue self.js_property_callbacks[event].append(callback)
[ "def", "js_on_change", "(", "self", ",", "event", ",", "*", "callbacks", ")", ":", "if", "len", "(", "callbacks", ")", "==", "0", ":", "raise", "ValueError", "(", "\"js_on_change takes an event name and one or more callbacks, got only one parameter\"", ")", "# handle ...
Attach a ``CustomJS`` callback to an arbitrary BokehJS model event. On the BokehJS side, change events for model properties have the form ``"change:property_name"``. As a convenience, if the event name passed to this method is also the name of a property on the model, then it will be prefixed with ``"change:"`` automatically: .. code:: python # these two are equivalent source.js_on_change('data', callback) source.js_on_change('change:data', callback) However, there are other kinds of events that can be useful to respond to, in addition to property change events. For example to run a callback whenever data is streamed to a ``ColumnDataSource``, use the ``"stream"`` event on the source: .. code:: python source.js_on_change('streaming', callback)
[ "Attach", "a", "CustomJS", "callback", "to", "an", "arbitrary", "BokehJS", "model", "event", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L506-L546
30,412
bokeh/bokeh
bokeh/model.py
Model.to_json_string
def to_json_string(self, include_defaults): ''' Returns a JSON string encoding the attributes of this object. References to other objects are serialized as references (just the object ID and type info), so the deserializer will need to separately have the full attributes of those other objects. There's no corresponding ``from_json_string()`` because to deserialize an object is normally done in the context of a Document (since the Document can resolve references). For most purposes it's best to serialize and deserialize entire documents. Args: include_defaults (bool) : whether to include attributes that haven't been changed from the default ''' json_like = self._to_json_like(include_defaults=include_defaults) json_like['id'] = self.id # serialize_json "fixes" the JSON from _to_json_like by converting # all types into plain JSON types # (it converts Model into refs, # for example). return serialize_json(json_like)
python
def to_json_string(self, include_defaults): ''' Returns a JSON string encoding the attributes of this object. References to other objects are serialized as references (just the object ID and type info), so the deserializer will need to separately have the full attributes of those other objects. There's no corresponding ``from_json_string()`` because to deserialize an object is normally done in the context of a Document (since the Document can resolve references). For most purposes it's best to serialize and deserialize entire documents. Args: include_defaults (bool) : whether to include attributes that haven't been changed from the default ''' json_like = self._to_json_like(include_defaults=include_defaults) json_like['id'] = self.id # serialize_json "fixes" the JSON from _to_json_like by converting # all types into plain JSON types # (it converts Model into refs, # for example). return serialize_json(json_like)
[ "def", "to_json_string", "(", "self", ",", "include_defaults", ")", ":", "json_like", "=", "self", ".", "_to_json_like", "(", "include_defaults", "=", "include_defaults", ")", "json_like", "[", "'id'", "]", "=", "self", ".", "id", "# serialize_json \"fixes\" the J...
Returns a JSON string encoding the attributes of this object. References to other objects are serialized as references (just the object ID and type info), so the deserializer will need to separately have the full attributes of those other objects. There's no corresponding ``from_json_string()`` because to deserialize an object is normally done in the context of a Document (since the Document can resolve references). For most purposes it's best to serialize and deserialize entire documents. Args: include_defaults (bool) : whether to include attributes that haven't been changed from the default
[ "Returns", "a", "JSON", "string", "encoding", "the", "attributes", "of", "this", "object", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L654-L679
30,413
bokeh/bokeh
bokeh/model.py
Model._attach_document
def _attach_document(self, doc): ''' Attach a model to a Bokeh |Document|. This private interface should only ever called by the Document implementation to set the private ._document field properly ''' if self._document is not None and self._document is not doc: raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self)) doc.theme.apply_to_model(self) self._document = doc self._update_event_callbacks()
python
def _attach_document(self, doc): ''' Attach a model to a Bokeh |Document|. This private interface should only ever called by the Document implementation to set the private ._document field properly ''' if self._document is not None and self._document is not doc: raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self)) doc.theme.apply_to_model(self) self._document = doc self._update_event_callbacks()
[ "def", "_attach_document", "(", "self", ",", "doc", ")", ":", "if", "self", ".", "_document", "is", "not", "None", "and", "self", ".", "_document", "is", "not", "doc", ":", "raise", "RuntimeError", "(", "\"Models must be owned by only a single document, %r is alre...
Attach a model to a Bokeh |Document|. This private interface should only ever called by the Document implementation to set the private ._document field properly
[ "Attach", "a", "model", "to", "a", "Bokeh", "|Document|", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L704-L715
30,414
bokeh/bokeh
bokeh/model.py
Model._to_json_like
def _to_json_like(self, include_defaults): ''' Returns a dictionary of the attributes of this object, in a layout corresponding to what BokehJS expects at unmarshalling time. This method does not convert "Bokeh types" into "plain JSON types," for example each child Model will still be a Model, rather than turning into a reference, numpy isn't handled, etc. That's what "json like" means. This method should be considered "private" or "protected", for use internal to Bokeh; use ``to_json()`` instead because it gives you only plain JSON-compatible types. Args: include_defaults (bool) : whether to include attributes that haven't been changed from the default. ''' all_attrs = self.properties_with_values(include_defaults=include_defaults) # If __subtype__ is defined, then this model may introduce properties # that don't exist on __view_model__ in bokehjs. Don't serialize such # properties. subtype = getattr(self.__class__, "__subtype__", None) if subtype is not None and subtype != self.__class__.__view_model__: attrs = {} for attr, value in all_attrs.items(): if attr in self.__class__.__dict__: continue else: attrs[attr] = value else: attrs = all_attrs for (k, v) in attrs.items(): # we can't serialize Infinity, we send it as None and # the other side has to fix it up. This transformation # can't be in our json_encoder because the json # module checks for inf before it calls the custom # encoder. if isinstance(v, float) and v == float('inf'): attrs[k] = None return attrs
python
def _to_json_like(self, include_defaults): ''' Returns a dictionary of the attributes of this object, in a layout corresponding to what BokehJS expects at unmarshalling time. This method does not convert "Bokeh types" into "plain JSON types," for example each child Model will still be a Model, rather than turning into a reference, numpy isn't handled, etc. That's what "json like" means. This method should be considered "private" or "protected", for use internal to Bokeh; use ``to_json()`` instead because it gives you only plain JSON-compatible types. Args: include_defaults (bool) : whether to include attributes that haven't been changed from the default. ''' all_attrs = self.properties_with_values(include_defaults=include_defaults) # If __subtype__ is defined, then this model may introduce properties # that don't exist on __view_model__ in bokehjs. Don't serialize such # properties. subtype = getattr(self.__class__, "__subtype__", None) if subtype is not None and subtype != self.__class__.__view_model__: attrs = {} for attr, value in all_attrs.items(): if attr in self.__class__.__dict__: continue else: attrs[attr] = value else: attrs = all_attrs for (k, v) in attrs.items(): # we can't serialize Infinity, we send it as None and # the other side has to fix it up. This transformation # can't be in our json_encoder because the json # module checks for inf before it calls the custom # encoder. if isinstance(v, float) and v == float('inf'): attrs[k] = None return attrs
[ "def", "_to_json_like", "(", "self", ",", "include_defaults", ")", ":", "all_attrs", "=", "self", ".", "properties_with_values", "(", "include_defaults", "=", "include_defaults", ")", "# If __subtype__ is defined, then this model may introduce properties", "# that don't exist o...
Returns a dictionary of the attributes of this object, in a layout corresponding to what BokehJS expects at unmarshalling time. This method does not convert "Bokeh types" into "plain JSON types," for example each child Model will still be a Model, rather than turning into a reference, numpy isn't handled, etc. That's what "json like" means. This method should be considered "private" or "protected", for use internal to Bokeh; use ``to_json()`` instead because it gives you only plain JSON-compatible types. Args: include_defaults (bool) : whether to include attributes that haven't been changed from the default.
[ "Returns", "a", "dictionary", "of", "the", "attributes", "of", "this", "object", "in", "a", "layout", "corresponding", "to", "what", "BokehJS", "expects", "at", "unmarshalling", "time", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L734-L777
30,415
bokeh/bokeh
bokeh/colors/hsl.py
HSL.to_css
def to_css(self): ''' Generate the CSS representation of this HSL color. Returns: str, ``"hsl(...)"`` or ``"hsla(...)"`` ''' if self.a == 1.0: return "hsl(%d, %s%%, %s%%)" % (self.h, self.s*100, self.l*100) else: return "hsla(%d, %s%%, %s%%, %s)" % (self.h, self.s*100, self.l*100, self.a)
python
def to_css(self): ''' Generate the CSS representation of this HSL color. Returns: str, ``"hsl(...)"`` or ``"hsla(...)"`` ''' if self.a == 1.0: return "hsl(%d, %s%%, %s%%)" % (self.h, self.s*100, self.l*100) else: return "hsla(%d, %s%%, %s%%, %s)" % (self.h, self.s*100, self.l*100, self.a)
[ "def", "to_css", "(", "self", ")", ":", "if", "self", ".", "a", "==", "1.0", ":", "return", "\"hsl(%d, %s%%, %s%%)\"", "%", "(", "self", ".", "h", ",", "self", ".", "s", "*", "100", ",", "self", ".", "l", "*", "100", ")", "else", ":", "return", ...
Generate the CSS representation of this HSL color. Returns: str, ``"hsl(...)"`` or ``"hsla(...)"``
[ "Generate", "the", "CSS", "representation", "of", "this", "HSL", "color", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/hsl.py#L110-L120
30,416
bokeh/bokeh
bokeh/util/paths.py
serverdir
def serverdir(): """ Get the location of the server subpackage """ path = join(ROOT_DIR, 'server') path = normpath(path) if sys.platform == 'cygwin': path = realpath(path) return path
python
def serverdir(): """ Get the location of the server subpackage """ path = join(ROOT_DIR, 'server') path = normpath(path) if sys.platform == 'cygwin': path = realpath(path) return path
[ "def", "serverdir", "(", ")", ":", "path", "=", "join", "(", "ROOT_DIR", ",", "'server'", ")", "path", "=", "normpath", "(", "path", ")", "if", "sys", ".", "platform", "==", "'cygwin'", ":", "path", "=", "realpath", "(", "path", ")", "return", "path"...
Get the location of the server subpackage
[ "Get", "the", "location", "of", "the", "server", "subpackage" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/paths.py#L44-L50
30,417
bokeh/bokeh
bokeh/server/server.py
BaseServer.start
def start(self): ''' Install the Bokeh Server and its background tasks on a Tornado ``IOLoop``. This method does *not* block and does *not* affect the state of the Tornado ``IOLoop`` You must start and stop the loop yourself, i.e. this method is typically useful when you are already explicitly managing an ``IOLoop`` yourself. To start a Bokeh server and immediately "run forever" in a blocking manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`. ''' assert not self._started, "Already started" self._started = True self._tornado.start()
python
def start(self): ''' Install the Bokeh Server and its background tasks on a Tornado ``IOLoop``. This method does *not* block and does *not* affect the state of the Tornado ``IOLoop`` You must start and stop the loop yourself, i.e. this method is typically useful when you are already explicitly managing an ``IOLoop`` yourself. To start a Bokeh server and immediately "run forever" in a blocking manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`. ''' assert not self._started, "Already started" self._started = True self._tornado.start()
[ "def", "start", "(", "self", ")", ":", "assert", "not", "self", ".", "_started", ",", "\"Already started\"", "self", ".", "_started", "=", "True", "self", ".", "_tornado", ".", "start", "(", ")" ]
Install the Bokeh Server and its background tasks on a Tornado ``IOLoop``. This method does *not* block and does *not* affect the state of the Tornado ``IOLoop`` You must start and stop the loop yourself, i.e. this method is typically useful when you are already explicitly managing an ``IOLoop`` yourself. To start a Bokeh server and immediately "run forever" in a blocking manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`.
[ "Install", "the", "Bokeh", "Server", "and", "its", "background", "tasks", "on", "a", "Tornado", "IOLoop", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L120-L135
30,418
bokeh/bokeh
bokeh/server/server.py
BaseServer.stop
def stop(self, wait=True): ''' Stop the Bokeh Server. This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well as stops the ``HTTPServer`` that this instance was configured with. Args: fast (bool): Whether to wait for orderly cleanup (default: True) Returns: None ''' assert not self._stopped, "Already stopped" self._stopped = True self._tornado.stop(wait) self._http.stop()
python
def stop(self, wait=True): ''' Stop the Bokeh Server. This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well as stops the ``HTTPServer`` that this instance was configured with. Args: fast (bool): Whether to wait for orderly cleanup (default: True) Returns: None ''' assert not self._stopped, "Already stopped" self._stopped = True self._tornado.stop(wait) self._http.stop()
[ "def", "stop", "(", "self", ",", "wait", "=", "True", ")", ":", "assert", "not", "self", ".", "_stopped", ",", "\"Already stopped\"", "self", ".", "_stopped", "=", "True", "self", ".", "_tornado", ".", "stop", "(", "wait", ")", "self", ".", "_http", ...
Stop the Bokeh Server. This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well as stops the ``HTTPServer`` that this instance was configured with. Args: fast (bool): Whether to wait for orderly cleanup (default: True) Returns: None
[ "Stop", "the", "Bokeh", "Server", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L137-L154
30,419
bokeh/bokeh
bokeh/server/server.py
BaseServer.get_sessions
def get_sessions(self, app_path=None): ''' Gets all currently active sessions for applications. Args: app_path (str, optional) : The configured application path for the application to return sessions for. If None, return active sessions for all applications. (default: None) Returns: list[ServerSession] ''' if app_path is not None: return self._tornado.get_sessions(app_path) all_sessions = [] for path in self._tornado.app_paths: all_sessions += self._tornado.get_sessions(path) return all_sessions
python
def get_sessions(self, app_path=None): ''' Gets all currently active sessions for applications. Args: app_path (str, optional) : The configured application path for the application to return sessions for. If None, return active sessions for all applications. (default: None) Returns: list[ServerSession] ''' if app_path is not None: return self._tornado.get_sessions(app_path) all_sessions = [] for path in self._tornado.app_paths: all_sessions += self._tornado.get_sessions(path) return all_sessions
[ "def", "get_sessions", "(", "self", ",", "app_path", "=", "None", ")", ":", "if", "app_path", "is", "not", "None", ":", "return", "self", ".", "_tornado", ".", "get_sessions", "(", "app_path", ")", "all_sessions", "=", "[", "]", "for", "path", "in", "s...
Gets all currently active sessions for applications. Args: app_path (str, optional) : The configured application path for the application to return sessions for. If None, return active sessions for all applications. (default: None) Returns: list[ServerSession]
[ "Gets", "all", "currently", "active", "sessions", "for", "applications", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L206-L224
30,420
bokeh/bokeh
bokeh/server/server.py
BaseServer.show
def show(self, app_path, browser=None, new='tab'): ''' Opens an app in a browser window or tab. This method is useful for testing or running Bokeh server applications on a local machine but should not call when running Bokeh server for an actual deployment. Args: app_path (str) : the app path to open The part of the URL after the hostname:port, with leading slash. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : window or tab (default: "tab") If ``new`` is 'tab', then opens a new tab. If ``new`` is 'window', then opens a new window. Returns: None ''' if not app_path.startswith("/"): raise ValueError("app_path must start with a /") address_string = 'localhost' if self.address is not None and self.address != '': address_string = self.address url = "http://%s:%d%s%s" % (address_string, self.port, self.prefix, app_path) from bokeh.util.browser import view view(url, browser=browser, new=new)
python
def show(self, app_path, browser=None, new='tab'): ''' Opens an app in a browser window or tab. This method is useful for testing or running Bokeh server applications on a local machine but should not call when running Bokeh server for an actual deployment. Args: app_path (str) : the app path to open The part of the URL after the hostname:port, with leading slash. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : window or tab (default: "tab") If ``new`` is 'tab', then opens a new tab. If ``new`` is 'window', then opens a new window. Returns: None ''' if not app_path.startswith("/"): raise ValueError("app_path must start with a /") address_string = 'localhost' if self.address is not None and self.address != '': address_string = self.address url = "http://%s:%d%s%s" % (address_string, self.port, self.prefix, app_path) from bokeh.util.browser import view view(url, browser=browser, new=new)
[ "def", "show", "(", "self", ",", "app_path", ",", "browser", "=", "None", ",", "new", "=", "'tab'", ")", ":", "if", "not", "app_path", ".", "startswith", "(", "\"/\"", ")", ":", "raise", "ValueError", "(", "\"app_path must start with a /\"", ")", "address_...
Opens an app in a browser window or tab. This method is useful for testing or running Bokeh server applications on a local machine but should not call when running Bokeh server for an actual deployment. Args: app_path (str) : the app path to open The part of the URL after the hostname:port, with leading slash. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : window or tab (default: "tab") If ``new`` is 'tab', then opens a new tab. If ``new`` is 'window', then opens a new window. Returns: None
[ "Opens", "an", "app", "in", "a", "browser", "window", "or", "tab", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L226-L261
30,421
bokeh/bokeh
bokeh/application/handlers/code_runner.py
CodeRunner.new_module
def new_module(self): ''' Make a fresh module to run in. Returns: Module ''' self.reset_run_errors() if self._code is None: return None module_name = 'bk_script_' + make_id().replace('-', '') module = ModuleType(str(module_name)) # str needed for py2.7 module.__dict__['__file__'] = os.path.abspath(self._path) return module
python
def new_module(self): ''' Make a fresh module to run in. Returns: Module ''' self.reset_run_errors() if self._code is None: return None module_name = 'bk_script_' + make_id().replace('-', '') module = ModuleType(str(module_name)) # str needed for py2.7 module.__dict__['__file__'] = os.path.abspath(self._path) return module
[ "def", "new_module", "(", "self", ")", ":", "self", ".", "reset_run_errors", "(", ")", "if", "self", ".", "_code", "is", "None", ":", "return", "None", "module_name", "=", "'bk_script_'", "+", "make_id", "(", ")", ".", "replace", "(", "'-'", ",", "''",...
Make a fresh module to run in. Returns: Module
[ "Make", "a", "fresh", "module", "to", "run", "in", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/code_runner.py#L129-L145
30,422
bokeh/bokeh
bokeh/application/handlers/code_runner.py
CodeRunner.run
def run(self, module, post_check): ''' Execute the configured source code in a module and run any post checks. Args: module (Module) : a module to execute the configured code in. post_check(callable) : a function that can raise an exception if expected post-conditions are not met after code execution. ''' try: # Simulate the sys.path behaviour decribed here: # # https://docs.python.org/2/library/sys.html#sys.path _cwd = os.getcwd() _sys_path = list(sys.path) _sys_argv = list(sys.argv) sys.path.insert(0, os.path.dirname(self._path)) sys.argv = [os.path.basename(self._path)] + self._argv exec(self._code, module.__dict__) post_check() except Exception as e: self._failed = True self._error_detail = traceback.format_exc() _exc_type, _exc_value, exc_traceback = sys.exc_info() filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1] self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt) finally: # undo sys.path, CWD fixups os.chdir(_cwd) sys.path = _sys_path sys.argv = _sys_argv self.ran = True
python
def run(self, module, post_check): ''' Execute the configured source code in a module and run any post checks. Args: module (Module) : a module to execute the configured code in. post_check(callable) : a function that can raise an exception if expected post-conditions are not met after code execution. ''' try: # Simulate the sys.path behaviour decribed here: # # https://docs.python.org/2/library/sys.html#sys.path _cwd = os.getcwd() _sys_path = list(sys.path) _sys_argv = list(sys.argv) sys.path.insert(0, os.path.dirname(self._path)) sys.argv = [os.path.basename(self._path)] + self._argv exec(self._code, module.__dict__) post_check() except Exception as e: self._failed = True self._error_detail = traceback.format_exc() _exc_type, _exc_value, exc_traceback = sys.exc_info() filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1] self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt) finally: # undo sys.path, CWD fixups os.chdir(_cwd) sys.path = _sys_path sys.argv = _sys_argv self.ran = True
[ "def", "run", "(", "self", ",", "module", ",", "post_check", ")", ":", "try", ":", "# Simulate the sys.path behaviour decribed here:", "#", "# https://docs.python.org/2/library/sys.html#sys.path", "_cwd", "=", "os", ".", "getcwd", "(", ")", "_sys_path", "=", "list", ...
Execute the configured source code in a module and run any post checks. Args: module (Module) : a module to execute the configured code in. post_check(callable) : a function that can raise an exception if expected post-conditions are not met after code execution.
[ "Execute", "the", "configured", "source", "code", "in", "a", "module", "and", "run", "any", "post", "checks", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/code_runner.py#L158-L196
30,423
bokeh/bokeh
bokeh/client/connection.py
ClientConnection.pull_doc
def pull_doc(self, document): ''' Pull a document from the server, overwriting the passed-in document Args: document : (Document) The document to overwrite with server content. Returns: None ''' msg = self._protocol.create('PULL-DOC-REQ') reply = self._send_message_wait_for_reply(msg) if reply is None: raise RuntimeError("Connection to server was lost") elif reply.header['msgtype'] == 'ERROR': raise RuntimeError("Failed to pull document: " + reply.content['text']) else: reply.push_to_document(document)
python
def pull_doc(self, document): ''' Pull a document from the server, overwriting the passed-in document Args: document : (Document) The document to overwrite with server content. Returns: None ''' msg = self._protocol.create('PULL-DOC-REQ') reply = self._send_message_wait_for_reply(msg) if reply is None: raise RuntimeError("Connection to server was lost") elif reply.header['msgtype'] == 'ERROR': raise RuntimeError("Failed to pull document: " + reply.content['text']) else: reply.push_to_document(document)
[ "def", "pull_doc", "(", "self", ",", "document", ")", ":", "msg", "=", "self", ".", "_protocol", ".", "create", "(", "'PULL-DOC-REQ'", ")", "reply", "=", "self", ".", "_send_message_wait_for_reply", "(", "msg", ")", "if", "reply", "is", "None", ":", "rai...
Pull a document from the server, overwriting the passed-in document Args: document : (Document) The document to overwrite with server content. Returns: None
[ "Pull", "a", "document", "from", "the", "server", "overwriting", "the", "passed", "-", "in", "document" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/connection.py#L153-L171
30,424
bokeh/bokeh
bokeh/client/connection.py
ClientConnection.push_doc
def push_doc(self, document): ''' Push a document to the server, overwriting any existing server-side doc. Args: document : (Document) A Document to push to the server Returns: The server reply ''' msg = self._protocol.create('PUSH-DOC', document) reply = self._send_message_wait_for_reply(msg) if reply is None: raise RuntimeError("Connection to server was lost") elif reply.header['msgtype'] == 'ERROR': raise RuntimeError("Failed to push document: " + reply.content['text']) else: return reply
python
def push_doc(self, document): ''' Push a document to the server, overwriting any existing server-side doc. Args: document : (Document) A Document to push to the server Returns: The server reply ''' msg = self._protocol.create('PUSH-DOC', document) reply = self._send_message_wait_for_reply(msg) if reply is None: raise RuntimeError("Connection to server was lost") elif reply.header['msgtype'] == 'ERROR': raise RuntimeError("Failed to push document: " + reply.content['text']) else: return reply
[ "def", "push_doc", "(", "self", ",", "document", ")", ":", "msg", "=", "self", ".", "_protocol", ".", "create", "(", "'PUSH-DOC'", ",", "document", ")", "reply", "=", "self", ".", "_send_message_wait_for_reply", "(", "msg", ")", "if", "reply", "is", "Non...
Push a document to the server, overwriting any existing server-side doc. Args: document : (Document) A Document to push to the server Returns: The server reply
[ "Push", "a", "document", "to", "the", "server", "overwriting", "any", "existing", "server", "-", "side", "doc", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/connection.py#L173-L191
30,425
bokeh/bokeh
bokeh/client/connection.py
ClientConnection.request_server_info
def request_server_info(self): ''' Ask for information about the server. Returns: A dictionary of server attributes. ''' if self._server_info is None: self._server_info = self._send_request_server_info() return self._server_info
python
def request_server_info(self): ''' Ask for information about the server. Returns: A dictionary of server attributes. ''' if self._server_info is None: self._server_info = self._send_request_server_info() return self._server_info
[ "def", "request_server_info", "(", "self", ")", ":", "if", "self", ".", "_server_info", "is", "None", ":", "self", ".", "_server_info", "=", "self", ".", "_send_request_server_info", "(", ")", "return", "self", ".", "_server_info" ]
Ask for information about the server. Returns: A dictionary of server attributes.
[ "Ask", "for", "information", "about", "the", "server", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/connection.py#L193-L202
30,426
bokeh/bokeh
bokeh/io/export.py
export_png
def export_png(obj, filename=None, height=None, width=None, webdriver=None, timeout=5): ''' Export the ``LayoutDOM`` object or document as a PNG. If the filename is not given, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.png``) Args: obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget object or Document to export. filename (str, optional) : filename to save document under (default: None) If None, infer from the filename. height (int) : the desired height of the exported layout obj only if it's a Plot instance. Otherwise the height kwarg is ignored. width (int) : the desired width of the exported layout obj only if it's a Plot instance. Otherwise the width kwarg is ignored. webdriver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time (in seconds) to wait for Bokeh to initialize (default: 5) (Added in 1.1.1). Returns: filename (str) : the filename where the static file is saved. If you would like to access an Image object directly, rather than save a file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png` function. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode. ''' image = get_screenshot_as_png(obj, height=height, width=width, driver=webdriver, timeout=timeout) if filename is None: filename = default_filename("png") if image.width == 0 or image.height == 0: raise ValueError("unable to save an empty image") image.save(filename) return abspath(filename)
python
def export_png(obj, filename=None, height=None, width=None, webdriver=None, timeout=5): ''' Export the ``LayoutDOM`` object or document as a PNG. If the filename is not given, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.png``) Args: obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget object or Document to export. filename (str, optional) : filename to save document under (default: None) If None, infer from the filename. height (int) : the desired height of the exported layout obj only if it's a Plot instance. Otherwise the height kwarg is ignored. width (int) : the desired width of the exported layout obj only if it's a Plot instance. Otherwise the width kwarg is ignored. webdriver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time (in seconds) to wait for Bokeh to initialize (default: 5) (Added in 1.1.1). Returns: filename (str) : the filename where the static file is saved. If you would like to access an Image object directly, rather than save a file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png` function. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode. ''' image = get_screenshot_as_png(obj, height=height, width=width, driver=webdriver, timeout=timeout) if filename is None: filename = default_filename("png") if image.width == 0 or image.height == 0: raise ValueError("unable to save an empty image") image.save(filename) return abspath(filename)
[ "def", "export_png", "(", "obj", ",", "filename", "=", "None", ",", "height", "=", "None", ",", "width", "=", "None", ",", "webdriver", "=", "None", ",", "timeout", "=", "5", ")", ":", "image", "=", "get_screenshot_as_png", "(", "obj", ",", "height", ...
Export the ``LayoutDOM`` object or document as a PNG. If the filename is not given, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.png``) Args: obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget object or Document to export. filename (str, optional) : filename to save document under (default: None) If None, infer from the filename. height (int) : the desired height of the exported layout obj only if it's a Plot instance. Otherwise the height kwarg is ignored. width (int) : the desired width of the exported layout obj only if it's a Plot instance. Otherwise the width kwarg is ignored. webdriver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time (in seconds) to wait for Bokeh to initialize (default: 5) (Added in 1.1.1). Returns: filename (str) : the filename where the static file is saved. If you would like to access an Image object directly, rather than save a file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png` function. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
[ "Export", "the", "LayoutDOM", "object", "or", "document", "as", "a", "PNG", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L59-L107
30,427
bokeh/bokeh
bokeh/io/export.py
export_svgs
def export_svgs(obj, filename=None, height=None, width=None, webdriver=None, timeout=5): ''' Export the SVG-enabled plots within a layout. Each plot will result in a distinct SVG file. If the filename is not given, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``) Args: obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display filename (str, optional) : filename to save document under (default: None) If None, infer from the filename. height (int) : the desired height of the exported layout obj only if it's a Plot instance. Otherwise the height kwarg is ignored. width (int) : the desired width of the exported layout obj only if it's a Plot instance. Otherwise the width kwarg is ignored. webdriver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time (in seconds) to wait for Bokeh to initialize (default: 5) (Added in 1.1.1). Returns: filenames (list(str)) : the list of filenames where the SVGs files are saved. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode. ''' svgs = get_svgs(obj, height=height, width=width, driver=webdriver, timeout=timeout) if len(svgs) == 0: log.warning("No SVG Plots were found.") return if filename is None: filename = default_filename("svg") filenames = [] for i, svg in enumerate(svgs): if i == 0: filename = filename else: idx = filename.find(".svg") filename = filename[:idx] + "_{}".format(i) + filename[idx:] with io.open(filename, mode="w", encoding="utf-8") as f: f.write(svg) filenames.append(filename) return filenames
python
def export_svgs(obj, filename=None, height=None, width=None, webdriver=None, timeout=5): ''' Export the SVG-enabled plots within a layout. Each plot will result in a distinct SVG file. If the filename is not given, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``) Args: obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display filename (str, optional) : filename to save document under (default: None) If None, infer from the filename. height (int) : the desired height of the exported layout obj only if it's a Plot instance. Otherwise the height kwarg is ignored. width (int) : the desired width of the exported layout obj only if it's a Plot instance. Otherwise the width kwarg is ignored. webdriver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time (in seconds) to wait for Bokeh to initialize (default: 5) (Added in 1.1.1). Returns: filenames (list(str)) : the list of filenames where the SVGs files are saved. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode. ''' svgs = get_svgs(obj, height=height, width=width, driver=webdriver, timeout=timeout) if len(svgs) == 0: log.warning("No SVG Plots were found.") return if filename is None: filename = default_filename("svg") filenames = [] for i, svg in enumerate(svgs): if i == 0: filename = filename else: idx = filename.find(".svg") filename = filename[:idx] + "_{}".format(i) + filename[idx:] with io.open(filename, mode="w", encoding="utf-8") as f: f.write(svg) filenames.append(filename) return filenames
[ "def", "export_svgs", "(", "obj", ",", "filename", "=", "None", ",", "height", "=", "None", ",", "width", "=", "None", ",", "webdriver", "=", "None", ",", "timeout", "=", "5", ")", ":", "svgs", "=", "get_svgs", "(", "obj", ",", "height", "=", "heig...
Export the SVG-enabled plots within a layout. Each plot will result in a distinct SVG file. If the filename is not given, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``) Args: obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display filename (str, optional) : filename to save document under (default: None) If None, infer from the filename. height (int) : the desired height of the exported layout obj only if it's a Plot instance. Otherwise the height kwarg is ignored. width (int) : the desired width of the exported layout obj only if it's a Plot instance. Otherwise the width kwarg is ignored. webdriver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time (in seconds) to wait for Bokeh to initialize (default: 5) (Added in 1.1.1). Returns: filenames (list(str)) : the list of filenames where the SVGs files are saved. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
[ "Export", "the", "SVG", "-", "enabled", "plots", "within", "a", "layout", ".", "Each", "plot", "will", "result", "in", "a", "distinct", "SVG", "file", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L109-L166
30,428
bokeh/bokeh
bokeh/io/export.py
get_screenshot_as_png
def get_screenshot_as_png(obj, driver=None, timeout=5, **kwargs): ''' Get a screenshot of a ``LayoutDOM`` object. Args: obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget object or Document to export. driver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time to wait for initialization. It will be used as a timeout for loading Bokeh, then when waiting for the layout to be rendered. Returns: cropped_image (PIL.Image.Image) : a pillow image loaded from PNG. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode. ''' Image = import_required('PIL.Image', 'To use bokeh.io.export_png you need pillow ' + '("conda install pillow" or "pip install pillow")') with _tmp_html() as tmp: html = get_layout_html(obj, **kwargs) with io.open(tmp.path, mode="w", encoding="utf-8") as file: file.write(decode_utf8(html)) web_driver = driver if driver is not None else webdriver_control.get() web_driver.get("file:///" + tmp.path) web_driver.maximize_window() ## resize for PhantomJS compat web_driver.execute_script("document.body.style.width = '100%';") wait_until_render_complete(web_driver, timeout) png = web_driver.get_screenshot_as_png() b_rect = web_driver.execute_script(_BOUNDING_RECT_SCRIPT) image = Image.open(io.BytesIO(png)) cropped_image = _crop_image(image, **b_rect) return cropped_image
python
def get_screenshot_as_png(obj, driver=None, timeout=5, **kwargs): ''' Get a screenshot of a ``LayoutDOM`` object. Args: obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget object or Document to export. driver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time to wait for initialization. It will be used as a timeout for loading Bokeh, then when waiting for the layout to be rendered. Returns: cropped_image (PIL.Image.Image) : a pillow image loaded from PNG. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode. ''' Image = import_required('PIL.Image', 'To use bokeh.io.export_png you need pillow ' + '("conda install pillow" or "pip install pillow")') with _tmp_html() as tmp: html = get_layout_html(obj, **kwargs) with io.open(tmp.path, mode="w", encoding="utf-8") as file: file.write(decode_utf8(html)) web_driver = driver if driver is not None else webdriver_control.get() web_driver.get("file:///" + tmp.path) web_driver.maximize_window() ## resize for PhantomJS compat web_driver.execute_script("document.body.style.width = '100%';") wait_until_render_complete(web_driver, timeout) png = web_driver.get_screenshot_as_png() b_rect = web_driver.execute_script(_BOUNDING_RECT_SCRIPT) image = Image.open(io.BytesIO(png)) cropped_image = _crop_image(image, **b_rect) return cropped_image
[ "def", "get_screenshot_as_png", "(", "obj", ",", "driver", "=", "None", ",", "timeout", "=", "5", ",", "*", "*", "kwargs", ")", ":", "Image", "=", "import_required", "(", "'PIL.Image'", ",", "'To use bokeh.io.export_png you need pillow '", "+", "'(\"conda install ...
Get a screenshot of a ``LayoutDOM`` object. Args: obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget object or Document to export. driver (selenium.webdriver) : a selenium webdriver instance to use to export the image. timeout (int) : the maximum amount of time to wait for initialization. It will be used as a timeout for loading Bokeh, then when waiting for the layout to be rendered. Returns: cropped_image (PIL.Image.Image) : a pillow image loaded from PNG. .. warning:: Responsive sizing_modes may generate layouts with unexpected size and aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
[ "Get", "a", "screenshot", "of", "a", "LayoutDOM", "object", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L186-L234
30,429
bokeh/bokeh
bokeh/io/export.py
_crop_image
def _crop_image(image, left=0, top=0, right=0, bottom=0, **kwargs): ''' Crop the border from the layout ''' return image.crop((left, top, right, bottom))
python
def _crop_image(image, left=0, top=0, right=0, bottom=0, **kwargs): ''' Crop the border from the layout ''' return image.crop((left, top, right, bottom))
[ "def", "_crop_image", "(", "image", ",", "left", "=", "0", ",", "top", "=", "0", ",", "right", "=", "0", ",", "bottom", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "image", ".", "crop", "(", "(", "left", ",", "top", ",", "right", "...
Crop the border from the layout
[ "Crop", "the", "border", "from", "the", "layout" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L354-L358
30,430
bokeh/bokeh
bokeh/models/sources.py
ColumnDataSource._data_from_df
def _data_from_df(df): ''' Create a ``dict`` of columns from a Pandas ``DataFrame``, suitable for creating a ColumnDataSource. Args: df (DataFrame) : data to convert Returns: dict[str, np.array] ''' _df = df.copy() # Flatten columns if isinstance(df.columns, pd.MultiIndex): try: _df.columns = ['_'.join(col) for col in _df.columns.values] except TypeError: raise TypeError('Could not flatten MultiIndex columns. ' 'use string column names or flatten manually') # Transform columns CategoricalIndex in list if isinstance(df.columns, pd.CategoricalIndex): _df.columns = df.columns.tolist() # Flatten index index_name = ColumnDataSource._df_index_name(df) if index_name == 'index': _df.index = pd.Index(_df.index.values) else: _df.index = pd.Index(_df.index.values, name=index_name) _df.reset_index(inplace=True) tmp_data = {c: v.values for c, v in _df.iteritems()} new_data = {} for k, v in tmp_data.items(): new_data[k] = v return new_data
python
def _data_from_df(df): ''' Create a ``dict`` of columns from a Pandas ``DataFrame``, suitable for creating a ColumnDataSource. Args: df (DataFrame) : data to convert Returns: dict[str, np.array] ''' _df = df.copy() # Flatten columns if isinstance(df.columns, pd.MultiIndex): try: _df.columns = ['_'.join(col) for col in _df.columns.values] except TypeError: raise TypeError('Could not flatten MultiIndex columns. ' 'use string column names or flatten manually') # Transform columns CategoricalIndex in list if isinstance(df.columns, pd.CategoricalIndex): _df.columns = df.columns.tolist() # Flatten index index_name = ColumnDataSource._df_index_name(df) if index_name == 'index': _df.index = pd.Index(_df.index.values) else: _df.index = pd.Index(_df.index.values, name=index_name) _df.reset_index(inplace=True) tmp_data = {c: v.values for c, v in _df.iteritems()} new_data = {} for k, v in tmp_data.items(): new_data[k] = v return new_data
[ "def", "_data_from_df", "(", "df", ")", ":", "_df", "=", "df", ".", "copy", "(", ")", "# Flatten columns", "if", "isinstance", "(", "df", ".", "columns", ",", "pd", ".", "MultiIndex", ")", ":", "try", ":", "_df", ".", "columns", "=", "[", "'_'", "....
Create a ``dict`` of columns from a Pandas ``DataFrame``, suitable for creating a ColumnDataSource. Args: df (DataFrame) : data to convert Returns: dict[str, np.array]
[ "Create", "a", "dict", "of", "columns", "from", "a", "Pandas", "DataFrame", "suitable", "for", "creating", "a", "ColumnDataSource", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L195-L232
30,431
bokeh/bokeh
bokeh/models/sources.py
ColumnDataSource._df_index_name
def _df_index_name(df): ''' Return the Bokeh-appropriate column name for a ``DataFrame`` index If there is no named index, then `"index" is returned. If there is a single named index, then ``df.index.name`` is returned. If there is a multi-index, and the index names are all strings, then the names are joined with '_' and the result is returned, e.g. for a multi-index ``['ind1', 'ind2']`` the result will be "ind1_ind2". Otherwise if any index name is not a string, the fallback name "index" is returned. Args: df (DataFrame) : the ``DataFrame`` to find an index name for Returns: str ''' if df.index.name: return df.index.name elif df.index.names: try: return "_".join(df.index.names) except TypeError: return "index" else: return "index"
python
def _df_index_name(df): ''' Return the Bokeh-appropriate column name for a ``DataFrame`` index If there is no named index, then `"index" is returned. If there is a single named index, then ``df.index.name`` is returned. If there is a multi-index, and the index names are all strings, then the names are joined with '_' and the result is returned, e.g. for a multi-index ``['ind1', 'ind2']`` the result will be "ind1_ind2". Otherwise if any index name is not a string, the fallback name "index" is returned. Args: df (DataFrame) : the ``DataFrame`` to find an index name for Returns: str ''' if df.index.name: return df.index.name elif df.index.names: try: return "_".join(df.index.names) except TypeError: return "index" else: return "index"
[ "def", "_df_index_name", "(", "df", ")", ":", "if", "df", ".", "index", ".", "name", ":", "return", "df", ".", "index", ".", "name", "elif", "df", ".", "index", ".", "names", ":", "try", ":", "return", "\"_\"", ".", "join", "(", "df", ".", "index...
Return the Bokeh-appropriate column name for a ``DataFrame`` index If there is no named index, then `"index" is returned. If there is a single named index, then ``df.index.name`` is returned. If there is a multi-index, and the index names are all strings, then the names are joined with '_' and the result is returned, e.g. for a multi-index ``['ind1', 'ind2']`` the result will be "ind1_ind2". Otherwise if any index name is not a string, the fallback name "index" is returned. Args: df (DataFrame) : the ``DataFrame`` to find an index name for Returns: str
[ "Return", "the", "Bokeh", "-", "appropriate", "column", "name", "for", "a", "DataFrame", "index" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L252-L280
30,432
bokeh/bokeh
bokeh/models/sources.py
ColumnDataSource.add
def add(self, data, name=None): ''' Appends a new column of data to the data source. Args: data (seq) : new data to add name (str, optional) : column name to use. If not supplied, generate a name of the form "Series ####" Returns: str: the column name used ''' if name is None: n = len(self.data) while "Series %d"%n in self.data: n += 1 name = "Series %d"%n self.data[name] = data return name
python
def add(self, data, name=None): ''' Appends a new column of data to the data source. Args: data (seq) : new data to add name (str, optional) : column name to use. If not supplied, generate a name of the form "Series ####" Returns: str: the column name used ''' if name is None: n = len(self.data) while "Series %d"%n in self.data: n += 1 name = "Series %d"%n self.data[name] = data return name
[ "def", "add", "(", "self", ",", "data", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "n", "=", "len", "(", "self", ".", "data", ")", "while", "\"Series %d\"", "%", "n", "in", "self", ".", "data", ":", "n", "+=", "1", "...
Appends a new column of data to the data source. Args: data (seq) : new data to add name (str, optional) : column name to use. If not supplied, generate a name of the form "Series ####" Returns: str: the column name used
[ "Appends", "a", "new", "column", "of", "data", "to", "the", "data", "source", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L325-L343
30,433
bokeh/bokeh
bokeh/models/sources.py
ColumnDataSource.remove
def remove(self, name): ''' Remove a column of data. Args: name (str) : name of the column to remove Returns: None .. note:: If the column name does not exist, a warning is issued. ''' try: del self.data[name] except (ValueError, KeyError): import warnings warnings.warn("Unable to find column '%s' in data source" % name)
python
def remove(self, name): ''' Remove a column of data. Args: name (str) : name of the column to remove Returns: None .. note:: If the column name does not exist, a warning is issued. ''' try: del self.data[name] except (ValueError, KeyError): import warnings warnings.warn("Unable to find column '%s' in data source" % name)
[ "def", "remove", "(", "self", ",", "name", ")", ":", "try", ":", "del", "self", ".", "data", "[", "name", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Unable to find column '%s' in data...
Remove a column of data. Args: name (str) : name of the column to remove Returns: None .. note:: If the column name does not exist, a warning is issued.
[ "Remove", "a", "column", "of", "data", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L346-L363
30,434
bokeh/bokeh
bokeh/models/sources.py
ColumnDataSource.patch
def patch(self, patches, setter=None): ''' Efficiently update data source columns at specific locations If it is only necessary to update a small subset of data in a ``ColumnDataSource``, this method can be used to efficiently update only the subset, instead of requiring the entire data set to be sent. This method should be passed a dictionary that maps column names to lists of tuples that describe a patch change to apply. To replace individual items in columns entirely, the tuples should be of the form: .. code-block:: python (index, new_value) # replace a single column value # or (slice, new_values) # replace several column values Values at an index or slice will be replaced with the corresponding new values. In the case of columns whose values are other arrays or lists, (e.g. image or patches glyphs), it is also possible to patch "subregions". In this case the first item of the tuple should be a whose first element is the index of the array item in the CDS patch, and whose subsequent elements are integer indices or slices into the array item: .. code-block:: python # replace the entire 10th column of the 2nd array: +----------------- index of item in column data source | | +--------- row subindex into array item | | | | +- column subindex into array item V V V ([2, slice(None), 10], new_values) Imagining a list of 2d NumPy arrays, the patch above is roughly equivalent to: .. code-block:: python data = [arr1, arr2, ...] # list of 2d arrays data[2][:, 10] = new_data There are some limitations to the kinds of slices and data that can be accepted. * Negative ``start``, ``stop``, or ``step`` values for slices will result in a ``ValueError``. * In a slice, ``start > stop`` will result in a ``ValueError`` * When patching 1d or 2d subitems, the subitems must be NumPy arrays. * New values must be supplied as a **flattened one-dimensional array** of the appropriate size. Args: patches (dict[str, list[tuple]]) : lists of patches for each column Returns: None Raises: ValueError Example: The following example shows how to patch entire column elements. In this case, .. code-block:: python source = ColumnDataSource(data=dict(foo=[10, 20, 30], bar=[100, 200, 300])) patches = { 'foo' : [ (slice(2), [11, 12]) ], 'bar' : [ (0, 101), (2, 301) ], } source.patch(patches) After this operation, the value of the ``source.data`` will be: .. code-block:: python dict(foo=[11, 12, 30], bar=[101, 200, 301]) For a more comprehensive complete example, see :bokeh-tree:`examples/howto/patch_app.py`. ''' import numpy as np extra = set(patches.keys()) - set(self.data.keys()) if extra: raise ValueError("Can only patch existing columns (extra: %s)" % ", ".join(sorted(extra))) for name, patch in patches.items(): col_len = len(self.data[name]) for ind, value in patch: # integer index, patch single value of 1d column if isinstance(ind, int): if ind > col_len or ind < 0: raise ValueError("Out-of bounds index (%d) in patch for column: %s" % (ind, name)) # slice index, patch multiple values of 1d column elif isinstance(ind, slice): _check_slice(ind) if ind.stop is not None and ind.stop > col_len: raise ValueError("Out-of bounds slice index stop (%d) in patch for column: %s" % (ind.stop, name)) # multi-index, patch sub-regions of "n-d" column elif isinstance(ind, (list, tuple)): if len(ind) == 0: raise ValueError("Empty (length zero) patch multi-index") if len(ind) == 1: raise ValueError("Patch multi-index must contain more than one subindex") if not isinstance(ind[0], int): raise ValueError("Initial patch sub-index may only be integer, got: %s" % ind[0]) if ind[0] > col_len or ind[0] < 0: raise ValueError("Out-of bounds initial sub-index (%d) in patch for column: %s" % (ind, name)) if not isinstance(self.data[name][ind[0]], np.ndarray): raise ValueError("Can only sub-patch into columns with NumPy array items") if len(self.data[name][ind[0]].shape) != (len(ind)-1): raise ValueError("Shape mismatch between patch slice and sliced data") elif isinstance(ind[0], slice): _check_slice(ind[0]) if ind[0].stop is not None and ind[0].stop > col_len: raise ValueError("Out-of bounds initial slice sub-index stop (%d) in patch for column: %s" % (ind.stop, name)) # Note: bounds of sub-indices after the first are not checked! for subind in ind[1:]: if not isinstance(subind, (int, slice)): raise ValueError("Invalid patch sub-index: %s" % subind) if isinstance(subind, slice): _check_slice(subind) else: raise ValueError("Invalid patch index: %s" % ind) self.data._patch(self.document, self, patches, setter)
python
def patch(self, patches, setter=None): ''' Efficiently update data source columns at specific locations If it is only necessary to update a small subset of data in a ``ColumnDataSource``, this method can be used to efficiently update only the subset, instead of requiring the entire data set to be sent. This method should be passed a dictionary that maps column names to lists of tuples that describe a patch change to apply. To replace individual items in columns entirely, the tuples should be of the form: .. code-block:: python (index, new_value) # replace a single column value # or (slice, new_values) # replace several column values Values at an index or slice will be replaced with the corresponding new values. In the case of columns whose values are other arrays or lists, (e.g. image or patches glyphs), it is also possible to patch "subregions". In this case the first item of the tuple should be a whose first element is the index of the array item in the CDS patch, and whose subsequent elements are integer indices or slices into the array item: .. code-block:: python # replace the entire 10th column of the 2nd array: +----------------- index of item in column data source | | +--------- row subindex into array item | | | | +- column subindex into array item V V V ([2, slice(None), 10], new_values) Imagining a list of 2d NumPy arrays, the patch above is roughly equivalent to: .. code-block:: python data = [arr1, arr2, ...] # list of 2d arrays data[2][:, 10] = new_data There are some limitations to the kinds of slices and data that can be accepted. * Negative ``start``, ``stop``, or ``step`` values for slices will result in a ``ValueError``. * In a slice, ``start > stop`` will result in a ``ValueError`` * When patching 1d or 2d subitems, the subitems must be NumPy arrays. * New values must be supplied as a **flattened one-dimensional array** of the appropriate size. Args: patches (dict[str, list[tuple]]) : lists of patches for each column Returns: None Raises: ValueError Example: The following example shows how to patch entire column elements. In this case, .. code-block:: python source = ColumnDataSource(data=dict(foo=[10, 20, 30], bar=[100, 200, 300])) patches = { 'foo' : [ (slice(2), [11, 12]) ], 'bar' : [ (0, 101), (2, 301) ], } source.patch(patches) After this operation, the value of the ``source.data`` will be: .. code-block:: python dict(foo=[11, 12, 30], bar=[101, 200, 301]) For a more comprehensive complete example, see :bokeh-tree:`examples/howto/patch_app.py`. ''' import numpy as np extra = set(patches.keys()) - set(self.data.keys()) if extra: raise ValueError("Can only patch existing columns (extra: %s)" % ", ".join(sorted(extra))) for name, patch in patches.items(): col_len = len(self.data[name]) for ind, value in patch: # integer index, patch single value of 1d column if isinstance(ind, int): if ind > col_len or ind < 0: raise ValueError("Out-of bounds index (%d) in patch for column: %s" % (ind, name)) # slice index, patch multiple values of 1d column elif isinstance(ind, slice): _check_slice(ind) if ind.stop is not None and ind.stop > col_len: raise ValueError("Out-of bounds slice index stop (%d) in patch for column: %s" % (ind.stop, name)) # multi-index, patch sub-regions of "n-d" column elif isinstance(ind, (list, tuple)): if len(ind) == 0: raise ValueError("Empty (length zero) patch multi-index") if len(ind) == 1: raise ValueError("Patch multi-index must contain more than one subindex") if not isinstance(ind[0], int): raise ValueError("Initial patch sub-index may only be integer, got: %s" % ind[0]) if ind[0] > col_len or ind[0] < 0: raise ValueError("Out-of bounds initial sub-index (%d) in patch for column: %s" % (ind, name)) if not isinstance(self.data[name][ind[0]], np.ndarray): raise ValueError("Can only sub-patch into columns with NumPy array items") if len(self.data[name][ind[0]].shape) != (len(ind)-1): raise ValueError("Shape mismatch between patch slice and sliced data") elif isinstance(ind[0], slice): _check_slice(ind[0]) if ind[0].stop is not None and ind[0].stop > col_len: raise ValueError("Out-of bounds initial slice sub-index stop (%d) in patch for column: %s" % (ind.stop, name)) # Note: bounds of sub-indices after the first are not checked! for subind in ind[1:]: if not isinstance(subind, (int, slice)): raise ValueError("Invalid patch sub-index: %s" % subind) if isinstance(subind, slice): _check_slice(subind) else: raise ValueError("Invalid patch index: %s" % ind) self.data._patch(self.document, self, patches, setter)
[ "def", "patch", "(", "self", ",", "patches", ",", "setter", "=", "None", ")", ":", "import", "numpy", "as", "np", "extra", "=", "set", "(", "patches", ".", "keys", "(", ")", ")", "-", "set", "(", "self", ".", "data", ".", "keys", "(", ")", ")",...
Efficiently update data source columns at specific locations If it is only necessary to update a small subset of data in a ``ColumnDataSource``, this method can be used to efficiently update only the subset, instead of requiring the entire data set to be sent. This method should be passed a dictionary that maps column names to lists of tuples that describe a patch change to apply. To replace individual items in columns entirely, the tuples should be of the form: .. code-block:: python (index, new_value) # replace a single column value # or (slice, new_values) # replace several column values Values at an index or slice will be replaced with the corresponding new values. In the case of columns whose values are other arrays or lists, (e.g. image or patches glyphs), it is also possible to patch "subregions". In this case the first item of the tuple should be a whose first element is the index of the array item in the CDS patch, and whose subsequent elements are integer indices or slices into the array item: .. code-block:: python # replace the entire 10th column of the 2nd array: +----------------- index of item in column data source | | +--------- row subindex into array item | | | | +- column subindex into array item V V V ([2, slice(None), 10], new_values) Imagining a list of 2d NumPy arrays, the patch above is roughly equivalent to: .. code-block:: python data = [arr1, arr2, ...] # list of 2d arrays data[2][:, 10] = new_data There are some limitations to the kinds of slices and data that can be accepted. * Negative ``start``, ``stop``, or ``step`` values for slices will result in a ``ValueError``. * In a slice, ``start > stop`` will result in a ``ValueError`` * When patching 1d or 2d subitems, the subitems must be NumPy arrays. * New values must be supplied as a **flattened one-dimensional array** of the appropriate size. Args: patches (dict[str, list[tuple]]) : lists of patches for each column Returns: None Raises: ValueError Example: The following example shows how to patch entire column elements. In this case, .. code-block:: python source = ColumnDataSource(data=dict(foo=[10, 20, 30], bar=[100, 200, 300])) patches = { 'foo' : [ (slice(2), [11, 12]) ], 'bar' : [ (0, 101), (2, 301) ], } source.patch(patches) After this operation, the value of the ``source.data`` will be: .. code-block:: python dict(foo=[11, 12, 30], bar=[101, 200, 301]) For a more comprehensive complete example, see :bokeh-tree:`examples/howto/patch_app.py`.
[ "Efficiently", "update", "data", "source", "columns", "at", "specific", "locations" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L519-L674
30,435
bokeh/bokeh
bokeh/core/validation/check.py
silence
def silence(warning, silence=True): ''' Silence a particular warning on all Bokeh models. Args: warning (Warning) : Bokeh warning to silence silence (bool) : Whether or not to silence the warning Returns: A set containing the all silenced warnings This function adds or removes warnings from a set of silencers which is referred to when running ``check_integrity``. If a warning is added to the silencers - then it will never be raised. .. code-block:: python >>> from bokeh.core.validation.warnings import EMPTY_LAYOUT >>> bokeh.core.validation.silence(EMPTY_LAYOUT, True) {1002} To turn a warning back on use the same method but with the silence argument set to false .. code-block:: python >>> bokeh.core.validation.silence(EMPTY_LAYOUT, False) set() ''' if not isinstance(warning, int): raise ValueError('Input to silence should be a warning object ' '- not of type {}'.format(type(warning))) if silence: __silencers__.add(warning) elif warning in __silencers__: __silencers__.remove(warning) return __silencers__
python
def silence(warning, silence=True): ''' Silence a particular warning on all Bokeh models. Args: warning (Warning) : Bokeh warning to silence silence (bool) : Whether or not to silence the warning Returns: A set containing the all silenced warnings This function adds or removes warnings from a set of silencers which is referred to when running ``check_integrity``. If a warning is added to the silencers - then it will never be raised. .. code-block:: python >>> from bokeh.core.validation.warnings import EMPTY_LAYOUT >>> bokeh.core.validation.silence(EMPTY_LAYOUT, True) {1002} To turn a warning back on use the same method but with the silence argument set to false .. code-block:: python >>> bokeh.core.validation.silence(EMPTY_LAYOUT, False) set() ''' if not isinstance(warning, int): raise ValueError('Input to silence should be a warning object ' '- not of type {}'.format(type(warning))) if silence: __silencers__.add(warning) elif warning in __silencers__: __silencers__.remove(warning) return __silencers__
[ "def", "silence", "(", "warning", ",", "silence", "=", "True", ")", ":", "if", "not", "isinstance", "(", "warning", ",", "int", ")", ":", "raise", "ValueError", "(", "'Input to silence should be a warning object '", "'- not of type {}'", ".", "format", "(", "typ...
Silence a particular warning on all Bokeh models. Args: warning (Warning) : Bokeh warning to silence silence (bool) : Whether or not to silence the warning Returns: A set containing the all silenced warnings This function adds or removes warnings from a set of silencers which is referred to when running ``check_integrity``. If a warning is added to the silencers - then it will never be raised. .. code-block:: python >>> from bokeh.core.validation.warnings import EMPTY_LAYOUT >>> bokeh.core.validation.silence(EMPTY_LAYOUT, True) {1002} To turn a warning back on use the same method but with the silence argument set to false .. code-block:: python >>> bokeh.core.validation.silence(EMPTY_LAYOUT, False) set()
[ "Silence", "a", "particular", "warning", "on", "all", "Bokeh", "models", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/validation/check.py#L43-L79
30,436
bokeh/bokeh
bokeh/core/validation/check.py
check_integrity
def check_integrity(models): ''' Apply validation and integrity checks to a collection of Bokeh models. Args: models (seq[Model]) : a collection of Models to test Returns: None This function will emit log warning and error messages for all error or warning conditions that are detected. For example, layouts without any children will trigger a warning: .. code-block:: python >>> empty_row = Row >>> check_integrity([empty_row]) W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...) ''' messages = dict(error=[], warning=[]) for model in models: validators = [] for name in dir(model): if not name.startswith("_check"): continue obj = getattr(model, name) if getattr(obj, "validator_type", None): validators.append(obj) for func in validators: messages[func.validator_type].extend(func()) for msg in sorted(messages['error']): log.error("E-%d (%s): %s: %s" % msg) for msg in sorted(messages['warning']): code, name, desc, obj = msg if code not in __silencers__: log.warning("W-%d (%s): %s: %s" % msg)
python
def check_integrity(models): ''' Apply validation and integrity checks to a collection of Bokeh models. Args: models (seq[Model]) : a collection of Models to test Returns: None This function will emit log warning and error messages for all error or warning conditions that are detected. For example, layouts without any children will trigger a warning: .. code-block:: python >>> empty_row = Row >>> check_integrity([empty_row]) W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...) ''' messages = dict(error=[], warning=[]) for model in models: validators = [] for name in dir(model): if not name.startswith("_check"): continue obj = getattr(model, name) if getattr(obj, "validator_type", None): validators.append(obj) for func in validators: messages[func.validator_type].extend(func()) for msg in sorted(messages['error']): log.error("E-%d (%s): %s: %s" % msg) for msg in sorted(messages['warning']): code, name, desc, obj = msg if code not in __silencers__: log.warning("W-%d (%s): %s: %s" % msg)
[ "def", "check_integrity", "(", "models", ")", ":", "messages", "=", "dict", "(", "error", "=", "[", "]", ",", "warning", "=", "[", "]", ")", "for", "model", "in", "models", ":", "validators", "=", "[", "]", "for", "name", "in", "dir", "(", "model",...
Apply validation and integrity checks to a collection of Bokeh models. Args: models (seq[Model]) : a collection of Models to test Returns: None This function will emit log warning and error messages for all error or warning conditions that are detected. For example, layouts without any children will trigger a warning: .. code-block:: python >>> empty_row = Row >>> check_integrity([empty_row]) W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...)
[ "Apply", "validation", "and", "integrity", "checks", "to", "a", "collection", "of", "Bokeh", "models", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/validation/check.py#L82-L121
30,437
bokeh/bokeh
bokeh/themes/theme.py
Theme.apply_to_model
def apply_to_model(self, model): ''' Apply this theme to a model. .. warning:: Typically, don't call this method directly. Instead, set the theme on the :class:`~bokeh.document.Document` the model is a part of. ''' model.apply_theme(self._for_class(model.__class__)) # a little paranoia because it would be Bad(tm) to mess # this up... would be nicer if python had a way to freeze # the dict. if len(_empty_dict) > 0: raise RuntimeError("Somebody put stuff in _empty_dict")
python
def apply_to_model(self, model): ''' Apply this theme to a model. .. warning:: Typically, don't call this method directly. Instead, set the theme on the :class:`~bokeh.document.Document` the model is a part of. ''' model.apply_theme(self._for_class(model.__class__)) # a little paranoia because it would be Bad(tm) to mess # this up... would be nicer if python had a way to freeze # the dict. if len(_empty_dict) > 0: raise RuntimeError("Somebody put stuff in _empty_dict")
[ "def", "apply_to_model", "(", "self", ",", "model", ")", ":", "model", ".", "apply_theme", "(", "self", ".", "_for_class", "(", "model", ".", "__class__", ")", ")", "# a little paranoia because it would be Bad(tm) to mess", "# this up... would be nicer if python had a way...
Apply this theme to a model. .. warning:: Typically, don't call this method directly. Instead, set the theme on the :class:`~bokeh.document.Document` the model is a part of.
[ "Apply", "this", "theme", "to", "a", "model", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/themes/theme.py#L186-L200
30,438
bokeh/bokeh
bokeh/models/graphs.py
from_networkx
def from_networkx(graph, layout_function, **kwargs): ''' Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx layout function. Any keyword arguments will be passed to the layout function. Only two dimensional layouts are supported. Args: graph (networkx.Graph) : a networkx graph to render layout_function (function or dict) : a networkx layout function or mapping of node keys to positions. The position is a two element sequence containing the x and y coordinate. Returns: instance (GraphRenderer) .. note:: Node and edge attributes may be lists or tuples. However, a given attribute must either have *all* lists or tuple values, or *all* scalar values, for nodes or edges it is defined on. .. warning:: Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored. If you want to convert these attributes, please re-label them to other names. Raises: ValueError ''' # inline import to prevent circular imports from ..models.renderers import GraphRenderer from ..models.graphs import StaticLayoutProvider # Handles nx 1.x vs 2.x data structure change # Convert node attributes node_dict = dict() node_attr_keys = [attr_key for node in list(graph.nodes(data=True)) for attr_key in node[1].keys()] node_attr_keys = list(set(node_attr_keys)) for attr_key in node_attr_keys: values = [node_attr[attr_key] if attr_key in node_attr.keys() else None for _, node_attr in graph.nodes(data=True)] values = _handle_sublists(values) node_dict[attr_key] = values if 'index' in node_attr_keys: from warnings import warn warn("Converting node attributes labeled 'index' are skipped. " "If you want to convert these attributes, please re-label with other names.") node_dict['index'] = list(graph.nodes()) # Convert edge attributes edge_dict = dict() edge_attr_keys = [attr_key for edge in graph.edges(data=True) for attr_key in edge[2].keys()] edge_attr_keys = list(set(edge_attr_keys)) for attr_key in edge_attr_keys: values = [edge_attr[attr_key] if attr_key in edge_attr.keys() else None for _, _, edge_attr in graph.edges(data=True)] values = _handle_sublists(values) edge_dict[attr_key] = values if 'start' in edge_attr_keys or 'end' in edge_attr_keys: from warnings import warn warn("Converting edge attributes labeled 'start' or 'end' are skipped. " "If you want to convert these attributes, please re-label them with other names.") edge_dict['start'] = [x[0] for x in graph.edges()] edge_dict['end'] = [x[1] for x in graph.edges()] node_source = ColumnDataSource(data=node_dict) edge_source = ColumnDataSource(data=edge_dict) graph_renderer = GraphRenderer() graph_renderer.node_renderer.data_source.data = node_source.data graph_renderer.edge_renderer.data_source.data = edge_source.data if callable(layout_function): graph_layout = layout_function(graph, **kwargs) else: graph_layout = layout_function node_keys = graph_renderer.node_renderer.data_source.data['index'] if set(node_keys) != set(layout_function.keys()): from warnings import warn warn("Node keys in 'layout_function' don't match node keys in the graph. " "These nodes may not be displayed correctly.") graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) return graph_renderer
python
def from_networkx(graph, layout_function, **kwargs): ''' Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx layout function. Any keyword arguments will be passed to the layout function. Only two dimensional layouts are supported. Args: graph (networkx.Graph) : a networkx graph to render layout_function (function or dict) : a networkx layout function or mapping of node keys to positions. The position is a two element sequence containing the x and y coordinate. Returns: instance (GraphRenderer) .. note:: Node and edge attributes may be lists or tuples. However, a given attribute must either have *all* lists or tuple values, or *all* scalar values, for nodes or edges it is defined on. .. warning:: Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored. If you want to convert these attributes, please re-label them to other names. Raises: ValueError ''' # inline import to prevent circular imports from ..models.renderers import GraphRenderer from ..models.graphs import StaticLayoutProvider # Handles nx 1.x vs 2.x data structure change # Convert node attributes node_dict = dict() node_attr_keys = [attr_key for node in list(graph.nodes(data=True)) for attr_key in node[1].keys()] node_attr_keys = list(set(node_attr_keys)) for attr_key in node_attr_keys: values = [node_attr[attr_key] if attr_key in node_attr.keys() else None for _, node_attr in graph.nodes(data=True)] values = _handle_sublists(values) node_dict[attr_key] = values if 'index' in node_attr_keys: from warnings import warn warn("Converting node attributes labeled 'index' are skipped. " "If you want to convert these attributes, please re-label with other names.") node_dict['index'] = list(graph.nodes()) # Convert edge attributes edge_dict = dict() edge_attr_keys = [attr_key for edge in graph.edges(data=True) for attr_key in edge[2].keys()] edge_attr_keys = list(set(edge_attr_keys)) for attr_key in edge_attr_keys: values = [edge_attr[attr_key] if attr_key in edge_attr.keys() else None for _, _, edge_attr in graph.edges(data=True)] values = _handle_sublists(values) edge_dict[attr_key] = values if 'start' in edge_attr_keys or 'end' in edge_attr_keys: from warnings import warn warn("Converting edge attributes labeled 'start' or 'end' are skipped. " "If you want to convert these attributes, please re-label them with other names.") edge_dict['start'] = [x[0] for x in graph.edges()] edge_dict['end'] = [x[1] for x in graph.edges()] node_source = ColumnDataSource(data=node_dict) edge_source = ColumnDataSource(data=edge_dict) graph_renderer = GraphRenderer() graph_renderer.node_renderer.data_source.data = node_source.data graph_renderer.edge_renderer.data_source.data = edge_source.data if callable(layout_function): graph_layout = layout_function(graph, **kwargs) else: graph_layout = layout_function node_keys = graph_renderer.node_renderer.data_source.data['index'] if set(node_keys) != set(layout_function.keys()): from warnings import warn warn("Node keys in 'layout_function' don't match node keys in the graph. " "These nodes may not be displayed correctly.") graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) return graph_renderer
[ "def", "from_networkx", "(", "graph", ",", "layout_function", ",", "*", "*", "kwargs", ")", ":", "# inline import to prevent circular imports", "from", ".", ".", "models", ".", "renderers", "import", "GraphRenderer", "from", ".", ".", "models", ".", "graphs", "i...
Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx layout function. Any keyword arguments will be passed to the layout function. Only two dimensional layouts are supported. Args: graph (networkx.Graph) : a networkx graph to render layout_function (function or dict) : a networkx layout function or mapping of node keys to positions. The position is a two element sequence containing the x and y coordinate. Returns: instance (GraphRenderer) .. note:: Node and edge attributes may be lists or tuples. However, a given attribute must either have *all* lists or tuple values, or *all* scalar values, for nodes or edges it is defined on. .. warning:: Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored. If you want to convert these attributes, please re-label them to other names. Raises: ValueError
[ "Generate", "a", "GraphRenderer", "from", "a", "networkx", ".", "Graph", "object", "and", "networkx", "layout", "function", ".", "Any", "keyword", "arguments", "will", "be", "passed", "to", "the", "layout", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/graphs.py#L71-L169
30,439
bokeh/bokeh
bokeh/core/enums.py
enumeration
def enumeration(*values, **kwargs): ''' Create an |Enumeration| object from a sequence of values. Call ``enumeration`` with a sequence of (unique) strings to create an Enumeration object: .. code-block:: python #: Specify the horizontal alignment for rendering text TextAlign = enumeration("left", "right", "center") Args: values (str) : string enumeration values, passed as positional arguments The order of arguments is the order of the enumeration, and the first element will be considered the default value when used to create |Enum| properties. Keyword Args: case_sensitive (bool, optional) : Whether validation should consider case or not (default: True) quote (bool, optional): Whther values should be quoted in the string representations (default: False) Raises: ValueError if values empty, if any value is not a string or not unique Returns: Enumeration ''' if not (values and all(isinstance(value, string_types) and value for value in values)): raise ValueError("expected a non-empty sequence of strings, got %s" % values) if len(values) != len(set(values)): raise ValueError("enumeration items must be unique, got %s" % values) attrs = {value: value for value in values} attrs.update({ "_values": list(values), "_default": values[0], "_case_sensitive": kwargs.get("case_sensitive", True), "_quote": kwargs.get("quote", False), }) return type(str("Enumeration"), (Enumeration,), attrs)()
python
def enumeration(*values, **kwargs): ''' Create an |Enumeration| object from a sequence of values. Call ``enumeration`` with a sequence of (unique) strings to create an Enumeration object: .. code-block:: python #: Specify the horizontal alignment for rendering text TextAlign = enumeration("left", "right", "center") Args: values (str) : string enumeration values, passed as positional arguments The order of arguments is the order of the enumeration, and the first element will be considered the default value when used to create |Enum| properties. Keyword Args: case_sensitive (bool, optional) : Whether validation should consider case or not (default: True) quote (bool, optional): Whther values should be quoted in the string representations (default: False) Raises: ValueError if values empty, if any value is not a string or not unique Returns: Enumeration ''' if not (values and all(isinstance(value, string_types) and value for value in values)): raise ValueError("expected a non-empty sequence of strings, got %s" % values) if len(values) != len(set(values)): raise ValueError("enumeration items must be unique, got %s" % values) attrs = {value: value for value in values} attrs.update({ "_values": list(values), "_default": values[0], "_case_sensitive": kwargs.get("case_sensitive", True), "_quote": kwargs.get("quote", False), }) return type(str("Enumeration"), (Enumeration,), attrs)()
[ "def", "enumeration", "(", "*", "values", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "values", "and", "all", "(", "isinstance", "(", "value", ",", "string_types", ")", "and", "value", "for", "value", "in", "values", ")", ")", ":", "raise", ...
Create an |Enumeration| object from a sequence of values. Call ``enumeration`` with a sequence of (unique) strings to create an Enumeration object: .. code-block:: python #: Specify the horizontal alignment for rendering text TextAlign = enumeration("left", "right", "center") Args: values (str) : string enumeration values, passed as positional arguments The order of arguments is the order of the enumeration, and the first element will be considered the default value when used to create |Enum| properties. Keyword Args: case_sensitive (bool, optional) : Whether validation should consider case or not (default: True) quote (bool, optional): Whther values should be quoted in the string representations (default: False) Raises: ValueError if values empty, if any value is not a string or not unique Returns: Enumeration
[ "Create", "an", "|Enumeration|", "object", "from", "a", "sequence", "of", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/enums.py#L176-L223
30,440
bokeh/bokeh
bokeh/util/session_id.py
generate_session_id
def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()): """Generate a random session ID. Typically, each browser tab connected to a Bokeh application has its own session ID. In production deployments of a Bokeh app, session IDs should be random and unguessable - otherwise users of the app could interfere with one another. If session IDs are signed with a secret key, the server can verify that the generator of the session ID was "authorized" (the generator had to know the secret key). This can be used to have a separate process, such as another web application, which generates new sessions on a Bokeh server. This other process may require users to log in before redirecting them to the Bokeh server with a valid session ID, for example. Args: secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to sign the session ID (default: value of 'BOKEH_SIGN_SESSIONS' env var) """ secret_key = _ensure_bytes(secret_key) if signed: # note: '-' can also be in the base64 encoded signature base_id = _get_random_string(secret_key=secret_key) return base_id + '-' + _signature(base_id, secret_key) else: return _get_random_string(secret_key=secret_key)
python
def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()): """Generate a random session ID. Typically, each browser tab connected to a Bokeh application has its own session ID. In production deployments of a Bokeh app, session IDs should be random and unguessable - otherwise users of the app could interfere with one another. If session IDs are signed with a secret key, the server can verify that the generator of the session ID was "authorized" (the generator had to know the secret key). This can be used to have a separate process, such as another web application, which generates new sessions on a Bokeh server. This other process may require users to log in before redirecting them to the Bokeh server with a valid session ID, for example. Args: secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to sign the session ID (default: value of 'BOKEH_SIGN_SESSIONS' env var) """ secret_key = _ensure_bytes(secret_key) if signed: # note: '-' can also be in the base64 encoded signature base_id = _get_random_string(secret_key=secret_key) return base_id + '-' + _signature(base_id, secret_key) else: return _get_random_string(secret_key=secret_key)
[ "def", "generate_session_id", "(", "secret_key", "=", "settings", ".", "secret_key_bytes", "(", ")", ",", "signed", "=", "settings", ".", "sign_sessions", "(", ")", ")", ":", "secret_key", "=", "_ensure_bytes", "(", "secret_key", ")", "if", "signed", ":", "#...
Generate a random session ID. Typically, each browser tab connected to a Bokeh application has its own session ID. In production deployments of a Bokeh app, session IDs should be random and unguessable - otherwise users of the app could interfere with one another. If session IDs are signed with a secret key, the server can verify that the generator of the session ID was "authorized" (the generator had to know the secret key). This can be used to have a separate process, such as another web application, which generates new sessions on a Bokeh server. This other process may require users to log in before redirecting them to the Bokeh server with a valid session ID, for example. Args: secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to sign the session ID (default: value of 'BOKEH_SIGN_SESSIONS' env var)
[ "Generate", "a", "random", "session", "ID", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/session_id.py#L63-L91
30,441
bokeh/bokeh
bokeh/util/session_id.py
check_session_id_signature
def check_session_id_signature(session_id, secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()): """Check the signature of a session ID, returning True if it's valid. The server uses this function to check whether a session ID was generated with the correct secret key. If signed sessions are disabled, this function always returns True. Args: session_id (str) : The session ID to check secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to check anything (default: value of 'BOKEH_SIGN_SESSIONS' env var) """ secret_key = _ensure_bytes(secret_key) if signed: pieces = session_id.split('-', 1) if len(pieces) != 2: return False base_id = pieces[0] provided_signature = pieces[1] expected_signature = _signature(base_id, secret_key) # hmac.compare_digest() uses a string compare algorithm that doesn't # short-circuit so we don't allow timing analysis # encode_utf8 is used to ensure that strings have same encoding return hmac.compare_digest(encode_utf8(expected_signature), encode_utf8(provided_signature)) else: return True
python
def check_session_id_signature(session_id, secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()): """Check the signature of a session ID, returning True if it's valid. The server uses this function to check whether a session ID was generated with the correct secret key. If signed sessions are disabled, this function always returns True. Args: session_id (str) : The session ID to check secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to check anything (default: value of 'BOKEH_SIGN_SESSIONS' env var) """ secret_key = _ensure_bytes(secret_key) if signed: pieces = session_id.split('-', 1) if len(pieces) != 2: return False base_id = pieces[0] provided_signature = pieces[1] expected_signature = _signature(base_id, secret_key) # hmac.compare_digest() uses a string compare algorithm that doesn't # short-circuit so we don't allow timing analysis # encode_utf8 is used to ensure that strings have same encoding return hmac.compare_digest(encode_utf8(expected_signature), encode_utf8(provided_signature)) else: return True
[ "def", "check_session_id_signature", "(", "session_id", ",", "secret_key", "=", "settings", ".", "secret_key_bytes", "(", ")", ",", "signed", "=", "settings", ".", "sign_sessions", "(", ")", ")", ":", "secret_key", "=", "_ensure_bytes", "(", "secret_key", ")", ...
Check the signature of a session ID, returning True if it's valid. The server uses this function to check whether a session ID was generated with the correct secret key. If signed sessions are disabled, this function always returns True. Args: session_id (str) : The session ID to check secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to check anything (default: value of 'BOKEH_SIGN_SESSIONS' env var)
[ "Check", "the", "signature", "of", "a", "session", "ID", "returning", "True", "if", "it", "s", "valid", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/session_id.py#L93-L121
30,442
bokeh/bokeh
bokeh/embed/notebook.py
notebook_content
def notebook_content(model, notebook_comms_target=None, theme=FromCurdoc): ''' Return script and div that will display a Bokeh plot in a Jupyter Notebook. The data for the plot is stored directly in the returned HTML. Args: model (Model) : Bokeh object to render notebook_comms_target (str, optional) : A target name for a Jupyter Comms object that can update the document that is rendered to this notebook div theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: script, div, Document .. note:: Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent has already been executed. ''' if not isinstance(model, Model): raise ValueError("notebook_content expects a single Model instance") # Comms handling relies on the fact that the new_doc returned here # has models with the same IDs as they were started with with OutputDocumentFor([model], apply_theme=theme, always_new=True) as new_doc: (docs_json, [render_item]) = standalone_docs_json_and_render_items([model]) div = div_for_render_item(render_item) render_item = render_item.to_json() if notebook_comms_target: render_item["notebook_comms_target"] = notebook_comms_target script = DOC_NB_JS.render( docs_json=serialize_json(docs_json), render_items=serialize_json([render_item]), ) return encode_utf8(script), encode_utf8(div), new_doc
python
def notebook_content(model, notebook_comms_target=None, theme=FromCurdoc): ''' Return script and div that will display a Bokeh plot in a Jupyter Notebook. The data for the plot is stored directly in the returned HTML. Args: model (Model) : Bokeh object to render notebook_comms_target (str, optional) : A target name for a Jupyter Comms object that can update the document that is rendered to this notebook div theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: script, div, Document .. note:: Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent has already been executed. ''' if not isinstance(model, Model): raise ValueError("notebook_content expects a single Model instance") # Comms handling relies on the fact that the new_doc returned here # has models with the same IDs as they were started with with OutputDocumentFor([model], apply_theme=theme, always_new=True) as new_doc: (docs_json, [render_item]) = standalone_docs_json_and_render_items([model]) div = div_for_render_item(render_item) render_item = render_item.to_json() if notebook_comms_target: render_item["notebook_comms_target"] = notebook_comms_target script = DOC_NB_JS.render( docs_json=serialize_json(docs_json), render_items=serialize_json([render_item]), ) return encode_utf8(script), encode_utf8(div), new_doc
[ "def", "notebook_content", "(", "model", ",", "notebook_comms_target", "=", "None", ",", "theme", "=", "FromCurdoc", ")", ":", "if", "not", "isinstance", "(", "model", ",", "Model", ")", ":", "raise", "ValueError", "(", "\"notebook_content expects a single Model i...
Return script and div that will display a Bokeh plot in a Jupyter Notebook. The data for the plot is stored directly in the returned HTML. Args: model (Model) : Bokeh object to render notebook_comms_target (str, optional) : A target name for a Jupyter Comms object that can update the document that is rendered to this notebook div theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: script, div, Document .. note:: Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent has already been executed.
[ "Return", "script", "and", "div", "that", "will", "display", "a", "Bokeh", "plot", "in", "a", "Jupyter", "Notebook", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/notebook.py#L51-L98
30,443
bokeh/bokeh
bokeh/models/transforms.py
CustomJSTransform.from_py_func
def from_py_func(cls, func, v_func): ''' Create a ``CustomJSTransform`` instance from a pair of Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It's possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``func`` function namespace will contain the variable ``x`` (the untransformed value) at render time. The ``v_func`` function namespace will contain the variable ``xs`` (the untransformed vector) at render time. .. warning:: The vectorized function, ``v_func``, must return an array of the same length as the input ``xs`` array. Example: .. code-block:: python def transform(): from pscript.stubs import Math return Math.cos(x) def v_transform(): from pscript.stubs import Math return [Math.cos(x) for x in xs] customjs_transform = CustomJSTransform.from_py_func(transform, v_transform) Args: func (function) : a scalar function to transform a single ``x`` value v_func (function) : a vectorized function to transform a vector ``xs`` Returns: CustomJSTransform ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSTransform directly instead.") if not isinstance(func, FunctionType) or not isinstance(v_func, FunctionType): raise ValueError('CustomJSTransform.from_py_func only accepts function objects.') pscript = import_required( 'pscript', dedent("""\ To use Python functions for CustomJSTransform, you need PScript '("conda install -c conda-forge pscript" or "pip install pscript")""") ) def pscript_compile(func): sig = signature(func) all_names, default_values = get_param_info(sig) if len(all_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a Bokeh Model.") func_kwargs = dict(zip(all_names, default_values)) # Wrap the code attr in a function named `formatter` and call it # with arguments that match the `args` attr code = pscript.py2js(func, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names) return code, func_kwargs jsfunc, func_kwargs = pscript_compile(func) v_jsfunc, v_func_kwargs = pscript_compile(v_func) # Have to merge the function arguments func_kwargs.update(v_func_kwargs) return cls(func=jsfunc, v_func=v_jsfunc, args=func_kwargs)
python
def from_py_func(cls, func, v_func): ''' Create a ``CustomJSTransform`` instance from a pair of Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It's possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``func`` function namespace will contain the variable ``x`` (the untransformed value) at render time. The ``v_func`` function namespace will contain the variable ``xs`` (the untransformed vector) at render time. .. warning:: The vectorized function, ``v_func``, must return an array of the same length as the input ``xs`` array. Example: .. code-block:: python def transform(): from pscript.stubs import Math return Math.cos(x) def v_transform(): from pscript.stubs import Math return [Math.cos(x) for x in xs] customjs_transform = CustomJSTransform.from_py_func(transform, v_transform) Args: func (function) : a scalar function to transform a single ``x`` value v_func (function) : a vectorized function to transform a vector ``xs`` Returns: CustomJSTransform ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSTransform directly instead.") if not isinstance(func, FunctionType) or not isinstance(v_func, FunctionType): raise ValueError('CustomJSTransform.from_py_func only accepts function objects.') pscript = import_required( 'pscript', dedent("""\ To use Python functions for CustomJSTransform, you need PScript '("conda install -c conda-forge pscript" or "pip install pscript")""") ) def pscript_compile(func): sig = signature(func) all_names, default_values = get_param_info(sig) if len(all_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a Bokeh Model.") func_kwargs = dict(zip(all_names, default_values)) # Wrap the code attr in a function named `formatter` and call it # with arguments that match the `args` attr code = pscript.py2js(func, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names) return code, func_kwargs jsfunc, func_kwargs = pscript_compile(func) v_jsfunc, v_func_kwargs = pscript_compile(v_func) # Have to merge the function arguments func_kwargs.update(v_func_kwargs) return cls(func=jsfunc, v_func=v_jsfunc, args=func_kwargs)
[ "def", "from_py_func", "(", "cls", ",", "func", ",", "v_func", ")", ":", "from", "bokeh", ".", "util", ".", "deprecation", "import", "deprecated", "deprecated", "(", "\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"", "\"Use CustomJSTransfor...
Create a ``CustomJSTransform`` instance from a pair of Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It's possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``func`` function namespace will contain the variable ``x`` (the untransformed value) at render time. The ``v_func`` function namespace will contain the variable ``xs`` (the untransformed vector) at render time. .. warning:: The vectorized function, ``v_func``, must return an array of the same length as the input ``xs`` array. Example: .. code-block:: python def transform(): from pscript.stubs import Math return Math.cos(x) def v_transform(): from pscript.stubs import Math return [Math.cos(x) for x in xs] customjs_transform = CustomJSTransform.from_py_func(transform, v_transform) Args: func (function) : a scalar function to transform a single ``x`` value v_func (function) : a vectorized function to transform a vector ``xs`` Returns: CustomJSTransform
[ "Create", "a", "CustomJSTransform", "instance", "from", "a", "pair", "of", "Python", "functions", ".", "The", "function", "is", "translated", "to", "JavaScript", "using", "PScript", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/transforms.py#L89-L167
30,444
bokeh/bokeh
bokeh/models/transforms.py
CustomJSTransform.from_coffeescript
def from_coffeescript(cls, func, v_func, args={}): ''' Create a ``CustomJSTransform`` instance from a pair of CoffeeScript snippets. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``func`` snippet namespace will contain the variable ``x`` (the untransformed value) at render time. The ``v_func`` snippet namespace will contain the variable ``xs`` (the untransformed vector) at render time. Example: .. code-block:: coffeescript func = "return Math.cos(x)" v_func = "return [Math.cos(x) for x in xs]" transform = CustomJSTransform.from_coffeescript(func, v_func) Args: func (str) : a coffeescript snippet to transform a single ``x`` value v_func (str) : a coffeescript snippet function to transform a vector ``xs`` Returns: CustomJSTransform ''' compiled = nodejs_compile(func, lang="coffeescript", file="???") if "error" in compiled: raise CompilationError(compiled.error) v_compiled = nodejs_compile(v_func, lang="coffeescript", file="???") if "error" in v_compiled: raise CompilationError(v_compiled.error) return cls(func=compiled.code, v_func=v_compiled.code, args=args)
python
def from_coffeescript(cls, func, v_func, args={}): ''' Create a ``CustomJSTransform`` instance from a pair of CoffeeScript snippets. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``func`` snippet namespace will contain the variable ``x`` (the untransformed value) at render time. The ``v_func`` snippet namespace will contain the variable ``xs`` (the untransformed vector) at render time. Example: .. code-block:: coffeescript func = "return Math.cos(x)" v_func = "return [Math.cos(x) for x in xs]" transform = CustomJSTransform.from_coffeescript(func, v_func) Args: func (str) : a coffeescript snippet to transform a single ``x`` value v_func (str) : a coffeescript snippet function to transform a vector ``xs`` Returns: CustomJSTransform ''' compiled = nodejs_compile(func, lang="coffeescript", file="???") if "error" in compiled: raise CompilationError(compiled.error) v_compiled = nodejs_compile(v_func, lang="coffeescript", file="???") if "error" in v_compiled: raise CompilationError(v_compiled.error) return cls(func=compiled.code, v_func=v_compiled.code, args=args)
[ "def", "from_coffeescript", "(", "cls", ",", "func", ",", "v_func", ",", "args", "=", "{", "}", ")", ":", "compiled", "=", "nodejs_compile", "(", "func", ",", "lang", "=", "\"coffeescript\"", ",", "file", "=", "\"???\"", ")", "if", "\"error\"", "in", "...
Create a ``CustomJSTransform`` instance from a pair of CoffeeScript snippets. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``func`` snippet namespace will contain the variable ``x`` (the untransformed value) at render time. The ``v_func`` snippet namespace will contain the variable ``xs`` (the untransformed vector) at render time. Example: .. code-block:: coffeescript func = "return Math.cos(x)" v_func = "return [Math.cos(x) for x in xs]" transform = CustomJSTransform.from_coffeescript(func, v_func) Args: func (str) : a coffeescript snippet to transform a single ``x`` value v_func (str) : a coffeescript snippet function to transform a vector ``xs`` Returns: CustomJSTransform
[ "Create", "a", "CustomJSTransform", "instance", "from", "a", "pair", "of", "CoffeeScript", "snippets", ".", "The", "function", "bodies", "are", "translated", "to", "JavaScript", "functions", "using", "node", "and", "therefore", "require", "return", "statements", "...
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/transforms.py#L170-L206
30,445
bokeh/bokeh
bokeh/core/has_props.py
abstract
def abstract(cls): ''' A decorator to mark abstract base classes derived from |HasProps|. ''' if not issubclass(cls, HasProps): raise TypeError("%s is not a subclass of HasProps" % cls.__name__) # running python with -OO will discard docstrings -> __doc__ is None if cls.__doc__ is not None: cls.__doc__ += _ABSTRACT_ADMONITION return cls
python
def abstract(cls): ''' A decorator to mark abstract base classes derived from |HasProps|. ''' if not issubclass(cls, HasProps): raise TypeError("%s is not a subclass of HasProps" % cls.__name__) # running python with -OO will discard docstrings -> __doc__ is None if cls.__doc__ is not None: cls.__doc__ += _ABSTRACT_ADMONITION return cls
[ "def", "abstract", "(", "cls", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "HasProps", ")", ":", "raise", "TypeError", "(", "\"%s is not a subclass of HasProps\"", "%", "cls", ".", "__name__", ")", "# running python with -OO will discard docstrings -> __doc_...
A decorator to mark abstract base classes derived from |HasProps|.
[ "A", "decorator", "to", "mark", "abstract", "base", "classes", "derived", "from", "|HasProps|", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L65-L76
30,446
bokeh/bokeh
bokeh/core/has_props.py
HasProps.equals
def equals(self, other): ''' Structural equality of models. Args: other (HasProps) : the other instance to compare to Returns: True, if properties are structurally equal, otherwise False ''' # NOTE: don't try to use this to implement __eq__. Because then # you will be tempted to implement __hash__, which would interfere # with mutability of models. However, not implementing __hash__ # will make bokeh unusable in Python 3, where proper implementation # of __hash__ is required when implementing __eq__. if not isinstance(other, self.__class__): return False else: return self.properties_with_values() == other.properties_with_values()
python
def equals(self, other): ''' Structural equality of models. Args: other (HasProps) : the other instance to compare to Returns: True, if properties are structurally equal, otherwise False ''' # NOTE: don't try to use this to implement __eq__. Because then # you will be tempted to implement __hash__, which would interfere # with mutability of models. However, not implementing __hash__ # will make bokeh unusable in Python 3, where proper implementation # of __hash__ is required when implementing __eq__. if not isinstance(other, self.__class__): return False else: return self.properties_with_values() == other.properties_with_values()
[ "def", "equals", "(", "self", ",", "other", ")", ":", "# NOTE: don't try to use this to implement __eq__. Because then", "# you will be tempted to implement __hash__, which would interfere", "# with mutability of models. However, not implementing __hash__", "# will make bokeh unusable in Pytho...
Structural equality of models. Args: other (HasProps) : the other instance to compare to Returns: True, if properties are structurally equal, otherwise False
[ "Structural", "equality", "of", "models", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L295-L314
30,447
bokeh/bokeh
bokeh/core/has_props.py
HasProps.set_from_json
def set_from_json(self, name, json, models=None, setter=None): ''' Set a property value on this object from JSON. Args: name: (str) : name of the attribute to set json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' if name in self.properties(): log.trace("Patching attribute %r of %r with %r", name, self, json) descriptor = self.lookup(name) descriptor.set_from_json(self, json, models, setter) else: log.warning("JSON had attr %r on obj %r, which is a client-only or invalid attribute that shouldn't have been sent", name, self)
python
def set_from_json(self, name, json, models=None, setter=None): ''' Set a property value on this object from JSON. Args: name: (str) : name of the attribute to set json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' if name in self.properties(): log.trace("Patching attribute %r of %r with %r", name, self, json) descriptor = self.lookup(name) descriptor.set_from_json(self, json, models, setter) else: log.warning("JSON had attr %r on obj %r, which is a client-only or invalid attribute that shouldn't have been sent", name, self)
[ "def", "set_from_json", "(", "self", ",", "name", ",", "json", ",", "models", "=", "None", ",", "setter", "=", "None", ")", ":", "if", "name", "in", "self", ".", "properties", "(", ")", ":", "log", ".", "trace", "(", "\"Patching attribute %r of %r with %...
Set a property value on this object from JSON. Args: name: (str) : name of the attribute to set json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None
[ "Set", "a", "property", "value", "on", "this", "object", "from", "JSON", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L316-L349
30,448
bokeh/bokeh
bokeh/core/has_props.py
HasProps.update_from_json
def update_from_json(self, json_attributes, models=None, setter=None): ''' Updates the object's properties from a JSON attributes dictionary. Args: json_attributes: (JSON-dict) : attributes and values to update models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' for k, v in json_attributes.items(): self.set_from_json(k, v, models, setter)
python
def update_from_json(self, json_attributes, models=None, setter=None): ''' Updates the object's properties from a JSON attributes dictionary. Args: json_attributes: (JSON-dict) : attributes and values to update models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' for k, v in json_attributes.items(): self.set_from_json(k, v, models, setter)
[ "def", "update_from_json", "(", "self", ",", "json_attributes", ",", "models", "=", "None", ",", "setter", "=", "None", ")", ":", "for", "k", ",", "v", "in", "json_attributes", ".", "items", "(", ")", ":", "self", ".", "set_from_json", "(", "k", ",", ...
Updates the object's properties from a JSON attributes dictionary. Args: json_attributes: (JSON-dict) : attributes and values to update models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None
[ "Updates", "the", "object", "s", "properties", "from", "a", "JSON", "attributes", "dictionary", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L378-L405
30,449
bokeh/bokeh
bokeh/core/has_props.py
HasProps.properties
def properties(cls, with_bases=True): ''' Collect the names of properties on this class. This method *optionally* traverses the class hierarchy and includes properties defined on any parent classes. Args: with_bases (bool, optional) : Whether to include properties defined on parent classes in the results. (default: True) Returns: set[str] : property names ''' if with_bases: return accumulate_from_superclasses(cls, "__properties__") else: return set(cls.__properties__)
python
def properties(cls, with_bases=True): ''' Collect the names of properties on this class. This method *optionally* traverses the class hierarchy and includes properties defined on any parent classes. Args: with_bases (bool, optional) : Whether to include properties defined on parent classes in the results. (default: True) Returns: set[str] : property names ''' if with_bases: return accumulate_from_superclasses(cls, "__properties__") else: return set(cls.__properties__)
[ "def", "properties", "(", "cls", ",", "with_bases", "=", "True", ")", ":", "if", "with_bases", ":", "return", "accumulate_from_superclasses", "(", "cls", ",", "\"__properties__\"", ")", "else", ":", "return", "set", "(", "cls", ".", "__properties__", ")" ]
Collect the names of properties on this class. This method *optionally* traverses the class hierarchy and includes properties defined on any parent classes. Args: with_bases (bool, optional) : Whether to include properties defined on parent classes in the results. (default: True) Returns: set[str] : property names
[ "Collect", "the", "names", "of", "properties", "on", "this", "class", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L449-L467
30,450
bokeh/bokeh
bokeh/core/has_props.py
HasProps.properties_with_values
def properties_with_values(self, include_defaults=True): ''' Collect a dict mapping property names to their values. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Non-serializable properties are skipped and property values are in "serialized" format which may be slightly different from the values you would normally read from the properties; the intent of this method is to return the information needed to losslessly reconstitute the object instance. Args: include_defaults (bool, optional) : Whether to include properties that haven't been explicitly set since the object was created. (default: True) Returns: dict : mapping from property names to their values ''' return self.query_properties_with_values(lambda prop: prop.serialized, include_defaults)
python
def properties_with_values(self, include_defaults=True): ''' Collect a dict mapping property names to their values. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Non-serializable properties are skipped and property values are in "serialized" format which may be slightly different from the values you would normally read from the properties; the intent of this method is to return the information needed to losslessly reconstitute the object instance. Args: include_defaults (bool, optional) : Whether to include properties that haven't been explicitly set since the object was created. (default: True) Returns: dict : mapping from property names to their values ''' return self.query_properties_with_values(lambda prop: prop.serialized, include_defaults)
[ "def", "properties_with_values", "(", "self", ",", "include_defaults", "=", "True", ")", ":", "return", "self", ".", "query_properties_with_values", "(", "lambda", "prop", ":", "prop", ".", "serialized", ",", "include_defaults", ")" ]
Collect a dict mapping property names to their values. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Non-serializable properties are skipped and property values are in "serialized" format which may be slightly different from the values you would normally read from the properties; the intent of this method is to return the information needed to losslessly reconstitute the object instance. Args: include_defaults (bool, optional) : Whether to include properties that haven't been explicitly set since the object was created. (default: True) Returns: dict : mapping from property names to their values
[ "Collect", "a", "dict", "mapping", "property", "names", "to", "their", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L496-L517
30,451
bokeh/bokeh
bokeh/core/has_props.py
HasProps.query_properties_with_values
def query_properties_with_values(self, query, include_defaults=True): ''' Query the properties values of |HasProps| instances with a predicate. Args: query (callable) : A callable that accepts property descriptors and returns True or False include_defaults (bool, optional) : Whether to include properties that have not been explicitly set by a user (default: True) Returns: dict : mapping of property names and values for matching properties ''' themed_keys = set() result = dict() if include_defaults: keys = self.properties() else: # TODO (bev) For now, include unstable default values. Things rely on Instances # always getting serialized, even defaults, and adding unstable defaults here # accomplishes that. Unmodified defaults for property value containers will be # weeded out below. keys = set(self._property_values.keys()) | set(self._unstable_default_values.keys()) if self.themed_values(): themed_keys = set(self.themed_values().keys()) keys |= themed_keys for key in keys: descriptor = self.lookup(key) if not query(descriptor): continue value = descriptor.serializable_value(self) if not include_defaults and key not in themed_keys: if isinstance(value, PropertyValueContainer) and key in self._unstable_default_values: continue result[key] = value return result
python
def query_properties_with_values(self, query, include_defaults=True): ''' Query the properties values of |HasProps| instances with a predicate. Args: query (callable) : A callable that accepts property descriptors and returns True or False include_defaults (bool, optional) : Whether to include properties that have not been explicitly set by a user (default: True) Returns: dict : mapping of property names and values for matching properties ''' themed_keys = set() result = dict() if include_defaults: keys = self.properties() else: # TODO (bev) For now, include unstable default values. Things rely on Instances # always getting serialized, even defaults, and adding unstable defaults here # accomplishes that. Unmodified defaults for property value containers will be # weeded out below. keys = set(self._property_values.keys()) | set(self._unstable_default_values.keys()) if self.themed_values(): themed_keys = set(self.themed_values().keys()) keys |= themed_keys for key in keys: descriptor = self.lookup(key) if not query(descriptor): continue value = descriptor.serializable_value(self) if not include_defaults and key not in themed_keys: if isinstance(value, PropertyValueContainer) and key in self._unstable_default_values: continue result[key] = value return result
[ "def", "query_properties_with_values", "(", "self", ",", "query", ",", "include_defaults", "=", "True", ")", ":", "themed_keys", "=", "set", "(", ")", "result", "=", "dict", "(", ")", "if", "include_defaults", ":", "keys", "=", "self", ".", "properties", "...
Query the properties values of |HasProps| instances with a predicate. Args: query (callable) : A callable that accepts property descriptors and returns True or False include_defaults (bool, optional) : Whether to include properties that have not been explicitly set by a user (default: True) Returns: dict : mapping of property names and values for matching properties
[ "Query", "the", "properties", "values", "of", "|HasProps|", "instances", "with", "a", "predicate", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L528-L570
30,452
bokeh/bokeh
bokeh/core/has_props.py
HasProps.apply_theme
def apply_theme(self, property_values): ''' Apply a set of theme values which will be used rather than defaults, but will not override application-set values. The passed-in dictionary may be kept around as-is and shared with other instances to save memory (so neither the caller nor the |HasProps| instance should modify it). Args: property_values (dict) : theme values to use in place of defaults Returns: None ''' old_dict = self.themed_values() # if the same theme is set again, it should reuse the same dict if old_dict is property_values: return removed = set() # we're doing a little song-and-dance to avoid storing __themed_values__ or # an empty dict, if there's no theme that applies to this HasProps instance. if old_dict is not None: removed.update(set(old_dict.keys())) added = set(property_values.keys()) old_values = dict() for k in added.union(removed): old_values[k] = getattr(self, k) if len(property_values) > 0: setattr(self, '__themed_values__', property_values) elif hasattr(self, '__themed_values__'): delattr(self, '__themed_values__') # Property container values might be cached even if unmodified. Invalidate # any cached values that are not modified at this point. for k, v in old_values.items(): if k in self._unstable_themed_values: del self._unstable_themed_values[k] # Emit any change notifications that result for k, v in old_values.items(): descriptor = self.lookup(k) descriptor.trigger_if_changed(self, v)
python
def apply_theme(self, property_values): ''' Apply a set of theme values which will be used rather than defaults, but will not override application-set values. The passed-in dictionary may be kept around as-is and shared with other instances to save memory (so neither the caller nor the |HasProps| instance should modify it). Args: property_values (dict) : theme values to use in place of defaults Returns: None ''' old_dict = self.themed_values() # if the same theme is set again, it should reuse the same dict if old_dict is property_values: return removed = set() # we're doing a little song-and-dance to avoid storing __themed_values__ or # an empty dict, if there's no theme that applies to this HasProps instance. if old_dict is not None: removed.update(set(old_dict.keys())) added = set(property_values.keys()) old_values = dict() for k in added.union(removed): old_values[k] = getattr(self, k) if len(property_values) > 0: setattr(self, '__themed_values__', property_values) elif hasattr(self, '__themed_values__'): delattr(self, '__themed_values__') # Property container values might be cached even if unmodified. Invalidate # any cached values that are not modified at this point. for k, v in old_values.items(): if k in self._unstable_themed_values: del self._unstable_themed_values[k] # Emit any change notifications that result for k, v in old_values.items(): descriptor = self.lookup(k) descriptor.trigger_if_changed(self, v)
[ "def", "apply_theme", "(", "self", ",", "property_values", ")", ":", "old_dict", "=", "self", ".", "themed_values", "(", ")", "# if the same theme is set again, it should reuse the same dict", "if", "old_dict", "is", "property_values", ":", "return", "removed", "=", "...
Apply a set of theme values which will be used rather than defaults, but will not override application-set values. The passed-in dictionary may be kept around as-is and shared with other instances to save memory (so neither the caller nor the |HasProps| instance should modify it). Args: property_values (dict) : theme values to use in place of defaults Returns: None
[ "Apply", "a", "set", "of", "theme", "values", "which", "will", "be", "used", "rather", "than", "defaults", "but", "will", "not", "override", "application", "-", "set", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L584-L629
30,453
bokeh/bokeh
bokeh/util/string.py
indent
def indent(text, n=2, ch=" "): ''' Indent all the lines in a given block of text by a specified amount. Args: text (str) : The text to indent n (int, optional) : The amount to indent each line by (default: 2) ch (char, optional) : What character to fill the indentation with (default: " ") ''' padding = ch * n return "\n".join(padding+line for line in text.split("\n"))
python
def indent(text, n=2, ch=" "): ''' Indent all the lines in a given block of text by a specified amount. Args: text (str) : The text to indent n (int, optional) : The amount to indent each line by (default: 2) ch (char, optional) : What character to fill the indentation with (default: " ") ''' padding = ch * n return "\n".join(padding+line for line in text.split("\n"))
[ "def", "indent", "(", "text", ",", "n", "=", "2", ",", "ch", "=", "\" \"", ")", ":", "padding", "=", "ch", "*", "n", "return", "\"\\n\"", ".", "join", "(", "padding", "+", "line", "for", "line", "in", "text", ".", "split", "(", "\"\\n\"", ")", ...
Indent all the lines in a given block of text by a specified amount. Args: text (str) : The text to indent n (int, optional) : The amount to indent each line by (default: 2) ch (char, optional) : What character to fill the indentation with (default: " ")
[ "Indent", "all", "the", "lines", "in", "a", "given", "block", "of", "text", "by", "a", "specified", "amount", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/string.py#L105-L120
30,454
bokeh/bokeh
bokeh/util/string.py
nice_join
def nice_join(seq, sep=", ", conjuction="or"): ''' Join together sequences of strings into English-friendly phrases using the conjunction ``or`` when appropriate. Args: seq (seq[str]) : a sequence of strings to nicely join sep (str, optional) : a sequence delimiter to use (default: ", ") conjunction (str or None, optional) : a conjuction to use for the last two items, or None to reproduce basic join behaviour (default: "or") Returns: a joined string Examples: >>> nice_join(["a", "b", "c"]) 'a, b or c' ''' seq = [str(x) for x in seq] if len(seq) <= 1 or conjuction is None: return sep.join(seq) else: return "%s %s %s" % (sep.join(seq[:-1]), conjuction, seq[-1])
python
def nice_join(seq, sep=", ", conjuction="or"): ''' Join together sequences of strings into English-friendly phrases using the conjunction ``or`` when appropriate. Args: seq (seq[str]) : a sequence of strings to nicely join sep (str, optional) : a sequence delimiter to use (default: ", ") conjunction (str or None, optional) : a conjuction to use for the last two items, or None to reproduce basic join behaviour (default: "or") Returns: a joined string Examples: >>> nice_join(["a", "b", "c"]) 'a, b or c' ''' seq = [str(x) for x in seq] if len(seq) <= 1 or conjuction is None: return sep.join(seq) else: return "%s %s %s" % (sep.join(seq[:-1]), conjuction, seq[-1])
[ "def", "nice_join", "(", "seq", ",", "sep", "=", "\", \"", ",", "conjuction", "=", "\"or\"", ")", ":", "seq", "=", "[", "str", "(", "x", ")", "for", "x", "in", "seq", "]", "if", "len", "(", "seq", ")", "<=", "1", "or", "conjuction", "is", "None...
Join together sequences of strings into English-friendly phrases using the conjunction ``or`` when appropriate. Args: seq (seq[str]) : a sequence of strings to nicely join sep (str, optional) : a sequence delimiter to use (default: ", ") conjunction (str or None, optional) : a conjuction to use for the last two items, or None to reproduce basic join behaviour (default: "or") Returns: a joined string Examples: >>> nice_join(["a", "b", "c"]) 'a, b or c'
[ "Join", "together", "sequences", "of", "strings", "into", "English", "-", "friendly", "phrases", "using", "the", "conjunction", "or", "when", "appropriate", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/string.py#L122-L145
30,455
bokeh/bokeh
bokeh/application/handlers/document_lifecycle.py
_on_session_destroyed
def _on_session_destroyed(session_context): ''' Calls any on_session_destroyed callbacks defined on the Document ''' callbacks = session_context._document.session_destroyed_callbacks session_context._document.session_destroyed_callbacks = set() for callback in callbacks: try: callback(session_context) except Exception as e: log.warning('DocumentLifeCycleHandler on_session_destroyed ' 'callback %s failed with following error: %s' % (callback, e)) if callbacks: # If any session callbacks were defined garbage collect after deleting all references del callback del callbacks import gc gc.collect()
python
def _on_session_destroyed(session_context): ''' Calls any on_session_destroyed callbacks defined on the Document ''' callbacks = session_context._document.session_destroyed_callbacks session_context._document.session_destroyed_callbacks = set() for callback in callbacks: try: callback(session_context) except Exception as e: log.warning('DocumentLifeCycleHandler on_session_destroyed ' 'callback %s failed with following error: %s' % (callback, e)) if callbacks: # If any session callbacks were defined garbage collect after deleting all references del callback del callbacks import gc gc.collect()
[ "def", "_on_session_destroyed", "(", "session_context", ")", ":", "callbacks", "=", "session_context", ".", "_document", ".", "session_destroyed_callbacks", "session_context", ".", "_document", ".", "session_destroyed_callbacks", "=", "set", "(", ")", "for", "callback",...
Calls any on_session_destroyed callbacks defined on the Document
[ "Calls", "any", "on_session_destroyed", "callbacks", "defined", "on", "the", "Document" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/document_lifecycle.py#L60-L79
30,456
bokeh/bokeh
bokeh/client/session.py
pull_session
def pull_session(session_id=None, url='default', io_loop=None, arguments=None): ''' Create a session by loading the current server-side document. ``session.document`` will be a fresh document loaded from the server. While the connection to the server is open, changes made on the server side will be applied to this document, and changes made on the client side will be synced to the server. If you don't plan to modify ``session.document`` you probably don't need to use this function; instead you can directly ``show_session()`` or ``server_session()`` without downloading the session's document into your process first. It's much more efficient to avoid downloading the session if you don't need to. In a production scenario, the ``session_id`` should be unique for each browser tab, which keeps users from stomping on each other. It's neither scalable nor secure to use predictable session IDs or to share session IDs across users. For a notebook running on a single machine, ``session_id`` could be something human-readable such as ``"default"`` for convenience. If you allow ``pull_session()`` to generate a unique ``session_id``, you can obtain the generated ID with the ``id`` property on the returned ``ClientSession``. Args: session_id (string, optional) : The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL io_loop (``tornado.ioloop.IOLoop``, optional) : The ``IOLoop`` to use for the websocket arguments (dict[str, str], optional) : A dictionary of key/values to be passed as HTTP request arguments to Bokeh application code (default: None) Note that should only be provided when pulling new sessions. If ``session_id`` is not None, or a session with ``session_id`` already exists, these arguments will have no effect. Returns: ClientSession : A new ``ClientSession`` connected to the server ''' coords = _SessionCoordinates(session_id=session_id, url=url) session = ClientSession(session_id=session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop, arguments=arguments) session.pull() return session
python
def pull_session(session_id=None, url='default', io_loop=None, arguments=None): ''' Create a session by loading the current server-side document. ``session.document`` will be a fresh document loaded from the server. While the connection to the server is open, changes made on the server side will be applied to this document, and changes made on the client side will be synced to the server. If you don't plan to modify ``session.document`` you probably don't need to use this function; instead you can directly ``show_session()`` or ``server_session()`` without downloading the session's document into your process first. It's much more efficient to avoid downloading the session if you don't need to. In a production scenario, the ``session_id`` should be unique for each browser tab, which keeps users from stomping on each other. It's neither scalable nor secure to use predictable session IDs or to share session IDs across users. For a notebook running on a single machine, ``session_id`` could be something human-readable such as ``"default"`` for convenience. If you allow ``pull_session()`` to generate a unique ``session_id``, you can obtain the generated ID with the ``id`` property on the returned ``ClientSession``. Args: session_id (string, optional) : The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL io_loop (``tornado.ioloop.IOLoop``, optional) : The ``IOLoop`` to use for the websocket arguments (dict[str, str], optional) : A dictionary of key/values to be passed as HTTP request arguments to Bokeh application code (default: None) Note that should only be provided when pulling new sessions. If ``session_id`` is not None, or a session with ``session_id`` already exists, these arguments will have no effect. Returns: ClientSession : A new ``ClientSession`` connected to the server ''' coords = _SessionCoordinates(session_id=session_id, url=url) session = ClientSession(session_id=session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop, arguments=arguments) session.pull() return session
[ "def", "pull_session", "(", "session_id", "=", "None", ",", "url", "=", "'default'", ",", "io_loop", "=", "None", ",", "arguments", "=", "None", ")", ":", "coords", "=", "_SessionCoordinates", "(", "session_id", "=", "session_id", ",", "url", "=", "url", ...
Create a session by loading the current server-side document. ``session.document`` will be a fresh document loaded from the server. While the connection to the server is open, changes made on the server side will be applied to this document, and changes made on the client side will be synced to the server. If you don't plan to modify ``session.document`` you probably don't need to use this function; instead you can directly ``show_session()`` or ``server_session()`` without downloading the session's document into your process first. It's much more efficient to avoid downloading the session if you don't need to. In a production scenario, the ``session_id`` should be unique for each browser tab, which keeps users from stomping on each other. It's neither scalable nor secure to use predictable session IDs or to share session IDs across users. For a notebook running on a single machine, ``session_id`` could be something human-readable such as ``"default"`` for convenience. If you allow ``pull_session()`` to generate a unique ``session_id``, you can obtain the generated ID with the ``id`` property on the returned ``ClientSession``. Args: session_id (string, optional) : The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL io_loop (``tornado.ioloop.IOLoop``, optional) : The ``IOLoop`` to use for the websocket arguments (dict[str, str], optional) : A dictionary of key/values to be passed as HTTP request arguments to Bokeh application code (default: None) Note that should only be provided when pulling new sessions. If ``session_id`` is not None, or a session with ``session_id`` already exists, these arguments will have no effect. Returns: ClientSession : A new ``ClientSession`` connected to the server
[ "Create", "a", "session", "by", "loading", "the", "current", "server", "-", "side", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L68-L125
30,457
bokeh/bokeh
bokeh/client/session.py
push_session
def push_session(document, session_id=None, url='default', io_loop=None): ''' Create a session by pushing the given document to the server, overwriting any existing server-side document. ``session.document`` in the returned session will be your supplied document. While the connection to the server is open, changes made on the server side will be applied to this document, and changes made on the client side will be synced to the server. In a production scenario, the ``session_id`` should be unique for each browser tab, which keeps users from stomping on each other. It's neither scalable nor secure to use predictable session IDs or to share session IDs across users. For a notebook running on a single machine, ``session_id`` could be something human-readable such as ``"default"`` for convenience. If you allow ``push_session()`` to generate a unique ``session_id``, you can obtain the generated ID with the ``id`` property on the returned ``ClientSession``. Args: document : (bokeh.document.Document) The document to be pushed and set as session.document session_id : (string, optional) The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL io_loop : (tornado.ioloop.IOLoop, optional) The IOLoop to use for the websocket Returns: ClientSession A new ClientSession connected to the server ''' coords = _SessionCoordinates(session_id=session_id, url=url) session = ClientSession(session_id=coords.session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop) session.push(document) return session
python
def push_session(document, session_id=None, url='default', io_loop=None): ''' Create a session by pushing the given document to the server, overwriting any existing server-side document. ``session.document`` in the returned session will be your supplied document. While the connection to the server is open, changes made on the server side will be applied to this document, and changes made on the client side will be synced to the server. In a production scenario, the ``session_id`` should be unique for each browser tab, which keeps users from stomping on each other. It's neither scalable nor secure to use predictable session IDs or to share session IDs across users. For a notebook running on a single machine, ``session_id`` could be something human-readable such as ``"default"`` for convenience. If you allow ``push_session()`` to generate a unique ``session_id``, you can obtain the generated ID with the ``id`` property on the returned ``ClientSession``. Args: document : (bokeh.document.Document) The document to be pushed and set as session.document session_id : (string, optional) The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL io_loop : (tornado.ioloop.IOLoop, optional) The IOLoop to use for the websocket Returns: ClientSession A new ClientSession connected to the server ''' coords = _SessionCoordinates(session_id=session_id, url=url) session = ClientSession(session_id=coords.session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop) session.push(document) return session
[ "def", "push_session", "(", "document", ",", "session_id", "=", "None", ",", "url", "=", "'default'", ",", "io_loop", "=", "None", ")", ":", "coords", "=", "_SessionCoordinates", "(", "session_id", "=", "session_id", ",", "url", "=", "url", ")", "session",...
Create a session by pushing the given document to the server, overwriting any existing server-side document. ``session.document`` in the returned session will be your supplied document. While the connection to the server is open, changes made on the server side will be applied to this document, and changes made on the client side will be synced to the server. In a production scenario, the ``session_id`` should be unique for each browser tab, which keeps users from stomping on each other. It's neither scalable nor secure to use predictable session IDs or to share session IDs across users. For a notebook running on a single machine, ``session_id`` could be something human-readable such as ``"default"`` for convenience. If you allow ``push_session()`` to generate a unique ``session_id``, you can obtain the generated ID with the ``id`` property on the returned ``ClientSession``. Args: document : (bokeh.document.Document) The document to be pushed and set as session.document session_id : (string, optional) The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL io_loop : (tornado.ioloop.IOLoop, optional) The IOLoop to use for the websocket Returns: ClientSession A new ClientSession connected to the server
[ "Create", "a", "session", "by", "pushing", "the", "given", "document", "to", "the", "server", "overwriting", "any", "existing", "server", "-", "side", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L127-L169
30,458
bokeh/bokeh
bokeh/client/session.py
show_session
def show_session(session_id=None, url='default', session=None, browser=None, new="tab", controller=None): ''' Open a browser displaying a session document. If you have a session from ``pull_session()`` or ``push_session`` you can ``show_session(session=mysession)``. If you don't need to open a connection to the server yourself, you can show a new session in a browser by providing just the ``url``. Args: session_id (string, optional) : The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL session (ClientSession, optional) : session to get session ID and server URL from If you specify this, you don't need to specify session_id and url browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. ''' if session is not None: server_url = server_url_for_websocket_url(session._connection.url) session_id = session.id else: coords = _SessionCoordinates(session_id=session_id, url=url) server_url = coords.url session_id = coords.session_id if controller is None: from bokeh.util.browser import get_browser_controller controller = get_browser_controller(browser=browser) controller.open(server_url + "?bokeh-session-id=" + quote_plus(session_id), new=NEW_PARAM[new])
python
def show_session(session_id=None, url='default', session=None, browser=None, new="tab", controller=None): ''' Open a browser displaying a session document. If you have a session from ``pull_session()`` or ``push_session`` you can ``show_session(session=mysession)``. If you don't need to open a connection to the server yourself, you can show a new session in a browser by providing just the ``url``. Args: session_id (string, optional) : The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL session (ClientSession, optional) : session to get session ID and server URL from If you specify this, you don't need to specify session_id and url browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. ''' if session is not None: server_url = server_url_for_websocket_url(session._connection.url) session_id = session.id else: coords = _SessionCoordinates(session_id=session_id, url=url) server_url = coords.url session_id = coords.session_id if controller is None: from bokeh.util.browser import get_browser_controller controller = get_browser_controller(browser=browser) controller.open(server_url + "?bokeh-session-id=" + quote_plus(session_id), new=NEW_PARAM[new])
[ "def", "show_session", "(", "session_id", "=", "None", ",", "url", "=", "'default'", ",", "session", "=", "None", ",", "browser", "=", "None", ",", "new", "=", "\"tab\"", ",", "controller", "=", "None", ")", ":", "if", "session", "is", "not", "None", ...
Open a browser displaying a session document. If you have a session from ``pull_session()`` or ``push_session`` you can ``show_session(session=mysession)``. If you don't need to open a connection to the server yourself, you can show a new session in a browser by providing just the ``url``. Args: session_id (string, optional) : The name of the session, None to autogenerate a random one (default: None) url : (str, optional): The URL to a Bokeh application on a Bokeh server can also be `"default"` which will connect to the default app URL session (ClientSession, optional) : session to get session ID and server URL from If you specify this, you don't need to specify session_id and url browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window.
[ "Open", "a", "browser", "displaying", "a", "session", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L171-L214
30,459
bokeh/bokeh
bokeh/client/session.py
ClientSession.pull
def pull(self): ''' Pull the server's state and set it as session.document. If this is called more than once, session.document will be the same object instance but its contents will be overwritten. Automatically calls :func:`connect` before pulling. ''' self.connect() if not self.connected: raise IOError("Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)") if self.document is None: doc = Document() else: doc = self.document self._connection.pull_doc(doc) if self.document is None: self._attach_document(doc)
python
def pull(self): ''' Pull the server's state and set it as session.document. If this is called more than once, session.document will be the same object instance but its contents will be overwritten. Automatically calls :func:`connect` before pulling. ''' self.connect() if not self.connected: raise IOError("Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)") if self.document is None: doc = Document() else: doc = self.document self._connection.pull_doc(doc) if self.document is None: self._attach_document(doc)
[ "def", "pull", "(", "self", ")", ":", "self", ".", "connect", "(", ")", "if", "not", "self", ".", "connected", ":", "raise", "IOError", "(", "\"Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)\"", "...
Pull the server's state and set it as session.document. If this is called more than once, session.document will be the same object instance but its contents will be overwritten. Automatically calls :func:`connect` before pulling.
[ "Pull", "the", "server", "s", "state", "and", "set", "it", "as", "session", ".", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L356-L375
30,460
bokeh/bokeh
bokeh/client/session.py
ClientSession.push
def push(self, document=None): ''' Push the given document to the server and record it as session.document. If this is called more than once, the Document has to be the same (or None to mean "session.document"). .. note:: Automatically calls :func:`~connect` before pushing. Args: document (:class:`~bokeh.document.Document`, optional) : The document which will be kept in sync with the server document. None to use session.document or create a new document. ''' if self.document is None: if document is None: doc = Document() else: doc = document else: if document is None: doc = self.document else: raise ValueError("Cannot push() a different document from existing session.document") self.connect() if not self.connected: raise IOError("Cannot push session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)") self._connection.push_doc(doc) if self._document is None: self._attach_document(doc)
python
def push(self, document=None): ''' Push the given document to the server and record it as session.document. If this is called more than once, the Document has to be the same (or None to mean "session.document"). .. note:: Automatically calls :func:`~connect` before pushing. Args: document (:class:`~bokeh.document.Document`, optional) : The document which will be kept in sync with the server document. None to use session.document or create a new document. ''' if self.document is None: if document is None: doc = Document() else: doc = document else: if document is None: doc = self.document else: raise ValueError("Cannot push() a different document from existing session.document") self.connect() if not self.connected: raise IOError("Cannot push session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)") self._connection.push_doc(doc) if self._document is None: self._attach_document(doc)
[ "def", "push", "(", "self", ",", "document", "=", "None", ")", ":", "if", "self", ".", "document", "is", "None", ":", "if", "document", "is", "None", ":", "doc", "=", "Document", "(", ")", "else", ":", "doc", "=", "document", "else", ":", "if", "...
Push the given document to the server and record it as session.document. If this is called more than once, the Document has to be the same (or None to mean "session.document"). .. note:: Automatically calls :func:`~connect` before pushing. Args: document (:class:`~bokeh.document.Document`, optional) : The document which will be kept in sync with the server document. None to use session.document or create a new document.
[ "Push", "the", "given", "document", "to", "the", "server", "and", "record", "it", "as", "session", ".", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L377-L408
30,461
bokeh/bokeh
bokeh/client/session.py
ClientSession.show
def show(self, obj=None, browser=None, new="tab"): ''' Open a browser displaying this session. Args: obj (LayoutDOM object, optional) : a Layout (Row/Column), Plot or Widget object to display. The object will be added to the session's document. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. ''' if obj and obj not in self.document.roots: self.document.add_root(obj) show_session(session=self, browser=browser, new=new)
python
def show(self, obj=None, browser=None, new="tab"): ''' Open a browser displaying this session. Args: obj (LayoutDOM object, optional) : a Layout (Row/Column), Plot or Widget object to display. The object will be added to the session's document. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. ''' if obj and obj not in self.document.roots: self.document.add_root(obj) show_session(session=self, browser=browser, new=new)
[ "def", "show", "(", "self", ",", "obj", "=", "None", ",", "browser", "=", "None", ",", "new", "=", "\"tab\"", ")", ":", "if", "obj", "and", "obj", "not", "in", "self", ".", "document", ".", "roots", ":", "self", ".", "document", ".", "add_root", ...
Open a browser displaying this session. Args: obj (LayoutDOM object, optional) : a Layout (Row/Column), Plot or Widget object to display. The object will be added to the session's document. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window.
[ "Open", "a", "browser", "displaying", "this", "session", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L419-L441
30,462
bokeh/bokeh
bokeh/client/session.py
ClientSession._notify_disconnected
def _notify_disconnected(self): ''' Called by the ClientConnection we are using to notify us of disconnect. ''' if self.document is not None: self.document.remove_on_change(self) self._callbacks.remove_all_callbacks()
python
def _notify_disconnected(self): ''' Called by the ClientConnection we are using to notify us of disconnect. ''' if self.document is not None: self.document.remove_on_change(self) self._callbacks.remove_all_callbacks()
[ "def", "_notify_disconnected", "(", "self", ")", ":", "if", "self", ".", "document", "is", "not", "None", ":", "self", ".", "document", ".", "remove_on_change", "(", "self", ")", "self", ".", "_callbacks", ".", "remove_all_callbacks", "(", ")" ]
Called by the ClientConnection we are using to notify us of disconnect.
[ "Called", "by", "the", "ClientConnection", "we", "are", "using", "to", "notify", "us", "of", "disconnect", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L471-L477
30,463
bokeh/bokeh
bokeh/protocol/message.py
Message.assemble
def assemble(cls, header_json, metadata_json, content_json): ''' Creates a new message, assembled from JSON fragments. Args: header_json (``JSON``) : metadata_json (``JSON``) : content_json (``JSON``) : Returns: Message subclass Raises: MessageError ''' try: header = json_decode(header_json) except ValueError: raise MessageError("header could not be decoded") try: metadata = json_decode(metadata_json) except ValueError: raise MessageError("metadata could not be decoded") try: content = json_decode(content_json) except ValueError: raise MessageError("content could not be decoded") msg = cls(header, metadata, content) msg._header_json = header_json msg._metadata_json = metadata_json msg._content_json = content_json return msg
python
def assemble(cls, header_json, metadata_json, content_json): ''' Creates a new message, assembled from JSON fragments. Args: header_json (``JSON``) : metadata_json (``JSON``) : content_json (``JSON``) : Returns: Message subclass Raises: MessageError ''' try: header = json_decode(header_json) except ValueError: raise MessageError("header could not be decoded") try: metadata = json_decode(metadata_json) except ValueError: raise MessageError("metadata could not be decoded") try: content = json_decode(content_json) except ValueError: raise MessageError("content could not be decoded") msg = cls(header, metadata, content) msg._header_json = header_json msg._metadata_json = metadata_json msg._content_json = content_json return msg
[ "def", "assemble", "(", "cls", ",", "header_json", ",", "metadata_json", ",", "content_json", ")", ":", "try", ":", "header", "=", "json_decode", "(", "header_json", ")", "except", "ValueError", ":", "raise", "MessageError", "(", "\"header could not be decoded\"",...
Creates a new message, assembled from JSON fragments. Args: header_json (``JSON``) : metadata_json (``JSON``) : content_json (``JSON``) : Returns: Message subclass Raises: MessageError
[ "Creates", "a", "new", "message", "assembled", "from", "JSON", "fragments", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L119-L158
30,464
bokeh/bokeh
bokeh/protocol/message.py
Message.add_buffer
def add_buffer(self, buf_header, buf_payload): ''' Associate a buffer header and payload with this message. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer payload Returns: None Raises: MessageError ''' if 'num_buffers' in self._header: self._header['num_buffers'] += 1 else: self._header['num_buffers'] = 1 self._header_json = None self._buffers.append((buf_header, buf_payload))
python
def add_buffer(self, buf_header, buf_payload): ''' Associate a buffer header and payload with this message. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer payload Returns: None Raises: MessageError ''' if 'num_buffers' in self._header: self._header['num_buffers'] += 1 else: self._header['num_buffers'] = 1 self._header_json = None self._buffers.append((buf_header, buf_payload))
[ "def", "add_buffer", "(", "self", ",", "buf_header", ",", "buf_payload", ")", ":", "if", "'num_buffers'", "in", "self", ".", "_header", ":", "self", ".", "_header", "[", "'num_buffers'", "]", "+=", "1", "else", ":", "self", ".", "_header", "[", "'num_buf...
Associate a buffer header and payload with this message. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer payload Returns: None Raises: MessageError
[ "Associate", "a", "buffer", "header", "and", "payload", "with", "this", "message", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L160-L181
30,465
bokeh/bokeh
bokeh/protocol/message.py
Message.assemble_buffer
def assemble_buffer(self, buf_header, buf_payload): ''' Add a buffer header and payload that we read from the socket. This differs from add_buffer() because we're validating vs. the header's num_buffers, instead of filling in the header. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer payload Returns: None Raises: ProtocolError ''' if self.header.get('num_buffers', 0) <= len(self._buffers): raise ProtocolError("too many buffers received expecting " + str(self.header['num_buffers'])) self._buffers.append((buf_header, buf_payload))
python
def assemble_buffer(self, buf_header, buf_payload): ''' Add a buffer header and payload that we read from the socket. This differs from add_buffer() because we're validating vs. the header's num_buffers, instead of filling in the header. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer payload Returns: None Raises: ProtocolError ''' if self.header.get('num_buffers', 0) <= len(self._buffers): raise ProtocolError("too many buffers received expecting " + str(self.header['num_buffers'])) self._buffers.append((buf_header, buf_payload))
[ "def", "assemble_buffer", "(", "self", ",", "buf_header", ",", "buf_payload", ")", ":", "if", "self", ".", "header", ".", "get", "(", "'num_buffers'", ",", "0", ")", "<=", "len", "(", "self", ".", "_buffers", ")", ":", "raise", "ProtocolError", "(", "\...
Add a buffer header and payload that we read from the socket. This differs from add_buffer() because we're validating vs. the header's num_buffers, instead of filling in the header. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer payload Returns: None Raises: ProtocolError
[ "Add", "a", "buffer", "header", "and", "payload", "that", "we", "read", "from", "the", "socket", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L183-L201
30,466
bokeh/bokeh
bokeh/protocol/message.py
Message.write_buffers
def write_buffers(self, conn, locked=True): ''' Write any buffer headers and payloads to the given connection. Args: conn (object) : May be any object with a ``write_message`` method. Typically, a Tornado ``WSHandler`` or ``WebSocketClientConnection`` locked (bool) : Returns: int : number of bytes sent ''' if conn is None: raise ValueError("Cannot write_buffers to connection None") sent = 0 for header, payload in self._buffers: yield conn.write_message(header, locked=locked) yield conn.write_message(payload, binary=True, locked=locked) sent += (len(header) + len(payload)) raise gen.Return(sent)
python
def write_buffers(self, conn, locked=True): ''' Write any buffer headers and payloads to the given connection. Args: conn (object) : May be any object with a ``write_message`` method. Typically, a Tornado ``WSHandler`` or ``WebSocketClientConnection`` locked (bool) : Returns: int : number of bytes sent ''' if conn is None: raise ValueError("Cannot write_buffers to connection None") sent = 0 for header, payload in self._buffers: yield conn.write_message(header, locked=locked) yield conn.write_message(payload, binary=True, locked=locked) sent += (len(header) + len(payload)) raise gen.Return(sent)
[ "def", "write_buffers", "(", "self", ",", "conn", ",", "locked", "=", "True", ")", ":", "if", "conn", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot write_buffers to connection None\"", ")", "sent", "=", "0", "for", "header", ",", "payload", "in", ...
Write any buffer headers and payloads to the given connection. Args: conn (object) : May be any object with a ``write_message`` method. Typically, a Tornado ``WSHandler`` or ``WebSocketClientConnection`` locked (bool) : Returns: int : number of bytes sent
[ "Write", "any", "buffer", "headers", "and", "payloads", "to", "the", "given", "connection", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L204-L225
30,467
bokeh/bokeh
bokeh/protocol/message.py
Message.create_header
def create_header(cls, request_id=None): ''' Return a message header fragment dict. Args: request_id (str or None) : Message ID of the message this message replies to Returns: dict : a message header ''' header = { 'msgid' : bkserial.make_id(), 'msgtype' : cls.msgtype } if request_id is not None: header['reqid'] = request_id return header
python
def create_header(cls, request_id=None): ''' Return a message header fragment dict. Args: request_id (str or None) : Message ID of the message this message replies to Returns: dict : a message header ''' header = { 'msgid' : bkserial.make_id(), 'msgtype' : cls.msgtype } if request_id is not None: header['reqid'] = request_id return header
[ "def", "create_header", "(", "cls", ",", "request_id", "=", "None", ")", ":", "header", "=", "{", "'msgid'", ":", "bkserial", ".", "make_id", "(", ")", ",", "'msgtype'", ":", "cls", ".", "msgtype", "}", "if", "request_id", "is", "not", "None", ":", "...
Return a message header fragment dict. Args: request_id (str or None) : Message ID of the message this message replies to Returns: dict : a message header
[ "Return", "a", "message", "header", "fragment", "dict", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L228-L245
30,468
bokeh/bokeh
bokeh/protocol/message.py
Message.send
def send(self, conn): ''' Send the message on the given connection. Args: conn (WebSocketHandler) : a WebSocketHandler to send messages Returns: int : number of bytes sent ''' if conn is None: raise ValueError("Cannot send to connection None") with (yield conn.write_lock.acquire()): sent = 0 yield conn.write_message(self.header_json, locked=False) sent += len(self.header_json) # uncomment this to make it a lot easier to reproduce lock-related bugs #yield gen.sleep(0.1) yield conn.write_message(self.metadata_json, locked=False) sent += len(self.metadata_json) # uncomment this to make it a lot easier to reproduce lock-related bugs #yield gen.sleep(0.1) yield conn.write_message(self.content_json, locked=False) sent += len(self.content_json) sent += yield self.write_buffers(conn, locked=False) raise gen.Return(sent)
python
def send(self, conn): ''' Send the message on the given connection. Args: conn (WebSocketHandler) : a WebSocketHandler to send messages Returns: int : number of bytes sent ''' if conn is None: raise ValueError("Cannot send to connection None") with (yield conn.write_lock.acquire()): sent = 0 yield conn.write_message(self.header_json, locked=False) sent += len(self.header_json) # uncomment this to make it a lot easier to reproduce lock-related bugs #yield gen.sleep(0.1) yield conn.write_message(self.metadata_json, locked=False) sent += len(self.metadata_json) # uncomment this to make it a lot easier to reproduce lock-related bugs #yield gen.sleep(0.1) yield conn.write_message(self.content_json, locked=False) sent += len(self.content_json) sent += yield self.write_buffers(conn, locked=False) raise gen.Return(sent)
[ "def", "send", "(", "self", ",", "conn", ")", ":", "if", "conn", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot send to connection None\"", ")", "with", "(", "yield", "conn", ".", "write_lock", ".", "acquire", "(", ")", ")", ":", "sent", "=", ...
Send the message on the given connection. Args: conn (WebSocketHandler) : a WebSocketHandler to send messages Returns: int : number of bytes sent
[ "Send", "the", "message", "on", "the", "given", "connection", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L248-L281
30,469
bokeh/bokeh
bokeh/protocol/message.py
Message.complete
def complete(self): ''' Returns whether all required parts of a message are present. Returns: bool : True if the message is complete, False otherwise ''' return self.header is not None and \ self.metadata is not None and \ self.content is not None and \ self.header.get('num_buffers', 0) == len(self._buffers)
python
def complete(self): ''' Returns whether all required parts of a message are present. Returns: bool : True if the message is complete, False otherwise ''' return self.header is not None and \ self.metadata is not None and \ self.content is not None and \ self.header.get('num_buffers', 0) == len(self._buffers)
[ "def", "complete", "(", "self", ")", ":", "return", "self", ".", "header", "is", "not", "None", "and", "self", ".", "metadata", "is", "not", "None", "and", "self", ".", "content", "is", "not", "None", "and", "self", ".", "header", ".", "get", "(", ...
Returns whether all required parts of a message are present. Returns: bool : True if the message is complete, False otherwise
[ "Returns", "whether", "all", "required", "parts", "of", "a", "message", "are", "present", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L284-L294
30,470
bokeh/bokeh
bokeh/util/deprecation.py
deprecated
def deprecated(since_or_msg, old=None, new=None, extra=None): """ Issue a nicely formatted deprecation warning. """ if isinstance(since_or_msg, tuple): if old is None or new is None: raise ValueError("deprecated entity and a replacement are required") if len(since_or_msg) != 3 or not all(isinstance(x, int) and x >=0 for x in since_or_msg): raise ValueError("invalid version tuple: %r" % (since_or_msg,)) since = "%d.%d.%d" % since_or_msg message = "%(old)s was deprecated in Bokeh %(since)s and will be removed, use %(new)s instead." message = message % dict(old=old, since=since, new=new) if extra is not None: message += " " + extra.strip() elif isinstance(since_or_msg, six.string_types): if not (old is None and new is None and extra is None): raise ValueError("deprecated(message) signature doesn't allow extra arguments") message = since_or_msg else: raise ValueError("expected a version tuple or string message") warn(message)
python
def deprecated(since_or_msg, old=None, new=None, extra=None): """ Issue a nicely formatted deprecation warning. """ if isinstance(since_or_msg, tuple): if old is None or new is None: raise ValueError("deprecated entity and a replacement are required") if len(since_or_msg) != 3 or not all(isinstance(x, int) and x >=0 for x in since_or_msg): raise ValueError("invalid version tuple: %r" % (since_or_msg,)) since = "%d.%d.%d" % since_or_msg message = "%(old)s was deprecated in Bokeh %(since)s and will be removed, use %(new)s instead." message = message % dict(old=old, since=since, new=new) if extra is not None: message += " " + extra.strip() elif isinstance(since_or_msg, six.string_types): if not (old is None and new is None and extra is None): raise ValueError("deprecated(message) signature doesn't allow extra arguments") message = since_or_msg else: raise ValueError("expected a version tuple or string message") warn(message)
[ "def", "deprecated", "(", "since_or_msg", ",", "old", "=", "None", ",", "new", "=", "None", ",", "extra", "=", "None", ")", ":", "if", "isinstance", "(", "since_or_msg", ",", "tuple", ")", ":", "if", "old", "is", "None", "or", "new", "is", "None", ...
Issue a nicely formatted deprecation warning.
[ "Issue", "a", "nicely", "formatted", "deprecation", "warning", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/deprecation.py#L45-L68
30,471
bokeh/bokeh
bokeh/__main__.py
main
def main(): ''' Execute the "bokeh" command line program. ''' import sys from bokeh.command.bootstrap import main as _main # Main entry point (see setup.py) _main(sys.argv)
python
def main(): ''' Execute the "bokeh" command line program. ''' import sys from bokeh.command.bootstrap import main as _main # Main entry point (see setup.py) _main(sys.argv)
[ "def", "main", "(", ")", ":", "import", "sys", "from", "bokeh", ".", "command", ".", "bootstrap", "import", "main", "as", "_main", "# Main entry point (see setup.py)", "_main", "(", "sys", ".", "argv", ")" ]
Execute the "bokeh" command line program.
[ "Execute", "the", "bokeh", "command", "line", "program", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/__main__.py#L56-L64
30,472
bokeh/bokeh
bokeh/server/connection.py
ServerConnection.detach_session
def detach_session(self): """Allow the session to be discarded and don't get change notifications from it anymore""" if self._session is not None: self._session.unsubscribe(self) self._session = None
python
def detach_session(self): """Allow the session to be discarded and don't get change notifications from it anymore""" if self._session is not None: self._session.unsubscribe(self) self._session = None
[ "def", "detach_session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "not", "None", ":", "self", ".", "_session", ".", "unsubscribe", "(", "self", ")", "self", ".", "_session", "=", "None" ]
Allow the session to be discarded and don't get change notifications from it anymore
[ "Allow", "the", "session", "to", "be", "discarded", "and", "don", "t", "get", "change", "notifications", "from", "it", "anymore" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/connection.py#L62-L66
30,473
bokeh/bokeh
bokeh/server/connection.py
ServerConnection.send_patch_document
def send_patch_document(self, event): """ Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """ msg = self.protocol.create('PATCH-DOC', [event]) return self._socket.send_message(msg)
python
def send_patch_document(self, event): """ Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """ msg = self.protocol.create('PATCH-DOC', [event]) return self._socket.send_message(msg)
[ "def", "send_patch_document", "(", "self", ",", "event", ")", ":", "msg", "=", "self", ".", "protocol", ".", "create", "(", "'PATCH-DOC'", ",", "[", "event", "]", ")", "return", "self", ".", "_socket", ".", "send_message", "(", "msg", ")" ]
Sends a PATCH-DOC message, returning a Future that's completed when it's written out.
[ "Sends", "a", "PATCH", "-", "DOC", "message", "returning", "a", "Future", "that", "s", "completed", "when", "it", "s", "written", "out", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/connection.py#L74-L77
30,474
bokeh/bokeh
bokeh/document/util.py
initialize_references_json
def initialize_references_json(references_json, references, setter=None): ''' Given a JSON representation of the models in a graph, and new model objects, set the properties on the models from the JSON Args: references_json (``JSON``) JSON specifying attributes and values to initialize new model objects with. references (dict[str, Model]) A dictionary mapping model IDs to newly created (but not yet initialized) Bokeh models. **This is an "out" parameter**. The values it contains will be modified in-place. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. ''' for obj in references_json: obj_id = obj['id'] obj_attrs = obj['attributes'] instance = references[obj_id] # We want to avoid any Model specific initialization that happens with # Slider(...) when reconstituting from JSON, but we do need to perform # general HasProps machinery that sets properties, so call it explicitly HasProps.__init__(instance) instance.update_from_json(obj_attrs, models=references, setter=setter)
python
def initialize_references_json(references_json, references, setter=None): ''' Given a JSON representation of the models in a graph, and new model objects, set the properties on the models from the JSON Args: references_json (``JSON``) JSON specifying attributes and values to initialize new model objects with. references (dict[str, Model]) A dictionary mapping model IDs to newly created (but not yet initialized) Bokeh models. **This is an "out" parameter**. The values it contains will be modified in-place. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. ''' for obj in references_json: obj_id = obj['id'] obj_attrs = obj['attributes'] instance = references[obj_id] # We want to avoid any Model specific initialization that happens with # Slider(...) when reconstituting from JSON, but we do need to perform # general HasProps machinery that sets properties, so call it explicitly HasProps.__init__(instance) instance.update_from_json(obj_attrs, models=references, setter=setter)
[ "def", "initialize_references_json", "(", "references_json", ",", "references", ",", "setter", "=", "None", ")", ":", "for", "obj", "in", "references_json", ":", "obj_id", "=", "obj", "[", "'id'", "]", "obj_attrs", "=", "obj", "[", "'attributes'", "]", "inst...
Given a JSON representation of the models in a graph, and new model objects, set the properties on the models from the JSON Args: references_json (``JSON``) JSON specifying attributes and values to initialize new model objects with. references (dict[str, Model]) A dictionary mapping model IDs to newly created (but not yet initialized) Bokeh models. **This is an "out" parameter**. The values it contains will be modified in-place. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself.
[ "Given", "a", "JSON", "representation", "of", "the", "models", "in", "a", "graph", "and", "new", "model", "objects", "set", "the", "properties", "on", "the", "models", "from", "the", "JSON" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/util.py#L50-L90
30,475
bokeh/bokeh
bokeh/document/util.py
instantiate_references_json
def instantiate_references_json(references_json): ''' Given a JSON representation of all the models in a graph, return a dict of new model objects. Args: references_json (``JSON``) JSON specifying new Bokeh models to create Returns: dict[str, Model] ''' # Create all instances, but without setting their props references = {} for obj in references_json: obj_id = obj['id'] obj_type = obj.get('subtype', obj['type']) cls = get_class(obj_type) instance = cls.__new__(cls, id=obj_id) if instance is None: raise RuntimeError('Error loading model from JSON (type: %s, id: %s)' % (obj_type, obj_id)) references[instance.id] = instance return references
python
def instantiate_references_json(references_json): ''' Given a JSON representation of all the models in a graph, return a dict of new model objects. Args: references_json (``JSON``) JSON specifying new Bokeh models to create Returns: dict[str, Model] ''' # Create all instances, but without setting their props references = {} for obj in references_json: obj_id = obj['id'] obj_type = obj.get('subtype', obj['type']) cls = get_class(obj_type) instance = cls.__new__(cls, id=obj_id) if instance is None: raise RuntimeError('Error loading model from JSON (type: %s, id: %s)' % (obj_type, obj_id)) references[instance.id] = instance return references
[ "def", "instantiate_references_json", "(", "references_json", ")", ":", "# Create all instances, but without setting their props", "references", "=", "{", "}", "for", "obj", "in", "references_json", ":", "obj_id", "=", "obj", "[", "'id'", "]", "obj_type", "=", "obj", ...
Given a JSON representation of all the models in a graph, return a dict of new model objects. Args: references_json (``JSON``) JSON specifying new Bokeh models to create Returns: dict[str, Model]
[ "Given", "a", "JSON", "representation", "of", "all", "the", "models", "in", "a", "graph", "return", "a", "dict", "of", "new", "model", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/util.py#L92-L117
30,476
bokeh/bokeh
bokeh/document/util.py
references_json
def references_json(references): ''' Given a list of all models in a graph, return JSON representing them and their properties. Args: references (seq[Model]) : A list of models to convert to JSON Returns: list ''' references_json = [] for r in references: ref = r.ref ref['attributes'] = r._to_json_like(include_defaults=False) references_json.append(ref) return references_json
python
def references_json(references): ''' Given a list of all models in a graph, return JSON representing them and their properties. Args: references (seq[Model]) : A list of models to convert to JSON Returns: list ''' references_json = [] for r in references: ref = r.ref ref['attributes'] = r._to_json_like(include_defaults=False) references_json.append(ref) return references_json
[ "def", "references_json", "(", "references", ")", ":", "references_json", "=", "[", "]", "for", "r", "in", "references", ":", "ref", "=", "r", ".", "ref", "ref", "[", "'attributes'", "]", "=", "r", ".", "_to_json_like", "(", "include_defaults", "=", "Fal...
Given a list of all models in a graph, return JSON representing them and their properties. Args: references (seq[Model]) : A list of models to convert to JSON Returns: list
[ "Given", "a", "list", "of", "all", "models", "in", "a", "graph", "return", "JSON", "representing", "them", "and", "their", "properties", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/util.py#L119-L138
30,477
bokeh/bokeh
bokeh/events.py
Event.decode_json
def decode_json(cls, dct): ''' Custom JSON decoder for Events. Can be used as the ``object_hook`` argument of ``json.load`` or ``json.loads``. Args: dct (dict) : a JSON dictionary to decode The dictionary should have keys ``event_name`` and ``event_values`` Raises: ValueError, if the event_name is unknown Examples: .. code-block:: python >>> import json >>> from bokeh.events import Event >>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}' >>> json.loads(data, object_hook=Event.decode_json) <bokeh.events.Pan object at 0x1040f84a8> ''' if not ('event_name' in dct and 'event_values' in dct): return dct event_name = dct['event_name'] if event_name not in _CONCRETE_EVENT_CLASSES: raise ValueError("Could not find appropriate Event class for event_name: %r" % event_name) event_values = dct['event_values'] model_id = event_values.pop('model_id') event = _CONCRETE_EVENT_CLASSES[event_name](model=None, **event_values) event._model_id = model_id return event
python
def decode_json(cls, dct): ''' Custom JSON decoder for Events. Can be used as the ``object_hook`` argument of ``json.load`` or ``json.loads``. Args: dct (dict) : a JSON dictionary to decode The dictionary should have keys ``event_name`` and ``event_values`` Raises: ValueError, if the event_name is unknown Examples: .. code-block:: python >>> import json >>> from bokeh.events import Event >>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}' >>> json.loads(data, object_hook=Event.decode_json) <bokeh.events.Pan object at 0x1040f84a8> ''' if not ('event_name' in dct and 'event_values' in dct): return dct event_name = dct['event_name'] if event_name not in _CONCRETE_EVENT_CLASSES: raise ValueError("Could not find appropriate Event class for event_name: %r" % event_name) event_values = dct['event_values'] model_id = event_values.pop('model_id') event = _CONCRETE_EVENT_CLASSES[event_name](model=None, **event_values) event._model_id = model_id return event
[ "def", "decode_json", "(", "cls", ",", "dct", ")", ":", "if", "not", "(", "'event_name'", "in", "dct", "and", "'event_values'", "in", "dct", ")", ":", "return", "dct", "event_name", "=", "dct", "[", "'event_name'", "]", "if", "event_name", "not", "in", ...
Custom JSON decoder for Events. Can be used as the ``object_hook`` argument of ``json.load`` or ``json.loads``. Args: dct (dict) : a JSON dictionary to decode The dictionary should have keys ``event_name`` and ``event_values`` Raises: ValueError, if the event_name is unknown Examples: .. code-block:: python >>> import json >>> from bokeh.events import Event >>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}' >>> json.loads(data, object_hook=Event.decode_json) <bokeh.events.Pan object at 0x1040f84a8>
[ "Custom", "JSON", "decoder", "for", "Events", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/events.py#L150-L186
30,478
bokeh/bokeh
bokeh/sphinxext/bokeh_palette.py
bokeh_palette
def bokeh_palette(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Generate an inline visual representations of a single color palette. This function evaluates the expression ``"palette = %s" % text``, in the context of a ``globals`` namespace that has previously imported all of ``bokeh.plotting``. The resulting value for ``palette`` is used to construct a sequence of HTML ``<span>`` elements for each color. If evaluating the palette expression fails or does not produce a list or tuple of all strings, then a SphinxError is raised to terminate the build. For details on the arguments to this function, consult the Docutils docs: http://docutils.sourceforge.net/docs/howto/rst-roles.html#define-the-role-function ''' try: exec("palette = %s" % text, _globals) except Exception as e: raise SphinxError("cannot evaluate palette expression '%r', reason: %s" % (text, e)) p = _globals.get('palette', None) if not isinstance(p, (list, tuple)) or not all(isinstance(x, str) for x in p): raise SphinxError("palette expression '%r' generated invalid or no output: %s" % (text, p)) w = 20 if len(p) < 15 else 10 if len(p) < 32 else 5 if len(p) < 64 else 2 if len(p) < 128 else 1 html = PALETTE_DETAIL.render(palette=p, width=w) node = nodes.raw('', html, format="html") return [node], []
python
def bokeh_palette(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Generate an inline visual representations of a single color palette. This function evaluates the expression ``"palette = %s" % text``, in the context of a ``globals`` namespace that has previously imported all of ``bokeh.plotting``. The resulting value for ``palette`` is used to construct a sequence of HTML ``<span>`` elements for each color. If evaluating the palette expression fails or does not produce a list or tuple of all strings, then a SphinxError is raised to terminate the build. For details on the arguments to this function, consult the Docutils docs: http://docutils.sourceforge.net/docs/howto/rst-roles.html#define-the-role-function ''' try: exec("palette = %s" % text, _globals) except Exception as e: raise SphinxError("cannot evaluate palette expression '%r', reason: %s" % (text, e)) p = _globals.get('palette', None) if not isinstance(p, (list, tuple)) or not all(isinstance(x, str) for x in p): raise SphinxError("palette expression '%r' generated invalid or no output: %s" % (text, p)) w = 20 if len(p) < 15 else 10 if len(p) < 32 else 5 if len(p) < 64 else 2 if len(p) < 128 else 1 html = PALETTE_DETAIL.render(palette=p, width=w) node = nodes.raw('', html, format="html") return [node], []
[ "def", "bokeh_palette", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ")", ":", "try", ":", "exec", "(", "\"palette = %s\"", "%", "text", ",", "_globals", ")", "except...
Generate an inline visual representations of a single color palette. This function evaluates the expression ``"palette = %s" % text``, in the context of a ``globals`` namespace that has previously imported all of ``bokeh.plotting``. The resulting value for ``palette`` is used to construct a sequence of HTML ``<span>`` elements for each color. If evaluating the palette expression fails or does not produce a list or tuple of all strings, then a SphinxError is raised to terminate the build. For details on the arguments to this function, consult the Docutils docs: http://docutils.sourceforge.net/docs/howto/rst-roles.html#define-the-role-function
[ "Generate", "an", "inline", "visual", "representations", "of", "a", "single", "color", "palette", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_palette.py#L89-L115
30,479
bokeh/bokeh
bokeh/transform.py
cumsum
def cumsum(field, include_zero=False): ''' Create a Create a ``DataSpec`` dict to generate a ``CumSum`` expression for a ``ColumnDataSource``. Examples: .. code-block:: python p.wedge(start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), ...) will generate a ``CumSum`` expressions that sum the ``"angle"`` column of a data source. For the ``start_angle`` value, the cumulative sums will start with a zero value. For ``start_angle``, no initial zero will be added (i.e. the sums will start with the first angle value, and include the last). ''' return expr(CumSum(field=field, include_zero=include_zero))
python
def cumsum(field, include_zero=False): ''' Create a Create a ``DataSpec`` dict to generate a ``CumSum`` expression for a ``ColumnDataSource``. Examples: .. code-block:: python p.wedge(start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), ...) will generate a ``CumSum`` expressions that sum the ``"angle"`` column of a data source. For the ``start_angle`` value, the cumulative sums will start with a zero value. For ``start_angle``, no initial zero will be added (i.e. the sums will start with the first angle value, and include the last). ''' return expr(CumSum(field=field, include_zero=include_zero))
[ "def", "cumsum", "(", "field", ",", "include_zero", "=", "False", ")", ":", "return", "expr", "(", "CumSum", "(", "field", "=", "field", ",", "include_zero", "=", "include_zero", ")", ")" ]
Create a Create a ``DataSpec`` dict to generate a ``CumSum`` expression for a ``ColumnDataSource``. Examples: .. code-block:: python p.wedge(start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), ...) will generate a ``CumSum`` expressions that sum the ``"angle"`` column of a data source. For the ``start_angle`` value, the cumulative sums will start with a zero value. For ``start_angle``, no initial zero will be added (i.e. the sums will start with the first angle value, and include the last).
[ "Create", "a", "Create", "a", "DataSpec", "dict", "to", "generate", "a", "CumSum", "expression", "for", "a", "ColumnDataSource", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L55-L74
30,480
bokeh/bokeh
bokeh/transform.py
factor_cmap
def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applies a client-side ``CategoricalColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") Returns: dict ''' return field(field_name, CategoricalColorMapper(palette=palette, factors=factors, start=start, end=end, nan_color=nan_color))
python
def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applies a client-side ``CategoricalColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") Returns: dict ''' return field(field_name, CategoricalColorMapper(palette=palette, factors=factors, start=start, end=end, nan_color=nan_color))
[ "def", "factor_cmap", "(", "field_name", ",", "palette", ",", "factors", ",", "start", "=", "0", ",", "end", "=", "None", ",", "nan_color", "=", "\"gray\"", ")", ":", "return", "field", "(", "field_name", ",", "CategoricalColorMapper", "(", "palette", "=",...
Create a ``DataSpec`` dict that applies a client-side ``CategoricalColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") Returns: dict
[ "Create", "a", "DataSpec", "dict", "that", "applies", "a", "client", "-", "side", "CategoricalColorMapper", "transformation", "to", "a", "ColumnDataSource", "column", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L95-L125
30,481
bokeh/bokeh
bokeh/transform.py
factor_hatch
def factor_hatch(field_name, patterns, factors, start=0, end=None): ''' Create a ``DataSpec`` dict that applies a client-side ``CategoricalPatternMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with patterns (seq[string]) : a list of hatch patterns to use to map to factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) Returns: dict Added in version 1.1.1 ''' return field(field_name, CategoricalPatternMapper(patterns=patterns, factors=factors, start=start, end=end))
python
def factor_hatch(field_name, patterns, factors, start=0, end=None): ''' Create a ``DataSpec`` dict that applies a client-side ``CategoricalPatternMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with patterns (seq[string]) : a list of hatch patterns to use to map to factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) Returns: dict Added in version 1.1.1 ''' return field(field_name, CategoricalPatternMapper(patterns=patterns, factors=factors, start=start, end=end))
[ "def", "factor_hatch", "(", "field_name", ",", "patterns", ",", "factors", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "return", "field", "(", "field_name", ",", "CategoricalPatternMapper", "(", "patterns", "=", "patterns", ",", "factors", "...
Create a ``DataSpec`` dict that applies a client-side ``CategoricalPatternMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with patterns (seq[string]) : a list of hatch patterns to use to map to factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) Returns: dict Added in version 1.1.1
[ "Create", "a", "DataSpec", "dict", "that", "applies", "a", "client", "-", "side", "CategoricalPatternMapper", "transformation", "to", "a", "ColumnDataSource", "column", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L127-L155
30,482
bokeh/bokeh
bokeh/transform.py
factor_mark
def factor_mark(field_name, markers, factors, start=0, end=None): ''' Create a ``DataSpec`` dict that applies a client-side ``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource`` column. .. note:: This transform is primarily only useful with ``scatter``, which can be parameterized by glyph type. Args: field_name (str) : a field name to configure ``DataSpec`` with markers (seq[string]) : a list of markers to use to map to factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) Returns: dict ''' return field(field_name, CategoricalMarkerMapper(markers=markers, factors=factors, start=start, end=end))
python
def factor_mark(field_name, markers, factors, start=0, end=None): ''' Create a ``DataSpec`` dict that applies a client-side ``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource`` column. .. note:: This transform is primarily only useful with ``scatter``, which can be parameterized by glyph type. Args: field_name (str) : a field name to configure ``DataSpec`` with markers (seq[string]) : a list of markers to use to map to factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) Returns: dict ''' return field(field_name, CategoricalMarkerMapper(markers=markers, factors=factors, start=start, end=end))
[ "def", "factor_mark", "(", "field_name", ",", "markers", ",", "factors", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "return", "field", "(", "field_name", ",", "CategoricalMarkerMapper", "(", "markers", "=", "markers", ",", "factors", "=", ...
Create a ``DataSpec`` dict that applies a client-side ``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource`` column. .. note:: This transform is primarily only useful with ``scatter``, which can be parameterized by glyph type. Args: field_name (str) : a field name to configure ``DataSpec`` with markers (seq[string]) : a list of markers to use to map to factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) Returns: dict
[ "Create", "a", "DataSpec", "dict", "that", "applies", "a", "client", "-", "side", "CategoricalMarkerMapper", "transformation", "to", "a", "ColumnDataSource", "column", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L157-L187
30,483
bokeh/bokeh
bokeh/transform.py
linear_cmap
def linear_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applyies a client-side ``LinearColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") ''' return field(field_name, LinearColorMapper(palette=palette, low=low, high=high, nan_color=nan_color, low_color=low_color, high_color=high_color))
python
def linear_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applyies a client-side ``LinearColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") ''' return field(field_name, LinearColorMapper(palette=palette, low=low, high=high, nan_color=nan_color, low_color=low_color, high_color=high_color))
[ "def", "linear_cmap", "(", "field_name", ",", "palette", ",", "low", ",", "high", ",", "low_color", "=", "None", ",", "high_color", "=", "None", ",", "nan_color", "=", "\"gray\"", ")", ":", "return", "field", "(", "field_name", ",", "LinearColorMapper", "(...
Create a ``DataSpec`` dict that applyies a client-side ``LinearColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray")
[ "Create", "a", "DataSpec", "dict", "that", "applyies", "a", "client", "-", "side", "LinearColorMapper", "transformation", "to", "a", "ColumnDataSource", "column", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L216-L248
30,484
bokeh/bokeh
bokeh/transform.py
log_cmap
def log_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applies a client-side ``LogColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") ''' return field(field_name, LogColorMapper(palette=palette, low=low, high=high, nan_color=nan_color, low_color=low_color, high_color=high_color))
python
def log_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applies a client-side ``LogColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") ''' return field(field_name, LogColorMapper(palette=palette, low=low, high=high, nan_color=nan_color, low_color=low_color, high_color=high_color))
[ "def", "log_cmap", "(", "field_name", ",", "palette", ",", "low", ",", "high", ",", "low_color", "=", "None", ",", "high_color", "=", "None", ",", "nan_color", "=", "\"gray\"", ")", ":", "return", "field", "(", "field_name", ",", "LogColorMapper", "(", "...
Create a ``DataSpec`` dict that applies a client-side ``LogColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray")
[ "Create", "a", "DataSpec", "dict", "that", "applies", "a", "client", "-", "side", "LogColorMapper", "transformation", "to", "a", "ColumnDataSource", "column", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L250-L282
30,485
bokeh/bokeh
bokeh/util/browser.py
get_browser_controller
def get_browser_controller(browser=None): ''' Return a browser controller. Args: browser (str or None) : browser name, or ``None`` (default: ``None``) If passed the string ``'none'``, a dummy web browser controller is returned Otherwise, use the value to select an appropriate controller using the ``webbrowser`` standard library module. In the value is ``None`` then a system default is used. .. note:: If the environment variable ``BOKEH_BROWSER`` is set, it will take precedence. Returns: controller : a web browser controller ''' browser = settings.browser(browser) if browser is not None: if browser == 'none': controller = DummyWebBrowser() else: controller = webbrowser.get(browser) else: controller = webbrowser return controller
python
def get_browser_controller(browser=None): ''' Return a browser controller. Args: browser (str or None) : browser name, or ``None`` (default: ``None``) If passed the string ``'none'``, a dummy web browser controller is returned Otherwise, use the value to select an appropriate controller using the ``webbrowser`` standard library module. In the value is ``None`` then a system default is used. .. note:: If the environment variable ``BOKEH_BROWSER`` is set, it will take precedence. Returns: controller : a web browser controller ''' browser = settings.browser(browser) if browser is not None: if browser == 'none': controller = DummyWebBrowser() else: controller = webbrowser.get(browser) else: controller = webbrowser return controller
[ "def", "get_browser_controller", "(", "browser", "=", "None", ")", ":", "browser", "=", "settings", ".", "browser", "(", "browser", ")", "if", "browser", "is", "not", "None", ":", "if", "browser", "==", "'none'", ":", "controller", "=", "DummyWebBrowser", ...
Return a browser controller. Args: browser (str or None) : browser name, or ``None`` (default: ``None``) If passed the string ``'none'``, a dummy web browser controller is returned Otherwise, use the value to select an appropriate controller using the ``webbrowser`` standard library module. In the value is ``None`` then a system default is used. .. note:: If the environment variable ``BOKEH_BROWSER`` is set, it will take precedence. Returns: controller : a web browser controller
[ "Return", "a", "browser", "controller", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/browser.py#L56-L86
30,486
bokeh/bokeh
bokeh/util/browser.py
view
def view(location, browser=None, new="same", autoraise=True): ''' Open a browser to view the specified location. Args: location (str) : Location to open If location does not begin with "http:" it is assumed to be a file path on the local filesystem. browser (str or None) : what browser to use (default: None) If ``None``, use the system default browser. new (str) : How to open the location. Valid values are: ``'same'`` - open in the current tab ``'tab'`` - open a new tab in the current window ``'window'`` - open in a new window autoraise (bool) : Whether to automatically raise the location in a new browser window (default: True) Returns: None ''' try: new = { "same": 0, "window": 1, "tab": 2 }[new] except KeyError: raise RuntimeError("invalid 'new' value passed to view: %r, valid values are: 'same', 'window', or 'tab'" % new) if location.startswith("http"): url = location else: url = "file://" + abspath(location) try: controller = get_browser_controller(browser) controller.open(url, new=new, autoraise=autoraise) except (SystemExit, KeyboardInterrupt): raise except: pass
python
def view(location, browser=None, new="same", autoraise=True): ''' Open a browser to view the specified location. Args: location (str) : Location to open If location does not begin with "http:" it is assumed to be a file path on the local filesystem. browser (str or None) : what browser to use (default: None) If ``None``, use the system default browser. new (str) : How to open the location. Valid values are: ``'same'`` - open in the current tab ``'tab'`` - open a new tab in the current window ``'window'`` - open in a new window autoraise (bool) : Whether to automatically raise the location in a new browser window (default: True) Returns: None ''' try: new = { "same": 0, "window": 1, "tab": 2 }[new] except KeyError: raise RuntimeError("invalid 'new' value passed to view: %r, valid values are: 'same', 'window', or 'tab'" % new) if location.startswith("http"): url = location else: url = "file://" + abspath(location) try: controller = get_browser_controller(browser) controller.open(url, new=new, autoraise=autoraise) except (SystemExit, KeyboardInterrupt): raise except: pass
[ "def", "view", "(", "location", ",", "browser", "=", "None", ",", "new", "=", "\"same\"", ",", "autoraise", "=", "True", ")", ":", "try", ":", "new", "=", "{", "\"same\"", ":", "0", ",", "\"window\"", ":", "1", ",", "\"tab\"", ":", "2", "}", "[",...
Open a browser to view the specified location. Args: location (str) : Location to open If location does not begin with "http:" it is assumed to be a file path on the local filesystem. browser (str or None) : what browser to use (default: None) If ``None``, use the system default browser. new (str) : How to open the location. Valid values are: ``'same'`` - open in the current tab ``'tab'`` - open a new tab in the current window ``'window'`` - open in a new window autoraise (bool) : Whether to automatically raise the location in a new browser window (default: True) Returns: None
[ "Open", "a", "browser", "to", "view", "the", "specified", "location", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/browser.py#L88-L127
30,487
bokeh/bokeh
bokeh/models/filters.py
CustomJSFilter.from_py_func
def from_py_func(cls, func): ''' Create a ``CustomJSFilter`` instance from a Python function. The function is translated to JavaScript using PScript. The ``func`` function namespace will contain the variable ``source`` at render time. This will be the data source associated with the ``CDSView`` that this filter is added to. ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSFilter directly instead.") if not isinstance(func, FunctionType): raise ValueError('CustomJSFilter.from_py_func only accepts function objects.') pscript = import_required( 'pscript', dedent("""\ To use Python functions for CustomJSFilter, you need PScript '("conda install -c conda-forge pscript" or "pip install pscript")""") ) argspec = inspect.getargspec(func) default_names = argspec.args default_values = argspec.defaults or [] if len(default_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") # should the following be all of the values need to be Models? if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a plot object.") func_kwargs = dict(zip(default_names, default_values)) code = pscript.py2js(func, 'filter') + 'return filter(%s);\n' % ', '.join(default_names) return cls(code=code, args=func_kwargs)
python
def from_py_func(cls, func): ''' Create a ``CustomJSFilter`` instance from a Python function. The function is translated to JavaScript using PScript. The ``func`` function namespace will contain the variable ``source`` at render time. This will be the data source associated with the ``CDSView`` that this filter is added to. ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSFilter directly instead.") if not isinstance(func, FunctionType): raise ValueError('CustomJSFilter.from_py_func only accepts function objects.') pscript = import_required( 'pscript', dedent("""\ To use Python functions for CustomJSFilter, you need PScript '("conda install -c conda-forge pscript" or "pip install pscript")""") ) argspec = inspect.getargspec(func) default_names = argspec.args default_values = argspec.defaults or [] if len(default_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") # should the following be all of the values need to be Models? if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a plot object.") func_kwargs = dict(zip(default_names, default_values)) code = pscript.py2js(func, 'filter') + 'return filter(%s);\n' % ', '.join(default_names) return cls(code=code, args=func_kwargs)
[ "def", "from_py_func", "(", "cls", ",", "func", ")", ":", "from", "bokeh", ".", "util", ".", "deprecation", "import", "deprecated", "deprecated", "(", "\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"", "\"Use CustomJSFilter directly instead.\""...
Create a ``CustomJSFilter`` instance from a Python function. The function is translated to JavaScript using PScript. The ``func`` function namespace will contain the variable ``source`` at render time. This will be the data source associated with the ``CDSView`` that this filter is added to.
[ "Create", "a", "CustomJSFilter", "instance", "from", "a", "Python", "function", ".", "The", "function", "is", "translated", "to", "JavaScript", "using", "PScript", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/filters.py#L125-L162
30,488
bokeh/bokeh
examples/howto/events_app.py
print_event
def print_event(attributes=[]): """ Function that returns a Python callback to pretty print the events. """ def python_callback(event): cls_name = event.__class__.__name__ attrs = ', '.join(['{attr}={val}'.format(attr=attr, val=event.__dict__[attr]) for attr in attributes]) print('{cls_name}({attrs})'.format(cls_name=cls_name, attrs=attrs)) return python_callback
python
def print_event(attributes=[]): """ Function that returns a Python callback to pretty print the events. """ def python_callback(event): cls_name = event.__class__.__name__ attrs = ', '.join(['{attr}={val}'.format(attr=attr, val=event.__dict__[attr]) for attr in attributes]) print('{cls_name}({attrs})'.format(cls_name=cls_name, attrs=attrs)) return python_callback
[ "def", "print_event", "(", "attributes", "=", "[", "]", ")", ":", "def", "python_callback", "(", "event", ")", ":", "cls_name", "=", "event", ".", "__class__", ".", "__name__", "attrs", "=", "', '", ".", "join", "(", "[", "'{attr}={val}'", ".", "format",...
Function that returns a Python callback to pretty print the events.
[ "Function", "that", "returns", "a", "Python", "callback", "to", "pretty", "print", "the", "events", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/howto/events_app.py#L39-L48
30,489
bokeh/bokeh
bokeh/protocol/__init__.py
Protocol.create
def create(self, msgtype, *args, **kwargs): ''' Create a new Message instance for the given type. Args: msgtype (str) : ''' if msgtype not in self._messages: raise ProtocolError("Unknown message type %r for protocol version %s" % (msgtype, self._version)) return self._messages[msgtype].create(*args, **kwargs)
python
def create(self, msgtype, *args, **kwargs): ''' Create a new Message instance for the given type. Args: msgtype (str) : ''' if msgtype not in self._messages: raise ProtocolError("Unknown message type %r for protocol version %s" % (msgtype, self._version)) return self._messages[msgtype].create(*args, **kwargs)
[ "def", "create", "(", "self", ",", "msgtype", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "msgtype", "not", "in", "self", ".", "_messages", ":", "raise", "ProtocolError", "(", "\"Unknown message type %r for protocol version %s\"", "%", "(", "m...
Create a new Message instance for the given type. Args: msgtype (str) :
[ "Create", "a", "new", "Message", "instance", "for", "the", "given", "type", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/__init__.py#L71-L80
30,490
bokeh/bokeh
bokeh/protocol/__init__.py
Protocol.assemble
def assemble(self, header_json, metadata_json, content_json): ''' Create a Message instance assembled from json fragments. Args: header_json (``JSON``) : metadata_json (``JSON``) : content_json (``JSON``) : Returns: message ''' header = json_decode(header_json) if 'msgtype' not in header: log.error("Bad header with no msgtype was: %r", header) raise ProtocolError("No 'msgtype' in header") return self._messages[header['msgtype']].assemble( header_json, metadata_json, content_json )
python
def assemble(self, header_json, metadata_json, content_json): ''' Create a Message instance assembled from json fragments. Args: header_json (``JSON``) : metadata_json (``JSON``) : content_json (``JSON``) : Returns: message ''' header = json_decode(header_json) if 'msgtype' not in header: log.error("Bad header with no msgtype was: %r", header) raise ProtocolError("No 'msgtype' in header") return self._messages[header['msgtype']].assemble( header_json, metadata_json, content_json )
[ "def", "assemble", "(", "self", ",", "header_json", ",", "metadata_json", ",", "content_json", ")", ":", "header", "=", "json_decode", "(", "header_json", ")", "if", "'msgtype'", "not", "in", "header", ":", "log", ".", "error", "(", "\"Bad header with no msgty...
Create a Message instance assembled from json fragments. Args: header_json (``JSON``) : metadata_json (``JSON``) : content_json (``JSON``) : Returns: message
[ "Create", "a", "Message", "instance", "assembled", "from", "json", "fragments", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/__init__.py#L82-L102
30,491
bokeh/bokeh
bokeh/document/document.py
_combine_document_events
def _combine_document_events(new_event, old_events): ''' Attempt to combine a new event with a list of previous events. The ``old_event`` will be scanned in reverse, and ``.combine(new_event)`` will be called on each. If a combination can be made, the function will return immediately. Otherwise, ``new_event`` will be appended to ``old_events``. Args: new_event (DocumentChangedEvent) : The new event to attempt to combine old_events (list[DocumentChangedEvent]) A list of previous events to attempt to combine new_event with **This is an "out" parameter**. The values it contains will be modified in-place. Returns: None ''' for event in reversed(old_events): if event.combine(new_event): return # no combination was possible old_events.append(new_event)
python
def _combine_document_events(new_event, old_events): ''' Attempt to combine a new event with a list of previous events. The ``old_event`` will be scanned in reverse, and ``.combine(new_event)`` will be called on each. If a combination can be made, the function will return immediately. Otherwise, ``new_event`` will be appended to ``old_events``. Args: new_event (DocumentChangedEvent) : The new event to attempt to combine old_events (list[DocumentChangedEvent]) A list of previous events to attempt to combine new_event with **This is an "out" parameter**. The values it contains will be modified in-place. Returns: None ''' for event in reversed(old_events): if event.combine(new_event): return # no combination was possible old_events.append(new_event)
[ "def", "_combine_document_events", "(", "new_event", ",", "old_events", ")", ":", "for", "event", "in", "reversed", "(", "old_events", ")", ":", "if", "event", ".", "combine", "(", "new_event", ")", ":", "return", "# no combination was possible", "old_events", "...
Attempt to combine a new event with a list of previous events. The ``old_event`` will be scanned in reverse, and ``.combine(new_event)`` will be called on each. If a combination can be made, the function will return immediately. Otherwise, ``new_event`` will be appended to ``old_events``. Args: new_event (DocumentChangedEvent) : The new event to attempt to combine old_events (list[DocumentChangedEvent]) A list of previous events to attempt to combine new_event with **This is an "out" parameter**. The values it contains will be modified in-place. Returns: None
[ "Attempt", "to", "combine", "a", "new", "event", "with", "a", "list", "of", "previous", "events", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L1131-L1158
30,492
bokeh/bokeh
bokeh/document/document.py
Document.add_next_tick_callback
def add_next_tick_callback(self, callback): ''' Add callback to be invoked once on the next tick of the event loop. Args: callback (callable) : A callback function to execute on the next tick. Returns: NextTickCallback : can be used with ``remove_next_tick_callback`` .. note:: Next tick callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells. ''' from ..server.callbacks import NextTickCallback cb = NextTickCallback(self, None) return self._add_session_callback(cb, callback, one_shot=True, originator=self.add_next_tick_callback)
python
def add_next_tick_callback(self, callback): ''' Add callback to be invoked once on the next tick of the event loop. Args: callback (callable) : A callback function to execute on the next tick. Returns: NextTickCallback : can be used with ``remove_next_tick_callback`` .. note:: Next tick callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells. ''' from ..server.callbacks import NextTickCallback cb = NextTickCallback(self, None) return self._add_session_callback(cb, callback, one_shot=True, originator=self.add_next_tick_callback)
[ "def", "add_next_tick_callback", "(", "self", ",", "callback", ")", ":", "from", ".", ".", "server", ".", "callbacks", "import", "NextTickCallback", "cb", "=", "NextTickCallback", "(", "self", ",", "None", ")", "return", "self", ".", "_add_session_callback", "...
Add callback to be invoked once on the next tick of the event loop. Args: callback (callable) : A callback function to execute on the next tick. Returns: NextTickCallback : can be used with ``remove_next_tick_callback`` .. note:: Next tick callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells.
[ "Add", "callback", "to", "be", "invoked", "once", "on", "the", "next", "tick", "of", "the", "event", "loop", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L226-L244
30,493
bokeh/bokeh
bokeh/document/document.py
Document.add_periodic_callback
def add_periodic_callback(self, callback, period_milliseconds): ''' Add a callback to be invoked on a session periodically. Args: callback (callable) : A callback function to execute periodically period_milliseconds (int) : Number of milliseconds between each callback execution. Returns: PeriodicCallback : can be used with ``remove_periodic_callback`` .. note:: Periodic callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells. ''' from ..server.callbacks import PeriodicCallback cb = PeriodicCallback(self, None, period_milliseconds) return self._add_session_callback(cb, callback, one_shot=False, originator=self.add_periodic_callback)
python
def add_periodic_callback(self, callback, period_milliseconds): ''' Add a callback to be invoked on a session periodically. Args: callback (callable) : A callback function to execute periodically period_milliseconds (int) : Number of milliseconds between each callback execution. Returns: PeriodicCallback : can be used with ``remove_periodic_callback`` .. note:: Periodic callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells. ''' from ..server.callbacks import PeriodicCallback cb = PeriodicCallback(self, None, period_milliseconds) return self._add_session_callback(cb, callback, one_shot=False, originator=self.add_periodic_callback)
[ "def", "add_periodic_callback", "(", "self", ",", "callback", ",", "period_milliseconds", ")", ":", "from", ".", ".", "server", ".", "callbacks", "import", "PeriodicCallback", "cb", "=", "PeriodicCallback", "(", "self", ",", "None", ",", "period_milliseconds", "...
Add a callback to be invoked on a session periodically. Args: callback (callable) : A callback function to execute periodically period_milliseconds (int) : Number of milliseconds between each callback execution. Returns: PeriodicCallback : can be used with ``remove_periodic_callback`` .. note:: Periodic callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells.
[ "Add", "a", "callback", "to", "be", "invoked", "on", "a", "session", "periodically", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L246-L269
30,494
bokeh/bokeh
bokeh/document/document.py
Document.add_root
def add_root(self, model, setter=None): ''' Add a model as a root of this Document. Any changes to this model (including to other models referred to by it) will trigger ``on_change`` callbacks registered on this document. Args: model (Model) : The model to add as a root of this document. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. ''' if model in self._roots: return self._push_all_models_freeze() # TODO (bird) Should we do some kind of reporting of how many # LayoutDOM's are in the document roots? In vanilla bokeh cases e.g. # output_file more than one LayoutDOM is probably not going to go # well. But in embedded cases, you may well want more than one. try: self._roots.append(model) finally: self._pop_all_models_freeze() self._trigger_on_change(RootAddedEvent(self, model, setter))
python
def add_root(self, model, setter=None): ''' Add a model as a root of this Document. Any changes to this model (including to other models referred to by it) will trigger ``on_change`` callbacks registered on this document. Args: model (Model) : The model to add as a root of this document. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. ''' if model in self._roots: return self._push_all_models_freeze() # TODO (bird) Should we do some kind of reporting of how many # LayoutDOM's are in the document roots? In vanilla bokeh cases e.g. # output_file more than one LayoutDOM is probably not going to go # well. But in embedded cases, you may well want more than one. try: self._roots.append(model) finally: self._pop_all_models_freeze() self._trigger_on_change(RootAddedEvent(self, model, setter))
[ "def", "add_root", "(", "self", ",", "model", ",", "setter", "=", "None", ")", ":", "if", "model", "in", "self", ".", "_roots", ":", "return", "self", ".", "_push_all_models_freeze", "(", ")", "# TODO (bird) Should we do some kind of reporting of how many", "# Lay...
Add a model as a root of this Document. Any changes to this model (including to other models referred to by it) will trigger ``on_change`` callbacks registered on this document. Args: model (Model) : The model to add as a root of this document. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself.
[ "Add", "a", "model", "as", "a", "root", "of", "this", "Document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L271-L305
30,495
bokeh/bokeh
bokeh/document/document.py
Document.add_timeout_callback
def add_timeout_callback(self, callback, timeout_milliseconds): ''' Add callback to be invoked once, after a specified timeout passes. Args: callback (callable) : A callback function to execute after timeout timeout_milliseconds (int) : Number of milliseconds before callback execution. Returns: TimeoutCallback : can be used with ``remove_timeout_callback`` .. note:: Timeout callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells. ''' from ..server.callbacks import TimeoutCallback cb = TimeoutCallback(self, None, timeout_milliseconds) return self._add_session_callback(cb, callback, one_shot=True, originator=self.add_timeout_callback)
python
def add_timeout_callback(self, callback, timeout_milliseconds): ''' Add callback to be invoked once, after a specified timeout passes. Args: callback (callable) : A callback function to execute after timeout timeout_milliseconds (int) : Number of milliseconds before callback execution. Returns: TimeoutCallback : can be used with ``remove_timeout_callback`` .. note:: Timeout callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells. ''' from ..server.callbacks import TimeoutCallback cb = TimeoutCallback(self, None, timeout_milliseconds) return self._add_session_callback(cb, callback, one_shot=True, originator=self.add_timeout_callback)
[ "def", "add_timeout_callback", "(", "self", ",", "callback", ",", "timeout_milliseconds", ")", ":", "from", ".", ".", "server", ".", "callbacks", "import", "TimeoutCallback", "cb", "=", "TimeoutCallback", "(", "self", ",", "None", ",", "timeout_milliseconds", ")...
Add callback to be invoked once, after a specified timeout passes. Args: callback (callable) : A callback function to execute after timeout timeout_milliseconds (int) : Number of milliseconds before callback execution. Returns: TimeoutCallback : can be used with ``remove_timeout_callback`` .. note:: Timeout callbacks only work within the context of a Bokeh server session. This function will no effect when Bokeh outputs to standalone HTML or Jupyter notebook cells.
[ "Add", "callback", "to", "be", "invoked", "once", "after", "a", "specified", "timeout", "passes", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L307-L330
30,496
bokeh/bokeh
bokeh/document/document.py
Document.clear
def clear(self): ''' Remove all content from the document but do not reset title. Returns: None ''' self._push_all_models_freeze() try: while len(self._roots) > 0: r = next(iter(self._roots)) self.remove_root(r) finally: self._pop_all_models_freeze()
python
def clear(self): ''' Remove all content from the document but do not reset title. Returns: None ''' self._push_all_models_freeze() try: while len(self._roots) > 0: r = next(iter(self._roots)) self.remove_root(r) finally: self._pop_all_models_freeze()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_push_all_models_freeze", "(", ")", "try", ":", "while", "len", "(", "self", ".", "_roots", ")", ">", "0", ":", "r", "=", "next", "(", "iter", "(", "self", ".", "_roots", ")", ")", "self", ".",...
Remove all content from the document but do not reset title. Returns: None
[ "Remove", "all", "content", "from", "the", "document", "but", "do", "not", "reset", "title", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L450-L463
30,497
bokeh/bokeh
bokeh/document/document.py
Document.delete_modules
def delete_modules(self): ''' Clean up after any modules created by this Document when its session is destroyed. ''' from gc import get_referrers from types import FrameType log.debug("Deleting %s modules for %s" % (len(self._modules), self)) for module in self._modules: # Modules created for a Document should have three referrers at this point: # # - sys.modules # - self._modules # - a frame object # # This function will take care of removing these expected references. # # If there are any additional referrers, this probably means the module will be # leaked. Here we perform a detailed check that the only referrers are expected # ones. Otherwise issue an error log message with details. referrers = get_referrers(module) referrers = [x for x in referrers if x is not sys.modules] referrers = [x for x in referrers if x is not self._modules] referrers = [x for x in referrers if not isinstance(x, FrameType)] if len(referrers) != 0: log.error("Module %r has extra unexpected referrers! This could indicate a serious memory leak. Extra referrers: %r" % (module, referrers)) # remove the reference from sys.modules if module.__name__ in sys.modules: del sys.modules[module.__name__] # remove the reference from self._modules self._modules = None
python
def delete_modules(self): ''' Clean up after any modules created by this Document when its session is destroyed. ''' from gc import get_referrers from types import FrameType log.debug("Deleting %s modules for %s" % (len(self._modules), self)) for module in self._modules: # Modules created for a Document should have three referrers at this point: # # - sys.modules # - self._modules # - a frame object # # This function will take care of removing these expected references. # # If there are any additional referrers, this probably means the module will be # leaked. Here we perform a detailed check that the only referrers are expected # ones. Otherwise issue an error log message with details. referrers = get_referrers(module) referrers = [x for x in referrers if x is not sys.modules] referrers = [x for x in referrers if x is not self._modules] referrers = [x for x in referrers if not isinstance(x, FrameType)] if len(referrers) != 0: log.error("Module %r has extra unexpected referrers! This could indicate a serious memory leak. Extra referrers: %r" % (module, referrers)) # remove the reference from sys.modules if module.__name__ in sys.modules: del sys.modules[module.__name__] # remove the reference from self._modules self._modules = None
[ "def", "delete_modules", "(", "self", ")", ":", "from", "gc", "import", "get_referrers", "from", "types", "import", "FrameType", "log", ".", "debug", "(", "\"Deleting %s modules for %s\"", "%", "(", "len", "(", "self", ".", "_modules", ")", ",", "self", ")",...
Clean up after any modules created by this Document when its session is destroyed.
[ "Clean", "up", "after", "any", "modules", "created", "by", "this", "Document", "when", "its", "session", "is", "destroyed", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L485-L520
30,498
bokeh/bokeh
bokeh/document/document.py
Document.from_json
def from_json(cls, json): ''' Load a document from JSON. json (JSON-data) : A JSON-encoded document to create a new Document from. Returns: Document : ''' roots_json = json['roots'] root_ids = roots_json['root_ids'] references_json = roots_json['references'] references = instantiate_references_json(references_json) initialize_references_json(references_json, references) doc = Document() for r in root_ids: doc.add_root(references[r]) doc.title = json['title'] return doc
python
def from_json(cls, json): ''' Load a document from JSON. json (JSON-data) : A JSON-encoded document to create a new Document from. Returns: Document : ''' roots_json = json['roots'] root_ids = roots_json['root_ids'] references_json = roots_json['references'] references = instantiate_references_json(references_json) initialize_references_json(references_json, references) doc = Document() for r in root_ids: doc.add_root(references[r]) doc.title = json['title'] return doc
[ "def", "from_json", "(", "cls", ",", "json", ")", ":", "roots_json", "=", "json", "[", "'roots'", "]", "root_ids", "=", "roots_json", "[", "'root_ids'", "]", "references_json", "=", "roots_json", "[", "'references'", "]", "references", "=", "instantiate_refere...
Load a document from JSON. json (JSON-data) : A JSON-encoded document to create a new Document from. Returns: Document :
[ "Load", "a", "document", "from", "JSON", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L525-L548
30,499
bokeh/bokeh
bokeh/document/document.py
Document.hold
def hold(self, policy="combine"): ''' Activate a document hold. While a hold is active, no model changes will be applied, or trigger callbacks. Once ``unhold`` is called, the events collected during the hold will be applied according to the hold policy. Args: hold ('combine' or 'collect', optional) Whether events collected during a hold should attempt to be combined (default: 'combine') When set to ``'collect'`` all events will be collected and replayed in order as-is when ``unhold`` is called. When set to ``'combine'`` Bokeh will attempt to combine compatible events together. Typically, different events that change the same property on the same mode can be combined. For example, if the following sequence occurs: .. code-block:: python doc.hold('combine') slider.value = 10 slider.value = 11 slider.value = 12 Then only *one* callback, for the last ``slider.value = 12`` will be triggered. Returns: None .. note:: ``hold`` only applies to document change events, i.e. setting properties on models. It does not apply to events such as ``ButtonClick``, etc. ''' if self._hold is not None and self._hold != policy: log.warning("hold already active with '%s', ignoring '%s'" % (self._hold, policy)) return if policy not in HoldPolicy: raise ValueError("Unknown hold policy %r" % policy) self._hold = policy
python
def hold(self, policy="combine"): ''' Activate a document hold. While a hold is active, no model changes will be applied, or trigger callbacks. Once ``unhold`` is called, the events collected during the hold will be applied according to the hold policy. Args: hold ('combine' or 'collect', optional) Whether events collected during a hold should attempt to be combined (default: 'combine') When set to ``'collect'`` all events will be collected and replayed in order as-is when ``unhold`` is called. When set to ``'combine'`` Bokeh will attempt to combine compatible events together. Typically, different events that change the same property on the same mode can be combined. For example, if the following sequence occurs: .. code-block:: python doc.hold('combine') slider.value = 10 slider.value = 11 slider.value = 12 Then only *one* callback, for the last ``slider.value = 12`` will be triggered. Returns: None .. note:: ``hold`` only applies to document change events, i.e. setting properties on models. It does not apply to events such as ``ButtonClick``, etc. ''' if self._hold is not None and self._hold != policy: log.warning("hold already active with '%s', ignoring '%s'" % (self._hold, policy)) return if policy not in HoldPolicy: raise ValueError("Unknown hold policy %r" % policy) self._hold = policy
[ "def", "hold", "(", "self", ",", "policy", "=", "\"combine\"", ")", ":", "if", "self", ".", "_hold", "is", "not", "None", "and", "self", ".", "_hold", "!=", "policy", ":", "log", ".", "warning", "(", "\"hold already active with '%s', ignoring '%s'\"", "%", ...
Activate a document hold. While a hold is active, no model changes will be applied, or trigger callbacks. Once ``unhold`` is called, the events collected during the hold will be applied according to the hold policy. Args: hold ('combine' or 'collect', optional) Whether events collected during a hold should attempt to be combined (default: 'combine') When set to ``'collect'`` all events will be collected and replayed in order as-is when ``unhold`` is called. When set to ``'combine'`` Bokeh will attempt to combine compatible events together. Typically, different events that change the same property on the same mode can be combined. For example, if the following sequence occurs: .. code-block:: python doc.hold('combine') slider.value = 10 slider.value = 11 slider.value = 12 Then only *one* callback, for the last ``slider.value = 12`` will be triggered. Returns: None .. note:: ``hold`` only applies to document change events, i.e. setting properties on models. It does not apply to events such as ``ButtonClick``, etc.
[ "Activate", "a", "document", "hold", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L591-L635