code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Changing the date in a dateline is not supported yet, but if it gets implemented someday this will need to be # changed if date_line._text is not None: return date_line._text else: return date_utils.unicode_strftime(date_line.date, self.date_format)
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.
7.006569
6.269803
1.11751
line = [] # The entry is new, it didn't come from an existing line, so let's just return a simple text representation of # it if not entry._text: flags_text = self.flags_to_text(entry.flags) duration_text = self.duration_to_text(entry.duration) ...
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.
3.711721
3.536278
1.049612
split_line = re.match(self.entry_line_regexp, text) if not split_line: raise ParseError("Line must have an alias, a duration and a description") alias = split_line.group('alias') start_time = end_time = None if split_line.group('start_time') is not None: ...
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`.
2.616225
2.55442
1.024195
# Try to match dd/mm/yyyy format date_matches = re.match(self.DATE_LINE_REGEXP, text) # If no match, try with yyyy/mm/dd format if date_matches is None: date_matches = re.match(self.US_DATE_LINE_REGEXP, text) if date_matches is None: raise Value...
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.
2.023803
1.927997
1.049692
flags = set() reversed_flags_repr = {v: k for k, v in self.flags_repr.items()} for flag_repr in text: if flag_repr not in reversed_flags_repr: raise KeyError("Flag '%s' is not recognized" % flag_repr) else: flags.add(reversed_flags...
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.
2.753647
2.850301
0.96609
text = text.strip() lines = text.splitlines() parsed_lines = [] encountered_date = False for (lineno, line) in enumerate(lines, 1): try: parsed_line = self.parse_line(line) if isinstance(parsed_line, DateLine): ...
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 raised.
3.185508
2.692839
1.182955
text = text.strip().replace('\t', ' ' * 4) # The logic is: if the line starts with a #, consider it's a comment (TextLine), otherwise try to parse it as a # date and if this fails, try to parse it as an entry. If this fails too, the line is not valid if len(text) == 0 or text.s...
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 transformation methods :meth:`create_date_fro...
3.861146
3.008976
1.283209
_lines = lines[:] _lines = trim(_lines) if self.add_date_to_bottom is None: add_date_to_bottom = is_top_down(lines) else: add_date_to_bottom = self.add_date_to_bottom if add_date_to_bottom: _lines.append(TextLine('')) _li...
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).
2.886844
2.450012
1.178298
ctx.obj['view'].updating_projects_database() projects = [] for backend_name, backend_uri in ctx.obj['settings'].get_backends(): backend = plugins_registry.get_backend(backend_name) backend_projects = backend.get_projects() for project in backend_projects: project....
def update(ctx)
Synchronizes your project database with the server and updates the shared aliases.
3.68558
3.503245
1.052048
if not self._attribute_pages: self.fetch_attributes() result = {} for page in self._attribute_pages.values(): result.update(page.attributes) return result
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.
3.989894
3.444129
1.158463
return [backend for backend in self._backends_registry.values() if isinstance(backend, backend_class)]
def get_backends_by_class(self, backend_class)
Return a list of backends that are instances of the given `backend_class`.
3.667455
2.979589
1.230859
for name, uri in backends.items(): self._backends_registry[name] = self._load_backend(uri, context)
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 backend names as keys and URIs as values.
5.561588
4.720068
1.178286
parsed = parse.urlparse(backend_uri) options = dict(parse.parse_qsl(parsed.query)) try: backend = self._entry_points[self.BACKENDS_ENTRY_POINT][parsed.scheme].load() except KeyError: raise BackendNotFoundError( "The requested backend `%s`...
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.
3.083212
3.142723
0.981064
for command in self._entry_points[self.COMMANDS_ENTRY_POINT].values(): command.load()
def register_commands(self)
Load entry points for custom commands.
8.262492
5.583324
1.479852
meth = self.add_flag if add else self.remove_flag meth(flag)
def _add_or_remove_flag(self, flag, add)
Add the given `flag` if `add` is True, remove it otherwise.
4.894657
4.475841
1.093572
_check() rc = _ec.get_application_configuration(name) if rc is False: raise ValueError("Application configuration {0} not found.".format(name)) return rc
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 Streams applications require, such as: * Databas...
7.070809
8.230946
0.859052
args = (_get_opc(primitive), port_index, tuple_) _ec._submit(args)
def _submit(primitive, port_index, tuple_)
Internal method to submit a tuple
14.131276
11.768312
1.20079
args = (self.__ptr, int(value)) _ec.metric_set(args)
def value(self, value)
Set the current value of the metric.
23.994707
13.584517
1.766328
try: plc = self._op()._placement if not 'resourceTags' in plc: plc['resourceTags'] = set() return plc['resourceTags'] except TypeError: return frozenset()
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 `ingest`. Processing logic can be...
7.050294
5.370992
1.312662
streamsx._streams._version._mismatch_check(__name__) graph = graph.graph if not graph.operators: raise ValueError("Topology {0} does not contain any streams.".format(graph.topology.name)) context_submitter = _SubmitContextFactory(graph, config, username, password).get_submit_context(ctxty...
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. `ctxtype` defines how the application will be submitted, see :py:class:`ContextTypes`. ...
7.455515
7.221039
1.032471
if 'credentials' in service_def: credentials = service_def['credentials'] else: credentials = service_def service = {} service['credentials'] = credentials service['name'] = _name_from_service_definition(service_def) vcap = {'streaming-analytics': [service]} return vcap
def _vcap_from_service_definition(service_def)
Turn a service definition into a vcap services containing a single service.
2.936873
2.624898
1.118852
"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)
Pass the VCAP through the environment to the java submission
7.349247
3.910134
1.879538
"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(sc._delegator, streamsx.r...
def _get_java_env(self)
Set env vars from connection if set
5.736609
4.937635
1.161813
jc = JobConfig() jc.comment = overlays.get('comment') if 'jobConfigOverlays' in overlays: if len(overlays['jobConfigOverlays']) >= 1: jco = copy.deepcopy(overlays['jobConfigOverlays'][0]) # Now extract the logical information ...
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 as ``raw_overlay``. Args: ...
3.47025
3.260071
1.064471
if self._comment: config['comment'] = self._comment jco = {} config["jobConfigOverlays"] = [jco] if self._raw_overlay: jco.update(self._raw_overlay) jc = jco.get('jobConfig', {}) if self.job_name is not None: jc["jobName"] ...
def _add_overlays(self, config)
Add this as a jobConfigOverlays JSON to config.
3.322657
3.135645
1.059641
if self._submitter and hasattr(self._submitter, '_job_access'): return self._submitter._job_access() return None
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.
6.253478
6.505654
0.961237
if not hasattr(self, 'jobId'): return try: import ipywidgets as widgets if not description: description = 'Cancel job: ' description += self.name if hasattr(self, 'name') else self.job.name button = widgets.Butto...
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. A job may be cancelled directly using:: su...
2.48208
2.522773
0.98387
self.defaults[key] = HierarkeyDefault(value, default_type)
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 values for this key to, defaults to ``str``.
11.91886
10.899766
1.093497
self.types.append(HierarkeyType(type=type, serialize=serialize, unserialize=unserialize))
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. :param unserialize: A callable that takes a string and returns an object of type ``type``.
5.293373
5.589024
0.947101
if isinstance(cache_namespace, type): raise ImproperlyConfigured('Incorrect decorator usage, you need to use .add_global() ' 'instead of .add_global') def wrapper(wrapped_class): if issubclass(wrapped_class, models.Model): ...
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 the class this is applied to and the ``attribute_...
3.250406
3.131618
1.037932
if isinstance(cache_namespace, type): raise ImproperlyConfigured('Incorrect decorator usage, you need to use .add() instead of .add') def wrapper(model): if not issubclass(model, models.Model): raise ImproperlyConfigured('Hierarkey.add() can only be invo...
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 of the class this is applied to and the ``attribute_name`` of this ...
3.175835
3.060829
1.037573
import streamsx._streams._numpy if hasattr(value, 'spl_json'): return value if isinstance(value, Enum): value = streamsx.spl.op.Expression.expression(value.name) npcnv = streamsx._streams._numpy.as_spl_expr(value) if npcnv is not None: return npcnv retu...
def _as_spl_expr(value)
Return value converted to an SPL expression if needed other otherwise value.
6.371635
6.140205
1.037691
_id = self._id_gen self._id_gen += 1 return prefix + str(_id)
def _unique_id(self, prefix)
Generate a unique (within the graph) identifer internal to graph generation.
4.389112
4.08254
1.075094
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: pn = name + '_' + str(n) if pn not in self._used_names: self._us...
def _requested_name(self, name, action=None, func=None)
Create a unique name for an operator or a stream.
3.60012
3.381331
1.064705
if isinstance(self, Marker): return colocate_tag = '__spl_' + why + '$' + str(self.index) self._colocate_tag(colocate_tag) for op in others: op._colocate_tag(colocate_tag)
def colocate(self, others, why)
Colocate this operator with another.
6.174095
5.695099
1.084107
if '::' in kind: ns, name = kind.rsplit('::', 1) ns += '._spl' else: raise ValueError('Main composite requires a namespace qualified name: ' + str(kind)) topo = streamsx.topology.topology.Topology(name=name, namespace=ns) if toolkits: for tk_path in toolkits: ...
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 `Topology` may be used like any other topology instance in...
4.832922
3.677982
1.314015
if stream not in self._inputs: raise ValueError("Stream is not an input of this operator.") if len(self._inputs) == 1: return Expression('attribute', name) else: iport = self._op().inputPorts[self._inputs.index(stream)] return Expression('...
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 from. name(str): Name of the attrib...
5.367894
4.18759
1.281858
if stream not in self.outputs: raise ValueError("Stream is not an output of this operator.") e = self.expression(value) e._stream = stream return e
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: Expression: Output assignment ex...
6.609075
5.629261
1.174057
return super(Source, self).output(self.stream, value)
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 the context of this operator.
13.340126
22.370407
0.596329
return super(Map, self).attribute(self._inputs[0], name)
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 attribute.
14.072087
21.689348
0.648802
return super(Map, self).output(self.stream, value)
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 the context of this operator.
13.53684
21.058432
0.642823
if isinstance(value, Expression): # Clone the expression to allow it to # be used in multiple contexts return Expression(value._type, value._value) if hasattr(value, 'spl_json'): sj = value.spl_json() return Expression(sj['type'], sj['...
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`.
5.613832
5.328098
1.053628
_splj = {} _splj["type"] = self._type _splj["value"] = self._value return _splj
def spl_json(self)
Private method. May be removed at any time.
4.881868
4.038206
1.20892
extractor = _Extractor(args) if extractor._cmd_args.verbose: print("spl-python-extract:", __version__) print("Topology toolkit location:", _topology_tk_dir()) tk_dir = extractor._tk_dir tk_streams = os.path.join(tk_dir, 'opt', 'python', 'streams') if not os.path.isdir(tk_stre...
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.
4.378208
4.039973
1.083722
'''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''' rootDir = os.path.join(_topology_tk_...
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
4.136234
2.352168
1.758477
'''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 name is obtained from the project directory...
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 name is obtained from the project directory name ...
3.286318
2.344016
1.402003
_parse_args(args) streamsx._streams._version._mismatch_check('streamsx.topology.context') srp = pkg_resources.working_set.find(pkg_resources.Requirement.parse('streamsx')) if srp is not None: srv = srp.parsed_version location = srp.location spkg = 'package' else: ...
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.
3.044839
2.818526
1.080295
return ConsistentRegionConfig(trigger=ConsistentRegionConfig.Trigger.OPERATOR_DRIVEN, drain_timeout=drain_timeout, reset_timeout=reset_timeout, max_consecutive_attempts=max_consecutive_attempts)
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: The drain timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default ...
3.193763
2.874337
1.11113
return ConsistentRegionConfig(trigger=ConsistentRegionConfig.Trigger.PERIODIC, period=period, drain_timeout=drain_timeout, reset_timeout=reset_timeout, max_consecutive_attempts=max_consecutive_attempts)
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 by `period`. Args: period: The trigger period. This may be either a :py:class:`datetime.timedelta` value or th...
2.967869
2.627464
1.129557
if isinstance(ts, datetime.datetime): return Timestamp.from_datetime(ts).tuple() elif isinstance(ts, Timestamp): return ts raise TypeError('Timestamp or datetime.datetime required')
def _get_timestamp_tuple(ts)
Internal method to get a timestamp tuple from a value. Handles input being a datetime or a Timestamp.
4.14746
4.09171
1.013625
td = dt - Timestamp._EPOCH seconds = td.days * 3600 * 24 seconds += td.seconds return Timestamp(seconds, td.microseconds*1000, machine_id)
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.
4.605499
4.504611
1.022397
import streamsx.topology.topology assert isinstance(topology, streamsx.topology.topology.Topology) tkinfo = dict() tkinfo['root'] = os.path.abspath(location) topology.graph._spl_toolkits.append(tkinfo)
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.
5.325608
5.506869
0.967084
import streamsx.topology.topology assert isinstance(topology, streamsx.topology.topology.Topology) tkinfo = dict() tkinfo['name'] = name tkinfo['version'] = version topology.graph._spl_toolkits.append(tkinfo)
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. The following examples describe how to specify a depen...
4.182806
3.722013
1.123802
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) elif cmd_args.main_composite is not None: app = _get_spl_app(cmd_args) elif cmd_args.bundle is not None: ...
def submit(args=None)
Performs the submit according to arguments and returns an object describing the result.
4.250156
4.423199
0.960878
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 Streaming Analytics service') ctx_group.add_argument('-...
def _parse_args(args)
Argument parsing
4.450701
4.397332
1.012137
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', action='store_true', help='Preload job onto all resources in the instance') jo_group.add_argument('--trace', choices=['error'...
def _define_jco_args(cmd_parser)
Define job configuration arguments. Returns groups defined, currently one.
4.502103
4.327058
1.040454
cfg = app.cfg if cmd_args.create_bundle: ctxtype = ctx.ContextTypes.BUNDLE elif cmd_args.service_name: cfg[ctx.ConfigParams.FORCE_REMOTE_BUILD] = True cfg[ctx.ConfigParams.SERVICE_NAME] = cmd_args.service_name ctxtype = ctx.ContextTypes.STREAMING_ANALYTICS_SERVICE sr...
def _submit_topology(cmd_args, app)
Submit a Python topology to the service. This includes an SPL main composite wrapped in a Python topology.
5.755861
5.642864
1.020025
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 'exception' in sr: rc = 1 elif 'status_code' in sr: try: r...
def _submit_bundle(cmd_args, app)
Submit an existing bundle to the service
4.201151
4.220057
0.99552
if not inspect.isfunction(wrapped): raise TypeError('A function is required') return _wrapforsplop(_OperatorType.Pipe, wrapped, 'position', False)
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. The value returned f...
19.877871
17.995436
1.104606
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 = 0 if style == 'tuple': sig = _inspect.signature(callable_) pmds = sig.parameters ...
def _define_fixed(wrapped, callable_)
For the callable see how many positional parameters are required
3.523403
3.422686
1.029426
@functools.wraps(wrapped) def _ignore(*args, **kwargs): return wrapped(*args, **kwargs) _ignore._splpy_optype = _OperatorType.Ignore _ignore._splpy_file = inspect.getsourcefile(wrapped) return _ignore
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.
4.335031
4.344416
0.99784
if not inspect.isfunction(wrapped): raise TypeError('A function is required') return _wrapforsplop(_OperatorType.Sink, wrapped, 'position', False)
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.for_each <for_each>` instea...
19.949587
20.229107
0.986182
port_index = self._splpy_output_ports[port_id] ec._submit(self, port_index, tuple_)
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-python`. Args: port_id:...
13.132554
12.016259
1.092899
def _to_tuples(tuple_): if isinstance(tuple_, tuple): return tuple_ if isinstance(tuple_, dict): return tuple(tuple_.get(name, None) for name in attributes) if isinstance(tuple_, list): lt = list() for ev in tuple_: if isi...
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
2.605963
2.563146
1.016705
ofns = list() for fn in obj._splpy_input_ports: ofns.append(getattr(obj, fn.__name__)) return ofns
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.
5.812468
5.692543
1.021067
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_, ei): return None raise e1[1] return None
def _splpy_all_ports_ready(callable_)
Call all_ports_ready for a primitive operator.
7.547862
6.696214
1.127184
if not ikpdb: return "Error: IKP3db must be launched before calling ikpd.set_trace()." if a_frame is None: a_frame = sys._getframe().f_back ikpdb._line_tracer(a_frame) return None
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: frame :return: An error mess...
8.230792
6.716376
1.225481
if not ikpdb: return "Error: IKP3db must be launched before calling ikpd.post_mortem()." if exc_info: trace_back = exc_info[2] elif trace_back and not exc_info: if sys.exc_info()[2] == trace_back: exc_info = sys.exc_info() else: return "missing param...
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. Caller can also pass an *exc_info* that will be used to extra...
5.195589
4.294028
1.209957
if not ikpdb_log_arg: return IKPdbLogger.enabled = True logging_configuration_string = ikpdb_log_arg.lower() for letter in logging_configuration_string: if letter in IKPdbLogger.DOMAINS: IKPdbLogger.DOMAINS[letter] = 10
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` logging level on the components of the debugg...
4.598335
4.543944
1.01197
with self._connection_lock: payload = { '_id': _id, 'command': command, 'result': result, 'commandExecStatus': 'ok', 'frames': frames, 'info_messages': info_messages, 'warning_mes...
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. :type command: str :param _id: Unique id of the sent message. Right now, it's always `None` for messages by debugger to client. :type _i...
3.12651
3.456702
0.904478
with self._connection_lock: # TODO: add a parameter to remove args from messages ? if True: del obj['args'] obj['result'] = result obj['commandExecStatus'] = command_exec_status obj['info_messages'] = info_messages ...
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 the command execution to the debugger client. :type result: dict See send() above for others paramete...
3.300142
3.279718
1.006227
# with self._connection_lock: while self._network_loop: _logger.n_debug("Enter socket.recv(%s) with self._received_data = %s", self.SOCKET_BUFFER_SIZE, self._received_data) try: # We may land here ...
def receive(self, ikpdb)
Waits for a message from the debugger and returns it as a dict.
3.49428
3.467997
1.007579
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) if len(IKBreakpoint.breakpoints_files[self.file_name]) == 0: ...
def clear(self)
Clear a breakpoint by removing it from all lists.
3.299078
2.891991
1.140763
cls.any_active_breakpoint=any([bp.enabled for bp in cls.breakpoints_by_number if bp])
def update_active_breakpoint_flag(cls)
Checks all breakpoints to find wether at least one is active and update `any_active_breakpoint` accordingly.
13.00655
6.185843
2.102632
bp = cls.breakpoints_by_file_and_line.get((file_name, line_number), None) if not bp: return None if not bp.enabled: return None if not bp.condition: return bp try: value = eval(bp.condition, frame....
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 None
2.385207
2.412395
0.98873
breakpoints_list = [] for bp in cls.breakpoints_by_number: if bp: # breakpoint #0 exists and is always None bp_dict = { 'breakpoint_number': bp.number, 'file_name': bp.file_name, 'line_number': bp.line_numb...
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 must be done by clients (eg. inouk.i...
2.822709
2.263285
1.247174
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 disable_all_breakpoints(cls)
Disable all breakpoints and udate `active_breakpoint_flag`.
11.254763
7.985
1.409488
all_breakpoints_state = [] for bp in cls.breakpoints_by_number: if bp: all_breakpoints_state.append((bp.number, bp.enabled, bp.condition,)) return all_breakpoints_s...
def backup_breakpoints_state(cls)
Returns the state of all breakpoints in a list that can be used later to restore all breakpoints state
4.086801
3.932768
1.039166
for breakpoint_state in breakpoints_state_list: bp = cls.breakpoints_by_number[breakpoint_state[0]] if bp: bp.enabled = breakpoint_state[1] bp.condition = breakpoint_state[2] cls.update_active_breakpoint_flag() return
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 tuple. Each tuple is of form: (breakpoint_number, enabled, conditi...
2.989855
2.818666
1.060734
if file_name == "<" + file_name[1:-1] + ">": return file_name c_file_name = self.file_name_cache.get(file_name) if not c_file_name: c_file_name = os.path.abspath(file_name) c_file_name = os.path.normcase(c_file_name) self.file_name_cache[f...
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.
2.104595
2.059408
1.021941
_logger.p_debug("normalize_path_in(%s) with os.getcwd()=>%s", client_file_name, os.getcwd()) # remove client CWD from file_path if client_file_name.startswith(self._CLIENT_CWD): file_name = client_file_name[len(self._CLIENT_CWD):] else: file_name...
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.
2.630129
2.589252
1.015787
if path.startswith(self._CWD): normalized_path = path[len(self._CWD):] else: normalized_path = path # For remote debugging preprend client CWD if self._CLIENT_CWD: normalized_path = os.path.join(self._CLIENT_CWD, normalized_path) _logg...
def normalize_path_out(self, path)
Normalizes path sent to client :param path: path to normalize :return: normalized path
3.754699
3.691296
1.017176
o_type = type(o) if isinstance(o, (dict, list, tuple, set)): return len(o) elif isinstance(o, (type(None), bool, float, str, int, bytes, types.ModuleType, types.MethodType, types.FunctionT...
def object_properties_count(self, o)
returns the number of user browsable properties of an object.
3.00752
2.981289
1.008798
try: prop_str = repr(o)[:512] except: prop_str = "Error while extracting value" _logger.e_debug("extract_object_properties(%s)", prop_str) var_list = [] if isinstance(o, dict): a_var_name = None a_var_value = None ...
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.
1.949858
1.911087
1.020287
MAX_STRING_LEN_TO_RETURN = 487 try: t_value = repr(value) except: t_value = "Error while extracting value" # convert all var names to string if isinstance(name, str): r_name = name else: r_name = repr(name) ...
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)
4.774658
4.566479
1.045589
current_thread = threading.currentThread() frames = [] frame_browser = frame # Browse the frame chain as far as we can _logger.f_debug("dump_frames(), frame analysis:") spacer = "" while hasattr(frame_browser, 'f_back') and frame_browser.f_back !...
def dump_frames(self, frame)
dumps frames chain in a representation suitable for serialization and remote (debugger) client usage.
3.488993
3.358633
1.038813
if disable_break: breakpoints_backup = IKBreakpoint.backup_breakpoints_state() IKBreakpoint.disable_all_breakpoints() if frame_id and not global_context: eval_frame = ctypes.cast(frame_id, ctypes.py_object).value global_vars = eval_frame.f_global...
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. Note that - depending on the CGI_ESCAPE_EVALUATE_OUTPUT attribute - value is escap...
3.459157
3.197786
1.081735
breakpoints_backup = IKBreakpoint.backup_breakpoints_state() IKBreakpoint.disable_all_breakpoints() let_expression = "%s=%s" % (var_name, expression_value,) eval_frame = ctypes.cast(frame_id, ctypes.py_object).value global_vars = eval_frame.f_globals local_vars...
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.
3.741444
3.556941
1.051871
self.frame_calling = frame if pure: self.frame_stop = None else: self.frame_stop = frame self.frame_return = None self.frame_suspend = False self.pending_stop = True return
def setup_step_into(self, frame, pure=False)
Setup debugger for a "stepInto"
5.124629
5.149439
0.995182
self.frame_calling = None self.frame_stop = None self.frame_return = frame.f_back self.frame_suspend = False self.pending_stop = True return
def setup_step_out(self, frame)
Setup debugger for a "stepOut"
7.030491
7.053373
0.996756
self.frame_calling = None self.frame_stop = None self.frame_return = None self.frame_suspend = True self.pending_stop = True self.enable_tracing() return
def setup_suspend(self)
Setup debugger to "suspend" execution
6.614316
5.825813
1.135346
self.frame_calling = None self.frame_stop = None self.frame_return = None self.frame_suspend = False self.pending_stop = False if not IKBreakpoint.any_active_breakpoint: self.disable_tracing() return
def setup_resume(self)
Setup debugger to "resume" execution
10.58597
8.697098
1.217184
# TODO: Optimization => defines a set of modules / names where _tracer # is never registered. This will replace skip #if self.skip and self.is_skipped_module(frame.f_globals.get('__name__')): # return False # step into if self.frame_calling and self.frame_cal...
def should_stop_here(self, frame)
Called by dispatch function to check wether debugger must stop at this frame. Note that we test 'step into' first to give a chance to 'stepOver' in case user click on 'stepInto' on a 'no call' line.
7.737026
6.934664
1.115703
# Next line commented out for performance #_logger.b_debug("should_break_here(filename=%s, lineno=%s) with breaks=%s", # frame.f_code.co_filename, # frame.f_lineno, # IKBreakpoint.breakpoints_by_number) c_file...
def should_break_here(self, frame)
Check wether there is a breakpoint at this frame.
5.246376
5.060046
1.036824
thread_list = {} for thread in threading.enumerate(): thread_ident = thread.ident thread_list[thread_ident] = { "ident": thread_ident, "name": thread.name, "is_debugger": thread_ident == self.debugger_thread_ident, ...
def get_threads(self)
Returns a dict of all threads and indicates thread being debugged. key is thread ident and values thread info. Information from this list can be used to swap thread being debugged.
2.617625
1.962883
1.333561
if target_thread_ident is None: self.debugged_thread_ident = None self.debugged_thread_name = '' return { "result": self.get_threads(), "error": "" } thread_list = self.get_threads() if target_t...
def set_debugged_thread(self, target_thread_ident=None)
Allows to reset or set the thread to debug.
2.75697
2.669904
1.03261
_logger.x_debug("Dumping all threads Tracing state: (%s)" % context) _logger.x_debug(" self.tracing_enabled=%s" % self.tracing_enabled) _logger.x_debug(" self.execution_started=%s" % self.execution_started) _logger.x_debug(" self.status=%s" % self.status) _logge...
def dump_tracing_state(self, context)
A debug tool to dump all threads tracing state
2.736299
2.680828
1.020692
_logger.x_debug("entering enable_tracing()") # uncomment next line to get debugger tracing info #self.dump_tracing_state("before enable_tracing()") if not self.tracing_enabled and self.execution_started: # Restore or set trace function on all existing frames...
def enable_tracing(self)
Enable tracing if it is disabled and debugged program is running, else do nothing. Do this on all threads but the debugger thread. :return: True if tracing has been enabled, False else.
6.376767
5.771779
1.104818
_logger.x_debug("disable_tracing()") #self.dump_tracing_state("before disable_tracing()") if self.tracing_enabled and self.execution_started: threading.settrace(None) # don't trace threads to come iksettrace3._set_trace_off() self.tracing_enabled = F...
def disable_tracing(self)
Disable tracing if it is disabled and debugged program is running, else do nothing. :return: False if tracing has been disabled, True else.
7.817024
7.662073
1.020223
c_file_name = self.canonic(file_name) import linecache line = linecache.getline(c_file_name, line_number) if not line: return "Line %s:%d does not exist." % (c_file_name, line_number), None bp = IKBreakpoint(c_file_name, line_number, condition, enabled) ...
def set_breakpoint(self, file_name, line_number, condition=None, enabled=True)
Create a breakpoint, register it in the class's lists and returns a tuple of (error_message, break_number)
4.43789
3.981981
1.114493