INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
First undo normalization and then clip to the user-specified min/max range.
def project_result(self, X): """ First undo normalization and then clip to the user-specified min/max range. """ X = np.asarray(X) if self.normalizer is not None: X = self.normalizer.inverse_transform(X) return self.clip(X)
Fit the imputer and then transform input `X` Note: all imputations should have a `fit_transform` method, but only some (like IterativeImputer) also support inductive mode using `fit` or `fit_transform` on `X_train` and then `transform` on new `X_test`.
def fit_transform(self, X, y=None): """ Fit the imputer and then transform input `X` Note: all imputations should have a `fit_transform` method, but only some (like IterativeImputer) also support inductive mode using `fit` or `fit_transform` on `X_train` and then `transform` ...
Transform input `X`. Note: all imputations should have a `fit_transform` method, but only some (like IterativeImputer) also support inductive mode using `fit` or `fit_transform` on `X_train` and then `transform` on new `X_test`.
def transform(self, X, y=None): """ Transform input `X`. Note: all imputations should have a `fit_transform` method, but only some (like IterativeImputer) also support inductive mode using `fit` or `fit_transform` on `X_train` and then `transform` on new `X_test`. ...
Rescale the range of values in images to be between [0, 1]
def rescale_pixel_values(images, order="C"): """ Rescale the range of values in images to be between [0, 1] """ images = np.asarray(images, order=order).astype("float32") images -= images.min() images /= images.max() return images
Generator for (rank, name, MSE, MAE) sorted by increasing MAE
def sorted_errors(self): """ Generator for (rank, name, MSE, MAE) sorted by increasing MAE """ for i, (name, mae) in enumerate( sorted(self.mae_dict.items(), key=lambda x: x[1])): yield(i + 1, name, self.mse_dict[name], self.mae_dict[name],)
Tests if x is NaN This function is meant to overcome the issue that np.isnan does not allow non-numerical types as input, and that np.nan is not np.float('nan'). Parameters ---------- x : any type Returns ------- boolean Examples -------- >>> is_scalar_nan(np.nan) True ...
def is_scalar_nan(x): """Tests if x is NaN This function is meant to overcome the issue that np.isnan does not allow non-numerical types as input, and that np.nan is not np.float('nan'). Parameters ---------- x : any type Returns ------- boolean Examples -------- >>> is_s...
Compute the boolean mask X == missing_values.
def _get_mask(X, value_to_mask): """Compute the boolean mask X == missing_values.""" if is_scalar_nan(value_to_mask): if X.dtype.kind == "f": return np.isnan(X) elif X.dtype.kind in ("i", "u"): # can't have NaNs in integer array. return np.zeros(X.shape, dtype...
Compute the most frequent value in a 1d array extended with [extra_value] * n_repeat, where extra_value is assumed to be not part of the array.
def _most_frequent(array, extra_value, n_repeat): """Compute the most frequent value in a 1d array extended with [extra_value] * n_repeat, where extra_value is assumed to be not part of the array.""" # Compute the most frequent value in array only if array.size > 0: with warnings.catch...
Fit the imputer on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Input data, where ``n_samples`` is the number of samples and ``n_features`` is the number of features. Returns ------- self : _SimpleImpute...
def fit(self, X, y=None): """Fit the imputer on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Input data, where ``n_samples`` is the number of samples and ``n_features`` is the number of features. Returns ...
Fit the transformer on sparse data.
def _sparse_fit(self, X, strategy, missing_values, fill_value): """Fit the transformer on sparse data.""" mask_data = _get_mask(X.data, missing_values) n_implicit_zeros = X.shape[0] - np.diff(X.indptr) statistics = np.empty(X.shape[1]) if strategy == "constant": # f...
Fit the transformer on dense data.
def _dense_fit(self, X, strategy, missing_values, fill_value): """Fit the transformer on dense data.""" mask = _get_mask(X, missing_values) masked_X = ma.masked_array(X, mask=mask) # Mean if strategy == "mean": mean_masked = np.ma.mean(masked_X, axis=0) #...
Impute all missing values in X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data to complete.
def transform(self, X): """Impute all missing values in X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data to complete. """ check_is_fitted(self, 'statistics_') X = self._validate_input(X) ...
Impute a single feature from the others provided. This function predicts the missing values of one of the features using the current estimates of all the other features. The ``predictor`` must support ``return_std=True`` in its ``predict`` method for this function to work. Para...
def _impute_one_feature(self, X_filled, mask_missing_values, feat_idx, neighbor_feat_idx, predictor=None, fit_mode=True): """Impute a single fea...
Get a list of other features to predict ``feat_idx``. If self.n_nearest_features is less than or equal to the total number of features, then use a probability proportional to the absolute correlation between ``feat_idx`` and each other feature to randomly choose a subsample of the other...
def _get_neighbor_feat_idx(self, n_features, feat_idx, abs_corr_mat): """Get a list of other features to predict ``feat_idx``. If self.n_nearest_features is less than or equal to the total number of fea...
Decide in what order we will update the features. As a homage to the MICE R package, we will have 4 main options of how to order the updates, and use a random order if anything else is specified. Also, this function skips features which have no missing values. Parameters ...
def _get_ordered_idx(self, mask_missing_values): """Decide in what order we will update the features. As a homage to the MICE R package, we will have 4 main options of how to order the updates, and use a random order if anything else is specified. Also, this function skips feat...
Get absolute correlation matrix between features. Parameters ---------- X_filled : ndarray, shape (n_samples, n_features) Input data with the most recent imputations. tolerance : float, optional (default=1e-6) ``abs_corr_mat`` can have nans, which will be replac...
def _get_abs_corr_mat(self, X_filled, tolerance=1e-6): """Get absolute correlation matrix between features. Parameters ---------- X_filled : ndarray, shape (n_samples, n_features) Input data with the most recent imputations. tolerance : float, optional (default=1e-6...
Perform initial imputation for input X. Parameters ---------- X : ndarray, shape (n_samples, n_features) Input data, where "n_samples" is the number of samples and "n_features" is the number of features. Returns ------- Xt : ndarray, shape (n_sam...
def _initial_imputation(self, X): """Perform initial imputation for input X. Parameters ---------- X : ndarray, shape (n_samples, n_features) Input data, where "n_samples" is the number of samples and "n_features" is the number of features. Returns ...
Fits the imputer on X and return the transformed X. Parameters ---------- X : array-like, shape (n_samples, n_features) Input data, where "n_samples" is the number of samples and "n_features" is the number of features. y : ignored. Returns -----...
def fit_transform(self, X, y=None): """Fits the imputer on X and return the transformed X. Parameters ---------- X : array-like, shape (n_samples, n_features) Input data, where "n_samples" is the number of samples and "n_features" is the number of features. ...
Imputes all missing values in X. Note that this is stochastic, and that if random_state is not fixed, repeated calls, or permuted input, will yield different results. Parameters ---------- X : array-like, shape = [n_samples, n_features] The input data to complete. ...
def transform(self, X): """Imputes all missing values in X. Note that this is stochastic, and that if random_state is not fixed, repeated calls, or permuted input, will yield different results. Parameters ---------- X : array-like, shape = [n_samples, n_features] ...
Parameters ---------- X : np.array Data matrix with missing values filled in missing_mask : np.array Boolean array indicating where missing values were S : cvxpy.Variable Representation of solution variable
def _constraints(self, X, missing_mask, S, error_tolerance): """ Parameters ---------- X : np.array Data matrix with missing values filled in missing_mask : np.array Boolean array indicating where missing values were S : cvxpy.Variable ...
Parameters ---------- m, n : int Dimensions that of solution matrix Returns the objective function and a variable representing the solution to the convex optimization problem.
def _create_objective(self, m, n): """ Parameters ---------- m, n : int Dimensions that of solution matrix Returns the objective function and a variable representing the solution to the convex optimization problem. """ # S is the completed matr...
usage example: grid = import_from('sklearn.model_selection', 'GridSearchCV') is equivalent to: from sklearn.model_selection import GridSearchV as grid
def import_from(module, name): ''' usage example: grid = import_from('sklearn.model_selection', 'GridSearchCV') is equivalent to: from sklearn.model_selection import GridSearchV as grid ''' module = importlib.import_module(module) return getattr(module, name)
It's tricky to pick a single matrix out of all the candidate solutions with differing shrinkage thresholds. Our heuristic is to pick the matrix whose percentiles match best between the missing and observed data.
def choose_solution_using_percentiles( X_original, solutions, parameters=None, verbose=False, percentiles=list(range(10, 100, 10))): """ It's tricky to pick a single matrix out of all the candidate solutions with differing shrinkage thresholds. Our heuristic is to...
row_center[i] = sum{j in observed[i, :]}{ (1 / column_scale[j]) * (X[i, j] - column_center[j]) } ------------------------------------------------------------ sum{j in observed[i, :]}{1 / column_scale[j]}
def estimate_row_means( self, X, observed, column_means, column_scales): """ row_center[i] = sum{j in observed[i, :]}{ (1 / column_scale[j]) * (X[i, j] - column_center[j]) } ----------------------------------...
column_center[j] = sum{i in observed[:, j]}{ (1 / row_scale[i]) * (X[i, j]) - row_center[i]) } ------------------------------------------------------------ sum{i in observed[:, j]}{1 / row_scale[i]}
def estimate_column_means( self, X, observed, row_means, row_scales): """ column_center[j] = sum{i in observed[:, j]}{ (1 / row_scale[i]) * (X[i, j]) - row_center[i]) } ---------------------------------------...
row_scale[i]**2 = mean{j in observed[i, :]}{ (X[i, j] - row_center[i] - column_center[j]) ** 2 -------------------------------------------------- column_scale[j] ** 2 }
def estimate_row_scales( self, X_centered, column_scales): """ row_scale[i]**2 = mean{j in observed[i, :]}{ (X[i, j] - row_center[i] - column_center[j]) ** 2 -------------------------------------------------- col...
column_scale[j] ** 2 = mean{i in observed[:, j]}{ (X[i, j] - row_center[i] - column_center[j]) ** 2 ------------------------------------------------- row_scale[i] ** 2 }
def estimate_column_scales( self, X_centered, row_scales): """ column_scale[j] ** 2 = mean{i in observed[:, j]}{ (X[i, j] - row_center[i] - column_center[j]) ** 2 ------------------------------------------------- ...
Compute the continuous Jacard similarity between all pairs of keys in dictionary-of-dictionaries given as an input. Returns three element tuple: - similarity dictionary: (key, key) -> float - overlap count dictionary: key -> key -> int - weight dictionary: key -> key...
def jacard_similarity_from_nested_dicts(self, nested_dictionaries): """ Compute the continuous Jacard similarity between all pairs of keys in dictionary-of-dictionaries given as an input. Returns three element tuple: - similarity dictionary: (key, key) -> float -...
Keys of nested dictionaries can be arbitrary objects.
def complete_dict( self, values_dict): """ Keys of nested dictionaries can be arbitrary objects. """ if self.orientation != "rows": values_dict = transpose_nested_dictionary(values_dict) row_keys, column_keys = collect_nested_keys(values_dict)...
Give an ordering to the outer and inner keys used in a dictionary that maps to dictionaries.
def nested_key_indices(nested_dict): """ Give an ordering to the outer and inner keys used in a dictionary that maps to dictionaries. """ outer_keys, inner_keys = collect_nested_keys(nested_dict) outer_key_indices = {k: i for (i, k) in enumerate(outer_keys)} inner_key_indices = {k: i for (i,...
Combine the outer and inner keys of nested dictionaries into a single ordering.
def flattened_nested_key_indices(nested_dict): """ Combine the outer and inner keys of nested dictionaries into a single ordering. """ outer_keys, inner_keys = collect_nested_keys(nested_dict) combined_keys = list(sorted(set(outer_keys + inner_keys))) return {k: i for (i, k) in enumerate(com...
Parameters ---------- nested_dict : dict Dictionary which contains dictionaries array_fn : function Takes shape and dtype as arguments, returns empty array. dtype : dtype NumPy dtype of result array square_result : bool Combine keys from outer and inner dictionarie...
def array_from_nested_dictionary( nested_dict, array_fn, dtype="float32", square_result=False): """ Parameters ---------- nested_dict : dict Dictionary which contains dictionaries array_fn : function Takes shape and dtype as arguments, returns empty a...
X : numpy.ndarray row_keys : dict Dictionary mapping indices to row names. If omitted then maps each number to its string representation, such as 1 -> "1". column_keys : dict If omitted and matrix is square, then use the same dictionary as the rows. Otherwise map each column in...
def matrix_to_pair_dictionary( X, row_keys=None, column_keys=None, filter_fn=None): """ X : numpy.ndarray row_keys : dict Dictionary mapping indices to row names. If omitted then maps each number to its string representation, such as 1 -> "1". column_keys : dict If omit...
Transform dictionary from pairs of keys to dict -> dict -> float
def curry_pair_dictionary(key_pair_dict, default_value=0.0): """ Transform dictionary from pairs of keys to dict -> dict -> float """ result = defaultdict(dict) for (a, b), value in key_pair_dict.items(): result[a][b] = value return result
Transform dictionary from (key_a -> key_b -> float) to (key_a, key_b) -> float
def uncurry_nested_dictionary(curried_dict): """ Transform dictionary from (key_a -> key_b -> float) to (key_a, key_b) -> float """ result = {} for a, a_dict in curried_dict.items(): for b, value in a_dict.items(): result[(a, b)] = value return result
Convert a dictionary whose keys are pairs (k1, k2) into a sparse or incomplete array. Parameters ---------- pair_dict : dict Dictionary from pairs of keys to values. array_fn : function Takes shape and dtype as arguments, returns empty array. dtype : dtype NumPy dtype ...
def array_from_pair_dictionary( pair_dict, array_fn, dtype="float32", square_result=False): """ Convert a dictionary whose keys are pairs (k1, k2) into a sparse or incomplete array. Parameters ---------- pair_dict : dict Dictionary from pairs of keys to v...
Given a nested dictionary from k1 -> k2 > value transpose its outer and inner keys so it maps k2 -> k1 -> value.
def transpose_nested_dictionary(nested_dict): """ Given a nested dictionary from k1 -> k2 > value transpose its outer and inner keys so it maps k2 -> k1 -> value. """ result = defaultdict(dict) for k1, d in nested_dict.items(): for k2, v in d.items(): result[k2][k1] = v ...
Create reverse-lookup dictionary mapping each row key to a list of triplets: [(column key, value), ...] Parameters ---------- nested_values_dict : dict column_key -> row_key -> value weights_dict : dict column_key -> row_key -> sample weight Returns dictionary mapping row_key ...
def reverse_lookup_from_nested_dict(values_dict): """ Create reverse-lookup dictionary mapping each row key to a list of triplets: [(column key, value), ...] Parameters ---------- nested_values_dict : dict column_key -> row_key -> value weights_dict : dict column_key -> row...
Yield all cells in an nbformat-insensitive manner
def _cells(nb): """Yield all cells in an nbformat-insensitive manner""" if nb.nbformat < 4: for ws in nb.worksheets: for cell in ws.cells: yield cell else: for cell in nb.cells: yield cell
strip the outputs from a notebook object
def strip_output(nb): """strip the outputs from a notebook object""" nb.metadata.pop('signature', None) nb.metadata.pop('widgets', None) for cell in _cells(nb): if 'outputs' in cell: cell['outputs'] = [] if 'prompt_number' in cell: cell['prompt_number'] = None ...
Enforce min <= value <= max
def _validate_min(self, proposal): """Enforce min <= value <= max""" min = proposal['value'] if min > self.max: raise TraitError('Setting min > max') if min > self.value: self.value = min return min
Enforce min <= value <= max
def _validate_max(self, proposal): """Enforce min <= value <= max""" max = proposal['value'] if max < self.min: raise TraitError('setting max < min') if max < self.value: self.value = max return max
Cap and floor value
def _validate_value(self, proposal): """Cap and floor value""" value = proposal['value'] if self.base ** self.min > value or self.base ** self.max < value: value = min(max(value, self.base ** self.min), self.base ** self.max) return value
Show matplotlib plots immediately if using the inline backend. With ipywidgets 6.0, matplotlib plots don't work well with interact when using the inline backend that comes with ipykernel. Basically, the inline backend only shows the plot after the entire cell executes, which does not play well with dra...
def show_inline_matplotlib_plots(): """Show matplotlib plots immediately if using the inline backend. With ipywidgets 6.0, matplotlib plots don't work well with interact when using the inline backend that comes with ipykernel. Basically, the inline backend only shows the plot after the entire cell exec...
Connect widget controls to a function. This function does not generate a user interface for the widgets (unlike `interact`). This enables customisation of the widget user interface layout. The user interface layout must be defined and displayed manually.
def interactive_output(f, controls): """Connect widget controls to a function. This function does not generate a user interface for the widgets (unlike `interact`). This enables customisation of the widget user interface layout. The user interface layout must be defined and displayed manually. """ ...
Return min, max, value given input values with possible None.
def _get_min_max_value(min, max, value=None, step=None): """Return min, max, value given input values with possible None.""" # Either min and max need to be given, or value needs to be given if value is None: if min is None or max is None: raise ValueError('unable to infer range, value f...
Match a pattern of types in a sequence.
def _matches(o, pattern): """Match a pattern of types in a sequence.""" if not len(o) == len(pattern): return False comps = zip(o,pattern) return all(isinstance(obj,kind) for obj,kind in comps)
Get an abbreviation for a function parameter.
def _yield_abbreviations_for_parameter(param, kwargs): """Get an abbreviation for a function parameter.""" name = param.name kind = param.kind ann = param.annotation default = param.default not_found = (name, empty, empty) if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):...
Call the interact function and update the output widget with the result of the function call. Parameters ---------- *args : ignored Required for this method to be used as traitlets callback.
def update(self, *args): """ Call the interact function and update the output widget with the result of the function call. Parameters ---------- *args : ignored Required for this method to be used as traitlets callback. """ self.kwargs = {} ...
Find the abbreviations for the given function and kwargs. Return (name, abbrev, default) tuples.
def find_abbreviations(self, kwargs): """Find the abbreviations for the given function and kwargs. Return (name, abbrev, default) tuples. """ new_kwargs = [] try: sig = self.signature() except (ValueError, TypeError): # can't inspect, no info from ...
Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets.
def widgets_from_abbreviations(self, seq): """Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets.""" result = [] for name, abbrev, default in seq: widget = self.widget_from_abbrev(abbrev, default) if not (isinstance(widget, ValueWidget) or is...
Build a ValueWidget instance given an abbreviation or Widget.
def widget_from_abbrev(cls, abbrev, default=empty): """Build a ValueWidget instance given an abbreviation or Widget.""" if isinstance(abbrev, ValueWidget) or isinstance(abbrev, fixed): return abbrev if isinstance(abbrev, tuple): widget = cls.widget_from_tuple(abbrev) ...
Make widgets from single values, which can be used as parameter defaults.
def widget_from_single_value(o): """Make widgets from single values, which can be used as parameter defaults.""" if isinstance(o, string_types): return Text(value=unicode_type(o)) elif isinstance(o, bool): return Checkbox(value=o) elif isinstance(o, Integral): ...
Make widgets from a tuple abbreviation.
def widget_from_tuple(o): """Make widgets from a tuple abbreviation.""" if _matches(o, (Real, Real)): min, max, value = _get_min_max_value(o[0], o[1]) if all(isinstance(_, Integral) for _ in o): cls = IntSlider else: cls = FloatSlider ...
Make widgets from an iterable. This should not be done for a string or tuple.
def widget_from_iterable(o): """Make widgets from an iterable. This should not be done for a string or tuple.""" # Dropdown expects a dict or list, so we convert an arbitrary # iterable to either of those. if isinstance(o, (list, dict)): return Dropdown(options=o) ...
Return an interactive function widget for the given function. The widget is only constructed, not displayed nor attached to the function. Returns ------- An instance of ``self.cls`` (typically :class:`interactive`). Parameters ---------- f : function ...
def widget(self, f): """ Return an interactive function widget for the given function. The widget is only constructed, not displayed nor attached to the function. Returns ------- An instance of ``self.cls`` (typically :class:`interactive`). Parameters ...
Change options for interactive functions. Returns ------- A new :class:`_InteractFactory` which will apply the options when called.
def options(self, **kwds): """ Change options for interactive functions. Returns ------- A new :class:`_InteractFactory` which will apply the options when called. """ opts = dict(self.opts) for k in kwds: try: # Ensure ...
Sets the title of a container page. Parameters ---------- index : int Index of the container page title : unicode New title
def set_title(self, index, title): """Sets the title of a container page. Parameters ---------- index : int Index of the container page title : unicode New title """ # JSON dictionaries have string keys, so we convert index to a string ...
Gets the title of a container pages. Parameters ---------- index : int Index of the container page
def get_title(self, index): """Gets the title of a container pages. Parameters ---------- index : int Index of the container page """ # JSON dictionaries have string keys, so we convert index to a string index = unicode_type(int(index)) if ind...
Runs a bash script in the local directory
def bash(filename): """Runs a bash script in the local directory""" sys.stdout.flush() subprocess.call("bash {}".format(filename), shell=True)
The inverse of _remove_buffers, except here we modify the existing dict/lists. Modifying should be fine, since this is used when state comes from the wire.
def _put_buffers(state, buffer_paths, buffers): """The inverse of _remove_buffers, except here we modify the existing dict/lists. Modifying should be fine, since this is used when state comes from the wire. """ for buffer_path, buffer in zip(buffer_paths, buffers): # we'd like to set say sync_da...
For internal, see _remove_buffers
def _separate_buffers(substate, path, buffer_paths, buffers): """For internal, see _remove_buffers""" # remove binary types from dicts and lists, but keep track of their paths # any part of the dict/list that needs modification will be cloned, so the original stays untouched # e.g. {'x': {'ar': ar}, 'y'...
Return (state_without_buffers, buffer_paths, buffers) for binary message parts A binary message part is a memoryview, bytearray, or python 3 bytes object. As an example: >>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memoryview(ar2)}} >>> _remove_buffe...
def _remove_buffers(state): """Return (state_without_buffers, buffer_paths, buffers) for binary message parts A binary message part is a memoryview, bytearray, or python 3 bytes object. As an example: >>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo...
Compare two lists of buffers for equality. Used to decide whether two sequences of buffers (memoryviews, bytearrays, or python 3 bytes) differ, such that a sync is needed. Returns True if equal, False if unequal
def _buffer_list_equal(a, b): """Compare two lists of buffers for equality. Used to decide whether two sequences of buffers (memoryviews, bytearrays, or python 3 bytes) differ, such that a sync is needed. Returns True if equal, False if unequal """ if len(a) != len(b): return False ...
decorator for showing tracebacks in IPython
def _show_traceback(method): """decorator for showing tracebacks in IPython""" def m(self, *args, **kwargs): try: return(method(self, *args, **kwargs)) except Exception as e: ip = get_ipython() if ip is None: self.log.warning("Exception in widg...
For backwards compatibility, we support @register(name) syntax.
def register(name=''): "For backwards compatibility, we support @register(name) syntax." def reg(widget): """A decorator registering a widget class in the widget registry.""" w = widget.class_traits() Widget.widget_types.register(w['_model_module'].default_value, ...
(Un)Register a callback Parameters ---------- callback: method handle Method to be registered or unregistered. remove=False: bool Whether to unregister the callback.
def register_callback(self, callback, remove=False): """(Un)Register a callback Parameters ---------- callback: method handle Method to be registered or unregistered. remove=False: bool Whether to unregister the callback.""" # (Un)Register the ca...
Register a value
def register(self, model_module, model_module_version_range, model_name, view_module, view_module_version_range, view_name, klass): """Register a value""" model_module = self._registry.setdefault(model_module, {}) model_version = model_module.setdefault(model_module_version_range, {}) mo...
Get a value
def get(self, model_module, model_module_version, model_name, view_module, view_module_version, view_name): """Get a value""" module_versions = self._registry[model_module] # The python semver module doesn't work well, for example, it can't do match('3', '*') # so we just take the first ...
Static method, called when a widget is constructed.
def _call_widget_constructed(widget): """Static method, called when a widget is constructed.""" if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback): Widget._widget_construction_callback(widget)
Static method, called when a widget is constructed.
def handle_comm_opened(comm, msg): """Static method, called when a widget is constructed.""" version = msg.get('metadata', {}).get('version', '') if version.split('.')[0] != PROTOCOL_VERSION_MAJOR: raise ValueError("Incompatible widget protocol versions: received version %r, expected...
Returns the full state for a widget manager for embedding :param drop_defaults: when True, it will not include default value :param widgets: list with widgets to include in the state (or all widgets when None) :return:
def get_manager_state(drop_defaults=False, widgets=None): """Returns the full state for a widget manager for embedding :param drop_defaults: when True, it will not include default value :param widgets: list with widgets to include in the state (or all widgets when None) :return: ...
Open a comm to the frontend if one isn't already open.
def open(self): """Open a comm to the frontend if one isn't already open.""" if self.comm is None: state, buffer_paths, buffers = _remove_buffers(self.get_state()) args = dict(target_name='jupyter.widget', data={'state': state, 'buffer_paths': buffer_path...
Called when the comm is changed.
def _comm_changed(self, change): """Called when the comm is changed.""" if change['new'] is None: return self._model_id = self.model_id self.comm.on_msg(self._handle_msg) Widget.widgets[self.model_id] = self
Close method. Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.
def close(self): """Close method. Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.""" if self.comm is not None: Widget.widgets.pop(self.model_id, None) self.comm.close() ...
Sends the widget state, or a piece of it, to the front-end, if it exists. Parameters ---------- key : unicode, or iterable (optional) A single property's name or iterable of property names to sync with the front-end.
def send_state(self, key=None): """Sends the widget state, or a piece of it, to the front-end, if it exists. Parameters ---------- key : unicode, or iterable (optional) A single property's name or iterable of property names to sync with the front-end. """ sta...
Gets the widget state, or a piece of it. Parameters ---------- key : unicode or iterable (optional) A single property's name or iterable of property names to get. Returns ------- state : dict of states metadata : dict metadata for each fi...
def get_state(self, key=None, drop_defaults=False): """Gets the widget state, or a piece of it. Parameters ---------- key : unicode or iterable (optional) A single property's name or iterable of property names to get. Returns ------- state : dict of ...
Called when a state is received from the front-end.
def set_state(self, sync_data): """Called when a state is received from the front-end.""" # The order of these context managers is important. Properties must # be locked when the hold_trait_notification context manager is # released and notifications are fired. with self._lock_pr...
(Un)Register a custom msg receive callback. Parameters ---------- callback: callable callback will be passed three arguments when a message arrives:: callback(widget, content, buffers) remove: bool True if the callback should be unregistered.
def on_msg(self, callback, remove=False): """(Un)Register a custom msg receive callback. Parameters ---------- callback: callable callback will be passed three arguments when a message arrives:: callback(widget, content, buffers) remove: bool ...
(Un)Register a widget displayed callback. Parameters ---------- callback: method handler Must have a signature of:: callback(widget, **kwargs) kwargs from display are passed through without modification. remove: bool True if the call...
def on_displayed(self, callback, remove=False): """(Un)Register a widget displayed callback. Parameters ---------- callback: method handler Must have a signature of:: callback(widget, **kwargs) kwargs from display are passed through without modi...
Dynamically add trait attributes to the Widget.
def add_traits(self, **traits): """Dynamically add trait attributes to the Widget.""" super(Widget, self).add_traits(**traits) for name, trait in traits.items(): if trait.get_metadata('sync'): self.keys.append(name) self.send_state(name)
Called when a property has changed.
def notify_change(self, change): """Called when a property has changed.""" # Send the state to the frontend before the user-registered callbacks # are called. name = change['name'] if self.comm is not None and self.comm.kernel is not None: # Make sure this isn't infor...
Hold syncing any state until the outermost context manager exits
def hold_sync(self): """Hold syncing any state until the outermost context manager exits""" if self._holding_sync is True: yield else: try: self._holding_sync = True yield finally: self._holding_sync = False ...
Check the property lock (property_lock)
def _should_send_property(self, key, value): """Check the property lock (property_lock)""" to_json = self.trait_metadata(key, 'to_json', self._trait_to_json) if key in self._property_lock: # model_state, buffer_paths, buffers split_value = _remove_buffers({ key: to_json(v...
Called when a msg is received from the front-end
def _handle_msg(self, msg): """Called when a msg is received from the front-end""" data = msg['content']['data'] method = data['method'] if method == 'update': if 'state' in data: state = data['state'] if 'buffer_paths' in data: ...
Called when `IPython.display.display` is called on the widget.
def _ipython_display_(self, **kwargs): """Called when `IPython.display.display` is called on the widget.""" plaintext = repr(self) if len(plaintext) > 110: plaintext = plaintext[:110] + '…' data = { 'text/plain': plaintext, } if self._view_name is...
Sends a message to the model in the front-end.
def _send(self, msg, buffers=None): """Sends a message to the model in the front-end.""" if self.comm is not None and self.comm.kernel is not None: self.comm.send(data=msg, buffers=buffers)
Add int docstring template to class init.
def _int_doc(cls): """Add int docstring template to class init.""" def __init__(self, value=None, **kwargs): if value is not None: kwargs['value'] = value super(cls, self).__init__(**kwargs) __init__.__doc__ = _int_doc_t cls.__init__ = __init__ return cls
Add bounded int docstring template to class init.
def _bounded_int_doc(cls): """Add bounded int docstring template to class init.""" def __init__(self, value=None, min=None, max=None, step=None, **kwargs): if value is not None: kwargs['value'] = value if min is not None: kwargs['min'] = min if max is not None: ...
Serialize a Python datetime object to json. Instantiating a JavaScript Date object with a string assumes that the string is a UTC string, while instantiating it with constructor arguments assumes that it's in local time: >>> cdate = new Date('2015-05-12') Mon May 11 2015 20:00:00 GMT-0400 (Eastern...
def datetime_to_json(pydt, manager): """Serialize a Python datetime object to json. Instantiating a JavaScript Date object with a string assumes that the string is a UTC string, while instantiating it with constructor arguments assumes that it's in local time: >>> cdate = new Date('2015-05-12') ...
Deserialize a Python datetime object from json.
def datetime_from_json(js, manager): """Deserialize a Python datetime object from json.""" if js is None: return None else: return dt.datetime( js['year'], js['month'] + 1, # Months are 1-based in Python js['date'], js['hours'], js...
Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor.
def date_to_json(pydate, manager): """Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor. """ if pydate is None: return None else: return dict( year=pydate.year, month=pydate.month - 1, # Mon...
Find references to other widgets in a widget's state
def _find_widget_refs_by_state(widget, state): """Find references to other widgets in a widget's state""" # Copy keys to allow changes to state during iteration: keys = tuple(state.keys()) for key in keys: value = getattr(widget, key) # Trivial case: Direct references to other widgets: ...
Gets the embed state of a widget, and all other widgets it refers to as well
def _get_recursive_state(widget, store=None, drop_defaults=False): """Gets the embed state of a widget, and all other widgets it refers to as well""" if store is None: store = dict() state = widget._get_embed_state(drop_defaults=drop_defaults) store[widget.model_id] = state # Loop over all ...
Adds the state of any link models between two models in store
def add_resolved_links(store, drop_defaults): """Adds the state of any link models between two models in store""" for widget_id, widget in Widget.widgets.items(): # go over all widgets if isinstance(widget, Link) and widget_id not in store: if widget.source[0].model_id in store and widget.ta...
Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included widget - any widget in a dict attribute in the state...
def dependency_state(widgets, drop_defaults=True): """Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included...
Gets data for embedding. Use this to get the raw data for embedding if you have special formatting needs. Parameters ---------- {views_attribute} drop_defaults: boolean Whether to drop default values from the widget states. state: dict or None (default) The state to include...
def embed_data(views, drop_defaults=True, state=None): """Gets data for embedding. Use this to get the raw data for embedding if you have special formatting needs. Parameters ---------- {views_attribute} drop_defaults: boolean Whether to drop default values from the widget states. ...
Return a snippet that can be embedded in an HTML file. Parameters ---------- {views_attribute} {embed_kwargs} Returns ------- A unicode string with an HTML snippet containing several `<script>` tags.
def embed_snippet(views, drop_defaults=True, state=None, indent=2, embed_url=None, requirejs=True, cors=True ): """Return a snippet that can be embedded in an HTML file. Parameters -...
Write a minimal HTML file with widget views embedded. Parameters ---------- fp: filename or file-like object The file to write the HTML output to. {views_attribute} title: title of the html page. template: Template in which to embed the widget state. This should be a Python stri...
def embed_minimal_html(fp, views, title=u'IPyWidget export', template=None, **kwargs): """Write a minimal HTML file with widget views embedded. Parameters ---------- fp: filename or file-like object The file to write the HTML output to. {views_attribute} title: title of the html page. ...
Standardize the options tuple format. The returned tuple should be in the format (('label', value), ('label', value), ...). The input can be * an iterable of (label, value) pairs * an iterable of values, and labels will be generated
def _make_options(x): """Standardize the options tuple format. The returned tuple should be in the format (('label', value), ('label', value), ...). The input can be * an iterable of (label, value) pairs * an iterable of values, and labels will be generated """ # Check if x is a mapping of...