repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | ResourceAllocation.get_jobs | 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): A list of jobs matching the given `name`.
.. note:: If ``applicationResource`` is `False` an empty list is returned.
.. versionadded:: 1.9
"""
if self.applicationResource:
return self._get_elements(self.jobs, 'jobs', Job, None, name)
else:
return [] | python | 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): A list of jobs matching the given `name`.
.. note:: If ``applicationResource`` is `False` an empty list is returned.
.. versionadded:: 1.9
"""
if self.applicationResource:
return self._get_elements(self.jobs, 'jobs', Job, None, name)
else:
return [] | [
"def",
"get_jobs",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"self",
".",
"applicationResource",
":",
"return",
"self",
".",
"_get_elements",
"(",
"self",
".",
"jobs",
",",
"'jobs'",
",",
"Job",
",",
"None",
",",
"name",
")",
"else",
":"... | 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): A list of jobs matching the given `name`.
.. note:: If ``applicationResource`` is `False` an empty list is returned.
.. versionadded:: 1.9 | [
"Retrieves",
"jobs",
"running",
"on",
"this",
"resource",
"in",
"its",
"instance",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1345-L1361 | train | 44,000 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | ExportedStream.get_operator_output_port | def get_operator_output_port(self):
"""Get the output port of this exported stream.
Returns:
OperatorOutputPort: Output port of this exported stream.
"""
return OperatorOutputPort(self.rest_client.make_request(self.operatorOutputPort), self.rest_client) | python | def get_operator_output_port(self):
"""Get the output port of this exported stream.
Returns:
OperatorOutputPort: Output port of this exported stream.
"""
return OperatorOutputPort(self.rest_client.make_request(self.operatorOutputPort), self.rest_client) | [
"def",
"get_operator_output_port",
"(",
"self",
")",
":",
"return",
"OperatorOutputPort",
"(",
"self",
".",
"rest_client",
".",
"make_request",
"(",
"self",
".",
"operatorOutputPort",
")",
",",
"self",
".",
"rest_client",
")"
] | Get the output port of this exported stream.
Returns:
OperatorOutputPort: Output port of this exported stream. | [
"Get",
"the",
"output",
"port",
"of",
"this",
"exported",
"stream",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1435-L1441 | train | 44,001 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | ExportedStream._as_published_topic | def _as_published_topic(self):
"""This stream as a PublishedTopic if it is published otherwise None
"""
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['type'] != 'rstring':
continue
if p['name'] == '__spl_exportType':
if p['values'] == ['"topic"']:
seen_export_type = True
else:
return
if p['name'] == '__spl_topic':
topic = p['values'][0]
if seen_export_type and topic is not None:
schema = None
if hasattr(oop, 'tupleAttributes'):
ta_url = oop.tupleAttributes
ta_resp = self.rest_client.make_request(ta_url)
schema = streamsx.topology.schema.StreamSchema(ta_resp['splType'])
return PublishedTopic(topic[1:-1], schema)
return | python | def _as_published_topic(self):
"""This stream as a PublishedTopic if it is published otherwise None
"""
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['type'] != 'rstring':
continue
if p['name'] == '__spl_exportType':
if p['values'] == ['"topic"']:
seen_export_type = True
else:
return
if p['name'] == '__spl_topic':
topic = p['values'][0]
if seen_export_type and topic is not None:
schema = None
if hasattr(oop, 'tupleAttributes'):
ta_url = oop.tupleAttributes
ta_resp = self.rest_client.make_request(ta_url)
schema = streamsx.topology.schema.StreamSchema(ta_resp['splType'])
return PublishedTopic(topic[1:-1], schema)
return | [
"def",
"_as_published_topic",
"(",
"self",
")",
":",
"oop",
"=",
"self",
".",
"get_operator_output_port",
"(",
")",
"if",
"not",
"hasattr",
"(",
"oop",
",",
"'export'",
")",
":",
"return",
"export",
"=",
"oop",
".",
"export",
"if",
"export",
"[",
"'type'... | This stream as a PublishedTopic if it is published otherwise None | [
"This",
"stream",
"as",
"a",
"PublishedTopic",
"if",
"it",
"is",
"published",
"otherwise",
"None"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1443-L1476 | train | 44,002 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Instance.of_service | 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::
# Two lines are code injected in a Jupyter notebook by selecting the service instance
from icpd_core import ipcd_util
cfg = icpd_util.get_service_details(name='instanceName')
instance = Instance.of_service(cfg)
SSL host verification is disabled by setting :py:const:`~streamsx.topology.context.ConfigParams.SSL_VERIFY`
to ``False`` within `config` before calling this method::
cfg[ConfigParams.SSL_VERIFY] = False
instance = Instance.of_service(cfg)
Args:
config(dict): Configuration of IBM Streams service instance.
Returns:
Instance: Instance representing for IBM Streams service instance.
.. note:: Only supported when running within the ICPD cluster,
for example in a Jupyter notebook within a ICPD project.
.. versionadded:: 1.12
"""
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=resource_url, auth=_ICPDAuthHandler(name, service['service_token']))
if streamsx.topology.context.ConfigParams.SSL_VERIFY in config:
sc.session.verify = config[streamsx.topology.context.ConfigParams.SSL_VERIFY]
return sc.get_instance(name) | python | 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::
# Two lines are code injected in a Jupyter notebook by selecting the service instance
from icpd_core import ipcd_util
cfg = icpd_util.get_service_details(name='instanceName')
instance = Instance.of_service(cfg)
SSL host verification is disabled by setting :py:const:`~streamsx.topology.context.ConfigParams.SSL_VERIFY`
to ``False`` within `config` before calling this method::
cfg[ConfigParams.SSL_VERIFY] = False
instance = Instance.of_service(cfg)
Args:
config(dict): Configuration of IBM Streams service instance.
Returns:
Instance: Instance representing for IBM Streams service instance.
.. note:: Only supported when running within the ICPD cluster,
for example in a Jupyter notebook within a ICPD project.
.. versionadded:: 1.12
"""
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=resource_url, auth=_ICPDAuthHandler(name, service['service_token']))
if streamsx.topology.context.ConfigParams.SSL_VERIFY in config:
sc.session.verify = config[streamsx.topology.context.ConfigParams.SSL_VERIFY]
return sc.get_instance(name) | [
"def",
"of_service",
"(",
"config",
")",
":",
"service",
"=",
"Instance",
".",
"_find_service_def",
"(",
"config",
")",
"if",
"not",
"service",
":",
"raise",
"ValueError",
"(",
")",
"endpoint",
"=",
"service",
"[",
"'connection_info'",
"]",
".",
"get",
"("... | 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::
# Two lines are code injected in a Jupyter notebook by selecting the service instance
from icpd_core import ipcd_util
cfg = icpd_util.get_service_details(name='instanceName')
instance = Instance.of_service(cfg)
SSL host verification is disabled by setting :py:const:`~streamsx.topology.context.ConfigParams.SSL_VERIFY`
to ``False`` within `config` before calling this method::
cfg[ConfigParams.SSL_VERIFY] = False
instance = Instance.of_service(cfg)
Args:
config(dict): Configuration of IBM Streams service instance.
Returns:
Instance: Instance representing for IBM Streams service instance.
.. note:: Only supported when running within the ICPD cluster,
for example in a Jupyter notebook within a ICPD project.
.. versionadded:: 1.12 | [
"Connect",
"to",
"an",
"IBM",
"Streams",
"service",
"instance",
"running",
"in",
"IBM",
"Cloud",
"Private",
"for",
"Data",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1541-L1579 | train | 44,003 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Instance.get_job | 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`
"""
return self._get_element_by_id(self.jobs, 'jobs', Job, str(id)) | python | 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`
"""
return self._get_element_by_id(self.jobs, 'jobs', Job, str(id)) | [
"def",
"get_job",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"_get_element_by_id",
"(",
"self",
".",
"jobs",
",",
"'jobs'",
",",
"Job",
",",
"str",
"(",
"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` | [
"Retrieves",
"a",
"job",
"matching",
"the",
"given",
"id"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1717-L1729 | train | 44,004 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Instance.get_published_topics | 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 schema. It is recommended that a
topic is only associated with a single schema.
Streams may be published and subscribed by applications regardless of the
implementation language. For example a Python application can publish
a stream of JSON tuples that are subscribed to by SPL and Java applications.
Returns:
list(PublishedTopic): List of currently published topics.
"""
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.
seen_topics = {}
for es in self.get_exported_streams():
pt = es._as_published_topic()
if pt is not None:
if pt.topic in seen_topics:
if pt.schema is None:
continue
if pt.schema in seen_topics[pt.topic]:
continue
seen_topics[pt.topic].append(pt.schema)
else:
seen_topics[pt.topic] = [pt.schema]
published_topics.append(pt)
return published_topics | python | 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 schema. It is recommended that a
topic is only associated with a single schema.
Streams may be published and subscribed by applications regardless of the
implementation language. For example a Python application can publish
a stream of JSON tuples that are subscribed to by SPL and Java applications.
Returns:
list(PublishedTopic): List of currently published topics.
"""
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.
seen_topics = {}
for es in self.get_exported_streams():
pt = es._as_published_topic()
if pt is not None:
if pt.topic in seen_topics:
if pt.schema is None:
continue
if pt.schema in seen_topics[pt.topic]:
continue
seen_topics[pt.topic].append(pt.schema)
else:
seen_topics[pt.topic] = [pt.schema]
published_topics.append(pt)
return published_topics | [
"def",
"get_published_topics",
"(",
"self",
")",
":",
"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 ... | 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 schema. It is recommended that a
topic is only associated with a single schema.
Streams may be published and subscribed by applications regardless of the
implementation language. For example a Python application can publish
a stream of JSON tuples that are subscribed to by SPL and Java applications.
Returns:
list(PublishedTopic): List of currently published topics. | [
"Get",
"a",
"list",
"of",
"published",
"topics",
"for",
"this",
"instance",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1765-L1802 | train | 44,005 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Instance.get_application_configurations | 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 returned.
Returns:
list(ApplicationConfiguration): A list of application configurations matching the given `name`.
.. versionadded 1.12
"""
if hasattr(self, 'applicationConfigurations'):
return self._get_elements(self.applicationConfigurations, 'applicationConfigurations', ApplicationConfiguration, None, name) | python | 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 returned.
Returns:
list(ApplicationConfiguration): A list of application configurations matching the given `name`.
.. versionadded 1.12
"""
if hasattr(self, 'applicationConfigurations'):
return self._get_elements(self.applicationConfigurations, 'applicationConfigurations', ApplicationConfiguration, None, name) | [
"def",
"get_application_configurations",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'applicationConfigurations'",
")",
":",
"return",
"self",
".",
"_get_elements",
"(",
"self",
".",
"applicationConfigurations",
",",
"'ap... | 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 returned.
Returns:
list(ApplicationConfiguration): A list of application configurations matching the given `name`.
.. versionadded 1.12 | [
"Retrieves",
"application",
"configurations",
"for",
"this",
"instance",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1844-L1857 | train | 44,006 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Instance.create_application_configuration | 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
"""
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'},
json=cv)
_handle_http_errors(res)
return ApplicationConfiguration(res.json(), self.rest_client) | python | 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
"""
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'},
json=cv)
_handle_http_errors(res)
return ApplicationConfiguration(res.json(), self.rest_client) | [
"def",
"create_application_configuration",
"(",
"self",
",",
"name",
",",
"properties",
",",
"description",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'applicationConfigurations'",
")",
":",
"raise",
"NotImplementedError",
"(",
")",
"cv",
... | 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 | [
"Create",
"an",
"application",
"configuration",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1859-L1875 | train | 44,007 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | _StreamingAnalyticsServiceV2Delegator._get_jobs_url | def _get_jobs_url(self):
"""Get & save jobs URL from the status call."""
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 | python | def _get_jobs_url(self):
"""Get & save jobs URL from the status call."""
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",
")",
":",
"if",
"self",
".",
"_jobs_url",
"is",
"None",
":",
"self",
".",
"get_instance_status",
"(",
")",
"if",
"self",
".",
"_jobs_url",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot obtain jobs URL\"",
")",
... | Get & save jobs URL from the status call. | [
"Get",
"&",
"save",
"jobs",
"URL",
"from",
"the",
"status",
"call",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2140-L2146 | train | 44,008 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | _StreamingAnalyticsServiceV1Delegator.start_instance | def start_instance(self):
"""Start the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance start operation.
"""
start_url = self._get_url('start_path')
res = self.rest_client.session.put(start_url, json={})
_handle_http_errors(res)
return res.json() | python | def start_instance(self):
"""Start the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance start operation.
"""
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_url",
"=",
"self",
".",
"_get_url",
"(",
"'start_path'",
")",
"res",
"=",
"self",
".",
"rest_client",
".",
"session",
".",
"put",
"(",
"start_url",
",",
"json",
"=",
"{",
"}",
")",
"_handle_http_erro... | Start the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance start operation. | [
"Start",
"the",
"instance",
"for",
"this",
"Streaming",
"Analytics",
"service",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2286-L2295 | train | 44,009 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | _StreamingAnalyticsServiceV1Delegator.stop_instance | def stop_instance(self):
"""Stop the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance stop operation.
"""
stop_url = self._get_url('stop_path')
res = self.rest_client.session.put(stop_url, json={})
_handle_http_errors(res)
return res.json() | python | def stop_instance(self):
"""Stop the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance stop operation.
"""
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_url",
"=",
"self",
".",
"_get_url",
"(",
"'stop_path'",
")",
"res",
"=",
"self",
".",
"rest_client",
".",
"session",
".",
"put",
"(",
"stop_url",
",",
"json",
"=",
"{",
"}",
")",
"_handle_http_errors",... | Stop the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance stop operation. | [
"Stop",
"the",
"instance",
"for",
"this",
"Streaming",
"Analytics",
"service",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2297-L2306 | train | 44,010 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | _StreamingAnalyticsServiceV1Delegator.get_instance_status | def get_instance_status(self):
"""Get the status the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance status operation.
"""
status_url = self._get_url('status_path')
res = self.rest_client.session.get(status_url)
_handle_http_errors(res)
return res.json() | python | def get_instance_status(self):
"""Get the status the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance status operation.
"""
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",
")",
":",
"status_url",
"=",
"self",
".",
"_get_url",
"(",
"'status_path'",
")",
"res",
"=",
"self",
".",
"rest_client",
".",
"session",
".",
"get",
"(",
"status_url",
")",
"_handle_http_errors",
"(",
"res",
")",
... | Get the status the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance status operation. | [
"Get",
"the",
"status",
"the",
"instance",
"for",
"this",
"Streaming",
"Analytics",
"service",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2308-L2317 | train | 44,011 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | _StreamsV4Delegator._cancel_job | def _cancel_job(self, job, force):
"""Cancel job using streamtool."""
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 | python | def _cancel_job(self, job, force):
"""Cancel job using streamtool."""
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",
")",
":",
"import",
"streamsx",
".",
"st",
"as",
"st",
"if",
"st",
".",
"_has_local_install",
":",
"return",
"st",
".",
"_cancel_job",
"(",
"job",
".",
"id",
",",
"force",
",",
"domain_id",
... | Cancel job using streamtool. | [
"Cancel",
"job",
"using",
"streamtool",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2419-L2425 | train | 44,012 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | ApplicationConfiguration.update | 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 properties are unchanged.
description (str): Description for the configuration. If ``None`` the description is unchanged.
Returns:
ApplicationConfiguration: self
"""
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_errors(res)
self.json_rep = res.json()
return self | python | 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 properties are unchanged.
description (str): Description for the configuration. If ``None`` the description is unchanged.
Returns:
ApplicationConfiguration: self
"""
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_errors(res)
self.json_rep = res.json()
return self | [
"def",
"update",
"(",
"self",
",",
"properties",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"cv",
"=",
"ApplicationConfiguration",
".",
"_props",
"(",
"properties",
"=",
"properties",
",",
"description",
"=",
"description",
")",
"res",
"=",
"s... | 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 properties are unchanged.
description (str): Description for the configuration. If ``None`` the description is unchanged.
Returns:
ApplicationConfiguration: self | [
"Update",
"this",
"application",
"configuration",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2465-L2488 | train | 44,013 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | ApplicationConfiguration.delete | def delete(self):
"""Delete this application configuration.
"""
res = self.rest_client.session.delete(self.rest_self)
_handle_http_errors(res) | python | def delete(self):
"""Delete this application configuration.
"""
res = self.rest_client.session.delete(self.rest_self)
_handle_http_errors(res) | [
"def",
"delete",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"rest_client",
".",
"session",
".",
"delete",
"(",
"self",
".",
"rest_self",
")",
"_handle_http_errors",
"(",
"res",
")"
] | Delete this application configuration. | [
"Delete",
"this",
"application",
"configuration",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2490-L2494 | train | 44,014 |
IBMStreams/pypi.streamsx | streamsx/topology/schema.py | _normalize | def _normalize(schema, allow_none=True):
"""
Normalize a schema.
"""
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.Python,
_spl_str: CommonSchema.String,
json: CommonSchema.Json,
}
if schema in py_types:
return py_types[schema]
# With Python 3 allow a named tuple with type hints
# to be used as a schema definition
if sys.version_info.major == 3:
import typing
if isinstance(schema, type) and issubclass(schema, tuple):
if hasattr(schema, '_fields') and hasattr(schema, '_field_types'):
return _from_named_tuple(schema)
raise ValueError("Unknown stream schema type:" + str(schema)) | python | def _normalize(schema, allow_none=True):
"""
Normalize a schema.
"""
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.Python,
_spl_str: CommonSchema.String,
json: CommonSchema.Json,
}
if schema in py_types:
return py_types[schema]
# With Python 3 allow a named tuple with type hints
# to be used as a schema definition
if sys.version_info.major == 3:
import typing
if isinstance(schema, type) and issubclass(schema, tuple):
if hasattr(schema, '_fields') and hasattr(schema, '_field_types'):
return _from_named_tuple(schema)
raise ValueError("Unknown stream schema type:" + str(schema)) | [
"def",
"_normalize",
"(",
"schema",
",",
"allow_none",
"=",
"True",
")",
":",
"if",
"allow_none",
"and",
"schema",
"is",
"None",
":",
"return",
"schema",
"if",
"isinstance",
"(",
"schema",
",",
"CommonSchema",
")",
":",
"return",
"schema",
"if",
"isinstanc... | Normalize a schema. | [
"Normalize",
"a",
"schema",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/schema.py#L103-L134 | train | 44,015 |
IBMStreams/pypi.streamsx | streamsx/topology/schema.py | is_common | 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``.
"""
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 | python | 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``.
"""
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",
")",
":",
"if",
"isinstance",
"(",
"schema",
",",
"StreamSchema",
")",
":",
"return",
"schema",
".",
"schema",
"(",
")",
"in",
"_SCHEMA_COMMON",
"if",
"isinstance",
"(",
"schema",
",",
"CommonSchema",
")",
":",
"return",
... | Is `schema` an common schema.
Args:
schema: Scheme to test.
Returns:
bool: ``True`` if schema is a common schema, otherwise ``False``. | [
"Is",
"schema",
"an",
"common",
"schema",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/schema.py#L136-L153 | train | 44,016 |
IBMStreams/pypi.streamsx | streamsx/topology/schema.py | StreamSchema._set | def _set(self, schema):
"""Set a schema from another schema"""
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._style | python | def _set(self, schema):
"""Set a schema from another schema"""
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._style | [
"def",
"_set",
"(",
"self",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"schema",
",",
"CommonSchema",
")",
":",
"self",
".",
"_spl_type",
"=",
"False",
"self",
".",
"_schema",
"=",
"schema",
".",
"schema",
"(",
")",
"self",
".",
"_style",
"=",... | Set a schema from another schema | [
"Set",
"a",
"schema",
"from",
"another",
"schema"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/schema.py#L464-L473 | train | 44,017 |
IBMStreams/pypi.streamsx | streamsx/topology/schema.py | StreamSchema.as_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 tuple**
When `named` evaluates to ``False`` then each stream tuple will
be passed as a ``tuple``. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t[0]`` and the second as ``t[1]`` where ``t`` represents
the passed value..
**Passing as named tuple**
When `named` is ``True`` or a ``str`` then each stream tuple will
be passed as a named tuple. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t.id`` (or ``t[0]``) and the second as ``t.value`` (``t[1]``)
where ``t`` represents the passed value.
.. warning:: If an schema's attribute name is not a valid Python identifier or
starts with an underscore then it will be renamed as positional name ``_n``.
For example, with the schema ``tuple<int32 a, int32 def, int32 id>`` the
field names are ``a``, ``_1``, ``_2``.
The value of `named` is used as the name of the named tuple
class with ``StreamTuple`` used when `named` is ``True``.
It is not guaranteed that the class of the namedtuple is the
same for all callables processing tuples with the same
structured schema, only that the tuple is a named tuple
with the correct field names.
Args:
named: Pass stream tuples as a named tuple.
If not set then stream tuples are passed as
instances of ``tuple``.
Returns:
StreamSchema: Schema passing stream tuples as ``tuple`` if allowed.
.. versionadded:: 1.8
.. versionadded:: 1.9 Addition of `named` parameter.
"""
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) | python | 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 tuple**
When `named` evaluates to ``False`` then each stream tuple will
be passed as a ``tuple``. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t[0]`` and the second as ``t[1]`` where ``t`` represents
the passed value..
**Passing as named tuple**
When `named` is ``True`` or a ``str`` then each stream tuple will
be passed as a named tuple. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t.id`` (or ``t[0]``) and the second as ``t.value`` (``t[1]``)
where ``t`` represents the passed value.
.. warning:: If an schema's attribute name is not a valid Python identifier or
starts with an underscore then it will be renamed as positional name ``_n``.
For example, with the schema ``tuple<int32 a, int32 def, int32 id>`` the
field names are ``a``, ``_1``, ``_2``.
The value of `named` is used as the name of the named tuple
class with ``StreamTuple`` used when `named` is ``True``.
It is not guaranteed that the class of the namedtuple is the
same for all callables processing tuples with the same
structured schema, only that the tuple is a named tuple
with the correct field names.
Args:
named: Pass stream tuples as a named tuple.
If not set then stream tuples are passed as
instances of ``tuple``.
Returns:
StreamSchema: Schema passing stream tuples as ``tuple`` if allowed.
.. versionadded:: 1.8
.. versionadded:: 1.9 Addition of `named` parameter.
"""
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",
")",
":",
"if",
"not",
"named",
":",
"return",
"self",
".",
"_copy",
"(",
"tuple",
")",
"if",
"named",
"==",
"True",
"or",
"isinstance",
"(",
"named",
",",
"basestring",
")",
":",
"return",
... | 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 tuple**
When `named` evaluates to ``False`` then each stream tuple will
be passed as a ``tuple``. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t[0]`` and the second as ``t[1]`` where ``t`` represents
the passed value..
**Passing as named tuple**
When `named` is ``True`` or a ``str`` then each stream tuple will
be passed as a named tuple. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t.id`` (or ``t[0]``) and the second as ``t.value`` (``t[1]``)
where ``t`` represents the passed value.
.. warning:: If an schema's attribute name is not a valid Python identifier or
starts with an underscore then it will be renamed as positional name ``_n``.
For example, with the schema ``tuple<int32 a, int32 def, int32 id>`` the
field names are ``a``, ``_1``, ``_2``.
The value of `named` is used as the name of the named tuple
class with ``StreamTuple`` used when `named` is ``True``.
It is not guaranteed that the class of the namedtuple is the
same for all callables processing tuples with the same
structured schema, only that the tuple is a named tuple
with the correct field names.
Args:
named: Pass stream tuples as a named tuple.
If not set then stream tuples are passed as
instances of ``tuple``.
Returns:
StreamSchema: Schema passing stream tuples as ``tuple`` if allowed.
.. versionadded:: 1.8
.. versionadded:: 1.9 Addition of `named` parameter. | [
"Create",
"a",
"structured",
"schema",
"that",
"will",
"pass",
"stream",
"tuples",
"into",
"callables",
"as",
"tuple",
"instances",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/schema.py#L537-L594 | train | 44,018 |
IBMStreams/pypi.streamsx | streamsx/topology/schema.py | StreamSchema.extend | 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.
Returns:
StreamSchema: New schema that is an extension of this schema.
"""
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) | python | 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.
Returns:
StreamSchema: New schema that is an extension of this schema.
"""
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",
")",
":",
"if",
"self",
".",
"_spl_type",
":",
"raise",
"TypeError",
"(",
"\"Not supported for declared SPL types\"",
")",
"base",
"=",
"self",
".",
"schema",
"(",
")",
"extends",
"=",
"schema",
".",
"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.
Returns:
StreamSchema: New schema that is an extension of this schema. | [
"Extend",
"a",
"structured",
"schema",
"by",
"another",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/schema.py#L627-L645 | train | 44,019 |
IBMStreams/pypi.streamsx | streamsx/topology/schema.py | StreamSchema._fnop_style | def _fnop_style(schema, op, name):
"""Set an operator's parameter representing the style of this schema."""
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'
elif _is_namedtuple(schema.style) and hasattr(schema.style, '_splpy_namedtuple'):
ntp = 'namedtuple:' + schema.style._splpy_namedtuple
else:
return
op.params[name] = ntp | python | def _fnop_style(schema, op, name):
"""Set an operator's parameter representing the style of this schema."""
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'
elif _is_namedtuple(schema.style) and hasattr(schema.style, '_splpy_namedtuple'):
ntp = 'namedtuple:' + schema.style._splpy_namedtuple
else:
return
op.params[name] = ntp | [
"def",
"_fnop_style",
"(",
"schema",
",",
"op",
",",
"name",
")",
":",
"if",
"is_common",
"(",
"schema",
")",
":",
"if",
"name",
"in",
"op",
".",
"params",
":",
"del",
"op",
".",
"params",
"[",
"name",
"]",
"return",
"if",
"_is_pending",
"(",
"sche... | Set an operator's parameter representing the style of this schema. | [
"Set",
"an",
"operator",
"s",
"parameter",
"representing",
"the",
"style",
"of",
"this",
"schema",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/schema.py#L659-L675 | train | 44,020 |
raphaelm/django-hierarkey | hierarkey/forms.py | HierarkeyForm.save | def save(self) -> None:
"""
Saves all changed values to the database.
"""
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:
default_storage.delete(fname.name)
except OSError: # pragma: no cover
logger.error('Deleting file %s failed.' % fname.name)
# Create new file
newname = default_storage.save(self.get_new_filename(value.name), value)
value._name = newname
self._s.set(name, value)
elif isinstance(value, File):
# file is unchanged
continue
elif isinstance(field, forms.FileField):
# file is deleted
fname = self._s.get(name, as_type=File)
if fname:
try:
default_storage.delete(fname.name)
except OSError: # pragma: no cover
logger.error('Deleting file %s failed.' % fname.name)
del self._s[name]
elif value is None:
del self._s[name]
elif self._s.get(name, as_type=type(value)) != value:
self._s.set(name, value) | python | def save(self) -> None:
"""
Saves all changed values to the database.
"""
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:
default_storage.delete(fname.name)
except OSError: # pragma: no cover
logger.error('Deleting file %s failed.' % fname.name)
# Create new file
newname = default_storage.save(self.get_new_filename(value.name), value)
value._name = newname
self._s.set(name, value)
elif isinstance(value, File):
# file is unchanged
continue
elif isinstance(field, forms.FileField):
# file is deleted
fname = self._s.get(name, as_type=File)
if fname:
try:
default_storage.delete(fname.name)
except OSError: # pragma: no cover
logger.error('Deleting file %s failed.' % fname.name)
del self._s[name]
elif value is None:
del self._s[name]
elif self._s.get(name, as_type=type(value)) != value:
self._s.set(name, value) | [
"def",
"save",
"(",
"self",
")",
"->",
"None",
":",
"for",
"name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"value",
"=",
"self",
".",
"cleaned_data",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"value",
",",
"Uploaded... | Saves all changed values to the database. | [
"Saves",
"all",
"changed",
"values",
"to",
"the",
"database",
"."
] | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/forms.py#L30-L64 | train | 44,021 |
IBMStreams/pypi.streamsx | streamsx/scripts/service.py | _stop | def _stop(sas, cmd_args):
"""Stop the service if no jobs are running unless force is set"""
if not cmd_args.force:
status = sas.get_instance_status()
jobs = int(status['job_count'])
if jobs:
return status
return sas.stop_instance() | python | def _stop(sas, cmd_args):
"""Stop the service if no jobs are running unless force is set"""
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",
")",
":",
"if",
"not",
"cmd_args",
".",
"force",
":",
"status",
"=",
"sas",
".",
"get_instance_status",
"(",
")",
"jobs",
"=",
"int",
"(",
"status",
"[",
"'job_count'",
"]",
")",
"if",
"jobs",
":",
"return... | Stop the service if no jobs are running unless force is set | [
"Stop",
"the",
"service",
"if",
"no",
"jobs",
"are",
"running",
"unless",
"force",
"is",
"set"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/service.py#L14-L21 | train | 44,022 |
IBMStreams/pypi.streamsx | streamsx/scripts/service.py | main | def main(args=None):
""" Performs an action against a Streaming Analytics service.
"""
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 | python | def main(args=None):
""" Performs an action against a Streaming Analytics service.
"""
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",
")",
":",
"streamsx",
".",
"_streams",
".",
"_version",
".",
"_mismatch_check",
"(",
"'streamsx.topology.context'",
")",
"try",
":",
"sr",
"=",
"run_cmd",
"(",
"args",
")",
"sr",
"[",
"'return_code'",
"]",
"=",
"0... | Performs an action against a Streaming Analytics service. | [
"Performs",
"an",
"action",
"against",
"a",
"Streaming",
"Analytics",
"service",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/service.py#L39-L48 | train | 44,023 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Topology.source | 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 an iterable.
Each tuple that is not None from the iterator is present on the returned stream.
Each tuple is a Python object and must be picklable to allow execution of the application
to be distributed across available resources in the Streams instance.
If the iterator's ``__iter__`` or ``__next__`` block then shutdown,
checkpointing or consistent region processing may be delayed.
Having ``__next__`` return ``None`` (no available tuples) or tuples
to submit will allow such processing to proceed.
A shutdown ``threading.Event`` is available through
:py:func:`streamsx.ec.shutdown` which becomes set when a shutdown
of the processing element has been requested. This event my be waited
on to perform a sleep that will terminate upon shutdown.
Args:
func(callable): An iterable or a zero-argument callable that returns an iterable of tuples.
name(str): Name of the stream, defaults to a generated name.
Exceptions raised by ``func`` or its iterator will cause
its processing element will terminate.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method.
Suppressing an exception raised by ``func.__iter__`` causes the
source to be empty, no tuples are submitted to the stream.
Suppressing an exception raised by ``__next__`` on the iterator
results in no tuples being submitted for that call to ``__next__``.
Processing continues with calls to ``__next__`` to fetch subsequent tuples.
Returns:
Stream: A stream whose tuples are the result of the iterable obtained from `func`.
"""
_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(_source_info(), "source")
_name = self.graph._requested_name(_name, action='source', func=func)
# source is always stateful
op = self.graph.addOperator(self.opnamespace+"::Source", func, name=_name, sl=sl)
op._layout(kind='Source', name=_name, orig_name=name)
oport = op.addOutputPort(name=_name)
return Stream(self, oport)._make_placeable() | python | 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 an iterable.
Each tuple that is not None from the iterator is present on the returned stream.
Each tuple is a Python object and must be picklable to allow execution of the application
to be distributed across available resources in the Streams instance.
If the iterator's ``__iter__`` or ``__next__`` block then shutdown,
checkpointing or consistent region processing may be delayed.
Having ``__next__`` return ``None`` (no available tuples) or tuples
to submit will allow such processing to proceed.
A shutdown ``threading.Event`` is available through
:py:func:`streamsx.ec.shutdown` which becomes set when a shutdown
of the processing element has been requested. This event my be waited
on to perform a sleep that will terminate upon shutdown.
Args:
func(callable): An iterable or a zero-argument callable that returns an iterable of tuples.
name(str): Name of the stream, defaults to a generated name.
Exceptions raised by ``func`` or its iterator will cause
its processing element will terminate.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method.
Suppressing an exception raised by ``func.__iter__`` causes the
source to be empty, no tuples are submitted to the stream.
Suppressing an exception raised by ``__next__`` on the iterator
results in no tuples being submitted for that call to ``__next__``.
Processing continues with calls to ``__next__`` to fetch subsequent tuples.
Returns:
Stream: A stream whose tuples are the result of the iterable obtained from `func`.
"""
_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(_source_info(), "source")
_name = self.graph._requested_name(_name, action='source', func=func)
# source is always stateful
op = self.graph.addOperator(self.opnamespace+"::Source", func, name=_name, sl=sl)
op._layout(kind='Source', name=_name, orig_name=name)
oport = op.addOutputPort(name=_name)
return Stream(self, oport)._make_placeable() | [
"def",
"source",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
")",
":",
"_name",
"=",
"name",
"if",
"inspect",
".",
"isroutine",
"(",
"func",
")",
":",
"pass",
"elif",
"callable",
"(",
"func",
")",
":",
"pass",
"else",
":",
"if",
"_name",
... | 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 an iterable.
Each tuple that is not None from the iterator is present on the returned stream.
Each tuple is a Python object and must be picklable to allow execution of the application
to be distributed across available resources in the Streams instance.
If the iterator's ``__iter__`` or ``__next__`` block then shutdown,
checkpointing or consistent region processing may be delayed.
Having ``__next__`` return ``None`` (no available tuples) or tuples
to submit will allow such processing to proceed.
A shutdown ``threading.Event`` is available through
:py:func:`streamsx.ec.shutdown` which becomes set when a shutdown
of the processing element has been requested. This event my be waited
on to perform a sleep that will terminate upon shutdown.
Args:
func(callable): An iterable or a zero-argument callable that returns an iterable of tuples.
name(str): Name of the stream, defaults to a generated name.
Exceptions raised by ``func`` or its iterator will cause
its processing element will terminate.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method.
Suppressing an exception raised by ``func.__iter__`` causes the
source to be empty, no tuples are submitted to the stream.
Suppressing an exception raised by ``__next__`` on the iterator
results in no tuples being submitted for that call to ``__next__``.
Processing continues with calls to ``__next__`` to fetch subsequent tuples.
Returns:
Stream: A stream whose tuples are the result of the iterable obtained from `func`. | [
"Declare",
"a",
"source",
"stream",
"that",
"introduces",
"tuples",
"into",
"the",
"application",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L434-L495 | train | 44,024 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Topology.subscribe | 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.topology.schema.CommonSchema.Python` objects
which connects to streams published to topic by Python Streams applications.
Structured schemas are subscribed to using an instance of
:py:class:`StreamSchema`. A Streams application publishing
structured schema streams may have been implemented in any
programming language supported by Streams.
JSON streams are subscribed to using schema :py:const:`~streamsx.topology.schema.CommonSchema.Json`.
Each tuple on the returned stream will be a Python dictionary
object created by ``json.loads(tuple)``.
A Streams application publishing JSON streams may have been implemented in any programming language
supported by Streams.
String streams are subscribed to using schema :py:const:`~streamsx.topology.schema.CommonSchema.String`.
Each tuple on the returned stream will be a Python string object.
A Streams application publishing string streams may have been implemented in any programming language
supported by Streams.
Subscribers can ensure they do not slow down matching publishers
by using a buffered connection with a buffer full policy
that drops tuples.
Args:
topic(str): Topic to subscribe to.
schema(~streamsx.topology.schema.StreamSchema): schema to subscribe to.
name(str): Name of the subscribed stream, defaults to a generated name.
connect(SubscribeConnection): How subscriber will be connected to matching publishers. Defaults to :py:const:`~SubscribeConnection.Direct` connection.
buffer_capacity(int): Buffer capacity in tuples when `connect` is set to :py:const:`~SubscribeConnection.Buffered`. Defaults to 1000 when `connect` is `Buffered`. Ignored when `connect` is `None` or `Direct`.
buffer_full_policy(~streamsx.types.CongestionPolicy): Policy when a pulished tuple arrives and the subscriber's buffer is full. Defaults to `Wait` when `connect` is `Buffered`. Ignored when `connect` is `None` or `Direct`.
Returns:
Stream: A stream whose tuples have been published to the topic by other Streams applications.
.. versionchanged:: 1.9 `connect`, `buffer_capacity` and `buffer_full_policy` parameters added.
.. seealso:`SubscribeConnection`
"""
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, name=_name, stateful=False)
oport = op.addOutputPort(schema=schema, name=_name)
params = {'topic': topic, 'streamType': schema}
if connect is not None and connect != SubscribeConnection.Direct:
params['connect'] = connect
if buffer_capacity:
params['bufferCapacity'] = int(buffer_capacity)
if buffer_full_policy:
params['bufferFullPolicy'] = buffer_full_policy
op.setParameters(params)
op._layout_group('Subscribe', name if name else _name)
return Stream(self, oport)._make_placeable() | python | 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.topology.schema.CommonSchema.Python` objects
which connects to streams published to topic by Python Streams applications.
Structured schemas are subscribed to using an instance of
:py:class:`StreamSchema`. A Streams application publishing
structured schema streams may have been implemented in any
programming language supported by Streams.
JSON streams are subscribed to using schema :py:const:`~streamsx.topology.schema.CommonSchema.Json`.
Each tuple on the returned stream will be a Python dictionary
object created by ``json.loads(tuple)``.
A Streams application publishing JSON streams may have been implemented in any programming language
supported by Streams.
String streams are subscribed to using schema :py:const:`~streamsx.topology.schema.CommonSchema.String`.
Each tuple on the returned stream will be a Python string object.
A Streams application publishing string streams may have been implemented in any programming language
supported by Streams.
Subscribers can ensure they do not slow down matching publishers
by using a buffered connection with a buffer full policy
that drops tuples.
Args:
topic(str): Topic to subscribe to.
schema(~streamsx.topology.schema.StreamSchema): schema to subscribe to.
name(str): Name of the subscribed stream, defaults to a generated name.
connect(SubscribeConnection): How subscriber will be connected to matching publishers. Defaults to :py:const:`~SubscribeConnection.Direct` connection.
buffer_capacity(int): Buffer capacity in tuples when `connect` is set to :py:const:`~SubscribeConnection.Buffered`. Defaults to 1000 when `connect` is `Buffered`. Ignored when `connect` is `None` or `Direct`.
buffer_full_policy(~streamsx.types.CongestionPolicy): Policy when a pulished tuple arrives and the subscriber's buffer is full. Defaults to `Wait` when `connect` is `Buffered`. Ignored when `connect` is `None` or `Direct`.
Returns:
Stream: A stream whose tuples have been published to the topic by other Streams applications.
.. versionchanged:: 1.9 `connect`, `buffer_capacity` and `buffer_full_policy` parameters added.
.. seealso:`SubscribeConnection`
"""
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, name=_name, stateful=False)
oport = op.addOutputPort(schema=schema, name=_name)
params = {'topic': topic, 'streamType': schema}
if connect is not None and connect != SubscribeConnection.Direct:
params['connect'] = connect
if buffer_capacity:
params['bufferCapacity'] = int(buffer_capacity)
if buffer_full_policy:
params['bufferFullPolicy'] = buffer_full_policy
op.setParameters(params)
op._layout_group('Subscribe', name if name else _name)
return Stream(self, oport)._make_placeable() | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"schema",
"=",
"streamsx",
".",
"topology",
".",
"schema",
".",
"CommonSchema",
".",
"Python",
",",
"name",
"=",
"None",
",",
"connect",
"=",
"None",
",",
"buffer_capacity",
"=",
"None",
",",
"buffer_fu... | 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.topology.schema.CommonSchema.Python` objects
which connects to streams published to topic by Python Streams applications.
Structured schemas are subscribed to using an instance of
:py:class:`StreamSchema`. A Streams application publishing
structured schema streams may have been implemented in any
programming language supported by Streams.
JSON streams are subscribed to using schema :py:const:`~streamsx.topology.schema.CommonSchema.Json`.
Each tuple on the returned stream will be a Python dictionary
object created by ``json.loads(tuple)``.
A Streams application publishing JSON streams may have been implemented in any programming language
supported by Streams.
String streams are subscribed to using schema :py:const:`~streamsx.topology.schema.CommonSchema.String`.
Each tuple on the returned stream will be a Python string object.
A Streams application publishing string streams may have been implemented in any programming language
supported by Streams.
Subscribers can ensure they do not slow down matching publishers
by using a buffered connection with a buffer full policy
that drops tuples.
Args:
topic(str): Topic to subscribe to.
schema(~streamsx.topology.schema.StreamSchema): schema to subscribe to.
name(str): Name of the subscribed stream, defaults to a generated name.
connect(SubscribeConnection): How subscriber will be connected to matching publishers. Defaults to :py:const:`~SubscribeConnection.Direct` connection.
buffer_capacity(int): Buffer capacity in tuples when `connect` is set to :py:const:`~SubscribeConnection.Buffered`. Defaults to 1000 when `connect` is `Buffered`. Ignored when `connect` is `None` or `Direct`.
buffer_full_policy(~streamsx.types.CongestionPolicy): Policy when a pulished tuple arrives and the subscriber's buffer is full. Defaults to `Wait` when `connect` is `Buffered`. Ignored when `connect` is `None` or `Direct`.
Returns:
Stream: A stream whose tuples have been published to the topic by other Streams applications.
.. versionchanged:: 1.9 `connect`, `buffer_capacity` and `buffer_full_policy` parameters added.
.. seealso:`SubscribeConnection` | [
"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... | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L497-L558 | train | 44,025 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Topology.add_file_dependency | 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
is relative to the application directory. Two values for
location are supported `etc` and `opt`.
The runtime path relative to application directory is returned.
The copy is made during the submit call thus the contents of
the file or directory must remain availble until submit returns.
For example calling
``add_file_dependency('/tmp/conf.properties', 'etc')``
will result in contents of the local file `conf.properties`
being available at runtime at the path `application directory`/etc/conf.properties. This call returns ``etc/conf.properties``.
Python callables can determine the application directory at
runtime with :py:func:`~streamsx.ec.get_application_directory`.
For example the path above at runtime is
``os.path.join(streamsx.ec.get_application_directory(), 'etc', 'conf.properties')``
Args:
path(str): Path of the file on the local system.
location(str): Location of the file in the bundle relative to the application directory.
Returns:
str: Path relative to application directory that can be joined at runtime with ``get_application_directory``.
.. versionadded:: 1.7
"""
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]
else:
self._files[location].append(path)
return location + '/' + os.path.basename(path) | python | 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
is relative to the application directory. Two values for
location are supported `etc` and `opt`.
The runtime path relative to application directory is returned.
The copy is made during the submit call thus the contents of
the file or directory must remain availble until submit returns.
For example calling
``add_file_dependency('/tmp/conf.properties', 'etc')``
will result in contents of the local file `conf.properties`
being available at runtime at the path `application directory`/etc/conf.properties. This call returns ``etc/conf.properties``.
Python callables can determine the application directory at
runtime with :py:func:`~streamsx.ec.get_application_directory`.
For example the path above at runtime is
``os.path.join(streamsx.ec.get_application_directory(), 'etc', 'conf.properties')``
Args:
path(str): Path of the file on the local system.
location(str): Location of the file in the bundle relative to the application directory.
Returns:
str: Path relative to application directory that can be joined at runtime with ``get_application_directory``.
.. versionadded:: 1.7
"""
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]
else:
self._files[location].append(path)
return location + '/' + os.path.basename(path) | [
"def",
"add_file_dependency",
"(",
"self",
",",
"path",
",",
"location",
")",
":",
"if",
"location",
"not",
"in",
"{",
"'etc'",
",",
"'opt'",
"}",
":",
"raise",
"ValueError",
"(",
"location",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"... | 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
is relative to the application directory. Two values for
location are supported `etc` and `opt`.
The runtime path relative to application directory is returned.
The copy is made during the submit call thus the contents of
the file or directory must remain availble until submit returns.
For example calling
``add_file_dependency('/tmp/conf.properties', 'etc')``
will result in contents of the local file `conf.properties`
being available at runtime at the path `application directory`/etc/conf.properties. This call returns ``etc/conf.properties``.
Python callables can determine the application directory at
runtime with :py:func:`~streamsx.ec.get_application_directory`.
For example the path above at runtime is
``os.path.join(streamsx.ec.get_application_directory(), 'etc', 'conf.properties')``
Args:
path(str): Path of the file on the local system.
location(str): Location of the file in the bundle relative to the application directory.
Returns:
str: Path relative to application directory that can be joined at runtime with ``get_application_directory``.
.. versionadded:: 1.7 | [
"Add",
"a",
"file",
"or",
"directory",
"dependency",
"into",
"an",
"Streams",
"application",
"bundle",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L560-L607 | train | 44,026 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Topology.add_pip_package | 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 be available from `pypi.org`.
If the package is already installed on the build system
then it is not added into the `sab` file.
The assumption is that the runtime hosts for a Streams
instance have the same Python packages installed as the
build machines. This is always true for IBM Cloud
Private for Data and the Streaming Analytics service on IBM Cloud.
The project name extracted from the requirement
specifier is added to :py:attr:`~exclude_packages`
to avoid the package being added by the dependency
resolver. Thus the package should be added before
it is used in any stream transformation.
When an application is run with trace level ``info``
the available Python packages on the running system
are listed to application trace. This includes
any packages added by this method.
Example::
topo = Topology()
# Add dependency on pint package
# and astral at version 0.8.1
topo.add_pip_package('pint')
topo.add_pip_package('astral==0.8.1')
Args:
requirement(str): Package requirements specifier.
.. warning::
Only supported when using the build service with
a Streams instance in IBM Cloud Private for Data
or Streaming Analytics service on IBM Cloud.
.. note::
Installing packages through `pip` is preferred to
the automatic dependency checking performed on local
modules. This is because `pip` will perform a full
install of the package including any dependent packages
and additional files, such as shared libraries, that
might be missed by dependency discovery.
.. versionadded:: 1.9
"""
self._pip_packages.append(str(requirement))
pr = pkg_resources.Requirement.parse(requirement)
self.exclude_packages.add(pr.project_name) | python | 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 be available from `pypi.org`.
If the package is already installed on the build system
then it is not added into the `sab` file.
The assumption is that the runtime hosts for a Streams
instance have the same Python packages installed as the
build machines. This is always true for IBM Cloud
Private for Data and the Streaming Analytics service on IBM Cloud.
The project name extracted from the requirement
specifier is added to :py:attr:`~exclude_packages`
to avoid the package being added by the dependency
resolver. Thus the package should be added before
it is used in any stream transformation.
When an application is run with trace level ``info``
the available Python packages on the running system
are listed to application trace. This includes
any packages added by this method.
Example::
topo = Topology()
# Add dependency on pint package
# and astral at version 0.8.1
topo.add_pip_package('pint')
topo.add_pip_package('astral==0.8.1')
Args:
requirement(str): Package requirements specifier.
.. warning::
Only supported when using the build service with
a Streams instance in IBM Cloud Private for Data
or Streaming Analytics service on IBM Cloud.
.. note::
Installing packages through `pip` is preferred to
the automatic dependency checking performed on local
modules. This is because `pip` will perform a full
install of the package including any dependent packages
and additional files, such as shared libraries, that
might be missed by dependency discovery.
.. versionadded:: 1.9
"""
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",
")",
":",
"self",
".",
"_pip_packages",
".",
"append",
"(",
"str",
"(",
"requirement",
")",
")",
"pr",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"requirement",
")",
"self",
".",
... | 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 be available from `pypi.org`.
If the package is already installed on the build system
then it is not added into the `sab` file.
The assumption is that the runtime hosts for a Streams
instance have the same Python packages installed as the
build machines. This is always true for IBM Cloud
Private for Data and the Streaming Analytics service on IBM Cloud.
The project name extracted from the requirement
specifier is added to :py:attr:`~exclude_packages`
to avoid the package being added by the dependency
resolver. Thus the package should be added before
it is used in any stream transformation.
When an application is run with trace level ``info``
the available Python packages on the running system
are listed to application trace. This includes
any packages added by this method.
Example::
topo = Topology()
# Add dependency on pint package
# and astral at version 0.8.1
topo.add_pip_package('pint')
topo.add_pip_package('astral==0.8.1')
Args:
requirement(str): Package requirements specifier.
.. warning::
Only supported when using the build service with
a Streams instance in IBM Cloud Private for Data
or Streaming Analytics service on IBM Cloud.
.. note::
Installing packages through `pip` is preferred to
the automatic dependency checking performed on local
modules. This is because `pip` will perform a full
install of the package including any dependent packages
and additional files, such as shared libraries, that
might be missed by dependency discovery.
.. versionadded:: 1.9 | [
"Add",
"a",
"Python",
"package",
"dependency",
"for",
"this",
"topology",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L609-L666 | train | 44,027 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Topology.create_submission_parameter | 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 topology.
The returned parameter is a `callable`.
Prior to submitting the topology, while constructing the topology,
invoking it returns ``None``.
After the topology is submitted, invoking the parameter
within the executing topology returns the actual submission time value
(or the default value if it was not set at submission time).
Submission parameters may be used within functional logic. e.g.::
threshold = topology.create_submission_parameter('threshold', 100);
# s is some stream of integers
s = ...
s = s.filter(lambda v : v > threshold())
.. note::
The parameter (value returned from this method) is only
supported within a lambda expression or a callable
that is not a function.
The default type of a submission parameter's value is a `str`
(`unicode` on Python 2.7). When a `default` is specified
the type of the value matches the type of the default.
If `default` is not set, then the type can be set with `type_`.
The types supported are ``str``, ``int``, ``float`` and ``bool``.
Topology submission behavior when a submission parameter
lacking a default value is created and a value is not provided at
submission time is defined by the underlying topology execution runtime.
* Submission fails for contexts ``DISTRIBUTED``, ``STANDALONE``, and ``STREAMING_ANALYTICS_SERVICE``.
Args:
name(str): Name for submission parameter.
default: Default parameter when submission parameter is not set.
type_: Type of parameter value when default is not set. Supported values are `str`, `int`, `float` and `bool`.
.. versionadded:: 1.9
"""
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 | python | 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 topology.
The returned parameter is a `callable`.
Prior to submitting the topology, while constructing the topology,
invoking it returns ``None``.
After the topology is submitted, invoking the parameter
within the executing topology returns the actual submission time value
(or the default value if it was not set at submission time).
Submission parameters may be used within functional logic. e.g.::
threshold = topology.create_submission_parameter('threshold', 100);
# s is some stream of integers
s = ...
s = s.filter(lambda v : v > threshold())
.. note::
The parameter (value returned from this method) is only
supported within a lambda expression or a callable
that is not a function.
The default type of a submission parameter's value is a `str`
(`unicode` on Python 2.7). When a `default` is specified
the type of the value matches the type of the default.
If `default` is not set, then the type can be set with `type_`.
The types supported are ``str``, ``int``, ``float`` and ``bool``.
Topology submission behavior when a submission parameter
lacking a default value is created and a value is not provided at
submission time is defined by the underlying topology execution runtime.
* Submission fails for contexts ``DISTRIBUTED``, ``STANDALONE``, and ``STREAMING_ANALYTICS_SERVICE``.
Args:
name(str): Name for submission parameter.
default: Default parameter when submission parameter is not set.
type_: Type of parameter value when default is not set. Supported values are `str`, `int`, `float` and `bool`.
.. versionadded:: 1.9
"""
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",
")",
":",
"if",
"name",
"in",
"self",
".",
"_submission_parameters",
":",
"raise",
"ValueError",
"(",
"\"Submission parameter {} already defined... | 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 topology.
The returned parameter is a `callable`.
Prior to submitting the topology, while constructing the topology,
invoking it returns ``None``.
After the topology is submitted, invoking the parameter
within the executing topology returns the actual submission time value
(or the default value if it was not set at submission time).
Submission parameters may be used within functional logic. e.g.::
threshold = topology.create_submission_parameter('threshold', 100);
# s is some stream of integers
s = ...
s = s.filter(lambda v : v > threshold())
.. note::
The parameter (value returned from this method) is only
supported within a lambda expression or a callable
that is not a function.
The default type of a submission parameter's value is a `str`
(`unicode` on Python 2.7). When a `default` is specified
the type of the value matches the type of the default.
If `default` is not set, then the type can be set with `type_`.
The types supported are ``str``, ``int``, ``float`` and ``bool``.
Topology submission behavior when a submission parameter
lacking a default value is created and a value is not provided at
submission time is defined by the underlying topology execution runtime.
* Submission fails for contexts ``DISTRIBUTED``, ``STANDALONE``, and ``STREAMING_ANALYTICS_SERVICE``.
Args:
name(str): Name for submission parameter.
default: Default parameter when submission parameter is not set.
type_: Type of parameter value when default is not set. Supported values are `str`, `int`, `float` and `bool`.
.. versionadded:: 1.9 | [
"Create",
"a",
"submission",
"parameter",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L668-L725 | train | 44,028 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Topology._generate_requirements | def _generate_requirements(self):
"""Generate the info to create requirements.txt in the toookit."""
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' not in self._files:
self._files['opt'] = [reqs_include]
else:
self._files['opt'].append(reqs_include) | python | def _generate_requirements(self):
"""Generate the info to create requirements.txt in the toookit."""
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' not in self._files:
self._files['opt'] = [reqs_include]
else:
self._files['opt'].append(reqs_include) | [
"def",
"_generate_requirements",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pip_packages",
":",
"return",
"reqs",
"=",
"''",
"for",
"req",
"in",
"self",
".",
"_pip_packages",
":",
"reqs",
"+=",
"\"{}\\n\"",
".",
"format",
"(",
"req",
")",
"reqs_i... | Generate the info to create requirements.txt in the toookit. | [
"Generate",
"the",
"info",
"to",
"create",
"requirements",
".",
"txt",
"in",
"the",
"toookit",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L775-L791 | train | 44,029 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Topology._add_job_control_plane | 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.
"""
if not self._has_jcp:
jcp = self.graph.addOperator(kind="spl.control::JobControlPlane", name="JobControlPlane")
jcp.viewable = False
self._has_jcp = True | python | 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.
"""
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",
")",
":",
"if",
"not",
"self",
".",
"_has_jcp",
":",
"jcp",
"=",
"self",
".",
"graph",
".",
"addOperator",
"(",
"kind",
"=",
"\"spl.control::JobControlPlane\"",
",",
"name",
"=",
"\"JobControlPlane\"",
")",
"jcp",
... | 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. | [
"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",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L793-L802 | train | 44,030 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.aliased_as | 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 name
of the actual stream.
Example use where the filter expression for a ``Filter`` SPL operator
uses ``IN`` to access input tuple attribute ``seq``::
s = ...
s = s.aliased_as('IN')
params = {'filter': op.Expression.expression('IN.seq % 4ul == 0ul')}
f = op.Map('spl.relational::Filter', stream, params = params)
Args:
name(str): Name for returned stream.
Returns:
Stream: Alias of this stream with ``name`` equal to `name`.
.. versionadded:: 1.9
"""
stream = copy.copy(self)
stream._alias = name
return stream | python | 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 name
of the actual stream.
Example use where the filter expression for a ``Filter`` SPL operator
uses ``IN`` to access input tuple attribute ``seq``::
s = ...
s = s.aliased_as('IN')
params = {'filter': op.Expression.expression('IN.seq % 4ul == 0ul')}
f = op.Map('spl.relational::Filter', stream, params = params)
Args:
name(str): Name for returned stream.
Returns:
Stream: Alias of this stream with ``name`` equal to `name`.
.. versionadded:: 1.9
"""
stream = copy.copy(self)
stream._alias = name
return stream | [
"def",
"aliased_as",
"(",
"self",
",",
"name",
")",
":",
"stream",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"stream",
".",
"_alias",
"=",
"name",
"return",
"stream"
] | 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 name
of the actual stream.
Example use where the filter expression for a ``Filter`` SPL operator
uses ``IN`` to access input tuple attribute ``seq``::
s = ...
s = s.aliased_as('IN')
params = {'filter': op.Expression.expression('IN.seq % 4ul == 0ul')}
f = op.Map('spl.relational::Filter', stream, params = params)
Args:
name(str): Name for returned stream.
Returns:
Stream: Alias of this stream with ``name`` equal to `name`.
.. versionadded:: 1.9 | [
"Create",
"an",
"alias",
"of",
"this",
"stream",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L844-L874 | train | 44,031 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.view | 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.streams.excel.doc/doc/excel_overview.html>`_ or REST clients.
The view created by this method can be used by external clients
and through the returned :py:class:`~streamsx.topology.topology.View` object after the topology is submitted. For example a Jupyter Notebook can
declare and submit an application with views, and then
use the resultant `View` objects to visualize live data within the streams.
When the stream contains Python objects then they are converted
to JSON.
Args:
buffer_time: Specifies the buffer size to use measured in seconds.
sample_size: Specifies the number of tuples to sample per second.
name(str): Name of the view. Name must be unique within the topology. Defaults to a generated name.
description: Description of the view.
start(bool): Start buffering data when the job is submitted.
If `False` then the view starts buffering data when the first
remote client accesses it to retrieve data.
Returns:
streamsx.topology.topology.View: View object which can be used to access the data when the
topology is submitted.
.. note:: Views are only supported when submitting to distributed
contexts including Streaming Analytics service.
"""
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_stream = self.as_json(force_object=False)._layout(hidden=True)
view_stream = self._json_stream
# colocate map operator with stream that is being viewed.
if self._placeable:
self._colocate(view_stream, 'view')
else:
view_stream = self
port = view_stream.oport.name
view_config = {
'name': name,
'port': port,
'description': description,
'bufferTime': buffer_time,
'sampleSize': sample_size}
if start:
view_config['activateOption'] = 'automatic'
view_stream.oport.operator.addViewConfig(view_config)
_view = View(name)
self.topology.graph._views.append(_view)
return _view | python | 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.streams.excel.doc/doc/excel_overview.html>`_ or REST clients.
The view created by this method can be used by external clients
and through the returned :py:class:`~streamsx.topology.topology.View` object after the topology is submitted. For example a Jupyter Notebook can
declare and submit an application with views, and then
use the resultant `View` objects to visualize live data within the streams.
When the stream contains Python objects then they are converted
to JSON.
Args:
buffer_time: Specifies the buffer size to use measured in seconds.
sample_size: Specifies the number of tuples to sample per second.
name(str): Name of the view. Name must be unique within the topology. Defaults to a generated name.
description: Description of the view.
start(bool): Start buffering data when the job is submitted.
If `False` then the view starts buffering data when the first
remote client accesses it to retrieve data.
Returns:
streamsx.topology.topology.View: View object which can be used to access the data when the
topology is submitted.
.. note:: Views are only supported when submitting to distributed
contexts including Streaming Analytics service.
"""
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_stream = self.as_json(force_object=False)._layout(hidden=True)
view_stream = self._json_stream
# colocate map operator with stream that is being viewed.
if self._placeable:
self._colocate(view_stream, 'view')
else:
view_stream = self
port = view_stream.oport.name
view_config = {
'name': name,
'port': port,
'description': description,
'bufferTime': buffer_time,
'sampleSize': sample_size}
if start:
view_config['activateOption'] = 'automatic'
view_stream.oport.operator.addViewConfig(view_config)
_view = View(name)
self.topology.graph._views.append(_view)
return _view | [
"def",
"view",
"(",
"self",
",",
"buffer_time",
"=",
"10.0",
",",
"sample_size",
"=",
"10000",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"start",
"=",
"False",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"''",
".",... | 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.streams.excel.doc/doc/excel_overview.html>`_ or REST clients.
The view created by this method can be used by external clients
and through the returned :py:class:`~streamsx.topology.topology.View` object after the topology is submitted. For example a Jupyter Notebook can
declare and submit an application with views, and then
use the resultant `View` objects to visualize live data within the streams.
When the stream contains Python objects then they are converted
to JSON.
Args:
buffer_time: Specifies the buffer size to use measured in seconds.
sample_size: Specifies the number of tuples to sample per second.
name(str): Name of the view. Name must be unique within the topology. Defaults to a generated name.
description: Description of the view.
start(bool): Start buffering data when the job is submitted.
If `False` then the view starts buffering data when the first
remote client accesses it to retrieve data.
Returns:
streamsx.topology.topology.View: View object which can be used to access the data when the
topology is submitted.
.. note:: Views are only supported when submitting to distributed
contexts including Streaming Analytics service. | [
"Defines",
"a",
"view",
"on",
"a",
"stream",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L963-L1023 | train | 44,032 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.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.
By default the submitted tuple is ``result`` without modification
resulting in a stream of picklable Python objects. Setting the
`schema` parameter changes the type of the stream and
modifies each ``result`` before submission.
* ``object`` or :py:const:`~streamsx.topology.schema.CommonSchema.Python` - The default: `result` is submitted.
* ``str`` type (``unicode`` 2.7) or :py:const:`~streamsx.topology.schema.CommonSchema.String` - A stream of strings: ``str(result)`` is submitted.
* ``json`` or :py:const:`~streamsx.topology.schema.CommonSchema.Json` - A stream of JSON objects: ``result`` must be convertable to a JSON object using `json` package.
* :py:const:`~streamsx.topology.schema.StreamSchema` - A structured stream. `result` must be a `dict` or (Python) `tuple`. When a `dict` is returned the outgoing stream tuple attributes are set by name, when a `tuple` is returned stream tuple attributes are set by position.
* string value - Equivalent to passing ``StreamSchema(schema)``
Args:
func: A callable that takes a single parameter for the tuple.
If not supplied then a function equivalent to ``lambda tuple_ : tuple_`` is used.
name(str): Name of the mapped stream, defaults to a generated name.
schema(StreamSchema|CommonSchema|str): Schema of the resulting stream.
If invoking ``func`` for a tuple on the stream raises an exception
then its processing element will terminate. By default the processing
element will automatically restart though tuples may be lost.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method. When an
exception is suppressed no tuple is submitted to the mapped
stream corresponding to the input tuple that caused the exception.
Returns:
Stream: A stream containing tuples mapped by `func`.
.. versionadded:: 1.7 `schema` argument added to allow conversion to
a structured stream.
.. versionadded:: 1.8 Support for submitting `dict` objects as stream tuples to a structured stream (in addition to existing support for `tuple` objects).
.. versionchanged:: 1.11 `func` is optional.
"""
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')
ms.oport.operator.sl = _SourceLocation(_source_info(), 'map')
return ms | python | 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.
By default the submitted tuple is ``result`` without modification
resulting in a stream of picklable Python objects. Setting the
`schema` parameter changes the type of the stream and
modifies each ``result`` before submission.
* ``object`` or :py:const:`~streamsx.topology.schema.CommonSchema.Python` - The default: `result` is submitted.
* ``str`` type (``unicode`` 2.7) or :py:const:`~streamsx.topology.schema.CommonSchema.String` - A stream of strings: ``str(result)`` is submitted.
* ``json`` or :py:const:`~streamsx.topology.schema.CommonSchema.Json` - A stream of JSON objects: ``result`` must be convertable to a JSON object using `json` package.
* :py:const:`~streamsx.topology.schema.StreamSchema` - A structured stream. `result` must be a `dict` or (Python) `tuple`. When a `dict` is returned the outgoing stream tuple attributes are set by name, when a `tuple` is returned stream tuple attributes are set by position.
* string value - Equivalent to passing ``StreamSchema(schema)``
Args:
func: A callable that takes a single parameter for the tuple.
If not supplied then a function equivalent to ``lambda tuple_ : tuple_`` is used.
name(str): Name of the mapped stream, defaults to a generated name.
schema(StreamSchema|CommonSchema|str): Schema of the resulting stream.
If invoking ``func`` for a tuple on the stream raises an exception
then its processing element will terminate. By default the processing
element will automatically restart though tuples may be lost.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method. When an
exception is suppressed no tuple is submitted to the mapped
stream corresponding to the input tuple that caused the exception.
Returns:
Stream: A stream containing tuples mapped by `func`.
.. versionadded:: 1.7 `schema` argument added to allow conversion to
a structured stream.
.. versionadded:: 1.8 Support for submitting `dict` objects as stream tuples to a structured stream (in addition to existing support for `tuple` objects).
.. versionchanged:: 1.11 `func` is optional.
"""
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')
ms.oport.operator.sl = _SourceLocation(_source_info(), 'map')
return ms | [
"def",
"map",
"(",
"self",
",",
"func",
"=",
"None",
",",
"name",
"=",
"None",
",",
"schema",
"=",
"None",
")",
":",
"if",
"schema",
"is",
"None",
":",
"schema",
"=",
"streamsx",
".",
"topology",
".",
"schema",
".",
"CommonSchema",
".",
"Python",
"... | 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.
By default the submitted tuple is ``result`` without modification
resulting in a stream of picklable Python objects. Setting the
`schema` parameter changes the type of the stream and
modifies each ``result`` before submission.
* ``object`` or :py:const:`~streamsx.topology.schema.CommonSchema.Python` - The default: `result` is submitted.
* ``str`` type (``unicode`` 2.7) or :py:const:`~streamsx.topology.schema.CommonSchema.String` - A stream of strings: ``str(result)`` is submitted.
* ``json`` or :py:const:`~streamsx.topology.schema.CommonSchema.Json` - A stream of JSON objects: ``result`` must be convertable to a JSON object using `json` package.
* :py:const:`~streamsx.topology.schema.StreamSchema` - A structured stream. `result` must be a `dict` or (Python) `tuple`. When a `dict` is returned the outgoing stream tuple attributes are set by name, when a `tuple` is returned stream tuple attributes are set by position.
* string value - Equivalent to passing ``StreamSchema(schema)``
Args:
func: A callable that takes a single parameter for the tuple.
If not supplied then a function equivalent to ``lambda tuple_ : tuple_`` is used.
name(str): Name of the mapped stream, defaults to a generated name.
schema(StreamSchema|CommonSchema|str): Schema of the resulting stream.
If invoking ``func`` for a tuple on the stream raises an exception
then its processing element will terminate. By default the processing
element will automatically restart though tuples may be lost.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method. When an
exception is suppressed no tuple is submitted to the mapped
stream corresponding to the input tuple that caused the exception.
Returns:
Stream: A stream containing tuples mapped by `func`.
.. versionadded:: 1.7 `schema` argument added to allow conversion to
a structured stream.
.. versionadded:: 1.8 Support for submitting `dict` objects as stream tuples to a structured stream (in addition to existing support for `tuple` objects).
.. versionchanged:: 1.11 `func` is optional. | [
"Maps",
"each",
"tuple",
"from",
"this",
"stream",
"into",
"0",
"or",
"1",
"stream",
"tuples",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1025-L1078 | train | 44,033 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.flat_map | 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.
If the result is `None` or an empty iterable then no tuples are submitted to
the returned stream.
Args:
func: A callable that takes a single parameter for the tuple.
If not supplied then a function equivalent to ``lambda tuple_ : tuple_`` is used.
This is suitable when each tuple on this stream is an iterable to be flattened.
name(str): Name of the flattened stream, defaults to a generated name.
If invoking ``func`` for a tuple on the stream raises an exception
then its processing element will terminate. By default the processing
element will automatically restart though tuples may be lost.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method. When an
exception is suppressed no tuples are submitted to the flattened
and mapped stream corresponding to the input tuple
that caused the exception.
Returns:
Stream: A Stream containing flattened and mapped tuples.
Raises:
TypeError: if `func` does not return an iterator nor None
.. versionchanged:: 1.11 `func` is optional.
"""
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)
stateful = self._determine_statefulness(func)
op = self.topology.graph.addOperator(self.topology.opnamespace+"::FlatMap", func, name=_name, sl=sl, stateful=stateful)
op.addInputPort(outputPort=self.oport)
streamsx.topology.schema.StreamSchema._fnop_style(self.oport.schema, op, 'pyStyle')
oport = op.addOutputPort(name=_name)
return Stream(self.topology, oport)._make_placeable()._layout('FlatMap', name=_name, orig_name=name) | python | 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.
If the result is `None` or an empty iterable then no tuples are submitted to
the returned stream.
Args:
func: A callable that takes a single parameter for the tuple.
If not supplied then a function equivalent to ``lambda tuple_ : tuple_`` is used.
This is suitable when each tuple on this stream is an iterable to be flattened.
name(str): Name of the flattened stream, defaults to a generated name.
If invoking ``func`` for a tuple on the stream raises an exception
then its processing element will terminate. By default the processing
element will automatically restart though tuples may be lost.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method. When an
exception is suppressed no tuples are submitted to the flattened
and mapped stream corresponding to the input tuple
that caused the exception.
Returns:
Stream: A Stream containing flattened and mapped tuples.
Raises:
TypeError: if `func` does not return an iterator nor None
.. versionchanged:: 1.11 `func` is optional.
"""
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)
stateful = self._determine_statefulness(func)
op = self.topology.graph.addOperator(self.topology.opnamespace+"::FlatMap", func, name=_name, sl=sl, stateful=stateful)
op.addInputPort(outputPort=self.oport)
streamsx.topology.schema.StreamSchema._fnop_style(self.oport.schema, op, 'pyStyle')
oport = op.addOutputPort(name=_name)
return Stream(self.topology, oport)._make_placeable()._layout('FlatMap', name=_name, orig_name=name) | [
"def",
"flat_map",
"(",
"self",
",",
"func",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
":",
"func",
"=",
"streamsx",
".",
"topology",
".",
"runtime",
".",
"_identity",
"if",
"name",
"is",
"None",
":",
"name",
"=",... | 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.
If the result is `None` or an empty iterable then no tuples are submitted to
the returned stream.
Args:
func: A callable that takes a single parameter for the tuple.
If not supplied then a function equivalent to ``lambda tuple_ : tuple_`` is used.
This is suitable when each tuple on this stream is an iterable to be flattened.
name(str): Name of the flattened stream, defaults to a generated name.
If invoking ``func`` for a tuple on the stream raises an exception
then its processing element will terminate. By default the processing
element will automatically restart though tuples may be lost.
If ``func`` is a callable object then it may suppress exceptions
by return a true value from its ``__exit__`` method. When an
exception is suppressed no tuples are submitted to the flattened
and mapped stream corresponding to the input tuple
that caused the exception.
Returns:
Stream: A Stream containing flattened and mapped tuples.
Raises:
TypeError: if `func` does not return an iterator nor None
.. versionchanged:: 1.11 `func` is optional. | [
"Maps",
"and",
"flatterns",
"each",
"tuple",
"from",
"this",
"stream",
"into",
"0",
"or",
"more",
"tuples",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1089-L1138 | train | 44,034 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.end_parallel | 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`
"""
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.addOutputPort(schema=self.oport.schema)
op = self.topology.graph.addOperator("$EndParallel$")
op.addInputPort(outputPort=outport)
oport = op.addOutputPort(schema=self.oport.schema)
endP = Stream(self.topology, oport)
return endP | python | 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`
"""
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.addOutputPort(schema=self.oport.schema)
op = self.topology.graph.addOperator("$EndParallel$")
op.addInputPort(outputPort=outport)
oport = op.addOutputPort(schema=self.oport.schema)
endP = Stream(self.topology, oport)
return endP | [
"def",
"end_parallel",
"(",
"self",
")",
":",
"outport",
"=",
"self",
".",
"oport",
"if",
"isinstance",
"(",
"self",
".",
"oport",
".",
"operator",
",",
"streamsx",
".",
"topology",
".",
"graph",
".",
"Marker",
")",
":",
"if",
"self",
".",
"oport",
"... | 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` | [
"Ends",
"a",
"parallel",
"region",
"by",
"merging",
"the",
"channels",
"into",
"a",
"single",
"stream",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1335-L1354 | train | 44,035 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.set_parallel | 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::
s = topo.source(S())
s.set_parallel(3)
f = s.filter(F())
e = f.end_parallel()
Each channel has independent instances of ``S`` and ``F``. Tuples
created by the instance of ``S`` in channel 0 are passed to the
instance of ``F`` in channel 0, and so on for channels 1 and 2.
Callable transforms instances within the channel can use
the runtime functions
:py:func:`~streamsx.ec.channel`,
:py:func:`~streamsx.ec.local_channel`,
:py:func:`~streamsx.ec.max_channels` &
:py:func:`~streamsx.ec.local_max_channels`
to adapt to being invoked in parallel. For example a
source callable can use its channel number to determine
which partition to read from in a partitioned external system.
Calling ``set_parallel`` on a stream created by
:py:meth:`~Topology.subscribe` results in the stream
having `width` channels. Subscribe ensures that the
stream will contain all published tuples matching the
topic subscription and type. A published tuple will appear
on one of the channels though the specific channel is not known
in advance.
A parallel region is terminated by :py:meth:`end_parallel`
or :py:meth:`for_each`.
The number of channels is set by `width` which may be an `int` greater
than zero or a submission parameter created by
:py:meth:`Topology.create_submission_parameter`.
With IBM Streams 4.3 or later the number of channels can be
dynamically changed at runtime.
Parallel regions are started on non-source streams using
:py:meth:`parallel`.
Args:
width: The degree of parallelism for the parallel region.
name(str): Name of the parallel region. Defaults to the name of this stream.
Returns:
Stream: Returns this stream.
.. seealso:: :py:meth:`parallel`, :py:meth:`end_parallel`
.. versionadded:: 1.9
.. versionchanged:: 1.11 `name` parameter added.
"""
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'] = name
return self | python | 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::
s = topo.source(S())
s.set_parallel(3)
f = s.filter(F())
e = f.end_parallel()
Each channel has independent instances of ``S`` and ``F``. Tuples
created by the instance of ``S`` in channel 0 are passed to the
instance of ``F`` in channel 0, and so on for channels 1 and 2.
Callable transforms instances within the channel can use
the runtime functions
:py:func:`~streamsx.ec.channel`,
:py:func:`~streamsx.ec.local_channel`,
:py:func:`~streamsx.ec.max_channels` &
:py:func:`~streamsx.ec.local_max_channels`
to adapt to being invoked in parallel. For example a
source callable can use its channel number to determine
which partition to read from in a partitioned external system.
Calling ``set_parallel`` on a stream created by
:py:meth:`~Topology.subscribe` results in the stream
having `width` channels. Subscribe ensures that the
stream will contain all published tuples matching the
topic subscription and type. A published tuple will appear
on one of the channels though the specific channel is not known
in advance.
A parallel region is terminated by :py:meth:`end_parallel`
or :py:meth:`for_each`.
The number of channels is set by `width` which may be an `int` greater
than zero or a submission parameter created by
:py:meth:`Topology.create_submission_parameter`.
With IBM Streams 4.3 or later the number of channels can be
dynamically changed at runtime.
Parallel regions are started on non-source streams using
:py:meth:`parallel`.
Args:
width: The degree of parallelism for the parallel region.
name(str): Name of the parallel region. Defaults to the name of this stream.
Returns:
Stream: Returns this stream.
.. seealso:: :py:meth:`parallel`, :py:meth:`end_parallel`
.. versionadded:: 1.9
.. versionchanged:: 1.11 `name` parameter added.
"""
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'] = name
return self | [
"def",
"set_parallel",
"(",
"self",
",",
"width",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"oport",
".",
"operator",
".",
"config",
"[",
"'parallel'",
"]",
"=",
"True",
"self",
".",
"oport",
".",
"operator",
".",
"config",
"[",
"'width'",
"]"... | 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::
s = topo.source(S())
s.set_parallel(3)
f = s.filter(F())
e = f.end_parallel()
Each channel has independent instances of ``S`` and ``F``. Tuples
created by the instance of ``S`` in channel 0 are passed to the
instance of ``F`` in channel 0, and so on for channels 1 and 2.
Callable transforms instances within the channel can use
the runtime functions
:py:func:`~streamsx.ec.channel`,
:py:func:`~streamsx.ec.local_channel`,
:py:func:`~streamsx.ec.max_channels` &
:py:func:`~streamsx.ec.local_max_channels`
to adapt to being invoked in parallel. For example a
source callable can use its channel number to determine
which partition to read from in a partitioned external system.
Calling ``set_parallel`` on a stream created by
:py:meth:`~Topology.subscribe` results in the stream
having `width` channels. Subscribe ensures that the
stream will contain all published tuples matching the
topic subscription and type. A published tuple will appear
on one of the channels though the specific channel is not known
in advance.
A parallel region is terminated by :py:meth:`end_parallel`
or :py:meth:`for_each`.
The number of channels is set by `width` which may be an `int` greater
than zero or a submission parameter created by
:py:meth:`Topology.create_submission_parameter`.
With IBM Streams 4.3 or later the number of channels can be
dynamically changed at runtime.
Parallel regions are started on non-source streams using
:py:meth:`parallel`.
Args:
width: The degree of parallelism for the parallel region.
name(str): Name of the parallel region. Defaults to the name of this stream.
Returns:
Stream: Returns this stream.
.. seealso:: :py:meth:`parallel`, :py:meth:`end_parallel`
.. versionadded:: 1.9
.. versionchanged:: 1.11 `name` parameter added. | [
"Set",
"this",
"source",
"stream",
"to",
"be",
"split",
"into",
"multiple",
"channels",
"as",
"the",
"start",
"of",
"a",
"parallel",
"region",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1356-L1423 | train | 44,036 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.set_consistent | 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
"""
# add job control plane if needed
self.topology._add_job_control_plane()
self.oport.operator.consistent(consistent_config)
return self._make_placeable() | python | 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
"""
# 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",
")",
":",
"# add job control plane if needed",
"self",
".",
"topology",
".",
"_add_job_control_plane",
"(",
")",
"self",
".",
"oport",
".",
"operator",
".",
"consistent",
"(",
"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 | [
"Indicates",
"that",
"the",
"stream",
"is",
"the",
"start",
"of",
"a",
"consistent",
"region",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1425-L1440 | train | 44,037 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.last | 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 recent) ten tuples.
If `size` is an `datetime.timedelta` then it is the duration
of the window. With a `timedelta` representing five minutes
then the window contains any tuples that arrived in the last
five minutes.
Args:
size: The size of the window, either an `int` to define the
number of tuples or `datetime.timedelta` to define the
duration of the window.
Examples::
# Create a window against stream s of the last 100 tuples
w = s.last(size=100)
::
# Create a window against stream s of tuples
# arrived on the stream in the last five minutes
w = s.last(size=datetime.timedelta(minutes=5))
Returns:
Window: Window of the last (most recent) tuples on this stream.
"""
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 | python | 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 recent) ten tuples.
If `size` is an `datetime.timedelta` then it is the duration
of the window. With a `timedelta` representing five minutes
then the window contains any tuples that arrived in the last
five minutes.
Args:
size: The size of the window, either an `int` to define the
number of tuples or `datetime.timedelta` to define the
duration of the window.
Examples::
# Create a window against stream s of the last 100 tuples
w = s.last(size=100)
::
# Create a window against stream s of tuples
# arrived on the stream in the last five minutes
w = s.last(size=datetime.timedelta(minutes=5))
Returns:
Window: Window of the last (most recent) tuples on this stream.
"""
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",
")",
":",
"win",
"=",
"Window",
"(",
"self",
",",
"'SLIDING'",
")",
"if",
"isinstance",
"(",
"size",
",",
"datetime",
".",
"timedelta",
")",
":",
"win",
".",
"_evict_time",
"(",
"size",
")",
"elif"... | 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 recent) ten tuples.
If `size` is an `datetime.timedelta` then it is the duration
of the window. With a `timedelta` representing five minutes
then the window contains any tuples that arrived in the last
five minutes.
Args:
size: The size of the window, either an `int` to define the
number of tuples or `datetime.timedelta` to define the
duration of the window.
Examples::
# Create a window against stream s of the last 100 tuples
w = s.last(size=100)
::
# Create a window against stream s of tuples
# arrived on the stream in the last five minutes
w = s.last(size=datetime.timedelta(minutes=5))
Returns:
Window: Window of the last (most recent) tuples on this stream. | [
"Declares",
"a",
"slding",
"window",
"containing",
"most",
"recent",
"tuples",
"on",
"this",
"stream",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1442-L1483 | train | 44,038 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.print | 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 generated name.
Returns:
streamsx.topology.topology.Sink: Stream termination.
.. versionadded:: 1.6.1 `tag`, `name` parameters.
.. versionchanged:: 1.7
Now returns a :py:class:`Sink` instance.
"""
_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=_name)
sp._op().sl = _SourceLocation(_source_info(), 'print')
return sp | python | 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 generated name.
Returns:
streamsx.topology.topology.Sink: Stream termination.
.. versionadded:: 1.6.1 `tag`, `name` parameters.
.. versionchanged:: 1.7
Now returns a :py:class:`Sink` instance.
"""
_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=_name)
sp._op().sl = _SourceLocation(_source_info(), 'print')
return sp | [
"def",
"print",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"_name",
"=",
"name",
"if",
"_name",
"is",
"None",
":",
"_name",
"=",
"'print'",
"fn",
"=",
"streamsx",
".",
"topology",
".",
"functions",
".",
"print_flush",
... | 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 generated name.
Returns:
streamsx.topology.topology.Sink: Stream termination.
.. versionadded:: 1.6.1 `tag`, `name` parameters.
.. versionchanged:: 1.7
Now returns a :py:class:`Sink` instance. | [
"Prints",
"each",
"tuple",
"to",
"stdout",
"flushing",
"after",
"each",
"tuple",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1571-L1599 | train | 44,039 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.publish | 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 schema.
A stream of :py:const:`Python objects <streamsx.topology.schema.CommonSchema.Python>` can be subscribed to by other Streams Python applications.
If a stream is published setting `schema` to
:py:const:`~streamsx.topology.schema.CommonSchema.Json`
then it is published as a stream of JSON objects.
Other Streams applications may subscribe to it regardless
of their implementation language.
If a stream is published setting `schema` to
:py:const:`~streamsx.topology.schema.CommonSchema.String`
then it is published as strings
Other Streams applications may subscribe to it regardless
of their implementation language.
Supported values of `schema` are only
:py:const:`~streamsx.topology.schema.CommonSchema.Json`
and
:py:const:`~streamsx.topology.schema.CommonSchema.String`.
Args:
topic(str): Topic to publish this stream to.
schema: Schema to publish. Defaults to the schema of this stream.
name(str): Name of the publish operator, defaults to a generated name.
Returns:
streamsx.topology.topology.Sink: Stream termination.
.. versionadded:: 1.6.1 `name` parameter.
.. versionchanged:: 1.7
Now returns a :py:class:`Sink` instance.
"""
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_change = self.as_json()
elif schema == streamsx.topology.schema.CommonSchema.String:
schema_change = self.as_string()
else:
raise ValueError(schema)
if self._placeable:
self._colocate(schema_change, 'publish')
sp = schema_change.publish(topic, schema=schema, name=name)
sp._op().sl = sl
return sp
_name = self.topology.graph._requested_name(name, action="publish")
# publish is never stateful
op = self.topology.graph.addOperator("com.ibm.streamsx.topology.topic::Publish", params={'topic': topic}, sl=sl, name=_name, stateful=False)
op.addInputPort(outputPort=self.oport)
op._layout_group('Publish', name if name else _name)
sink = Sink(op)
if self._placeable:
self._colocate(sink, 'publish')
return sink | python | 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 schema.
A stream of :py:const:`Python objects <streamsx.topology.schema.CommonSchema.Python>` can be subscribed to by other Streams Python applications.
If a stream is published setting `schema` to
:py:const:`~streamsx.topology.schema.CommonSchema.Json`
then it is published as a stream of JSON objects.
Other Streams applications may subscribe to it regardless
of their implementation language.
If a stream is published setting `schema` to
:py:const:`~streamsx.topology.schema.CommonSchema.String`
then it is published as strings
Other Streams applications may subscribe to it regardless
of their implementation language.
Supported values of `schema` are only
:py:const:`~streamsx.topology.schema.CommonSchema.Json`
and
:py:const:`~streamsx.topology.schema.CommonSchema.String`.
Args:
topic(str): Topic to publish this stream to.
schema: Schema to publish. Defaults to the schema of this stream.
name(str): Name of the publish operator, defaults to a generated name.
Returns:
streamsx.topology.topology.Sink: Stream termination.
.. versionadded:: 1.6.1 `name` parameter.
.. versionchanged:: 1.7
Now returns a :py:class:`Sink` instance.
"""
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_change = self.as_json()
elif schema == streamsx.topology.schema.CommonSchema.String:
schema_change = self.as_string()
else:
raise ValueError(schema)
if self._placeable:
self._colocate(schema_change, 'publish')
sp = schema_change.publish(topic, schema=schema, name=name)
sp._op().sl = sl
return sp
_name = self.topology.graph._requested_name(name, action="publish")
# publish is never stateful
op = self.topology.graph.addOperator("com.ibm.streamsx.topology.topic::Publish", params={'topic': topic}, sl=sl, name=_name, stateful=False)
op.addInputPort(outputPort=self.oport)
op._layout_group('Publish', name if name else _name)
sink = Sink(op)
if self._placeable:
self._colocate(sink, 'publish')
return sink | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"schema",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"sl",
"=",
"_SourceLocation",
"(",
"_source_info",
"(",
")",
",",
"'publish'",
")",
"schema",
"=",
"streamsx",
".",
"topology",
".",
"schema",
... | 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 schema.
A stream of :py:const:`Python objects <streamsx.topology.schema.CommonSchema.Python>` can be subscribed to by other Streams Python applications.
If a stream is published setting `schema` to
:py:const:`~streamsx.topology.schema.CommonSchema.Json`
then it is published as a stream of JSON objects.
Other Streams applications may subscribe to it regardless
of their implementation language.
If a stream is published setting `schema` to
:py:const:`~streamsx.topology.schema.CommonSchema.String`
then it is published as strings
Other Streams applications may subscribe to it regardless
of their implementation language.
Supported values of `schema` are only
:py:const:`~streamsx.topology.schema.CommonSchema.Json`
and
:py:const:`~streamsx.topology.schema.CommonSchema.String`.
Args:
topic(str): Topic to publish this stream to.
schema: Schema to publish. Defaults to the schema of this stream.
name(str): Name of the publish operator, defaults to a generated name.
Returns:
streamsx.topology.topology.Sink: Stream termination.
.. versionadded:: 1.6.1 `name` parameter.
.. versionchanged:: 1.7
Now returns a :py:class:`Sink` instance. | [
"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"... | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1601-L1667 | train | 44,040 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream.as_json | 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`
will be converted to a JSON object with a single key `payload`
containing the tuple. Thus each object on the stream will
be a JSON object.
If `force_object` is `False` then each tuple is converted to
a JSON value directly using `json` package.
If this stream is already typed as a JSON stream then it will
be returned (with no additional processing against it and
`force_object` and `name` are ignored).
Args:
force_object(bool): Force conversion of non dicts to JSON objects.
name(str): Name of the resulting stream.
When `None` defaults to a generated name.
.. versionadded:: 1.6.1
Returns:
Stream: Stream containing the JSON representations of tuples on this stream.
"""
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 | python | 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`
will be converted to a JSON object with a single key `payload`
containing the tuple. Thus each object on the stream will
be a JSON object.
If `force_object` is `False` then each tuple is converted to
a JSON value directly using `json` package.
If this stream is already typed as a JSON stream then it will
be returned (with no additional processing against it and
`force_object` and `name` are ignored).
Args:
force_object(bool): Force conversion of non dicts to JSON objects.
name(str): Name of the resulting stream.
When `None` defaults to a generated name.
.. versionadded:: 1.6.1
Returns:
Stream: Stream containing the JSON representations of tuples on this stream.
"""
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",
")",
":",
"func",
"=",
"streamsx",
".",
"topology",
".",
"runtime",
".",
"_json_force_object",
"if",
"force_object",
"else",
"None",
"saj",
"=",
"self",
".",
"_cha... | 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`
will be converted to a JSON object with a single key `payload`
containing the tuple. Thus each object on the stream will
be a JSON object.
If `force_object` is `False` then each tuple is converted to
a JSON value directly using `json` package.
If this stream is already typed as a JSON stream then it will
be returned (with no additional processing against it and
`force_object` and `name` are ignored).
Args:
force_object(bool): Force conversion of non dicts to JSON objects.
name(str): Name of the resulting stream.
When `None` defaults to a generated name.
.. versionadded:: 1.6.1
Returns:
Stream: Stream containing the JSON representations of tuples on this stream. | [
"Declares",
"a",
"stream",
"converting",
"each",
"tuple",
"on",
"this",
"stream",
"into",
"a",
"JSON",
"value",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1718-L1753 | train | 44,041 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Stream._change_schema | def _change_schema(self, schema, action, name=None, func=None):
"""Internal method to change a schema.
"""
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._placeable:
self._colocate(css, action)
return css | python | def _change_schema(self, schema, action, name=None, func=None):
"""Internal method to change a schema.
"""
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._placeable:
self._colocate(css, action)
return css | [
"def",
"_change_schema",
"(",
"self",
",",
"schema",
",",
"action",
",",
"name",
"=",
"None",
",",
"func",
"=",
"None",
")",
":",
"if",
"self",
".",
"oport",
".",
"schema",
".",
"schema",
"(",
")",
"==",
"schema",
".",
"schema",
"(",
")",
":",
"r... | Internal method to change a schema. | [
"Internal",
"method",
"to",
"change",
"a",
"schema",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1755-L1770 | train | 44,042 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | View._initialize_rest | def _initialize_rest(self):
"""Used to initialize the View object on first use.
"""
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] | python | def _initialize_rest(self):
"""Used to initialize the View object on first use.
"""
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",
")",
":",
"if",
"self",
".",
"_submit_context",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"View has not been created.\"",
")",
"job",
"=",
"self",
".",
"_submit_context",
".",
"_job_access",
"(",
")",
"self",
".",... | Used to initialize the View object on first use. | [
"Used",
"to",
"initialize",
"the",
"View",
"object",
"on",
"first",
"use",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1814-L1820 | train | 44,043 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | PendingStream.complete | 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.
"""
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 automatically updated to the correct schema
self._pending_schema._set(self.stream.oport.schema)
# Mark the operator with the pending stream
# a start point for graph travesal
stream.oport.operator._start_op = True | python | 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.
"""
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 automatically updated to the correct schema
self._pending_schema._set(self.stream.oport.schema)
# Mark the operator with the pending stream
# a start point for graph travesal
stream.oport.operator._start_op = True | [
"def",
"complete",
"(",
"self",
",",
"stream",
")",
":",
"assert",
"not",
"self",
".",
"is_complete",
"(",
")",
"self",
".",
"_marker",
".",
"addInputPort",
"(",
"outputPort",
"=",
"stream",
".",
"oport",
")",
"self",
".",
"stream",
".",
"oport",
".",
... | 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. | [
"Complete",
"the",
"pending",
"stream",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1933-L1952 | train | 44,044 |
IBMStreams/pypi.streamsx | streamsx/topology/topology.py | Window.trigger | 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 an `datetime.timedelta` then it is the period
of the trigger. With a `timedelta` representing one minute
then the window is triggered every minute.
By default, when `trigger` has not been called on a `Window`
it triggers for every tuple inserted into the window
(equivalent to ``when=1``).
Args:
when: The size of the window, either an `int` to define the
number of tuples or `datetime.timedelta` to define the
duration of the window.
Returns:
Window: Window that will be triggered.
.. warning:: A trigger is only supported for a sliding window
such as one created by :py:meth:`last`.
"""
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 isinstance(when, datetime.timedelta):
tw._config['triggerPolicy'] = 'TIME'
tw._config['triggerConfig'] = int(when.total_seconds() * 1000.0)
tw._config['triggerTimeUnit'] = 'MILLISECONDS'
elif isinstance(when, int):
tw._config['triggerPolicy'] = 'COUNT'
tw._config['triggerConfig'] = when
else:
raise ValueError(when)
return tw | python | 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 an `datetime.timedelta` then it is the period
of the trigger. With a `timedelta` representing one minute
then the window is triggered every minute.
By default, when `trigger` has not been called on a `Window`
it triggers for every tuple inserted into the window
(equivalent to ``when=1``).
Args:
when: The size of the window, either an `int` to define the
number of tuples or `datetime.timedelta` to define the
duration of the window.
Returns:
Window: Window that will be triggered.
.. warning:: A trigger is only supported for a sliding window
such as one created by :py:meth:`last`.
"""
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 isinstance(when, datetime.timedelta):
tw._config['triggerPolicy'] = 'TIME'
tw._config['triggerConfig'] = int(when.total_seconds() * 1000.0)
tw._config['triggerTimeUnit'] = 'MILLISECONDS'
elif isinstance(when, int):
tw._config['triggerPolicy'] = 'COUNT'
tw._config['triggerConfig'] = when
else:
raise ValueError(when)
return tw | [
"def",
"trigger",
"(",
"self",
",",
"when",
"=",
"1",
")",
":",
"tw",
"=",
"Window",
"(",
"self",
".",
"stream",
",",
"self",
".",
"_config",
"[",
"'type'",
"]",
")",
"tw",
".",
"_config",
"[",
"'evictPolicy'",
"]",
"=",
"self",
".",
"_config",
"... | 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 an `datetime.timedelta` then it is the period
of the trigger. With a `timedelta` representing one minute
then the window is triggered every minute.
By default, when `trigger` has not been called on a `Window`
it triggers for every tuple inserted into the window
(equivalent to ``when=1``).
Args:
when: The size of the window, either an `int` to define the
number of tuples or `datetime.timedelta` to define the
duration of the window.
Returns:
Window: Window that will be triggered.
.. warning:: A trigger is only supported for a sliding window
such as one created by :py:meth:`last`. | [
"Declare",
"a",
"window",
"with",
"this",
"window",
"s",
"size",
"and",
"a",
"trigger",
"policy",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/topology.py#L1991-L2034 | train | 44,045 |
IBMStreams/pypi.streamsx | streamsx/st.py | get_rest_api | def get_rest_api():
"""
Get the root URL for the IBM Streams REST API.
"""
assert _has_local_install
url=[]
ok = _run_st(['geturl', '--api'], lines=url)
if not ok:
raise ChildProcessError('streamtool geturl')
return url[0] | python | def get_rest_api():
"""
Get the root URL for the IBM Streams REST API.
"""
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",
"(",
")",
":",
"assert",
"_has_local_install",
"url",
"=",
"[",
"]",
"ok",
"=",
"_run_st",
"(",
"[",
"'geturl'",
",",
"'--api'",
"]",
",",
"lines",
"=",
"url",
")",
"if",
"not",
"ok",
":",
"raise",
"ChildProcessError",
"(",
"'str... | Get the root URL for the IBM Streams REST API. | [
"Get",
"the",
"root",
"URL",
"for",
"the",
"IBM",
"Streams",
"REST",
"API",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/st.py#L25-L35 | train | 44,046 |
IBMStreams/pypi.streamsx | streamsx/topology/dependency.py | _is_builtin_module | def _is_builtin_module(module):
"""Is builtin or part of standard library
"""
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):
return True
if not '.' in module.__name__:
return False
mn_top = module.__name__.split('.')[0]
return mn_top in _stdlib._STD_LIB_MODULES | python | def _is_builtin_module(module):
"""Is builtin or part of standard library
"""
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):
return True
if not '.' in module.__name__:
return False
mn_top = module.__name__.split('.')[0]
return mn_top in _stdlib._STD_LIB_MODULES | [
"def",
"_is_builtin_module",
"(",
"module",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"module",
",",
"'__file__'",
")",
")",
"or",
"module",
".",
"__name__",
"in",
"sys",
".",
"builtin_module_names",
":",
"return",
"True",
"if",
"module",
".",
"__name__"... | Is builtin or part of standard library | [
"Is",
"builtin",
"or",
"part",
"of",
"standard",
"library"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/dependency.py#L252-L267 | train | 44,047 |
IBMStreams/pypi.streamsx | streamsx/topology/dependency.py | _DependencyResolver._find_dependent_modules | def _find_dependent_modules(self, module):
"""
Return the set of dependent modules for used modules,
classes and routines.
"""
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_module(dms, ur[1])
return dms | python | def _find_dependent_modules(self, module):
"""
Return the set of dependent modules for used modules,
classes and routines.
"""
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_module(dms, ur[1])
return dms | [
"def",
"_find_dependent_modules",
"(",
"self",
",",
"module",
")",
":",
"dms",
"=",
"set",
"(",
")",
"for",
"um",
"in",
"inspect",
".",
"getmembers",
"(",
"module",
",",
"inspect",
".",
"ismodule",
")",
":",
"dms",
".",
"add",
"(",
"um",
"[",
"1",
... | Return the set of dependent modules for used modules,
classes and routines. | [
"Return",
"the",
"set",
"of",
"dependent",
"modules",
"for",
"used",
"modules",
"classes",
"and",
"routines",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/dependency.py#L35-L49 | train | 44,048 |
IBMStreams/pypi.streamsx | streamsx/topology/dependency.py | _DependencyResolver.add_dependencies | 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.
"""
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 is __main__, don't add it. Just add its dependencies.
if mn == "__main__":
self._processed_modules.add(module)
# add the module as a dependency
elif not self._add_dependency(module, mn):
_debug.debug("add_dependencies:not added:module=%s", mn)
return None
_debug.debug("add_dependencies:ADDED:module=%s", mn)
# recursively get the module's imports and add those as dependencies
for dm in self._find_dependent_modules(module):
_debug.debug("add_dependencies:adding dependent module %s for %s", dm, mn)
self.add_dependencies(dm) | python | 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.
"""
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 is __main__, don't add it. Just add its dependencies.
if mn == "__main__":
self._processed_modules.add(module)
# add the module as a dependency
elif not self._add_dependency(module, mn):
_debug.debug("add_dependencies:not added:module=%s", mn)
return None
_debug.debug("add_dependencies:ADDED:module=%s", mn)
# recursively get the module's imports and add those as dependencies
for dm in self._find_dependent_modules(module):
_debug.debug("add_dependencies:adding dependent module %s for %s", dm, mn)
self.add_dependencies(dm) | [
"def",
"add_dependencies",
"(",
"self",
",",
"module",
")",
":",
"if",
"module",
"in",
"self",
".",
"_processed_modules",
":",
"return",
"None",
"if",
"hasattr",
"(",
"module",
",",
"\"__name__\"",
")",
":",
"mn",
"=",
"module",
".",
"__name__",
"else",
... | Adds a module and its dependencies to the list of dependencies.
Top-level entry point for adding a module and its dependecies. | [
"Adds",
"a",
"module",
"and",
"its",
"dependencies",
"to",
"the",
"list",
"of",
"dependencies",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/dependency.py#L56-L87 | train | 44,049 |
IBMStreams/pypi.streamsx | streamsx/topology/dependency.py | _DependencyResolver._include_module | 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 to do a direct comparison. Instead, we want to exclude packages
which are either exactly "<package_name>", or start with "<package_name>".
"""
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 + '.'):
_debug.debug("_include_module:explicit pattern using __include_packages: module=%s pattern=%s", mn, \
include_package + '.')
return True
if mn in self.topology.exclude_packages:
_debug.debug("_include_module:explicit using __exclude_packages: module=%s", mn)
return False
if '.' in mn:
for exclude_package in self.topology.exclude_packages:
if mn.startswith(exclude_package + '.'):
_debug.debug("_include_module:explicit pattern using __exclude_packages: module=%s pattern=%s", mn, \
exclude_package + '.')
return False
_debug.debug("_include_module:including: module=%s", mn)
return True | python | 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 to do a direct comparison. Instead, we want to exclude packages
which are either exactly "<package_name>", or start with "<package_name>".
"""
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 + '.'):
_debug.debug("_include_module:explicit pattern using __include_packages: module=%s pattern=%s", mn, \
include_package + '.')
return True
if mn in self.topology.exclude_packages:
_debug.debug("_include_module:explicit using __exclude_packages: module=%s", mn)
return False
if '.' in mn:
for exclude_package in self.topology.exclude_packages:
if mn.startswith(exclude_package + '.'):
_debug.debug("_include_module:explicit pattern using __exclude_packages: module=%s pattern=%s", mn, \
exclude_package + '.')
return False
_debug.debug("_include_module:including: module=%s", mn)
return True | [
"def",
"_include_module",
"(",
"self",
",",
"module",
",",
"mn",
")",
":",
"if",
"mn",
"in",
"self",
".",
"topology",
".",
"include_packages",
":",
"_debug",
".",
"debug",
"(",
"\"_include_module:explicit using __include_packages: module=%s\"",
",",
"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 to do a direct comparison. Instead, we want to exclude packages
which are either exactly "<package_name>", or start with "<package_name>". | [
"See",
"if",
"a",
"module",
"should",
"be",
"included",
"or",
"excluded",
"based",
"upon",
"included_packages",
"and",
"excluded_packages",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/dependency.py#L103-L138 | train | 44,050 |
IBMStreams/pypi.streamsx | streamsx/topology/dependency.py | _DependencyResolver._add_dependency | 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.
"""
_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 False
if not self._include_module(module, mn):
#print ("ignoring dependencies for {0} {1}".format(module.__name__, module))
return False
package_name = _get_package_name(module)
top_package_name = module.__name__.split('.')[0]
if package_name and top_package_name in sys.modules:
# module is part of a package
# get the top-level package
top_package = sys.modules[top_package_name]
if "__path__" in top_package.__dict__:
# for regular packages, there is one top-level directory
# for namespace packages, there can be more than one.
# they will be merged in the bundle
seen_non_site_package = False
for top_package_path in reversed(list(top_package.__path__)):
top_package_path = os.path.abspath(top_package_path)
if 'site-packages' in top_package_path:
continue
seen_non_site_package = True
self._add_package(top_package_path)
if not seen_non_site_package:
_debug.debug("_add_dependency:site-packages path module=%s", mn)
return False
elif hasattr(top_package, '__file__'):
# package that is an individual python file with empty __path__
if 'site-packages' in top_package.__file__:
_debug.debug("_add_dependency:site-packages module=%s", mn)
return False
self._add_package(os.path.abspath(top_package.__file__))
elif hasattr(module, '__file__'):
# individual Python module
module_path = os.path.abspath(module.__file__)
if 'site-packages' in module_path:
_debug.debug("_add_dependency:site-packages module=%s", mn)
return False
self._modules.add(module_path)
self._processed_modules.add(module)
return True | python | 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.
"""
_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 False
if not self._include_module(module, mn):
#print ("ignoring dependencies for {0} {1}".format(module.__name__, module))
return False
package_name = _get_package_name(module)
top_package_name = module.__name__.split('.')[0]
if package_name and top_package_name in sys.modules:
# module is part of a package
# get the top-level package
top_package = sys.modules[top_package_name]
if "__path__" in top_package.__dict__:
# for regular packages, there is one top-level directory
# for namespace packages, there can be more than one.
# they will be merged in the bundle
seen_non_site_package = False
for top_package_path in reversed(list(top_package.__path__)):
top_package_path = os.path.abspath(top_package_path)
if 'site-packages' in top_package_path:
continue
seen_non_site_package = True
self._add_package(top_package_path)
if not seen_non_site_package:
_debug.debug("_add_dependency:site-packages path module=%s", mn)
return False
elif hasattr(top_package, '__file__'):
# package that is an individual python file with empty __path__
if 'site-packages' in top_package.__file__:
_debug.debug("_add_dependency:site-packages module=%s", mn)
return False
self._add_package(os.path.abspath(top_package.__file__))
elif hasattr(module, '__file__'):
# individual Python module
module_path = os.path.abspath(module.__file__)
if 'site-packages' in module_path:
_debug.debug("_add_dependency:site-packages module=%s", mn)
return False
self._modules.add(module_path)
self._processed_modules.add(module)
return True | [
"def",
"_add_dependency",
"(",
"self",
",",
"module",
",",
"mn",
")",
":",
"_debug",
".",
"debug",
"(",
"\"_add_dependency:module=%s\"",
",",
"mn",
")",
"if",
"_is_streamsx_module",
"(",
"module",
")",
":",
"_debug",
".",
"debug",
"(",
"\"_add_dependency:strea... | 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. | [
"Adds",
"a",
"module",
"to",
"the",
"list",
"of",
"dependencies",
"without",
"handling",
"the",
"modules",
"dependences",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/dependency.py#L140-L199 | train | 44,051 |
raphaelm/django-hierarkey | hierarkey/proxy.py | HierarkeyProxy.freeze | def freeze(self) -> dict:
"""
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults.
"""
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.get(key)
return settings | python | def freeze(self) -> dict:
"""
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults.
"""
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.get(key)
return settings | [
"def",
"freeze",
"(",
"self",
")",
"->",
"dict",
":",
"settings",
"=",
"{",
"}",
"for",
"key",
",",
"v",
"in",
"self",
".",
"_h",
".",
"defaults",
".",
"items",
"(",
")",
":",
"settings",
"[",
"key",
"]",
"=",
"self",
".",
"_unserialize",
"(",
... | Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults. | [
"Returns",
"a",
"dictionary",
"of",
"all",
"settings",
"set",
"for",
"this",
"object",
"including",
"any",
"values",
"of",
"its",
"parents",
"or",
"hardcoded",
"defaults",
"."
] | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/proxy.py#L72-L84 | train | 44,052 |
raphaelm/django-hierarkey | hierarkey/proxy.py | HierarkeyProxy.get | 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.
If the setting with the specified name does not exist on this object, any parent object
up to the global settings layer (if configured) will be queried. If still no value is
found, a default value set in ths source code will be returned if one exists.
If not, the value of the ``default`` argument of this method will be returned instead.
If you receive a ``File`` object, it will already be opened. You can specify the ``binary_file``
flag to indicate that it should be opened in binary mode.
"""
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_name).get(key, as_type=str)
if value is None and key in self._h.defaults:
value = self._h.defaults[key].value
if value is None and default is not None:
value = default
return self._unserialize(value, as_type, binary_file=binary_file) | python | 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.
If the setting with the specified name does not exist on this object, any parent object
up to the global settings layer (if configured) will be queried. If still no value is
found, a default value set in ths source code will be returned if one exists.
If not, the value of the ``default`` argument of this method will be returned instead.
If you receive a ``File`` object, it will already be opened. You can specify the ``binary_file``
flag to indicate that it should be opened in binary mode.
"""
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_name).get(key, as_type=str)
if value is None and key in self._h.defaults:
value = self._h.defaults[key].value
if value is None and default is not None:
value = default
return self._unserialize(value, as_type, binary_file=binary_file) | [
"def",
"get",
"(",
"self",
",",
"key",
":",
"str",
",",
"default",
"=",
"None",
",",
"as_type",
":",
"type",
"=",
"None",
",",
"binary_file",
"=",
"False",
")",
":",
"if",
"as_type",
"is",
"None",
"and",
"key",
"in",
"self",
".",
"_h",
".",
"defa... | 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.
If the setting with the specified name does not exist on this object, any parent object
up to the global settings layer (if configured) will be queried. If still no value is
found, a default value set in ths source code will be returned if one exists.
If not, the value of the ``default`` argument of this method will be returned instead.
If you receive a ``File`` object, it will already be opened. You can specify the ``binary_file``
flag to indicate that it should be opened in binary mode. | [
"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_... | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/proxy.py#L144-L173 | train | 44,053 |
raphaelm/django-hierarkey | hierarkey/proxy.py | HierarkeyProxy.set | 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.
"""
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() | python | 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.
"""
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",
":",
"wc",
"=",
"self",
".",
"_write_cache",
"(",
")",
"if",
"key",
"in",
"wc",
":",
"s",
"=",
"wc",
"[",
"key",
"]",
"else",
":",
"s",
"=",
"se... | 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. | [
"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"... | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/proxy.py#L191-L207 | train | 44,054 |
raphaelm/django-hierarkey | hierarkey/proxy.py | HierarkeyProxy.delete | 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.
"""
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() | python | 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.
"""
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",
":",
"if",
"key",
"in",
"self",
".",
"_write_cache",
"(",
")",
":",
"self",
".",
"_write_cache",
"(",
")",
"[",
"key",
"]",
".",
"delete",
"(",
")",
"del",
"self",
".",
"_... | 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. | [
"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",
"th... | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/proxy.py#L217-L231 | train | 44,055 |
IBMStreams/pypi.streamsx | streamsx/rest.py | _get_vcap_services | 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.
vcap_services (dict): Return the dict as is.
Returns:
dict: A dict representation of the VCAP Services information.
Raises:
ValueError:
* if `vcap_services` nor VCAP_SERVICES environment variable are specified.
* cannot parse `vcap_services` as a JSON string nor as a filename.
"""
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(vcap_services, dict):
return vcap_services
try:
# Otherwise, if it's a string, try to load it as json
vcap_services = json.loads(vcap_services)
except json.JSONDecodeError:
# If that doesn't work, attempt to open it as a file path to the json config.
try:
with open(vcap_services) as vcap_json_data:
vcap_services = json.load(vcap_json_data)
except:
raise ValueError("VCAP_SERVICES information is not JSON or a file containing JSON:", vcap_services)
return vcap_services | python | 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.
vcap_services (dict): Return the dict as is.
Returns:
dict: A dict representation of the VCAP Services information.
Raises:
ValueError:
* if `vcap_services` nor VCAP_SERVICES environment variable are specified.
* cannot parse `vcap_services` as a JSON string nor as a filename.
"""
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(vcap_services, dict):
return vcap_services
try:
# Otherwise, if it's a string, try to load it as json
vcap_services = json.loads(vcap_services)
except json.JSONDecodeError:
# If that doesn't work, attempt to open it as a file path to the json config.
try:
with open(vcap_services) as vcap_json_data:
vcap_services = json.load(vcap_json_data)
except:
raise ValueError("VCAP_SERVICES information is not JSON or a file containing JSON:", vcap_services)
return vcap_services | [
"def",
"_get_vcap_services",
"(",
"vcap_services",
"=",
"None",
")",
":",
"vcap_services",
"=",
"vcap_services",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'VCAP_SERVICES'",
")",
"if",
"not",
"vcap_services",
":",
"raise",
"ValueError",
"(",
"\"VCAP_SERVICES ... | 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.
vcap_services (dict): Return the dict as is.
Returns:
dict: A dict representation of the VCAP Services information.
Raises:
ValueError:
* if `vcap_services` nor VCAP_SERVICES environment variable are specified.
* cannot parse `vcap_services` as a JSON string nor as a filename. | [
"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"... | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest.py#L309-L342 | train | 44,056 |
IBMStreams/pypi.streamsx | streamsx/rest.py | _get_credentials | 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.
service_name (str): One of the service name stored in `vcap_services`
Returns:
dict: A dict representation of the credentials.
Raises:
ValueError: Cannot find `service_name` in `vcap_services`
"""
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 = service['credentials']
break
# If no corresponding service is found, error
if creds is None:
raise ValueError("Streaming Analytics service " + str(service_name) + " was not found in VCAP_SERVICES")
return creds | python | 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.
service_name (str): One of the service name stored in `vcap_services`
Returns:
dict: A dict representation of the credentials.
Raises:
ValueError: Cannot find `service_name` in `vcap_services`
"""
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 = service['credentials']
break
# If no corresponding service is found, error
if creds is None:
raise ValueError("Streaming Analytics service " + str(service_name) + " was not found in VCAP_SERVICES")
return creds | [
"def",
"_get_credentials",
"(",
"vcap_services",
",",
"service_name",
"=",
"None",
")",
":",
"service_name",
"=",
"service_name",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'STREAMING_ANALYTICS_SERVICE_NAME'",
",",
"None",
")",
"# Get the service corresponding to t... | 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.
service_name (str): One of the service name stored in `vcap_services`
Returns:
dict: A dict representation of the credentials.
Raises:
ValueError: Cannot find `service_name` in `vcap_services` | [
"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"... | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest.py#L345-L372 | train | 44,057 |
IBMStreams/pypi.streamsx | streamsx/rest.py | StreamsConnection.get_domains | def get_domains(self):
"""Retrieves available domains.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains
"""
# Domains are fixed and actually only one per REST api.
if self._domains is None:
self._domains = self._get_elements('domains', Domain)
return self._domains | python | def get_domains(self):
"""Retrieves available domains.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains
"""
# Domains are fixed and actually only one per REST api.
if self._domains is None:
self._domains = self._get_elements('domains', Domain)
return self._domains | [
"def",
"get_domains",
"(",
"self",
")",
":",
"# Domains are fixed and actually only one per REST api.",
"if",
"self",
".",
"_domains",
"is",
"None",
":",
"self",
".",
"_domains",
"=",
"self",
".",
"_get_elements",
"(",
"'domains'",
",",
"Domain",
")",
"return",
... | Retrieves available domains.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains | [
"Retrieves",
"available",
"domains",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest.py#L163-L172 | train | 44,058 |
IBMStreams/pypi.streamsx | streamsx/rest.py | StreamsConnection.get_resources | def get_resources(self):
"""Retrieves a list of all known Streams high-level REST resources.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources.
"""
json_resources = self.rest_client.make_request(self.resource_url)['resources']
return [RestResource(resource, self.rest_client) for resource in json_resources] | python | def get_resources(self):
"""Retrieves a list of all known Streams high-level REST resources.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources.
"""
json_resources = self.rest_client.make_request(self.resource_url)['resources']
return [RestResource(resource, self.rest_client) for resource in json_resources] | [
"def",
"get_resources",
"(",
"self",
")",
":",
"json_resources",
"=",
"self",
".",
"rest_client",
".",
"make_request",
"(",
"self",
".",
"resource_url",
")",
"[",
"'resources'",
"]",
"return",
"[",
"RestResource",
"(",
"resource",
",",
"self",
".",
"rest_cli... | Retrieves a list of all known Streams high-level REST resources.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources. | [
"Retrieves",
"a",
"list",
"of",
"all",
"known",
"Streams",
"high",
"-",
"level",
"REST",
"resources",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest.py#L218-L225 | train | 44,059 |
IBMStreams/pypi.streamsx | streamsx/rest.py | StreamingAnalyticsConnection.of_definition | def of_definition(service_def):
"""Create a connection to a Streaming Analytics service.
The single service is defined by `service_def` which can be one of
* The `service credentials` copied from the `Service credentials` page of the service console (not the Streams console). Credentials are provided in JSON format. They contain such as the API key and secret, as well as connection information for the service.
* A JSON object (`dict`) of the form: ``{ "type": "streaming-analytics", "name": "service name", "credentials": {...} }`` with the `service credentials` as the value of the ``credentials`` key.
Args:
service_def(dict): Definition of the service to connect to.
Returns:
StreamingAnalyticsConnection: Connection to defined service.
"""
vcap_services = streamsx.topology.context._vcap_from_service_definition(service_def)
service_name = streamsx.topology.context._name_from_service_definition(service_def)
return StreamingAnalyticsConnection(vcap_services, service_name) | python | def of_definition(service_def):
"""Create a connection to a Streaming Analytics service.
The single service is defined by `service_def` which can be one of
* The `service credentials` copied from the `Service credentials` page of the service console (not the Streams console). Credentials are provided in JSON format. They contain such as the API key and secret, as well as connection information for the service.
* A JSON object (`dict`) of the form: ``{ "type": "streaming-analytics", "name": "service name", "credentials": {...} }`` with the `service credentials` as the value of the ``credentials`` key.
Args:
service_def(dict): Definition of the service to connect to.
Returns:
StreamingAnalyticsConnection: Connection to defined service.
"""
vcap_services = streamsx.topology.context._vcap_from_service_definition(service_def)
service_name = streamsx.topology.context._name_from_service_definition(service_def)
return StreamingAnalyticsConnection(vcap_services, service_name) | [
"def",
"of_definition",
"(",
"service_def",
")",
":",
"vcap_services",
"=",
"streamsx",
".",
"topology",
".",
"context",
".",
"_vcap_from_service_definition",
"(",
"service_def",
")",
"service_name",
"=",
"streamsx",
".",
"topology",
".",
"context",
".",
"_name_fr... | Create a connection to a Streaming Analytics service.
The single service is defined by `service_def` which can be one of
* The `service credentials` copied from the `Service credentials` page of the service console (not the Streams console). Credentials are provided in JSON format. They contain such as the API key and secret, as well as connection information for the service.
* A JSON object (`dict`) of the form: ``{ "type": "streaming-analytics", "name": "service name", "credentials": {...} }`` with the `service credentials` as the value of the ``credentials`` key.
Args:
service_def(dict): Definition of the service to connect to.
Returns:
StreamingAnalyticsConnection: Connection to defined service. | [
"Create",
"a",
"connection",
"to",
"a",
"Streaming",
"Analytics",
"service",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest.py#L271-L287 | train | 44,060 |
orcasgit/django-tastypie-oauth | tastypie_oauth/authentication.py | OAuth20Authentication.is_authenticated | def is_authenticated(self, request, **kwargs):
"""
Verify 2-legged oauth request. Parameters accepted as
values in the "Authorization" header, as a GET request parameter,
or in a POST body.
"""
log.info("OAuth20Authentication")
try:
key = request.GET.get('oauth_consumer_key')
if not key:
for header in ['Authorization', 'HTTP_AUTHORIZATION']:
auth_header_value = request.META.get(header)
if auth_header_value:
key = auth_header_value.split(' ', 1)[1]
break
if not key and request.method == 'POST':
if request.META.get('CONTENT_TYPE') == 'application/json':
decoded_body = request.body.decode('utf8')
key = json.loads(decoded_body)['oauth_consumer_key']
if not key:
log.info('OAuth20Authentication. No consumer_key found.')
return None
"""
If verify_access_token() does not pass, it will raise an error
"""
token = self.verify_access_token(key, request, **kwargs)
# If OAuth authentication is successful, set the request user to
# the token user for authorization
request.user = token.user
# If OAuth authentication is successful, set oauth_consumer_key on
# request in case we need it later
request.META['oauth_consumer_key'] = key
return True
except KeyError:
log.exception("Error in OAuth20Authentication.")
request.user = AnonymousUser()
return False
except Exception:
log.exception("Error in OAuth20Authentication.")
return False | python | def is_authenticated(self, request, **kwargs):
"""
Verify 2-legged oauth request. Parameters accepted as
values in the "Authorization" header, as a GET request parameter,
or in a POST body.
"""
log.info("OAuth20Authentication")
try:
key = request.GET.get('oauth_consumer_key')
if not key:
for header in ['Authorization', 'HTTP_AUTHORIZATION']:
auth_header_value = request.META.get(header)
if auth_header_value:
key = auth_header_value.split(' ', 1)[1]
break
if not key and request.method == 'POST':
if request.META.get('CONTENT_TYPE') == 'application/json':
decoded_body = request.body.decode('utf8')
key = json.loads(decoded_body)['oauth_consumer_key']
if not key:
log.info('OAuth20Authentication. No consumer_key found.')
return None
"""
If verify_access_token() does not pass, it will raise an error
"""
token = self.verify_access_token(key, request, **kwargs)
# If OAuth authentication is successful, set the request user to
# the token user for authorization
request.user = token.user
# If OAuth authentication is successful, set oauth_consumer_key on
# request in case we need it later
request.META['oauth_consumer_key'] = key
return True
except KeyError:
log.exception("Error in OAuth20Authentication.")
request.user = AnonymousUser()
return False
except Exception:
log.exception("Error in OAuth20Authentication.")
return False | [
"def",
"is_authenticated",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"\"OAuth20Authentication\"",
")",
"try",
":",
"key",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'oauth_consumer_key'",
")",
"if",
"not"... | Verify 2-legged oauth request. Parameters accepted as
values in the "Authorization" header, as a GET request parameter,
or in a POST body. | [
"Verify",
"2",
"-",
"legged",
"oauth",
"request",
".",
"Parameters",
"accepted",
"as",
"values",
"in",
"the",
"Authorization",
"header",
"as",
"a",
"GET",
"request",
"parameter",
"or",
"in",
"a",
"POST",
"body",
"."
] | 01c40de7b86ae3c6cc9e9463ec9bcecbb22b897e | https://github.com/orcasgit/django-tastypie-oauth/blob/01c40de7b86ae3c6cc9e9463ec9bcecbb22b897e/tastypie_oauth/authentication.py#L39-L80 | train | 44,061 |
orcasgit/django-tastypie-oauth | tastypie_oauth/authentication.py | OAuth2ScopedAuthentication.check_scope | def check_scope(self, token, request):
http_method = request.method
if not hasattr(self, http_method):
raise OAuthError("HTTP method is not recognized")
required_scopes = getattr(self, http_method)
# a None scope means always allowed
if required_scopes is None:
return True
"""
The required scope is either a string or an iterable. If string,
check if it is allowed for our access token otherwise, iterate through
the required_scopes to see which scopes are allowed
"""
# for non iterable types
if isinstance(required_scopes, six.string_types):
if token.allow_scopes(required_scopes.split()):
return [required_scopes]
return []
allowed_scopes = []
try:
for scope in required_scopes:
if token.allow_scopes(scope.split()):
allowed_scopes.append(scope)
except:
raise Exception('Invalid required scope values')
else:
return allowed_scopes | python | def check_scope(self, token, request):
http_method = request.method
if not hasattr(self, http_method):
raise OAuthError("HTTP method is not recognized")
required_scopes = getattr(self, http_method)
# a None scope means always allowed
if required_scopes is None:
return True
"""
The required scope is either a string or an iterable. If string,
check if it is allowed for our access token otherwise, iterate through
the required_scopes to see which scopes are allowed
"""
# for non iterable types
if isinstance(required_scopes, six.string_types):
if token.allow_scopes(required_scopes.split()):
return [required_scopes]
return []
allowed_scopes = []
try:
for scope in required_scopes:
if token.allow_scopes(scope.split()):
allowed_scopes.append(scope)
except:
raise Exception('Invalid required scope values')
else:
return allowed_scopes | [
"def",
"check_scope",
"(",
"self",
",",
"token",
",",
"request",
")",
":",
"http_method",
"=",
"request",
".",
"method",
"if",
"not",
"hasattr",
"(",
"self",
",",
"http_method",
")",
":",
"raise",
"OAuthError",
"(",
"\"HTTP method is not recognized\"",
")",
... | The required scope is either a string or an iterable. If string,
check if it is allowed for our access token otherwise, iterate through
the required_scopes to see which scopes are allowed | [
"The",
"required",
"scope",
"is",
"either",
"a",
"string",
"or",
"an",
"iterable",
".",
"If",
"string",
"check",
"if",
"it",
"is",
"allowed",
"for",
"our",
"access",
"token",
"otherwise",
"iterate",
"through",
"the",
"required_scopes",
"to",
"see",
"which",
... | 01c40de7b86ae3c6cc9e9463ec9bcecbb22b897e | https://github.com/orcasgit/django-tastypie-oauth/blob/01c40de7b86ae3c6cc9e9463ec9bcecbb22b897e/tastypie_oauth/authentication.py#L140-L166 | train | 44,062 |
feluxe/sty | sty/primitive.py | Base.as_dict | def as_dict(self) -> Dict[str, str]:
"""
Export color register as dict.
"""
items: Dict[str, str] = {}
for k, v in self.items():
if type(v) is str:
items.update({k: v})
return items | python | def as_dict(self) -> Dict[str, str]:
"""
Export color register as dict.
"""
items: Dict[str, str] = {}
for k, v in self.items():
if type(v) is str:
items.update({k: v})
return items | [
"def",
"as_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"items",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"v",
... | Export color register as dict. | [
"Export",
"color",
"register",
"as",
"dict",
"."
] | 60af9c1c59556a6f285d3d0ba4b8e125f8adc107 | https://github.com/feluxe/sty/blob/60af9c1c59556a6f285d3d0ba4b8e125f8adc107/sty/primitive.py#L170-L181 | train | 44,063 |
feluxe/sty | sty/primitive.py | Base.as_namedtuple | def as_namedtuple(self):
"""
Export color register as namedtuple.
"""
d = self.as_dict()
return namedtuple('ColorRegister', d.keys())(*d.values()) | python | def as_namedtuple(self):
"""
Export color register as namedtuple.
"""
d = self.as_dict()
return namedtuple('ColorRegister', d.keys())(*d.values()) | [
"def",
"as_namedtuple",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"as_dict",
"(",
")",
"return",
"namedtuple",
"(",
"'ColorRegister'",
",",
"d",
".",
"keys",
"(",
")",
")",
"(",
"*",
"d",
".",
"values",
"(",
")",
")"
] | Export color register as namedtuple. | [
"Export",
"color",
"register",
"as",
"namedtuple",
"."
] | 60af9c1c59556a6f285d3d0ba4b8e125f8adc107 | https://github.com/feluxe/sty/blob/60af9c1c59556a6f285d3d0ba4b8e125f8adc107/sty/primitive.py#L183-L188 | train | 44,064 |
tomduck/pandoc-fignos | pandoc_fignos.py | _extract_attrs | def _extract_attrs(x, n):
"""Extracts attributes for an image. n is the index where the
attributes begin. Extracted elements are deleted from the element
list x. Attrs are returned in pandoc format.
"""
try:
return extract_attrs(x, n)
except (ValueError, IndexError):
if PANDOCVERSION < '1.16':
# Look for attributes attached to the image path, as occurs with
# image references for pandoc < 1.16 (pandoc-fignos Issue #14).
# See http://pandoc.org/MANUAL.html#images for the syntax.
# Note: This code does not handle the "optional title" for
# image references (search for link_attributes in pandoc's docs).
assert x[n-1]['t'] == 'Image'
image = x[n-1]
s = image['c'][-1][0]
if '%20%7B' in s:
path = s[:s.index('%20%7B')]
attrs = unquote(s[s.index('%7B'):])
image['c'][-1][0] = path # Remove attr string from the path
return PandocAttributes(attrs.strip(), 'markdown').to_pandoc()
raise | python | def _extract_attrs(x, n):
"""Extracts attributes for an image. n is the index where the
attributes begin. Extracted elements are deleted from the element
list x. Attrs are returned in pandoc format.
"""
try:
return extract_attrs(x, n)
except (ValueError, IndexError):
if PANDOCVERSION < '1.16':
# Look for attributes attached to the image path, as occurs with
# image references for pandoc < 1.16 (pandoc-fignos Issue #14).
# See http://pandoc.org/MANUAL.html#images for the syntax.
# Note: This code does not handle the "optional title" for
# image references (search for link_attributes in pandoc's docs).
assert x[n-1]['t'] == 'Image'
image = x[n-1]
s = image['c'][-1][0]
if '%20%7B' in s:
path = s[:s.index('%20%7B')]
attrs = unquote(s[s.index('%7B'):])
image['c'][-1][0] = path # Remove attr string from the path
return PandocAttributes(attrs.strip(), 'markdown').to_pandoc()
raise | [
"def",
"_extract_attrs",
"(",
"x",
",",
"n",
")",
":",
"try",
":",
"return",
"extract_attrs",
"(",
"x",
",",
"n",
")",
"except",
"(",
"ValueError",
",",
"IndexError",
")",
":",
"if",
"PANDOCVERSION",
"<",
"'1.16'",
":",
"# Look for attributes attached to the... | Extracts attributes for an image. n is the index where the
attributes begin. Extracted elements are deleted from the element
list x. Attrs are returned in pandoc format. | [
"Extracts",
"attributes",
"for",
"an",
"image",
".",
"n",
"is",
"the",
"index",
"where",
"the",
"attributes",
"begin",
".",
"Extracted",
"elements",
"are",
"deleted",
"from",
"the",
"element",
"list",
"x",
".",
"Attrs",
"are",
"returned",
"in",
"pandoc",
"... | 44776d885b8101d9d6aeb6845b17ad1625e88e6f | https://github.com/tomduck/pandoc-fignos/blob/44776d885b8101d9d6aeb6845b17ad1625e88e6f/pandoc_fignos.py#L93-L117 | train | 44,065 |
tomduck/pandoc-fignos | pandoc_fignos.py | process_figures | def process_figures(key, value, fmt, meta): # pylint: disable=unused-argument
"""Processes the figures."""
global has_unnumbered_figures # pylint: disable=global-statement
# Process figures wrapped in Para elements
if key == 'Para' and len(value) == 1 and \
value[0]['t'] == 'Image' and value[0]['c'][-1][1].startswith('fig:'):
# Inspect the image
if len(value[0]['c']) == 2: # Unattributed, bail out
has_unnumbered_figures = True
if fmt == 'latex':
return [RawBlock('tex', r'\begin{no-prefix-figure-caption}'),
Para(value),
RawBlock('tex', r'\end{no-prefix-figure-caption}')]
return None
# Process the figure
fig = _process_figure(value, fmt)
# Context-dependent output
attrs = fig['attrs']
if fig['is_unnumbered']: # Unnumbered is also unreferenceable
if fmt == 'latex':
return [
RawBlock('tex', r'\begin{no-prefix-figure-caption}'),
Para(value),
RawBlock('tex', r'\end{no-prefix-figure-caption}')]
elif fmt in ['latex', 'beamer']:
key = attrs[0]
if PANDOCVERSION >= '1.17':
# Remove id from the image attributes. It is incorrectly
# handled by pandoc's TeX writer for these versions.
if LABEL_PATTERN.match(attrs[0]):
attrs[0] = ''
if fig['is_tagged']: # Code in the tags
tex = '\n'.join([r'\let\oldthefigure=\thefigure',
r'\renewcommand\thefigure{%s}'%\
references[key]])
pre = RawBlock('tex', tex)
tex = '\n'.join([r'\let\thefigure=\oldthefigure',
r'\addtocounter{figure}{-1}'])
post = RawBlock('tex', tex)
return [pre, Para(value), post]
elif fig['is_unreferenceable']:
attrs[0] = '' # The label isn't needed any further
elif PANDOCVERSION < '1.16' and fmt in ('html', 'html5') \
and LABEL_PATTERN.match(attrs[0]):
# Insert anchor
anchor = RawBlock('html', '<a name="%s"></a>'%attrs[0])
return [anchor, Para(value)]
elif fmt == 'docx':
# As per http://officeopenxml.com/WPhyperlink.php
bookmarkstart = \
RawBlock('openxml',
'<w:bookmarkStart w:id="0" w:name="%s"/>'
%attrs[0])
bookmarkend = \
RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>')
return [bookmarkstart, Para(value), bookmarkend]
return None | python | def process_figures(key, value, fmt, meta): # pylint: disable=unused-argument
"""Processes the figures."""
global has_unnumbered_figures # pylint: disable=global-statement
# Process figures wrapped in Para elements
if key == 'Para' and len(value) == 1 and \
value[0]['t'] == 'Image' and value[0]['c'][-1][1].startswith('fig:'):
# Inspect the image
if len(value[0]['c']) == 2: # Unattributed, bail out
has_unnumbered_figures = True
if fmt == 'latex':
return [RawBlock('tex', r'\begin{no-prefix-figure-caption}'),
Para(value),
RawBlock('tex', r'\end{no-prefix-figure-caption}')]
return None
# Process the figure
fig = _process_figure(value, fmt)
# Context-dependent output
attrs = fig['attrs']
if fig['is_unnumbered']: # Unnumbered is also unreferenceable
if fmt == 'latex':
return [
RawBlock('tex', r'\begin{no-prefix-figure-caption}'),
Para(value),
RawBlock('tex', r'\end{no-prefix-figure-caption}')]
elif fmt in ['latex', 'beamer']:
key = attrs[0]
if PANDOCVERSION >= '1.17':
# Remove id from the image attributes. It is incorrectly
# handled by pandoc's TeX writer for these versions.
if LABEL_PATTERN.match(attrs[0]):
attrs[0] = ''
if fig['is_tagged']: # Code in the tags
tex = '\n'.join([r'\let\oldthefigure=\thefigure',
r'\renewcommand\thefigure{%s}'%\
references[key]])
pre = RawBlock('tex', tex)
tex = '\n'.join([r'\let\thefigure=\oldthefigure',
r'\addtocounter{figure}{-1}'])
post = RawBlock('tex', tex)
return [pre, Para(value), post]
elif fig['is_unreferenceable']:
attrs[0] = '' # The label isn't needed any further
elif PANDOCVERSION < '1.16' and fmt in ('html', 'html5') \
and LABEL_PATTERN.match(attrs[0]):
# Insert anchor
anchor = RawBlock('html', '<a name="%s"></a>'%attrs[0])
return [anchor, Para(value)]
elif fmt == 'docx':
# As per http://officeopenxml.com/WPhyperlink.php
bookmarkstart = \
RawBlock('openxml',
'<w:bookmarkStart w:id="0" w:name="%s"/>'
%attrs[0])
bookmarkend = \
RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>')
return [bookmarkstart, Para(value), bookmarkend]
return None | [
"def",
"process_figures",
"(",
"key",
",",
"value",
",",
"fmt",
",",
"meta",
")",
":",
"# pylint: disable=unused-argument",
"global",
"has_unnumbered_figures",
"# pylint: disable=global-statement",
"# Process figures wrapped in Para elements",
"if",
"key",
"==",
"'Para'",
"... | Processes the figures. | [
"Processes",
"the",
"figures",
"."
] | 44776d885b8101d9d6aeb6845b17ad1625e88e6f | https://github.com/tomduck/pandoc-fignos/blob/44776d885b8101d9d6aeb6845b17ad1625e88e6f/pandoc_fignos.py#L204-L266 | train | 44,066 |
samluescher/django-media-tree | media_tree/admin/filenode_admin.py | FileNodeAdmin.i18n_javascript | def i18n_javascript(self, request):
"""
Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster.
"""
if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages=['media_tree']) | python | def i18n_javascript(self, request):
"""
Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster.
"""
if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages=['media_tree']) | [
"def",
"i18n_javascript",
"(",
"self",
",",
"request",
")",
":",
"if",
"settings",
".",
"USE_I18N",
":",
"from",
"django",
".",
"views",
".",
"i18n",
"import",
"javascript_catalog",
"else",
":",
"from",
"django",
".",
"views",
".",
"i18n",
"import",
"null_... | Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster. | [
"Displays",
"the",
"i18n",
"JavaScript",
"that",
"the",
"Django",
"admin",
"requires",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/filenode_admin.py#L364-L375 | train | 44,067 |
samluescher/django-media-tree | media_tree/admin/change_list.py | MediaTreeChangeList.get_results | def get_results(self, request):
"""
Temporarily decreases the `level` attribute of all search results in
order to prevent indendation when displaying them.
"""
super(MediaTreeChangeList, self).get_results(request)
try:
reduce_levels = abs(int(get_request_attr(request, 'reduce_levels', 0)))
except TypeError:
reduce_levels = 0
is_filtered = self.is_filtered(request)
if is_filtered or reduce_levels:
for item in self.result_list:
item.prevent_save()
item.actual_level = item.level
if is_filtered:
item.reduce_levels = item.level
item.level = 0
else:
item.reduce_levels = reduce_levels
item.level = max(0, item.level - reduce_levels) | python | def get_results(self, request):
"""
Temporarily decreases the `level` attribute of all search results in
order to prevent indendation when displaying them.
"""
super(MediaTreeChangeList, self).get_results(request)
try:
reduce_levels = abs(int(get_request_attr(request, 'reduce_levels', 0)))
except TypeError:
reduce_levels = 0
is_filtered = self.is_filtered(request)
if is_filtered or reduce_levels:
for item in self.result_list:
item.prevent_save()
item.actual_level = item.level
if is_filtered:
item.reduce_levels = item.level
item.level = 0
else:
item.reduce_levels = reduce_levels
item.level = max(0, item.level - reduce_levels) | [
"def",
"get_results",
"(",
"self",
",",
"request",
")",
":",
"super",
"(",
"MediaTreeChangeList",
",",
"self",
")",
".",
"get_results",
"(",
"request",
")",
"try",
":",
"reduce_levels",
"=",
"abs",
"(",
"int",
"(",
"get_request_attr",
"(",
"request",
",",
... | Temporarily decreases the `level` attribute of all search results in
order to prevent indendation when displaying them. | [
"Temporarily",
"decreases",
"the",
"level",
"attribute",
"of",
"all",
"search",
"results",
"in",
"order",
"to",
"prevent",
"indendation",
"when",
"displaying",
"them",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/change_list.py#L57-L77 | train | 44,068 |
samluescher/django-media-tree | media_tree/media_backends/__init__.py | get_media_backend | def get_media_backend(fail_silently=True, handles_media_types=None,
handles_file_extensions=None, supports_thumbnails=None):
"""
Returns the MediaBackend subclass that is configured for use with
media_tree.
"""
backends = app_settings.MEDIA_TREE_MEDIA_BACKENDS
if not len(backends):
if not fail_silently:
raise ImproperlyConfigured('There is no media backend configured.' \
+ ' Please define `MEDIA_TREE_MEDIA_BACKENDS` in your settings.')
else:
return False
for path in backends:
# Traverse backends until there is one supporting what's requested:
backend = get_module_attr(path)
if (not handles_media_types or backend.handles_media_types(handles_media_types)) \
and (not handles_file_extensions or backend.handles_file_extensions(handles_file_extensions)) \
and (not supports_thumbnails or backend.supports_thumbnails()):
return backend
if not fail_silently:
raise ImproperlyConfigured('There is no media backend configured to handle' \
' the specified file types.')
return False | python | def get_media_backend(fail_silently=True, handles_media_types=None,
handles_file_extensions=None, supports_thumbnails=None):
"""
Returns the MediaBackend subclass that is configured for use with
media_tree.
"""
backends = app_settings.MEDIA_TREE_MEDIA_BACKENDS
if not len(backends):
if not fail_silently:
raise ImproperlyConfigured('There is no media backend configured.' \
+ ' Please define `MEDIA_TREE_MEDIA_BACKENDS` in your settings.')
else:
return False
for path in backends:
# Traverse backends until there is one supporting what's requested:
backend = get_module_attr(path)
if (not handles_media_types or backend.handles_media_types(handles_media_types)) \
and (not handles_file_extensions or backend.handles_file_extensions(handles_file_extensions)) \
and (not supports_thumbnails or backend.supports_thumbnails()):
return backend
if not fail_silently:
raise ImproperlyConfigured('There is no media backend configured to handle' \
' the specified file types.')
return False | [
"def",
"get_media_backend",
"(",
"fail_silently",
"=",
"True",
",",
"handles_media_types",
"=",
"None",
",",
"handles_file_extensions",
"=",
"None",
",",
"supports_thumbnails",
"=",
"None",
")",
":",
"backends",
"=",
"app_settings",
".",
"MEDIA_TREE_MEDIA_BACKENDS",
... | Returns the MediaBackend subclass that is configured for use with
media_tree. | [
"Returns",
"the",
"MediaBackend",
"subclass",
"that",
"is",
"configured",
"for",
"use",
"with",
"media_tree",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/media_backends/__init__.py#L11-L36 | train | 44,069 |
samluescher/django-media-tree | media_tree/templatetags/media_tree_thumbnail.py | thumbnail_size | def thumbnail_size(parser, token):
"""Returns a pre-configured thumbnail size, or assigns it to a context
variable.
Basic tag syntax::
{% thumbnail_size [size_name] [as var_name] %}
The ``size`` parameter can be any of the size names configured using the
setting ``MEDIA_TREE_THUMBNAIL_SIZES``. If omitted, the default size will
be returned.
If the ``as var_name`` clause is present, the size will be assigned to
the respective context variable instead of being returned.
You can use this template tag in conjunction with :func:`thumbnail` in order
to use pre-configured thumbnail sizes in your templates.
For example::
{% thumbnail_size "large" as large_size %}
{% thumbnail some_file large_size as large_thumb %}
<img src="{{ large_thumb.url }} width="{{ large_thumb.width }} ... />
"""
args = token.split_contents()
tag = args.pop(0)
if len(args) >= 2 and args[-2] == 'as':
context_name = args[-1]
args = args[:-2]
else:
context_name = None
if len(args) > 1:
raise template.TemplateSyntaxError("Invalid syntax. Expected "
"'{%% %s [\"size_name\"] [as context_var] %%}'" % tag)
elif len(args) == 1:
size_name = args[0]
else:
size_name = None
return ThumbnailSizeNode(size_name=size_name, context_name=context_name) | python | def thumbnail_size(parser, token):
"""Returns a pre-configured thumbnail size, or assigns it to a context
variable.
Basic tag syntax::
{% thumbnail_size [size_name] [as var_name] %}
The ``size`` parameter can be any of the size names configured using the
setting ``MEDIA_TREE_THUMBNAIL_SIZES``. If omitted, the default size will
be returned.
If the ``as var_name`` clause is present, the size will be assigned to
the respective context variable instead of being returned.
You can use this template tag in conjunction with :func:`thumbnail` in order
to use pre-configured thumbnail sizes in your templates.
For example::
{% thumbnail_size "large" as large_size %}
{% thumbnail some_file large_size as large_thumb %}
<img src="{{ large_thumb.url }} width="{{ large_thumb.width }} ... />
"""
args = token.split_contents()
tag = args.pop(0)
if len(args) >= 2 and args[-2] == 'as':
context_name = args[-1]
args = args[:-2]
else:
context_name = None
if len(args) > 1:
raise template.TemplateSyntaxError("Invalid syntax. Expected "
"'{%% %s [\"size_name\"] [as context_var] %%}'" % tag)
elif len(args) == 1:
size_name = args[0]
else:
size_name = None
return ThumbnailSizeNode(size_name=size_name, context_name=context_name) | [
"def",
"thumbnail_size",
"(",
"parser",
",",
"token",
")",
":",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"tag",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"if",
"len",
"(",
"args",
")",
">=",
"2",
"and",
"args",
"[",
"-",
"2",
"]",
"... | Returns a pre-configured thumbnail size, or assigns it to a context
variable.
Basic tag syntax::
{% thumbnail_size [size_name] [as var_name] %}
The ``size`` parameter can be any of the size names configured using the
setting ``MEDIA_TREE_THUMBNAIL_SIZES``. If omitted, the default size will
be returned.
If the ``as var_name`` clause is present, the size will be assigned to
the respective context variable instead of being returned.
You can use this template tag in conjunction with :func:`thumbnail` in order
to use pre-configured thumbnail sizes in your templates.
For example::
{% thumbnail_size "large" as large_size %}
{% thumbnail some_file large_size as large_thumb %}
<img src="{{ large_thumb.url }} width="{{ large_thumb.width }} ... /> | [
"Returns",
"a",
"pre",
"-",
"configured",
"thumbnail",
"size",
"or",
"assigns",
"it",
"to",
"a",
"context",
"variable",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/templatetags/media_tree_thumbnail.py#L63-L105 | train | 44,070 |
analyzere/analyzere-python | analyzere/utils.py | file_length | def file_length(file_obj):
"""
Returns the length in bytes of a given file object.
Necessary because os.fstat only works on real files and not file-like
objects. This works on more types of streams, primarily StringIO.
"""
file_obj.seek(0, 2)
length = file_obj.tell()
file_obj.seek(0)
return length | python | def file_length(file_obj):
"""
Returns the length in bytes of a given file object.
Necessary because os.fstat only works on real files and not file-like
objects. This works on more types of streams, primarily StringIO.
"""
file_obj.seek(0, 2)
length = file_obj.tell()
file_obj.seek(0)
return length | [
"def",
"file_length",
"(",
"file_obj",
")",
":",
"file_obj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"length",
"=",
"file_obj",
".",
"tell",
"(",
")",
"file_obj",
".",
"seek",
"(",
"0",
")",
"return",
"length"
] | Returns the length in bytes of a given file object.
Necessary because os.fstat only works on real files and not file-like
objects. This works on more types of streams, primarily StringIO. | [
"Returns",
"the",
"length",
"in",
"bytes",
"of",
"a",
"given",
"file",
"object",
".",
"Necessary",
"because",
"os",
".",
"fstat",
"only",
"works",
"on",
"real",
"files",
"and",
"not",
"file",
"-",
"like",
"objects",
".",
"This",
"works",
"on",
"more",
... | 0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f | https://github.com/analyzere/analyzere-python/blob/0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f/analyzere/utils.py#L55-L64 | train | 44,071 |
analyzere/analyzere-python | analyzere/utils.py | parse_href | def parse_href(href):
"""Parses an Analyze Re href into collection name and ID"""
url = urlparse(href)
path = url.path.split('/')
collection_name = path[1]
id_ = path[2]
return collection_name, id_ | python | def parse_href(href):
"""Parses an Analyze Re href into collection name and ID"""
url = urlparse(href)
path = url.path.split('/')
collection_name = path[1]
id_ = path[2]
return collection_name, id_ | [
"def",
"parse_href",
"(",
"href",
")",
":",
"url",
"=",
"urlparse",
"(",
"href",
")",
"path",
"=",
"url",
".",
"path",
".",
"split",
"(",
"'/'",
")",
"collection_name",
"=",
"path",
"[",
"1",
"]",
"id_",
"=",
"path",
"[",
"2",
"]",
"return",
"col... | Parses an Analyze Re href into collection name and ID | [
"Parses",
"an",
"Analyze",
"Re",
"href",
"into",
"collection",
"name",
"and",
"ID"
] | 0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f | https://github.com/analyzere/analyzere-python/blob/0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f/analyzere/utils.py#L78-L84 | train | 44,072 |
analyzere/analyzere-python | analyzere/utils.py | vectorize | def vectorize(values):
"""
Takes a value or list of values and returns a single result, joined by ","
if necessary.
"""
if isinstance(values, list):
return ','.join(str(v) for v in values)
return values | python | def vectorize(values):
"""
Takes a value or list of values and returns a single result, joined by ","
if necessary.
"""
if isinstance(values, list):
return ','.join(str(v) for v in values)
return values | [
"def",
"vectorize",
"(",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"return",
"','",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
"return",
"values"
] | Takes a value or list of values and returns a single result, joined by ","
if necessary. | [
"Takes",
"a",
"value",
"or",
"list",
"of",
"values",
"and",
"returns",
"a",
"single",
"result",
"joined",
"by",
"if",
"necessary",
"."
] | 0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f | https://github.com/analyzere/analyzere-python/blob/0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f/analyzere/utils.py#L87-L94 | train | 44,073 |
analyzere/analyzere-python | analyzere/utils.py | vectorize_range | def vectorize_range(values):
"""
This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_'
"""
if isinstance(values, tuple):
return '_'.join(str(i) for i in values)
if isinstance(values, list):
if not all([isinstance(item, tuple) for item in values]):
raise TypeError('Items in the list must be tuples')
return ','.join('_'.join(str(i) for i in v) for v in values)
return str(values) | python | def vectorize_range(values):
"""
This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_'
"""
if isinstance(values, tuple):
return '_'.join(str(i) for i in values)
if isinstance(values, list):
if not all([isinstance(item, tuple) for item in values]):
raise TypeError('Items in the list must be tuples')
return ','.join('_'.join(str(i) for i in v) for v in values)
return str(values) | [
"def",
"vectorize_range",
"(",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"tuple",
")",
":",
"return",
"'_'",
".",
"join",
"(",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"values",
")",
"if",
"isinstance",
"(",
"values",
",",
"list",
... | This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_' | [
"This",
"function",
"is",
"for",
"url",
"encoding",
".",
"Takes",
"a",
"value",
"or",
"a",
"tuple",
"or",
"list",
"of",
"tuples",
"and",
"returns",
"a",
"single",
"result",
"tuples",
"are",
"joined",
"by",
"if",
"necessary",
"elements",
"in",
"tuple",
"a... | 0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f | https://github.com/analyzere/analyzere-python/blob/0593d5b7b69c4df6d6dbc80387cc6ff5dc5f4e8f/analyzere/utils.py#L97-L109 | train | 44,074 |
samluescher/django-media-tree | media_tree/admin/actions/maintenance_actions.py | delete_orphaned_files | def delete_orphaned_files(modeladmin, request, queryset=None):
"""
Deletes orphaned files, i.e. media files existing in storage that are not in the database.
"""
execute = request.POST.get('execute')
storage = get_media_storage()
broken_node_links = []
orphaned_files_choices = []
broken_nodes, orphaned_files = get_broken_media()
for node in broken_nodes:
link = mark_safe('<a href="%s">%s</a>' % (node.get_admin_url(), node.__unicode__()))
broken_node_links.append(link)
for storage_name in orphaned_files:
file_path = storage.path(storage_name)
link = mark_safe('<a href="%s">%s</a>' % (
storage.url(storage_name), file_path))
orphaned_files_choices.append((storage_name, link))
if not len(orphaned_files_choices) and not len(broken_node_links):
messages.success(request, message=_('There are no orphaned files.'))
return HttpResponseRedirect('')
if execute:
form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices, request.POST)
if form.is_valid():
form.save()
node = FileNode.get_top_node()
messages.success(request, message=ungettext('Deleted %i file from storage.', 'Deleted %i files from storage.', len(form.success_files)) % len(form.success_files))
if form.error_files:
messages.error(request, message=_('The following files could not be deleted from storage:')+' '+repr(form.error_files))
return HttpResponseRedirect(node.get_admin_url())
if not execute:
if len(orphaned_files_choices) > 0:
form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices)
else:
form = None
c = get_actions_context(modeladmin)
c.update({
'title': _('Orphaned files'),
'submit_label': _('Delete selected files'),
'form': form,
'select_all': 'selected_files',
'node_list_title': _('The following files in the database do not exist in storage. You should fix these media objects:'),
'node_list': broken_node_links,
})
return render_to_response('admin/media_tree/filenode/actions_form.html', c, context_instance=RequestContext(request)) | python | def delete_orphaned_files(modeladmin, request, queryset=None):
"""
Deletes orphaned files, i.e. media files existing in storage that are not in the database.
"""
execute = request.POST.get('execute')
storage = get_media_storage()
broken_node_links = []
orphaned_files_choices = []
broken_nodes, orphaned_files = get_broken_media()
for node in broken_nodes:
link = mark_safe('<a href="%s">%s</a>' % (node.get_admin_url(), node.__unicode__()))
broken_node_links.append(link)
for storage_name in orphaned_files:
file_path = storage.path(storage_name)
link = mark_safe('<a href="%s">%s</a>' % (
storage.url(storage_name), file_path))
orphaned_files_choices.append((storage_name, link))
if not len(orphaned_files_choices) and not len(broken_node_links):
messages.success(request, message=_('There are no orphaned files.'))
return HttpResponseRedirect('')
if execute:
form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices, request.POST)
if form.is_valid():
form.save()
node = FileNode.get_top_node()
messages.success(request, message=ungettext('Deleted %i file from storage.', 'Deleted %i files from storage.', len(form.success_files)) % len(form.success_files))
if form.error_files:
messages.error(request, message=_('The following files could not be deleted from storage:')+' '+repr(form.error_files))
return HttpResponseRedirect(node.get_admin_url())
if not execute:
if len(orphaned_files_choices) > 0:
form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices)
else:
form = None
c = get_actions_context(modeladmin)
c.update({
'title': _('Orphaned files'),
'submit_label': _('Delete selected files'),
'form': form,
'select_all': 'selected_files',
'node_list_title': _('The following files in the database do not exist in storage. You should fix these media objects:'),
'node_list': broken_node_links,
})
return render_to_response('admin/media_tree/filenode/actions_form.html', c, context_instance=RequestContext(request)) | [
"def",
"delete_orphaned_files",
"(",
"modeladmin",
",",
"request",
",",
"queryset",
"=",
"None",
")",
":",
"execute",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'execute'",
")",
"storage",
"=",
"get_media_storage",
"(",
")",
"broken_node_links",
"=",
"["... | Deletes orphaned files, i.e. media files existing in storage that are not in the database. | [
"Deletes",
"orphaned",
"files",
"i",
".",
"e",
".",
"media",
"files",
"existing",
"in",
"storage",
"that",
"are",
"not",
"in",
"the",
"database",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/actions/maintenance_actions.py#L17-L69 | train | 44,075 |
samluescher/django-media-tree | media_tree/admin/actions/maintenance_actions.py | rebuild_tree | def rebuild_tree(modeladmin, request, queryset=None):
"""
Rebuilds whole tree in database using `parent` link.
"""
tree = FileNode.tree.rebuild()
messages.success(request, message=_('The node tree was rebuilt.'))
return HttpResponseRedirect('') | python | def rebuild_tree(modeladmin, request, queryset=None):
"""
Rebuilds whole tree in database using `parent` link.
"""
tree = FileNode.tree.rebuild()
messages.success(request, message=_('The node tree was rebuilt.'))
return HttpResponseRedirect('') | [
"def",
"rebuild_tree",
"(",
"modeladmin",
",",
"request",
",",
"queryset",
"=",
"None",
")",
":",
"tree",
"=",
"FileNode",
".",
"tree",
".",
"rebuild",
"(",
")",
"messages",
".",
"success",
"(",
"request",
",",
"message",
"=",
"_",
"(",
"'The node tree w... | Rebuilds whole tree in database using `parent` link. | [
"Rebuilds",
"whole",
"tree",
"in",
"database",
"using",
"parent",
"link",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/actions/maintenance_actions.py#L74-L80 | train | 44,076 |
samluescher/django-media-tree | media_tree/admin/actions/maintenance_actions.py | clear_cache | def clear_cache(modeladmin, request, queryset=None):
"""
Clears media cache files such as thumbnails.
"""
execute = request.POST.get('execute')
files_in_storage = []
storage = get_media_storage()
cache_files_choices = []
for storage_name in get_cache_files():
link = mark_safe('<a href="%s">%s</a>' % (
storage.url(storage_name), storage_name))
cache_files_choices.append((storage_name, link))
if not len(cache_files_choices):
messages.warning(request, message=_('There are no cache files.'))
return HttpResponseRedirect('')
if execute:
form = DeleteCacheFilesForm(queryset, cache_files_choices, request.POST)
if form.is_valid():
form.save()
node = FileNode.get_top_node()
message = ungettext('Deleted %i cache file.', 'Deleted %i cache files.', len(form.success_files)) % len(form.success_files)
if len(form.success_files) == len(cache_files_choices):
message = '%s %s' % (_('The cache was cleared.'), message)
messages.success(request, message=message)
if form.error_files:
messages.error(request, message=_('The following files could not be deleted:')+' '+repr(form.error_files))
return HttpResponseRedirect(node.get_admin_url())
if not execute:
if len(cache_files_choices) > 0:
form = DeleteCacheFilesForm(queryset, cache_files_choices)
else:
form = None
c = get_actions_context(modeladmin)
c.update({
'title': _('Clear cache'),
'submit_label': _('Delete selected files'),
'form': form,
'select_all': 'selected_files',
})
return render_to_response('admin/media_tree/filenode/actions_form.html', c, context_instance=RequestContext(request))
return HttpResponseRedirect('') | python | def clear_cache(modeladmin, request, queryset=None):
"""
Clears media cache files such as thumbnails.
"""
execute = request.POST.get('execute')
files_in_storage = []
storage = get_media_storage()
cache_files_choices = []
for storage_name in get_cache_files():
link = mark_safe('<a href="%s">%s</a>' % (
storage.url(storage_name), storage_name))
cache_files_choices.append((storage_name, link))
if not len(cache_files_choices):
messages.warning(request, message=_('There are no cache files.'))
return HttpResponseRedirect('')
if execute:
form = DeleteCacheFilesForm(queryset, cache_files_choices, request.POST)
if form.is_valid():
form.save()
node = FileNode.get_top_node()
message = ungettext('Deleted %i cache file.', 'Deleted %i cache files.', len(form.success_files)) % len(form.success_files)
if len(form.success_files) == len(cache_files_choices):
message = '%s %s' % (_('The cache was cleared.'), message)
messages.success(request, message=message)
if form.error_files:
messages.error(request, message=_('The following files could not be deleted:')+' '+repr(form.error_files))
return HttpResponseRedirect(node.get_admin_url())
if not execute:
if len(cache_files_choices) > 0:
form = DeleteCacheFilesForm(queryset, cache_files_choices)
else:
form = None
c = get_actions_context(modeladmin)
c.update({
'title': _('Clear cache'),
'submit_label': _('Delete selected files'),
'form': form,
'select_all': 'selected_files',
})
return render_to_response('admin/media_tree/filenode/actions_form.html', c, context_instance=RequestContext(request))
return HttpResponseRedirect('') | [
"def",
"clear_cache",
"(",
"modeladmin",
",",
"request",
",",
"queryset",
"=",
"None",
")",
":",
"execute",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'execute'",
")",
"files_in_storage",
"=",
"[",
"]",
"storage",
"=",
"get_media_storage",
"(",
")",
... | Clears media cache files such as thumbnails. | [
"Clears",
"media",
"cache",
"files",
"such",
"as",
"thumbnails",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/actions/maintenance_actions.py#L85-L132 | train | 44,077 |
samluescher/django-media-tree | media_tree/utils/__init__.py | autodiscover_media_extensions | def autodiscover_media_extensions():
"""
Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when
not present. This forces an import on them to register any media extension bits
they may want.
Rip of django.contrib.admin.autodiscover()
"""
import copy
from django.conf import settings
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
import_module('%s.media_extension' % app)
except:
if module_has_submodule(mod, 'media_extension'):
raise | python | def autodiscover_media_extensions():
"""
Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when
not present. This forces an import on them to register any media extension bits
they may want.
Rip of django.contrib.admin.autodiscover()
"""
import copy
from django.conf import settings
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
import_module('%s.media_extension' % app)
except:
if module_has_submodule(mod, 'media_extension'):
raise | [
"def",
"autodiscover_media_extensions",
"(",
")",
":",
"import",
"copy",
"from",
"django",
".",
"conf",
"import",
"settings",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"module_has_submodule",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_A... | Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when
not present. This forces an import on them to register any media extension bits
they may want.
Rip of django.contrib.admin.autodiscover() | [
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"media_extensions",
".",
"py",
"modules",
"and",
"fail",
"silently",
"when",
"not",
"present",
".",
"This",
"forces",
"an",
"import",
"on",
"them",
"to",
"register",
"any",
"media",
"extension",
"bits",
"they",
"may",... | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/utils/__init__.py#L37-L55 | train | 44,078 |
samluescher/django-media-tree | media_tree/utils/__init__.py | join_formatted | def join_formatted(text, new_text, glue_format_if_true = u'%s%s', glue_format_if_false = u'%s%s', condition=None, format = u'%s', escape=False):
"""
Joins two strings, optionally escaping the second, and using one of two
string formats for glueing them together, depending on whether a condition
is True or False.
This function is a shorthand for complicated code blocks when you want to
format some strings and link them together. A typical use case might be:
Wrap string B with <strong> tags, but only if it is not empty, and join it
with A with a comma in between, but only if A is not empty, etc.
"""
if condition is None:
condition = text and new_text
add_text = new_text
if escape:
add_text = conditional_escape(add_text)
if add_text:
add_text = format % add_text
glue_format = glue_format_if_true if condition else glue_format_if_false
return glue_format % (text, add_text) | python | def join_formatted(text, new_text, glue_format_if_true = u'%s%s', glue_format_if_false = u'%s%s', condition=None, format = u'%s', escape=False):
"""
Joins two strings, optionally escaping the second, and using one of two
string formats for glueing them together, depending on whether a condition
is True or False.
This function is a shorthand for complicated code blocks when you want to
format some strings and link them together. A typical use case might be:
Wrap string B with <strong> tags, but only if it is not empty, and join it
with A with a comma in between, but only if A is not empty, etc.
"""
if condition is None:
condition = text and new_text
add_text = new_text
if escape:
add_text = conditional_escape(add_text)
if add_text:
add_text = format % add_text
glue_format = glue_format_if_true if condition else glue_format_if_false
return glue_format % (text, add_text) | [
"def",
"join_formatted",
"(",
"text",
",",
"new_text",
",",
"glue_format_if_true",
"=",
"u'%s%s'",
",",
"glue_format_if_false",
"=",
"u'%s%s'",
",",
"condition",
"=",
"None",
",",
"format",
"=",
"u'%s'",
",",
"escape",
"=",
"False",
")",
":",
"if",
"conditio... | Joins two strings, optionally escaping the second, and using one of two
string formats for glueing them together, depending on whether a condition
is True or False.
This function is a shorthand for complicated code blocks when you want to
format some strings and link them together. A typical use case might be:
Wrap string B with <strong> tags, but only if it is not empty, and join it
with A with a comma in between, but only if A is not empty, etc. | [
"Joins",
"two",
"strings",
"optionally",
"escaping",
"the",
"second",
"and",
"using",
"one",
"of",
"two",
"string",
"formats",
"for",
"glueing",
"them",
"together",
"depending",
"on",
"whether",
"a",
"condition",
"is",
"True",
"or",
"False",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/utils/__init__.py#L90-L109 | train | 44,079 |
psss/fmf | fmf/base.py | Tree._initialize | def _initialize(self, path):
""" Find metadata tree root, detect format version """
# Find the tree root
root = os.path.abspath(path)
try:
while ".fmf" not in next(os.walk(root))[1]:
if root == "/":
raise utils.RootError(
"Unable to find tree root for '{0}'.".format(
os.path.abspath(path)))
root = os.path.abspath(os.path.join(root, os.pardir))
except StopIteration:
raise utils.FileError("Invalid directory path: {0}".format(root))
log.info("Root directory found: {0}".format(root))
self.root = root
# Detect format version
try:
with open(os.path.join(self.root, ".fmf", "version")) as version:
self.version = int(version.read())
log.info("Format version detected: {0}".format(self.version))
except IOError as error:
raise utils.FormatError(
"Unable to detect format version: {0}".format(error))
except ValueError:
raise utils.FormatError("Invalid version format") | python | def _initialize(self, path):
""" Find metadata tree root, detect format version """
# Find the tree root
root = os.path.abspath(path)
try:
while ".fmf" not in next(os.walk(root))[1]:
if root == "/":
raise utils.RootError(
"Unable to find tree root for '{0}'.".format(
os.path.abspath(path)))
root = os.path.abspath(os.path.join(root, os.pardir))
except StopIteration:
raise utils.FileError("Invalid directory path: {0}".format(root))
log.info("Root directory found: {0}".format(root))
self.root = root
# Detect format version
try:
with open(os.path.join(self.root, ".fmf", "version")) as version:
self.version = int(version.read())
log.info("Format version detected: {0}".format(self.version))
except IOError as error:
raise utils.FormatError(
"Unable to detect format version: {0}".format(error))
except ValueError:
raise utils.FormatError("Invalid version format") | [
"def",
"_initialize",
"(",
"self",
",",
"path",
")",
":",
"# Find the tree root",
"root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"try",
":",
"while",
"\".fmf\"",
"not",
"in",
"next",
"(",
"os",
".",
"walk",
"(",
"root",
")",
")",
... | Find metadata tree root, detect format version | [
"Find",
"metadata",
"tree",
"root",
"detect",
"format",
"version"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L85-L109 | train | 44,080 |
psss/fmf | fmf/base.py | Tree.merge | def merge(self, parent=None):
""" Merge parent data """
# Check parent, append source files
if parent is None:
parent = self.parent
if parent is None:
return
self.sources = parent.sources + self.sources
# Merge child data with parent data
data = copy.deepcopy(parent.data)
for key, value in sorted(self.data.items()):
# Handle attribute adding
if key.endswith('+'):
key = key.rstrip('+')
if key in data:
# Use dict.update() for merging dictionaries
if type(data[key]) == type(value) == dict:
data[key].update(value)
continue
try:
value = data[key] + value
except TypeError as error:
raise utils.MergeError(
"MergeError: Key '{0}' in {1} ({2}).".format(
key, self.name, str(error)))
# And finally update the value
data[key] = value
self.data = data | python | def merge(self, parent=None):
""" Merge parent data """
# Check parent, append source files
if parent is None:
parent = self.parent
if parent is None:
return
self.sources = parent.sources + self.sources
# Merge child data with parent data
data = copy.deepcopy(parent.data)
for key, value in sorted(self.data.items()):
# Handle attribute adding
if key.endswith('+'):
key = key.rstrip('+')
if key in data:
# Use dict.update() for merging dictionaries
if type(data[key]) == type(value) == dict:
data[key].update(value)
continue
try:
value = data[key] + value
except TypeError as error:
raise utils.MergeError(
"MergeError: Key '{0}' in {1} ({2}).".format(
key, self.name, str(error)))
# And finally update the value
data[key] = value
self.data = data | [
"def",
"merge",
"(",
"self",
",",
"parent",
"=",
"None",
")",
":",
"# Check parent, append source files",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"self",
".",
"parent",
"if",
"parent",
"is",
"None",
":",
"return",
"self",
".",
"sources",
"=",
"... | Merge parent data | [
"Merge",
"parent",
"data"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L111-L138 | train | 44,081 |
psss/fmf | fmf/base.py | Tree.update | def update(self, data):
""" Update metadata, handle virtual hierarchy """
# Nothing to do if no data
if data is None:
return
for key, value in sorted(data.items()):
# Handle child attributes
if key.startswith('/'):
name = key.lstrip('/')
# Handle deeper nesting (e.g. keys like /one/two/three) by
# extracting only the first level of the hierarchy as name
match = re.search("([^/]+)(/.*)", name)
if match:
name = match.groups()[0]
value = {match.groups()[1]: value}
# Update existing child or create a new one
self.child(name, value)
# Update regular attributes
else:
self.data[key] = value
log.debug("Data for '{0}' updated.".format(self))
log.data(pretty(self.data)) | python | def update(self, data):
""" Update metadata, handle virtual hierarchy """
# Nothing to do if no data
if data is None:
return
for key, value in sorted(data.items()):
# Handle child attributes
if key.startswith('/'):
name = key.lstrip('/')
# Handle deeper nesting (e.g. keys like /one/two/three) by
# extracting only the first level of the hierarchy as name
match = re.search("([^/]+)(/.*)", name)
if match:
name = match.groups()[0]
value = {match.groups()[1]: value}
# Update existing child or create a new one
self.child(name, value)
# Update regular attributes
else:
self.data[key] = value
log.debug("Data for '{0}' updated.".format(self))
log.data(pretty(self.data)) | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"# Nothing to do if no data",
"if",
"data",
"is",
"None",
":",
"return",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"data",
".",
"items",
"(",
")",
")",
":",
"# Handle child attributes",
"if",
"k... | Update metadata, handle virtual hierarchy | [
"Update",
"metadata",
"handle",
"virtual",
"hierarchy"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L152-L173 | train | 44,082 |
psss/fmf | fmf/base.py | Tree.get | def get(self, name=None, default=None):
"""
Get attribute value or return default
Whole data dictionary is returned when no attribute provided.
Supports direct values retrieval from deep dictionaries as well.
Dictionary path should be provided as list. The following two
examples are equal:
tree.data['hardware']['memory']['size']
tree.get(['hardware', 'memory', 'size'])
However the latter approach will also correctly handle providing
default value when any of the dictionary keys does not exist.
"""
# Return the whole dictionary if no attribute specified
if name is None:
return self.data
if not isinstance(name, list):
name = [name]
data = self.data
try:
for key in name:
data = data[key]
except KeyError:
return default
return data | python | def get(self, name=None, default=None):
"""
Get attribute value or return default
Whole data dictionary is returned when no attribute provided.
Supports direct values retrieval from deep dictionaries as well.
Dictionary path should be provided as list. The following two
examples are equal:
tree.data['hardware']['memory']['size']
tree.get(['hardware', 'memory', 'size'])
However the latter approach will also correctly handle providing
default value when any of the dictionary keys does not exist.
"""
# Return the whole dictionary if no attribute specified
if name is None:
return self.data
if not isinstance(name, list):
name = [name]
data = self.data
try:
for key in name:
data = data[key]
except KeyError:
return default
return data | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"# Return the whole dictionary if no attribute specified",
"if",
"name",
"is",
"None",
":",
"return",
"self",
".",
"data",
"if",
"not",
"isinstance",
"(",
"name",
","... | Get attribute value or return default
Whole data dictionary is returned when no attribute provided.
Supports direct values retrieval from deep dictionaries as well.
Dictionary path should be provided as list. The following two
examples are equal:
tree.data['hardware']['memory']['size']
tree.get(['hardware', 'memory', 'size'])
However the latter approach will also correctly handle providing
default value when any of the dictionary keys does not exist. | [
"Get",
"attribute",
"value",
"or",
"return",
"default"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L175-L202 | train | 44,083 |
psss/fmf | fmf/base.py | Tree.child | def child(self, name, data, source=None):
""" Create or update child with given data """
try:
if isinstance(data, dict):
self.children[name].update(data)
else:
self.children[name].grow(data)
except KeyError:
self.children[name] = Tree(data, name, parent=self)
# Save source file
if source is not None:
self.children[name].sources.append(source) | python | def child(self, name, data, source=None):
""" Create or update child with given data """
try:
if isinstance(data, dict):
self.children[name].update(data)
else:
self.children[name].grow(data)
except KeyError:
self.children[name] = Tree(data, name, parent=self)
# Save source file
if source is not None:
self.children[name].sources.append(source) | [
"def",
"child",
"(",
"self",
",",
"name",
",",
"data",
",",
"source",
"=",
"None",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"self",
".",
"children",
"[",
"name",
"]",
".",
"update",
"(",
"data",
")",
"else",
... | Create or update child with given data | [
"Create",
"or",
"update",
"child",
"with",
"given",
"data"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L204-L215 | train | 44,084 |
psss/fmf | fmf/base.py | Tree.grow | def grow(self, path):
"""
Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value more than once!
"""
if path is None:
return
path = path.rstrip("/")
log.info("Walking through directory {0}".format(
os.path.abspath(path)))
dirpath, dirnames, filenames = next(os.walk(path))
# Investigate main.fmf as the first file (for correct inheritance)
filenames = sorted(
[filename for filename in filenames if filename.endswith(SUFFIX)])
try:
filenames.insert(0, filenames.pop(filenames.index(MAIN)))
except ValueError:
pass
# Check every metadata file and load data (ignore hidden)
for filename in filenames:
if filename.startswith("."):
continue
fullpath = os.path.abspath(os.path.join(dirpath, filename))
log.info("Checking file {0}".format(fullpath))
try:
with open(fullpath) as datafile:
data = yaml.load(datafile, Loader=FullLoader)
except yaml.scanner.ScannerError as error:
raise(utils.FileError("Failed to parse '{0}'\n{1}".format(
fullpath, error)))
log.data(pretty(data))
# Handle main.fmf as data for self
if filename == MAIN:
self.sources.append(fullpath)
self.update(data)
# Handle other *.fmf files as children
else:
self.child(os.path.splitext(filename)[0], data, fullpath)
# Explore every child directory (ignore hidden dirs and subtrees)
for dirname in sorted(dirnames):
if dirname.startswith("."):
continue
# Ignore metadata subtrees
if os.path.isdir(os.path.join(path, dirname, SUFFIX)):
log.debug("Ignoring metadata tree '{0}'.".format(dirname))
continue
self.child(dirname, os.path.join(path, dirname))
# Remove empty children (ignore directories without metadata)
for name in list(self.children.keys()):
child = self.children[name]
if not child.data and not child.children:
del(self.children[name])
log.debug("Empty tree '{0}' removed.".format(child.name))
# Apply inheritance when all scattered data are gathered.
# This is done only once, from the top parent object.
if self.parent is None:
self.inherit() | python | def grow(self, path):
"""
Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value more than once!
"""
if path is None:
return
path = path.rstrip("/")
log.info("Walking through directory {0}".format(
os.path.abspath(path)))
dirpath, dirnames, filenames = next(os.walk(path))
# Investigate main.fmf as the first file (for correct inheritance)
filenames = sorted(
[filename for filename in filenames if filename.endswith(SUFFIX)])
try:
filenames.insert(0, filenames.pop(filenames.index(MAIN)))
except ValueError:
pass
# Check every metadata file and load data (ignore hidden)
for filename in filenames:
if filename.startswith("."):
continue
fullpath = os.path.abspath(os.path.join(dirpath, filename))
log.info("Checking file {0}".format(fullpath))
try:
with open(fullpath) as datafile:
data = yaml.load(datafile, Loader=FullLoader)
except yaml.scanner.ScannerError as error:
raise(utils.FileError("Failed to parse '{0}'\n{1}".format(
fullpath, error)))
log.data(pretty(data))
# Handle main.fmf as data for self
if filename == MAIN:
self.sources.append(fullpath)
self.update(data)
# Handle other *.fmf files as children
else:
self.child(os.path.splitext(filename)[0], data, fullpath)
# Explore every child directory (ignore hidden dirs and subtrees)
for dirname in sorted(dirnames):
if dirname.startswith("."):
continue
# Ignore metadata subtrees
if os.path.isdir(os.path.join(path, dirname, SUFFIX)):
log.debug("Ignoring metadata tree '{0}'.".format(dirname))
continue
self.child(dirname, os.path.join(path, dirname))
# Remove empty children (ignore directories without metadata)
for name in list(self.children.keys()):
child = self.children[name]
if not child.data and not child.children:
del(self.children[name])
log.debug("Empty tree '{0}' removed.".format(child.name))
# Apply inheritance when all scattered data are gathered.
# This is done only once, from the top parent object.
if self.parent is None:
self.inherit() | [
"def",
"grow",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"path",
"=",
"path",
".",
"rstrip",
"(",
"\"/\"",
")",
"log",
".",
"info",
"(",
"\"Walking through directory {0}\"",
".",
"format",
"(",
"os",
".",
"path",
... | Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value more than once! | [
"Grow",
"the",
"metadata",
"tree",
"for",
"the",
"given",
"directory",
"path"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L217-L276 | train | 44,085 |
psss/fmf | fmf/base.py | Tree.find | def find(self, name):
""" Find node with given name """
for node in self.climb(whole=True):
if node.name == name:
return node
return None | python | def find(self, name):
""" Find node with given name """
for node in self.climb(whole=True):
if node.name == name:
return node
return None | [
"def",
"find",
"(",
"self",
",",
"name",
")",
":",
"for",
"node",
"in",
"self",
".",
"climb",
"(",
"whole",
"=",
"True",
")",
":",
"if",
"node",
".",
"name",
"==",
"name",
":",
"return",
"node",
"return",
"None"
] | Find node with given name | [
"Find",
"node",
"with",
"given",
"name"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L286-L291 | train | 44,086 |
psss/fmf | fmf/base.py | Tree.prune | def prune(self, whole=False, keys=[], names=[], filters=[]):
""" Filter tree nodes based on given criteria """
for node in self.climb(whole):
# Select only nodes with key content
if not all([key in node.data for key in keys]):
continue
# Select nodes with name matching regular expression
if names and not any(
[re.search(name, node.name) for name in names]):
continue
# Apply advanced filters if given
try:
if not all([utils.filter(filter, node.data, regexp=True)
for filter in filters]):
continue
# Handle missing attribute as if filter failed
except utils.FilterError:
continue
# All criteria met, thus yield the node
yield node | python | def prune(self, whole=False, keys=[], names=[], filters=[]):
""" Filter tree nodes based on given criteria """
for node in self.climb(whole):
# Select only nodes with key content
if not all([key in node.data for key in keys]):
continue
# Select nodes with name matching regular expression
if names and not any(
[re.search(name, node.name) for name in names]):
continue
# Apply advanced filters if given
try:
if not all([utils.filter(filter, node.data, regexp=True)
for filter in filters]):
continue
# Handle missing attribute as if filter failed
except utils.FilterError:
continue
# All criteria met, thus yield the node
yield node | [
"def",
"prune",
"(",
"self",
",",
"whole",
"=",
"False",
",",
"keys",
"=",
"[",
"]",
",",
"names",
"=",
"[",
"]",
",",
"filters",
"=",
"[",
"]",
")",
":",
"for",
"node",
"in",
"self",
".",
"climb",
"(",
"whole",
")",
":",
"# Select only nodes wit... | Filter tree nodes based on given criteria | [
"Filter",
"tree",
"nodes",
"based",
"on",
"given",
"criteria"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/base.py#L293-L312 | train | 44,087 |
samluescher/django-media-tree | media_tree/contrib/legacy_mptt_support/forms.py | MoveNodeForm.save | def save(self):
"""
Attempts to move the node using the selected target and
position.
If an invalid move is attempted, the related error message will
be added to the form's non-field errors and the error will be
re-raised. Callers should attempt to catch ``InvalidNode`` to
redisplay the form with the error, should it occur.
"""
try:
self.node.move_to(self.cleaned_data['target'],
self.cleaned_data['position'])
return self.node
except InvalidMove, e:
self.errors[NON_FIELD_ERRORS] = ErrorList(e)
raise | python | def save(self):
"""
Attempts to move the node using the selected target and
position.
If an invalid move is attempted, the related error message will
be added to the form's non-field errors and the error will be
re-raised. Callers should attempt to catch ``InvalidNode`` to
redisplay the form with the error, should it occur.
"""
try:
self.node.move_to(self.cleaned_data['target'],
self.cleaned_data['position'])
return self.node
except InvalidMove, e:
self.errors[NON_FIELD_ERRORS] = ErrorList(e)
raise | [
"def",
"save",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"node",
".",
"move_to",
"(",
"self",
".",
"cleaned_data",
"[",
"'target'",
"]",
",",
"self",
".",
"cleaned_data",
"[",
"'position'",
"]",
")",
"return",
"self",
".",
"node",
"except",
"In... | Attempts to move the node using the selected target and
position.
If an invalid move is attempted, the related error message will
be added to the form's non-field errors and the error will be
re-raised. Callers should attempt to catch ``InvalidNode`` to
redisplay the form with the error, should it occur. | [
"Attempts",
"to",
"move",
"the",
"node",
"using",
"the",
"selected",
"target",
"and",
"position",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/contrib/legacy_mptt_support/forms.py#L136-L152 | train | 44,088 |
psss/fmf | fmf/cli.py | Parser.show | def show(self, brief=False):
""" Show metadata for each path given """
output = []
for path in self.options.paths or ["."]:
if self.options.verbose:
utils.info("Checking {0} for metadata.".format(path))
tree = fmf.Tree(path)
for node in tree.prune(
self.options.whole, self.options.keys, self.options.names,
self.options.filters):
if brief:
show = node.show(brief=True)
else:
show = node.show(
brief=False,
formatting=self.options.formatting,
values=self.options.values)
# List source files when in debug mode
if self.options.debug:
for source in node.sources:
show += utils.color("{0}\n".format(source), "blue")
if show is not None:
output.append(show)
# Print output and summary
if brief or self.options.formatting:
joined = "".join(output)
else:
joined = "\n".join(output)
try: # pragma: no cover
print(joined, end="")
except UnicodeEncodeError: # pragma: no cover
print(joined.encode('utf-8'), end="")
if self.options.verbose:
utils.info("Found {0}.".format(
utils.listed(len(output), "object")))
self.output = joined | python | def show(self, brief=False):
""" Show metadata for each path given """
output = []
for path in self.options.paths or ["."]:
if self.options.verbose:
utils.info("Checking {0} for metadata.".format(path))
tree = fmf.Tree(path)
for node in tree.prune(
self.options.whole, self.options.keys, self.options.names,
self.options.filters):
if brief:
show = node.show(brief=True)
else:
show = node.show(
brief=False,
formatting=self.options.formatting,
values=self.options.values)
# List source files when in debug mode
if self.options.debug:
for source in node.sources:
show += utils.color("{0}\n".format(source), "blue")
if show is not None:
output.append(show)
# Print output and summary
if brief or self.options.formatting:
joined = "".join(output)
else:
joined = "\n".join(output)
try: # pragma: no cover
print(joined, end="")
except UnicodeEncodeError: # pragma: no cover
print(joined.encode('utf-8'), end="")
if self.options.verbose:
utils.info("Found {0}.".format(
utils.listed(len(output), "object")))
self.output = joined | [
"def",
"show",
"(",
"self",
",",
"brief",
"=",
"False",
")",
":",
"output",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"options",
".",
"paths",
"or",
"[",
"\".\"",
"]",
":",
"if",
"self",
".",
"options",
".",
"verbose",
":",
"utils",
".",
... | Show metadata for each path given | [
"Show",
"metadata",
"for",
"each",
"path",
"given"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/cli.py#L150-L186 | train | 44,089 |
psss/fmf | fmf/utils.py | filter | def filter(filter, data, sensitive=True, regexp=False):
"""
Return true if provided filter matches given dictionary of values
Filter supports disjunctive normal form with '|' used for OR, '&'
for AND and '-' for negation. Individual values are prefixed with
'value:', leading/trailing white-space is stripped. For example::
tag: Tier1 | tag: Tier2 | tag: Tier3
category: Sanity, Security & tag: -destructive
Note that multiple comma-separated values can be used as a syntactic
sugar to shorten the filter notation::
tag: A, B, C ---> tag: A | tag: B | tag: C
Values should be provided as a dictionary of lists each describing
the values against which the filter is to be matched. For example::
data = {tag: ["Tier1", "TIPpass"], category: ["Sanity"]}
Other types of dictionary values are converted into a string.
A FilterError exception is raised when a dimension parsed from the
filter is not found in the data dictionary. Set option 'sensitive'
to False to enable case-insensitive matching. If 'regexp' option is
True, regular expressions can be used in the filter values as well.
"""
def match_value(pattern, text):
""" Match value against data (simple or regexp) """
if regexp:
return re.match("^{0}$".format(pattern), text)
else:
return pattern == text
def check_value(dimension, value):
""" Check whether the value matches data """
# E.g. value = 'A, B' or value = "C" or value = "-D"
# If there are multiple values, at least one must match
for atom in re.split("\s*,\s*", value):
# Handle negative values (check the whole data for non-presence)
if atom.startswith("-"):
atom = atom[1:]
# Check each value for given dimension
for dato in data[dimension]:
if match_value(atom, dato):
break
# Pattern not found ---> good
else:
return True
# Handle positive values (return True upon first successful match)
else:
# Check each value for given dimension
for dato in data[dimension]:
if match_value(atom, dato):
# Pattern found ---> good
return True
# No value matched the data
return False
def check_dimension(dimension, values):
""" Check whether all values for given dimension match data """
# E.g. dimension = 'tag', values = ['A, B', 'C', '-D']
# Raise exception upon unknown dimension
if dimension not in data:
raise FilterError("Invalid filter '{0}'".format(dimension))
# Every value must match at least one value for data
return all([check_value(dimension, value) for value in values])
def check_clause(clause):
""" Split into literals and check whether all match """
# E.g. clause = 'tag: A, B & tag: C & tag: -D'
# Split into individual literals by dimension
literals = dict()
for literal in re.split("\s*&\s*", clause):
# E.g. literal = 'tag: A, B'
# Make sure the literal matches dimension:value format
matched = re.match("^(.*)\s*:\s*(.*)$", literal)
if not matched:
raise FilterError("Invalid filter '{0}'".format(literal))
dimension, value = matched.groups()
values = [value]
# Append the literal value(s) to corresponding dimension list
literals.setdefault(dimension, []).extend(values)
# For each dimension all literals must match given data
return all([check_dimension(dimension, values)
for dimension, values in literals.items()])
# Default to True if no filter given, bail out if weird data given
if filter is None or filter == "": return True
if not isinstance(data, dict):
raise FilterError("Invalid data type '{0}'".format(type(data)))
# Make sure that data dictionary contains lists of strings
data = copy.deepcopy(data)
try: # pragma: no cover
for key in data:
if isinstance(data[key], list):
data[key] = [unicode(item) for item in data[key]]
else:
data[key] = [unicode(data[key])]
except NameError: # pragma: no cover
for key in data:
if isinstance(data[key], list):
data[key] = [str(item) for item in data[key]]
else:
data[key] = [str(data[key])]
# Turn all data into lowercase if sensitivity is off
if not sensitive:
filter = filter.lower()
lowered = dict()
for key, values in data.items():
lowered[key.lower()] = [value.lower() for value in values]
data = lowered
# At least one clause must be true
return any([check_clause(clause)
for clause in re.split("\s*\|\s*", filter)]) | python | def filter(filter, data, sensitive=True, regexp=False):
"""
Return true if provided filter matches given dictionary of values
Filter supports disjunctive normal form with '|' used for OR, '&'
for AND and '-' for negation. Individual values are prefixed with
'value:', leading/trailing white-space is stripped. For example::
tag: Tier1 | tag: Tier2 | tag: Tier3
category: Sanity, Security & tag: -destructive
Note that multiple comma-separated values can be used as a syntactic
sugar to shorten the filter notation::
tag: A, B, C ---> tag: A | tag: B | tag: C
Values should be provided as a dictionary of lists each describing
the values against which the filter is to be matched. For example::
data = {tag: ["Tier1", "TIPpass"], category: ["Sanity"]}
Other types of dictionary values are converted into a string.
A FilterError exception is raised when a dimension parsed from the
filter is not found in the data dictionary. Set option 'sensitive'
to False to enable case-insensitive matching. If 'regexp' option is
True, regular expressions can be used in the filter values as well.
"""
def match_value(pattern, text):
""" Match value against data (simple or regexp) """
if regexp:
return re.match("^{0}$".format(pattern), text)
else:
return pattern == text
def check_value(dimension, value):
""" Check whether the value matches data """
# E.g. value = 'A, B' or value = "C" or value = "-D"
# If there are multiple values, at least one must match
for atom in re.split("\s*,\s*", value):
# Handle negative values (check the whole data for non-presence)
if atom.startswith("-"):
atom = atom[1:]
# Check each value for given dimension
for dato in data[dimension]:
if match_value(atom, dato):
break
# Pattern not found ---> good
else:
return True
# Handle positive values (return True upon first successful match)
else:
# Check each value for given dimension
for dato in data[dimension]:
if match_value(atom, dato):
# Pattern found ---> good
return True
# No value matched the data
return False
def check_dimension(dimension, values):
""" Check whether all values for given dimension match data """
# E.g. dimension = 'tag', values = ['A, B', 'C', '-D']
# Raise exception upon unknown dimension
if dimension not in data:
raise FilterError("Invalid filter '{0}'".format(dimension))
# Every value must match at least one value for data
return all([check_value(dimension, value) for value in values])
def check_clause(clause):
""" Split into literals and check whether all match """
# E.g. clause = 'tag: A, B & tag: C & tag: -D'
# Split into individual literals by dimension
literals = dict()
for literal in re.split("\s*&\s*", clause):
# E.g. literal = 'tag: A, B'
# Make sure the literal matches dimension:value format
matched = re.match("^(.*)\s*:\s*(.*)$", literal)
if not matched:
raise FilterError("Invalid filter '{0}'".format(literal))
dimension, value = matched.groups()
values = [value]
# Append the literal value(s) to corresponding dimension list
literals.setdefault(dimension, []).extend(values)
# For each dimension all literals must match given data
return all([check_dimension(dimension, values)
for dimension, values in literals.items()])
# Default to True if no filter given, bail out if weird data given
if filter is None or filter == "": return True
if not isinstance(data, dict):
raise FilterError("Invalid data type '{0}'".format(type(data)))
# Make sure that data dictionary contains lists of strings
data = copy.deepcopy(data)
try: # pragma: no cover
for key in data:
if isinstance(data[key], list):
data[key] = [unicode(item) for item in data[key]]
else:
data[key] = [unicode(data[key])]
except NameError: # pragma: no cover
for key in data:
if isinstance(data[key], list):
data[key] = [str(item) for item in data[key]]
else:
data[key] = [str(data[key])]
# Turn all data into lowercase if sensitivity is off
if not sensitive:
filter = filter.lower()
lowered = dict()
for key, values in data.items():
lowered[key.lower()] = [value.lower() for value in values]
data = lowered
# At least one clause must be true
return any([check_clause(clause)
for clause in re.split("\s*\|\s*", filter)]) | [
"def",
"filter",
"(",
"filter",
",",
"data",
",",
"sensitive",
"=",
"True",
",",
"regexp",
"=",
"False",
")",
":",
"def",
"match_value",
"(",
"pattern",
",",
"text",
")",
":",
"\"\"\" Match value against data (simple or regexp) \"\"\"",
"if",
"regexp",
":",
"r... | Return true if provided filter matches given dictionary of values
Filter supports disjunctive normal form with '|' used for OR, '&'
for AND and '-' for negation. Individual values are prefixed with
'value:', leading/trailing white-space is stripped. For example::
tag: Tier1 | tag: Tier2 | tag: Tier3
category: Sanity, Security & tag: -destructive
Note that multiple comma-separated values can be used as a syntactic
sugar to shorten the filter notation::
tag: A, B, C ---> tag: A | tag: B | tag: C
Values should be provided as a dictionary of lists each describing
the values against which the filter is to be matched. For example::
data = {tag: ["Tier1", "TIPpass"], category: ["Sanity"]}
Other types of dictionary values are converted into a string.
A FilterError exception is raised when a dimension parsed from the
filter is not found in the data dictionary. Set option 'sensitive'
to False to enable case-insensitive matching. If 'regexp' option is
True, regular expressions can be used in the filter values as well. | [
"Return",
"true",
"if",
"provided",
"filter",
"matches",
"given",
"dictionary",
"of",
"values"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/utils.py#L150-L267 | train | 44,090 |
psss/fmf | fmf/utils.py | color | def color(text, color=None, background=None, light=False, enabled="auto"):
"""
Return text in desired color if coloring enabled
Available colors: black red green yellow blue magenta cyan white.
Alternatively color can be prefixed with "light", e.g. lightgreen.
"""
colors = {"black": 30, "red": 31, "green": 32, "yellow": 33,
"blue": 34, "magenta": 35, "cyan": 36, "white": 37}
# Nothing do do if coloring disabled
if enabled == "auto":
enabled = Coloring().enabled()
if not enabled:
return text
# Prepare colors (strip 'light' if present in color)
if color and color.startswith("light"):
light = True
color = color[5:]
color = color and ";{0}".format(colors[color]) or ""
background = background and ";{0}".format(colors[background] + 10) or ""
light = light and 1 or 0
# Starting and finishing sequence
start = "\033[{0}{1}{2}m".format(light, color, background)
finish = "\033[1;m"
return "".join([start, text, finish]) | python | def color(text, color=None, background=None, light=False, enabled="auto"):
"""
Return text in desired color if coloring enabled
Available colors: black red green yellow blue magenta cyan white.
Alternatively color can be prefixed with "light", e.g. lightgreen.
"""
colors = {"black": 30, "red": 31, "green": 32, "yellow": 33,
"blue": 34, "magenta": 35, "cyan": 36, "white": 37}
# Nothing do do if coloring disabled
if enabled == "auto":
enabled = Coloring().enabled()
if not enabled:
return text
# Prepare colors (strip 'light' if present in color)
if color and color.startswith("light"):
light = True
color = color[5:]
color = color and ";{0}".format(colors[color]) or ""
background = background and ";{0}".format(colors[background] + 10) or ""
light = light and 1 or 0
# Starting and finishing sequence
start = "\033[{0}{1}{2}m".format(light, color, background)
finish = "\033[1;m"
return "".join([start, text, finish]) | [
"def",
"color",
"(",
"text",
",",
"color",
"=",
"None",
",",
"background",
"=",
"None",
",",
"light",
"=",
"False",
",",
"enabled",
"=",
"\"auto\"",
")",
":",
"colors",
"=",
"{",
"\"black\"",
":",
"30",
",",
"\"red\"",
":",
"31",
",",
"\"green\"",
... | Return text in desired color if coloring enabled
Available colors: black red green yellow blue magenta cyan white.
Alternatively color can be prefixed with "light", e.g. lightgreen. | [
"Return",
"text",
"in",
"desired",
"color",
"if",
"coloring",
"enabled"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/utils.py#L391-L415 | train | 44,091 |
psss/fmf | fmf/utils.py | Logging._create_logger | def _create_logger(name='fmf', level=None):
""" Create fmf logger """
# Create logger, handler and formatter
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(Logging.ColoredFormatter())
logger.addHandler(handler)
# Save log levels in the logger itself (backward compatibility)
for level in Logging.LEVELS:
setattr(logger, level, getattr(logging, level))
# Additional logging constants and methods for cache and xmlrpc
logger.DATA = LOG_DATA
logger.CACHE = LOG_CACHE
logger.ALL = LOG_ALL
logger.cache = lambda message: logger.log(LOG_CACHE, message) # NOQA
logger.data = lambda message: logger.log(LOG_DATA, message) # NOQA
logger.all = lambda message: logger.log(LOG_ALL, message) # NOQA
return logger | python | def _create_logger(name='fmf', level=None):
""" Create fmf logger """
# Create logger, handler and formatter
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(Logging.ColoredFormatter())
logger.addHandler(handler)
# Save log levels in the logger itself (backward compatibility)
for level in Logging.LEVELS:
setattr(logger, level, getattr(logging, level))
# Additional logging constants and methods for cache and xmlrpc
logger.DATA = LOG_DATA
logger.CACHE = LOG_CACHE
logger.ALL = LOG_ALL
logger.cache = lambda message: logger.log(LOG_CACHE, message) # NOQA
logger.data = lambda message: logger.log(LOG_DATA, message) # NOQA
logger.all = lambda message: logger.log(LOG_ALL, message) # NOQA
return logger | [
"def",
"_create_logger",
"(",
"name",
"=",
"'fmf'",
",",
"level",
"=",
"None",
")",
":",
"# Create logger, handler and formatter",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"handler... | Create fmf logger | [
"Create",
"fmf",
"logger"
] | 419f2f195d92339b8f9e5d11c0bea0f303e5fd75 | https://github.com/psss/fmf/blob/419f2f195d92339b8f9e5d11c0bea0f303e5fd75/fmf/utils.py#L338-L355 | train | 44,092 |
samluescher/django-media-tree | media_tree/models.py | FileNode.get_admin_url | def get_admin_url(self, query_params=None, use_path=False):
"""Returns the URL for viewing a FileNode in the admin."""
if not query_params:
query_params = {}
url = ''
if self.is_top_node():
url = reverse('admin:media_tree_filenode_changelist');
elif use_path and (self.is_folder() or self.pk):
url = reverse('admin:media_tree_filenode_open_path', args=(self.get_path(),));
elif self.is_folder():
url = reverse('admin:media_tree_filenode_changelist');
query_params['folder_id'] = self.pk
elif self.pk:
return reverse('admin:media_tree_filenode_change', args=(self.pk,));
if len(query_params):
params = ['%s=%s' % (key, value) for key, value in query_params.items()]
url = '%s?%s' % (url, "&".join(params))
return url | python | def get_admin_url(self, query_params=None, use_path=False):
"""Returns the URL for viewing a FileNode in the admin."""
if not query_params:
query_params = {}
url = ''
if self.is_top_node():
url = reverse('admin:media_tree_filenode_changelist');
elif use_path and (self.is_folder() or self.pk):
url = reverse('admin:media_tree_filenode_open_path', args=(self.get_path(),));
elif self.is_folder():
url = reverse('admin:media_tree_filenode_changelist');
query_params['folder_id'] = self.pk
elif self.pk:
return reverse('admin:media_tree_filenode_change', args=(self.pk,));
if len(query_params):
params = ['%s=%s' % (key, value) for key, value in query_params.items()]
url = '%s?%s' % (url, "&".join(params))
return url | [
"def",
"get_admin_url",
"(",
"self",
",",
"query_params",
"=",
"None",
",",
"use_path",
"=",
"False",
")",
":",
"if",
"not",
"query_params",
":",
"query_params",
"=",
"{",
"}",
"url",
"=",
"''",
"if",
"self",
".",
"is_top_node",
"(",
")",
":",
"url",
... | Returns the URL for viewing a FileNode in the admin. | [
"Returns",
"the",
"URL",
"for",
"viewing",
"a",
"FileNode",
"in",
"the",
"admin",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/models.py#L482-L503 | train | 44,093 |
samluescher/django-media-tree | media_tree/models.py | FileNode.get_caption_formatted | def get_caption_formatted(self, field_formats = app_settings.MEDIA_TREE_METADATA_FORMATS, escape=True):
"""Returns object metadata that has been selected to be displayed to
users, compiled as a string including default formatting, for example
bold titles.
You can use this method in templates where you want to output image
captions.
"""
if self.override_caption != '':
return self.override_caption
else:
return mark_safe(self.get_metadata_display(field_formats, escape=escape)) | python | def get_caption_formatted(self, field_formats = app_settings.MEDIA_TREE_METADATA_FORMATS, escape=True):
"""Returns object metadata that has been selected to be displayed to
users, compiled as a string including default formatting, for example
bold titles.
You can use this method in templates where you want to output image
captions.
"""
if self.override_caption != '':
return self.override_caption
else:
return mark_safe(self.get_metadata_display(field_formats, escape=escape)) | [
"def",
"get_caption_formatted",
"(",
"self",
",",
"field_formats",
"=",
"app_settings",
".",
"MEDIA_TREE_METADATA_FORMATS",
",",
"escape",
"=",
"True",
")",
":",
"if",
"self",
".",
"override_caption",
"!=",
"''",
":",
"return",
"self",
".",
"override_caption",
"... | Returns object metadata that has been selected to be displayed to
users, compiled as a string including default formatting, for example
bold titles.
You can use this method in templates where you want to output image
captions. | [
"Returns",
"object",
"metadata",
"that",
"has",
"been",
"selected",
"to",
"be",
"displayed",
"to",
"users",
"compiled",
"as",
"a",
"string",
"including",
"default",
"formatting",
"for",
"example",
"bold",
"titles",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/models.py#L693-L704 | train | 44,094 |
samluescher/django-media-tree | media_tree/admin/actions/forms.py | MoveSelectedForm.save | def save(self):
"""
Attempts to move the nodes using the selected target and
position.
If an invalid move is attempted, the related error message will
be added to the form's non-field errors and the error will be
re-raised. Callers should attempt to catch ``InvalidMove`` to
redisplay the form with the error, should it occur.
"""
self.success_count = 0
for node in self.get_selected_nodes():
self.move_node(node, self.cleaned_data['target_node']) | python | def save(self):
"""
Attempts to move the nodes using the selected target and
position.
If an invalid move is attempted, the related error message will
be added to the form's non-field errors and the error will be
re-raised. Callers should attempt to catch ``InvalidMove`` to
redisplay the form with the error, should it occur.
"""
self.success_count = 0
for node in self.get_selected_nodes():
self.move_node(node, self.cleaned_data['target_node']) | [
"def",
"save",
"(",
"self",
")",
":",
"self",
".",
"success_count",
"=",
"0",
"for",
"node",
"in",
"self",
".",
"get_selected_nodes",
"(",
")",
":",
"self",
".",
"move_node",
"(",
"node",
",",
"self",
".",
"cleaned_data",
"[",
"'target_node'",
"]",
")"... | Attempts to move the nodes using the selected target and
position.
If an invalid move is attempted, the related error message will
be added to the form's non-field errors and the error will be
re-raised. Callers should attempt to catch ``InvalidMove`` to
redisplay the form with the error, should it occur. | [
"Attempts",
"to",
"move",
"the",
"nodes",
"using",
"the",
"selected",
"target",
"and",
"position",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/actions/forms.py#L86-L98 | train | 44,095 |
samluescher/django-media-tree | media_tree/admin/actions/forms.py | DeleteStorageFilesForm.save | def save(self):
"""
Deletes the selected files from storage
"""
storage = get_media_storage()
for storage_name in self.cleaned_data['selected_files']:
full_path = storage.path(storage_name)
try:
storage.delete(storage_name)
self.success_files.append(full_path)
except OSError:
self.error_files.append(full_path) | python | def save(self):
"""
Deletes the selected files from storage
"""
storage = get_media_storage()
for storage_name in self.cleaned_data['selected_files']:
full_path = storage.path(storage_name)
try:
storage.delete(storage_name)
self.success_files.append(full_path)
except OSError:
self.error_files.append(full_path) | [
"def",
"save",
"(",
"self",
")",
":",
"storage",
"=",
"get_media_storage",
"(",
")",
"for",
"storage_name",
"in",
"self",
".",
"cleaned_data",
"[",
"'selected_files'",
"]",
":",
"full_path",
"=",
"storage",
".",
"path",
"(",
"storage_name",
")",
"try",
":"... | Deletes the selected files from storage | [
"Deletes",
"the",
"selected",
"files",
"from",
"storage"
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/actions/forms.py#L204-L215 | train | 44,096 |
samluescher/django-media-tree | media_tree/utils/filenode.py | get_file_link | def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra=''):
"""
Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file.
"""
link_text = None
if use_metadata:
link_text = node.get_metadata_display()
if not link_text:
link_text = node.__unicode__()
if node.node_type != media_types.FOLDER:
if include_extension:
if extra != '':
extra += ' '
extra = '<span class="file-extension">%s</span>' % node.extension.upper()
if include_size:
if extra != '':
extra += ', '
extra += '<span class="file-size">%s</span>' % filesizeformat(node.size)
if extra:
extra = ' <span class="details">(%s)</span>' % extra
link_class = 'file %s' % node.extension
else:
link_class = 'folder'
if extra_class:
link_class = '%s %s' % (link_class, extra_class)
if node.node_type != media_types.FOLDER and not href:
href = node.file.url
icon = ''
if include_icon:
icon_file = node.get_icon_file()
if icon_file:
icon = '<span class="icon"><img src="%s" alt="%s" /></span>' % (
icon_file.url, node.alt)
if href:
link = u'<a class="%s" href="%s">%s%s</a>%s' % (
link_class, href, icon, link_text, extra)
else:
link = u'<span class="%s">%s%s</span>%s' % (
link_class, icon, link_text, extra)
return force_unicode(mark_safe(link)) | python | def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra=''):
"""
Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file.
"""
link_text = None
if use_metadata:
link_text = node.get_metadata_display()
if not link_text:
link_text = node.__unicode__()
if node.node_type != media_types.FOLDER:
if include_extension:
if extra != '':
extra += ' '
extra = '<span class="file-extension">%s</span>' % node.extension.upper()
if include_size:
if extra != '':
extra += ', '
extra += '<span class="file-size">%s</span>' % filesizeformat(node.size)
if extra:
extra = ' <span class="details">(%s)</span>' % extra
link_class = 'file %s' % node.extension
else:
link_class = 'folder'
if extra_class:
link_class = '%s %s' % (link_class, extra_class)
if node.node_type != media_types.FOLDER and not href:
href = node.file.url
icon = ''
if include_icon:
icon_file = node.get_icon_file()
if icon_file:
icon = '<span class="icon"><img src="%s" alt="%s" /></span>' % (
icon_file.url, node.alt)
if href:
link = u'<a class="%s" href="%s">%s%s</a>%s' % (
link_class, href, icon, link_text, extra)
else:
link = u'<span class="%s">%s%s</span>%s' % (
link_class, icon, link_text, extra)
return force_unicode(mark_safe(link)) | [
"def",
"get_file_link",
"(",
"node",
",",
"use_metadata",
"=",
"False",
",",
"include_size",
"=",
"False",
",",
"include_extension",
"=",
"False",
",",
"include_icon",
"=",
"False",
",",
"href",
"=",
"None",
",",
"extra_class",
"=",
"''",
",",
"extra",
"="... | Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file. | [
"Returns",
"a",
"formatted",
"HTML",
"link",
"tag",
"to",
"the",
"FileNode",
"s",
"file",
"optionally",
"including",
"some",
"meta",
"information",
"about",
"the",
"file",
"."
] | 3eb6345faaf57e2fbe35ca431d4d133f950f2b5f | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/utils/filenode.py#L134-L177 | train | 44,097 |
resonai/ybt | yabt/target_utils.py | norm_name | def norm_name(build_module: str, target_name: str):
"""Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path from the project root
to the target build module (POSIX), and <name> is a valid target name
(see `validate_name()`).
"""
if ':' not in target_name:
raise ValueError(
"Must provide fully-qualified target name (with `:') to avoid "
"possible ambiguity - `{}' not valid".format(target_name))
mod, name = split(target_name)
return '{}:{}'.format(
PurePath(norm_proj_path(mod, build_module)).as_posix().strip('.'),
validate_name(name)) | python | def norm_name(build_module: str, target_name: str):
"""Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path from the project root
to the target build module (POSIX), and <name> is a valid target name
(see `validate_name()`).
"""
if ':' not in target_name:
raise ValueError(
"Must provide fully-qualified target name (with `:') to avoid "
"possible ambiguity - `{}' not valid".format(target_name))
mod, name = split(target_name)
return '{}:{}'.format(
PurePath(norm_proj_path(mod, build_module)).as_posix().strip('.'),
validate_name(name)) | [
"def",
"norm_name",
"(",
"build_module",
":",
"str",
",",
"target_name",
":",
"str",
")",
":",
"if",
"':'",
"not",
"in",
"target_name",
":",
"raise",
"ValueError",
"(",
"\"Must provide fully-qualified target name (with `:') to avoid \"",
"\"possible ambiguity - `{}' not v... | Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path from the project root
to the target build module (POSIX), and <name> is a valid target name
(see `validate_name()`). | [
"Return",
"a",
"normalized",
"canonical",
"target",
"name",
"for",
"the",
"target_name",
"observed",
"in",
"build",
"module",
"build_module",
"."
] | 5b40df0922ef3383eb85f2b04a26a2db4b81b3fd | https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/target_utils.py#L75-L92 | train | 44,098 |
resonai/ybt | yabt/target_utils.py | hashify_targets | def hashify_targets(targets: list, build_context) -> list:
"""Return sorted hashes of `targets`."""
return sorted(build_context.targets[target_name].hash(build_context)
for target_name in listify(targets)) | python | def hashify_targets(targets: list, build_context) -> list:
"""Return sorted hashes of `targets`."""
return sorted(build_context.targets[target_name].hash(build_context)
for target_name in listify(targets)) | [
"def",
"hashify_targets",
"(",
"targets",
":",
"list",
",",
"build_context",
")",
"->",
"list",
":",
"return",
"sorted",
"(",
"build_context",
".",
"targets",
"[",
"target_name",
"]",
".",
"hash",
"(",
"build_context",
")",
"for",
"target_name",
"in",
"listi... | Return sorted hashes of `targets`. | [
"Return",
"sorted",
"hashes",
"of",
"targets",
"."
] | 5b40df0922ef3383eb85f2b04a26a2db4b81b3fd | https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/target_utils.py#L129-L132 | train | 44,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.