Exemple #1
0
    def set_output(self,
                   output: Any,
                   magic_name: Text,
                   bind_to: Optional[Text] = '') -> Optional[Any]:
        """Sets an output from a magic and stores it in the namespace if needed.

    Args:
      output (object): the output from the magic as executed.
      magic_name (str): the name of the magic that was used.
      bind_to (str): optional name of a variable. If this is provided
        the output is omitted and variable is stored in the namespace using
        the name provided here.

    Returns:
      Returns the output object.
    """
        with _LOCK:
            self._last_output = output
            self._last_magic = magic_name

            if bind_to:
                _ = utils.ipython_bind_global(name=bind_to, value=output)
                return None

            return output
Exemple #2
0
 def _click_function(_):
     sketch = timesketch_get_sketch_func()
     search_obj = search.Search(sketch)
     if start_time_form.value and end_time_form.value:
         date_chip = search.DateRangeChip()
         date_chip.start_time = start_time_form.value.strftime(
             '%Y-%m-%dT%H:%M:%S')
         date_chip.end_time = end_time_form.value.strftime(
             '%Y-%m-%dT%H:%M:%S')
         search_obj.add_chip(date_chip)
     search_obj.query_string = query_string_form.value
     display(
         Markdown(f'Query **executed** - returned: {len(search_obj.table)} '
                  'records'))
     utils.ipython_bind_global('search_obj', search_obj)
     display(Markdown('Results are stored in the **search_obj**'))
Exemple #3
0
 def _click_function(_):
     with output:
         timesketch_set_active_sketch_func(str(sketch_field.value))
         sketch = timesketch_get_sketch_func()
         try:
             display(
                 Markdown(
                     f'Connected to sketch: {sketch.id}: **{sketch.name}**')
             )
             valid = widgets.Valid(value=True, description='Connected')
             display(valid)
             utils.ipython_bind_global('sketch', sketch)
             display(Markdown('Sketch object saved to **sketch**'))
         except KeyError:
             display(Markdown('**Unable to connect to sketch.**'))
             invalid = widgets.Valid(value=False, description='Connected')
             display(invalid)
Exemple #4
0
def picatrix_helper(function: Callable[..., Any]) -> Callable[..., Any]:
    """Decorator to register a picatrix helper.

  Args:
    function (function): if the decorator is called without any
        arguments the helper function is passed to the decorator.

  Returns:
   The function that was passed in.
  """
    typing_hints = typing.get_type_hints(function)
    manager.MagicManager.register_helper(name=function.__name__,
                                         helper=function,
                                         typing_help=typing_hints)

    try:
        _ = utils.ipython_get_global(function.__name__)
    except KeyError:
        utils.ipython_bind_global(function.__name__, function)

    return function
Exemple #5
0
    def register_magic(cls,
                       function: Callable[[Text, Text], Text],
                       conditional: Callable[[], bool] = None):
        """Register magic function as a magic in picatrix.

    Args:
      function (function): the function to register as a line and a
          cell magic.
      conditional (function): a function that should return a bool, used to
          determine whether to register magic or not. This can be used by
          magics to determine whether a magic should be registered or not, for
          instance basing that on whether the notebook is able to reach the
          required service, or whether a connection to a client can be achieved,
          etc. This is optional and if not provided a magic will be registered.

    Raises:
      KeyError: if the magic is already registered.
    """
        if conditional and not conditional():
            return

        magic_name = function.magic_name

        if magic_name in cls._magics:
            raise KeyError(f'The magic [{magic_name}] is already registered.')

        ip = get_ipython()
        if ip:
            ip.register_magic_function(function,
                                       magic_kind='line_cell',
                                       magic_name=magic_name)

        cls._magics[magic_name] = function
        function_name = f'{magic_name}_func'

        def capture_output(function, name):
            """A function that wraps around magic functions to capture output."""
            @functools.wraps(function)
            def wrapper(*args, **kwargs):
                function_output = function(*args, **kwargs)
                state_obj = state.state()
                return state_obj.set_output(function_output, magic_name=name)

            return wrapper

        _ = utils.ipython_bind_global(
            function_name, capture_output(function.fn, function_name))
Exemple #6
0
    def register_magic(cls,
                       function: Callable[[str, str], str],
                       conditional: Callable[[], bool] = None):
        """Register magic function as a magic in picatrix.

    Args:
      function (function): the function to register as a line and a
          cell magic.
      conditional (function): a function that should return a bool, used to
          determine whether to register magic or not. This can be used by
          magics to determine whether a magic should be registered or not, for
          instance basing that on whether the notebook is able to reach the
          required service, or whether a connection to a client can be achieved,
          etc. This is optional and if not provided a magic will be registered.

    Raises:
      KeyError: if the magic is already registered.
    """
        if conditional and not conditional():
            return

        magic_name = function.magic_name

        if magic_name in cls._magics:
            raise KeyError(f'The magic [{magic_name}] is already registered.')

        ip = get_ipython()
        if ip:
            ip.register_magic_function(function,
                                       magic_kind='line_cell',
                                       magic_name=magic_name)

        cls._magics[magic_name] = function
        function_name = f'{magic_name}_func'

        _ = utils.ipython_bind_global(function_name, function.fn)