text
stringlengths
18
773k
def add(ctx, alias, mapping, backend): """ Add a new alias to your configuration file. """ if not backend: backends_list = ctx.obj['settings'].get_backends() if len(backends_list) > 1: raise click.UsageError( "You're using more than 1 backend. Please set the b...
def convert_to_4(self): """ Convert a pre-4.0 configuration file to a 4.0 configuration file. """ from six.moves.urllib import parse if not self.config.has_section('backends'): self.config.add_section('backends') site = parse.urlparse(self.get('site', defaul...
def autofill(ctx, f): """ Fills your timesheet up to today, for the defined auto_fill_days. """ auto_fill_days = ctx.obj['settings']['auto_fill_days'] if not auto_fill_days: ctx.obj['view'].view.err("The parameter `auto_fill_days` must be set " "to use this ...
def list_(ctx, search, backend): """ Searches for a project by its name. The letter in the first column indicates the status of the project: [N]ot started, [A]ctive, [F]inished, [C]ancelled. """ projects = ctx.obj['projects_db'].search(search, backend=backend) projects = sorted(projects, key...
def alias(ctx, search, backend): """ Searches for the given project and interactively add an alias for it. """ projects = ctx.obj['projects_db'].search(search, active_only=True) projects = sorted(projects, key=lambda project: project.name) if len(projects) == 0: ctx.obj['view'].msg( ...
def show(ctx, project_id, backend): """ Shows the details of the given project id. """ try: project = ctx.obj['projects_db'].get(project_id, backend) except IOError: raise Exception("Error: the projects database file doesn't exist. " "Please run `taxi update` ...
def stop(ctx, description, f): """ Use it when you stop working on the current task. You can add a description to what you've done. """ description = ' '.join(description) try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) current_timesheet = timesheet_colle...
def start(ctx, alias, description, f): """ Use it when you start working on the given activity. This will add the activity and the current time to your entries file. When you're finished, use the stop command. """ today = datetime.date.today() try: timesheet_collection = get_timeshe...
def create_time_from_text(text): """ Parse a time in the form ``hh:mm`` or ``hhmm`` (or even ``hmm``) and return a :class:`datetime.time` object. If no valid time can be extracted from the given string, :exc:`ValueError` will be raised. """ text = text.replace(':', '') if not re.match('^\d{3,}$...
def duration_to_text(self, duration): """ Return the textual representation of the given `duration`. The duration can either be a tuple of :class:`datetime.time` objects, or a simple number. The returned text will be either a hhmm-hhmm string (if the given `duration` is a tuple) or a num...
def to_text(self, line): """ Return the textual representation of the given `line`. """ return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line)
def date_line_to_text(self, date_line): """ Return the textual representation of the given :class:`~taxi.timesheet.lines.DateLine` instance. The date format is set by the `date_format` parameter given when instanciating the parser instance. """ # Changing the date in a dateline i...
def entry_line_to_text(self, entry): """ Return the textual representation of an :class:`~taxi.timesheet.lines.Entry` instance. This method is a bit convoluted since we don't want to completely mess up the original formatting of the entry. """ line = [] # The entry is ne...
def create_entry_line_from_text(self, text): """ Try to parse the given text line and extract and entry. Return an :class:`~taxi.timesheet.lines.Entry` object if parsing is successful, otherwise raise :exc:`~taxi.exceptions.ParseError`. """ split_line = re.match(self.entry_line_r...
def create_date_from_text(self, text): """ Parse a text in the form dd/mm/yyyy, dd/mm/yy or yyyy/mm/dd and return a corresponding :class:`datetime.date` object. If no date can be extracted from the given text, a :exc:`ValueError` will be raised. """ # Try to match dd/mm/yyyy form...
def extract_flags_from_text(self, text): """ Extract the flags from the given text and return a :class:`set` of flag values. See :class:`~taxi.timesheet.lines.Entry` for a list of existing flags. """ flags = set() reversed_flags_repr = {v: k for k, v in self.flags_repr.it...
def parse_text(self, text): """ Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`, :class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an error during parsing, a :exc:`taxi.exceptions.ParseError` will be ra...
def parse_line(self, text): """ Parse the given `text` and return either a :class:`~taxi.timesheet.lines.DateLine`, an :class:`~taxi.timesheet.lines.Entry`, or a :class:`~taxi.timesheet.lines.TextLine`, or raise :exc:`taxi.exceptions.ParseError` if the line can't be parser. See the trans...
def add_date(self, date, lines): """ Return the given `lines` with the `date` added in the right place (ie. to the beginning or to the end of the given lines, depending on the `add_date_to_bottom` property). """ _lines = lines[:] _lines = trim(_lines) if self.add...
def update(ctx): """ Synchronizes your project database with the server and updates the shared aliases. """ ctx.obj['view'].updating_projects_database() projects = [] for backend_name, backend_uri in ctx.obj['settings'].get_backends(): backend = plugins_registry.get_backend(backend...
def attributes(self): """ A dictionary mapping names of attributes to BiomartAttribute instances. This causes overwriting errors if there are diffferent pages which use the same attribute names, but is kept for backward compatibility. """ if not self._attribute_pages: ...
def get_backends_by_class(self, backend_class): """ Return a list of backends that are instances of the given `backend_class`. """ return [backend for backend in self._backends_registry.values() if isinstance(backend, backend_class)]
def populate_backends(self, backends, context): """ Iterate over the given backends list and instantiate every backend found. Can raise :exc:`BackendNotFoundError` if a backend could not be found in the registered entry points. The `backends` parameter should be a dict with back...
def _load_backend(self, backend_uri, context): """ Return the instantiated backend object identified by the given `backend_uri`. The entry point that is used to create the backend object is determined by the protocol part of the given URI. """ parsed = parse.urlp...
def register_commands(self): """ Load entry points for custom commands. """ for command in self._entry_points[self.COMMANDS_ENTRY_POINT].values(): command.load()
def _add_or_remove_flag(self, flag, add): """ Add the given `flag` if `add` is True, remove it otherwise. """ meth = self.add_flag if add else self.remove_flag meth(flag)
def get_application_configuration(name): """Get a named application configuration. An application configuration is a named set of securely stored properties where each key and its value in the property set is a string. An application configuration object is used to store information that IBM Strea...
def _submit(primitive, port_index, tuple_): """Internal method to submit a tuple""" args = (_get_opc(primitive), port_index, tuple_) _ec._submit(args)
def value(self, value): """ Set the current value of the metric. """ args = (self.__ptr, int(value)) _ec.metric_set(args)
def resource_tags(self): """Resource tags for this processing logic. Tags are a mechanism for differentiating and identifying resources that have different physical characteristics or logical uses. For example a resource (host) that has external connectivity for public data sources may be tagged `inges...
def submit(ctxtype, graph, config=None, username=None, password=None): """ Submits a `Topology` (application) using the specified context type. Used to submit an application for compilation into a Streams application and execution within an Streaming Analytics service or IBM Streams instance. `ctx...
def _vcap_from_service_definition(service_def): """Turn a service definition into a vcap services containing a single service. """ if 'credentials' in service_def: credentials = service_def['credentials'] else: credentials = service_def service = {} service['credentials'] = ...
def _get_java_env(self): "Pass the VCAP through the environment to the java submission" env = super(_StreamingAnalyticsSubmitter, self)._get_java_env() vcap = streamsx.rest._get_vcap_services(self._vcap_services) env['VCAP_SERVICES'] = json.dumps(vcap) return env
def _get_java_env(self): "Set env vars from connection if set" env = super(_DistributedSubmitter, self)._get_java_env() if self._streams_connection is not None: # Need to sure the environment matches the connection. sc = self._streams_connection if isinstance(...
def from_overlays(overlays): """Create a `JobConfig` instance from a full job configuration overlays object. All logical items, such as ``comment`` and ``job_name``, are extracted from `overlays`. The remaining information in the single job config overlay in ``overlays`` is set ...
def _add_overlays(self, config): """ Add this as a jobConfigOverlays JSON to config. """ if self._comment: config['comment'] = self._comment jco = {} config["jobConfigOverlays"] = [jco] if self._raw_overlay: jco.update(self._raw_overlay) ...
def job(self): """REST binding for the job associated with the submitted build. Returns: Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted. """ if self._submitter and hasattr(self._submitter, '_job_access'): ...
def cancel_job_button(self, description=None): """Display a button that will cancel the submitted job. Used in a Jupyter IPython notebook to provide an interactive mechanism to cancel a job submitted from the notebook. Once clicked the button is disabled unless the cancel fails. ...
def add_default(self, key: str, value: Optional[str], default_type: type = str) -> None: """ Adds a default value and a default type for a key. :param key: Key :param value: *Serialized* default value, i.e. a string or ``None``. :param default_type: The type to unserialize value...
def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None: """ Adds serialization support for a new type. :param type: The type to add support for. :param serialize: A callable that takes an object of type ``type`` and returns a string. ...
def set_global(self, cache_namespace: str = None) -> type: """ Decorator. Attaches the global key-value store of this hierarchy to an object. :param cache_namespace: Optional. A custom namespace used for caching. By default this is constructed from the name of th...
def add(self, cache_namespace: str = None, parent_field: str = None) -> type: """ Decorator. Attaches a global key-value store to a Django model. :param cache_namespace: Optional. A custom namespace used for caching. By default this is constructed from the name o...
def _as_spl_expr(value): """ Return value converted to an SPL expression if needed other otherwise value. """ import streamsx._streams._numpy if hasattr(value, 'spl_json'): return value if isinstance(value, Enum): value = streamsx.spl.op.Expression.expression(value.name) ...
def _unique_id(self, prefix): """ Generate a unique (within the graph) identifer internal to graph generation. """ _id = self._id_gen self._id_gen += 1 return prefix + str(_id)
def _requested_name(self, name, action=None, func=None): """Create a unique name for an operator or a stream. """ if name is not None: if name in self._used_names: # start at 2 for the "second" one of this name n = 2 while True: ...
def colocate(self, others, why): """ Colocate this operator with another. """ if isinstance(self, Marker): return colocate_tag = '__spl_' + why + '$' + str(self.index) self._colocate_tag(colocate_tag) for op in others: op._colocate_tag(colo...
def main_composite(kind, toolkits=None, name=None): """Wrap a main composite invocation as a `Topology`. Provides a bridge between an SPL application (main composite) and a `Topology`. Create a `Topology` that contains just the invocation of the main composite defined by `kind`. The returned `To...
def attribute(self, stream, name): """Expression for an input attribute. An input attribute is an attribute on one of the input ports of the operator invocation. `stream` must have been used to declare this invocation. Args: stream(Stream): Stream the attribute is f...
def output(self, stream, value): """SPL output port assignment expression. Arguments: stream(Stream): Output stream the assignment is for. value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: ...
def output(self, value): """SPL output port assignment expression. Arguments: value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: Expression: Output assignment expression that is valid as a t...
def attribute(self, name): """Expression for an input attribute. An input attribute is an attribute on the input port of the operator invocation. Args: name(str): Name of the attribute. Returns: Expression: Expression representing the input a...
def output(self, value): """SPL output port assignment expression. Arguments: value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: Expression: Output assignment expression that is valid as a t...
def expression(value): """Create an SPL expression. Args: value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value. Returns: Expression: SPL expression from `value`....
def spl_json(self): """Private method. May be removed at any time.""" _splj = {} _splj["type"] = self._type _splj["value"] = self._value return _splj
def _extract_from_toolkit(args): """ Look at all the modules in opt/python/streams (opt/python/streams/*.py) and extract any spl decorated function as an operator. """ extractor = _Extractor(args) if extractor._cmd_args.verbose: print("spl-python-extract:", __version__) print("T...
def _copy_globalization_resources(self): '''Copy the language resource files for python api functions This function copies the TopologySplpy Resource files from Topology toolkit directory into the impl/nl folder of the project. Returns: the list with the copied locale strings''' ...
def _setup_info_xml(self, languageList): '''Setup the info.xml file This function prepares or checks the info.xml file in the project directory - if the info.xml does not exist in the project directory, it copies the template info.xml into the project directory. The project na...
def main(args=None): """ Output information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams. """ _parse_args(args) streamsx._streams._version._mismatch_check('streamsx.topology.context') srp = pkg_res...
def operator_driven(drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS): """Define an operator-driven consistent region configuration. The source operator triggers drain and checkpoint cycles for the region. Args: drain_timeout: Th...
def periodic(period, drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS): """Create a periodic consistent region configuration. The IBM Streams runtime will trigger a drain and checkpoint the region periodically at the time interval specified b...
def _get_timestamp_tuple(ts): """ Internal method to get a timestamp tuple from a value. Handles input being a datetime or a Timestamp. """ if isinstance(ts, datetime.datetime): return Timestamp.from_datetime(ts).tuple() elif isinstance(ts, Timestamp): return ts raise...
def from_datetime(dt, machine_id=0): """ Convert a datetime to an SPL `Timestamp`. Args: dt(datetime.datetime): Datetime to be converted. machine_id(int): Machine identifier. Returns: Timestamp: Datetime converted to Timestamp. """ ...
def add_toolkit(topology, location): """Add an SPL toolkit to a topology. Args: topology(Topology): Topology to include toolkit in. location(str): Location of the toolkit directory. """ import streamsx.topology.topology assert isinstance(topology, streamsx.topology.topology.Topology...
def add_toolkit_dependency(topology, name, version): """Add a version dependency on an SPL toolkit to a topology. To specify a range of versions for the dependent toolkits, use brackets (``[]``) or parentheses. Use brackets to represent an inclusive range and parentheses to represent an exclusive range...
def submit(args=None): """ Performs the submit according to arguments and returns an object describing the result. """ streamsx._streams._version._mismatch_check('streamsx.topology.context') cmd_args = _parse_args(args) if cmd_args.topology is not None: app = _get_topology_app(cmd_args) ...
def _parse_args(args): """ Argument parsing """ cmd_parser = argparse.ArgumentParser(description='Execute a Streams application using a Streaming Analytics service.') ctx_group = cmd_parser.add_mutually_exclusive_group(required=True) ctx_group.add_argument('--service-name', help='Submit to Streamin...
def _define_jco_args(cmd_parser): """ Define job configuration arguments. Returns groups defined, currently one. """ jo_group = cmd_parser.add_argument_group('Job options', 'Job configuration options') jo_group.add_argument('--job-name', help='Job name') jo_group.add_argument('--preload', a...
def _submit_topology(cmd_args, app): """Submit a Python topology to the service. This includes an SPL main composite wrapped in a Python topology. """ cfg = app.cfg if cmd_args.create_bundle: ctxtype = ctx.ContextTypes.BUNDLE elif cmd_args.service_name: cfg[ctx.ConfigParams.FORCE...
def _submit_bundle(cmd_args, app): """Submit an existing bundle to the service""" sac = streamsx.rest.StreamingAnalyticsConnection(service_name=cmd_args.service_name) sas = sac.get_streaming_analytics() sr = sas.submit_job(bundle=app.app, job_config=app.cfg[ctx.ConfigParams.JOB_CONFIG]) if 'exceptio...
def pipe(wrapped): """ Decorator to create an SPL operator from a function. A pipe SPL operator with a single input port and a single output port. For each tuple on the input port the function is called passing the contents of the tuple. SPL attributes from the tuple are passed by position...
def _define_fixed(wrapped, callable_): """For the callable see how many positional parameters are required""" is_class = inspect.isclass(wrapped) style = callable_._splpy_style if hasattr(callable_, '_splpy_style') else wrapped._splpy_style if style == 'dictionary': return -1 fixed_count =...
def ignore(wrapped): """ Decorator to ignore a Python function. If a Python callable is decorated with ``@spl.ignore`` then function is ignored by ``spl-python-extract.py``. Args: wrapped: Function that will be ignored. """ @functools.wraps(wrapped) def _ignore(*args, **kw...
def sink(wrapped): """Creates an SPL operator with a single input port. A SPL operator with a single input port and no output ports. For each tuple on the input port the decorated function is called passing the contents of the tuple. .. deprecated:: 1.8 Recommended to use :py:class:`@spl.f...
def submit(self, port_id, tuple_): """Submit a tuple to the output port. The value to be submitted (``tuple_``) can be a ``None`` (nothing will be submitted), ``tuple``, ``dict` or ``list`` of those types. For details on how the ``tuple_`` is mapped to an SPL tuple see :ref:`submit-from...
def _splpy_convert_tuple(attributes): """Create a function that converts tuples to be submitted as dict objects into Python tuples with the value by position. Return function handles tuple,dict,list[tuple|dict|None],None """ def _to_tuples(tuple_): if isinstance(tuple_, tuple): ...
def _splpy_primitive_input_fns(obj): """Convert the list of class input functions to be instance functions against obj. Used by @spl.primitive_operator SPL cpp template. """ ofns = list() for fn in obj._splpy_input_ports: ofns.append(getattr(obj, fn.__name__)) return ofns
def _splpy_all_ports_ready(callable_): """Call all_ports_ready for a primitive operator.""" if hasattr(type(callable_), 'all_ports_ready'): try: return callable_.all_ports_ready() except: ei = sys.exc_info() if streamsx._streams._runtime._call_exit(callable_, ...
def set_trace(a_frame=None): """ Breaks on the line that invoked this function or at given frame. User can then resume execution. To call set_trace() use: .. code-block:: python import ikp3db ; ikp3db.set_trace() :param a_frame: The frame at which to break on. :type a_frame: ...
def post_mortem(trace_back=None, exc_info=None): """ Breaks on a traceback and send all execution information to the debugger client. If the interpreter is handling an exception at this traceback, exception information is sent to _line_tracer() which will transmit it to the debugging client. Call...
def setup(cls, ikpdb_log_arg): """ activates DEBUG logging level based on the `ikpdb_log_arg` parameter string. `ikpdb_log_arg` corresponds to the `--ikpdb-log` command line argument. `ikpdb_log_arg` is composed of a serie of letters that set the `DEBUG` lo...
def send(self, command, _id=None, result={}, frames=[], threads=None, error_messages=[], warning_messages=[], info_messages=[], exception=None): """ Build a message from parameters and send it to debugger. :param command: The command sent to the debugger client. ...
def reply(self, obj, result, command_exec_status='ok', info_messages=[], warning_messages=[], error_messages=[]): """Build a response from a previouslsy received command message, send it and return number of sent bytes. :param result: Used to send back the result of th...
def receive(self, ikpdb): """Waits for a message from the debugger and returns it as a dict. """ # with self._connection_lock: while self._network_loop: _logger.n_debug("Enter socket.recv(%s) with self._received_data = %s", self.SOCKET_BUFFER_SIZE...
def clear(self): """ Clear a breakpoint by removing it from all lists. """ del IKBreakpoint.breakpoints_by_file_and_line[self.file_name, self.line_number] IKBreakpoint.breakpoints_by_number[self.number] = None IKBreakpoint.breakpoints_files[self.file_name].remove(self.line_number...
def update_active_breakpoint_flag(cls): """ Checks all breakpoints to find wether at least one is active and update `any_active_breakpoint` accordingly. """ cls.any_active_breakpoint=any([bp.enabled for bp in cls.breakpoints_by_number if bp])
def lookup_effective_breakpoint(cls, file_name, line_number, frame): """ Checks if there is an enabled breakpoint at given file_name and line_number. Check breakpoint condition if any. :return: found, enabled and condition verified breakpoint or None :rtype: IKPdbBreakpoint or ...
def get_breakpoints_list(cls): """:return: a list of all breakpoints. :rtype: a list of dict with this keys: `breakpoint_number`, `bp.number`, `file_name`, `line_number`, `condition`, `enabled`. Warning: IKPDb line numbers are 1 based so line number conversion ...
def disable_all_breakpoints(cls): """ Disable all breakpoints and udate `active_breakpoint_flag`. """ for bp in cls.breakpoints_by_number: if bp: # breakpoint #0 exists and is always None bp.enabled = False cls.update_active_breakpoint_flag() return
def backup_breakpoints_state(cls): """ Returns the state of all breakpoints in a list that can be used later to restore all breakpoints state""" all_breakpoints_state = [] for bp in cls.breakpoints_by_number: if bp: all_breakpoints_state.append((bp.number, ...
def restore_breakpoints_state(cls, breakpoints_state_list): """Restore the state of breakpoints given a list provided by backup_breakpoints_state(). If list of breakpoint has changed since backup missing or added breakpoints are ignored. breakpoints_state_list is a list of tup...
def canonic(self, file_name): """ returns canonical version of a file name. A canonical file name is an absolute, lowercase normalized path to a given file. """ if file_name == "<" + file_name[1:-1] + ">": return file_name c_file_name = self.file_name_cache.g...
def normalize_path_in(self, client_file_name): """Translate a (possibly incomplete) file or module name received from debugging client into an absolute file name. """ _logger.p_debug("normalize_path_in(%s) with os.getcwd()=>%s", client_file_name, os.getcwd()) # remove cl...
def normalize_path_out(self, path): """Normalizes path sent to client :param path: path to normalize :return: normalized path """ if path.startswith(self._CWD): normalized_path = path[len(self._CWD):] else: normalized_path = path # For remo...
def object_properties_count(self, o): """ returns the number of user browsable properties of an object. """ o_type = type(o) if isinstance(o, (dict, list, tuple, set)): return len(o) elif isinstance(o, (type(None), bool, float, str, int, ...
def extract_object_properties(self, o, limit_size=False): """Extracts all properties from an object (eg. f_locals, f_globals, user dict, instance ...) and returns them as an array of variables. """ try: prop_str = repr(o)[:512] except: prop_str = "Error w...
def extract_name_value_type(self, name, value, limit_size=False): """Extracts value of any object, eventually reduces it's size and returns name, truncated value and type (for str with size appended) """ MAX_STRING_LEN_TO_RETURN = 487 try: t_value = repr(value) ...
def dump_frames(self, frame): """ dumps frames chain in a representation suitable for serialization and remote (debugger) client usage. """ current_thread = threading.currentThread() frames = [] frame_browser = frame # Browse the frame chain as far as...
def evaluate(self, frame_id, expression, global_context=False, disable_break=False): """Evaluates 'expression' in the context of the frame identified by 'frame_id' or globally. Breakpoints are disabled depending on 'disable_break' value. Returns a tuple of value and type both as str. ...
def let_variable(self, frame_id, var_name, expression_value): """ Let a frame's var with a value by building then eval a let expression with breakoints disabled. """ breakpoints_backup = IKBreakpoint.backup_breakpoints_state() IKBreakpoint.disable_all_breakpoints() let_...
def setup_step_into(self, frame, pure=False): """Setup debugger for a "stepInto" """ self.frame_calling = frame if pure: self.frame_stop = None else: self.frame_stop = frame self.frame_return = None self.frame_suspend = False self.p...