def _update_value(self, event): """ This will update the IntSlider (behind the scene) based on changes to the DiscreteSlider (front). _syncing options is to avoid infinite loop. event.name is either value or value_throttled. """ values = self.values if getattr(self, event.name) not in values: with param.edit_constant(self): setattr(self, event.name, values[0]) return index = self.values.index(getattr(self, event.name)) if event.name == 'value': self._text.value = self.labels[index] if self._syncing: return try: self._syncing = True with param.edit_constant(self._slider): setattr(self._slider, event.name, index) finally: self._syncing = False
def _create_view(self): with param.edit_constant(self): return pn.Param(self, widgets=self._widgets, show_name=False, sizing_mode="stretch_width", display_threshold=self._view_display_treshold)
def _stop_server(self, _=None): self.view[:] = [StoppedComponent().view] if self.server: self.server.stop() with param.edit_constant(self): self.server = None raise SystemExit
def _update_results(self): # pylint: disable=unsubscriptable-object with param.edit_constant(self): if self.results and "alternatives" in self.results[-1]: self.value = (self.results[-1]["alternatives"][0]["transcript"]).lstrip() else: self.value = ""
def _reload_component(self, _=None): try: self._signal_reload_start() if self.component_instance is not None: for mod in self.modules_to_reload: # pylint: disable=not-an-iterable importlib.reload(mod) mod = sys.modules[self.component.__module__] importlib.reload(mod) with param.edit_constant(self): self.component = getattr(mod, self.component.__name__) if self.parameters: if not self._parameter_instances: self._parameter_instances = _to_instances(self.parameters) # pylint: disable=not-a-mapping component_instance = self.component( **self._parameter_instances) else: component_instance = self.component() self.component_instance = _to_parameterized(component_instance) self._reset_error_message() except Exception as ex: # pylint: disable=broad-except self._report_exception(ex) finally: self._signal_reload_end()
def cultural_build_tribute_plot(self): # Limits the target raise bounds when ploting the charts self.bounds_target_raise() df_hatch_params_to_plot = self.output_scenarios() # Drop NaN rows df_hatch_params_to_plot = df_hatch_params_to_plot.dropna() with pd.option_context('mode.chained_assignment', None): df_hatch_params_to_plot['Cultural Build Tribute'] = df_hatch_params_to_plot['Cultural Build Tribute'].mul(100) cultural_build_tribute_plot = df_hatch_params_to_plot.hvplot.area(title='Cultural Build Tribute (%)', x='Total XDAI Raised', y='Cultural Build Tribute', xformatter='%.0f', yformatter='%.1f', hover=True, ylim=(0, 100), xlim=self.config_bounds['min_max_raise']['xlim'] ).opts(axiswise=True) try: #cultural_build_tribute_target = df_hatch_params_to_plot.loc[df_hatch_params_to_plot['Total XDAI Raised'] == self.target_raise]['Cultural Build Tribute'].values[0] cultural_build_tribute_target = df_hatch_params_to_plot[df_hatch_params_to_plot['Total XDAI Raised'] >= self.target_raise].iloc[0]['Cultural Build Tribute'] except: cultural_build_tribute_target = 0 with param.edit_constant(self): self.target_cultural_build_tribute = round(cultural_build_tribute_target, 2) return cultural_build_tribute_plot * hv.VLine(self.target_raise).opts(color='#E31212') * hv.HLine(cultural_build_tribute_target).opts(color='#E31212')
def _sync_start_value(self, event): if event.name == 'value': end = self.value[1] if self.value else self.end else: end = self.value_throttled[1] if self.value_throttled else self.end with param.edit_constant(self): self.param.update(**{event.name: (event.new, end)})
def report( self, value: int = 0, message: str = "", value_max: int = 100, active_count: int = 0, ): """Report the value and message. When the function or code is finished the progress is reset. Can be used as context manager or decorator. Args: value (int, optional): A value between 0 and 100. Default is 0. value_max(int): The maximum value the progress value can be message (str, optional): A message for the user describing what is happening. active_count (int, optional): Used to mark that the application is in_progress "" Yields: None: Nothing is yielded """ previous_progress = self.progress self.update(value=value, message=message, value_max=value_max, active_count=active_count) yield with param.edit_constant(self): self.progress = previous_progress
def test_discrete_slider_options_dict(document, comm): options = OrderedDict([('0.1', 0.1), ('1', 1), ('10', 10), ('100', 100)]) discrete_slider = DiscreteSlider(name='DiscreteSlider', value=1, options=options) box = discrete_slider.get_root(document, comm=comm) label = box.children[0] widget = box.children[1] assert isinstance(label, BkDiv) assert isinstance(widget, BkSlider) assert widget.value == 1 assert widget.value_throttled == 1 assert widget.start == 0 assert widget.end == 3 assert widget.step == 1 assert label.text == 'DiscreteSlider: <b>1</b>' widget.value = 2 discrete_slider._slider._process_events({'value': 2}) assert discrete_slider.value == 10 discrete_slider._slider._process_events({'value_throttled': 2}) assert discrete_slider.value_throttled == 10 discrete_slider.value = 100 assert widget.value == 3 with param.edit_constant(discrete_slider): discrete_slider.value_throttled = 100 assert widget.value_throttled == 3
def update( self, value: Optional[int] = None, message: Optional[str] = None, value_max: Optional[int] = None, active_count: Optional[int] = None, ): """Updates the value and message Args: value (int): A value between 0 and 100 message (str): A message for the user describing what is happening value_max (int, optional): The value should be between value and value_max active_count (int, optional): Used to mark that the application is in_progress """ # Please note the order matters as the Widgets updates two times. One for each change old_progress = self.progress if value is None: value = old_progress.value if value_max is None: value_max = old_progress.value_max if message is None: message = old_progress.message if active_count is None: active_count = old_progress.active_count progress = Progress( value=value, value_max=value_max, message=message, active_count=active_count, ) with param.edit_constant(self): self.progress = progress
def test_discrete_date_slider(document, comm): dates = OrderedDict([('2016-01-0%d' % i, datetime(2016, 1, i)) for i in range(1, 4)]) discrete_slider = DiscreteSlider(name='DiscreteSlider', value=dates['2016-01-02'], options=dates) box = discrete_slider.get_root(document, comm=comm) assert isinstance(box, BkColumn) label = box.children[0] widget = box.children[1] assert isinstance(label, BkDiv) assert isinstance(widget, BkSlider) assert widget.value == 1 assert widget.value_throttled == 1 assert widget.start == 0 assert widget.end == 2 assert widget.step == 1 assert label.text == 'DiscreteSlider: <b>2016-01-02</b>' widget.value = 2 discrete_slider._slider._process_events({'value': 2}) assert discrete_slider.value == dates['2016-01-03'] discrete_slider._slider._process_events({'value_throttled': 2}) assert discrete_slider.value_throttled == dates['2016-01-03'] discrete_slider.value = dates['2016-01-01'] assert widget.value == 0 with param.edit_constant(discrete_slider): discrete_slider.value_throttled = dates['2016-01-01'] assert widget.value_throttled == 0
def _update_object_from_parameters(self, *_): with param.edit_constant(self): self.object = ( f'<a href="{self.link_url}" target="_blank">' f'<img src="{self.image_url}" style="height:100%;max-width:100%;display:block;' 'margin-left:auto;margin-right:auto"></a>' )
def _update_link_url_from_parameters(self, *_): folder = self._html_encode(self.folder) notebook = self._html_encode(self.notebook) with param.edit_constant(self): self.link_url = ( f"https://mybinder.org/v2/gh/{self.repository}/{self.branch}" f"?filepath={folder}%2F{notebook}")
def _sync_end_value(self, event): if event.name == 'value': start = self.value[0] if self.value else self.start else: start = self.value_throttled[ 0] if self.value_throttled else self.start with param.edit_constant(self): self.param.update(**{event.name: (start, event.new)})
def __init__(self, application: Application, page_service: PageService, **params): super().__init__(self, **params) with param.edit_constant(self): self.application = application self.page_service = page_service self[:] = self._get_view_objects()
def _create_editor(self): with param.edit_constant(self): return pn.Param(self, widgets=self._widgets, show_name=False, sizing_mode="stretch_width", display_threshold=self._editor_display_treshold, expand=True, expand_button=True)
def set_default_page(self, page: Page): """Change the default_page to the specified page Args: page (Page): The new default_page """ if not page in self.pages: self.create(page) with param.edit_constant(self): self.default_page = page
def _reset(self): self._fd = 0 self._child_pid = 0 if self._periodic_callback: self._periodic_callback.stop() self._periodic_callback = None if self._watcher: self._terminal.param.unwatch(self._watcher) with param.edit_constant(self): self.running = False
def _acked(self, err, msg): """Delivery report handler called on successful or failed delivery of message""" if err is not None: logger.error("Failed to deliver message: {}".format(err)) else: with param.edit_constant(self): self.delivered_records += 1 logger.info( "Produced record to topic {} partition [{}] @ offset {}". format(msg.topic(), msg.partition(), msg.offset()))
def _update_image_url_from_theme(self, *events): # pylint: disable=unused-argument with param.edit_constant(self): self.image_url = IMAGE_URLS[self.theme] height = LAYOUTS[self.theme]["height"] width = LAYOUTS[self.theme]["width"] if self.height: self.width = int(self.height * width / height) else: self.height = height self.width = width self.style = LAYOUTS[self.theme]["style"]
def run(self, *args, **kwargs): """ Runs a subprocess command. """ import pty # Inspiration: https://github.com/cs01/pyxtermjs # Inspiration: https://github.com/jupyter/terminado if not args: args = self.args if not args: raise ValueError("Error. No args provided") if self.running: raise ValueError( "Error. A child process is already running. Cannot start another." ) args = self._clean_args(args) # Clean for security reasons if self.kwargs: kwargs = {**self.kwargs, **kwargs} # A fork is an operation whereby a process creates a copy of itself # The two processes will continue from here as a PARENT and a CHILD process (child_pid, fd) = pty.fork() if child_pid == 0: # This is the CHILD process fork. # Anything printed here will show up in the pty, including the output # of this subprocess # The process will end by printing 'CompletedProcess(...)' to signal to the parent # that it finished. try: result = subprocess.run(args, **kwargs) print(str(result)) except FileNotFoundError as e: print(str(e) + "\nCompletedProcess('FileNotFoundError')") else: # this is the PARENT process fork. self._child_pid = child_pid self._fd = fd self._set_winsize() self._periodic_callback = PeriodicCallback( callback=self._forward_subprocess_output_to_terminal, period=self._period) self._periodic_callback.start() self._watcher = self._terminal.param.watch( self._forward_terminal_input_to_subprocess, 'value', onlychanged=False) with param.edit_constant(self): self.running = True
def set_default_author(self, author: Author): """Change the default_author to the specified author Args: author (Author): The new default_author """ if not author in self.authors: self.create(author) with param.edit_constant(self): self.default_author = author
def _create_view(self): widgets = {"sasl_password": pn.widgets.PasswordInput} view = pn.Column(pn.pane.Markdown("## Kafka Configuration", margin=(0, 15)), pn.Param(self.config, widgets=widgets, show_name=False, margin=(0, 5), sizing_mode="stretch_width"), sizing_mode="stretch_width") with param.edit_constant(self): self.view = view
def _calc_shapes(self, array): num_items, num_states = array.shape if self.frames is None: if num_states < 10: num_steps = int(np.ceil(60 / num_states)) else: num_steps = int(np.ceil(120 / num_states)) else: num_steps = self.frames with param.edit_constant(self): self.num_steps = num_steps num_result = (num_states - 1) * num_steps return num_items, num_states, num_steps, num_result
def _sync_value(self, event): """ This will update the DiscreteSlider (front) based on changes to the IntSlider (behind the scene). _syncing options is to avoid infinite loop. event.name is either value or value_throttled. """ if self._syncing: return try: self._syncing = True with param.edit_constant(self): setattr(self, event.name, self.values[event.new]) finally: self._syncing = False
def __init__(self, component, **params): if not isinstance(params, dict): params = {} params["component"] = component super().__init__(**params) try: name = self.component.name except AttributeError: name = self.component.__name__ with param.edit_constant(self): self.name = name self.reload_component = self._reload_component self.reload_css_file = self._reload_css_file self.reload_js_file = self._reload_js_file
def __init__(self, components): if not components: raise ValueError( "Error: component_reloaders is empty. This is allowed") pn.config.raw_css.append(config.CSS) components = _to_component_reloaders(components) self.param.component_reloader.objects = components self.param.component_reloader.default = components[0] super().__init__() with param.edit_constant(self): self.name = "Panel Designer App" self.title_component = TitleComponent() self.css_pane = self._create_css_pane() self.js_pane = self._create_js_pane() self.component_pane = self._create_component_pane() self.action_pane = self._create_action_pane() self.settings_pane = self._create_settings_pane() self.settings_scroll_pane = self._create_settings_scroll_pane( self.settings_pane) self.font_pane = self._create_font_pane() self.error_pane = self._create_error_pane() self.stop_server_pane = self._create_stop_server_pane() self.designer_pane = self._create_designer_pane( title_component=self.title_component, action_pane=self.action_pane, settings_scroll_pane=self.settings_scroll_pane, stop_server_pane=self.stop_server_pane, font_pane=self.font_pane, css_pane=self.css_pane, js_pane=self.js_pane, ) self.view = self._create_view(self.component_pane, self.designer_pane) self.show = self._show self.stop_server = self._stop_server self._create_watchers(components) self._handle_component_reloader_change()
def test_tabulator_comms(document, comm, column_data_source, configuration): # Given tabulator = Tabulator(value=column_data_source, configuration=configuration) widget = tabulator.get_root(document, comm=comm) # Then assert isinstance(widget, tabulator._widget_type) assert widget.source == column_data_source assert widget.configuration == configuration # When with param.edit_constant(tabulator): tabulator._process_events({ "configuration": { "a": 1 }, }) # Then assert tabulator.configuration == {"a": 1}
def _update_component(self, *events): # pylint: disable=unused-argument # pylint: disable=no-member action_pane_index = self.designer_pane.objects.index(self.action_pane) # pylint: enable=no-member with param.edit_constant(self): self.action_pane = self._create_action_pane() self.designer_pane[action_pane_index] = self.action_pane if self.component_reloader_.component_instance: self.settings_pane.object = self.component_reloader_.component_instance if isinstance(self.component_reloader_.component_instance, pn.reactive.Reactive): component_view = self.component_reloader_.component_instance elif hasattr(self.component_reloader_.component_instance, "view"): component_view = self.component_reloader_.component_instance.view else: component_view = self.component_reloader_.component_instance self.component_pane.component = component_view self.component_pane._update() # pylint: disable=protected-access print("_update_component", self.component_reloader)
def impact_hours_view(self): # Limits the target raise bounds when ploting the charts self.bounds_target_raise() self.df_impact_hours = self.impact_hours_formula(self.config_bounds['min_max_raise']['bounds'][0], self.max_raise) df = self.df_impact_hours df_fill_minimum = df[df['Total XDAI Raised'] <= self.min_raise] try: target_impact_hour_rate = df[df['Total XDAI Raised'] >= self.target_raise].iloc[0]['Impact Hour Rate'] except: target_impact_hour_rate = 0 impact_hours_plot = df.hvplot.area(title='Impact Hour Rate', x='Total XDAI Raised', xformatter='%.0f', yformatter='%.4f', hover=True, xlim=self.config_bounds['min_max_raise']['xlim'], label='Hatch happens ✅' ).opts(axiswise=True) minimum_raise_plot = df_fill_minimum.hvplot.area(x='Total XDAI Raised', xformatter='%.0f', yformatter='%.4f', color='red', xlim=self.config_bounds['min_max_raise']['xlim'], label='Hatch fails 🚫' ).opts(axiswise=True) # Enables the edition of constant params with param.edit_constant(self): self.target_impact_hour_rate = round(target_impact_hour_rate, 2) #return impact_hours_plot * hv.VLine(expected_raise) * hv.HLine(expected_impact_hour_rate) * hv.VLine(self.target_raise) * hv.HLine(target_impact_hour_rate) return (impact_hours_plot * minimum_raise_plot * hv.VLine(self.target_raise).opts(color='#E31212') * hv.HLine(self.target_impact_hour_rate).opts(color='#E31212') ).opts(legend_position='top_left')