repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
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", "(", "palette", "=", "palette", ",", "low", "=", "low", ",", "high", "=", "high", ",", "nan_color", "=", "nan_color", ",", "low_color", "=", "low_color", ",", "high_color", "=", "high_color", ")", ")" ]
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
train
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", "(", "palette", "=", "palette", ",", "low", "=", "low", ",", "high", "=", "high", ",", "nan_color", "=", "nan_color", ",", "low_color", "=", "low_color", ",", "high_color", "=", "high_color", ")", ")" ]
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
train
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", "(", ")", "else", ":", "controller", "=", "webbrowser", ".", "get", "(", "browser", ")", "else", ":", "controller", "=", "webbrowser", "return", "controller" ]
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
train
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", "}", "[", "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" ]
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
train
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.\"", ")", "if", "not", "isinstance", "(", "func", ",", "FunctionType", ")", ":", "raise", "ValueError", "(", "'CustomJSFilter.from_py_func only accepts function objects.'", ")", "pscript", "=", "import_required", "(", "'pscript'", ",", "dedent", "(", "\"\"\"\\\n To use Python functions for CustomJSFilter, you need PScript\n '(\"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", ")" ]
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
train
bokeh/bokeh
examples/plotting/file/vector.py
streamlines
def streamlines(x, y, u, v, density=1): ''' Return streamlines of a vector flow. * x and y are 1d arrays defining an *evenly spaced* grid. * u and v are 2d arrays (shape [y,x]) giving velocities. * density controls the closeness of the streamlines. For different densities in each direction, use a tuple or list [densityx, densityy]. ''' ## Set up some constants - size of the grid used. NGX = len(x) NGY = len(y) ## Constants used to convert between grid index coords and user coords. DX = x[1]-x[0] DY = y[1]-y[0] XOFF = x[0] YOFF = y[0] ## Now rescale velocity onto axes-coordinates u = u / (x[-1]-x[0]) v = v / (y[-1]-y[0]) speed = np.sqrt(u*u+v*v) ## s (path length) will now be in axes-coordinates, but we must ## rescale u for integrations. u *= NGX v *= NGY ## Now u and v in grid-coordinates. NBX = int(30*density) NBY = int(30*density) blank = np.zeros((NBY,NBX)) bx_spacing = NGX/float(NBX-1) by_spacing = NGY/float(NBY-1) def blank_pos(xi, yi): return int((xi / bx_spacing) + 0.5), \ int((yi / by_spacing) + 0.5) def value_at(a, xi, yi): if type(xi) == np.ndarray: x = xi.astype(np.int) y = yi.astype(np.int) else: x = np.int(xi) y = np.int(yi) a00 = a[y,x] a01 = a[y,x+1] a10 = a[y+1,x] a11 = a[y+1,x+1] xt = xi - x yt = yi - y a0 = a00*(1-xt) + a01*xt a1 = a10*(1-xt) + a11*xt return a0*(1-yt) + a1*yt def rk4_integrate(x0, y0): ## This function does RK4 forward and back trajectories from ## the initial conditions, with the odd 'blank array' ## termination conditions. TODO tidy the integration loops. def f(xi, yi): dt_ds = 1./value_at(speed, xi, yi) ui = value_at(u, xi, yi) vi = value_at(v, xi, yi) return ui*dt_ds, vi*dt_ds def g(xi, yi): dt_ds = 1./value_at(speed, xi, yi) ui = value_at(u, xi, yi) vi = value_at(v, xi, yi) return -ui*dt_ds, -vi*dt_ds check = lambda xi, yi: xi>=0 and xi<NGX-1 and yi>=0 and yi<NGY-1 bx_changes = [] by_changes = [] ## Integrator function def rk4(x0, y0, f): ds = 0.01 #min(1./NGX, 1./NGY, 0.01) stotal = 0 xi = x0 yi = y0 xb, yb = blank_pos(xi, yi) xf_traj = [] yf_traj = [] while check(xi, yi): # Time step. First save the point. xf_traj.append(xi) yf_traj.append(yi) # Next, advance one using RK4 try: k1x, k1y = f(xi, yi) k2x, k2y = f(xi + .5*ds*k1x, yi + .5*ds*k1y) k3x, k3y = f(xi + .5*ds*k2x, yi + .5*ds*k2y) k4x, k4y = f(xi + ds*k3x, yi + ds*k3y) except IndexError: # Out of the domain on one of the intermediate steps break xi += ds*(k1x+2*k2x+2*k3x+k4x) / 6. yi += ds*(k1y+2*k2y+2*k3y+k4y) / 6. # Final position might be out of the domain if not check(xi, yi): break stotal += ds # Next, if s gets to thres, check blank. new_xb, new_yb = blank_pos(xi, yi) if new_xb != xb or new_yb != yb: # New square, so check and colour. Quit if required. if blank[new_yb,new_xb] == 0: blank[new_yb,new_xb] = 1 bx_changes.append(new_xb) by_changes.append(new_yb) xb = new_xb yb = new_yb else: break if stotal > 2: break return stotal, xf_traj, yf_traj integrator = rk4 sf, xf_traj, yf_traj = integrator(x0, y0, f) sb, xb_traj, yb_traj = integrator(x0, y0, g) stotal = sf + sb x_traj = xb_traj[::-1] + xf_traj[1:] y_traj = yb_traj[::-1] + yf_traj[1:] ## Tests to check length of traj. Remember, s in units of axes. if len(x_traj) < 1: return None if stotal > .2: initxb, inityb = blank_pos(x0, y0) blank[inityb, initxb] = 1 return x_traj, y_traj else: for xb, yb in zip(bx_changes, by_changes): blank[yb, xb] = 0 return None ## A quick function for integrating trajectories if blank==0. trajectories = [] def traj(xb, yb): if xb < 0 or xb >= NBX or yb < 0 or yb >= NBY: return if blank[yb, xb] == 0: t = rk4_integrate(xb*bx_spacing, yb*by_spacing) if t is not None: trajectories.append(t) ## Now we build up the trajectory set. I've found it best to look ## for blank==0 along the edges first, and work inwards. for indent in range((max(NBX,NBY))//2): for xi in range(max(NBX,NBY)-2*indent): traj(xi+indent, indent) traj(xi+indent, NBY-1-indent) traj(indent, xi+indent) traj(NBX-1-indent, xi+indent) xs = [np.array(t[0])*DX+XOFF for t in trajectories] ys = [np.array(t[1])*DY+YOFF for t in trajectories] return xs, ys
python
def streamlines(x, y, u, v, density=1): ''' Return streamlines of a vector flow. * x and y are 1d arrays defining an *evenly spaced* grid. * u and v are 2d arrays (shape [y,x]) giving velocities. * density controls the closeness of the streamlines. For different densities in each direction, use a tuple or list [densityx, densityy]. ''' ## Set up some constants - size of the grid used. NGX = len(x) NGY = len(y) ## Constants used to convert between grid index coords and user coords. DX = x[1]-x[0] DY = y[1]-y[0] XOFF = x[0] YOFF = y[0] ## Now rescale velocity onto axes-coordinates u = u / (x[-1]-x[0]) v = v / (y[-1]-y[0]) speed = np.sqrt(u*u+v*v) ## s (path length) will now be in axes-coordinates, but we must ## rescale u for integrations. u *= NGX v *= NGY ## Now u and v in grid-coordinates. NBX = int(30*density) NBY = int(30*density) blank = np.zeros((NBY,NBX)) bx_spacing = NGX/float(NBX-1) by_spacing = NGY/float(NBY-1) def blank_pos(xi, yi): return int((xi / bx_spacing) + 0.5), \ int((yi / by_spacing) + 0.5) def value_at(a, xi, yi): if type(xi) == np.ndarray: x = xi.astype(np.int) y = yi.astype(np.int) else: x = np.int(xi) y = np.int(yi) a00 = a[y,x] a01 = a[y,x+1] a10 = a[y+1,x] a11 = a[y+1,x+1] xt = xi - x yt = yi - y a0 = a00*(1-xt) + a01*xt a1 = a10*(1-xt) + a11*xt return a0*(1-yt) + a1*yt def rk4_integrate(x0, y0): ## This function does RK4 forward and back trajectories from ## the initial conditions, with the odd 'blank array' ## termination conditions. TODO tidy the integration loops. def f(xi, yi): dt_ds = 1./value_at(speed, xi, yi) ui = value_at(u, xi, yi) vi = value_at(v, xi, yi) return ui*dt_ds, vi*dt_ds def g(xi, yi): dt_ds = 1./value_at(speed, xi, yi) ui = value_at(u, xi, yi) vi = value_at(v, xi, yi) return -ui*dt_ds, -vi*dt_ds check = lambda xi, yi: xi>=0 and xi<NGX-1 and yi>=0 and yi<NGY-1 bx_changes = [] by_changes = [] ## Integrator function def rk4(x0, y0, f): ds = 0.01 #min(1./NGX, 1./NGY, 0.01) stotal = 0 xi = x0 yi = y0 xb, yb = blank_pos(xi, yi) xf_traj = [] yf_traj = [] while check(xi, yi): # Time step. First save the point. xf_traj.append(xi) yf_traj.append(yi) # Next, advance one using RK4 try: k1x, k1y = f(xi, yi) k2x, k2y = f(xi + .5*ds*k1x, yi + .5*ds*k1y) k3x, k3y = f(xi + .5*ds*k2x, yi + .5*ds*k2y) k4x, k4y = f(xi + ds*k3x, yi + ds*k3y) except IndexError: # Out of the domain on one of the intermediate steps break xi += ds*(k1x+2*k2x+2*k3x+k4x) / 6. yi += ds*(k1y+2*k2y+2*k3y+k4y) / 6. # Final position might be out of the domain if not check(xi, yi): break stotal += ds # Next, if s gets to thres, check blank. new_xb, new_yb = blank_pos(xi, yi) if new_xb != xb or new_yb != yb: # New square, so check and colour. Quit if required. if blank[new_yb,new_xb] == 0: blank[new_yb,new_xb] = 1 bx_changes.append(new_xb) by_changes.append(new_yb) xb = new_xb yb = new_yb else: break if stotal > 2: break return stotal, xf_traj, yf_traj integrator = rk4 sf, xf_traj, yf_traj = integrator(x0, y0, f) sb, xb_traj, yb_traj = integrator(x0, y0, g) stotal = sf + sb x_traj = xb_traj[::-1] + xf_traj[1:] y_traj = yb_traj[::-1] + yf_traj[1:] ## Tests to check length of traj. Remember, s in units of axes. if len(x_traj) < 1: return None if stotal > .2: initxb, inityb = blank_pos(x0, y0) blank[inityb, initxb] = 1 return x_traj, y_traj else: for xb, yb in zip(bx_changes, by_changes): blank[yb, xb] = 0 return None ## A quick function for integrating trajectories if blank==0. trajectories = [] def traj(xb, yb): if xb < 0 or xb >= NBX or yb < 0 or yb >= NBY: return if blank[yb, xb] == 0: t = rk4_integrate(xb*bx_spacing, yb*by_spacing) if t is not None: trajectories.append(t) ## Now we build up the trajectory set. I've found it best to look ## for blank==0 along the edges first, and work inwards. for indent in range((max(NBX,NBY))//2): for xi in range(max(NBX,NBY)-2*indent): traj(xi+indent, indent) traj(xi+indent, NBY-1-indent) traj(indent, xi+indent) traj(NBX-1-indent, xi+indent) xs = [np.array(t[0])*DX+XOFF for t in trajectories] ys = [np.array(t[1])*DY+YOFF for t in trajectories] return xs, ys
[ "def", "streamlines", "(", "x", ",", "y", ",", "u", ",", "v", ",", "density", "=", "1", ")", ":", "## Set up some constants - size of the grid used.", "NGX", "=", "len", "(", "x", ")", "NGY", "=", "len", "(", "y", ")", "## Constants used to convert between grid index coords and user coords.", "DX", "=", "x", "[", "1", "]", "-", "x", "[", "0", "]", "DY", "=", "y", "[", "1", "]", "-", "y", "[", "0", "]", "XOFF", "=", "x", "[", "0", "]", "YOFF", "=", "y", "[", "0", "]", "## Now rescale velocity onto axes-coordinates", "u", "=", "u", "/", "(", "x", "[", "-", "1", "]", "-", "x", "[", "0", "]", ")", "v", "=", "v", "/", "(", "y", "[", "-", "1", "]", "-", "y", "[", "0", "]", ")", "speed", "=", "np", ".", "sqrt", "(", "u", "*", "u", "+", "v", "*", "v", ")", "## s (path length) will now be in axes-coordinates, but we must", "## rescale u for integrations.", "u", "*=", "NGX", "v", "*=", "NGY", "## Now u and v in grid-coordinates.", "NBX", "=", "int", "(", "30", "*", "density", ")", "NBY", "=", "int", "(", "30", "*", "density", ")", "blank", "=", "np", ".", "zeros", "(", "(", "NBY", ",", "NBX", ")", ")", "bx_spacing", "=", "NGX", "/", "float", "(", "NBX", "-", "1", ")", "by_spacing", "=", "NGY", "/", "float", "(", "NBY", "-", "1", ")", "def", "blank_pos", "(", "xi", ",", "yi", ")", ":", "return", "int", "(", "(", "xi", "/", "bx_spacing", ")", "+", "0.5", ")", ",", "int", "(", "(", "yi", "/", "by_spacing", ")", "+", "0.5", ")", "def", "value_at", "(", "a", ",", "xi", ",", "yi", ")", ":", "if", "type", "(", "xi", ")", "==", "np", ".", "ndarray", ":", "x", "=", "xi", ".", "astype", "(", "np", ".", "int", ")", "y", "=", "yi", ".", "astype", "(", "np", ".", "int", ")", "else", ":", "x", "=", "np", ".", "int", "(", "xi", ")", "y", "=", "np", ".", "int", "(", "yi", ")", "a00", "=", "a", "[", "y", ",", "x", "]", "a01", "=", "a", "[", "y", ",", "x", "+", "1", "]", "a10", "=", "a", "[", "y", "+", "1", ",", "x", "]", "a11", "=", "a", "[", "y", "+", "1", ",", "x", "+", "1", "]", "xt", "=", "xi", "-", "x", "yt", "=", "yi", "-", "y", "a0", "=", "a00", "*", "(", "1", "-", "xt", ")", "+", "a01", "*", "xt", "a1", "=", "a10", "*", "(", "1", "-", "xt", ")", "+", "a11", "*", "xt", "return", "a0", "*", "(", "1", "-", "yt", ")", "+", "a1", "*", "yt", "def", "rk4_integrate", "(", "x0", ",", "y0", ")", ":", "## This function does RK4 forward and back trajectories from", "## the initial conditions, with the odd 'blank array'", "## termination conditions. TODO tidy the integration loops.", "def", "f", "(", "xi", ",", "yi", ")", ":", "dt_ds", "=", "1.", "/", "value_at", "(", "speed", ",", "xi", ",", "yi", ")", "ui", "=", "value_at", "(", "u", ",", "xi", ",", "yi", ")", "vi", "=", "value_at", "(", "v", ",", "xi", ",", "yi", ")", "return", "ui", "*", "dt_ds", ",", "vi", "*", "dt_ds", "def", "g", "(", "xi", ",", "yi", ")", ":", "dt_ds", "=", "1.", "/", "value_at", "(", "speed", ",", "xi", ",", "yi", ")", "ui", "=", "value_at", "(", "u", ",", "xi", ",", "yi", ")", "vi", "=", "value_at", "(", "v", ",", "xi", ",", "yi", ")", "return", "-", "ui", "*", "dt_ds", ",", "-", "vi", "*", "dt_ds", "check", "=", "lambda", "xi", ",", "yi", ":", "xi", ">=", "0", "and", "xi", "<", "NGX", "-", "1", "and", "yi", ">=", "0", "and", "yi", "<", "NGY", "-", "1", "bx_changes", "=", "[", "]", "by_changes", "=", "[", "]", "## Integrator function", "def", "rk4", "(", "x0", ",", "y0", ",", "f", ")", ":", "ds", "=", "0.01", "#min(1./NGX, 1./NGY, 0.01)", "stotal", "=", "0", "xi", "=", "x0", "yi", "=", "y0", "xb", ",", "yb", "=", "blank_pos", "(", "xi", ",", "yi", ")", "xf_traj", "=", "[", "]", "yf_traj", "=", "[", "]", "while", "check", "(", "xi", ",", "yi", ")", ":", "# Time step. First save the point.", "xf_traj", ".", "append", "(", "xi", ")", "yf_traj", ".", "append", "(", "yi", ")", "# Next, advance one using RK4", "try", ":", "k1x", ",", "k1y", "=", "f", "(", "xi", ",", "yi", ")", "k2x", ",", "k2y", "=", "f", "(", "xi", "+", ".5", "*", "ds", "*", "k1x", ",", "yi", "+", ".5", "*", "ds", "*", "k1y", ")", "k3x", ",", "k3y", "=", "f", "(", "xi", "+", ".5", "*", "ds", "*", "k2x", ",", "yi", "+", ".5", "*", "ds", "*", "k2y", ")", "k4x", ",", "k4y", "=", "f", "(", "xi", "+", "ds", "*", "k3x", ",", "yi", "+", "ds", "*", "k3y", ")", "except", "IndexError", ":", "# Out of the domain on one of the intermediate steps", "break", "xi", "+=", "ds", "*", "(", "k1x", "+", "2", "*", "k2x", "+", "2", "*", "k3x", "+", "k4x", ")", "/", "6.", "yi", "+=", "ds", "*", "(", "k1y", "+", "2", "*", "k2y", "+", "2", "*", "k3y", "+", "k4y", ")", "/", "6.", "# Final position might be out of the domain", "if", "not", "check", "(", "xi", ",", "yi", ")", ":", "break", "stotal", "+=", "ds", "# Next, if s gets to thres, check blank.", "new_xb", ",", "new_yb", "=", "blank_pos", "(", "xi", ",", "yi", ")", "if", "new_xb", "!=", "xb", "or", "new_yb", "!=", "yb", ":", "# New square, so check and colour. Quit if required.", "if", "blank", "[", "new_yb", ",", "new_xb", "]", "==", "0", ":", "blank", "[", "new_yb", ",", "new_xb", "]", "=", "1", "bx_changes", ".", "append", "(", "new_xb", ")", "by_changes", ".", "append", "(", "new_yb", ")", "xb", "=", "new_xb", "yb", "=", "new_yb", "else", ":", "break", "if", "stotal", ">", "2", ":", "break", "return", "stotal", ",", "xf_traj", ",", "yf_traj", "integrator", "=", "rk4", "sf", ",", "xf_traj", ",", "yf_traj", "=", "integrator", "(", "x0", ",", "y0", ",", "f", ")", "sb", ",", "xb_traj", ",", "yb_traj", "=", "integrator", "(", "x0", ",", "y0", ",", "g", ")", "stotal", "=", "sf", "+", "sb", "x_traj", "=", "xb_traj", "[", ":", ":", "-", "1", "]", "+", "xf_traj", "[", "1", ":", "]", "y_traj", "=", "yb_traj", "[", ":", ":", "-", "1", "]", "+", "yf_traj", "[", "1", ":", "]", "## Tests to check length of traj. Remember, s in units of axes.", "if", "len", "(", "x_traj", ")", "<", "1", ":", "return", "None", "if", "stotal", ">", ".2", ":", "initxb", ",", "inityb", "=", "blank_pos", "(", "x0", ",", "y0", ")", "blank", "[", "inityb", ",", "initxb", "]", "=", "1", "return", "x_traj", ",", "y_traj", "else", ":", "for", "xb", ",", "yb", "in", "zip", "(", "bx_changes", ",", "by_changes", ")", ":", "blank", "[", "yb", ",", "xb", "]", "=", "0", "return", "None", "## A quick function for integrating trajectories if blank==0.", "trajectories", "=", "[", "]", "def", "traj", "(", "xb", ",", "yb", ")", ":", "if", "xb", "<", "0", "or", "xb", ">=", "NBX", "or", "yb", "<", "0", "or", "yb", ">=", "NBY", ":", "return", "if", "blank", "[", "yb", ",", "xb", "]", "==", "0", ":", "t", "=", "rk4_integrate", "(", "xb", "*", "bx_spacing", ",", "yb", "*", "by_spacing", ")", "if", "t", "is", "not", "None", ":", "trajectories", ".", "append", "(", "t", ")", "## Now we build up the trajectory set. I've found it best to look", "## for blank==0 along the edges first, and work inwards.", "for", "indent", "in", "range", "(", "(", "max", "(", "NBX", ",", "NBY", ")", ")", "//", "2", ")", ":", "for", "xi", "in", "range", "(", "max", "(", "NBX", ",", "NBY", ")", "-", "2", "*", "indent", ")", ":", "traj", "(", "xi", "+", "indent", ",", "indent", ")", "traj", "(", "xi", "+", "indent", ",", "NBY", "-", "1", "-", "indent", ")", "traj", "(", "indent", ",", "xi", "+", "indent", ")", "traj", "(", "NBX", "-", "1", "-", "indent", ",", "xi", "+", "indent", ")", "xs", "=", "[", "np", ".", "array", "(", "t", "[", "0", "]", ")", "*", "DX", "+", "XOFF", "for", "t", "in", "trajectories", "]", "ys", "=", "[", "np", ".", "array", "(", "t", "[", "1", "]", ")", "*", "DY", "+", "YOFF", "for", "t", "in", "trajectories", "]", "return", "xs", ",", "ys" ]
Return streamlines of a vector flow. * x and y are 1d arrays defining an *evenly spaced* grid. * u and v are 2d arrays (shape [y,x]) giving velocities. * density controls the closeness of the streamlines. For different densities in each direction, use a tuple or list [densityx, densityy].
[ "Return", "streamlines", "of", "a", "vector", "flow", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/plotting/file/vector.py#L8-L172
train
bokeh/bokeh
examples/howto/events_app.py
display_event
def display_event(div, attributes=[]): """ Function to build a suitable CustomJS to display the current event in the div model. """ style = 'float: left; clear: left; font-size: 10pt' return CustomJS(args=dict(div=div), code=""" var attrs = %s; var args = []; for (var i = 0; i<attrs.length; i++ ) { var val = JSON.stringify(cb_obj[attrs[i]], function(key, val) { return val.toFixed ? Number(val.toFixed(2)) : val; }) args.push(attrs[i] + '=' + val) } var line = "<span style=%r><b>" + cb_obj.event_name + "</b>(" + args.join(", ") + ")</span>\\n"; var text = div.text.concat(line); var lines = text.split("\\n") if (lines.length > 35) lines.shift(); div.text = lines.join("\\n"); """ % (attributes, style))
python
def display_event(div, attributes=[]): """ Function to build a suitable CustomJS to display the current event in the div model. """ style = 'float: left; clear: left; font-size: 10pt' return CustomJS(args=dict(div=div), code=""" var attrs = %s; var args = []; for (var i = 0; i<attrs.length; i++ ) { var val = JSON.stringify(cb_obj[attrs[i]], function(key, val) { return val.toFixed ? Number(val.toFixed(2)) : val; }) args.push(attrs[i] + '=' + val) } var line = "<span style=%r><b>" + cb_obj.event_name + "</b>(" + args.join(", ") + ")</span>\\n"; var text = div.text.concat(line); var lines = text.split("\\n") if (lines.length > 35) lines.shift(); div.text = lines.join("\\n"); """ % (attributes, style))
[ "def", "display_event", "(", "div", ",", "attributes", "=", "[", "]", ")", ":", "style", "=", "'float: left; clear: left; font-size: 10pt'", "return", "CustomJS", "(", "args", "=", "dict", "(", "div", "=", "div", ")", ",", "code", "=", "\"\"\"\n var attrs = %s;\n var args = [];\n for (var i = 0; i<attrs.length; i++ ) {\n var val = JSON.stringify(cb_obj[attrs[i]], function(key, val) {\n return val.toFixed ? Number(val.toFixed(2)) : val;\n })\n args.push(attrs[i] + '=' + val)\n }\n var line = \"<span style=%r><b>\" + cb_obj.event_name + \"</b>(\" + args.join(\", \") + \")</span>\\\\n\";\n var text = div.text.concat(line);\n var lines = text.split(\"\\\\n\")\n if (lines.length > 35)\n lines.shift();\n div.text = lines.join(\"\\\\n\");\n \"\"\"", "%", "(", "attributes", ",", "style", ")", ")" ]
Function to build a suitable CustomJS to display the current event in the div model.
[ "Function", "to", "build", "a", "suitable", "CustomJS", "to", "display", "the", "current", "event", "in", "the", "div", "model", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/howto/events_app.py#L16-L37
train
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", "(", "attr", "=", "attr", ",", "val", "=", "event", ".", "__dict__", "[", "attr", "]", ")", "for", "attr", "in", "attributes", "]", ")", "print", "(", "'{cls_name}({attrs})'", ".", "format", "(", "cls_name", "=", "cls_name", ",", "attrs", "=", "attrs", ")", ")", "return", "python_callback" ]
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
train
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\"", "%", "(", "msgtype", ",", "self", ".", "_version", ")", ")", "return", "self", ".", "_messages", "[", "msgtype", "]", ".", "create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
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
train
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 msgtype was: %r\"", ",", "header", ")", "raise", "ProtocolError", "(", "\"No 'msgtype' in header\"", ")", "return", "self", ".", "_messages", "[", "header", "[", "'msgtype'", "]", "]", ".", "assemble", "(", "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
[ "Create", "a", "Message", "instance", "assembled", "from", "json", "fragments", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/__init__.py#L82-L102
train
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", ".", "append", "(", "new_event", ")" ]
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
train
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", "(", "cb", ",", "callback", ",", "one_shot", "=", "True", ",", "originator", "=", "self", ".", "add_next_tick_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
train
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", ")", "return", "self", ".", "_add_session_callback", "(", "cb", ",", "callback", ",", "one_shot", "=", "False", ",", "originator", "=", "self", ".", "add_periodic_callback", ")" ]
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
train
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", "# 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", ")", ")" ]
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
train
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", ")", "return", "self", ".", "_add_session_callback", "(", "cb", ",", "callback", ",", "one_shot", "=", "True", ",", "originator", "=", "self", ".", "add_timeout_callback", ")" ]
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
train
bokeh/bokeh
bokeh/document/document.py
Document.apply_json_patch
def apply_json_patch(self, patch, setter=None): ''' Apply a JSON patch object and process any resulting events. Args: patch (JSON-data) : The JSON-object containing the patch to apply. 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. Returns: None ''' references_json = patch['references'] events_json = patch['events'] references = instantiate_references_json(references_json) # Use our existing model instances whenever we have them for obj in references.values(): if obj.id in self._all_models: references[obj.id] = self._all_models[obj.id] # The model being changed isn't always in references so add it in for event_json in events_json: if 'model' in event_json: model_id = event_json['model']['id'] if model_id in self._all_models: references[model_id] = self._all_models[model_id] initialize_references_json(references_json, references, setter) for event_json in events_json: if event_json['kind'] == 'ModelChanged': patched_id = event_json['model']['id'] if patched_id not in self._all_models: if patched_id not in self._all_former_model_ids: raise RuntimeError("Cannot apply patch to %s which is not in the document" % (str(patched_id))) else: log.warning("Cannot apply patch to %s which is not in the document anymore" % (str(patched_id))) break patched_obj = self._all_models[patched_id] attr = event_json['attr'] value = event_json['new'] patched_obj.set_from_json(attr, value, models=references, setter=setter) elif event_json['kind'] == 'ColumnDataChanged': source_id = event_json['column_source']['id'] if source_id not in self._all_models: raise RuntimeError("Cannot apply patch to %s which is not in the document" % (str(source_id))) source = self._all_models[source_id] value = event_json['new'] source.set_from_json('data', value, models=references, setter=setter) elif event_json['kind'] == 'ColumnsStreamed': source_id = event_json['column_source']['id'] if source_id not in self._all_models: raise RuntimeError("Cannot stream to %s which is not in the document" % (str(source_id))) source = self._all_models[source_id] data = event_json['data'] rollover = event_json.get('rollover', None) source._stream(data, rollover, setter) elif event_json['kind'] == 'ColumnsPatched': source_id = event_json['column_source']['id'] if source_id not in self._all_models: raise RuntimeError("Cannot apply patch to %s which is not in the document" % (str(source_id))) source = self._all_models[source_id] patches = event_json['patches'] source.patch(patches, setter) elif event_json['kind'] == 'RootAdded': root_id = event_json['model']['id'] root_obj = references[root_id] self.add_root(root_obj, setter) elif event_json['kind'] == 'RootRemoved': root_id = event_json['model']['id'] root_obj = references[root_id] self.remove_root(root_obj, setter) elif event_json['kind'] == 'TitleChanged': self._set_title(event_json['title'], setter) else: raise RuntimeError("Unknown patch event " + repr(event_json))
python
def apply_json_patch(self, patch, setter=None): ''' Apply a JSON patch object and process any resulting events. Args: patch (JSON-data) : The JSON-object containing the patch to apply. 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. Returns: None ''' references_json = patch['references'] events_json = patch['events'] references = instantiate_references_json(references_json) # Use our existing model instances whenever we have them for obj in references.values(): if obj.id in self._all_models: references[obj.id] = self._all_models[obj.id] # The model being changed isn't always in references so add it in for event_json in events_json: if 'model' in event_json: model_id = event_json['model']['id'] if model_id in self._all_models: references[model_id] = self._all_models[model_id] initialize_references_json(references_json, references, setter) for event_json in events_json: if event_json['kind'] == 'ModelChanged': patched_id = event_json['model']['id'] if patched_id not in self._all_models: if patched_id not in self._all_former_model_ids: raise RuntimeError("Cannot apply patch to %s which is not in the document" % (str(patched_id))) else: log.warning("Cannot apply patch to %s which is not in the document anymore" % (str(patched_id))) break patched_obj = self._all_models[patched_id] attr = event_json['attr'] value = event_json['new'] patched_obj.set_from_json(attr, value, models=references, setter=setter) elif event_json['kind'] == 'ColumnDataChanged': source_id = event_json['column_source']['id'] if source_id not in self._all_models: raise RuntimeError("Cannot apply patch to %s which is not in the document" % (str(source_id))) source = self._all_models[source_id] value = event_json['new'] source.set_from_json('data', value, models=references, setter=setter) elif event_json['kind'] == 'ColumnsStreamed': source_id = event_json['column_source']['id'] if source_id not in self._all_models: raise RuntimeError("Cannot stream to %s which is not in the document" % (str(source_id))) source = self._all_models[source_id] data = event_json['data'] rollover = event_json.get('rollover', None) source._stream(data, rollover, setter) elif event_json['kind'] == 'ColumnsPatched': source_id = event_json['column_source']['id'] if source_id not in self._all_models: raise RuntimeError("Cannot apply patch to %s which is not in the document" % (str(source_id))) source = self._all_models[source_id] patches = event_json['patches'] source.patch(patches, setter) elif event_json['kind'] == 'RootAdded': root_id = event_json['model']['id'] root_obj = references[root_id] self.add_root(root_obj, setter) elif event_json['kind'] == 'RootRemoved': root_id = event_json['model']['id'] root_obj = references[root_id] self.remove_root(root_obj, setter) elif event_json['kind'] == 'TitleChanged': self._set_title(event_json['title'], setter) else: raise RuntimeError("Unknown patch event " + repr(event_json))
[ "def", "apply_json_patch", "(", "self", ",", "patch", ",", "setter", "=", "None", ")", ":", "references_json", "=", "patch", "[", "'references'", "]", "events_json", "=", "patch", "[", "'events'", "]", "references", "=", "instantiate_references_json", "(", "references_json", ")", "# Use our existing model instances whenever we have them", "for", "obj", "in", "references", ".", "values", "(", ")", ":", "if", "obj", ".", "id", "in", "self", ".", "_all_models", ":", "references", "[", "obj", ".", "id", "]", "=", "self", ".", "_all_models", "[", "obj", ".", "id", "]", "# The model being changed isn't always in references so add it in", "for", "event_json", "in", "events_json", ":", "if", "'model'", "in", "event_json", ":", "model_id", "=", "event_json", "[", "'model'", "]", "[", "'id'", "]", "if", "model_id", "in", "self", ".", "_all_models", ":", "references", "[", "model_id", "]", "=", "self", ".", "_all_models", "[", "model_id", "]", "initialize_references_json", "(", "references_json", ",", "references", ",", "setter", ")", "for", "event_json", "in", "events_json", ":", "if", "event_json", "[", "'kind'", "]", "==", "'ModelChanged'", ":", "patched_id", "=", "event_json", "[", "'model'", "]", "[", "'id'", "]", "if", "patched_id", "not", "in", "self", ".", "_all_models", ":", "if", "patched_id", "not", "in", "self", ".", "_all_former_model_ids", ":", "raise", "RuntimeError", "(", "\"Cannot apply patch to %s which is not in the document\"", "%", "(", "str", "(", "patched_id", ")", ")", ")", "else", ":", "log", ".", "warning", "(", "\"Cannot apply patch to %s which is not in the document anymore\"", "%", "(", "str", "(", "patched_id", ")", ")", ")", "break", "patched_obj", "=", "self", ".", "_all_models", "[", "patched_id", "]", "attr", "=", "event_json", "[", "'attr'", "]", "value", "=", "event_json", "[", "'new'", "]", "patched_obj", ".", "set_from_json", "(", "attr", ",", "value", ",", "models", "=", "references", ",", "setter", "=", "setter", ")", "elif", "event_json", "[", "'kind'", "]", "==", "'ColumnDataChanged'", ":", "source_id", "=", "event_json", "[", "'column_source'", "]", "[", "'id'", "]", "if", "source_id", "not", "in", "self", ".", "_all_models", ":", "raise", "RuntimeError", "(", "\"Cannot apply patch to %s which is not in the document\"", "%", "(", "str", "(", "source_id", ")", ")", ")", "source", "=", "self", ".", "_all_models", "[", "source_id", "]", "value", "=", "event_json", "[", "'new'", "]", "source", ".", "set_from_json", "(", "'data'", ",", "value", ",", "models", "=", "references", ",", "setter", "=", "setter", ")", "elif", "event_json", "[", "'kind'", "]", "==", "'ColumnsStreamed'", ":", "source_id", "=", "event_json", "[", "'column_source'", "]", "[", "'id'", "]", "if", "source_id", "not", "in", "self", ".", "_all_models", ":", "raise", "RuntimeError", "(", "\"Cannot stream to %s which is not in the document\"", "%", "(", "str", "(", "source_id", ")", ")", ")", "source", "=", "self", ".", "_all_models", "[", "source_id", "]", "data", "=", "event_json", "[", "'data'", "]", "rollover", "=", "event_json", ".", "get", "(", "'rollover'", ",", "None", ")", "source", ".", "_stream", "(", "data", ",", "rollover", ",", "setter", ")", "elif", "event_json", "[", "'kind'", "]", "==", "'ColumnsPatched'", ":", "source_id", "=", "event_json", "[", "'column_source'", "]", "[", "'id'", "]", "if", "source_id", "not", "in", "self", ".", "_all_models", ":", "raise", "RuntimeError", "(", "\"Cannot apply patch to %s which is not in the document\"", "%", "(", "str", "(", "source_id", ")", ")", ")", "source", "=", "self", ".", "_all_models", "[", "source_id", "]", "patches", "=", "event_json", "[", "'patches'", "]", "source", ".", "patch", "(", "patches", ",", "setter", ")", "elif", "event_json", "[", "'kind'", "]", "==", "'RootAdded'", ":", "root_id", "=", "event_json", "[", "'model'", "]", "[", "'id'", "]", "root_obj", "=", "references", "[", "root_id", "]", "self", ".", "add_root", "(", "root_obj", ",", "setter", ")", "elif", "event_json", "[", "'kind'", "]", "==", "'RootRemoved'", ":", "root_id", "=", "event_json", "[", "'model'", "]", "[", "'id'", "]", "root_obj", "=", "references", "[", "root_id", "]", "self", ".", "remove_root", "(", "root_obj", ",", "setter", ")", "elif", "event_json", "[", "'kind'", "]", "==", "'TitleChanged'", ":", "self", ".", "_set_title", "(", "event_json", "[", "'title'", "]", ",", "setter", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unknown patch event \"", "+", "repr", "(", "event_json", ")", ")" ]
Apply a JSON patch object and process any resulting events. Args: patch (JSON-data) : The JSON-object containing the patch to apply. 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. Returns: None
[ "Apply", "a", "JSON", "patch", "object", "and", "process", "any", "resulting", "events", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L341-L435
train
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_root", "(", "r", ")", "finally", ":", "self", ".", "_pop_all_models_freeze", "(", ")" ]
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
train
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", ")", ")", "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" ]
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
train
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_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" ]
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
train
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'\"", "%", "(", "self", ".", "_hold", ",", "policy", ")", ")", "return", "if", "policy", "not", "in", "HoldPolicy", ":", "raise", "ValueError", "(", "\"Unknown hold policy %r\"", "%", "policy", ")", "self", ".", "_hold", "=", "policy" ]
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
train
bokeh/bokeh
bokeh/document/document.py
Document.unhold
def unhold(self): ''' Turn off any active document hold and apply any collected events. Returns: None ''' # no-op if we are already no holding if self._hold is None: return self._hold = None events = list(self._held_events) self._held_events = [] for event in events: self._trigger_on_change(event)
python
def unhold(self): ''' Turn off any active document hold and apply any collected events. Returns: None ''' # no-op if we are already no holding if self._hold is None: return self._hold = None events = list(self._held_events) self._held_events = [] for event in events: self._trigger_on_change(event)
[ "def", "unhold", "(", "self", ")", ":", "# no-op if we are already no holding", "if", "self", ".", "_hold", "is", "None", ":", "return", "self", ".", "_hold", "=", "None", "events", "=", "list", "(", "self", ".", "_held_events", ")", "self", ".", "_held_events", "=", "[", "]", "for", "event", "in", "events", ":", "self", ".", "_trigger_on_change", "(", "event", ")" ]
Turn off any active document hold and apply any collected events. Returns: None
[ "Turn", "off", "any", "active", "document", "hold", "and", "apply", "any", "collected", "events", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L637-L652
train
bokeh/bokeh
bokeh/document/document.py
Document.on_change
def on_change(self, *callbacks): ''' Provide callbacks to invoke if the document or any Model reachable from its roots changes. ''' for callback in callbacks: if callback in self._callbacks: continue _check_callback(callback, ('event',)) self._callbacks[callback] = callback
python
def on_change(self, *callbacks): ''' Provide callbacks to invoke if the document or any Model reachable from its roots changes. ''' for callback in callbacks: if callback in self._callbacks: continue _check_callback(callback, ('event',)) self._callbacks[callback] = callback
[ "def", "on_change", "(", "self", ",", "*", "callbacks", ")", ":", "for", "callback", "in", "callbacks", ":", "if", "callback", "in", "self", ".", "_callbacks", ":", "continue", "_check_callback", "(", "callback", ",", "(", "'event'", ",", ")", ")", "self", ".", "_callbacks", "[", "callback", "]", "=", "callback" ]
Provide callbacks to invoke if the document or any Model reachable from its roots changes.
[ "Provide", "callbacks", "to", "invoke", "if", "the", "document", "or", "any", "Model", "reachable", "from", "its", "roots", "changes", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L654-L665
train
bokeh/bokeh
bokeh/document/document.py
Document.on_session_destroyed
def on_session_destroyed(self, *callbacks): ''' Provide callbacks to invoke when the session serving the Document is destroyed ''' for callback in callbacks: _check_callback(callback, ('session_context',)) self._session_destroyed_callbacks.add(callback)
python
def on_session_destroyed(self, *callbacks): ''' Provide callbacks to invoke when the session serving the Document is destroyed ''' for callback in callbacks: _check_callback(callback, ('session_context',)) self._session_destroyed_callbacks.add(callback)
[ "def", "on_session_destroyed", "(", "self", ",", "*", "callbacks", ")", ":", "for", "callback", "in", "callbacks", ":", "_check_callback", "(", "callback", ",", "(", "'session_context'", ",", ")", ")", "self", ".", "_session_destroyed_callbacks", ".", "add", "(", "callback", ")" ]
Provide callbacks to invoke when the session serving the Document is destroyed
[ "Provide", "callbacks", "to", "invoke", "when", "the", "session", "serving", "the", "Document", "is", "destroyed" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L671-L678
train
bokeh/bokeh
bokeh/document/document.py
Document.remove_root
def remove_root(self, model, setter=None): ''' Remove a model as root model from this Document. Changes to this model may still trigger ``on_change`` callbacks on this document, if the model is still referred to by other root models. 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 not in self._roots: return # TODO (bev) ValueError? self._push_all_models_freeze() try: self._roots.remove(model) finally: self._pop_all_models_freeze() self._trigger_on_change(RootRemovedEvent(self, model, setter))
python
def remove_root(self, model, setter=None): ''' Remove a model as root model from this Document. Changes to this model may still trigger ``on_change`` callbacks on this document, if the model is still referred to by other root models. 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 not in self._roots: return # TODO (bev) ValueError? self._push_all_models_freeze() try: self._roots.remove(model) finally: self._pop_all_models_freeze() self._trigger_on_change(RootRemovedEvent(self, model, setter))
[ "def", "remove_root", "(", "self", ",", "model", ",", "setter", "=", "None", ")", ":", "if", "model", "not", "in", "self", ".", "_roots", ":", "return", "# TODO (bev) ValueError?", "self", ".", "_push_all_models_freeze", "(", ")", "try", ":", "self", ".", "_roots", ".", "remove", "(", "model", ")", "finally", ":", "self", ".", "_pop_all_models_freeze", "(", ")", "self", ".", "_trigger_on_change", "(", "RootRemovedEvent", "(", "self", ",", "model", ",", "setter", ")", ")" ]
Remove a model as root model from this Document. Changes to this model may still trigger ``on_change`` callbacks on this document, if the model is still referred to by other root models. 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.
[ "Remove", "a", "model", "as", "root", "model", "from", "this", "Document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L720-L750
train
bokeh/bokeh
bokeh/document/document.py
Document.replace_with_json
def replace_with_json(self, json): ''' Overwrite everything in this document with the JSON-encoded document. json (JSON-data) : A JSON-encoded document to overwrite this one. Returns: None ''' replacement = self.from_json(json) replacement._destructively_move(self)
python
def replace_with_json(self, json): ''' Overwrite everything in this document with the JSON-encoded document. json (JSON-data) : A JSON-encoded document to overwrite this one. Returns: None ''' replacement = self.from_json(json) replacement._destructively_move(self)
[ "def", "replace_with_json", "(", "self", ",", "json", ")", ":", "replacement", "=", "self", ".", "from_json", "(", "json", ")", "replacement", ".", "_destructively_move", "(", "self", ")" ]
Overwrite everything in this document with the JSON-encoded document. json (JSON-data) : A JSON-encoded document to overwrite this one. Returns: None
[ "Overwrite", "everything", "in", "this", "document", "with", "the", "JSON", "-", "encoded", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L767-L779
train
bokeh/bokeh
bokeh/document/document.py
Document.select
def select(self, selector): ''' Query this document for objects that match the given selector. Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: seq[Model] ''' if self._is_single_string_selector(selector, 'name'): # special-case optimization for by-name query return self._all_models_by_name.get_all(selector['name']) else: return find(self._all_models.values(), selector)
python
def select(self, selector): ''' Query this document for objects that match the given selector. Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: seq[Model] ''' if self._is_single_string_selector(selector, 'name'): # special-case optimization for by-name query return self._all_models_by_name.get_all(selector['name']) else: return find(self._all_models.values(), selector)
[ "def", "select", "(", "self", ",", "selector", ")", ":", "if", "self", ".", "_is_single_string_selector", "(", "selector", ",", "'name'", ")", ":", "# special-case optimization for by-name query", "return", "self", ".", "_all_models_by_name", ".", "get_all", "(", "selector", "[", "'name'", "]", ")", "else", ":", "return", "find", "(", "self", ".", "_all_models", ".", "values", "(", ")", ",", "selector", ")" ]
Query this document for objects that match the given selector. Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: seq[Model]
[ "Query", "this", "document", "for", "objects", "that", "match", "the", "given", "selector", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L781-L796
train
bokeh/bokeh
bokeh/document/document.py
Document.select_one
def select_one(self, selector): ''' Query this document for objects that match the given selector. Raises an error if more than one object is found. Returns single matching object, or None if nothing is found Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: Model or None ''' result = list(self.select(selector)) if len(result) > 1: raise ValueError("Found more than one model matching %s: %r" % (selector, result)) if len(result) == 0: return None return result[0]
python
def select_one(self, selector): ''' Query this document for objects that match the given selector. Raises an error if more than one object is found. Returns single matching object, or None if nothing is found Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: Model or None ''' result = list(self.select(selector)) if len(result) > 1: raise ValueError("Found more than one model matching %s: %r" % (selector, result)) if len(result) == 0: return None return result[0]
[ "def", "select_one", "(", "self", ",", "selector", ")", ":", "result", "=", "list", "(", "self", ".", "select", "(", "selector", ")", ")", "if", "len", "(", "result", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Found more than one model matching %s: %r\"", "%", "(", "selector", ",", "result", ")", ")", "if", "len", "(", "result", ")", "==", "0", ":", "return", "None", "return", "result", "[", "0", "]" ]
Query this document for objects that match the given selector. Raises an error if more than one object is found. Returns single matching object, or None if nothing is found Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: Model or None
[ "Query", "this", "document", "for", "objects", "that", "match", "the", "given", "selector", ".", "Raises", "an", "error", "if", "more", "than", "one", "object", "is", "found", ".", "Returns", "single", "matching", "object", "or", "None", "if", "nothing", "is", "found" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L798-L816
train
bokeh/bokeh
bokeh/document/document.py
Document.to_json_string
def to_json_string(self, indent=None): ''' Convert the document to a JSON string. Args: indent (int or None, optional) : number of spaces to indent, or None to suppress all newlines and indentation (default: None) Returns: str ''' root_ids = [] for r in self._roots: root_ids.append(r.id) root_references = self._all_models.values() json = { 'title' : self.title, 'roots' : { 'root_ids' : root_ids, 'references' : references_json(root_references) }, 'version' : __version__ } return serialize_json(json, indent=indent)
python
def to_json_string(self, indent=None): ''' Convert the document to a JSON string. Args: indent (int or None, optional) : number of spaces to indent, or None to suppress all newlines and indentation (default: None) Returns: str ''' root_ids = [] for r in self._roots: root_ids.append(r.id) root_references = self._all_models.values() json = { 'title' : self.title, 'roots' : { 'root_ids' : root_ids, 'references' : references_json(root_references) }, 'version' : __version__ } return serialize_json(json, indent=indent)
[ "def", "to_json_string", "(", "self", ",", "indent", "=", "None", ")", ":", "root_ids", "=", "[", "]", "for", "r", "in", "self", ".", "_roots", ":", "root_ids", ".", "append", "(", "r", ".", "id", ")", "root_references", "=", "self", ".", "_all_models", ".", "values", "(", ")", "json", "=", "{", "'title'", ":", "self", ".", "title", ",", "'roots'", ":", "{", "'root_ids'", ":", "root_ids", ",", "'references'", ":", "references_json", "(", "root_references", ")", "}", ",", "'version'", ":", "__version__", "}", "return", "serialize_json", "(", "json", ",", "indent", "=", "indent", ")" ]
Convert the document to a JSON string. Args: indent (int or None, optional) : number of spaces to indent, or None to suppress all newlines and indentation (default: None) Returns: str
[ "Convert", "the", "document", "to", "a", "JSON", "string", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L848-L874
train
bokeh/bokeh
bokeh/document/document.py
Document.validate
def validate(self): ''' Perform integrity checks on the modes in this document. Returns: None ''' for r in self.roots: refs = r.references() check_integrity(refs)
python
def validate(self): ''' Perform integrity checks on the modes in this document. Returns: None ''' for r in self.roots: refs = r.references() check_integrity(refs)
[ "def", "validate", "(", "self", ")", ":", "for", "r", "in", "self", ".", "roots", ":", "refs", "=", "r", ".", "references", "(", ")", "check_integrity", "(", "refs", ")" ]
Perform integrity checks on the modes in this document. Returns: None
[ "Perform", "integrity", "checks", "on", "the", "modes", "in", "this", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L876-L885
train
bokeh/bokeh
bokeh/document/document.py
Document._add_session_callback
def _add_session_callback(self, callback_obj, callback, one_shot, originator): ''' Internal implementation for adding session callbacks. Args: callback_obj (SessionCallback) : A session callback object that wraps a callable and is passed to ``trigger_on_change``. callback (callable) : A callable to execute when session events happen. one_shot (bool) : Whether the callback should immediately auto-remove itself after one execution. Returns: SessionCallback : passed in as ``callback_obj``. Raises: ValueError, if the callback has been previously added ''' if one_shot: @wraps(callback) def remove_then_invoke(*args, **kwargs): if callback_obj in self._session_callbacks: self._remove_session_callback(callback_obj, originator) return callback(*args, **kwargs) actual_callback = remove_then_invoke else: actual_callback = callback callback_obj._callback = self._wrap_with_self_as_curdoc(actual_callback) self._session_callbacks.add(callback_obj) self._callback_objs_by_callable[originator][callback].add(callback_obj) # emit event so the session is notified of the new callback self._trigger_on_change(SessionCallbackAdded(self, callback_obj)) return callback_obj
python
def _add_session_callback(self, callback_obj, callback, one_shot, originator): ''' Internal implementation for adding session callbacks. Args: callback_obj (SessionCallback) : A session callback object that wraps a callable and is passed to ``trigger_on_change``. callback (callable) : A callable to execute when session events happen. one_shot (bool) : Whether the callback should immediately auto-remove itself after one execution. Returns: SessionCallback : passed in as ``callback_obj``. Raises: ValueError, if the callback has been previously added ''' if one_shot: @wraps(callback) def remove_then_invoke(*args, **kwargs): if callback_obj in self._session_callbacks: self._remove_session_callback(callback_obj, originator) return callback(*args, **kwargs) actual_callback = remove_then_invoke else: actual_callback = callback callback_obj._callback = self._wrap_with_self_as_curdoc(actual_callback) self._session_callbacks.add(callback_obj) self._callback_objs_by_callable[originator][callback].add(callback_obj) # emit event so the session is notified of the new callback self._trigger_on_change(SessionCallbackAdded(self, callback_obj)) return callback_obj
[ "def", "_add_session_callback", "(", "self", ",", "callback_obj", ",", "callback", ",", "one_shot", ",", "originator", ")", ":", "if", "one_shot", ":", "@", "wraps", "(", "callback", ")", "def", "remove_then_invoke", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "callback_obj", "in", "self", ".", "_session_callbacks", ":", "self", ".", "_remove_session_callback", "(", "callback_obj", ",", "originator", ")", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "actual_callback", "=", "remove_then_invoke", "else", ":", "actual_callback", "=", "callback", "callback_obj", ".", "_callback", "=", "self", ".", "_wrap_with_self_as_curdoc", "(", "actual_callback", ")", "self", ".", "_session_callbacks", ".", "add", "(", "callback_obj", ")", "self", ".", "_callback_objs_by_callable", "[", "originator", "]", "[", "callback", "]", ".", "add", "(", "callback_obj", ")", "# emit event so the session is notified of the new callback", "self", ".", "_trigger_on_change", "(", "SessionCallbackAdded", "(", "self", ",", "callback_obj", ")", ")", "return", "callback_obj" ]
Internal implementation for adding session callbacks. Args: callback_obj (SessionCallback) : A session callback object that wraps a callable and is passed to ``trigger_on_change``. callback (callable) : A callable to execute when session events happen. one_shot (bool) : Whether the callback should immediately auto-remove itself after one execution. Returns: SessionCallback : passed in as ``callback_obj``. Raises: ValueError, if the callback has been previously added
[ "Internal", "implementation", "for", "adding", "session", "callbacks", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L889-L928
train
bokeh/bokeh
bokeh/document/document.py
Document._destructively_move
def _destructively_move(self, dest_doc): ''' Move all data in this doc to the dest_doc, leaving this doc empty. Args: dest_doc (Document) : The Bokeh document to populate with data from this one Returns: None ''' if dest_doc is self: raise RuntimeError("Attempted to overwrite a document with itself") dest_doc.clear() # we have to remove ALL roots before adding any # to the new doc or else models referenced from multiple # roots could be in both docs at once, which isn't allowed. roots = [] self._push_all_models_freeze() try: while self.roots: r = next(iter(self.roots)) self.remove_root(r) roots.append(r) finally: self._pop_all_models_freeze() for r in roots: if r.document is not None: raise RuntimeError("Somehow we didn't detach %r" % (r)) if len(self._all_models) != 0: raise RuntimeError("_all_models still had stuff in it: %r" % (self._all_models)) for r in roots: dest_doc.add_root(r) dest_doc.title = self.title
python
def _destructively_move(self, dest_doc): ''' Move all data in this doc to the dest_doc, leaving this doc empty. Args: dest_doc (Document) : The Bokeh document to populate with data from this one Returns: None ''' if dest_doc is self: raise RuntimeError("Attempted to overwrite a document with itself") dest_doc.clear() # we have to remove ALL roots before adding any # to the new doc or else models referenced from multiple # roots could be in both docs at once, which isn't allowed. roots = [] self._push_all_models_freeze() try: while self.roots: r = next(iter(self.roots)) self.remove_root(r) roots.append(r) finally: self._pop_all_models_freeze() for r in roots: if r.document is not None: raise RuntimeError("Somehow we didn't detach %r" % (r)) if len(self._all_models) != 0: raise RuntimeError("_all_models still had stuff in it: %r" % (self._all_models)) for r in roots: dest_doc.add_root(r) dest_doc.title = self.title
[ "def", "_destructively_move", "(", "self", ",", "dest_doc", ")", ":", "if", "dest_doc", "is", "self", ":", "raise", "RuntimeError", "(", "\"Attempted to overwrite a document with itself\"", ")", "dest_doc", ".", "clear", "(", ")", "# we have to remove ALL roots before adding any", "# to the new doc or else models referenced from multiple", "# roots could be in both docs at once, which isn't allowed.", "roots", "=", "[", "]", "self", ".", "_push_all_models_freeze", "(", ")", "try", ":", "while", "self", ".", "roots", ":", "r", "=", "next", "(", "iter", "(", "self", ".", "roots", ")", ")", "self", ".", "remove_root", "(", "r", ")", "roots", ".", "append", "(", "r", ")", "finally", ":", "self", ".", "_pop_all_models_freeze", "(", ")", "for", "r", "in", "roots", ":", "if", "r", ".", "document", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"Somehow we didn't detach %r\"", "%", "(", "r", ")", ")", "if", "len", "(", "self", ".", "_all_models", ")", "!=", "0", ":", "raise", "RuntimeError", "(", "\"_all_models still had stuff in it: %r\"", "%", "(", "self", ".", "_all_models", ")", ")", "for", "r", "in", "roots", ":", "dest_doc", ".", "add_root", "(", "r", ")", "dest_doc", ".", "title", "=", "self", ".", "title" ]
Move all data in this doc to the dest_doc, leaving this doc empty. Args: dest_doc (Document) : The Bokeh document to populate with data from this one Returns: None
[ "Move", "all", "data", "in", "this", "doc", "to", "the", "dest_doc", "leaving", "this", "doc", "empty", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L930-L966
train
bokeh/bokeh
bokeh/document/document.py
Document._notify_change
def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None): ''' Called by Model when it changes ''' # if name changes, update by-name index if attr == 'name': if old is not None: self._all_models_by_name.remove_value(old, model) if new is not None: self._all_models_by_name.add_value(new, model) if hint is None: serializable_new = model.lookup(attr).serializable_value(model) else: serializable_new = None event = ModelChangedEvent(self, model, attr, old, new, serializable_new, hint, setter, callback_invoker) self._trigger_on_change(event)
python
def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None): ''' Called by Model when it changes ''' # if name changes, update by-name index if attr == 'name': if old is not None: self._all_models_by_name.remove_value(old, model) if new is not None: self._all_models_by_name.add_value(new, model) if hint is None: serializable_new = model.lookup(attr).serializable_value(model) else: serializable_new = None event = ModelChangedEvent(self, model, attr, old, new, serializable_new, hint, setter, callback_invoker) self._trigger_on_change(event)
[ "def", "_notify_change", "(", "self", ",", "model", ",", "attr", ",", "old", ",", "new", ",", "hint", "=", "None", ",", "setter", "=", "None", ",", "callback_invoker", "=", "None", ")", ":", "# if name changes, update by-name index", "if", "attr", "==", "'name'", ":", "if", "old", "is", "not", "None", ":", "self", ".", "_all_models_by_name", ".", "remove_value", "(", "old", ",", "model", ")", "if", "new", "is", "not", "None", ":", "self", ".", "_all_models_by_name", ".", "add_value", "(", "new", ",", "model", ")", "if", "hint", "is", "None", ":", "serializable_new", "=", "model", ".", "lookup", "(", "attr", ")", ".", "serializable_value", "(", "model", ")", "else", ":", "serializable_new", "=", "None", "event", "=", "ModelChangedEvent", "(", "self", ",", "model", ",", "attr", ",", "old", ",", "new", ",", "serializable_new", ",", "hint", ",", "setter", ",", "callback_invoker", ")", "self", ".", "_trigger_on_change", "(", "event", ")" ]
Called by Model when it changes
[ "Called", "by", "Model", "when", "it", "changes" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L988-L1005
train
bokeh/bokeh
bokeh/document/document.py
Document._remove_session_callback
def _remove_session_callback(self, callback_obj, originator): ''' Remove a callback added earlier with ``add_periodic_callback``, ``add_timeout_callback``, or ``add_next_tick_callback``. Returns: None Raises: KeyError, if the callback was never added ''' try: callback_objs = [callback_obj] self._session_callbacks.remove(callback_obj) for cb, cb_objs in list(self._callback_objs_by_callable[originator].items()): try: cb_objs.remove(callback_obj) if not cb_objs: del self._callback_objs_by_callable[originator][cb] except KeyError: pass except KeyError: raise ValueError("callback already ran or was already removed, cannot be removed again") # emit event so the session is notified and can remove the callback for callback_obj in callback_objs: self._trigger_on_change(SessionCallbackRemoved(self, callback_obj))
python
def _remove_session_callback(self, callback_obj, originator): ''' Remove a callback added earlier with ``add_periodic_callback``, ``add_timeout_callback``, or ``add_next_tick_callback``. Returns: None Raises: KeyError, if the callback was never added ''' try: callback_objs = [callback_obj] self._session_callbacks.remove(callback_obj) for cb, cb_objs in list(self._callback_objs_by_callable[originator].items()): try: cb_objs.remove(callback_obj) if not cb_objs: del self._callback_objs_by_callable[originator][cb] except KeyError: pass except KeyError: raise ValueError("callback already ran or was already removed, cannot be removed again") # emit event so the session is notified and can remove the callback for callback_obj in callback_objs: self._trigger_on_change(SessionCallbackRemoved(self, callback_obj))
[ "def", "_remove_session_callback", "(", "self", ",", "callback_obj", ",", "originator", ")", ":", "try", ":", "callback_objs", "=", "[", "callback_obj", "]", "self", ".", "_session_callbacks", ".", "remove", "(", "callback_obj", ")", "for", "cb", ",", "cb_objs", "in", "list", "(", "self", ".", "_callback_objs_by_callable", "[", "originator", "]", ".", "items", "(", ")", ")", ":", "try", ":", "cb_objs", ".", "remove", "(", "callback_obj", ")", "if", "not", "cb_objs", ":", "del", "self", ".", "_callback_objs_by_callable", "[", "originator", "]", "[", "cb", "]", "except", "KeyError", ":", "pass", "except", "KeyError", ":", "raise", "ValueError", "(", "\"callback already ran or was already removed, cannot be removed again\"", ")", "# emit event so the session is notified and can remove the callback", "for", "callback_obj", "in", "callback_objs", ":", "self", ".", "_trigger_on_change", "(", "SessionCallbackRemoved", "(", "self", ",", "callback_obj", ")", ")" ]
Remove a callback added earlier with ``add_periodic_callback``, ``add_timeout_callback``, or ``add_next_tick_callback``. Returns: None Raises: KeyError, if the callback was never added
[ "Remove", "a", "callback", "added", "earlier", "with", "add_periodic_callback", "add_timeout_callback", "or", "add_next_tick_callback", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L1046-L1071
train
bokeh/bokeh
bokeh/util/callback_manager.py
_check_callback
def _check_callback(callback, fargs, what="Callback functions"): '''Bokeh-internal function to check callback signature''' sig = signature(callback) formatted_args = format_signature(sig) error_msg = what + " must have signature func(%s), got func%s" all_names, default_values = get_param_info(sig) nargs = len(all_names) - len(default_values) if nargs != len(fargs): raise ValueError(error_msg % (", ".join(fargs), formatted_args))
python
def _check_callback(callback, fargs, what="Callback functions"): '''Bokeh-internal function to check callback signature''' sig = signature(callback) formatted_args = format_signature(sig) error_msg = what + " must have signature func(%s), got func%s" all_names, default_values = get_param_info(sig) nargs = len(all_names) - len(default_values) if nargs != len(fargs): raise ValueError(error_msg % (", ".join(fargs), formatted_args))
[ "def", "_check_callback", "(", "callback", ",", "fargs", ",", "what", "=", "\"Callback functions\"", ")", ":", "sig", "=", "signature", "(", "callback", ")", "formatted_args", "=", "format_signature", "(", "sig", ")", "error_msg", "=", "what", "+", "\" must have signature func(%s), got func%s\"", "all_names", ",", "default_values", "=", "get_param_info", "(", "sig", ")", "nargs", "=", "len", "(", "all_names", ")", "-", "len", "(", "default_values", ")", "if", "nargs", "!=", "len", "(", "fargs", ")", ":", "raise", "ValueError", "(", "error_msg", "%", "(", "\", \"", ".", "join", "(", "fargs", ")", ",", "formatted_args", ")", ")" ]
Bokeh-internal function to check callback signature
[ "Bokeh", "-", "internal", "function", "to", "check", "callback", "signature" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/callback_manager.py#L178-L188
train
bokeh/bokeh
bokeh/util/callback_manager.py
PropertyCallbackManager.on_change
def on_change(self, attr, *callbacks): ''' Add a callback on this object to trigger when ``attr`` changes. Args: attr (str) : an attribute name on this object callback (callable) : a callback function to register Returns: None ''' if len(callbacks) == 0: raise ValueError("on_change takes an attribute name and one or more callbacks, got only one parameter") _callbacks = self._callbacks.setdefault(attr, []) for callback in callbacks: if callback in _callbacks: continue _check_callback(callback, ('attr', 'old', 'new')) _callbacks.append(callback)
python
def on_change(self, attr, *callbacks): ''' Add a callback on this object to trigger when ``attr`` changes. Args: attr (str) : an attribute name on this object callback (callable) : a callback function to register Returns: None ''' if len(callbacks) == 0: raise ValueError("on_change takes an attribute name and one or more callbacks, got only one parameter") _callbacks = self._callbacks.setdefault(attr, []) for callback in callbacks: if callback in _callbacks: continue _check_callback(callback, ('attr', 'old', 'new')) _callbacks.append(callback)
[ "def", "on_change", "(", "self", ",", "attr", ",", "*", "callbacks", ")", ":", "if", "len", "(", "callbacks", ")", "==", "0", ":", "raise", "ValueError", "(", "\"on_change takes an attribute name and one or more callbacks, got only one parameter\"", ")", "_callbacks", "=", "self", ".", "_callbacks", ".", "setdefault", "(", "attr", ",", "[", "]", ")", "for", "callback", "in", "callbacks", ":", "if", "callback", "in", "_callbacks", ":", "continue", "_check_callback", "(", "callback", ",", "(", "'attr'", ",", "'old'", ",", "'new'", ")", ")", "_callbacks", ".", "append", "(", "callback", ")" ]
Add a callback on this object to trigger when ``attr`` changes. Args: attr (str) : an attribute name on this object callback (callable) : a callback function to register Returns: None
[ "Add", "a", "callback", "on", "this", "object", "to", "trigger", "when", "attr", "changes", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/callback_manager.py#L111-L133
train
bokeh/bokeh
bokeh/util/callback_manager.py
PropertyCallbackManager.remove_on_change
def remove_on_change(self, attr, *callbacks): ''' Remove a callback from this object ''' if len(callbacks) == 0: raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter") _callbacks = self._callbacks.setdefault(attr, []) for callback in callbacks: _callbacks.remove(callback)
python
def remove_on_change(self, attr, *callbacks): ''' Remove a callback from this object ''' if len(callbacks) == 0: raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter") _callbacks = self._callbacks.setdefault(attr, []) for callback in callbacks: _callbacks.remove(callback)
[ "def", "remove_on_change", "(", "self", ",", "attr", ",", "*", "callbacks", ")", ":", "if", "len", "(", "callbacks", ")", "==", "0", ":", "raise", "ValueError", "(", "\"remove_on_change takes an attribute name and one or more callbacks, got only one parameter\"", ")", "_callbacks", "=", "self", ".", "_callbacks", ".", "setdefault", "(", "attr", ",", "[", "]", ")", "for", "callback", "in", "callbacks", ":", "_callbacks", ".", "remove", "(", "callback", ")" ]
Remove a callback from this object
[ "Remove", "a", "callback", "from", "this", "object" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/callback_manager.py#L135-L141
train
bokeh/bokeh
bokeh/util/callback_manager.py
PropertyCallbackManager.trigger
def trigger(self, attr, old, new, hint=None, setter=None): ''' Trigger callbacks for ``attr`` on this object. Args: attr (str) : old (object) : new (object) : Returns: None ''' def invoke(): callbacks = self._callbacks.get(attr) if callbacks: for callback in callbacks: callback(attr, old, new) if hasattr(self, '_document') and self._document is not None: self._document._notify_change(self, attr, old, new, hint, setter, invoke) else: invoke()
python
def trigger(self, attr, old, new, hint=None, setter=None): ''' Trigger callbacks for ``attr`` on this object. Args: attr (str) : old (object) : new (object) : Returns: None ''' def invoke(): callbacks = self._callbacks.get(attr) if callbacks: for callback in callbacks: callback(attr, old, new) if hasattr(self, '_document') and self._document is not None: self._document._notify_change(self, attr, old, new, hint, setter, invoke) else: invoke()
[ "def", "trigger", "(", "self", ",", "attr", ",", "old", ",", "new", ",", "hint", "=", "None", ",", "setter", "=", "None", ")", ":", "def", "invoke", "(", ")", ":", "callbacks", "=", "self", ".", "_callbacks", ".", "get", "(", "attr", ")", "if", "callbacks", ":", "for", "callback", "in", "callbacks", ":", "callback", "(", "attr", ",", "old", ",", "new", ")", "if", "hasattr", "(", "self", ",", "'_document'", ")", "and", "self", ".", "_document", "is", "not", "None", ":", "self", ".", "_document", ".", "_notify_change", "(", "self", ",", "attr", ",", "old", ",", "new", ",", "hint", ",", "setter", ",", "invoke", ")", "else", ":", "invoke", "(", ")" ]
Trigger callbacks for ``attr`` on this object. Args: attr (str) : old (object) : new (object) : Returns: None
[ "Trigger", "callbacks", "for", "attr", "on", "this", "object", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/callback_manager.py#L143-L163
train
bokeh/bokeh
bokeh/util/sampledata.py
download
def download(progress=True): ''' Download larger data sets for various Bokeh examples. ''' data_dir = external_data_dir(create=True) print("Using data directory: %s" % data_dir) s3 = 'https://bokeh-sampledata.s3.amazonaws.com' files = [ (s3, 'CGM.csv'), (s3, 'US_Counties.zip'), (s3, 'us_cities.json'), (s3, 'unemployment09.csv'), (s3, 'AAPL.csv'), (s3, 'FB.csv'), (s3, 'GOOG.csv'), (s3, 'IBM.csv'), (s3, 'MSFT.csv'), (s3, 'WPP2012_SA_DB03_POPULATION_QUINQUENNIAL.zip'), (s3, 'gapminder_fertility.csv'), (s3, 'gapminder_population.csv'), (s3, 'gapminder_life_expectancy.csv'), (s3, 'gapminder_regions.csv'), (s3, 'world_cities.zip'), (s3, 'airports.json'), (s3, 'movies.db.zip'), (s3, 'airports.csv'), (s3, 'routes.csv'), (s3, 'haarcascade_frontalface_default.xml'), ] for base_url, filename in files: _download_file(base_url, filename, data_dir, progress=progress)
python
def download(progress=True): ''' Download larger data sets for various Bokeh examples. ''' data_dir = external_data_dir(create=True) print("Using data directory: %s" % data_dir) s3 = 'https://bokeh-sampledata.s3.amazonaws.com' files = [ (s3, 'CGM.csv'), (s3, 'US_Counties.zip'), (s3, 'us_cities.json'), (s3, 'unemployment09.csv'), (s3, 'AAPL.csv'), (s3, 'FB.csv'), (s3, 'GOOG.csv'), (s3, 'IBM.csv'), (s3, 'MSFT.csv'), (s3, 'WPP2012_SA_DB03_POPULATION_QUINQUENNIAL.zip'), (s3, 'gapminder_fertility.csv'), (s3, 'gapminder_population.csv'), (s3, 'gapminder_life_expectancy.csv'), (s3, 'gapminder_regions.csv'), (s3, 'world_cities.zip'), (s3, 'airports.json'), (s3, 'movies.db.zip'), (s3, 'airports.csv'), (s3, 'routes.csv'), (s3, 'haarcascade_frontalface_default.xml'), ] for base_url, filename in files: _download_file(base_url, filename, data_dir, progress=progress)
[ "def", "download", "(", "progress", "=", "True", ")", ":", "data_dir", "=", "external_data_dir", "(", "create", "=", "True", ")", "print", "(", "\"Using data directory: %s\"", "%", "data_dir", ")", "s3", "=", "'https://bokeh-sampledata.s3.amazonaws.com'", "files", "=", "[", "(", "s3", ",", "'CGM.csv'", ")", ",", "(", "s3", ",", "'US_Counties.zip'", ")", ",", "(", "s3", ",", "'us_cities.json'", ")", ",", "(", "s3", ",", "'unemployment09.csv'", ")", ",", "(", "s3", ",", "'AAPL.csv'", ")", ",", "(", "s3", ",", "'FB.csv'", ")", ",", "(", "s3", ",", "'GOOG.csv'", ")", ",", "(", "s3", ",", "'IBM.csv'", ")", ",", "(", "s3", ",", "'MSFT.csv'", ")", ",", "(", "s3", ",", "'WPP2012_SA_DB03_POPULATION_QUINQUENNIAL.zip'", ")", ",", "(", "s3", ",", "'gapminder_fertility.csv'", ")", ",", "(", "s3", ",", "'gapminder_population.csv'", ")", ",", "(", "s3", ",", "'gapminder_life_expectancy.csv'", ")", ",", "(", "s3", ",", "'gapminder_regions.csv'", ")", ",", "(", "s3", ",", "'world_cities.zip'", ")", ",", "(", "s3", ",", "'airports.json'", ")", ",", "(", "s3", ",", "'movies.db.zip'", ")", ",", "(", "s3", ",", "'airports.csv'", ")", ",", "(", "s3", ",", "'routes.csv'", ")", ",", "(", "s3", ",", "'haarcascade_frontalface_default.xml'", ")", ",", "]", "for", "base_url", ",", "filename", "in", "files", ":", "_download_file", "(", "base_url", ",", "filename", ",", "data_dir", ",", "progress", "=", "progress", ")" ]
Download larger data sets for various Bokeh examples.
[ "Download", "larger", "data", "sets", "for", "various", "Bokeh", "examples", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/sampledata.py#L49-L81
train
bokeh/bokeh
bokeh/command/bootstrap.py
main
def main(argv): ''' Execute the Bokeh command. Args: argv (seq[str]) : a list of command line arguments to process Returns: None The first item in ``argv`` is typically "bokeh", and the second should be the name of one of the available subcommands: * :ref:`html <bokeh.command.subcommands.html>` * :ref:`info <bokeh.command.subcommands.info>` * :ref:`json <bokeh.command.subcommands.json>` * :ref:`png <bokeh.command.subcommands.png>` * :ref:`sampledata <bokeh.command.subcommands.sampledata>` * :ref:`secret <bokeh.command.subcommands.secret>` * :ref:`serve <bokeh.command.subcommands.serve>` * :ref:`static <bokeh.command.subcommands.static>` * :ref:`svg <bokeh.command.subcommands.svg>` ''' if len(argv) == 1: die("ERROR: Must specify subcommand, one of: %s" % nice_join(x.name for x in subcommands.all)) parser = argparse.ArgumentParser( prog=argv[0], epilog="See '<command> --help' to read about a specific subcommand.") # we don't use settings.version() because the point of this option # is to report the actual version of Bokeh, while settings.version() # lets people change the version used for CDN for example. parser.add_argument('-v', '--version', action='version', version=__version__) subs = parser.add_subparsers(help="Sub-commands") for cls in subcommands.all: subparser = subs.add_parser(cls.name, help=cls.help) subcommand = cls(parser=subparser) subparser.set_defaults(invoke=subcommand.invoke) args = parser.parse_args(argv[1:]) try: args.invoke(args) except Exception as e: die("ERROR: " + str(e))
python
def main(argv): ''' Execute the Bokeh command. Args: argv (seq[str]) : a list of command line arguments to process Returns: None The first item in ``argv`` is typically "bokeh", and the second should be the name of one of the available subcommands: * :ref:`html <bokeh.command.subcommands.html>` * :ref:`info <bokeh.command.subcommands.info>` * :ref:`json <bokeh.command.subcommands.json>` * :ref:`png <bokeh.command.subcommands.png>` * :ref:`sampledata <bokeh.command.subcommands.sampledata>` * :ref:`secret <bokeh.command.subcommands.secret>` * :ref:`serve <bokeh.command.subcommands.serve>` * :ref:`static <bokeh.command.subcommands.static>` * :ref:`svg <bokeh.command.subcommands.svg>` ''' if len(argv) == 1: die("ERROR: Must specify subcommand, one of: %s" % nice_join(x.name for x in subcommands.all)) parser = argparse.ArgumentParser( prog=argv[0], epilog="See '<command> --help' to read about a specific subcommand.") # we don't use settings.version() because the point of this option # is to report the actual version of Bokeh, while settings.version() # lets people change the version used for CDN for example. parser.add_argument('-v', '--version', action='version', version=__version__) subs = parser.add_subparsers(help="Sub-commands") for cls in subcommands.all: subparser = subs.add_parser(cls.name, help=cls.help) subcommand = cls(parser=subparser) subparser.set_defaults(invoke=subcommand.invoke) args = parser.parse_args(argv[1:]) try: args.invoke(args) except Exception as e: die("ERROR: " + str(e))
[ "def", "main", "(", "argv", ")", ":", "if", "len", "(", "argv", ")", "==", "1", ":", "die", "(", "\"ERROR: Must specify subcommand, one of: %s\"", "%", "nice_join", "(", "x", ".", "name", "for", "x", "in", "subcommands", ".", "all", ")", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "argv", "[", "0", "]", ",", "epilog", "=", "\"See '<command> --help' to read about a specific subcommand.\"", ")", "# we don't use settings.version() because the point of this option", "# is to report the actual version of Bokeh, while settings.version()", "# lets people change the version used for CDN for example.", "parser", ".", "add_argument", "(", "'-v'", ",", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "__version__", ")", "subs", "=", "parser", ".", "add_subparsers", "(", "help", "=", "\"Sub-commands\"", ")", "for", "cls", "in", "subcommands", ".", "all", ":", "subparser", "=", "subs", ".", "add_parser", "(", "cls", ".", "name", ",", "help", "=", "cls", ".", "help", ")", "subcommand", "=", "cls", "(", "parser", "=", "subparser", ")", "subparser", ".", "set_defaults", "(", "invoke", "=", "subcommand", ".", "invoke", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", "[", "1", ":", "]", ")", "try", ":", "args", ".", "invoke", "(", "args", ")", "except", "Exception", "as", "e", ":", "die", "(", "\"ERROR: \"", "+", "str", "(", "e", ")", ")" ]
Execute the Bokeh command. Args: argv (seq[str]) : a list of command line arguments to process Returns: None The first item in ``argv`` is typically "bokeh", and the second should be the name of one of the available subcommands: * :ref:`html <bokeh.command.subcommands.html>` * :ref:`info <bokeh.command.subcommands.info>` * :ref:`json <bokeh.command.subcommands.json>` * :ref:`png <bokeh.command.subcommands.png>` * :ref:`sampledata <bokeh.command.subcommands.sampledata>` * :ref:`secret <bokeh.command.subcommands.secret>` * :ref:`serve <bokeh.command.subcommands.serve>` * :ref:`static <bokeh.command.subcommands.static>` * :ref:`svg <bokeh.command.subcommands.svg>`
[ "Execute", "the", "Bokeh", "command", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/bootstrap.py#L69-L115
train
bokeh/bokeh
bokeh/io/showing.py
show
def show(obj, browser=None, new="tab", notebook_handle=False, notebook_url="localhost:8888", **kw): ''' Immediately display a Bokeh object or application. :func:`show` may be called multiple times in a single Jupyter notebook cell to display multiple objects. The objects are displayed in order. Args: obj (LayoutDOM or Application or callable) : A Bokeh object to display. Bokeh plots, widgets, layouts (i.e. rows and columns) may be passed to ``show`` in order to display them. When ``output_file`` has been called, the output will be to an HTML file, which is also opened in a new browser window or tab. When ``output_notebook`` has been called in a Jupyter notebook, the output will be inline in the associated notebook output cell. In a Jupyter notebook, a Bokeh application or callable may also be passed. A callable will be turned into an Application using a ``FunctionHandler``. The application will be run and displayed inline in the associated notebook output cell. browser (str, optional) : Specify the browser to use to open output files(default: None) For file output, the **browser** argument allows for specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". Not all platforms may support this option, see the documentation for the standard library webbrowser_ module for more information new (str, optional) : Specify the browser mode to use for output files (default: "tab") For file 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. notebook_handle (bool, optional) : Whether to create a notebook interaction handle (default: False) For notebook output, toggles whether a handle which can be used with ``push_notebook`` is returned. Note that notebook handles only apply to standalone plots, layouts, etc. They do not apply when showing Applications in the notebook. notebook_url (URL, optional) : Location of the Jupyter notebook page (default: "localhost:8888") When showing Bokeh applications, the Bokeh server must be explicitly configured to allow connections originating from different URLs. This parameter defaults to the standard notebook host and port. If you are running on a different location, you will need to supply this value for the application to display properly. If no protocol is supplied in the URL, e.g. if it is of the form "localhost:8888", then "http" will be used. ``notebook_url`` can also be a function that takes one int for the bound server port. If the port is provided, the function needs to generate the full public URL to the bokeh server. If None is passed, the function is to generate the origin URL. Some parameters are only useful when certain output modes are active: * The ``browser`` and ``new`` parameters only apply when ``output_file`` is active. * The ``notebook_handle`` parameter only applies when ``output_notebook`` is active, and non-Application objects are being shown. It is only supported to Jupyter notebook, raise exception for other notebook types when it is True. * The ``notebook_url`` parameter only applies when showing Bokeh Applications in a Jupyter notebook. * Any additional keyword arguments are passed to :class:`~bokeh.server.Server` when showing a Bokeh app (added in version 1.1) Returns: When in a Jupyter notebook (with ``output_notebook`` enabled) and ``notebook_handle=True``, returns a handle that can be used by ``push_notebook``, None otherwise. .. _webbrowser: https://docs.python.org/2/library/webbrowser.html ''' state = curstate() is_application = getattr(obj, '_is_a_bokeh_application_class', False) if not (isinstance(obj, LayoutDOM) or is_application or callable(obj)): raise ValueError(_BAD_SHOW_MSG) # TODO (bev) check callable signature more thoroughly # This ugliness is to prevent importing bokeh.application (which would bring # in Tornado) just in order to show a non-server object if is_application or callable(obj): return run_notebook_hook(state.notebook_type, 'app', obj, state, notebook_url, **kw) return _show_with_state(obj, state, browser, new, notebook_handle=notebook_handle)
python
def show(obj, browser=None, new="tab", notebook_handle=False, notebook_url="localhost:8888", **kw): ''' Immediately display a Bokeh object or application. :func:`show` may be called multiple times in a single Jupyter notebook cell to display multiple objects. The objects are displayed in order. Args: obj (LayoutDOM or Application or callable) : A Bokeh object to display. Bokeh plots, widgets, layouts (i.e. rows and columns) may be passed to ``show`` in order to display them. When ``output_file`` has been called, the output will be to an HTML file, which is also opened in a new browser window or tab. When ``output_notebook`` has been called in a Jupyter notebook, the output will be inline in the associated notebook output cell. In a Jupyter notebook, a Bokeh application or callable may also be passed. A callable will be turned into an Application using a ``FunctionHandler``. The application will be run and displayed inline in the associated notebook output cell. browser (str, optional) : Specify the browser to use to open output files(default: None) For file output, the **browser** argument allows for specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". Not all platforms may support this option, see the documentation for the standard library webbrowser_ module for more information new (str, optional) : Specify the browser mode to use for output files (default: "tab") For file 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. notebook_handle (bool, optional) : Whether to create a notebook interaction handle (default: False) For notebook output, toggles whether a handle which can be used with ``push_notebook`` is returned. Note that notebook handles only apply to standalone plots, layouts, etc. They do not apply when showing Applications in the notebook. notebook_url (URL, optional) : Location of the Jupyter notebook page (default: "localhost:8888") When showing Bokeh applications, the Bokeh server must be explicitly configured to allow connections originating from different URLs. This parameter defaults to the standard notebook host and port. If you are running on a different location, you will need to supply this value for the application to display properly. If no protocol is supplied in the URL, e.g. if it is of the form "localhost:8888", then "http" will be used. ``notebook_url`` can also be a function that takes one int for the bound server port. If the port is provided, the function needs to generate the full public URL to the bokeh server. If None is passed, the function is to generate the origin URL. Some parameters are only useful when certain output modes are active: * The ``browser`` and ``new`` parameters only apply when ``output_file`` is active. * The ``notebook_handle`` parameter only applies when ``output_notebook`` is active, and non-Application objects are being shown. It is only supported to Jupyter notebook, raise exception for other notebook types when it is True. * The ``notebook_url`` parameter only applies when showing Bokeh Applications in a Jupyter notebook. * Any additional keyword arguments are passed to :class:`~bokeh.server.Server` when showing a Bokeh app (added in version 1.1) Returns: When in a Jupyter notebook (with ``output_notebook`` enabled) and ``notebook_handle=True``, returns a handle that can be used by ``push_notebook``, None otherwise. .. _webbrowser: https://docs.python.org/2/library/webbrowser.html ''' state = curstate() is_application = getattr(obj, '_is_a_bokeh_application_class', False) if not (isinstance(obj, LayoutDOM) or is_application or callable(obj)): raise ValueError(_BAD_SHOW_MSG) # TODO (bev) check callable signature more thoroughly # This ugliness is to prevent importing bokeh.application (which would bring # in Tornado) just in order to show a non-server object if is_application or callable(obj): return run_notebook_hook(state.notebook_type, 'app', obj, state, notebook_url, **kw) return _show_with_state(obj, state, browser, new, notebook_handle=notebook_handle)
[ "def", "show", "(", "obj", ",", "browser", "=", "None", ",", "new", "=", "\"tab\"", ",", "notebook_handle", "=", "False", ",", "notebook_url", "=", "\"localhost:8888\"", ",", "*", "*", "kw", ")", ":", "state", "=", "curstate", "(", ")", "is_application", "=", "getattr", "(", "obj", ",", "'_is_a_bokeh_application_class'", ",", "False", ")", "if", "not", "(", "isinstance", "(", "obj", ",", "LayoutDOM", ")", "or", "is_application", "or", "callable", "(", "obj", ")", ")", ":", "raise", "ValueError", "(", "_BAD_SHOW_MSG", ")", "# TODO (bev) check callable signature more thoroughly", "# This ugliness is to prevent importing bokeh.application (which would bring", "# in Tornado) just in order to show a non-server object", "if", "is_application", "or", "callable", "(", "obj", ")", ":", "return", "run_notebook_hook", "(", "state", ".", "notebook_type", ",", "'app'", ",", "obj", ",", "state", ",", "notebook_url", ",", "*", "*", "kw", ")", "return", "_show_with_state", "(", "obj", ",", "state", ",", "browser", ",", "new", ",", "notebook_handle", "=", "notebook_handle", ")" ]
Immediately display a Bokeh object or application. :func:`show` may be called multiple times in a single Jupyter notebook cell to display multiple objects. The objects are displayed in order. Args: obj (LayoutDOM or Application or callable) : A Bokeh object to display. Bokeh plots, widgets, layouts (i.e. rows and columns) may be passed to ``show`` in order to display them. When ``output_file`` has been called, the output will be to an HTML file, which is also opened in a new browser window or tab. When ``output_notebook`` has been called in a Jupyter notebook, the output will be inline in the associated notebook output cell. In a Jupyter notebook, a Bokeh application or callable may also be passed. A callable will be turned into an Application using a ``FunctionHandler``. The application will be run and displayed inline in the associated notebook output cell. browser (str, optional) : Specify the browser to use to open output files(default: None) For file output, the **browser** argument allows for specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". Not all platforms may support this option, see the documentation for the standard library webbrowser_ module for more information new (str, optional) : Specify the browser mode to use for output files (default: "tab") For file 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. notebook_handle (bool, optional) : Whether to create a notebook interaction handle (default: False) For notebook output, toggles whether a handle which can be used with ``push_notebook`` is returned. Note that notebook handles only apply to standalone plots, layouts, etc. They do not apply when showing Applications in the notebook. notebook_url (URL, optional) : Location of the Jupyter notebook page (default: "localhost:8888") When showing Bokeh applications, the Bokeh server must be explicitly configured to allow connections originating from different URLs. This parameter defaults to the standard notebook host and port. If you are running on a different location, you will need to supply this value for the application to display properly. If no protocol is supplied in the URL, e.g. if it is of the form "localhost:8888", then "http" will be used. ``notebook_url`` can also be a function that takes one int for the bound server port. If the port is provided, the function needs to generate the full public URL to the bokeh server. If None is passed, the function is to generate the origin URL. Some parameters are only useful when certain output modes are active: * The ``browser`` and ``new`` parameters only apply when ``output_file`` is active. * The ``notebook_handle`` parameter only applies when ``output_notebook`` is active, and non-Application objects are being shown. It is only supported to Jupyter notebook, raise exception for other notebook types when it is True. * The ``notebook_url`` parameter only applies when showing Bokeh Applications in a Jupyter notebook. * Any additional keyword arguments are passed to :class:`~bokeh.server.Server` when showing a Bokeh app (added in version 1.1) Returns: When in a Jupyter notebook (with ``output_notebook`` enabled) and ``notebook_handle=True``, returns a handle that can be used by ``push_notebook``, None otherwise. .. _webbrowser: https://docs.python.org/2/library/webbrowser.html
[ "Immediately", "display", "a", "Bokeh", "object", "or", "application", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/showing.py#L46-L145
train
bokeh/bokeh
bokeh/embed/elements.py
html_page_for_render_items
def html_page_for_render_items(bundle, docs_json, render_items, title, template=None, template_variables={}): ''' Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str ''' if title is None: title = DEFAULT_TITLE bokeh_js, bokeh_css = bundle json_id = make_id() json = escape(serialize_json(docs_json), quote=False) json = wrap_in_script_tag(json, "application/json", json_id) script = wrap_in_script_tag(script_for_render_items(json_id, render_items)) context = template_variables.copy() context.update(dict( title = title, bokeh_js = bokeh_js, bokeh_css = bokeh_css, plot_script = json + script, docs = render_items, base = FILE, macros = MACROS, )) if len(render_items) == 1: context["doc"] = context["docs"][0] context["roots"] = context["doc"].roots # XXX: backwards compatibility, remove for 1.0 context["plot_div"] = "\n".join(div_for_render_item(item) for item in render_items) if template is None: template = FILE elif isinstance(template, string_types): template = _env.from_string("{% extends base %}\n" + template) html = template.render(context) return encode_utf8(html)
python
def html_page_for_render_items(bundle, docs_json, render_items, title, template=None, template_variables={}): ''' Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str ''' if title is None: title = DEFAULT_TITLE bokeh_js, bokeh_css = bundle json_id = make_id() json = escape(serialize_json(docs_json), quote=False) json = wrap_in_script_tag(json, "application/json", json_id) script = wrap_in_script_tag(script_for_render_items(json_id, render_items)) context = template_variables.copy() context.update(dict( title = title, bokeh_js = bokeh_js, bokeh_css = bokeh_css, plot_script = json + script, docs = render_items, base = FILE, macros = MACROS, )) if len(render_items) == 1: context["doc"] = context["docs"][0] context["roots"] = context["doc"].roots # XXX: backwards compatibility, remove for 1.0 context["plot_div"] = "\n".join(div_for_render_item(item) for item in render_items) if template is None: template = FILE elif isinstance(template, string_types): template = _env.from_string("{% extends base %}\n" + template) html = template.render(context) return encode_utf8(html)
[ "def", "html_page_for_render_items", "(", "bundle", ",", "docs_json", ",", "render_items", ",", "title", ",", "template", "=", "None", ",", "template_variables", "=", "{", "}", ")", ":", "if", "title", "is", "None", ":", "title", "=", "DEFAULT_TITLE", "bokeh_js", ",", "bokeh_css", "=", "bundle", "json_id", "=", "make_id", "(", ")", "json", "=", "escape", "(", "serialize_json", "(", "docs_json", ")", ",", "quote", "=", "False", ")", "json", "=", "wrap_in_script_tag", "(", "json", ",", "\"application/json\"", ",", "json_id", ")", "script", "=", "wrap_in_script_tag", "(", "script_for_render_items", "(", "json_id", ",", "render_items", ")", ")", "context", "=", "template_variables", ".", "copy", "(", ")", "context", ".", "update", "(", "dict", "(", "title", "=", "title", ",", "bokeh_js", "=", "bokeh_js", ",", "bokeh_css", "=", "bokeh_css", ",", "plot_script", "=", "json", "+", "script", ",", "docs", "=", "render_items", ",", "base", "=", "FILE", ",", "macros", "=", "MACROS", ",", ")", ")", "if", "len", "(", "render_items", ")", "==", "1", ":", "context", "[", "\"doc\"", "]", "=", "context", "[", "\"docs\"", "]", "[", "0", "]", "context", "[", "\"roots\"", "]", "=", "context", "[", "\"doc\"", "]", ".", "roots", "# XXX: backwards compatibility, remove for 1.0", "context", "[", "\"plot_div\"", "]", "=", "\"\\n\"", ".", "join", "(", "div_for_render_item", "(", "item", ")", "for", "item", "in", "render_items", ")", "if", "template", "is", "None", ":", "template", "=", "FILE", "elif", "isinstance", "(", "template", ",", "string_types", ")", ":", "template", "=", "_env", ".", "from_string", "(", "\"{% extends base %}\\n\"", "+", "template", ")", "html", "=", "template", ".", "render", "(", "context", ")", "return", "encode_utf8", "(", "html", ")" ]
Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str
[ "Render", "an", "HTML", "page", "from", "a", "template", "and", "Bokeh", "render", "items", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/elements.py#L68-L130
train
bokeh/bokeh
examples/app/stocks/download_sample_data.py
extract_hosted_zip
def extract_hosted_zip(data_url, save_dir, exclude_term=None): """Downloads, then extracts a zip file.""" zip_name = os.path.join(save_dir, 'temp.zip') # get the zip file try: print('Downloading %r to %r' % (data_url, zip_name)) zip_name, hdrs = urllib.request.urlretrieve(url=data_url, filename=zip_name) print('Download successfully completed') except IOError as e: print("Could not successfully retrieve %r" % data_url) raise e # extract, then remove temp file extract_zip(zip_name=zip_name, exclude_term=exclude_term) os.unlink(zip_name) print("Extraction Complete")
python
def extract_hosted_zip(data_url, save_dir, exclude_term=None): """Downloads, then extracts a zip file.""" zip_name = os.path.join(save_dir, 'temp.zip') # get the zip file try: print('Downloading %r to %r' % (data_url, zip_name)) zip_name, hdrs = urllib.request.urlretrieve(url=data_url, filename=zip_name) print('Download successfully completed') except IOError as e: print("Could not successfully retrieve %r" % data_url) raise e # extract, then remove temp file extract_zip(zip_name=zip_name, exclude_term=exclude_term) os.unlink(zip_name) print("Extraction Complete")
[ "def", "extract_hosted_zip", "(", "data_url", ",", "save_dir", ",", "exclude_term", "=", "None", ")", ":", "zip_name", "=", "os", ".", "path", ".", "join", "(", "save_dir", ",", "'temp.zip'", ")", "# get the zip file", "try", ":", "print", "(", "'Downloading %r to %r'", "%", "(", "data_url", ",", "zip_name", ")", ")", "zip_name", ",", "hdrs", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "url", "=", "data_url", ",", "filename", "=", "zip_name", ")", "print", "(", "'Download successfully completed'", ")", "except", "IOError", "as", "e", ":", "print", "(", "\"Could not successfully retrieve %r\"", "%", "data_url", ")", "raise", "e", "# extract, then remove temp file", "extract_zip", "(", "zip_name", "=", "zip_name", ",", "exclude_term", "=", "exclude_term", ")", "os", ".", "unlink", "(", "zip_name", ")", "print", "(", "\"Extraction Complete\"", ")" ]
Downloads, then extracts a zip file.
[ "Downloads", "then", "extracts", "a", "zip", "file", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/app/stocks/download_sample_data.py#L7-L24
train
bokeh/bokeh
examples/app/stocks/download_sample_data.py
extract_zip
def extract_zip(zip_name, exclude_term=None): """Extracts a zip file to its containing directory.""" zip_dir = os.path.dirname(os.path.abspath(zip_name)) try: with zipfile.ZipFile(zip_name) as z: # write each zipped file out if it isn't a directory files = [zip_file for zip_file in z.namelist() if not zip_file.endswith('/')] print('Extracting %i files from %r.' % (len(files), zip_name)) for zip_file in files: # remove any provided extra directory term from zip file if exclude_term: dest_file = zip_file.replace(exclude_term, '') else: dest_file = zip_file dest_file = os.path.normpath(os.path.join(zip_dir, dest_file)) dest_dir = os.path.dirname(dest_file) # make directory if it does not exist if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # read file from zip, then write to new directory data = z.read(zip_file) with open(dest_file, 'wb') as f: f.write(encode_utf8(data)) except zipfile.error as e: print("Bad zipfile (%r): %s" % (zip_name, e)) raise e
python
def extract_zip(zip_name, exclude_term=None): """Extracts a zip file to its containing directory.""" zip_dir = os.path.dirname(os.path.abspath(zip_name)) try: with zipfile.ZipFile(zip_name) as z: # write each zipped file out if it isn't a directory files = [zip_file for zip_file in z.namelist() if not zip_file.endswith('/')] print('Extracting %i files from %r.' % (len(files), zip_name)) for zip_file in files: # remove any provided extra directory term from zip file if exclude_term: dest_file = zip_file.replace(exclude_term, '') else: dest_file = zip_file dest_file = os.path.normpath(os.path.join(zip_dir, dest_file)) dest_dir = os.path.dirname(dest_file) # make directory if it does not exist if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # read file from zip, then write to new directory data = z.read(zip_file) with open(dest_file, 'wb') as f: f.write(encode_utf8(data)) except zipfile.error as e: print("Bad zipfile (%r): %s" % (zip_name, e)) raise e
[ "def", "extract_zip", "(", "zip_name", ",", "exclude_term", "=", "None", ")", ":", "zip_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "zip_name", ")", ")", "try", ":", "with", "zipfile", ".", "ZipFile", "(", "zip_name", ")", "as", "z", ":", "# write each zipped file out if it isn't a directory", "files", "=", "[", "zip_file", "for", "zip_file", "in", "z", ".", "namelist", "(", ")", "if", "not", "zip_file", ".", "endswith", "(", "'/'", ")", "]", "print", "(", "'Extracting %i files from %r.'", "%", "(", "len", "(", "files", ")", ",", "zip_name", ")", ")", "for", "zip_file", "in", "files", ":", "# remove any provided extra directory term from zip file", "if", "exclude_term", ":", "dest_file", "=", "zip_file", ".", "replace", "(", "exclude_term", ",", "''", ")", "else", ":", "dest_file", "=", "zip_file", "dest_file", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "zip_dir", ",", "dest_file", ")", ")", "dest_dir", "=", "os", ".", "path", ".", "dirname", "(", "dest_file", ")", "# make directory if it does not exist", "if", "not", "os", ".", "path", ".", "isdir", "(", "dest_dir", ")", ":", "os", ".", "makedirs", "(", "dest_dir", ")", "# read file from zip, then write to new directory", "data", "=", "z", ".", "read", "(", "zip_file", ")", "with", "open", "(", "dest_file", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "encode_utf8", "(", "data", ")", ")", "except", "zipfile", ".", "error", "as", "e", ":", "print", "(", "\"Bad zipfile (%r): %s\"", "%", "(", "zip_name", ",", "e", ")", ")", "raise", "e" ]
Extracts a zip file to its containing directory.
[ "Extracts", "a", "zip", "file", "to", "its", "containing", "directory", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/app/stocks/download_sample_data.py#L27-L61
train
bokeh/bokeh
bokeh/models/widgets/sliders.py
DateRangeSlider.value_as_datetime
def value_as_datetime(self): ''' Convenience property to retrieve the value tuple as a tuple of datetime objects. ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): d1 = datetime.utcfromtimestamp(v1 / 1000) else: d1 = v1 if isinstance(v2, numbers.Number): d2 = datetime.utcfromtimestamp(v2 / 1000) else: d2 = v2 return d1, d2
python
def value_as_datetime(self): ''' Convenience property to retrieve the value tuple as a tuple of datetime objects. ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): d1 = datetime.utcfromtimestamp(v1 / 1000) else: d1 = v1 if isinstance(v2, numbers.Number): d2 = datetime.utcfromtimestamp(v2 / 1000) else: d2 = v2 return d1, d2
[ "def", "value_as_datetime", "(", "self", ")", ":", "if", "self", ".", "value", "is", "None", ":", "return", "None", "v1", ",", "v2", "=", "self", ".", "value", "if", "isinstance", "(", "v1", ",", "numbers", ".", "Number", ")", ":", "d1", "=", "datetime", ".", "utcfromtimestamp", "(", "v1", "/", "1000", ")", "else", ":", "d1", "=", "v1", "if", "isinstance", "(", "v2", ",", "numbers", ".", "Number", ")", ":", "d2", "=", "datetime", ".", "utcfromtimestamp", "(", "v2", "/", "1000", ")", "else", ":", "d2", "=", "v2", "return", "d1", ",", "d2" ]
Convenience property to retrieve the value tuple as a tuple of datetime objects.
[ "Convenience", "property", "to", "retrieve", "the", "value", "tuple", "as", "a", "tuple", "of", "datetime", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/sliders.py#L182-L198
train
bokeh/bokeh
bokeh/models/widgets/sliders.py
DateRangeSlider.value_as_date
def value_as_date(self): ''' Convenience property to retrieve the value tuple as a tuple of date objects. Added in version 1.1 ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): dt = datetime.utcfromtimestamp(v1 / 1000) d1 = date(*dt.timetuple()[:3]) else: d1 = v1 if isinstance(v2, numbers.Number): dt = datetime.utcfromtimestamp(v2 / 1000) d2 = date(*dt.timetuple()[:3]) else: d2 = v2 return d1, d2
python
def value_as_date(self): ''' Convenience property to retrieve the value tuple as a tuple of date objects. Added in version 1.1 ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): dt = datetime.utcfromtimestamp(v1 / 1000) d1 = date(*dt.timetuple()[:3]) else: d1 = v1 if isinstance(v2, numbers.Number): dt = datetime.utcfromtimestamp(v2 / 1000) d2 = date(*dt.timetuple()[:3]) else: d2 = v2 return d1, d2
[ "def", "value_as_date", "(", "self", ")", ":", "if", "self", ".", "value", "is", "None", ":", "return", "None", "v1", ",", "v2", "=", "self", ".", "value", "if", "isinstance", "(", "v1", ",", "numbers", ".", "Number", ")", ":", "dt", "=", "datetime", ".", "utcfromtimestamp", "(", "v1", "/", "1000", ")", "d1", "=", "date", "(", "*", "dt", ".", "timetuple", "(", ")", "[", ":", "3", "]", ")", "else", ":", "d1", "=", "v1", "if", "isinstance", "(", "v2", ",", "numbers", ".", "Number", ")", ":", "dt", "=", "datetime", ".", "utcfromtimestamp", "(", "v2", "/", "1000", ")", "d2", "=", "date", "(", "*", "dt", ".", "timetuple", "(", ")", "[", ":", "3", "]", ")", "else", ":", "d2", "=", "v2", "return", "d1", ",", "d2" ]
Convenience property to retrieve the value tuple as a tuple of date objects. Added in version 1.1
[ "Convenience", "property", "to", "retrieve", "the", "value", "tuple", "as", "a", "tuple", "of", "date", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/sliders.py#L201-L220
train
bokeh/bokeh
bokeh/application/handlers/directory.py
DirectoryHandler.modify_document
def modify_document(self, doc): ''' Execute the configured ``main.py`` or ``main.ipynb`` to modify the document. This method will also search the app directory for any theme or template files, and automatically configure the document with them if they are found. ''' if self._lifecycle_handler.failed: return # Note: we do NOT copy self._theme, which assumes the Theme # class is immutable (has no setters) if self._theme is not None: doc.theme = self._theme if self._template is not None: doc.template = self._template # This internal handler should never add a template self._main_handler.modify_document(doc)
python
def modify_document(self, doc): ''' Execute the configured ``main.py`` or ``main.ipynb`` to modify the document. This method will also search the app directory for any theme or template files, and automatically configure the document with them if they are found. ''' if self._lifecycle_handler.failed: return # Note: we do NOT copy self._theme, which assumes the Theme # class is immutable (has no setters) if self._theme is not None: doc.theme = self._theme if self._template is not None: doc.template = self._template # This internal handler should never add a template self._main_handler.modify_document(doc)
[ "def", "modify_document", "(", "self", ",", "doc", ")", ":", "if", "self", ".", "_lifecycle_handler", ".", "failed", ":", "return", "# Note: we do NOT copy self._theme, which assumes the Theme", "# class is immutable (has no setters)", "if", "self", ".", "_theme", "is", "not", "None", ":", "doc", ".", "theme", "=", "self", ".", "_theme", "if", "self", ".", "_template", "is", "not", "None", ":", "doc", ".", "template", "=", "self", ".", "_template", "# This internal handler should never add a template", "self", ".", "_main_handler", ".", "modify_document", "(", "doc", ")" ]
Execute the configured ``main.py`` or ``main.ipynb`` to modify the document. This method will also search the app directory for any theme or template files, and automatically configure the document with them if they are found.
[ "Execute", "the", "configured", "main", ".", "py", "or", "main", ".", "ipynb", "to", "modify", "the", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/directory.py#L173-L193
train
bokeh/bokeh
bokeh/plotting/figure.py
markers
def markers(): ''' Prints a list of valid marker types for scatter() Returns: None ''' print("Available markers: \n\n - " + "\n - ".join(list(MarkerType))) print() print("Shortcuts: \n\n" + "\n".join(" %r: %s" % item for item in _MARKER_SHORTCUTS.items()))
python
def markers(): ''' Prints a list of valid marker types for scatter() Returns: None ''' print("Available markers: \n\n - " + "\n - ".join(list(MarkerType))) print() print("Shortcuts: \n\n" + "\n".join(" %r: %s" % item for item in _MARKER_SHORTCUTS.items()))
[ "def", "markers", "(", ")", ":", "print", "(", "\"Available markers: \\n\\n - \"", "+", "\"\\n - \"", ".", "join", "(", "list", "(", "MarkerType", ")", ")", ")", "print", "(", ")", "print", "(", "\"Shortcuts: \\n\\n\"", "+", "\"\\n\"", ".", "join", "(", "\" %r: %s\"", "%", "item", "for", "item", "in", "_MARKER_SHORTCUTS", ".", "items", "(", ")", ")", ")" ]
Prints a list of valid marker types for scatter() Returns: None
[ "Prints", "a", "list", "of", "valid", "marker", "types", "for", "scatter", "()" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L1179-L1187
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.scatter
def scatter(self, *args, **kwargs): ''' Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : values or field names of sizes in screen units marker (str, or list[str]): values or field names of marker types color (color value, optional): shorthand to set both fill and line color source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` Examples: >>> p.scatter([1,2,3],[4,5,6], marker="square", fill_color="red") >>> p.scatter("data1", "data2", marker="mtype", source=data_source, ...) .. note:: When passing ``marker="circle"`` it is also possible to supply a ``radius`` value in data-space units. When configuring marker type from a data source column, *all* markers incuding circles may only be configured with ``size`` in screen units. ''' marker_type = kwargs.pop("marker", "circle") if isinstance(marker_type, string_types) and marker_type in _MARKER_SHORTCUTS: marker_type = _MARKER_SHORTCUTS[marker_type] # The original scatter implementation allowed circle scatters to set a # radius. We will leave this here for compatibility but note that it # only works when the marker type is "circle" (and not referencing a # data source column). Consider deprecating in the future. if marker_type == "circle" and "radius" in kwargs: return self.circle(*args, **kwargs) else: return self._scatter(*args, marker=marker_type, **kwargs)
python
def scatter(self, *args, **kwargs): ''' Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : values or field names of sizes in screen units marker (str, or list[str]): values or field names of marker types color (color value, optional): shorthand to set both fill and line color source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` Examples: >>> p.scatter([1,2,3],[4,5,6], marker="square", fill_color="red") >>> p.scatter("data1", "data2", marker="mtype", source=data_source, ...) .. note:: When passing ``marker="circle"`` it is also possible to supply a ``radius`` value in data-space units. When configuring marker type from a data source column, *all* markers incuding circles may only be configured with ``size`` in screen units. ''' marker_type = kwargs.pop("marker", "circle") if isinstance(marker_type, string_types) and marker_type in _MARKER_SHORTCUTS: marker_type = _MARKER_SHORTCUTS[marker_type] # The original scatter implementation allowed circle scatters to set a # radius. We will leave this here for compatibility but note that it # only works when the marker type is "circle" (and not referencing a # data source column). Consider deprecating in the future. if marker_type == "circle" and "radius" in kwargs: return self.circle(*args, **kwargs) else: return self._scatter(*args, marker=marker_type, **kwargs)
[ "def", "scatter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "marker_type", "=", "kwargs", ".", "pop", "(", "\"marker\"", ",", "\"circle\"", ")", "if", "isinstance", "(", "marker_type", ",", "string_types", ")", "and", "marker_type", "in", "_MARKER_SHORTCUTS", ":", "marker_type", "=", "_MARKER_SHORTCUTS", "[", "marker_type", "]", "# The original scatter implementation allowed circle scatters to set a", "# radius. We will leave this here for compatibility but note that it", "# only works when the marker type is \"circle\" (and not referencing a", "# data source column). Consider deprecating in the future.", "if", "marker_type", "==", "\"circle\"", "and", "\"radius\"", "in", "kwargs", ":", "return", "self", ".", "circle", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "self", ".", "_scatter", "(", "*", "args", ",", "marker", "=", "marker_type", ",", "*", "*", "kwargs", ")" ]
Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : values or field names of sizes in screen units marker (str, or list[str]): values or field names of marker types color (color value, optional): shorthand to set both fill and line color source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` Examples: >>> p.scatter([1,2,3],[4,5,6], marker="square", fill_color="red") >>> p.scatter("data1", "data2", marker="mtype", source=data_source, ...) .. note:: When passing ``marker="circle"`` it is also possible to supply a ``radius`` value in data-space units. When configuring marker type from a data source column, *all* markers incuding circles may only be configured with ``size`` in screen units.
[ "Creates", "a", "scatter", "plot", "of", "the", "given", "x", "and", "y", "items", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L757-L801
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.hexbin
def hexbin(self, x, y, size, orientation="pointytop", palette="Viridis256", line_color=None, fill_color=None, aspect_scale=1, **kwargs): ''' Perform a simple equal-weight hexagonal binning. A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display the binning. The :class:`~bokeh.models.sources.ColumnDataSource` for the glyph will have columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. It is often useful to set ``match_aspect=True`` on the associated plot, so that hexagonal tiles are all regular (i.e. not "stretched") in screen space. For more sophisticated use-cases, e.g. weighted binning or individually scaling hex tiles, use :func:`hex_tile` directly, or consider a higher level library such as HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates to bin into hexagonal tiles. y (array[float]) : A NumPy array of y-coordinates to bin into hexagonal tiles size (float) : The size of the hexagonal tiling to use. The size is defined as distance from the center of a hexagon to a corner. In case the aspect scaling is not 1-1, then specifically `size` is the distance from the center to the "top" corner with the `"pointytop"` orientation, and the distance from the center to a "side" corner with the "flattop" orientation. orientation ("pointytop" or "flattop", optional) : Whether the hexagonal tiles should be oriented with a pointed corner on top, or a flat side on top. (default: "pointytop") palette (str or seq[color], optional) : A palette (or palette name) to use to colormap the bins according to count. (default: 'Viridis256') If ``fill_color`` is supplied, it overrides this value. line_color (color, optional) : The outline color for hex tiles, or None (default: None) fill_color (color, optional) : An optional fill color for hex tiles, or None. If None, then the ``palette`` will be used to color map the tiles by count. (default: None) aspect_scale (float) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Any additional keyword arguments are passed to :func:`hex_tile`. Returns (Glyphrender, DataFrame) A tuple with the ``HexTile`` renderer generated to display the binning, and a Pandas ``DataFrame`` with columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. Example: .. bokeh-plot:: :source-position: above import numpy as np from bokeh.models import HoverTool from bokeh.plotting import figure, show x = 2 + 2*np.random.standard_normal(500) y = 2 + 2*np.random.standard_normal(500) p = figure(match_aspect=True, tools="wheel_zoom,reset") p.background_fill_color = '#440154' p.grid.visible = False p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8) hover = HoverTool(tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")]) p.add_tools(hover) show(p) .. _axial coordinates: https://www.redblobgames.com/grids/hexagons/#coordinates-axial ''' from ..util.hex import hexbin bins = hexbin(x, y, size, orientation, aspect_scale=aspect_scale) if fill_color is None: fill_color = linear_cmap('c', palette, 0, max(bins.counts)) source = ColumnDataSource(data=dict(q=bins.q, r=bins.r, c=bins.counts)) r = self.hex_tile(q="q", r="r", size=size, orientation=orientation, aspect_scale=aspect_scale, source=source, line_color=line_color, fill_color=fill_color, **kwargs) return (r, bins)
python
def hexbin(self, x, y, size, orientation="pointytop", palette="Viridis256", line_color=None, fill_color=None, aspect_scale=1, **kwargs): ''' Perform a simple equal-weight hexagonal binning. A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display the binning. The :class:`~bokeh.models.sources.ColumnDataSource` for the glyph will have columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. It is often useful to set ``match_aspect=True`` on the associated plot, so that hexagonal tiles are all regular (i.e. not "stretched") in screen space. For more sophisticated use-cases, e.g. weighted binning or individually scaling hex tiles, use :func:`hex_tile` directly, or consider a higher level library such as HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates to bin into hexagonal tiles. y (array[float]) : A NumPy array of y-coordinates to bin into hexagonal tiles size (float) : The size of the hexagonal tiling to use. The size is defined as distance from the center of a hexagon to a corner. In case the aspect scaling is not 1-1, then specifically `size` is the distance from the center to the "top" corner with the `"pointytop"` orientation, and the distance from the center to a "side" corner with the "flattop" orientation. orientation ("pointytop" or "flattop", optional) : Whether the hexagonal tiles should be oriented with a pointed corner on top, or a flat side on top. (default: "pointytop") palette (str or seq[color], optional) : A palette (or palette name) to use to colormap the bins according to count. (default: 'Viridis256') If ``fill_color`` is supplied, it overrides this value. line_color (color, optional) : The outline color for hex tiles, or None (default: None) fill_color (color, optional) : An optional fill color for hex tiles, or None. If None, then the ``palette`` will be used to color map the tiles by count. (default: None) aspect_scale (float) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Any additional keyword arguments are passed to :func:`hex_tile`. Returns (Glyphrender, DataFrame) A tuple with the ``HexTile`` renderer generated to display the binning, and a Pandas ``DataFrame`` with columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. Example: .. bokeh-plot:: :source-position: above import numpy as np from bokeh.models import HoverTool from bokeh.plotting import figure, show x = 2 + 2*np.random.standard_normal(500) y = 2 + 2*np.random.standard_normal(500) p = figure(match_aspect=True, tools="wheel_zoom,reset") p.background_fill_color = '#440154' p.grid.visible = False p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8) hover = HoverTool(tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")]) p.add_tools(hover) show(p) .. _axial coordinates: https://www.redblobgames.com/grids/hexagons/#coordinates-axial ''' from ..util.hex import hexbin bins = hexbin(x, y, size, orientation, aspect_scale=aspect_scale) if fill_color is None: fill_color = linear_cmap('c', palette, 0, max(bins.counts)) source = ColumnDataSource(data=dict(q=bins.q, r=bins.r, c=bins.counts)) r = self.hex_tile(q="q", r="r", size=size, orientation=orientation, aspect_scale=aspect_scale, source=source, line_color=line_color, fill_color=fill_color, **kwargs) return (r, bins)
[ "def", "hexbin", "(", "self", ",", "x", ",", "y", ",", "size", ",", "orientation", "=", "\"pointytop\"", ",", "palette", "=", "\"Viridis256\"", ",", "line_color", "=", "None", ",", "fill_color", "=", "None", ",", "aspect_scale", "=", "1", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "util", ".", "hex", "import", "hexbin", "bins", "=", "hexbin", "(", "x", ",", "y", ",", "size", ",", "orientation", ",", "aspect_scale", "=", "aspect_scale", ")", "if", "fill_color", "is", "None", ":", "fill_color", "=", "linear_cmap", "(", "'c'", ",", "palette", ",", "0", ",", "max", "(", "bins", ".", "counts", ")", ")", "source", "=", "ColumnDataSource", "(", "data", "=", "dict", "(", "q", "=", "bins", ".", "q", ",", "r", "=", "bins", ".", "r", ",", "c", "=", "bins", ".", "counts", ")", ")", "r", "=", "self", ".", "hex_tile", "(", "q", "=", "\"q\"", ",", "r", "=", "\"r\"", ",", "size", "=", "size", ",", "orientation", "=", "orientation", ",", "aspect_scale", "=", "aspect_scale", ",", "source", "=", "source", ",", "line_color", "=", "line_color", ",", "fill_color", "=", "fill_color", ",", "*", "*", "kwargs", ")", "return", "(", "r", ",", "bins", ")" ]
Perform a simple equal-weight hexagonal binning. A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display the binning. The :class:`~bokeh.models.sources.ColumnDataSource` for the glyph will have columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. It is often useful to set ``match_aspect=True`` on the associated plot, so that hexagonal tiles are all regular (i.e. not "stretched") in screen space. For more sophisticated use-cases, e.g. weighted binning or individually scaling hex tiles, use :func:`hex_tile` directly, or consider a higher level library such as HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates to bin into hexagonal tiles. y (array[float]) : A NumPy array of y-coordinates to bin into hexagonal tiles size (float) : The size of the hexagonal tiling to use. The size is defined as distance from the center of a hexagon to a corner. In case the aspect scaling is not 1-1, then specifically `size` is the distance from the center to the "top" corner with the `"pointytop"` orientation, and the distance from the center to a "side" corner with the "flattop" orientation. orientation ("pointytop" or "flattop", optional) : Whether the hexagonal tiles should be oriented with a pointed corner on top, or a flat side on top. (default: "pointytop") palette (str or seq[color], optional) : A palette (or palette name) to use to colormap the bins according to count. (default: 'Viridis256') If ``fill_color`` is supplied, it overrides this value. line_color (color, optional) : The outline color for hex tiles, or None (default: None) fill_color (color, optional) : An optional fill color for hex tiles, or None. If None, then the ``palette`` will be used to color map the tiles by count. (default: None) aspect_scale (float) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Any additional keyword arguments are passed to :func:`hex_tile`. Returns (Glyphrender, DataFrame) A tuple with the ``HexTile`` renderer generated to display the binning, and a Pandas ``DataFrame`` with columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. Example: .. bokeh-plot:: :source-position: above import numpy as np from bokeh.models import HoverTool from bokeh.plotting import figure, show x = 2 + 2*np.random.standard_normal(500) y = 2 + 2*np.random.standard_normal(500) p = figure(match_aspect=True, tools="wheel_zoom,reset") p.background_fill_color = '#440154' p.grid.visible = False p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8) hover = HoverTool(tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")]) p.add_tools(hover) show(p) .. _axial coordinates: https://www.redblobgames.com/grids/hexagons/#coordinates-axial
[ "Perform", "a", "simple", "equal", "-", "weight", "hexagonal", "binning", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L803-L912
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.harea_stack
def harea_stack(self, stackers, **kw): ''' Generate multiple ``HArea`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``x1`` and ``x2`` harea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``harea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``harea_stack`` will will create two ``HArea`` renderers that stack: .. code-block:: python p.harea_stack(['2016', '2017'], y='y', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.harea(x1=stack(), x2=stack('2016'), y='y', color='blue', source=source, name='2016') p.harea(x1=stack('2016'), x2=stack('2016', '2017'), y='y', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "x1", "x2", **kw): result.append(self.harea(**kw)) return result
python
def harea_stack(self, stackers, **kw): ''' Generate multiple ``HArea`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``x1`` and ``x2`` harea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``harea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``harea_stack`` will will create two ``HArea`` renderers that stack: .. code-block:: python p.harea_stack(['2016', '2017'], y='y', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.harea(x1=stack(), x2=stack('2016'), y='y', color='blue', source=source, name='2016') p.harea(x1=stack('2016'), x2=stack('2016', '2017'), y='y', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "x1", "x2", **kw): result.append(self.harea(**kw)) return result
[ "def", "harea_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"x1\"", ",", "\"x2\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", "(", "self", ".", "harea", "(", "*", "*", "kw", ")", ")", "return", "result" ]
Generate multiple ``HArea`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``x1`` and ``x2`` harea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``harea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``harea_stack`` will will create two ``HArea`` renderers that stack: .. code-block:: python p.harea_stack(['2016', '2017'], y='y', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.harea(x1=stack(), x2=stack('2016'), y='y', color='blue', source=source, name='2016') p.harea(x1=stack('2016'), x2=stack('2016', '2017'), y='y', color='red', source=source, name='2017')
[ "Generate", "multiple", "HArea", "renderers", "for", "levels", "stacked", "left", "to", "right", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L914-L954
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.hbar_stack
def hbar_stack(self, stackers, **kw): ''' Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "left", "right", **kw): result.append(self.hbar(**kw)) return result
python
def hbar_stack(self, stackers, **kw): ''' Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "left", "right", **kw): result.append(self.hbar(**kw)) return result
[ "def", "hbar_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"left\"", ",", "\"right\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", "(", "self", ".", "hbar", "(", "*", "*", "kw", ")", ")", "return", "result" ]
Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017')
[ "Generate", "multiple", "HBar", "renderers", "for", "levels", "stacked", "left", "to", "right", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L956-L995
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.line_stack
def line_stack(self, x, y, **kw): ''' Generate multiple ``Line`` renderers for lines stacked vertically or horizontally. Args: x (seq[str]) : y (seq[str]) : Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``line_stack`` with stackers for the y-coordinates will will create two ``Line`` renderers that stack: .. code-block:: python p.line_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.line(y=stack('2016'), x='x', color='blue', source=source, name='2016') p.line(y=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' if all(isinstance(val, (list, tuple)) for val in (x,y)): raise ValueError("Only one of x or y may be a list of stackers") result = [] if isinstance(y, (list, tuple)): kw['x'] = x for kw in _single_stack(y, "y", **kw): result.append(self.line(**kw)) return result if isinstance(x, (list, tuple)): kw['y'] = y for kw in _single_stack(x, "x", **kw): result.append(self.line(**kw)) return result return [self.line(x, y, **kw)]
python
def line_stack(self, x, y, **kw): ''' Generate multiple ``Line`` renderers for lines stacked vertically or horizontally. Args: x (seq[str]) : y (seq[str]) : Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``line_stack`` with stackers for the y-coordinates will will create two ``Line`` renderers that stack: .. code-block:: python p.line_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.line(y=stack('2016'), x='x', color='blue', source=source, name='2016') p.line(y=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' if all(isinstance(val, (list, tuple)) for val in (x,y)): raise ValueError("Only one of x or y may be a list of stackers") result = [] if isinstance(y, (list, tuple)): kw['x'] = x for kw in _single_stack(y, "y", **kw): result.append(self.line(**kw)) return result if isinstance(x, (list, tuple)): kw['y'] = y for kw in _single_stack(x, "x", **kw): result.append(self.line(**kw)) return result return [self.line(x, y, **kw)]
[ "def", "line_stack", "(", "self", ",", "x", ",", "y", ",", "*", "*", "kw", ")", ":", "if", "all", "(", "isinstance", "(", "val", ",", "(", "list", ",", "tuple", ")", ")", "for", "val", "in", "(", "x", ",", "y", ")", ")", ":", "raise", "ValueError", "(", "\"Only one of x or y may be a list of stackers\"", ")", "result", "=", "[", "]", "if", "isinstance", "(", "y", ",", "(", "list", ",", "tuple", ")", ")", ":", "kw", "[", "'x'", "]", "=", "x", "for", "kw", "in", "_single_stack", "(", "y", ",", "\"y\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", "(", "self", ".", "line", "(", "*", "*", "kw", ")", ")", "return", "result", "if", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "kw", "[", "'y'", "]", "=", "y", "for", "kw", "in", "_single_stack", "(", "x", ",", "\"x\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", "(", "self", ".", "line", "(", "*", "*", "kw", ")", ")", "return", "result", "return", "[", "self", ".", "line", "(", "x", ",", "y", ",", "*", "*", "kw", ")", "]" ]
Generate multiple ``Line`` renderers for lines stacked vertically or horizontally. Args: x (seq[str]) : y (seq[str]) : Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``line_stack`` with stackers for the y-coordinates will will create two ``Line`` renderers that stack: .. code-block:: python p.line_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.line(y=stack('2016'), x='x', color='blue', source=source, name='2016') p.line(y=stack('2016', '2017'), x='x', color='red', source=source, name='2017')
[ "Generate", "multiple", "Line", "renderers", "for", "lines", "stacked", "vertically", "or", "horizontally", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L997-L1053
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.varea_stack
def varea_stack(self, stackers, **kw): ''' Generate multiple ``VArea`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``y1`` and ``y1`` varea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``varea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``varea_stack`` will will create two ``VArea`` renderers that stack: .. code-block:: python p.varea_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.varea(y1=stack(), y2=stack('2016'), x='x', color='blue', source=source, name='2016') p.varea(y1=stack('2016'), y2=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "y1", "y2", **kw): result.append(self.varea(**kw)) return result
python
def varea_stack(self, stackers, **kw): ''' Generate multiple ``VArea`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``y1`` and ``y1`` varea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``varea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``varea_stack`` will will create two ``VArea`` renderers that stack: .. code-block:: python p.varea_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.varea(y1=stack(), y2=stack('2016'), x='x', color='blue', source=source, name='2016') p.varea(y1=stack('2016'), y2=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "y1", "y2", **kw): result.append(self.varea(**kw)) return result
[ "def", "varea_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"y1\"", ",", "\"y2\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", "(", "self", ".", "varea", "(", "*", "*", "kw", ")", ")", "return", "result" ]
Generate multiple ``VArea`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``y1`` and ``y1`` varea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``varea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``varea_stack`` will will create two ``VArea`` renderers that stack: .. code-block:: python p.varea_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.varea(y1=stack(), y2=stack('2016'), x='x', color='blue', source=source, name='2016') p.varea(y1=stack('2016'), y2=stack('2016', '2017'), x='x', color='red', source=source, name='2017')
[ "Generate", "multiple", "VArea", "renderers", "for", "levels", "stacked", "bottom", "to", "top", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L1055-L1095
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.vbar_stack
def vbar_stack(self, stackers, **kw): ''' Generate multiple ``VBar`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``vbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``vbar_stack`` will will create two ``VBar`` renderers that stack: .. code-block:: python p.vbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.vbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.vbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "bottom", "top", **kw): result.append(self.vbar(**kw)) return result
python
def vbar_stack(self, stackers, **kw): ''' Generate multiple ``VBar`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``vbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``vbar_stack`` will will create two ``VBar`` renderers that stack: .. code-block:: python p.vbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.vbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.vbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "bottom", "top", **kw): result.append(self.vbar(**kw)) return result
[ "def", "vbar_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"bottom\"", ",", "\"top\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", "(", "self", ".", "vbar", "(", "*", "*", "kw", ")", ")", "return", "result" ]
Generate multiple ``VBar`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``vbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``vbar_stack`` will will create two ``VBar`` renderers that stack: .. code-block:: python p.vbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.vbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.vbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017')
[ "Generate", "multiple", "VBar", "renderers", "for", "levels", "stacked", "bottom", "to", "top", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L1097-L1137
train
bokeh/bokeh
bokeh/plotting/figure.py
Figure.graph
def graph(self, node_source, edge_source, layout_provider, **kwargs): ''' Creates a network graph using the given node, edge and layout provider. Args: node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph nodes. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. edge_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph edges. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. layout_provider (:class:`~bokeh.models.graphs.LayoutProvider`) : a ``LayoutProvider`` instance to provide the graph coordinates in Cartesian space. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` ''' kw = _graph(node_source, edge_source, **kwargs) graph_renderer = GraphRenderer(layout_provider=layout_provider, **kw) self.renderers.append(graph_renderer) return graph_renderer
python
def graph(self, node_source, edge_source, layout_provider, **kwargs): ''' Creates a network graph using the given node, edge and layout provider. Args: node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph nodes. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. edge_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph edges. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. layout_provider (:class:`~bokeh.models.graphs.LayoutProvider`) : a ``LayoutProvider`` instance to provide the graph coordinates in Cartesian space. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` ''' kw = _graph(node_source, edge_source, **kwargs) graph_renderer = GraphRenderer(layout_provider=layout_provider, **kw) self.renderers.append(graph_renderer) return graph_renderer
[ "def", "graph", "(", "self", ",", "node_source", ",", "edge_source", ",", "layout_provider", ",", "*", "*", "kwargs", ")", ":", "kw", "=", "_graph", "(", "node_source", ",", "edge_source", ",", "*", "*", "kwargs", ")", "graph_renderer", "=", "GraphRenderer", "(", "layout_provider", "=", "layout_provider", ",", "*", "*", "kw", ")", "self", ".", "renderers", ".", "append", "(", "graph_renderer", ")", "return", "graph_renderer" ]
Creates a network graph using the given node, edge and layout provider. Args: node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph nodes. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. edge_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph edges. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. layout_provider (:class:`~bokeh.models.graphs.LayoutProvider`) : a ``LayoutProvider`` instance to provide the graph coordinates in Cartesian space. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties`
[ "Creates", "a", "network", "graph", "using", "the", "given", "node", "edge", "and", "layout", "provider", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L1139-L1162
train
bokeh/bokeh
bokeh/client/util.py
server_url_for_websocket_url
def server_url_for_websocket_url(url): ''' Convert an ``ws(s)`` URL for a Bokeh server into the appropriate ``http(s)`` URL for the websocket endpoint. Args: url (str): An ``ws(s)`` URL ending in ``/ws`` Returns: str: The corresponding ``http(s)`` URL. Raises: ValueError: If the input URL is not of the proper form. ''' if url.startswith("ws:"): reprotocoled = "http" + url[2:] elif url.startswith("wss:"): reprotocoled = "https" + url[3:] else: raise ValueError("URL has non-websocket protocol " + url) if not reprotocoled.endswith("/ws"): raise ValueError("websocket URL does not end in /ws") return reprotocoled[:-2]
python
def server_url_for_websocket_url(url): ''' Convert an ``ws(s)`` URL for a Bokeh server into the appropriate ``http(s)`` URL for the websocket endpoint. Args: url (str): An ``ws(s)`` URL ending in ``/ws`` Returns: str: The corresponding ``http(s)`` URL. Raises: ValueError: If the input URL is not of the proper form. ''' if url.startswith("ws:"): reprotocoled = "http" + url[2:] elif url.startswith("wss:"): reprotocoled = "https" + url[3:] else: raise ValueError("URL has non-websocket protocol " + url) if not reprotocoled.endswith("/ws"): raise ValueError("websocket URL does not end in /ws") return reprotocoled[:-2]
[ "def", "server_url_for_websocket_url", "(", "url", ")", ":", "if", "url", ".", "startswith", "(", "\"ws:\"", ")", ":", "reprotocoled", "=", "\"http\"", "+", "url", "[", "2", ":", "]", "elif", "url", ".", "startswith", "(", "\"wss:\"", ")", ":", "reprotocoled", "=", "\"https\"", "+", "url", "[", "3", ":", "]", "else", ":", "raise", "ValueError", "(", "\"URL has non-websocket protocol \"", "+", "url", ")", "if", "not", "reprotocoled", ".", "endswith", "(", "\"/ws\"", ")", ":", "raise", "ValueError", "(", "\"websocket URL does not end in /ws\"", ")", "return", "reprotocoled", "[", ":", "-", "2", "]" ]
Convert an ``ws(s)`` URL for a Bokeh server into the appropriate ``http(s)`` URL for the websocket endpoint. Args: url (str): An ``ws(s)`` URL ending in ``/ws`` Returns: str: The corresponding ``http(s)`` URL. Raises: ValueError: If the input URL is not of the proper form.
[ "Convert", "an", "ws", "(", "s", ")", "URL", "for", "a", "Bokeh", "server", "into", "the", "appropriate", "http", "(", "s", ")", "URL", "for", "the", "websocket", "endpoint", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/util.py#L46-L71
train
bokeh/bokeh
bokeh/client/util.py
websocket_url_for_server_url
def websocket_url_for_server_url(url): ''' Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into the appropriate ``ws(s)`` URL Args: url (str): An ``http(s)`` URL Returns: str: The corresponding ``ws(s)`` URL ending in ``/ws`` Raises: ValueError: If the input URL is not of the proper form. ''' if url.startswith("http:"): reprotocoled = "ws" + url[4:] elif url.startswith("https:"): reprotocoled = "wss" + url[5:] else: raise ValueError("URL has unknown protocol " + url) if reprotocoled.endswith("/"): return reprotocoled + "ws" else: return reprotocoled + "/ws"
python
def websocket_url_for_server_url(url): ''' Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into the appropriate ``ws(s)`` URL Args: url (str): An ``http(s)`` URL Returns: str: The corresponding ``ws(s)`` URL ending in ``/ws`` Raises: ValueError: If the input URL is not of the proper form. ''' if url.startswith("http:"): reprotocoled = "ws" + url[4:] elif url.startswith("https:"): reprotocoled = "wss" + url[5:] else: raise ValueError("URL has unknown protocol " + url) if reprotocoled.endswith("/"): return reprotocoled + "ws" else: return reprotocoled + "/ws"
[ "def", "websocket_url_for_server_url", "(", "url", ")", ":", "if", "url", ".", "startswith", "(", "\"http:\"", ")", ":", "reprotocoled", "=", "\"ws\"", "+", "url", "[", "4", ":", "]", "elif", "url", ".", "startswith", "(", "\"https:\"", ")", ":", "reprotocoled", "=", "\"wss\"", "+", "url", "[", "5", ":", "]", "else", ":", "raise", "ValueError", "(", "\"URL has unknown protocol \"", "+", "url", ")", "if", "reprotocoled", ".", "endswith", "(", "\"/\"", ")", ":", "return", "reprotocoled", "+", "\"ws\"", "else", ":", "return", "reprotocoled", "+", "\"/ws\"" ]
Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into the appropriate ``ws(s)`` URL Args: url (str): An ``http(s)`` URL Returns: str: The corresponding ``ws(s)`` URL ending in ``/ws`` Raises: ValueError: If the input URL is not of the proper form.
[ "Convert", "an", "http", "(", "s", ")", "URL", "for", "a", "Bokeh", "server", "websocket", "endpoint", "into", "the", "appropriate", "ws", "(", "s", ")", "URL" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/util.py#L73-L99
train
bokeh/bokeh
bokeh/core/property/validation.py
without_property_validation
def without_property_validation(input_function): ''' Turn off property validation during update callbacks Example: .. code-block:: python @without_property_validation def update(attr, old, new): # do things without validation See Also: :class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control ''' @wraps(input_function) def func(*args, **kwargs): with validate(False): return input_function(*args, **kwargs) return func
python
def without_property_validation(input_function): ''' Turn off property validation during update callbacks Example: .. code-block:: python @without_property_validation def update(attr, old, new): # do things without validation See Also: :class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control ''' @wraps(input_function) def func(*args, **kwargs): with validate(False): return input_function(*args, **kwargs) return func
[ "def", "without_property_validation", "(", "input_function", ")", ":", "@", "wraps", "(", "input_function", ")", "def", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "validate", "(", "False", ")", ":", "return", "input_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "func" ]
Turn off property validation during update callbacks Example: .. code-block:: python @without_property_validation def update(attr, old, new): # do things without validation See Also: :class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control
[ "Turn", "off", "property", "validation", "during", "update", "callbacks" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/validation.py#L80-L98
train
bokeh/bokeh
bokeh/core/templates.py
get_env
def get_env(): ''' Get the correct Jinja2 Environment, also for frozen scripts. ''' if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): # PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates') else: # Non-frozen Python and cx_Freeze can use __file__ directly templates_path = join(dirname(__file__), '_templates') return Environment(loader=FileSystemLoader(templates_path))
python
def get_env(): ''' Get the correct Jinja2 Environment, also for frozen scripts. ''' if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): # PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates') else: # Non-frozen Python and cx_Freeze can use __file__ directly templates_path = join(dirname(__file__), '_templates') return Environment(loader=FileSystemLoader(templates_path))
[ "def", "get_env", "(", ")", ":", "if", "getattr", "(", "sys", ",", "'frozen'", ",", "False", ")", "and", "hasattr", "(", "sys", ",", "'_MEIPASS'", ")", ":", "# PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader", "templates_path", "=", "join", "(", "sys", ".", "_MEIPASS", ",", "'bokeh'", ",", "'core'", ",", "'_templates'", ")", "else", ":", "# Non-frozen Python and cx_Freeze can use __file__ directly", "templates_path", "=", "join", "(", "dirname", "(", "__file__", ")", ",", "'_templates'", ")", "return", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "templates_path", ")", ")" ]
Get the correct Jinja2 Environment, also for frozen scripts.
[ "Get", "the", "correct", "Jinja2", "Environment", "also", "for", "frozen", "scripts", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/templates.py#L72-L82
train
bokeh/bokeh
examples/custom/parallel_plot/parallel_plot.py
parallel_plot
def parallel_plot(df, color=None, palette=None): """From a dataframe create a parallel coordinate plot """ npts = df.shape[0] ndims = len(df.columns) if color is None: color = np.ones(npts) if palette is None: palette = ['#ff0000'] cmap = LinearColorMapper(high=color.min(), low=color.max(), palette=palette) data_source = ColumnDataSource(dict( xs=np.arange(ndims)[None, :].repeat(npts, axis=0).tolist(), ys=np.array((df-df.min())/(df.max()-df.min())).tolist(), color=color)) p = figure(x_range=(-1, ndims), y_range=(0, 1), width=1000, tools="pan, box_zoom") # Create x axis ticks from columns contained in dataframe fixed_x_ticks = FixedTicker( ticks=np.arange(ndims), minor_ticks=[]) formatter_x_ticks = FuncTickFormatter( code="return columns[index]", args={"columns": df.columns}) p.xaxis.ticker = fixed_x_ticks p.xaxis.formatter = formatter_x_ticks p.yaxis.visible = False p.y_range.start = 0 p.y_range.end = 1 p.y_range.bounds = (-0.1, 1.1) # add a little padding around y axis p.xgrid.visible = False p.ygrid.visible = False # Create extra y axis for each dataframe column tickformatter = BasicTickFormatter(precision=1) for index, col in enumerate(df.columns): start = df[col].min() end = df[col].max() bound_min = start + abs(end-start) * (p.y_range.bounds[0] - p.y_range.start) bound_max = end + abs(end-start) * (p.y_range.bounds[1] - p.y_range.end) p.extra_y_ranges.update( {col: Range1d(start=bound_min, end=bound_max, bounds=(bound_min, bound_max))}) fixedticks = FixedTicker( ticks=np.linspace(start, end, 8), minor_ticks=[]) p.add_layout(LinearAxis(fixed_location=index, y_range_name=col, ticker=fixedticks, formatter=tickformatter), 'right') # create the data renderer ( MultiLine ) # specify selected and non selected style non_selected_line_style = dict(line_color='grey', line_width=0.1, line_alpha=0.5) selected_line_style = dict(line_color={'field': 'color', 'transform': cmap}, line_width=1) parallel_renderer = p.multi_line( xs="xs", ys="ys", source=data_source, **non_selected_line_style) # Specify selection style selected_lines = MultiLine(**selected_line_style) # Specify non selection style nonselected_lines = MultiLine(**non_selected_line_style) parallel_renderer.selection_glyph = selected_lines parallel_renderer.nonselection_glyph = nonselected_lines p.y_range.start = p.y_range.bounds[0] p.y_range.end = p.y_range.bounds[1] rect_source = ColumnDataSource({ 'x': [], 'y': [], 'width': [], 'height': [] }) # add rectangle selections selection_renderer = p.rect(x='x', y='y', width='width', height='height', source=rect_source, fill_alpha=0.7, fill_color='#009933') selection_tool = ParallelSelectionTool( renderer_select=selection_renderer, renderer_data=parallel_renderer, box_width=10) # custom resets (reset only axes not selections) reset_axes = ParallelResetTool() # add tools and activate selection ones p.add_tools(selection_tool, reset_axes) p.toolbar.active_drag = selection_tool return p
python
def parallel_plot(df, color=None, palette=None): """From a dataframe create a parallel coordinate plot """ npts = df.shape[0] ndims = len(df.columns) if color is None: color = np.ones(npts) if palette is None: palette = ['#ff0000'] cmap = LinearColorMapper(high=color.min(), low=color.max(), palette=palette) data_source = ColumnDataSource(dict( xs=np.arange(ndims)[None, :].repeat(npts, axis=0).tolist(), ys=np.array((df-df.min())/(df.max()-df.min())).tolist(), color=color)) p = figure(x_range=(-1, ndims), y_range=(0, 1), width=1000, tools="pan, box_zoom") # Create x axis ticks from columns contained in dataframe fixed_x_ticks = FixedTicker( ticks=np.arange(ndims), minor_ticks=[]) formatter_x_ticks = FuncTickFormatter( code="return columns[index]", args={"columns": df.columns}) p.xaxis.ticker = fixed_x_ticks p.xaxis.formatter = formatter_x_ticks p.yaxis.visible = False p.y_range.start = 0 p.y_range.end = 1 p.y_range.bounds = (-0.1, 1.1) # add a little padding around y axis p.xgrid.visible = False p.ygrid.visible = False # Create extra y axis for each dataframe column tickformatter = BasicTickFormatter(precision=1) for index, col in enumerate(df.columns): start = df[col].min() end = df[col].max() bound_min = start + abs(end-start) * (p.y_range.bounds[0] - p.y_range.start) bound_max = end + abs(end-start) * (p.y_range.bounds[1] - p.y_range.end) p.extra_y_ranges.update( {col: Range1d(start=bound_min, end=bound_max, bounds=(bound_min, bound_max))}) fixedticks = FixedTicker( ticks=np.linspace(start, end, 8), minor_ticks=[]) p.add_layout(LinearAxis(fixed_location=index, y_range_name=col, ticker=fixedticks, formatter=tickformatter), 'right') # create the data renderer ( MultiLine ) # specify selected and non selected style non_selected_line_style = dict(line_color='grey', line_width=0.1, line_alpha=0.5) selected_line_style = dict(line_color={'field': 'color', 'transform': cmap}, line_width=1) parallel_renderer = p.multi_line( xs="xs", ys="ys", source=data_source, **non_selected_line_style) # Specify selection style selected_lines = MultiLine(**selected_line_style) # Specify non selection style nonselected_lines = MultiLine(**non_selected_line_style) parallel_renderer.selection_glyph = selected_lines parallel_renderer.nonselection_glyph = nonselected_lines p.y_range.start = p.y_range.bounds[0] p.y_range.end = p.y_range.bounds[1] rect_source = ColumnDataSource({ 'x': [], 'y': [], 'width': [], 'height': [] }) # add rectangle selections selection_renderer = p.rect(x='x', y='y', width='width', height='height', source=rect_source, fill_alpha=0.7, fill_color='#009933') selection_tool = ParallelSelectionTool( renderer_select=selection_renderer, renderer_data=parallel_renderer, box_width=10) # custom resets (reset only axes not selections) reset_axes = ParallelResetTool() # add tools and activate selection ones p.add_tools(selection_tool, reset_axes) p.toolbar.active_drag = selection_tool return p
[ "def", "parallel_plot", "(", "df", ",", "color", "=", "None", ",", "palette", "=", "None", ")", ":", "npts", "=", "df", ".", "shape", "[", "0", "]", "ndims", "=", "len", "(", "df", ".", "columns", ")", "if", "color", "is", "None", ":", "color", "=", "np", ".", "ones", "(", "npts", ")", "if", "palette", "is", "None", ":", "palette", "=", "[", "'#ff0000'", "]", "cmap", "=", "LinearColorMapper", "(", "high", "=", "color", ".", "min", "(", ")", ",", "low", "=", "color", ".", "max", "(", ")", ",", "palette", "=", "palette", ")", "data_source", "=", "ColumnDataSource", "(", "dict", "(", "xs", "=", "np", ".", "arange", "(", "ndims", ")", "[", "None", ",", ":", "]", ".", "repeat", "(", "npts", ",", "axis", "=", "0", ")", ".", "tolist", "(", ")", ",", "ys", "=", "np", ".", "array", "(", "(", "df", "-", "df", ".", "min", "(", ")", ")", "/", "(", "df", ".", "max", "(", ")", "-", "df", ".", "min", "(", ")", ")", ")", ".", "tolist", "(", ")", ",", "color", "=", "color", ")", ")", "p", "=", "figure", "(", "x_range", "=", "(", "-", "1", ",", "ndims", ")", ",", "y_range", "=", "(", "0", ",", "1", ")", ",", "width", "=", "1000", ",", "tools", "=", "\"pan, box_zoom\"", ")", "# Create x axis ticks from columns contained in dataframe", "fixed_x_ticks", "=", "FixedTicker", "(", "ticks", "=", "np", ".", "arange", "(", "ndims", ")", ",", "minor_ticks", "=", "[", "]", ")", "formatter_x_ticks", "=", "FuncTickFormatter", "(", "code", "=", "\"return columns[index]\"", ",", "args", "=", "{", "\"columns\"", ":", "df", ".", "columns", "}", ")", "p", ".", "xaxis", ".", "ticker", "=", "fixed_x_ticks", "p", ".", "xaxis", ".", "formatter", "=", "formatter_x_ticks", "p", ".", "yaxis", ".", "visible", "=", "False", "p", ".", "y_range", ".", "start", "=", "0", "p", ".", "y_range", ".", "end", "=", "1", "p", ".", "y_range", ".", "bounds", "=", "(", "-", "0.1", ",", "1.1", ")", "# add a little padding around y axis", "p", ".", "xgrid", ".", "visible", "=", "False", "p", ".", "ygrid", ".", "visible", "=", "False", "# Create extra y axis for each dataframe column", "tickformatter", "=", "BasicTickFormatter", "(", "precision", "=", "1", ")", "for", "index", ",", "col", "in", "enumerate", "(", "df", ".", "columns", ")", ":", "start", "=", "df", "[", "col", "]", ".", "min", "(", ")", "end", "=", "df", "[", "col", "]", ".", "max", "(", ")", "bound_min", "=", "start", "+", "abs", "(", "end", "-", "start", ")", "*", "(", "p", ".", "y_range", ".", "bounds", "[", "0", "]", "-", "p", ".", "y_range", ".", "start", ")", "bound_max", "=", "end", "+", "abs", "(", "end", "-", "start", ")", "*", "(", "p", ".", "y_range", ".", "bounds", "[", "1", "]", "-", "p", ".", "y_range", ".", "end", ")", "p", ".", "extra_y_ranges", ".", "update", "(", "{", "col", ":", "Range1d", "(", "start", "=", "bound_min", ",", "end", "=", "bound_max", ",", "bounds", "=", "(", "bound_min", ",", "bound_max", ")", ")", "}", ")", "fixedticks", "=", "FixedTicker", "(", "ticks", "=", "np", ".", "linspace", "(", "start", ",", "end", ",", "8", ")", ",", "minor_ticks", "=", "[", "]", ")", "p", ".", "add_layout", "(", "LinearAxis", "(", "fixed_location", "=", "index", ",", "y_range_name", "=", "col", ",", "ticker", "=", "fixedticks", ",", "formatter", "=", "tickformatter", ")", ",", "'right'", ")", "# create the data renderer ( MultiLine )", "# specify selected and non selected style", "non_selected_line_style", "=", "dict", "(", "line_color", "=", "'grey'", ",", "line_width", "=", "0.1", ",", "line_alpha", "=", "0.5", ")", "selected_line_style", "=", "dict", "(", "line_color", "=", "{", "'field'", ":", "'color'", ",", "'transform'", ":", "cmap", "}", ",", "line_width", "=", "1", ")", "parallel_renderer", "=", "p", ".", "multi_line", "(", "xs", "=", "\"xs\"", ",", "ys", "=", "\"ys\"", ",", "source", "=", "data_source", ",", "*", "*", "non_selected_line_style", ")", "# Specify selection style", "selected_lines", "=", "MultiLine", "(", "*", "*", "selected_line_style", ")", "# Specify non selection style", "nonselected_lines", "=", "MultiLine", "(", "*", "*", "non_selected_line_style", ")", "parallel_renderer", ".", "selection_glyph", "=", "selected_lines", "parallel_renderer", ".", "nonselection_glyph", "=", "nonselected_lines", "p", ".", "y_range", ".", "start", "=", "p", ".", "y_range", ".", "bounds", "[", "0", "]", "p", ".", "y_range", ".", "end", "=", "p", ".", "y_range", ".", "bounds", "[", "1", "]", "rect_source", "=", "ColumnDataSource", "(", "{", "'x'", ":", "[", "]", ",", "'y'", ":", "[", "]", ",", "'width'", ":", "[", "]", ",", "'height'", ":", "[", "]", "}", ")", "# add rectangle selections", "selection_renderer", "=", "p", ".", "rect", "(", "x", "=", "'x'", ",", "y", "=", "'y'", ",", "width", "=", "'width'", ",", "height", "=", "'height'", ",", "source", "=", "rect_source", ",", "fill_alpha", "=", "0.7", ",", "fill_color", "=", "'#009933'", ")", "selection_tool", "=", "ParallelSelectionTool", "(", "renderer_select", "=", "selection_renderer", ",", "renderer_data", "=", "parallel_renderer", ",", "box_width", "=", "10", ")", "# custom resets (reset only axes not selections)", "reset_axes", "=", "ParallelResetTool", "(", ")", "# add tools and activate selection ones", "p", ".", "add_tools", "(", "selection_tool", ",", "reset_axes", ")", "p", ".", "toolbar", ".", "active_drag", "=", "selection_tool", "return", "p" ]
From a dataframe create a parallel coordinate plot
[ "From", "a", "dataframe", "create", "a", "parallel", "coordinate", "plot" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/custom/parallel_plot/parallel_plot.py#L14-L107
train
bokeh/bokeh
bokeh/server/protocol_handler.py
ProtocolHandler.handle
def handle(self, message, connection): ''' Delegate a received message to the appropriate handler. Args: message (Message) : The message that was receive that needs to be handled connection (ServerConnection) : The connection that received this message Raises: ProtocolError ''' handler = self._handlers.get((message.msgtype, message.revision)) if handler is None: handler = self._handlers.get(message.msgtype) if handler is None: raise ProtocolError("%s not expected on server" % message) try: work = yield handler(message, connection) except Exception as e: log.error("error handling message %r: %r", message, e) log.debug(" message header %r content %r", message.header, message.content, exc_info=1) work = connection.error(message, repr(e)) raise gen.Return(work)
python
def handle(self, message, connection): ''' Delegate a received message to the appropriate handler. Args: message (Message) : The message that was receive that needs to be handled connection (ServerConnection) : The connection that received this message Raises: ProtocolError ''' handler = self._handlers.get((message.msgtype, message.revision)) if handler is None: handler = self._handlers.get(message.msgtype) if handler is None: raise ProtocolError("%s not expected on server" % message) try: work = yield handler(message, connection) except Exception as e: log.error("error handling message %r: %r", message, e) log.debug(" message header %r content %r", message.header, message.content, exc_info=1) work = connection.error(message, repr(e)) raise gen.Return(work)
[ "def", "handle", "(", "self", ",", "message", ",", "connection", ")", ":", "handler", "=", "self", ".", "_handlers", ".", "get", "(", "(", "message", ".", "msgtype", ",", "message", ".", "revision", ")", ")", "if", "handler", "is", "None", ":", "handler", "=", "self", ".", "_handlers", ".", "get", "(", "message", ".", "msgtype", ")", "if", "handler", "is", "None", ":", "raise", "ProtocolError", "(", "\"%s not expected on server\"", "%", "message", ")", "try", ":", "work", "=", "yield", "handler", "(", "message", ",", "connection", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "\"error handling message %r: %r\"", ",", "message", ",", "e", ")", "log", ".", "debug", "(", "\" message header %r content %r\"", ",", "message", ".", "header", ",", "message", ".", "content", ",", "exc_info", "=", "1", ")", "work", "=", "connection", ".", "error", "(", "message", ",", "repr", "(", "e", ")", ")", "raise", "gen", ".", "Return", "(", "work", ")" ]
Delegate a received message to the appropriate handler. Args: message (Message) : The message that was receive that needs to be handled connection (ServerConnection) : The connection that received this message Raises: ProtocolError
[ "Delegate", "a", "received", "message", "to", "the", "appropriate", "handler", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/protocol_handler.py#L76-L105
train
bokeh/bokeh
bokeh/server/session.py
_needs_document_lock
def _needs_document_lock(func): '''Decorator that adds the necessary locking and post-processing to manipulate the session's document. Expects to decorate a method on ServerSession and transforms it into a coroutine if it wasn't already. ''' @gen.coroutine def _needs_document_lock_wrapper(self, *args, **kwargs): # while we wait for and hold the lock, prevent the session # from being discarded. This avoids potential weirdness # with the session vanishing in the middle of some async # task. if self.destroyed: log.debug("Ignoring locked callback on already-destroyed session.") raise gen.Return(None) self.block_expiration() try: with (yield self._lock.acquire()): if self._pending_writes is not None: raise RuntimeError("internal class invariant violated: _pending_writes " + \ "should be None if lock is not held") self._pending_writes = [] try: result = yield yield_for_all_futures(func(self, *args, **kwargs)) finally: # we want to be very sure we reset this or we'll # keep hitting the RuntimeError above as soon as # any callback goes wrong pending_writes = self._pending_writes self._pending_writes = None for p in pending_writes: yield p raise gen.Return(result) finally: self.unblock_expiration() return _needs_document_lock_wrapper
python
def _needs_document_lock(func): '''Decorator that adds the necessary locking and post-processing to manipulate the session's document. Expects to decorate a method on ServerSession and transforms it into a coroutine if it wasn't already. ''' @gen.coroutine def _needs_document_lock_wrapper(self, *args, **kwargs): # while we wait for and hold the lock, prevent the session # from being discarded. This avoids potential weirdness # with the session vanishing in the middle of some async # task. if self.destroyed: log.debug("Ignoring locked callback on already-destroyed session.") raise gen.Return(None) self.block_expiration() try: with (yield self._lock.acquire()): if self._pending_writes is not None: raise RuntimeError("internal class invariant violated: _pending_writes " + \ "should be None if lock is not held") self._pending_writes = [] try: result = yield yield_for_all_futures(func(self, *args, **kwargs)) finally: # we want to be very sure we reset this or we'll # keep hitting the RuntimeError above as soon as # any callback goes wrong pending_writes = self._pending_writes self._pending_writes = None for p in pending_writes: yield p raise gen.Return(result) finally: self.unblock_expiration() return _needs_document_lock_wrapper
[ "def", "_needs_document_lock", "(", "func", ")", ":", "@", "gen", ".", "coroutine", "def", "_needs_document_lock_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# while we wait for and hold the lock, prevent the session", "# from being discarded. This avoids potential weirdness", "# with the session vanishing in the middle of some async", "# task.", "if", "self", ".", "destroyed", ":", "log", ".", "debug", "(", "\"Ignoring locked callback on already-destroyed session.\"", ")", "raise", "gen", ".", "Return", "(", "None", ")", "self", ".", "block_expiration", "(", ")", "try", ":", "with", "(", "yield", "self", ".", "_lock", ".", "acquire", "(", ")", ")", ":", "if", "self", ".", "_pending_writes", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"internal class invariant violated: _pending_writes \"", "+", "\"should be None if lock is not held\"", ")", "self", ".", "_pending_writes", "=", "[", "]", "try", ":", "result", "=", "yield", "yield_for_all_futures", "(", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "finally", ":", "# we want to be very sure we reset this or we'll", "# keep hitting the RuntimeError above as soon as", "# any callback goes wrong", "pending_writes", "=", "self", ".", "_pending_writes", "self", ".", "_pending_writes", "=", "None", "for", "p", "in", "pending_writes", ":", "yield", "p", "raise", "gen", ".", "Return", "(", "result", ")", "finally", ":", "self", ".", "unblock_expiration", "(", ")", "return", "_needs_document_lock_wrapper" ]
Decorator that adds the necessary locking and post-processing to manipulate the session's document. Expects to decorate a method on ServerSession and transforms it into a coroutine if it wasn't already.
[ "Decorator", "that", "adds", "the", "necessary", "locking", "and", "post", "-", "processing", "to", "manipulate", "the", "session", "s", "document", ".", "Expects", "to", "decorate", "a", "method", "on", "ServerSession", "and", "transforms", "it", "into", "a", "coroutine", "if", "it", "wasn", "t", "already", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/session.py#L47-L82
train
bokeh/bokeh
bokeh/server/session.py
ServerSession.unsubscribe
def unsubscribe(self, connection): """This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken""" self._subscribed_connections.discard(connection) self._last_unsubscribe_time = current_time()
python
def unsubscribe(self, connection): """This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken""" self._subscribed_connections.discard(connection) self._last_unsubscribe_time = current_time()
[ "def", "unsubscribe", "(", "self", ",", "connection", ")", ":", "self", ".", "_subscribed_connections", ".", "discard", "(", "connection", ")", "self", ".", "_last_unsubscribe_time", "=", "current_time", "(", ")" ]
This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken
[ "This", "should", "only", "be", "called", "by", "ServerConnection", ".", "unsubscribe_session", "or", "our", "book", "-", "keeping", "will", "be", "broken" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/session.py#L175-L178
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_cwd
def set_cwd(self, dirname): """Set shell current working directory.""" # Replace single for double backslashes on Windows if os.name == 'nt': dirname = dirname.replace(u"\\", u"\\\\") if not self.external_kernel: code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code) self._cwd = dirname
python
def set_cwd(self, dirname): """Set shell current working directory.""" # Replace single for double backslashes on Windows if os.name == 'nt': dirname = dirname.replace(u"\\", u"\\\\") if not self.external_kernel: code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code) self._cwd = dirname
[ "def", "set_cwd", "(", "self", ",", "dirname", ")", ":", "# Replace single for double backslashes on Windows", "if", "os", ".", "name", "==", "'nt'", ":", "dirname", "=", "dirname", ".", "replace", "(", "u\"\\\\\"", ",", "u\"\\\\\\\\\"", ")", "if", "not", "self", ".", "external_kernel", ":", "code", "=", "u\"get_ipython().kernel.set_cwd(u'''{}''')\"", ".", "format", "(", "dirname", ")", "if", "self", ".", "_reading", ":", "self", ".", "kernel_client", ".", "input", "(", "u'!'", "+", "code", ")", "else", ":", "self", ".", "silent_execute", "(", "code", ")", "self", ".", "_cwd", "=", "dirname" ]
Set shell current working directory.
[ "Set", "shell", "current", "working", "directory", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L110-L122
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_bracket_matcher_color_scheme
def set_bracket_matcher_color_scheme(self, color_scheme): """Set color scheme for matched parentheses.""" bsh = sh.BaseSH(parent=self, color_scheme=color_scheme) mpcolor = bsh.get_matched_p_color() self._bracket_matcher.format.setBackground(mpcolor)
python
def set_bracket_matcher_color_scheme(self, color_scheme): """Set color scheme for matched parentheses.""" bsh = sh.BaseSH(parent=self, color_scheme=color_scheme) mpcolor = bsh.get_matched_p_color() self._bracket_matcher.format.setBackground(mpcolor)
[ "def", "set_bracket_matcher_color_scheme", "(", "self", ",", "color_scheme", ")", ":", "bsh", "=", "sh", ".", "BaseSH", "(", "parent", "=", "self", ",", "color_scheme", "=", "color_scheme", ")", "mpcolor", "=", "bsh", ".", "get_matched_p_color", "(", ")", "self", ".", "_bracket_matcher", ".", "format", ".", "setBackground", "(", "mpcolor", ")" ]
Set color scheme for matched parentheses.
[ "Set", "color", "scheme", "for", "matched", "parentheses", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L136-L140
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_color_scheme
def set_color_scheme(self, color_scheme, reset=True): """Set color scheme of the shell.""" self.set_bracket_matcher_color_scheme(color_scheme) self.style_sheet, dark_color = create_qss_style(color_scheme) self.syntax_style = color_scheme self._style_sheet_changed() self._syntax_style_changed() if reset: self.reset(clear=True) if not dark_color: self.silent_execute("%colors linux") else: self.silent_execute("%colors lightbg")
python
def set_color_scheme(self, color_scheme, reset=True): """Set color scheme of the shell.""" self.set_bracket_matcher_color_scheme(color_scheme) self.style_sheet, dark_color = create_qss_style(color_scheme) self.syntax_style = color_scheme self._style_sheet_changed() self._syntax_style_changed() if reset: self.reset(clear=True) if not dark_color: self.silent_execute("%colors linux") else: self.silent_execute("%colors lightbg")
[ "def", "set_color_scheme", "(", "self", ",", "color_scheme", ",", "reset", "=", "True", ")", ":", "self", ".", "set_bracket_matcher_color_scheme", "(", "color_scheme", ")", "self", ".", "style_sheet", ",", "dark_color", "=", "create_qss_style", "(", "color_scheme", ")", "self", ".", "syntax_style", "=", "color_scheme", "self", ".", "_style_sheet_changed", "(", ")", "self", ".", "_syntax_style_changed", "(", ")", "if", "reset", ":", "self", ".", "reset", "(", "clear", "=", "True", ")", "if", "not", "dark_color", ":", "self", ".", "silent_execute", "(", "\"%colors linux\"", ")", "else", ":", "self", ".", "silent_execute", "(", "\"%colors lightbg\"", ")" ]
Set color scheme of the shell.
[ "Set", "color", "scheme", "of", "the", "shell", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L142-L154
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.long_banner
def long_banner(self): """Banner for IPython widgets with pylab message""" # Default banner try: from IPython.core.usage import quick_guide except Exception: quick_guide = '' banner_parts = [ 'Python %s\n' % self.interpreter_versions['python_version'], 'Type "copyright", "credits" or "license" for more information.\n\n', 'IPython %s -- An enhanced Interactive Python.\n' % \ self.interpreter_versions['ipython_version'], quick_guide ] banner = ''.join(banner_parts) # Pylab additions pylab_o = self.additional_options['pylab'] autoload_pylab_o = self.additional_options['autoload_pylab'] mpl_installed = programs.is_module_installed('matplotlib') if mpl_installed and (pylab_o and autoload_pylab_o): pylab_message = ("\nPopulating the interactive namespace from " "numpy and matplotlib\n") banner = banner + pylab_message # Sympy additions sympy_o = self.additional_options['sympy'] if sympy_o: lines = """ These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) """ banner = banner + lines if (pylab_o and sympy_o): lines = """ Warning: pylab (numpy and matplotlib) and symbolic math (sympy) are both enabled at the same time. Some pylab functions are going to be overrided by the sympy module (e.g. plot) """ banner = banner + lines return banner
python
def long_banner(self): """Banner for IPython widgets with pylab message""" # Default banner try: from IPython.core.usage import quick_guide except Exception: quick_guide = '' banner_parts = [ 'Python %s\n' % self.interpreter_versions['python_version'], 'Type "copyright", "credits" or "license" for more information.\n\n', 'IPython %s -- An enhanced Interactive Python.\n' % \ self.interpreter_versions['ipython_version'], quick_guide ] banner = ''.join(banner_parts) # Pylab additions pylab_o = self.additional_options['pylab'] autoload_pylab_o = self.additional_options['autoload_pylab'] mpl_installed = programs.is_module_installed('matplotlib') if mpl_installed and (pylab_o and autoload_pylab_o): pylab_message = ("\nPopulating the interactive namespace from " "numpy and matplotlib\n") banner = banner + pylab_message # Sympy additions sympy_o = self.additional_options['sympy'] if sympy_o: lines = """ These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) """ banner = banner + lines if (pylab_o and sympy_o): lines = """ Warning: pylab (numpy and matplotlib) and symbolic math (sympy) are both enabled at the same time. Some pylab functions are going to be overrided by the sympy module (e.g. plot) """ banner = banner + lines return banner
[ "def", "long_banner", "(", "self", ")", ":", "# Default banner", "try", ":", "from", "IPython", ".", "core", ".", "usage", "import", "quick_guide", "except", "Exception", ":", "quick_guide", "=", "''", "banner_parts", "=", "[", "'Python %s\\n'", "%", "self", ".", "interpreter_versions", "[", "'python_version'", "]", ",", "'Type \"copyright\", \"credits\" or \"license\" for more information.\\n\\n'", ",", "'IPython %s -- An enhanced Interactive Python.\\n'", "%", "self", ".", "interpreter_versions", "[", "'ipython_version'", "]", ",", "quick_guide", "]", "banner", "=", "''", ".", "join", "(", "banner_parts", ")", "# Pylab additions", "pylab_o", "=", "self", ".", "additional_options", "[", "'pylab'", "]", "autoload_pylab_o", "=", "self", ".", "additional_options", "[", "'autoload_pylab'", "]", "mpl_installed", "=", "programs", ".", "is_module_installed", "(", "'matplotlib'", ")", "if", "mpl_installed", "and", "(", "pylab_o", "and", "autoload_pylab_o", ")", ":", "pylab_message", "=", "(", "\"\\nPopulating the interactive namespace from \"", "\"numpy and matplotlib\\n\"", ")", "banner", "=", "banner", "+", "pylab_message", "# Sympy additions", "sympy_o", "=", "self", ".", "additional_options", "[", "'sympy'", "]", "if", "sympy_o", ":", "lines", "=", "\"\"\"\nThese commands were executed:\n>>> from __future__ import division\n>>> from sympy import *\n>>> x, y, z, t = symbols('x y z t')\n>>> k, m, n = symbols('k m n', integer=True)\n>>> f, g, h = symbols('f g h', cls=Function)\n\"\"\"", "banner", "=", "banner", "+", "lines", "if", "(", "pylab_o", "and", "sympy_o", ")", ":", "lines", "=", "\"\"\"\nWarning: pylab (numpy and matplotlib) and symbolic math (sympy) are both \nenabled at the same time. Some pylab functions are going to be overrided by \nthe sympy module (e.g. plot)\n\"\"\"", "banner", "=", "banner", "+", "lines", "return", "banner" ]
Banner for IPython widgets with pylab message
[ "Banner", "for", "IPython", "widgets", "with", "pylab", "message" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L173-L217
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.reset_namespace
def reset_namespace(self, warning=False, message=False): """Reset the namespace by removing all names defined by the user.""" reset_str = _("Remove all variables") warn_str = _("All user-defined variables will be removed. " "Are you sure you want to proceed?") kernel_env = self.kernel_manager._kernel_spec.env if warning: box = MessageCheckBox(icon=QMessageBox.Warning, parent=self) box.setWindowTitle(reset_str) box.set_checkbox_text(_("Don't show again.")) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.Yes) box.set_checked(False) box.set_check_visible(True) box.setText(warn_str) answer = box.exec_() # Update checkbox based on user interaction CONF.set('ipython_console', 'show_reset_namespace_warning', not box.is_checked()) self.ipyclient.reset_warning = not box.is_checked() if answer != QMessageBox.Yes: return try: if self._reading: self.dbg_exec_magic('reset', '-f') else: if message: self.reset() self._append_html(_("<br><br>Removing all variables..." "\n<hr>"), before_prompt=False) self.silent_execute("%reset -f") if kernel_env.get('SPY_AUTOLOAD_PYLAB_O') == 'True': self.silent_execute("from pylab import *") if kernel_env.get('SPY_SYMPY_O') == 'True': sympy_init = """ from __future__ import division from sympy import * x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) init_printing()""" self.silent_execute(dedent(sympy_init)) if kernel_env.get('SPY_RUN_CYTHON') == 'True': self.silent_execute("%reload_ext Cython") self.refresh_namespacebrowser() if not self.external_kernel: self.silent_execute( 'get_ipython().kernel.close_all_mpl_figures()') except AttributeError: pass
python
def reset_namespace(self, warning=False, message=False): """Reset the namespace by removing all names defined by the user.""" reset_str = _("Remove all variables") warn_str = _("All user-defined variables will be removed. " "Are you sure you want to proceed?") kernel_env = self.kernel_manager._kernel_spec.env if warning: box = MessageCheckBox(icon=QMessageBox.Warning, parent=self) box.setWindowTitle(reset_str) box.set_checkbox_text(_("Don't show again.")) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.Yes) box.set_checked(False) box.set_check_visible(True) box.setText(warn_str) answer = box.exec_() # Update checkbox based on user interaction CONF.set('ipython_console', 'show_reset_namespace_warning', not box.is_checked()) self.ipyclient.reset_warning = not box.is_checked() if answer != QMessageBox.Yes: return try: if self._reading: self.dbg_exec_magic('reset', '-f') else: if message: self.reset() self._append_html(_("<br><br>Removing all variables..." "\n<hr>"), before_prompt=False) self.silent_execute("%reset -f") if kernel_env.get('SPY_AUTOLOAD_PYLAB_O') == 'True': self.silent_execute("from pylab import *") if kernel_env.get('SPY_SYMPY_O') == 'True': sympy_init = """ from __future__ import division from sympy import * x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) init_printing()""" self.silent_execute(dedent(sympy_init)) if kernel_env.get('SPY_RUN_CYTHON') == 'True': self.silent_execute("%reload_ext Cython") self.refresh_namespacebrowser() if not self.external_kernel: self.silent_execute( 'get_ipython().kernel.close_all_mpl_figures()') except AttributeError: pass
[ "def", "reset_namespace", "(", "self", ",", "warning", "=", "False", ",", "message", "=", "False", ")", ":", "reset_str", "=", "_", "(", "\"Remove all variables\"", ")", "warn_str", "=", "_", "(", "\"All user-defined variables will be removed. \"", "\"Are you sure you want to proceed?\"", ")", "kernel_env", "=", "self", ".", "kernel_manager", ".", "_kernel_spec", ".", "env", "if", "warning", ":", "box", "=", "MessageCheckBox", "(", "icon", "=", "QMessageBox", ".", "Warning", ",", "parent", "=", "self", ")", "box", ".", "setWindowTitle", "(", "reset_str", ")", "box", ".", "set_checkbox_text", "(", "_", "(", "\"Don't show again.\"", ")", ")", "box", ".", "setStandardButtons", "(", "QMessageBox", ".", "Yes", "|", "QMessageBox", ".", "No", ")", "box", ".", "setDefaultButton", "(", "QMessageBox", ".", "Yes", ")", "box", ".", "set_checked", "(", "False", ")", "box", ".", "set_check_visible", "(", "True", ")", "box", ".", "setText", "(", "warn_str", ")", "answer", "=", "box", ".", "exec_", "(", ")", "# Update checkbox based on user interaction", "CONF", ".", "set", "(", "'ipython_console'", ",", "'show_reset_namespace_warning'", ",", "not", "box", ".", "is_checked", "(", ")", ")", "self", ".", "ipyclient", ".", "reset_warning", "=", "not", "box", ".", "is_checked", "(", ")", "if", "answer", "!=", "QMessageBox", ".", "Yes", ":", "return", "try", ":", "if", "self", ".", "_reading", ":", "self", ".", "dbg_exec_magic", "(", "'reset'", ",", "'-f'", ")", "else", ":", "if", "message", ":", "self", ".", "reset", "(", ")", "self", ".", "_append_html", "(", "_", "(", "\"<br><br>Removing all variables...\"", "\"\\n<hr>\"", ")", ",", "before_prompt", "=", "False", ")", "self", ".", "silent_execute", "(", "\"%reset -f\"", ")", "if", "kernel_env", ".", "get", "(", "'SPY_AUTOLOAD_PYLAB_O'", ")", "==", "'True'", ":", "self", ".", "silent_execute", "(", "\"from pylab import *\"", ")", "if", "kernel_env", ".", "get", "(", "'SPY_SYMPY_O'", ")", "==", "'True'", ":", "sympy_init", "=", "\"\"\"\n from __future__ import division\n from sympy import *\n x, y, z, t = symbols('x y z t')\n k, m, n = symbols('k m n', integer=True)\n f, g, h = symbols('f g h', cls=Function)\n init_printing()\"\"\"", "self", ".", "silent_execute", "(", "dedent", "(", "sympy_init", ")", ")", "if", "kernel_env", ".", "get", "(", "'SPY_RUN_CYTHON'", ")", "==", "'True'", ":", "self", ".", "silent_execute", "(", "\"%reload_ext Cython\"", ")", "self", ".", "refresh_namespacebrowser", "(", ")", "if", "not", "self", ".", "external_kernel", ":", "self", ".", "silent_execute", "(", "'get_ipython().kernel.close_all_mpl_figures()'", ")", "except", "AttributeError", ":", "pass" ]
Reset the namespace by removing all names defined by the user.
[ "Reset", "the", "namespace", "by", "removing", "all", "names", "defined", "by", "the", "user", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L237-L294
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.create_shortcuts
def create_shortcuts(self): """Create shortcuts for ipyconsole.""" inspect = config_shortcut(self._control.inspect_current_object, context='Console', name='Inspect current object', parent=self) clear_console = config_shortcut(self.clear_console, context='Console', name='Clear shell', parent=self) restart_kernel = config_shortcut(self.ipyclient.restart_kernel, context='ipython_console', name='Restart kernel', parent=self) new_tab = config_shortcut(lambda: self.new_client.emit(), context='ipython_console', name='new tab', parent=self) reset_namespace = config_shortcut(lambda: self._reset_namespace(), context='ipython_console', name='reset namespace', parent=self) array_inline = config_shortcut(self._control.enter_array_inline, context='array_builder', name='enter array inline', parent=self) array_table = config_shortcut(self._control.enter_array_table, context='array_builder', name='enter array table', parent=self) clear_line = config_shortcut(self.ipyclient.clear_line, context='console', name='clear line', parent=self) return [inspect, clear_console, restart_kernel, new_tab, reset_namespace, array_inline, array_table, clear_line]
python
def create_shortcuts(self): """Create shortcuts for ipyconsole.""" inspect = config_shortcut(self._control.inspect_current_object, context='Console', name='Inspect current object', parent=self) clear_console = config_shortcut(self.clear_console, context='Console', name='Clear shell', parent=self) restart_kernel = config_shortcut(self.ipyclient.restart_kernel, context='ipython_console', name='Restart kernel', parent=self) new_tab = config_shortcut(lambda: self.new_client.emit(), context='ipython_console', name='new tab', parent=self) reset_namespace = config_shortcut(lambda: self._reset_namespace(), context='ipython_console', name='reset namespace', parent=self) array_inline = config_shortcut(self._control.enter_array_inline, context='array_builder', name='enter array inline', parent=self) array_table = config_shortcut(self._control.enter_array_table, context='array_builder', name='enter array table', parent=self) clear_line = config_shortcut(self.ipyclient.clear_line, context='console', name='clear line', parent=self) return [inspect, clear_console, restart_kernel, new_tab, reset_namespace, array_inline, array_table, clear_line]
[ "def", "create_shortcuts", "(", "self", ")", ":", "inspect", "=", "config_shortcut", "(", "self", ".", "_control", ".", "inspect_current_object", ",", "context", "=", "'Console'", ",", "name", "=", "'Inspect current object'", ",", "parent", "=", "self", ")", "clear_console", "=", "config_shortcut", "(", "self", ".", "clear_console", ",", "context", "=", "'Console'", ",", "name", "=", "'Clear shell'", ",", "parent", "=", "self", ")", "restart_kernel", "=", "config_shortcut", "(", "self", ".", "ipyclient", ".", "restart_kernel", ",", "context", "=", "'ipython_console'", ",", "name", "=", "'Restart kernel'", ",", "parent", "=", "self", ")", "new_tab", "=", "config_shortcut", "(", "lambda", ":", "self", ".", "new_client", ".", "emit", "(", ")", ",", "context", "=", "'ipython_console'", ",", "name", "=", "'new tab'", ",", "parent", "=", "self", ")", "reset_namespace", "=", "config_shortcut", "(", "lambda", ":", "self", ".", "_reset_namespace", "(", ")", ",", "context", "=", "'ipython_console'", ",", "name", "=", "'reset namespace'", ",", "parent", "=", "self", ")", "array_inline", "=", "config_shortcut", "(", "self", ".", "_control", ".", "enter_array_inline", ",", "context", "=", "'array_builder'", ",", "name", "=", "'enter array inline'", ",", "parent", "=", "self", ")", "array_table", "=", "config_shortcut", "(", "self", ".", "_control", ".", "enter_array_table", ",", "context", "=", "'array_builder'", ",", "name", "=", "'enter array table'", ",", "parent", "=", "self", ")", "clear_line", "=", "config_shortcut", "(", "self", ".", "ipyclient", ".", "clear_line", ",", "context", "=", "'console'", ",", "name", "=", "'clear line'", ",", "parent", "=", "self", ")", "return", "[", "inspect", ",", "clear_console", ",", "restart_kernel", ",", "new_tab", ",", "reset_namespace", ",", "array_inline", ",", "array_table", ",", "clear_line", "]" ]
Create shortcuts for ipyconsole.
[ "Create", "shortcuts", "for", "ipyconsole", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L296-L323
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.silent_execute
def silent_execute(self, code): """Execute code in the kernel without increasing the prompt""" try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
python
def silent_execute(self, code): """Execute code in the kernel without increasing the prompt""" try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
[ "def", "silent_execute", "(", "self", ",", "code", ")", ":", "try", ":", "self", ".", "kernel_client", ".", "execute", "(", "to_text_string", "(", "code", ")", ",", "silent", "=", "True", ")", "except", "AttributeError", ":", "pass" ]
Execute code in the kernel without increasing the prompt
[ "Execute", "code", "in", "the", "kernel", "without", "increasing", "the", "prompt" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L326-L331
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.silent_exec_method
def silent_exec_method(self, code): """Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string Code that contains the kernel method as part of its string See Also -------- handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD """ # Generate uuid, which would be used as an indication of whether or # not the unique request originated from here local_uuid = to_text_string(uuid.uuid1()) code = to_text_string(code) if self.kernel_client is None: return msg_id = self.kernel_client.execute('', silent=True, user_expressions={ local_uuid:code }) self._kernel_methods[local_uuid] = code self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_method')
python
def silent_exec_method(self, code): """Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string Code that contains the kernel method as part of its string See Also -------- handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD """ # Generate uuid, which would be used as an indication of whether or # not the unique request originated from here local_uuid = to_text_string(uuid.uuid1()) code = to_text_string(code) if self.kernel_client is None: return msg_id = self.kernel_client.execute('', silent=True, user_expressions={ local_uuid:code }) self._kernel_methods[local_uuid] = code self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_method')
[ "def", "silent_exec_method", "(", "self", ",", "code", ")", ":", "# Generate uuid, which would be used as an indication of whether or", "# not the unique request originated from here", "local_uuid", "=", "to_text_string", "(", "uuid", ".", "uuid1", "(", ")", ")", "code", "=", "to_text_string", "(", "code", ")", "if", "self", ".", "kernel_client", "is", "None", ":", "return", "msg_id", "=", "self", ".", "kernel_client", ".", "execute", "(", "''", ",", "silent", "=", "True", ",", "user_expressions", "=", "{", "local_uuid", ":", "code", "}", ")", "self", ".", "_kernel_methods", "[", "local_uuid", "]", "=", "code", "self", ".", "_request_info", "[", "'execute'", "]", "[", "msg_id", "]", "=", "self", ".", "_ExecutionRequest", "(", "msg_id", ",", "'silent_exec_method'", ")" ]
Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string Code that contains the kernel method as part of its string See Also -------- handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD
[ "Silently", "execute", "a", "kernel", "method", "and", "save", "its", "reply" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L333-L368
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.handle_exec_method
def handle_exec_method(self, msg): """ Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._kernel_methods: # Process kernel reply method = self._kernel_methods[expression] reply = user_exp[expression] data = reply.get('data') if 'get_namespace_view' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) view = ast.literal_eval(literal) else: view = None self.sig_namespace_view.emit(view) elif 'get_var_properties' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) properties = ast.literal_eval(literal) else: properties = None self.sig_var_properties.emit(properties) elif 'get_cwd' in method: if data is not None and 'text/plain' in data: self._cwd = ast.literal_eval(data['text/plain']) if PY2: self._cwd = encoding.to_unicode_from_fs(self._cwd) else: self._cwd = '' self.sig_change_cwd.emit(self._cwd) elif 'get_syspath' in method: if data is not None and 'text/plain' in data: syspath = ast.literal_eval(data['text/plain']) else: syspath = None self.sig_show_syspath.emit(syspath) elif 'get_env' in method: if data is not None and 'text/plain' in data: env = ast.literal_eval(data['text/plain']) else: env = None self.sig_show_env.emit(env) elif 'getattr' in method: if data is not None and 'text/plain' in data: is_spyder_kernel = data['text/plain'] if 'SpyderKernel' in is_spyder_kernel: self.sig_is_spykernel.emit(self) else: if data is not None and 'text/plain' in data: self._kernel_reply = ast.literal_eval(data['text/plain']) else: self._kernel_reply = None self.sig_got_reply.emit() # Remove method after being processed self._kernel_methods.pop(expression)
python
def handle_exec_method(self, msg): """ Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._kernel_methods: # Process kernel reply method = self._kernel_methods[expression] reply = user_exp[expression] data = reply.get('data') if 'get_namespace_view' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) view = ast.literal_eval(literal) else: view = None self.sig_namespace_view.emit(view) elif 'get_var_properties' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) properties = ast.literal_eval(literal) else: properties = None self.sig_var_properties.emit(properties) elif 'get_cwd' in method: if data is not None and 'text/plain' in data: self._cwd = ast.literal_eval(data['text/plain']) if PY2: self._cwd = encoding.to_unicode_from_fs(self._cwd) else: self._cwd = '' self.sig_change_cwd.emit(self._cwd) elif 'get_syspath' in method: if data is not None and 'text/plain' in data: syspath = ast.literal_eval(data['text/plain']) else: syspath = None self.sig_show_syspath.emit(syspath) elif 'get_env' in method: if data is not None and 'text/plain' in data: env = ast.literal_eval(data['text/plain']) else: env = None self.sig_show_env.emit(env) elif 'getattr' in method: if data is not None and 'text/plain' in data: is_spyder_kernel = data['text/plain'] if 'SpyderKernel' in is_spyder_kernel: self.sig_is_spykernel.emit(self) else: if data is not None and 'text/plain' in data: self._kernel_reply = ast.literal_eval(data['text/plain']) else: self._kernel_reply = None self.sig_got_reply.emit() # Remove method after being processed self._kernel_methods.pop(expression)
[ "def", "handle_exec_method", "(", "self", ",", "msg", ")", ":", "user_exp", "=", "msg", "[", "'content'", "]", ".", "get", "(", "'user_expressions'", ")", "if", "not", "user_exp", ":", "return", "for", "expression", "in", "user_exp", ":", "if", "expression", "in", "self", ".", "_kernel_methods", ":", "# Process kernel reply", "method", "=", "self", ".", "_kernel_methods", "[", "expression", "]", "reply", "=", "user_exp", "[", "expression", "]", "data", "=", "reply", ".", "get", "(", "'data'", ")", "if", "'get_namespace_view'", "in", "method", ":", "if", "data", "is", "not", "None", "and", "'text/plain'", "in", "data", ":", "literal", "=", "ast", ".", "literal_eval", "(", "data", "[", "'text/plain'", "]", ")", "view", "=", "ast", ".", "literal_eval", "(", "literal", ")", "else", ":", "view", "=", "None", "self", ".", "sig_namespace_view", ".", "emit", "(", "view", ")", "elif", "'get_var_properties'", "in", "method", ":", "if", "data", "is", "not", "None", "and", "'text/plain'", "in", "data", ":", "literal", "=", "ast", ".", "literal_eval", "(", "data", "[", "'text/plain'", "]", ")", "properties", "=", "ast", ".", "literal_eval", "(", "literal", ")", "else", ":", "properties", "=", "None", "self", ".", "sig_var_properties", ".", "emit", "(", "properties", ")", "elif", "'get_cwd'", "in", "method", ":", "if", "data", "is", "not", "None", "and", "'text/plain'", "in", "data", ":", "self", ".", "_cwd", "=", "ast", ".", "literal_eval", "(", "data", "[", "'text/plain'", "]", ")", "if", "PY2", ":", "self", ".", "_cwd", "=", "encoding", ".", "to_unicode_from_fs", "(", "self", ".", "_cwd", ")", "else", ":", "self", ".", "_cwd", "=", "''", "self", ".", "sig_change_cwd", ".", "emit", "(", "self", ".", "_cwd", ")", "elif", "'get_syspath'", "in", "method", ":", "if", "data", "is", "not", "None", "and", "'text/plain'", "in", "data", ":", "syspath", "=", "ast", ".", "literal_eval", "(", "data", "[", "'text/plain'", "]", ")", "else", ":", "syspath", "=", "None", "self", ".", "sig_show_syspath", ".", "emit", "(", "syspath", ")", "elif", "'get_env'", "in", "method", ":", "if", "data", "is", "not", "None", "and", "'text/plain'", "in", "data", ":", "env", "=", "ast", ".", "literal_eval", "(", "data", "[", "'text/plain'", "]", ")", "else", ":", "env", "=", "None", "self", ".", "sig_show_env", ".", "emit", "(", "env", ")", "elif", "'getattr'", "in", "method", ":", "if", "data", "is", "not", "None", "and", "'text/plain'", "in", "data", ":", "is_spyder_kernel", "=", "data", "[", "'text/plain'", "]", "if", "'SpyderKernel'", "in", "is_spyder_kernel", ":", "self", ".", "sig_is_spykernel", ".", "emit", "(", "self", ")", "else", ":", "if", "data", "is", "not", "None", "and", "'text/plain'", "in", "data", ":", "self", ".", "_kernel_reply", "=", "ast", ".", "literal_eval", "(", "data", "[", "'text/plain'", "]", ")", "else", ":", "self", ".", "_kernel_reply", "=", "None", "self", ".", "sig_got_reply", ".", "emit", "(", ")", "# Remove method after being processed", "self", ".", "_kernel_methods", ".", "pop", "(", "expression", ")" ]
Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD.
[ "Handle", "data", "returned", "by", "silent", "executions", "of", "kernel", "methods" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L370-L433
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_backend_for_mayavi
def set_backend_for_mayavi(self, command): """ Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """ calling_mayavi = False lines = command.splitlines() for l in lines: if not l.startswith('#'): if 'import mayavi' in l or 'from mayavi' in l: calling_mayavi = True break if calling_mayavi: message = _("Changing backend to Qt for Mayavi") self._append_plain_text(message + '\n') self.silent_execute("%gui inline\n%gui qt")
python
def set_backend_for_mayavi(self, command): """ Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """ calling_mayavi = False lines = command.splitlines() for l in lines: if not l.startswith('#'): if 'import mayavi' in l or 'from mayavi' in l: calling_mayavi = True break if calling_mayavi: message = _("Changing backend to Qt for Mayavi") self._append_plain_text(message + '\n') self.silent_execute("%gui inline\n%gui qt")
[ "def", "set_backend_for_mayavi", "(", "self", ",", "command", ")", ":", "calling_mayavi", "=", "False", "lines", "=", "command", ".", "splitlines", "(", ")", "for", "l", "in", "lines", ":", "if", "not", "l", ".", "startswith", "(", "'#'", ")", ":", "if", "'import mayavi'", "in", "l", "or", "'from mayavi'", "in", "l", ":", "calling_mayavi", "=", "True", "break", "if", "calling_mayavi", ":", "message", "=", "_", "(", "\"Changing backend to Qt for Mayavi\"", ")", "self", ".", "_append_plain_text", "(", "message", "+", "'\\n'", ")", "self", ".", "silent_execute", "(", "\"%gui inline\\n%gui qt\"", ")" ]
Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends
[ "Mayavi", "plots", "require", "the", "Qt", "backend", "so", "we", "try", "to", "detect", "if", "one", "is", "generated", "to", "change", "backends" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L435-L450
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.change_mpl_backend
def change_mpl_backend(self, command): """ If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002 """ if command.startswith('%matplotlib') and \ len(command.splitlines()) == 1: if not 'inline' in command: self.silent_execute(command)
python
def change_mpl_backend(self, command): """ If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002 """ if command.startswith('%matplotlib') and \ len(command.splitlines()) == 1: if not 'inline' in command: self.silent_execute(command)
[ "def", "change_mpl_backend", "(", "self", ",", "command", ")", ":", "if", "command", ".", "startswith", "(", "'%matplotlib'", ")", "and", "len", "(", "command", ".", "splitlines", "(", ")", ")", "==", "1", ":", "if", "not", "'inline'", "in", "command", ":", "self", ".", "silent_execute", "(", "command", ")" ]
If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002
[ "If", "the", "user", "is", "trying", "to", "change", "Matplotlib", "backends", "with", "%matplotlib", "send", "the", "same", "command", "again", "to", "the", "kernel", "to", "correctly", "change", "it", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L452-L463
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._context_menu_make
def _context_menu_make(self, pos): """Reimplement the IPython context menu""" menu = super(ShellWidget, self)._context_menu_make(pos) return self.ipyclient.add_actions_to_context_menu(menu)
python
def _context_menu_make(self, pos): """Reimplement the IPython context menu""" menu = super(ShellWidget, self)._context_menu_make(pos) return self.ipyclient.add_actions_to_context_menu(menu)
[ "def", "_context_menu_make", "(", "self", ",", "pos", ")", ":", "menu", "=", "super", "(", "ShellWidget", ",", "self", ")", ".", "_context_menu_make", "(", "pos", ")", "return", "self", ".", "ipyclient", ".", "add_actions_to_context_menu", "(", "menu", ")" ]
Reimplement the IPython context menu
[ "Reimplement", "the", "IPython", "context", "menu" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L473-L476
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._banner_default
def _banner_default(self): """ Reimplement banner creation to let the user decide if he wants a banner or not """ # Don't change banner for external kernels if self.external_kernel: return '' show_banner_o = self.additional_options['show_banner'] if show_banner_o: return self.long_banner() else: return self.short_banner()
python
def _banner_default(self): """ Reimplement banner creation to let the user decide if he wants a banner or not """ # Don't change banner for external kernels if self.external_kernel: return '' show_banner_o = self.additional_options['show_banner'] if show_banner_o: return self.long_banner() else: return self.short_banner()
[ "def", "_banner_default", "(", "self", ")", ":", "# Don't change banner for external kernels", "if", "self", ".", "external_kernel", ":", "return", "''", "show_banner_o", "=", "self", ".", "additional_options", "[", "'show_banner'", "]", "if", "show_banner_o", ":", "return", "self", ".", "long_banner", "(", ")", "else", ":", "return", "self", ".", "short_banner", "(", ")" ]
Reimplement banner creation to let the user decide if he wants a banner or not
[ "Reimplement", "banner", "creation", "to", "let", "the", "user", "decide", "if", "he", "wants", "a", "banner", "or", "not" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L478-L490
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._syntax_style_changed
def _syntax_style_changed(self): """Refresh the highlighting with the current syntax style by class.""" if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter._style = create_style_class(self.syntax_style) self._highlighter._clear_caches() else: self._highlighter.set_style_sheet(self.style_sheet)
python
def _syntax_style_changed(self): """Refresh the highlighting with the current syntax style by class.""" if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter._style = create_style_class(self.syntax_style) self._highlighter._clear_caches() else: self._highlighter.set_style_sheet(self.style_sheet)
[ "def", "_syntax_style_changed", "(", "self", ")", ":", "if", "self", ".", "_highlighter", "is", "None", ":", "# ignore premature calls", "return", "if", "self", ".", "syntax_style", ":", "self", ".", "_highlighter", ".", "_style", "=", "create_style_class", "(", "self", ".", "syntax_style", ")", "self", ".", "_highlighter", ".", "_clear_caches", "(", ")", "else", ":", "self", ".", "_highlighter", ".", "set_style_sheet", "(", "self", ".", "style_sheet", ")" ]
Refresh the highlighting with the current syntax style by class.
[ "Refresh", "the", "highlighting", "with", "the", "current", "syntax", "style", "by", "class", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L496-L505
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._prompt_started_hook
def _prompt_started_hook(self): """Emit a signal when the prompt is ready.""" if not self._reading: self._highlighter.highlighting_on = True self.sig_prompt_ready.emit()
python
def _prompt_started_hook(self): """Emit a signal when the prompt is ready.""" if not self._reading: self._highlighter.highlighting_on = True self.sig_prompt_ready.emit()
[ "def", "_prompt_started_hook", "(", "self", ")", ":", "if", "not", "self", ".", "_reading", ":", "self", ".", "_highlighter", ".", "highlighting_on", "=", "True", "self", ".", "sig_prompt_ready", ".", "emit", "(", ")" ]
Emit a signal when the prompt is ready.
[ "Emit", "a", "signal", "when", "the", "prompt", "is", "ready", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L507-L511
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.focusInEvent
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ShellWidget, self).focusInEvent(event)
python
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ShellWidget, self).focusInEvent(event)
[ "def", "focusInEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "return", "super", "(", "ShellWidget", ",", "self", ")", ".", "focusInEvent", "(", "event", ")" ]
Reimplement Qt method to send focus change notification
[ "Reimplement", "Qt", "method", "to", "send", "focus", "change", "notification" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L514-L517
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.focusOutEvent
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ShellWidget, self).focusOutEvent(event)
python
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ShellWidget, self).focusOutEvent(event)
[ "def", "focusOutEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "return", "super", "(", "ShellWidget", ",", "self", ")", ".", "focusOutEvent", "(", "event", ")" ]
Reimplement Qt method to send focus change notification
[ "Reimplement", "Qt", "method", "to", "send", "focus", "change", "notification" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L519-L522
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.register
def register(self, panel, position=Panel.Position.LEFT): """ Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel """ assert panel is not None pos_to_string = { Panel.Position.BOTTOM: 'bottom', Panel.Position.LEFT: 'left', Panel.Position.RIGHT: 'right', Panel.Position.TOP: 'top', Panel.Position.FLOATING: 'floating' } logger.debug('adding panel %s at %s' % (panel.name, pos_to_string[position])) panel.order_in_zone = len(self._panels[position]) self._panels[position][panel.name] = panel panel.position = position panel.on_install(self.editor) logger.debug('panel %s installed' % panel.name) return panel
python
def register(self, panel, position=Panel.Position.LEFT): """ Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel """ assert panel is not None pos_to_string = { Panel.Position.BOTTOM: 'bottom', Panel.Position.LEFT: 'left', Panel.Position.RIGHT: 'right', Panel.Position.TOP: 'top', Panel.Position.FLOATING: 'floating' } logger.debug('adding panel %s at %s' % (panel.name, pos_to_string[position])) panel.order_in_zone = len(self._panels[position]) self._panels[position][panel.name] = panel panel.position = position panel.on_install(self.editor) logger.debug('panel %s installed' % panel.name) return panel
[ "def", "register", "(", "self", ",", "panel", ",", "position", "=", "Panel", ".", "Position", ".", "LEFT", ")", ":", "assert", "panel", "is", "not", "None", "pos_to_string", "=", "{", "Panel", ".", "Position", ".", "BOTTOM", ":", "'bottom'", ",", "Panel", ".", "Position", ".", "LEFT", ":", "'left'", ",", "Panel", ".", "Position", ".", "RIGHT", ":", "'right'", ",", "Panel", ".", "Position", ".", "TOP", ":", "'top'", ",", "Panel", ".", "Position", ".", "FLOATING", ":", "'floating'", "}", "logger", ".", "debug", "(", "'adding panel %s at %s'", "%", "(", "panel", ".", "name", ",", "pos_to_string", "[", "position", "]", ")", ")", "panel", ".", "order_in_zone", "=", "len", "(", "self", ".", "_panels", "[", "position", "]", ")", "self", ".", "_panels", "[", "position", "]", "[", "panel", ".", "name", "]", "=", "panel", "panel", ".", "position", "=", "position", "panel", ".", "on_install", "(", "self", ".", "editor", ")", "logger", ".", "debug", "(", "'panel %s installed'", "%", "panel", ".", "name", ")", "return", "panel" ]
Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel
[ "Installs", "a", "panel", "on", "the", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L58-L81
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.remove
def remove(self, name_or_klass): """ Removes the specified panel. :param name_or_klass: Name or class of the panel to remove. :return: The removed panel """ logger.debug('removing panel %s' % name_or_klass) panel = self.get(name_or_klass) panel.on_uninstall() panel.hide() panel.setParent(None) return self._panels[panel.position].pop(panel.name, None)
python
def remove(self, name_or_klass): """ Removes the specified panel. :param name_or_klass: Name or class of the panel to remove. :return: The removed panel """ logger.debug('removing panel %s' % name_or_klass) panel = self.get(name_or_klass) panel.on_uninstall() panel.hide() panel.setParent(None) return self._panels[panel.position].pop(panel.name, None)
[ "def", "remove", "(", "self", ",", "name_or_klass", ")", ":", "logger", ".", "debug", "(", "'removing panel %s'", "%", "name_or_klass", ")", "panel", "=", "self", ".", "get", "(", "name_or_klass", ")", "panel", ".", "on_uninstall", "(", ")", "panel", ".", "hide", "(", ")", "panel", ".", "setParent", "(", "None", ")", "return", "self", ".", "_panels", "[", "panel", ".", "position", "]", ".", "pop", "(", "panel", ".", "name", ",", "None", ")" ]
Removes the specified panel. :param name_or_klass: Name or class of the panel to remove. :return: The removed panel
[ "Removes", "the", "specified", "panel", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L83-L95
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.clear
def clear(self): """Removes all panel from the CodeEditor.""" for i in range(4): while len(self._panels[i]): key = sorted(list(self._panels[i].keys()))[0] panel = self.remove(key) panel.setParent(None) panel.deleteLater()
python
def clear(self): """Removes all panel from the CodeEditor.""" for i in range(4): while len(self._panels[i]): key = sorted(list(self._panels[i].keys()))[0] panel = self.remove(key) panel.setParent(None) panel.deleteLater()
[ "def", "clear", "(", "self", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "while", "len", "(", "self", ".", "_panels", "[", "i", "]", ")", ":", "key", "=", "sorted", "(", "list", "(", "self", ".", "_panels", "[", "i", "]", ".", "keys", "(", ")", ")", ")", "[", "0", "]", "panel", "=", "self", ".", "remove", "(", "key", ")", "panel", ".", "setParent", "(", "None", ")", "panel", ".", "deleteLater", "(", ")" ]
Removes all panel from the CodeEditor.
[ "Removes", "all", "panel", "from", "the", "CodeEditor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L97-L104
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.get
def get(self, name_or_klass): """ Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance. """ if not is_text_string(name_or_klass): name_or_klass = name_or_klass.__name__ for zone in range(4): try: panel = self._panels[zone][name_or_klass] except KeyError: pass else: return panel raise KeyError(name_or_klass)
python
def get(self, name_or_klass): """ Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance. """ if not is_text_string(name_or_klass): name_or_klass = name_or_klass.__name__ for zone in range(4): try: panel = self._panels[zone][name_or_klass] except KeyError: pass else: return panel raise KeyError(name_or_klass)
[ "def", "get", "(", "self", ",", "name_or_klass", ")", ":", "if", "not", "is_text_string", "(", "name_or_klass", ")", ":", "name_or_klass", "=", "name_or_klass", ".", "__name__", "for", "zone", "in", "range", "(", "4", ")", ":", "try", ":", "panel", "=", "self", ".", "_panels", "[", "zone", "]", "[", "name_or_klass", "]", "except", "KeyError", ":", "pass", "else", ":", "return", "panel", "raise", "KeyError", "(", "name_or_klass", ")" ]
Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance.
[ "Gets", "a", "specific", "panel", "instance", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L106-L122
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.refresh
def refresh(self): """Refreshes the editor panels (resize and update margins).""" logger.debug('Refresh panels') self.resize() self._update(self.editor.contentsRect(), 0, force_update_margins=True)
python
def refresh(self): """Refreshes the editor panels (resize and update margins).""" logger.debug('Refresh panels') self.resize() self._update(self.editor.contentsRect(), 0, force_update_margins=True)
[ "def", "refresh", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Refresh panels'", ")", "self", ".", "resize", "(", ")", "self", ".", "_update", "(", "self", ".", "editor", ".", "contentsRect", "(", ")", ",", "0", ",", "force_update_margins", "=", "True", ")" ]
Refreshes the editor panels (resize and update margins).
[ "Refreshes", "the", "editor", "panels", "(", "resize", "and", "update", "margins", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L156-L161
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.resize
def resize(self): """Resizes panels.""" crect = self.editor.contentsRect() view_crect = self.editor.viewport().contentsRect() s_bottom, s_left, s_right, s_top = self._compute_zones_sizes() tw = s_left + s_right th = s_bottom + s_top w_offset = crect.width() - (view_crect.width() + tw) h_offset = crect.height() - (view_crect.height() + th) left = 0 panels = self.panels_for_zone(Panel.Position.LEFT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue panel.adjustSize() size_hint = panel.sizeHint() panel.setGeometry(crect.left() + left, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) left += size_hint.width() right = 0 panels = self.panels_for_zone(Panel.Position.RIGHT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.right() - right - size_hint.width() - w_offset, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) right += size_hint.width() top = 0 panels = self.panels_for_zone(Panel.Position.TOP) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry(crect.left(), crect.top() + top, crect.width() - w_offset, size_hint.height()) top += size_hint.height() bottom = 0 panels = self.panels_for_zone(Panel.Position.BOTTOM) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.left(), crect.bottom() - bottom - size_hint.height() - h_offset, crect.width() - w_offset, size_hint.height()) bottom += size_hint.height()
python
def resize(self): """Resizes panels.""" crect = self.editor.contentsRect() view_crect = self.editor.viewport().contentsRect() s_bottom, s_left, s_right, s_top = self._compute_zones_sizes() tw = s_left + s_right th = s_bottom + s_top w_offset = crect.width() - (view_crect.width() + tw) h_offset = crect.height() - (view_crect.height() + th) left = 0 panels = self.panels_for_zone(Panel.Position.LEFT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue panel.adjustSize() size_hint = panel.sizeHint() panel.setGeometry(crect.left() + left, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) left += size_hint.width() right = 0 panels = self.panels_for_zone(Panel.Position.RIGHT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.right() - right - size_hint.width() - w_offset, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) right += size_hint.width() top = 0 panels = self.panels_for_zone(Panel.Position.TOP) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry(crect.left(), crect.top() + top, crect.width() - w_offset, size_hint.height()) top += size_hint.height() bottom = 0 panels = self.panels_for_zone(Panel.Position.BOTTOM) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.left(), crect.bottom() - bottom - size_hint.height() - h_offset, crect.width() - w_offset, size_hint.height()) bottom += size_hint.height()
[ "def", "resize", "(", "self", ")", ":", "crect", "=", "self", ".", "editor", ".", "contentsRect", "(", ")", "view_crect", "=", "self", ".", "editor", ".", "viewport", "(", ")", ".", "contentsRect", "(", ")", "s_bottom", ",", "s_left", ",", "s_right", ",", "s_top", "=", "self", ".", "_compute_zones_sizes", "(", ")", "tw", "=", "s_left", "+", "s_right", "th", "=", "s_bottom", "+", "s_top", "w_offset", "=", "crect", ".", "width", "(", ")", "-", "(", "view_crect", ".", "width", "(", ")", "+", "tw", ")", "h_offset", "=", "crect", ".", "height", "(", ")", "-", "(", "view_crect", ".", "height", "(", ")", "+", "th", ")", "left", "=", "0", "panels", "=", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "LEFT", ")", "panels", ".", "sort", "(", "key", "=", "lambda", "panel", ":", "panel", ".", "order_in_zone", ",", "reverse", "=", "True", ")", "for", "panel", "in", "panels", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "panel", ".", "adjustSize", "(", ")", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "panel", ".", "setGeometry", "(", "crect", ".", "left", "(", ")", "+", "left", ",", "crect", ".", "top", "(", ")", "+", "s_top", ",", "size_hint", ".", "width", "(", ")", ",", "crect", ".", "height", "(", ")", "-", "s_bottom", "-", "s_top", "-", "h_offset", ")", "left", "+=", "size_hint", ".", "width", "(", ")", "right", "=", "0", "panels", "=", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "RIGHT", ")", "panels", ".", "sort", "(", "key", "=", "lambda", "panel", ":", "panel", ".", "order_in_zone", ",", "reverse", "=", "True", ")", "for", "panel", "in", "panels", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "panel", ".", "setGeometry", "(", "crect", ".", "right", "(", ")", "-", "right", "-", "size_hint", ".", "width", "(", ")", "-", "w_offset", ",", "crect", ".", "top", "(", ")", "+", "s_top", ",", "size_hint", ".", "width", "(", ")", ",", "crect", ".", "height", "(", ")", "-", "s_bottom", "-", "s_top", "-", "h_offset", ")", "right", "+=", "size_hint", ".", "width", "(", ")", "top", "=", "0", "panels", "=", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "TOP", ")", "panels", ".", "sort", "(", "key", "=", "lambda", "panel", ":", "panel", ".", "order_in_zone", ")", "for", "panel", "in", "panels", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "panel", ".", "setGeometry", "(", "crect", ".", "left", "(", ")", ",", "crect", ".", "top", "(", ")", "+", "top", ",", "crect", ".", "width", "(", ")", "-", "w_offset", ",", "size_hint", ".", "height", "(", ")", ")", "top", "+=", "size_hint", ".", "height", "(", ")", "bottom", "=", "0", "panels", "=", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "BOTTOM", ")", "panels", ".", "sort", "(", "key", "=", "lambda", "panel", ":", "panel", ".", "order_in_zone", ")", "for", "panel", "in", "panels", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "panel", ".", "setGeometry", "(", "crect", ".", "left", "(", ")", ",", "crect", ".", "bottom", "(", ")", "-", "bottom", "-", "size_hint", ".", "height", "(", ")", "-", "h_offset", ",", "crect", ".", "width", "(", ")", "-", "w_offset", ",", "size_hint", ".", "height", "(", ")", ")", "bottom", "+=", "size_hint", ".", "height", "(", ")" ]
Resizes panels.
[ "Resizes", "panels", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L163-L222
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.update_floating_panels
def update_floating_panels(self): """Update foating panels.""" crect = self.editor.contentsRect() panels = self.panels_for_zone(Panel.Position.FLOATING) for panel in panels: if not panel.isVisible(): continue panel.set_geometry(crect)
python
def update_floating_panels(self): """Update foating panels.""" crect = self.editor.contentsRect() panels = self.panels_for_zone(Panel.Position.FLOATING) for panel in panels: if not panel.isVisible(): continue panel.set_geometry(crect)
[ "def", "update_floating_panels", "(", "self", ")", ":", "crect", "=", "self", ".", "editor", ".", "contentsRect", "(", ")", "panels", "=", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "FLOATING", ")", "for", "panel", "in", "panels", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "panel", ".", "set_geometry", "(", "crect", ")" ]
Update foating panels.
[ "Update", "foating", "panels", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L224-L231
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager._update_viewport_margins
def _update_viewport_margins(self): """Update viewport margins.""" top = 0 left = 0 right = 0 bottom = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if panel.isVisible(): width = panel.sizeHint().width() left += width for panel in self.panels_for_zone(Panel.Position.RIGHT): if panel.isVisible(): width = panel.sizeHint().width() right += width for panel in self.panels_for_zone(Panel.Position.TOP): if panel.isVisible(): height = panel.sizeHint().height() top += height for panel in self.panels_for_zone(Panel.Position.BOTTOM): if panel.isVisible(): height = panel.sizeHint().height() bottom += height self._margin_sizes = (top, left, right, bottom) self.editor.setViewportMargins(left, top, right, bottom)
python
def _update_viewport_margins(self): """Update viewport margins.""" top = 0 left = 0 right = 0 bottom = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if panel.isVisible(): width = panel.sizeHint().width() left += width for panel in self.panels_for_zone(Panel.Position.RIGHT): if panel.isVisible(): width = panel.sizeHint().width() right += width for panel in self.panels_for_zone(Panel.Position.TOP): if panel.isVisible(): height = panel.sizeHint().height() top += height for panel in self.panels_for_zone(Panel.Position.BOTTOM): if panel.isVisible(): height = panel.sizeHint().height() bottom += height self._margin_sizes = (top, left, right, bottom) self.editor.setViewportMargins(left, top, right, bottom)
[ "def", "_update_viewport_margins", "(", "self", ")", ":", "top", "=", "0", "left", "=", "0", "right", "=", "0", "bottom", "=", "0", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "LEFT", ")", ":", "if", "panel", ".", "isVisible", "(", ")", ":", "width", "=", "panel", ".", "sizeHint", "(", ")", ".", "width", "(", ")", "left", "+=", "width", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "RIGHT", ")", ":", "if", "panel", ".", "isVisible", "(", ")", ":", "width", "=", "panel", ".", "sizeHint", "(", ")", ".", "width", "(", ")", "right", "+=", "width", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "TOP", ")", ":", "if", "panel", ".", "isVisible", "(", ")", ":", "height", "=", "panel", ".", "sizeHint", "(", ")", ".", "height", "(", ")", "top", "+=", "height", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "BOTTOM", ")", ":", "if", "panel", ".", "isVisible", "(", ")", ":", "height", "=", "panel", ".", "sizeHint", "(", ")", ".", "height", "(", ")", "bottom", "+=", "height", "self", ".", "_margin_sizes", "=", "(", "top", ",", "left", ",", "right", ",", "bottom", ")", "self", ".", "editor", ".", "setViewportMargins", "(", "left", ",", "top", ",", "right", ",", "bottom", ")" ]
Update viewport margins.
[ "Update", "viewport", "margins", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L255-L278
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager._compute_zones_sizes
def _compute_zones_sizes(self): """Compute panel zone sizes.""" # Left panels left = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if not panel.isVisible(): continue size_hint = panel.sizeHint() left += size_hint.width() # Right panels right = 0 for panel in self.panels_for_zone(Panel.Position.RIGHT): if not panel.isVisible(): continue size_hint = panel.sizeHint() right += size_hint.width() # Top panels top = 0 for panel in self.panels_for_zone(Panel.Position.TOP): if not panel.isVisible(): continue size_hint = panel.sizeHint() top += size_hint.height() # Bottom panels bottom = 0 for panel in self.panels_for_zone(Panel.Position.BOTTOM): if not panel.isVisible(): continue size_hint = panel.sizeHint() bottom += size_hint.height() self._top, self._left, self._right, self._bottom = ( top, left, right, bottom) return bottom, left, right, top
python
def _compute_zones_sizes(self): """Compute panel zone sizes.""" # Left panels left = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if not panel.isVisible(): continue size_hint = panel.sizeHint() left += size_hint.width() # Right panels right = 0 for panel in self.panels_for_zone(Panel.Position.RIGHT): if not panel.isVisible(): continue size_hint = panel.sizeHint() right += size_hint.width() # Top panels top = 0 for panel in self.panels_for_zone(Panel.Position.TOP): if not panel.isVisible(): continue size_hint = panel.sizeHint() top += size_hint.height() # Bottom panels bottom = 0 for panel in self.panels_for_zone(Panel.Position.BOTTOM): if not panel.isVisible(): continue size_hint = panel.sizeHint() bottom += size_hint.height() self._top, self._left, self._right, self._bottom = ( top, left, right, bottom) return bottom, left, right, top
[ "def", "_compute_zones_sizes", "(", "self", ")", ":", "# Left panels", "left", "=", "0", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "LEFT", ")", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "left", "+=", "size_hint", ".", "width", "(", ")", "# Right panels", "right", "=", "0", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "RIGHT", ")", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "right", "+=", "size_hint", ".", "width", "(", ")", "# Top panels", "top", "=", "0", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "TOP", ")", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "top", "+=", "size_hint", ".", "height", "(", ")", "# Bottom panels", "bottom", "=", "0", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "BOTTOM", ")", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", "continue", "size_hint", "=", "panel", ".", "sizeHint", "(", ")", "bottom", "+=", "size_hint", ".", "height", "(", ")", "self", ".", "_top", ",", "self", ".", "_left", ",", "self", ".", "_right", ",", "self", ".", "_bottom", "=", "(", "top", ",", "left", ",", "right", ",", "bottom", ")", "return", "bottom", ",", "left", ",", "right", ",", "top" ]
Compute panel zone sizes.
[ "Compute", "panel", "zone", "sizes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L291-L323
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
python_like_mod_finder
def python_like_mod_finder(import_line, alt_path=None, stop_token=None): """ Locate a module path based on an import line in an python-like file import_line is the line of source code containing the import alt_path specifies an alternate base path for the module stop_token specifies the desired name to stop on This is used to a find the path to python-like modules (e.g. cython and enaml) for a goto definition. """ if stop_token and '.' in stop_token: stop_token = stop_token.split('.')[-1] tokens = re.split(r'\W', import_line) if tokens[0] in ['from', 'import']: # find the base location try: _, path, _ = imp.find_module(tokens[1]) except ImportError: if alt_path: path = osp.join(alt_path, tokens[1]) else: path = None if path: path = osp.realpath(path) if not tokens[1] == stop_token: for part in tokens[2:]: if part in ['import', 'cimport', 'as']: break path = osp.join(path, part) if part == stop_token: break # from package import module if stop_token and not stop_token in path: for ext in python_like_exts(): fname = '%s%s' % (stop_token, ext) if osp.exists(osp.join(path, fname)): return osp.join(path, fname) # from module import name for ext in python_like_exts(): fname = '%s%s' % (path, ext) if osp.exists(fname): return fname # if it is a file, return it if osp.exists(path) and not osp.isdir(path): return path # default to the package file path = osp.join(path, '__init__.py') if osp.exists(path): return path
python
def python_like_mod_finder(import_line, alt_path=None, stop_token=None): """ Locate a module path based on an import line in an python-like file import_line is the line of source code containing the import alt_path specifies an alternate base path for the module stop_token specifies the desired name to stop on This is used to a find the path to python-like modules (e.g. cython and enaml) for a goto definition. """ if stop_token and '.' in stop_token: stop_token = stop_token.split('.')[-1] tokens = re.split(r'\W', import_line) if tokens[0] in ['from', 'import']: # find the base location try: _, path, _ = imp.find_module(tokens[1]) except ImportError: if alt_path: path = osp.join(alt_path, tokens[1]) else: path = None if path: path = osp.realpath(path) if not tokens[1] == stop_token: for part in tokens[2:]: if part in ['import', 'cimport', 'as']: break path = osp.join(path, part) if part == stop_token: break # from package import module if stop_token and not stop_token in path: for ext in python_like_exts(): fname = '%s%s' % (stop_token, ext) if osp.exists(osp.join(path, fname)): return osp.join(path, fname) # from module import name for ext in python_like_exts(): fname = '%s%s' % (path, ext) if osp.exists(fname): return fname # if it is a file, return it if osp.exists(path) and not osp.isdir(path): return path # default to the package file path = osp.join(path, '__init__.py') if osp.exists(path): return path
[ "def", "python_like_mod_finder", "(", "import_line", ",", "alt_path", "=", "None", ",", "stop_token", "=", "None", ")", ":", "if", "stop_token", "and", "'.'", "in", "stop_token", ":", "stop_token", "=", "stop_token", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "tokens", "=", "re", ".", "split", "(", "r'\\W'", ",", "import_line", ")", "if", "tokens", "[", "0", "]", "in", "[", "'from'", ",", "'import'", "]", ":", "# find the base location\r", "try", ":", "_", ",", "path", ",", "_", "=", "imp", ".", "find_module", "(", "tokens", "[", "1", "]", ")", "except", "ImportError", ":", "if", "alt_path", ":", "path", "=", "osp", ".", "join", "(", "alt_path", ",", "tokens", "[", "1", "]", ")", "else", ":", "path", "=", "None", "if", "path", ":", "path", "=", "osp", ".", "realpath", "(", "path", ")", "if", "not", "tokens", "[", "1", "]", "==", "stop_token", ":", "for", "part", "in", "tokens", "[", "2", ":", "]", ":", "if", "part", "in", "[", "'import'", ",", "'cimport'", ",", "'as'", "]", ":", "break", "path", "=", "osp", ".", "join", "(", "path", ",", "part", ")", "if", "part", "==", "stop_token", ":", "break", "# from package import module\r", "if", "stop_token", "and", "not", "stop_token", "in", "path", ":", "for", "ext", "in", "python_like_exts", "(", ")", ":", "fname", "=", "'%s%s'", "%", "(", "stop_token", ",", "ext", ")", "if", "osp", ".", "exists", "(", "osp", ".", "join", "(", "path", ",", "fname", ")", ")", ":", "return", "osp", ".", "join", "(", "path", ",", "fname", ")", "# from module import name\r", "for", "ext", "in", "python_like_exts", "(", ")", ":", "fname", "=", "'%s%s'", "%", "(", "path", ",", "ext", ")", "if", "osp", ".", "exists", "(", "fname", ")", ":", "return", "fname", "# if it is a file, return it\r", "if", "osp", ".", "exists", "(", "path", ")", "and", "not", "osp", ".", "isdir", "(", "path", ")", ":", "return", "path", "# default to the package file\r", "path", "=", "osp", ".", "join", "(", "path", ",", "'__init__.py'", ")", "if", "osp", ".", "exists", "(", "path", ")", ":", "return", "path" ]
Locate a module path based on an import line in an python-like file import_line is the line of source code containing the import alt_path specifies an alternate base path for the module stop_token specifies the desired name to stop on This is used to a find the path to python-like modules (e.g. cython and enaml) for a goto definition.
[ "Locate", "a", "module", "path", "based", "on", "an", "import", "line", "in", "an", "python", "-", "like", "file", "import_line", "is", "the", "line", "of", "source", "code", "containing", "the", "import", "alt_path", "specifies", "an", "alternate", "base", "path", "for", "the", "module", "stop_token", "specifies", "the", "desired", "name", "to", "stop", "on", "This", "is", "used", "to", "a", "find", "the", "path", "to", "python", "-", "like", "modules", "(", "e", ".", "g", ".", "cython", "and", "enaml", ")", "for", "a", "goto", "definition", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L148-L198
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
get_definition_with_regex
def get_definition_with_regex(source, token, start_line=-1): """ Find the definition of an object within a source closest to a given line """ if not token: return None if DEBUG_EDITOR: t0 = time.time() patterns = [ # python / cython keyword definitions r'^c?import.*\W{0}{1}', r'from.*\W{0}\W.*c?import ', r'from .* c?import.*\W{0}{1}', r'class\s*{0}{1}', r'c?p?def[^=]*\W{0}{1}', r'cdef.*\[.*\].*\W{0}{1}', # enaml keyword definitions r'enamldef.*\W{0}{1}', r'attr.*\W{0}{1}', r'event.*\W{0}{1}', r'id\s*:.*\W{0}{1}'] matches = get_matches(patterns, source, token, start_line) if not matches: patterns = [r'.*\Wself.{0}{1}[^=!<>]*=[^=]', r'.*\W{0}{1}[^=!<>]*=[^=]', r'self.{0}{1}[^=!<>]*=[^=]', r'{0}{1}[^=!<>]*=[^=]'] matches = get_matches(patterns, source, token, start_line) # find the one closest to the start line (prefer before the start line) if matches: min_dist = len(source.splitlines()) best_ind = 0 for match in matches: dist = abs(start_line - match) if match <= start_line or not best_ind: if dist < min_dist: min_dist = dist best_ind = match if matches: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition match', t0) return best_ind else: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition failed match', t0) return None
python
def get_definition_with_regex(source, token, start_line=-1): """ Find the definition of an object within a source closest to a given line """ if not token: return None if DEBUG_EDITOR: t0 = time.time() patterns = [ # python / cython keyword definitions r'^c?import.*\W{0}{1}', r'from.*\W{0}\W.*c?import ', r'from .* c?import.*\W{0}{1}', r'class\s*{0}{1}', r'c?p?def[^=]*\W{0}{1}', r'cdef.*\[.*\].*\W{0}{1}', # enaml keyword definitions r'enamldef.*\W{0}{1}', r'attr.*\W{0}{1}', r'event.*\W{0}{1}', r'id\s*:.*\W{0}{1}'] matches = get_matches(patterns, source, token, start_line) if not matches: patterns = [r'.*\Wself.{0}{1}[^=!<>]*=[^=]', r'.*\W{0}{1}[^=!<>]*=[^=]', r'self.{0}{1}[^=!<>]*=[^=]', r'{0}{1}[^=!<>]*=[^=]'] matches = get_matches(patterns, source, token, start_line) # find the one closest to the start line (prefer before the start line) if matches: min_dist = len(source.splitlines()) best_ind = 0 for match in matches: dist = abs(start_line - match) if match <= start_line or not best_ind: if dist < min_dist: min_dist = dist best_ind = match if matches: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition match', t0) return best_ind else: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition failed match', t0) return None
[ "def", "get_definition_with_regex", "(", "source", ",", "token", ",", "start_line", "=", "-", "1", ")", ":", "if", "not", "token", ":", "return", "None", "if", "DEBUG_EDITOR", ":", "t0", "=", "time", ".", "time", "(", ")", "patterns", "=", "[", "# python / cython keyword definitions\r", "r'^c?import.*\\W{0}{1}'", ",", "r'from.*\\W{0}\\W.*c?import '", ",", "r'from .* c?import.*\\W{0}{1}'", ",", "r'class\\s*{0}{1}'", ",", "r'c?p?def[^=]*\\W{0}{1}'", ",", "r'cdef.*\\[.*\\].*\\W{0}{1}'", ",", "# enaml keyword definitions\r", "r'enamldef.*\\W{0}{1}'", ",", "r'attr.*\\W{0}{1}'", ",", "r'event.*\\W{0}{1}'", ",", "r'id\\s*:.*\\W{0}{1}'", "]", "matches", "=", "get_matches", "(", "patterns", ",", "source", ",", "token", ",", "start_line", ")", "if", "not", "matches", ":", "patterns", "=", "[", "r'.*\\Wself.{0}{1}[^=!<>]*=[^=]'", ",", "r'.*\\W{0}{1}[^=!<>]*=[^=]'", ",", "r'self.{0}{1}[^=!<>]*=[^=]'", ",", "r'{0}{1}[^=!<>]*=[^=]'", "]", "matches", "=", "get_matches", "(", "patterns", ",", "source", ",", "token", ",", "start_line", ")", "# find the one closest to the start line (prefer before the start line)\r", "if", "matches", ":", "min_dist", "=", "len", "(", "source", ".", "splitlines", "(", ")", ")", "best_ind", "=", "0", "for", "match", "in", "matches", ":", "dist", "=", "abs", "(", "start_line", "-", "match", ")", "if", "match", "<=", "start_line", "or", "not", "best_ind", ":", "if", "dist", "<", "min_dist", ":", "min_dist", "=", "dist", "best_ind", "=", "match", "if", "matches", ":", "if", "DEBUG_EDITOR", ":", "log_dt", "(", "LOG_FILENAME", ",", "'regex definition match'", ",", "t0", ")", "return", "best_ind", "else", ":", "if", "DEBUG_EDITOR", ":", "log_dt", "(", "LOG_FILENAME", ",", "'regex definition failed match'", ",", "t0", ")", "return", "None" ]
Find the definition of an object within a source closest to a given line
[ "Find", "the", "definition", "of", "an", "object", "within", "a", "source", "closest", "to", "a", "given", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L201-L247
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
python_like_exts
def python_like_exts(): """Return a list of all python-like extensions""" exts = [] for lang in languages.PYTHON_LIKE_LANGUAGES: exts.extend(list(languages.ALL_LANGUAGES[lang])) return ['.' + ext for ext in exts]
python
def python_like_exts(): """Return a list of all python-like extensions""" exts = [] for lang in languages.PYTHON_LIKE_LANGUAGES: exts.extend(list(languages.ALL_LANGUAGES[lang])) return ['.' + ext for ext in exts]
[ "def", "python_like_exts", "(", ")", ":", "exts", "=", "[", "]", "for", "lang", "in", "languages", ".", "PYTHON_LIKE_LANGUAGES", ":", "exts", ".", "extend", "(", "list", "(", "languages", ".", "ALL_LANGUAGES", "[", "lang", "]", ")", ")", "return", "[", "'.'", "+", "ext", "for", "ext", "in", "exts", "]" ]
Return a list of all python-like extensions
[ "Return", "a", "list", "of", "all", "python", "-", "like", "extensions" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L265-L270
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
all_editable_exts
def all_editable_exts(): """Return a list of all editable extensions""" exts = [] for (language, extensions) in languages.ALL_LANGUAGES.items(): exts.extend(list(extensions)) return ['.' + ext for ext in exts]
python
def all_editable_exts(): """Return a list of all editable extensions""" exts = [] for (language, extensions) in languages.ALL_LANGUAGES.items(): exts.extend(list(extensions)) return ['.' + ext for ext in exts]
[ "def", "all_editable_exts", "(", ")", ":", "exts", "=", "[", "]", "for", "(", "language", ",", "extensions", ")", "in", "languages", ".", "ALL_LANGUAGES", ".", "items", "(", ")", ":", "exts", ".", "extend", "(", "list", "(", "extensions", ")", ")", "return", "[", "'.'", "+", "ext", "for", "ext", "in", "exts", "]" ]
Return a list of all editable extensions
[ "Return", "a", "list", "of", "all", "editable", "extensions" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L273-L278
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
_complete_path
def _complete_path(path=None): """Perform completion of filesystem path. https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input """ if not path: return _listdir('.') dirname, rest = os.path.split(path) tmp = dirname if dirname else '.' res = [p for p in _listdir(tmp) if p.startswith(rest)] # more than one match, or single match which does not exist (typo) if len(res) > 1 or not os.path.exists(path): return res # resolved to a single directory, so return list of files below it if os.path.isdir(path): return [p for p in _listdir(path)] # exact file match terminates this completion return [path + ' ']
python
def _complete_path(path=None): """Perform completion of filesystem path. https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input """ if not path: return _listdir('.') dirname, rest = os.path.split(path) tmp = dirname if dirname else '.' res = [p for p in _listdir(tmp) if p.startswith(rest)] # more than one match, or single match which does not exist (typo) if len(res) > 1 or not os.path.exists(path): return res # resolved to a single directory, so return list of files below it if os.path.isdir(path): return [p for p in _listdir(path)] # exact file match terminates this completion return [path + ' ']
[ "def", "_complete_path", "(", "path", "=", "None", ")", ":", "if", "not", "path", ":", "return", "_listdir", "(", "'.'", ")", "dirname", ",", "rest", "=", "os", ".", "path", ".", "split", "(", "path", ")", "tmp", "=", "dirname", "if", "dirname", "else", "'.'", "res", "=", "[", "p", "for", "p", "in", "_listdir", "(", "tmp", ")", "if", "p", ".", "startswith", "(", "rest", ")", "]", "# more than one match, or single match which does not exist (typo)\r", "if", "len", "(", "res", ")", ">", "1", "or", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "res", "# resolved to a single directory, so return list of files below it\r", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "[", "p", "for", "p", "in", "_listdir", "(", "path", ")", "]", "# exact file match terminates this completion\r", "return", "[", "path", "+", "' '", "]" ]
Perform completion of filesystem path. https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input
[ "Perform", "completion", "of", "filesystem", "path", ".", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "5637124", "/", "tab", "-", "completion", "-", "in", "-", "pythons", "-", "raw", "-", "input" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L296-L312
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
FallbackPlugin.get_completions
def get_completions(self, info): """Return a list of (completion, type) tuples Simple completion based on python-like identifiers and whitespace """ if not info['obj']: return items = [] obj = info['obj'] if info['context']: lexer = find_lexer_for_filename(info['filename']) # get a list of token matches for the current object tokens = lexer.get_tokens(info['source_code']) for (context, token) in tokens: token = token.strip() if (context in info['context'] and token.startswith(obj) and obj != token): items.append(token) # add in keywords if not in a string if context not in Token.Literal.String: try: keywords = get_keywords(lexer) items.extend(k for k in keywords if k.startswith(obj)) except Exception: pass else: tokens = set(re.findall(info['id_regex'], info['source_code'])) items = [item for item in tokens if item.startswith(obj) and len(item) > len(obj)] if '.' in obj: start = obj.rfind('.') + 1 else: start = 0 items = [i[start:len(obj)] + i[len(obj):].split('.')[0] for i in items] # get path completions # get last word back to a space or a quote character match = re.search(r'''[ "\']([\w\.\\\\/]+)\Z''', info['line']) if match: items += _complete_path(match.groups()[0]) return [(i, '') for i in sorted(items)]
python
def get_completions(self, info): """Return a list of (completion, type) tuples Simple completion based on python-like identifiers and whitespace """ if not info['obj']: return items = [] obj = info['obj'] if info['context']: lexer = find_lexer_for_filename(info['filename']) # get a list of token matches for the current object tokens = lexer.get_tokens(info['source_code']) for (context, token) in tokens: token = token.strip() if (context in info['context'] and token.startswith(obj) and obj != token): items.append(token) # add in keywords if not in a string if context not in Token.Literal.String: try: keywords = get_keywords(lexer) items.extend(k for k in keywords if k.startswith(obj)) except Exception: pass else: tokens = set(re.findall(info['id_regex'], info['source_code'])) items = [item for item in tokens if item.startswith(obj) and len(item) > len(obj)] if '.' in obj: start = obj.rfind('.') + 1 else: start = 0 items = [i[start:len(obj)] + i[len(obj):].split('.')[0] for i in items] # get path completions # get last word back to a space or a quote character match = re.search(r'''[ "\']([\w\.\\\\/]+)\Z''', info['line']) if match: items += _complete_path(match.groups()[0]) return [(i, '') for i in sorted(items)]
[ "def", "get_completions", "(", "self", ",", "info", ")", ":", "if", "not", "info", "[", "'obj'", "]", ":", "return", "items", "=", "[", "]", "obj", "=", "info", "[", "'obj'", "]", "if", "info", "[", "'context'", "]", ":", "lexer", "=", "find_lexer_for_filename", "(", "info", "[", "'filename'", "]", ")", "# get a list of token matches for the current object\r", "tokens", "=", "lexer", ".", "get_tokens", "(", "info", "[", "'source_code'", "]", ")", "for", "(", "context", ",", "token", ")", "in", "tokens", ":", "token", "=", "token", ".", "strip", "(", ")", "if", "(", "context", "in", "info", "[", "'context'", "]", "and", "token", ".", "startswith", "(", "obj", ")", "and", "obj", "!=", "token", ")", ":", "items", ".", "append", "(", "token", ")", "# add in keywords if not in a string\r", "if", "context", "not", "in", "Token", ".", "Literal", ".", "String", ":", "try", ":", "keywords", "=", "get_keywords", "(", "lexer", ")", "items", ".", "extend", "(", "k", "for", "k", "in", "keywords", "if", "k", ".", "startswith", "(", "obj", ")", ")", "except", "Exception", ":", "pass", "else", ":", "tokens", "=", "set", "(", "re", ".", "findall", "(", "info", "[", "'id_regex'", "]", ",", "info", "[", "'source_code'", "]", ")", ")", "items", "=", "[", "item", "for", "item", "in", "tokens", "if", "item", ".", "startswith", "(", "obj", ")", "and", "len", "(", "item", ")", ">", "len", "(", "obj", ")", "]", "if", "'.'", "in", "obj", ":", "start", "=", "obj", ".", "rfind", "(", "'.'", ")", "+", "1", "else", ":", "start", "=", "0", "items", "=", "[", "i", "[", "start", ":", "len", "(", "obj", ")", "]", "+", "i", "[", "len", "(", "obj", ")", ":", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", "for", "i", "in", "items", "]", "# get path completions\r", "# get last word back to a space or a quote character\r", "match", "=", "re", ".", "search", "(", "r'''[ \"\\']([\\w\\.\\\\\\\\/]+)\\Z'''", ",", "info", "[", "'line'", "]", ")", "if", "match", ":", "items", "+=", "_complete_path", "(", "match", ".", "groups", "(", ")", "[", "0", "]", ")", "return", "[", "(", "i", ",", "''", ")", "for", "i", "in", "sorted", "(", "items", ")", "]" ]
Return a list of (completion, type) tuples Simple completion based on python-like identifiers and whitespace
[ "Return", "a", "list", "of", "(", "completion", "type", ")", "tuples", "Simple", "completion", "based", "on", "python", "-", "like", "identifiers", "and", "whitespace" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L37-L79
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
FallbackPlugin.get_definition
def get_definition(self, info): """ Find the definition for an object within a set of source code This is used to find the path of python-like modules (e.g. cython and enaml) for a goto definition """ if not info['is_python_like']: return token = info['obj'] lines = info['lines'] source_code = info['source_code'] filename = info['filename'] line_nr = None if token is None: return if '.' in token: token = token.split('.')[-1] line_nr = get_definition_with_regex(source_code, token, len(lines)) if line_nr is None: return line = info['line'] exts = python_like_exts() if not osp.splitext(filename)[-1] in exts: return filename, line_nr if line.startswith('import ') or line.startswith('from '): alt_path = osp.dirname(filename) source_file = python_like_mod_finder(line, alt_path=alt_path, stop_token=token) if (not source_file or not osp.splitext(source_file)[-1] in exts): line_nr = get_definition_with_regex(source_code, token, line_nr) return filename, line_nr mod_name = osp.basename(source_file).split('.')[0] if mod_name == token or mod_name == '__init__': return source_file, 1 else: with open(filename, 'rb') as fid: code = fid.read() code = encoding.decode(code)[0] line_nr = get_definition_with_regex(code, token) return filename, line_nr
python
def get_definition(self, info): """ Find the definition for an object within a set of source code This is used to find the path of python-like modules (e.g. cython and enaml) for a goto definition """ if not info['is_python_like']: return token = info['obj'] lines = info['lines'] source_code = info['source_code'] filename = info['filename'] line_nr = None if token is None: return if '.' in token: token = token.split('.')[-1] line_nr = get_definition_with_regex(source_code, token, len(lines)) if line_nr is None: return line = info['line'] exts = python_like_exts() if not osp.splitext(filename)[-1] in exts: return filename, line_nr if line.startswith('import ') or line.startswith('from '): alt_path = osp.dirname(filename) source_file = python_like_mod_finder(line, alt_path=alt_path, stop_token=token) if (not source_file or not osp.splitext(source_file)[-1] in exts): line_nr = get_definition_with_regex(source_code, token, line_nr) return filename, line_nr mod_name = osp.basename(source_file).split('.')[0] if mod_name == token or mod_name == '__init__': return source_file, 1 else: with open(filename, 'rb') as fid: code = fid.read() code = encoding.decode(code)[0] line_nr = get_definition_with_regex(code, token) return filename, line_nr
[ "def", "get_definition", "(", "self", ",", "info", ")", ":", "if", "not", "info", "[", "'is_python_like'", "]", ":", "return", "token", "=", "info", "[", "'obj'", "]", "lines", "=", "info", "[", "'lines'", "]", "source_code", "=", "info", "[", "'source_code'", "]", "filename", "=", "info", "[", "'filename'", "]", "line_nr", "=", "None", "if", "token", "is", "None", ":", "return", "if", "'.'", "in", "token", ":", "token", "=", "token", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "line_nr", "=", "get_definition_with_regex", "(", "source_code", ",", "token", ",", "len", "(", "lines", ")", ")", "if", "line_nr", "is", "None", ":", "return", "line", "=", "info", "[", "'line'", "]", "exts", "=", "python_like_exts", "(", ")", "if", "not", "osp", ".", "splitext", "(", "filename", ")", "[", "-", "1", "]", "in", "exts", ":", "return", "filename", ",", "line_nr", "if", "line", ".", "startswith", "(", "'import '", ")", "or", "line", ".", "startswith", "(", "'from '", ")", ":", "alt_path", "=", "osp", ".", "dirname", "(", "filename", ")", "source_file", "=", "python_like_mod_finder", "(", "line", ",", "alt_path", "=", "alt_path", ",", "stop_token", "=", "token", ")", "if", "(", "not", "source_file", "or", "not", "osp", ".", "splitext", "(", "source_file", ")", "[", "-", "1", "]", "in", "exts", ")", ":", "line_nr", "=", "get_definition_with_regex", "(", "source_code", ",", "token", ",", "line_nr", ")", "return", "filename", ",", "line_nr", "mod_name", "=", "osp", ".", "basename", "(", "source_file", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "if", "mod_name", "==", "token", "or", "mod_name", "==", "'__init__'", ":", "return", "source_file", ",", "1", "else", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fid", ":", "code", "=", "fid", ".", "read", "(", ")", "code", "=", "encoding", ".", "decode", "(", "code", ")", "[", "0", "]", "line_nr", "=", "get_definition_with_regex", "(", "code", ",", "token", ")", "return", "filename", ",", "line_nr" ]
Find the definition for an object within a set of source code This is used to find the path of python-like modules (e.g. cython and enaml) for a goto definition
[ "Find", "the", "definition", "for", "an", "object", "within", "a", "set", "of", "source", "code", "This", "is", "used", "to", "find", "the", "path", "of", "python", "-", "like", "modules", "(", "e", ".", "g", ".", "cython", "and", "enaml", ")", "for", "a", "goto", "definition" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L81-L127
train
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
FallbackPlugin.get_info
def get_info(self, info): """Get a formatted calltip and docstring from Fallback""" if info['docstring']: if info['filename']: filename = os.path.basename(info['filename']) filename = os.path.splitext(filename)[0] else: filename = '<module>' resp = dict(docstring=info['docstring'], name=filename, note='', argspec='', calltip=None) return resp else: return default_info_response()
python
def get_info(self, info): """Get a formatted calltip and docstring from Fallback""" if info['docstring']: if info['filename']: filename = os.path.basename(info['filename']) filename = os.path.splitext(filename)[0] else: filename = '<module>' resp = dict(docstring=info['docstring'], name=filename, note='', argspec='', calltip=None) return resp else: return default_info_response()
[ "def", "get_info", "(", "self", ",", "info", ")", ":", "if", "info", "[", "'docstring'", "]", ":", "if", "info", "[", "'filename'", "]", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "info", "[", "'filename'", "]", ")", "filename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "else", ":", "filename", "=", "'<module>'", "resp", "=", "dict", "(", "docstring", "=", "info", "[", "'docstring'", "]", ",", "name", "=", "filename", ",", "note", "=", "''", ",", "argspec", "=", "''", ",", "calltip", "=", "None", ")", "return", "resp", "else", ":", "return", "default_info_response", "(", ")" ]
Get a formatted calltip and docstring from Fallback
[ "Get", "a", "formatted", "calltip", "and", "docstring", "from", "Fallback" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L129-L144
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/objecteditor.py
create_dialog
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data) """ # Local import from spyder_kernels.utils.nsview import (ndarray, FakeObject, Image, is_known_type, DataFrame, Series) from spyder.plugins.variableexplorer.widgets.texteditor import TextEditor from spyder.plugins.variableexplorer.widgets.collectionseditor import ( CollectionsEditor) from spyder.plugins.variableexplorer.widgets.arrayeditor import ( ArrayEditor) if DataFrame is not FakeObject: from spyder.plugins.variableexplorer.widgets.dataframeeditor import ( DataFrameEditor) conv_func = lambda data: data readonly = not is_known_type(obj) if isinstance(obj, ndarray) and ndarray is not FakeObject: dialog = ArrayEditor() if not dialog.setup_and_check(obj, title=obj_name, readonly=readonly): return elif isinstance(obj, Image) and Image is not FakeObject \ and ndarray is not FakeObject: dialog = ArrayEditor() import numpy as np data = np.array(obj) if not dialog.setup_and_check(data, title=obj_name, readonly=readonly): return from spyder.pil_patch import Image conv_func = lambda data: Image.fromarray(data, mode=obj.mode) elif isinstance(obj, (DataFrame, Series)) and DataFrame is not FakeObject: dialog = DataFrameEditor() if not dialog.setup_and_check(obj): return elif is_text_string(obj): dialog = TextEditor(obj, title=obj_name, readonly=readonly) else: dialog = CollectionsEditor() dialog.setup(obj, title=obj_name, readonly=readonly) def end_func(dialog): return conv_func(dialog.get_value()) return dialog, end_func
python
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data) """ # Local import from spyder_kernels.utils.nsview import (ndarray, FakeObject, Image, is_known_type, DataFrame, Series) from spyder.plugins.variableexplorer.widgets.texteditor import TextEditor from spyder.plugins.variableexplorer.widgets.collectionseditor import ( CollectionsEditor) from spyder.plugins.variableexplorer.widgets.arrayeditor import ( ArrayEditor) if DataFrame is not FakeObject: from spyder.plugins.variableexplorer.widgets.dataframeeditor import ( DataFrameEditor) conv_func = lambda data: data readonly = not is_known_type(obj) if isinstance(obj, ndarray) and ndarray is not FakeObject: dialog = ArrayEditor() if not dialog.setup_and_check(obj, title=obj_name, readonly=readonly): return elif isinstance(obj, Image) and Image is not FakeObject \ and ndarray is not FakeObject: dialog = ArrayEditor() import numpy as np data = np.array(obj) if not dialog.setup_and_check(data, title=obj_name, readonly=readonly): return from spyder.pil_patch import Image conv_func = lambda data: Image.fromarray(data, mode=obj.mode) elif isinstance(obj, (DataFrame, Series)) and DataFrame is not FakeObject: dialog = DataFrameEditor() if not dialog.setup_and_check(obj): return elif is_text_string(obj): dialog = TextEditor(obj, title=obj_name, readonly=readonly) else: dialog = CollectionsEditor() dialog.setup(obj, title=obj_name, readonly=readonly) def end_func(dialog): return conv_func(dialog.get_value()) return dialog, end_func
[ "def", "create_dialog", "(", "obj", ",", "obj_name", ")", ":", "# Local import\r", "from", "spyder_kernels", ".", "utils", ".", "nsview", "import", "(", "ndarray", ",", "FakeObject", ",", "Image", ",", "is_known_type", ",", "DataFrame", ",", "Series", ")", "from", "spyder", ".", "plugins", ".", "variableexplorer", ".", "widgets", ".", "texteditor", "import", "TextEditor", "from", "spyder", ".", "plugins", ".", "variableexplorer", ".", "widgets", ".", "collectionseditor", "import", "(", "CollectionsEditor", ")", "from", "spyder", ".", "plugins", ".", "variableexplorer", ".", "widgets", ".", "arrayeditor", "import", "(", "ArrayEditor", ")", "if", "DataFrame", "is", "not", "FakeObject", ":", "from", "spyder", ".", "plugins", ".", "variableexplorer", ".", "widgets", ".", "dataframeeditor", "import", "(", "DataFrameEditor", ")", "conv_func", "=", "lambda", "data", ":", "data", "readonly", "=", "not", "is_known_type", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "ndarray", ")", "and", "ndarray", "is", "not", "FakeObject", ":", "dialog", "=", "ArrayEditor", "(", ")", "if", "not", "dialog", ".", "setup_and_check", "(", "obj", ",", "title", "=", "obj_name", ",", "readonly", "=", "readonly", ")", ":", "return", "elif", "isinstance", "(", "obj", ",", "Image", ")", "and", "Image", "is", "not", "FakeObject", "and", "ndarray", "is", "not", "FakeObject", ":", "dialog", "=", "ArrayEditor", "(", ")", "import", "numpy", "as", "np", "data", "=", "np", ".", "array", "(", "obj", ")", "if", "not", "dialog", ".", "setup_and_check", "(", "data", ",", "title", "=", "obj_name", ",", "readonly", "=", "readonly", ")", ":", "return", "from", "spyder", ".", "pil_patch", "import", "Image", "conv_func", "=", "lambda", "data", ":", "Image", ".", "fromarray", "(", "data", ",", "mode", "=", "obj", ".", "mode", ")", "elif", "isinstance", "(", "obj", ",", "(", "DataFrame", ",", "Series", ")", ")", "and", "DataFrame", "is", "not", "FakeObject", ":", "dialog", "=", "DataFrameEditor", "(", ")", "if", "not", "dialog", ".", "setup_and_check", "(", "obj", ")", ":", "return", "elif", "is_text_string", "(", "obj", ")", ":", "dialog", "=", "TextEditor", "(", "obj", ",", "title", "=", "obj_name", ",", "readonly", "=", "readonly", ")", "else", ":", "dialog", "=", "CollectionsEditor", "(", ")", "dialog", ".", "setup", "(", "obj", ",", "title", "=", "obj_name", ",", "readonly", "=", "readonly", ")", "def", "end_func", "(", "dialog", ")", ":", "return", "conv_func", "(", "dialog", ".", "get_value", "(", ")", ")", "return", "dialog", ",", "end_func" ]
Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data)
[ "Creates", "the", "editor", "dialog", "and", "returns", "a", "tuple", "(", "dialog", "func", ")", "where", "func", "is", "the", "function", "to", "be", "called", "with", "the", "dialog", "instance", "as", "argument", "after", "quitting", "the", "dialog", "box", "The", "role", "of", "this", "intermediate", "function", "is", "to", "allow", "easy", "monkey", "-", "patching", ".", "(", "uschmitt", "suggested", "this", "indirection", "here", "so", "that", "he", "can", "monkey", "patch", "oedit", "to", "show", "eMZed", "related", "data", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/objecteditor.py#L51-L103
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/objecteditor.py
oedit
def oedit(obj, modal=True, namespace=None): """Edit the object 'obj' in a GUI-based editor and return the edited copy (if Cancel is pressed, return None) The object 'obj' is a container Supported container types: dict, list, set, tuple, str/unicode or numpy.array (instantiate a new QApplication if necessary, so it can be called directly from the interpreter) """ # Local import from spyder.utils.qthelpers import qapplication app = qapplication() if modal: obj_name = '' else: assert is_text_string(obj) obj_name = obj if namespace is None: namespace = globals() keeper.set_namespace(namespace) obj = namespace[obj_name] # keep QApplication reference alive in the Python interpreter: namespace['__qapp__'] = app result = create_dialog(obj, obj_name) if result is None: return dialog, end_func = result if modal: if dialog.exec_(): return end_func(dialog) else: keeper.create_dialog(dialog, obj_name, end_func) import os if os.name == 'nt': app.exec_()
python
def oedit(obj, modal=True, namespace=None): """Edit the object 'obj' in a GUI-based editor and return the edited copy (if Cancel is pressed, return None) The object 'obj' is a container Supported container types: dict, list, set, tuple, str/unicode or numpy.array (instantiate a new QApplication if necessary, so it can be called directly from the interpreter) """ # Local import from spyder.utils.qthelpers import qapplication app = qapplication() if modal: obj_name = '' else: assert is_text_string(obj) obj_name = obj if namespace is None: namespace = globals() keeper.set_namespace(namespace) obj = namespace[obj_name] # keep QApplication reference alive in the Python interpreter: namespace['__qapp__'] = app result = create_dialog(obj, obj_name) if result is None: return dialog, end_func = result if modal: if dialog.exec_(): return end_func(dialog) else: keeper.create_dialog(dialog, obj_name, end_func) import os if os.name == 'nt': app.exec_()
[ "def", "oedit", "(", "obj", ",", "modal", "=", "True", ",", "namespace", "=", "None", ")", ":", "# Local import\r", "from", "spyder", ".", "utils", ".", "qthelpers", "import", "qapplication", "app", "=", "qapplication", "(", ")", "if", "modal", ":", "obj_name", "=", "''", "else", ":", "assert", "is_text_string", "(", "obj", ")", "obj_name", "=", "obj", "if", "namespace", "is", "None", ":", "namespace", "=", "globals", "(", ")", "keeper", ".", "set_namespace", "(", "namespace", ")", "obj", "=", "namespace", "[", "obj_name", "]", "# keep QApplication reference alive in the Python interpreter:\r", "namespace", "[", "'__qapp__'", "]", "=", "app", "result", "=", "create_dialog", "(", "obj", ",", "obj_name", ")", "if", "result", "is", "None", ":", "return", "dialog", ",", "end_func", "=", "result", "if", "modal", ":", "if", "dialog", ".", "exec_", "(", ")", ":", "return", "end_func", "(", "dialog", ")", "else", ":", "keeper", ".", "create_dialog", "(", "dialog", ",", "obj_name", ",", "end_func", ")", "import", "os", "if", "os", ".", "name", "==", "'nt'", ":", "app", ".", "exec_", "(", ")" ]
Edit the object 'obj' in a GUI-based editor and return the edited copy (if Cancel is pressed, return None) The object 'obj' is a container Supported container types: dict, list, set, tuple, str/unicode or numpy.array (instantiate a new QApplication if necessary, so it can be called directly from the interpreter)
[ "Edit", "the", "object", "obj", "in", "a", "GUI", "-", "based", "editor", "and", "return", "the", "edited", "copy", "(", "if", "Cancel", "is", "pressed", "return", "None", ")", "The", "object", "obj", "is", "a", "container", "Supported", "container", "types", ":", "dict", "list", "set", "tuple", "str", "/", "unicode", "or", "numpy", ".", "array", "(", "instantiate", "a", "new", "QApplication", "if", "necessary", "so", "it", "can", "be", "called", "directly", "from", "the", "interpreter", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/objecteditor.py#L106-L146
train
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
get_item_children
def get_item_children(item): """Return a sorted list of all the children items of 'item'.""" children = [item.child(index) for index in range(item.childCount())] for child in children[:]: others = get_item_children(child) if others is not None: children += others return sorted(children, key=lambda child: child.line)
python
def get_item_children(item): """Return a sorted list of all the children items of 'item'.""" children = [item.child(index) for index in range(item.childCount())] for child in children[:]: others = get_item_children(child) if others is not None: children += others return sorted(children, key=lambda child: child.line)
[ "def", "get_item_children", "(", "item", ")", ":", "children", "=", "[", "item", ".", "child", "(", "index", ")", "for", "index", "in", "range", "(", "item", ".", "childCount", "(", ")", ")", "]", "for", "child", "in", "children", "[", ":", "]", ":", "others", "=", "get_item_children", "(", "child", ")", "if", "others", "is", "not", "None", ":", "children", "+=", "others", "return", "sorted", "(", "children", ",", "key", "=", "lambda", "child", ":", "child", ".", "line", ")" ]
Return a sorted list of all the children items of 'item'.
[ "Return", "a", "sorted", "list", "of", "all", "the", "children", "items", "of", "item", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L121-L128
train