code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not (0 <= bp_number < len(IKBreakpoint.breakpoints_by_number)): return "Found no breakpoint numbered: %s" % bp_number bp = IKBreakpoint.breakpoints_by_number[bp_number] if not bp: return "Found no breakpoint numbered %s" % bp_number _logger.b_debug(" ...
def change_breakpoint_state(self, bp_number, enabled, condition=None)
Change breakpoint status or `condition` expression. :param bp_number: number of breakpoint to change :return: None or an error message (string)
4.397576
4.402995
0.998769
if not (0 <= breakpoint_number < len(IKBreakpoint.breakpoints_by_number)): return "Found no breakpoint numbered %s" % breakpoint_number bp = IKBreakpoint.breakpoints_by_number[breakpoint_number] if not bp: return "Found no breakpoint numbered: %s" % breakpoint_nu...
def clear_breakpoint(self, breakpoint_number)
Delete a breakpoint identified by it's number. :param breakpoint_number: index of breakpoint to delete :type breakpoint_number: int :return: an error message or None
4.784962
4.740635
1.00935
import __main__ __main__.__dict__.clear() __main__.__dict__.update({"__name__" : "__main__", "__file__" : filename, "__builtins__": __builtins__,}) self.mainpyfile = self.canonic(filename) #statem...
def _runscript(self, filename)
Launchs debugged program execution using the execfile() builtin. We reset and setup the __main__ dict to allow the script to run in __main__ namespace. This is required for imports from __main__ to run correctly. Note that this has the effect to wipe IKP3db's vars ...
8.122504
7.070907
1.148722
if id is not None and name is not None: raise ValueError("id and name cannot specified together") json_elements = self.rest_client.make_request(url)[key] return [eclass(element, self.rest_client) for element in json_elements if _exact_resource(element, id) a...
def _get_elements(self, url, key, eclass, id=None, name=None)
Get elements matching `id` or `name` Args: url(str): url of children. key(str): key in the returned JSON. eclass(subclass type of :py:class:`_ResourceElement`): element class to create instances of. id(str, optional): only return resources whose `id` property mat...
4.676262
4.501243
1.038882
elements = self._get_elements(url, key, eclass, id=id) if not elements: raise ValueError("No resource matching: {0}".format(id)) if len(elements) == 1: return elements[0] raise ValueError("Multiple resources matching: {0}".format(id))
def _get_element_by_id(self, url, key, eclass, id)
Get a single element matching an `id` Args: url(str): url of children. key(str): key in the returned JSON. eclass(subclass type of :py:class:`_ResourceElement`): element class to create instances of. id(str): return resources whose `id` property matches the given...
2.592701
2.641766
0.981428
if hasattr(self, 'domain'): return Domain(self.rest_client.make_request(self.domain), self.rest_client)
def get_domain(self)
Get the Streams domain for the instance that owns this view. Returns: Domain: Streams domain for the instance owning this view.
5.557917
5.323001
1.044132
return Instance(self.rest_client.make_request(self.instance), self.rest_client)
def get_instance(self)
Get the Streams instance that owns this view. Returns: Instance: Streams instance owning this view.
8.875833
15.906976
0.557984
return Job(self.rest_client.make_request(self.job), self.rest_client)
def get_job(self)
Get the Streams job that owns this view. Returns: Job: Streams Job owning this view.
8.011584
10.425463
0.768463
if self._data_fetcher: self._data_fetcher.stop.set() self._data_fetcher = None
def stop_data_fetch(self)
Stops the thread that fetches data from the Streams view server.
3.586943
3.096462
1.1584
self.stop_data_fetch() self._data_fetcher = _ViewDataFetcher(self, self._tuple_fn) t = threading.Thread(target=self._data_fetcher) t.start() return self._data_fetcher.items
def start_data_fetch(self)
Starts a thread that fetches data from the Streams view server. Each item in the returned `Queue` represents a single tuple on the stream the view is attached to. Returns: queue.Queue: Queue containing view data. .. note:: This is a queue of the tuples coverted to ...
5.423536
4.804597
1.128822
tuples = list() if timeout is None: while len(tuples) < max_tuples: fetcher = self._data_fetcher if not fetcher: break tuples.append(fetcher.items.get()) return tuples timeout = float(timeout) ...
def fetch_tuples(self, max_tuples=20, timeout=None)
Fetch a number of tuples from this view. Fetching of data must have been started with :py:meth:`start_data_fetch` before calling this method. If ``timeout`` is ``None`` then the returned list will contain ``max_tuples`` tuples. Otherwise if the timeout is reached the list may c...
2.466165
2.583592
0.954549
import ipywidgets as widgets vn = widgets.Text(value=self.description, description=self.name, disabled=True) active = widgets.Valid(value=True, description='Fetching', readout='Stopped') out = widgets.Output(layout={'border': '1px solid black'}) hb = widgets.HBox([vn, ac...
def display(self, duration=None, period=2)
Display a view within a Jupyter or IPython notebook. Provides an easy mechanism to visualize data on a stream using a view. Tuples are fetched from the view and displayed in a table within the notebook cell using a ``pandas.DataFrame``. The table is continually updated with the...
3.698017
3.786529
0.976624
view_items = [ViewItem(json_view_items, self.rest_client) for json_view_items in self.rest_client.make_request(self.viewItems)['viewItems']] logger.debug("Retrieved " + str(len(view_items)) + " items from view " + self.name) return view_items
def get_view_items(self)
Get a list of :py:class:`ViewItem` elements associated with this view. Returns: list(ViewItem): List of ViewItem(s) associated with this view.
4.305226
4.500499
0.956611
if hasattr(self, "applicationLogTrace") and self.applicationLogTrace is not None: logger.debug("Retrieving application logs from: " + self.applicationLogTrace) if not filename: filename = _file_name('job', self.id, '.tar.gz') return self.rest_client...
def retrieve_log_trace(self, filename=None, dir=None)
Retrieves the application log and trace files of the job and saves them as a compressed tar file. An existing file with the same name will be overwritten. Args: filename (str): name of the created tar file. Defaults to `job_<id>_<timestamp>.tar.gz` where `id` is the job identifier ...
4.593623
4.074615
1.127376
return self._get_elements(self.views, 'views', View, name=name)
def get_views(self, name=None)
Get the list of :py:class:`~streamsx.rest_primitives.View` elements associated with this job. Args: name(str, optional): Returns view(s) matching `name`. `name` can be a regular expression. If `name` is not supplied, then all views associated with this instance are returned. ...
6.510339
10.324876
0.630549
return self._get_elements(self.operators, 'operators', Operator, name=name)
def get_operators(self, name=None)
Get the list of :py:class:`Operator` elements associated with this job. Args: name(str): Only return operators matching `name`, where `name` can be a regular expression. If `name` is not supplied, then all operators for this job are returned. Returns: list(Oper...
7.080779
10.096703
0.701296
return self.rest_client._sc._delegator._cancel_job(self, force)
def cancel(self, force=False)
Cancel this job. Args: force (bool, optional): Forcefully cancel this job. Returns: bool: True if the job was cancelled, otherwise False if an error occurred.
26.398529
41.124607
0.641916
return self._get_elements(self.metrics, 'metrics', Metric, name=name)
def get_metrics(self, name=None)
Get metrics for this operator. Args: name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If `name` is not supplied, then all metrics for this operator are returned. Returns: list(Metric): List of matching metrics...
8.389837
13.028796
0.643946
if hasattr(self, 'host') and self.host: return Host(self.rest_client.make_request(self.host), self.rest_client)
def get_host(self)
Get resource this operator is currently executing in. If the operator is running on an externally managed resource ``None`` is returned. Returns: Host: Resource this operator is running on. .. versionadded:: 1.9
4.622638
5.006714
0.923288
return PE(self.rest_client.make_request(self.pe), self.rest_client)
def get_pe(self)
Get the Streams processing element this operator is executing in. Returns: PE: Processing element for this operator. .. versionadded:: 1.9
11.179821
17.73716
0.630305
if hasattr(self, "applicationTrace") and self.applicationTrace is not None: logger.debug("Retrieving PE trace: " + self.applicationTrace) if not filename: filename = _file_name('pe', self.id, '.trace') return self.rest_client._retrieve_file(self.appli...
def retrieve_trace(self, filename=None, dir=None)
Retrieves the application trace files for this PE and saves them as a plain text file. An existing file with the same name will be overwritten. Args: filename (str): name of the created file. Defaults to `pe_<id>_<timestamp>.trace` where `id` is the PE identifier and `timestamp` is...
5.335423
4.464109
1.195182
if hasattr(self, "consoleLog") and self.consoleLog is not None: logger.debug("Retrieving PE console log: " + self.consoleLog) if not filename: filename = _file_name('pe', self.id, '.stdouterr') return self.rest_client._retrieve_file(self.conso...
def retrieve_console_log(self, filename=None, dir=None)
Retrieves the application console log (standard out and error) files for this PE and saves them as a plain text file. An existing file with the same name will be overwritten. Args: filename (str): name of the created file. Defaults to `pe_<id>_<timestamp>.stdouterr` where `id` is t...
5.614686
4.570426
1.228482
if hasattr(self, 'resourceAllocation'): return ResourceAllocation(self.rest_client.make_request(self.resourceAllocation), self.rest_client)
def get_resource_allocation(self)
Get the :py:class:`ResourceAllocation` element tance. Returns: ResourceAllocation: Resource allocation used to access information about the resource where this PE is running. .. versionadded:: 1.9
5.36701
6.185173
0.867722
return Resource(self.rest_client.make_request(self.resource), self.rest_client)
def get_resource(self)
Get the :py:class:`Resource` of the resource allocation. Returns: Resource: Resource for this allocation. .. versionadded:: 1.9
7.685552
12.291228
0.625288
if self.applicationResource: return self._get_elements(self.jobs, 'jobs', Job, None, name) else: return []
def get_jobs(self, name=None)
Retrieves jobs running on this resource in its instance. Args: name (str, optional): Only return jobs containing property **name** that matches `name`. `name` can be a regular expression. If `name` is not supplied, then all jobs are returned. Returns: list(Job):...
11.417245
5.766152
1.980046
return OperatorOutputPort(self.rest_client.make_request(self.operatorOutputPort), self.rest_client)
def get_operator_output_port(self)
Get the output port of this exported stream. Returns: OperatorOutputPort: Output port of this exported stream.
9.754929
11.795548
0.827001
oop = self.get_operator_output_port() if not hasattr(oop, 'export'): return export = oop.export if export['type'] != 'properties': return seen_export_type = False topic = None for p in export['properties']: if p['ty...
def _as_published_topic(self)
This stream as a PublishedTopic if it is published otherwise None
4.662451
4.239193
1.099844
service = Instance._find_service_def(config) if not service: raise ValueError() endpoint = service['connection_info'].get('serviceRestEndpoint') resource_url, name = Instance._root_from_endpoint(endpoint) sc = streamsx.rest.StreamsConnection(resource_url=res...
def of_service(config)
Connect to an IBM Streams service instance running in IBM Cloud Private for Data. The instance is specified in `config`. The configuration may be code injected from the list of services in a Jupyter notebook running in ICPD or manually created. The code that selects a service instance by name is:: ...
7.413671
5.431852
1.364851
return self._get_element_by_id(self.jobs, 'jobs', Job, str(id))
def get_job(self, id)
Retrieves a job matching the given `id` Args: id (str): Job `id` to match. Returns: Job: Job matching the given `id` Raises: ValueError: No resource matches given `id` or multiple resources matching given `id`
8.799585
15.230212
0.577772
published_topics = [] # A topic can be published multiple times # (typically with the same schema) but the # returned list only wants to contain a topic,schema # pair once. I.e. the list of topics being published is # being returned, not the list of streams. ...
def get_published_topics(self)
Get a list of published topics for this instance. Streams applications publish streams to a a topic that can be subscribed to by other applications. This allows a microservice approach where publishers and subscribers are independent of each other. A published stream has a topic and a ...
4.169456
3.745866
1.113082
if hasattr(self, 'applicationConfigurations'): return self._get_elements(self.applicationConfigurations, 'applicationConfigurations', ApplicationConfiguration, None, name)
def get_application_configurations(self, name=None)
Retrieves application configurations for this instance. Args: name (str, optional): Only return application configurations containing property **name** that matches `name`. `name` can be a regular expression. If `name` is not supplied, then all application configurations are returne...
6.405943
8.701557
0.736184
if not hasattr(self, 'applicationConfigurations'): raise NotImplementedError() cv = ApplicationConfiguration._props(name, properties, description) res = self.rest_client.session.post(self.applicationConfigurations, headers = {'Accept' : 'application/json'}, ...
def create_application_configuration(self, name, properties, description=None)
Create an application configuration. Args: name (str, optional): Only return application configurations containing property **name** that matches `name`. `name` can be a .. versionadded 1.12
5.031547
5.696321
0.883298
return self._delegator._submit_job(bundle=bundle, job_config=job_config)
def submit_job(self, bundle, job_config=None)
Submit a Streams Application Bundle (sab file) to this Streaming Analytics service. Args: bundle(str): path to a Streams application bundle (sab file) containing the application to be submitted job_config(JobConfig): a job configuration overlay ...
6.293609
9.031461
0.696854
return self._delegator.cancel_job(job_id=job_id, job_name = job_name)
def cancel_job(self, job_id=None, job_name=None)
Cancel a running job. Args: job_id (str, optional): Identifier of job to be canceled. job_name (str, optional): Name of job to be canceled. Returns: dict: JSON response for the job cancel operation.
4.370367
7.228645
0.60459
if self._jobs_url is None: self.get_instance_status() if self._jobs_url is None: raise ValueError("Cannot obtain jobs URL") return self._jobs_url
def _get_jobs_url(self)
Get & save jobs URL from the status call.
4.232842
3.280315
1.290377
payload = {} if job_name is not None: payload['job_name'] = job_name if job_id is not None: payload['job_id'] = job_id jobs_url = self._get_url('jobs_path') res = self.rest_client.session.delete(jobs_url, params=payload) _handle_http_erro...
def cancel_job(self, job_id=None, job_name=None)
Cancel a running job. Args: job_id (str, optional): Identifier of job to be canceled. job_name (str, optional): Name of job to be canceled. Returns: dict: JSON response for the job cancel operation.
2.574535
2.91575
0.882975
start_url = self._get_url('start_path') res = self.rest_client.session.put(start_url, json={}) _handle_http_errors(res) return res.json()
def start_instance(self)
Start the instance for this Streaming Analytics service. Returns: dict: JSON response for the instance start operation.
5.656282
6.155935
0.918834
stop_url = self._get_url('stop_path') res = self.rest_client.session.put(stop_url, json={}) _handle_http_errors(res) return res.json()
def stop_instance(self)
Stop the instance for this Streaming Analytics service. Returns: dict: JSON response for the instance stop operation.
5.572572
5.771409
0.965548
status_url = self._get_url('status_path') res = self.rest_client.session.get(status_url) _handle_http_errors(res) return res.json()
def get_instance_status(self)
Get the status the instance for this Streaming Analytics service. Returns: dict: JSON response for the instance status operation.
5.145228
5.294919
0.971729
job_id = self._delegator._submit_bundle(self, job_config) return self._instance.get_job(job_id)
def submit_job(self, job_config=None)
Submit this Streams Application Bundle (sab file) to its associated instance. Args: job_config(JobConfig): a job configuration overlay Returns: Job: Resulting job instance.
7.634149
6.951314
1.098231
import streamsx.st as st if st._has_local_install: return st._cancel_job(job.id, force, domain_id=job.get_instance().get_domain().id, instance_id=job.get_instance().id) return False
def _cancel_job(self, job, force)
Cancel job using streamtool.
7.294957
6.133886
1.189288
cv = ApplicationConfiguration._props(properties=properties, description=description) res = self.rest_client.session.patch(self.rest_self, headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'}, json=cv) _handle_http_...
def update(self, properties=None, description=None)
Update this application configuration. To create or update a property provide its key-value pair in `properties`. To delete a property provide its key with the value ``None`` in properties. Args: properties (dict): Property values to be updated. If ``None`` the pro...
5.820567
5.560718
1.046729
res = self.rest_client.session.delete(self.rest_self) _handle_http_errors(res)
def delete(self)
Delete this application configuration.
10.127101
8.438577
1.200096
if allow_none and schema is None: return schema if isinstance(schema, CommonSchema): return schema if isinstance(schema, StreamSchema): return schema if isinstance(schema, basestring): return StreamSchema(schema) py_types = { _spl_object: CommonSchema.P...
def _normalize(schema, allow_none=True)
Normalize a schema.
4.073504
4.001531
1.017986
if isinstance(schema, StreamSchema): return schema.schema() in _SCHEMA_COMMON if isinstance(schema, CommonSchema): return True if isinstance(schema, basestring): return is_common(StreamSchema(schema)) return False
def is_common(schema)
Is `schema` an common schema. Args: schema: Scheme to test. Returns: bool: ``True`` if schema is a common schema, otherwise ``False``.
4.086129
4.832689
0.845519
if isinstance(schema, CommonSchema): self._spl_type = False self._schema = schema.schema() self._style = self._default_style() else: self._spl_type = schema._spl_type self._schema = schema._schema self._style = schema._styl...
def _set(self, schema)
Set a schema from another schema
4.341649
4.06848
1.067143
if not named: return self._copy(tuple) if named == True or isinstance(named, basestring): return self._copy(self._make_named_tuple(name=named)) return self._copy(tuple)
def as_tuple(self, named=None)
Create a structured schema that will pass stream tuples into callables as ``tuple`` instances. If this instance represents a common schema then it will be returned without modification. Stream tuples with common schemas are always passed according to their definition. **Passing as tupl...
4.996543
4.724277
1.057631
if self._spl_type: raise TypeError("Not supported for declared SPL types") base = self.schema() extends = schema.schema() new_schema = base[:-1] + ',' + extends[6:] return StreamSchema(new_schema)
def extend(self, schema)
Extend a structured schema by another. For example extending ``tuple<rstring id, timestamp ts, float64 value>`` with ``tuple<float32 score>`` results in ``tuple<rstring id, timestamp ts, float64 value, float32 score>``. Args: schema(StreamSchema): Schema to extend this schema by. ...
12.14976
10.924179
1.11219
if is_common(schema): if name in op.params: del op.params[name] return if _is_pending(schema): ntp = 'pending' elif schema.style is tuple: ntp = 'tuple' elif schema.style is _spl_dict: ntp = 'dict' ...
def _fnop_style(schema, op, name)
Set an operator's parameter representing the style of this schema.
4.297866
3.966199
1.083623
for name, field in self.fields.items(): value = self.cleaned_data[name] if isinstance(value, UploadedFile): # Delete old file fname = self._s.get(name, as_type=File) if fname: try: defaul...
def save(self) -> None
Saves all changed values to the database.
2.458546
2.364776
1.039653
nonce = get_random_string(length=8) return '%s-%s/%s/%s.%s.%s' % ( self.obj._meta.model_name, self.attribute_name, self.obj.pk, name, nonce, name.split('.')[-1] )
def get_new_filename(self, name: str) -> str
Returns the file name to use based on the original filename of an uploaded file. By default, the file name is constructed as:: <model_name>-<attribute_name>/<primary_key>/<original_basename>.<random_nonce>.<extension>
5.754869
3.182959
1.808025
if not cmd_args.force: status = sas.get_instance_status() jobs = int(status['job_count']) if jobs: return status return sas.stop_instance()
def _stop(sas, cmd_args)
Stop the service if no jobs are running unless force is set
5.74337
4.110112
1.397376
streamsx._streams._version._mismatch_check('streamsx.topology.context') try: sr = run_cmd(args) sr['return_code'] = 0 except: sr = {'return_code':1, 'error': sys.exc_info()} return sr
def main(args=None)
Performs an action against a Streaming Analytics service.
8.033847
7.360705
1.091451
cmd_parser = argparse.ArgumentParser(description='Control commands for a Streaming Analytics service.') cmd_parser.add_argument('--service-name', help='Streaming Analytics service name') cmd_parser.add_argument('--full-response', action='store_true', help='Print the full JSON response.') subparser...
def _parse_args(args)
Argument parsing
2.71589
2.687684
1.010494
ofi = inspect.getouterframes(inspect.currentframe())[2] try: calling_class = ofi[0].f_locals['self'].__class__ except KeyError: calling_class = None # Tuple of file,line,calling_class,function_name return ofi[1], ofi[2], calling_class, ofi[3]
def _source_info()
Get information from the user's code (two frames up) to leave breadcrumbs for file, line, class and function.
4.001119
3.542408
1.129491
return streamsx.spl.op.Expression.expression('com.ibm.streamsx.topology.topic::' + self.name).spl_json()
def spl_json(self)
Internal method.
12.79899
9.715814
1.317336
_name = name if inspect.isroutine(func): pass elif callable(func): pass else: if _name is None: _name = type(func).__name__ func = streamsx.topology.runtime._IterableInstance(func) sl = _SourceLocation(_sou...
def source(self, func, name=None)
Declare a source stream that introduces tuples into the application. Typically used to create a stream of tuple from an external source, such as a sensor or reading from an external system. Tuples are obtained from an iterator obtained from the passed iterable or callable that returns ...
7.709908
7.676914
1.004298
schema = streamsx.topology.schema._normalize(schema) _name = self.graph._requested_name(name, 'subscribe') sl = _SourceLocation(_source_info(), "subscribe") # subscribe is never stateful op = self.graph.addOperator(kind="com.ibm.streamsx.topology.topic::Subscribe", sl=sl...
def subscribe(self, topic, schema=streamsx.topology.schema.CommonSchema.Python, name=None, connect=None, buffer_capacity=None, buffer_full_policy=None)
Subscribe to a topic published by other Streams applications. A Streams application may publish a stream to allow other Streams applications to subscribe to it. A subscriber matches a publisher if the topic and schema match. By default a stream is subscribed as :py:const:`~streamsx.topo...
5.095618
5.050492
1.008935
if location not in {'etc', 'opt'}: raise ValueError(location) if not os.path.isfile(path) and not os.path.isdir(path): raise ValueError(path) path = os.path.abspath(path) if location not in self._files: self._files[location] = [path] ...
def add_file_dependency(self, path, location)
Add a file or directory dependency into an Streams application bundle. Ensures that the file or directory at `path` on the local system will be available at runtime. The file will be copied and made available relative to the application directory. Location determines where the file ...
2.88286
2.522243
1.142975
self._pip_packages.append(str(requirement)) pr = pkg_resources.Requirement.parse(requirement) self.exclude_packages.add(pr.project_name)
def add_pip_package(self, requirement)
Add a Python package dependency for this topology. If the package defined by the requirement specifier is not pre-installed on the build system then the package is installed using `pip` and becomes part of the Streams application bundle (`sab` file). The package is expected to b...
5.070715
5.34481
0.948718
if name in self._submission_parameters: raise ValueError("Submission parameter {} already defined.".format(name)) sp = streamsx.topology.runtime._SubmissionParam(name, default, type_) self._submission_parameters[name] = sp return sp
def create_submission_parameter(self, name, default=None, type_=None)
Create a submission parameter. A submission parameter is a handle for a value that is not defined until topology submission time. Submission parameters enable the creation of reusable topology bundles. A submission parameter has a `name`. The name must be unique within the to...
3.879172
4.369872
0.887708
if not self._pip_packages: return reqs = '' for req in self._pip_packages: reqs += "{}\n".format(req) reqs_include = { 'contents': reqs, 'target':'opt/python/streams', 'name': 'requirements.txt'} if 'opt' ...
def _generate_requirements(self)
Generate the info to create requirements.txt in the toookit.
4.913068
4.774416
1.029041
if not self._has_jcp: jcp = self.graph.addOperator(kind="spl.control::JobControlPlane", name="JobControlPlane") jcp.viewable = False self._has_jcp = True
def _add_job_control_plane(self)
Add a JobControlPlane operator to the topology, if one has not already been added. If a JobControlPlane operator has already been added, this has no effect.
7.758289
5.26334
1.474024
stream = copy.copy(self) stream._alias = name return stream
def aliased_as(self, name)
Create an alias of this stream. Returns an alias of this stream with name `name`. When invocation of an SPL operator requires an :py:class:`~streamsx.spl.op.Expression` against an input port this can be used to ensure expression matches the input port alias regardless of the nam...
9.419785
10.722555
0.878502
if name is None: name = ''.join(random.choice('0123456789abcdef') for x in range(16)) if self.oport.schema == streamsx.topology.schema.CommonSchema.Python: if self._json_stream: view_stream = self._json_stream else: self._json...
def view(self, buffer_time = 10.0, sample_size = 10000, name=None, description=None, start=False)
Defines a view on a stream. A view is a continually updated sampled buffer of a streams's tuples. Views allow visibility into a stream from external clients such as Jupyter Notebooks, the Streams console, `Microsoft Excel <https://www.ibm.com/support/knowledgecenter/SSCRJU_4.2.0/com.ibm...
4.990296
4.578574
1.089924
if schema is None: schema = streamsx.topology.schema.CommonSchema.Python if func is None: func = streamsx.topology.runtime._identity if name is None: name = 'identity' ms = self._map(func, schema=schema, name=name)._layout('Map') ...
def map(self, func=None, name=None, schema=None)
Maps each tuple from this stream into 0 or 1 stream tuples. For each tuple on this stream ``result = func(tuple)`` is called. If `result` is not `None` then the result will be submitted as a tuple on the returned stream. If `result` is `None` then no tuple submission will occur. ...
8.610271
8.167896
1.05416
if func is None: func = streamsx.topology.runtime._identity if name is None: name = 'flatten' sl = _SourceLocation(_source_info(), 'flat_map') _name = self.topology.graph._requested_name(name, action='flat_map', func=func) statef...
def flat_map(self, func=None, name=None)
Maps and flatterns each tuple from this stream into 0 or more tuples. For each tuple on this stream ``func(tuple)`` is called. If the result is not `None` then the the result is iterated over with each value from the iterator that is not `None` will be submitted to the return stream. ...
7.474869
7.775607
0.961323
outport = self.oport if isinstance(self.oport.operator, streamsx.topology.graph.Marker): if self.oport.operator.kind == "$Union$": pto = self.topology.graph.addPassThruOperator() pto.addInputPort(outputPort=self.oport) outport = pto.ad...
def end_parallel(self)
Ends a parallel region by merging the channels into a single stream. Returns: Stream: Stream for which subsequent transformations are no longer parallelized. .. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel`
4.281992
4.285653
0.999146
self.oport.operator.config['parallel'] = True self.oport.operator.config['width'] = streamsx.topology.graph._as_spl_json(width, int) if name: name = self.topology.graph._requested_name(str(name), action='set_parallel') self.oport.operator.config['regionName'] = n...
def set_parallel(self, width, name=None)
Set this source stream to be split into multiple channels as the start of a parallel region. Calling ``set_parallel`` on a stream created by :py:meth:`~Topology.source` results in the stream having `width` channels, each created by its own instance of the callable:: ...
8.34434
7.048347
1.183872
# add job control plane if needed self.topology._add_job_control_plane() self.oport.operator.consistent(consistent_config) return self._make_placeable()
def set_consistent(self, consistent_config)
Indicates that the stream is the start of a consistent region. Args: consistent_config(consistent.ConsistentRegionConfig): the configuration of the consistent region. Returns: Stream: Returns this stream. .. versionadded:: 1.11
20.611538
23.653912
0.87138
win = Window(self, 'SLIDING') if isinstance(size, datetime.timedelta): win._evict_time(size) elif isinstance(size, int): win._evict_count(size) else: raise ValueError(size) return win
def last(self, size=1)
Declares a slding window containing most recent tuples on this stream. The number of tuples maintained in the window is defined by `size`. If `size` is an `int` then it is the count of tuples in the window. For example, with ``size=10`` the window always contains the last (most...
5.960074
5.496813
1.084278
if(not isinstance(streamSet,set)) : raise TypeError("The union operator parameter must be a set object") if(len(streamSet) == 0): return self op = self.topology.graph.addOperator("$Union$") op.addInputPort(outputPort=self.oport) for stream...
def union(self, streamSet)
Creates a stream that is a union of this stream and other streams Args: streamSet: a set of Stream objects to merge with this stream Returns: Stream:
3.852686
3.852781
0.999975
_name = name if _name is None: _name = 'print' fn = streamsx.topology.functions.print_flush if tag is not None: tag = str(tag) + ': ' fn = lambda v : streamsx.topology.functions.print_flush(tag + str(v)) sp = self.for_each(fn, name=_na...
def print(self, tag=None, name=None)
Prints each tuple to stdout flushing after each tuple. If `tag` is not `None` then each tuple has "tag: " prepended to it before printing. Args: tag: A tag to prepend to each tuple. name(str): Name of the resulting stream. When `None` defaults to a gener...
6.453265
5.09366
1.266921
sl = _SourceLocation(_source_info(), 'publish') schema = streamsx.topology.schema._normalize(schema) if schema is not None and self.oport.schema.schema() != schema.schema(): nc = None if schema == streamsx.topology.schema.CommonSchema.Json: schema...
def publish(self, topic, schema=None, name=None)
Publish this stream on a topic for other Streams applications to subscribe to. A Streams application may publish a stream to allow other Streams applications to subscribe to it. A subscriber matches a publisher if the topic and schema match. By default a stream is published using its sc...
5.680521
5.015197
1.132662
op = self.topology.graph.addOperator("$Autonomous$") op.addInputPort(outputPort=self.oport) oport = op.addOutputPort(schema=self.oport.schema) return Stream(self.topology, oport)
def autonomous(self)
Starts an autonomous region for downstream processing. By default IBM Streams processing is executed in an autonomous region where any checkpointing of operator state is autonomous (independent) of other operators. This method may be used to end a consistent region by starting a...
8.476165
6.265408
1.352851
sas = self._change_schema(streamsx.topology.schema.CommonSchema.String, 'as_string', name)._layout('AsString') sas.oport.operator.sl = _SourceLocation(_source_info(), 'as_string') return sas
def as_string(self, name=None)
Declares a stream converting each tuple on this stream into a string using `str(tuple)`. The stream is typed as a :py:const:`string stream <streamsx.topology.schema.CommonSchema.String>`. If this stream is already typed as a string stream then it will be returned (with no additional pr...
21.388739
14.732986
1.451759
func = streamsx.topology.runtime._json_force_object if force_object else None saj = self._change_schema(streamsx.topology.schema.CommonSchema.Json, 'as_json', name, func)._layout('AsJson') saj.oport.operator.sl = _SourceLocation(_source_info(), 'as_json') return saj
def as_json(self, force_object=True, name=None)
Declares a stream converting each tuple on this stream into a JSON value. The stream is typed as a :py:const:`JSON stream <streamsx.topology.schema.CommonSchema.Json>`. Each tuple must be supported by `JSONEncoder`. If `force_object` is `True` then each tuple that not a `dict` ...
12.417282
11.352672
1.093776
if self.oport.schema.schema() == schema.schema(): return self if func is None: func = streamsx.topology.functions.identity _name = name if _name is None: _name = action css = self._map(func, schema, name=_name) if self._plac...
def _change_schema(self, schema, action, name=None, func=None)
Internal method to change a schema.
8.114311
8.036487
1.009684
if self._submit_context is None: raise ValueError("View has not been created.") job = self._submit_context._job_access() self._view_object = job.get_views(name=self.name)[0]
def _initialize_rest(self)
Used to initialize the View object on first use.
8.906167
7.525941
1.183396
self._initialize_rest() return self._view_object.display(duration, period)
def display(self, duration=None, period=2)
Display a view within a Jupyter or IPython notebook. Provides an easy mechanism to visualize data on a stream using a view. Tuples are fetched from the view and displayed in a table within the notebook cell using a ``pandas.DataFrame``. The table is continually updated with the...
19.351313
24.235281
0.798477
assert not self.is_complete() self._marker.addInputPort(outputPort=stream.oport) self.stream.oport.schema = stream.oport.schema # Update the pending schema to the actual schema # Any downstream filters that took the reference # will be...
def complete(self, stream)
Complete the pending stream. Any connections made to :py:attr:`stream` are connected to `stream` once this method returns. Args: stream(Stream): Stream that completes the connection.
12.735107
12.235606
1.040824
tw = Window(self.stream, self._config['type']) tw._config['evictPolicy'] = self._config['evictPolicy'] tw._config['evictConfig'] = self._config['evictConfig'] if self._config['evictPolicy'] == 'TIME': tw._config['evictTimeUnit'] = 'MILLISECONDS' if isinstanc...
def trigger(self, when=1)
Declare a window with this window's size and a trigger policy. When the window is triggered is defined by `when`. If `when` is an `int` then the window is triggered every `when` tuples. For example, with ``when=5`` the window will be triggered every five tuples. If `when` is ...
3.019114
2.773434
1.088583
schema = streamsx.topology.schema.CommonSchema.Python sl = _SourceLocation(_source_info(), "aggregate") _name = self.topology.graph._requested_name(name, action="aggregate", func=function) stateful = self.stream._determine_statefulness(function) op = self.topolo...
def aggregate(self, function, name=None)
Aggregates the contents of the window when the window is triggered. Upon a window trigger, the supplied function is passed a list containing the contents of the window: ``function(items)``. The order of the window items in the list are the order in which they were each receive...
8.822536
9.141046
0.965156
assert _has_local_install url=[] ok = _run_st(['geturl', '--api'], lines=url) if not ok: raise ChildProcessError('streamtool geturl') return url[0]
def get_rest_api()
Get the root URL for the IBM Streams REST API.
24.886974
19.278084
1.290946
try: # if __package__ is defined, use it package_name = module.__package__ except AttributeError: package_name = None if package_name is None: # if __path__ is defined, the package name is the module name package_name = module.__name__ if not h...
def _get_package_name(module)
Gets the package name given a module object Returns: str: If the module belongs to a package, the package name. if the module does not belong to a package, None or ''.
2.890905
2.872372
1.006452
module_name = function.__module__ if module_name == '__main__': # get the main module object of the function main_module = inspect.getmodule(function) # get the module name from __file__ by getting the base name and removing the .py extension # e.g. test1.py => test1 ...
def _get_module_name(function)
Gets the function's module name Resolves the __main__ module to an actual module name Returns: str: the function's module name
2.724687
2.743784
0.99304
if (not hasattr(module, '__file__')) or module.__name__ in sys.builtin_module_names: return True if module.__name__ in _stdlib._STD_LIB_MODULES: return True amp = os.path.abspath(module.__file__) if 'site-packages' in amp: return False if amp.startswith(_STD_MODULE_DIR)...
def _is_builtin_module(module)
Is builtin or part of standard library
3.518918
3.330266
1.056648
dms = set() for um in inspect.getmembers(module, inspect.ismodule): dms.add(um[1]) for uc in inspect.getmembers(module, inspect.isclass): self._add_obj_module(dms, uc[1]) for ur in inspect.getmembers(module, inspect.isroutine): self._add_obj_...
def _find_dependent_modules(self, module)
Return the set of dependent modules for used modules, classes and routines.
3.036318
2.354451
1.289608
if module in self._processed_modules: return None if hasattr(module, "__name__"): mn = module.__name__ else: mn = '<unknown>' _debug.debug("add_dependencies:module=%s", module) # If the module in which the class/function is defined...
def add_dependencies(self, module)
Adds a module and its dependencies to the list of dependencies. Top-level entry point for adding a module and its dependecies.
3.728266
3.656039
1.019756
if mn in self.topology.include_packages: _debug.debug("_include_module:explicit using __include_packages: module=%s", mn) return True if '.' in mn: for include_package in self.topology.include_packages: if mn.startswith(include_package + '.')...
def _include_module(self, module, mn)
See if a module should be included or excluded based upon included_packages and excluded_packages. As some packages have the following format: scipy.special.specfun scipy.linalg Where the top-level package name is just a prefix to a longer package name, we don't want t...
2.344229
2.298923
1.019708
_debug.debug("_add_dependency:module=%s", mn) if _is_streamsx_module(module): _debug.debug("_add_dependency:streamsx module=%s", mn) return False if _is_builtin_module(module): _debug.debug("_add_dependency:builtin module=%s", mn) return...
def _add_dependency(self, module, mn)
Adds a module to the list of dependencies without handling the modules dependences. Modules in site-packages are excluded from being added into the toolkit. This mimics dill.
2.85505
2.782771
1.025974
settings = {} for key, v in self._h.defaults.items(): settings[key] = self._unserialize(v.value, v.type) if self._parent: settings.update(getattr(self._parent, self._h.attribute_name).freeze()) for key in self._cache(): settings[key] = self.ge...
def freeze(self) -> dict
Returns a dictionary of all settings set for this object, including any values of its parents or hardcoded defaults.
5.532208
4.536277
1.219548
if as_type is None and key in self._h.defaults: as_type = self._h.defaults[key].type if key in self._cache(): value = self._cache()[key] else: value = None if self._parent: value = getattr(self._parent, self._h.attribute_n...
def get(self, key: str, default=None, as_type: type = None, binary_file=False)
Get a setting specified by key ``key``. Normally, settings are strings, but if you put non-strings into the settings object, you can request unserialization by specifying ``as_type``. If the key does not have a harcdoded default type, omitting ``as_type`` always will get you a string. I...
2.885928
2.783109
1.036944
wc = self._write_cache() if key in wc: s = wc[key] else: s = self._type(object=self._obj, key=key) s.value = self._serialize(value) s.save() self._cache()[key] = s.value wc[key] = s self._flush_external_cache()
def set(self, key: str, value: Any) -> None
Stores a setting to the database of its object. The write to the database is performed immediately and the cache in the cache backend is flushed. The cache within this object will be updated correctly.
5.940431
4.456031
1.333121
if key in self._write_cache(): self._write_cache()[key].delete() del self._write_cache()[key] if key in self._cache(): del self._cache()[key] self._flush_external_cache()
def delete(self, key: str) -> None
Deletes a setting from this object's storage. The write to the database is performed immediately and the cache in the cache backend is flushed. The cache within this object will be updated correctly.
4.606646
4.010069
1.14877
vcap_services = vcap_services or os.environ.get('VCAP_SERVICES') if not vcap_services: raise ValueError( "VCAP_SERVICES information must be supplied as a parameter or as environment variable 'VCAP_SERVICES'") # If it was passed to config as a dict, simply return it if isinstance...
def _get_vcap_services(vcap_services=None)
Retrieves the VCAP Services information from the `ConfigParams.VCAP_SERVICES` field in the config object. If `vcap_services` is not specified, it takes the information from VCAP_SERVICES environment variable. Args: vcap_services (str): Try to parse as a JSON string, otherwise, try open it as a file. ...
2.71281
2.819425
0.962186
service_name = service_name or os.environ.get('STREAMING_ANALYTICS_SERVICE_NAME', None) # Get the service corresponding to the SERVICE_NAME services = vcap_services['streaming-analytics'] creds = None for service in services: if service['name'] == service_name: creds = servi...
def _get_credentials(vcap_services, service_name=None)
Retrieves the credentials of the VCAP Service of the specified `service_name`. If `service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment variable. Args: vcap_services (dict): A dict representation of the VCAP Services information. servic...
2.949373
2.885029
1.022303
resources_url = credentials['rest_url'] + credentials['resources_path'] try: response_raw = session.get(resources_url, auth=(credentials['userid'], credentials['password'])) response = response_raw.json() except: logger.error("Error while retrieving rest REST url from: " + resou...
def _get_rest_api_url_from_creds(session, credentials)
Retrieves the Streams REST API URL from the provided credentials. Args: session (:py:class:`requests.Session`): A Requests session object for making REST calls credentials (dict): A dict representation of the credentials. Returns: str: The remote Streams REST API URL.
3.919405
3.900463
1.004857
res = rest_client.make_request(credentials[_IAMConstants.V2_REST_URL]) base = res['streams_self'] end = base.find('/instances') return base[:end] + '/resources'
def _get_iam_rest_api_url_from_creds(rest_client, credentials)
Retrieves the Streams REST API URL from the provided credentials using iam authentication. Args: rest_client (:py:class:`rest_primitives._IAMStreamsRestClient`): A client for making REST calls using IAM authentication credentials (dict): A dict representation of the credentials. Returns: ...
13.562258
12.876807
1.053231
self._resource_url = self._resource_url or st.get_rest_api() return self._resource_url
def resource_url(self)
str: Root URL for IBM Streams REST API
8.488147
5.245555
1.61816