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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
ClientPerMessageDeflateFactory.process_response_params
def process_response_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> PerMessageDeflate: """ Process response parameters. Return an extension instance. """ if any(other.name == self.name for other i...
python
def process_response_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> PerMessageDeflate: """ Process response parameters. Return an extension instance. """ if any(other.name == self.name for other i...
[ "def", "process_response_params", "(", "self", ",", "params", ":", "Sequence", "[", "ExtensionParameter", "]", ",", "accepted_extensions", ":", "Sequence", "[", "\"Extension\"", "]", ",", ")", "->", "PerMessageDeflate", ":", "if", "any", "(", "other", ".", "na...
Process response parameters. Return an extension instance.
[ "Process", "response", "parameters", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L325-L428
train
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
ServerPerMessageDeflateFactory.process_request_params
def process_request_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> Tuple[List[ExtensionParameter], PerMessageDeflate]: """ Process request parameters. Return response params and an extension instance. """...
python
def process_request_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence["Extension"], ) -> Tuple[List[ExtensionParameter], PerMessageDeflate]: """ Process request parameters. Return response params and an extension instance. """...
[ "def", "process_request_params", "(", "self", ",", "params", ":", "Sequence", "[", "ExtensionParameter", "]", ",", "accepted_extensions", ":", "Sequence", "[", "\"Extension\"", "]", ",", ")", "->", "Tuple", "[", "List", "[", "ExtensionParameter", "]", ",", "Pe...
Process request parameters. Return response params and an extension instance.
[ "Process", "request", "parameters", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L482-L592
train
aaugustin/websockets
src/websockets/utils.py
apply_mask
def apply_mask(data: bytes, mask: bytes) -> bytes: """ Apply masking to the data of a WebSocket message. ``data`` and ``mask`` are bytes-like objects. Return :class:`bytes`. """ if len(mask) != 4: raise ValueError("mask must contain 4 bytes") return bytes(b ^ m for b, m in zip(da...
python
def apply_mask(data: bytes, mask: bytes) -> bytes: """ Apply masking to the data of a WebSocket message. ``data`` and ``mask`` are bytes-like objects. Return :class:`bytes`. """ if len(mask) != 4: raise ValueError("mask must contain 4 bytes") return bytes(b ^ m for b, m in zip(da...
[ "def", "apply_mask", "(", "data", ":", "bytes", ",", "mask", ":", "bytes", ")", "->", "bytes", ":", "if", "len", "(", "mask", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"mask must contain 4 bytes\"", ")", "return", "bytes", "(", "b", "^", "m", ...
Apply masking to the data of a WebSocket message. ``data`` and ``mask`` are bytes-like objects. Return :class:`bytes`.
[ "Apply", "masking", "to", "the", "data", "of", "a", "WebSocket", "message", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/utils.py#L7-L19
train
aaugustin/websockets
src/websockets/exceptions.py
format_close
def format_close(code: int, reason: str) -> str: """ Display a human-readable version of the close code and reason. """ if 3000 <= code < 4000: explanation = "registered" elif 4000 <= code < 5000: explanation = "private use" else: explanation = CLOSE_CODES.get(code, "un...
python
def format_close(code: int, reason: str) -> str: """ Display a human-readable version of the close code and reason. """ if 3000 <= code < 4000: explanation = "registered" elif 4000 <= code < 5000: explanation = "private use" else: explanation = CLOSE_CODES.get(code, "un...
[ "def", "format_close", "(", "code", ":", "int", ",", "reason", ":", "str", ")", "->", "str", ":", "if", "3000", "<=", "code", "<", "4000", ":", "explanation", "=", "\"registered\"", "elif", "4000", "<=", "code", "<", "5000", ":", "explanation", "=", ...
Display a human-readable version of the close code and reason.
[ "Display", "a", "human", "-", "readable", "version", "of", "the", "close", "code", "and", "reason", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/exceptions.py#L202-L221
train
nameko/nameko
nameko/runners.py
ServiceRunner.start
def start(self): """ Start all the registered services. A new container is created for each service using the container class provided in the __init__ method. All containers are started concurrently and the method will block until all have completed their startup routine. ...
python
def start(self): """ Start all the registered services. A new container is created for each service using the container class provided in the __init__ method. All containers are started concurrently and the method will block until all have completed their startup routine. ...
[ "def", "start", "(", "self", ")", ":", "service_names", "=", "', '", ".", "join", "(", "self", ".", "service_names", ")", "_log", ".", "info", "(", "'starting services: %s'", ",", "service_names", ")", "SpawningProxy", "(", "self", ".", "containers", ")", ...
Start all the registered services. A new container is created for each service using the container class provided in the __init__ method. All containers are started concurrently and the method will block until all have completed their startup routine.
[ "Start", "all", "the", "registered", "services", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/runners.py#L54-L68
train
nameko/nameko
nameko/runners.py
ServiceRunner.wait
def wait(self): """ Wait for all running containers to stop. """ try: SpawningProxy(self.containers, abort_on_error=True).wait() except Exception: # If a single container failed, stop its peers and re-raise the # exception self.stop() ...
python
def wait(self): """ Wait for all running containers to stop. """ try: SpawningProxy(self.containers, abort_on_error=True).wait() except Exception: # If a single container failed, stop its peers and re-raise the # exception self.stop() ...
[ "def", "wait", "(", "self", ")", ":", "try", ":", "SpawningProxy", "(", "self", ".", "containers", ",", "abort_on_error", "=", "True", ")", ".", "wait", "(", ")", "except", "Exception", ":", "# If a single container failed, stop its peers and re-raise the", "# exc...
Wait for all running containers to stop.
[ "Wait", "for", "all", "running", "containers", "to", "stop", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/runners.py#L92-L101
train
nameko/nameko
nameko/amqp/publish.py
Publisher.publish
def publish(self, payload, **kwargs): """ Publish a message. """ publish_kwargs = self.publish_kwargs.copy() # merge headers from when the publisher was instantiated # with any provided now; "extra" headers always win headers = publish_kwargs.pop('headers', {}).copy() ...
python
def publish(self, payload, **kwargs): """ Publish a message. """ publish_kwargs = self.publish_kwargs.copy() # merge headers from when the publisher was instantiated # with any provided now; "extra" headers always win headers = publish_kwargs.pop('headers', {}).copy() ...
[ "def", "publish", "(", "self", ",", "payload", ",", "*", "*", "kwargs", ")", ":", "publish_kwargs", "=", "self", ".", "publish_kwargs", ".", "copy", "(", ")", "# merge headers from when the publisher was instantiated", "# with any provided now; \"extra\" headers always wi...
Publish a message.
[ "Publish", "a", "message", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/amqp/publish.py#L161-L223
train
nameko/nameko
nameko/rpc.py
RpcConsumer.stop
def stop(self): """ Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop. """ ...
python
def stop(self): """ Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop. """ ...
[ "def", "stop", "(", "self", ")", ":", "if", "not", "self", ".", "_providers_registered", ":", "self", ".", "queue_consumer", ".", "unregister_provider", "(", "self", ")", "self", ".", "_unregistered_from_queue_consumer", ".", "send", "(", "True", ")" ]
Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop.
[ "Stop", "the", "RpcConsumer", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/rpc.py#L70-L80
train
nameko/nameko
nameko/rpc.py
RpcConsumer.unregister_provider
def unregister_provider(self, provider): """ Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister. """ self._unregistering_providers.add(provider) remaining_providers =...
python
def unregister_provider(self, provider): """ Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister. """ self._unregistering_providers.add(provider) remaining_providers =...
[ "def", "unregister_provider", "(", "self", ",", "provider", ")", ":", "self", ".", "_unregistering_providers", ".", "add", "(", "provider", ")", "remaining_providers", "=", "self", ".", "_providers", "-", "self", ".", "_unregistering_providers", "if", "not", "re...
Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister.
[ "Unregister", "a", "provider", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/rpc.py#L82-L98
train
nameko/nameko
nameko/events.py
EventDispatcher.get_dependency
def get_dependency(self, worker_ctx): """ Inject a dispatch method onto the service instance """ extra_headers = self.get_message_headers(worker_ctx) def dispatch(event_type, event_data): self.publisher.publish( event_data, exchange=self.excha...
python
def get_dependency(self, worker_ctx): """ Inject a dispatch method onto the service instance """ extra_headers = self.get_message_headers(worker_ctx) def dispatch(event_type, event_data): self.publisher.publish( event_data, exchange=self.excha...
[ "def", "get_dependency", "(", "self", ",", "worker_ctx", ")", ":", "extra_headers", "=", "self", ".", "get_message_headers", "(", "worker_ctx", ")", "def", "dispatch", "(", "event_type", ",", "event_data", ")", ":", "self", ".", "publisher", ".", "publish", ...
Inject a dispatch method onto the service instance
[ "Inject", "a", "dispatch", "method", "onto", "the", "service", "instance" ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/events.py#L86-L99
train
nameko/nameko
nameko/events.py
EventHandler.broadcast_identifier
def broadcast_identifier(self): """ A unique string to identify a service instance for `BROADCAST` type handlers. The `broadcast_identifier` is appended to the queue name when the `BROADCAST` handler type is used. It must uniquely identify service instances that receive broadcas...
python
def broadcast_identifier(self): """ A unique string to identify a service instance for `BROADCAST` type handlers. The `broadcast_identifier` is appended to the queue name when the `BROADCAST` handler type is used. It must uniquely identify service instances that receive broadcas...
[ "def", "broadcast_identifier", "(", "self", ")", ":", "if", "self", ".", "handler_type", "is", "not", "BROADCAST", ":", "return", "None", "if", "self", ".", "reliable_delivery", ":", "raise", "EventHandlerConfigurationError", "(", "\"You are using the default broadcas...
A unique string to identify a service instance for `BROADCAST` type handlers. The `broadcast_identifier` is appended to the queue name when the `BROADCAST` handler type is used. It must uniquely identify service instances that receive broadcasts. The default `broadcast_identifi...
[ "A", "unique", "string", "to", "identify", "a", "service", "instance", "for", "BROADCAST", "type", "handlers", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/events.py#L166-L222
train
nameko/nameko
nameko/exceptions.py
get_module_path
def get_module_path(exc_type): """ Return the dotted module path of `exc_type`, including the class name. e.g.:: >>> get_module_path(MethodNotFound) >>> "nameko.exceptions.MethodNotFound" """ module = inspect.getmodule(exc_type) return "{}.{}".format(module.__name__, exc_type.__na...
python
def get_module_path(exc_type): """ Return the dotted module path of `exc_type`, including the class name. e.g.:: >>> get_module_path(MethodNotFound) >>> "nameko.exceptions.MethodNotFound" """ module = inspect.getmodule(exc_type) return "{}.{}".format(module.__name__, exc_type.__na...
[ "def", "get_module_path", "(", "exc_type", ")", ":", "module", "=", "inspect", ".", "getmodule", "(", "exc_type", ")", "return", "\"{}.{}\"", ".", "format", "(", "module", ".", "__name__", ",", "exc_type", ".", "__name__", ")" ]
Return the dotted module path of `exc_type`, including the class name. e.g.:: >>> get_module_path(MethodNotFound) >>> "nameko.exceptions.MethodNotFound"
[ "Return", "the", "dotted", "module", "path", "of", "exc_type", "including", "the", "class", "name", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L38-L48
train
nameko/nameko
nameko/exceptions.py
safe_for_serialization
def safe_for_serialization(value): """ Transform a value in preparation for serializing as json no-op for strings, mappings and iterables have their entries made safe, and all other values are stringified, with a fallback value if that fails """ if isinstance(value, six.string_types): retu...
python
def safe_for_serialization(value): """ Transform a value in preparation for serializing as json no-op for strings, mappings and iterables have their entries made safe, and all other values are stringified, with a fallback value if that fails """ if isinstance(value, six.string_types): retu...
[ "def", "safe_for_serialization", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "{", "safe_for_serialization", "(", ...
Transform a value in preparation for serializing as json no-op for strings, mappings and iterables have their entries made safe, and all other values are stringified, with a fallback value if that fails
[ "Transform", "a", "value", "in", "preparation", "for", "serializing", "as", "json" ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L62-L82
train
nameko/nameko
nameko/exceptions.py
serialize
def serialize(exc): """ Serialize `self.exc` into a data dictionary representing it. """ return { 'exc_type': type(exc).__name__, 'exc_path': get_module_path(type(exc)), 'exc_args': list(map(safe_for_serialization, exc.args)), 'value': safe_for_serialization(exc), }
python
def serialize(exc): """ Serialize `self.exc` into a data dictionary representing it. """ return { 'exc_type': type(exc).__name__, 'exc_path': get_module_path(type(exc)), 'exc_args': list(map(safe_for_serialization, exc.args)), 'value': safe_for_serialization(exc), }
[ "def", "serialize", "(", "exc", ")", ":", "return", "{", "'exc_type'", ":", "type", "(", "exc", ")", ".", "__name__", ",", "'exc_path'", ":", "get_module_path", "(", "type", "(", "exc", ")", ")", ",", "'exc_args'", ":", "list", "(", "map", "(", "safe...
Serialize `self.exc` into a data dictionary representing it.
[ "Serialize", "self", ".", "exc", "into", "a", "data", "dictionary", "representing", "it", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L85-L94
train
nameko/nameko
nameko/exceptions.py
deserialize
def deserialize(data): """ Deserialize `data` to an exception instance. If the `exc_path` value matches an exception registered as ``deserializable``, return an instance of that exception type. Otherwise, return a `RemoteError` instance describing the exception that occurred. """ key = data...
python
def deserialize(data): """ Deserialize `data` to an exception instance. If the `exc_path` value matches an exception registered as ``deserializable``, return an instance of that exception type. Otherwise, return a `RemoteError` instance describing the exception that occurred. """ key = data...
[ "def", "deserialize", "(", "data", ")", ":", "key", "=", "data", ".", "get", "(", "'exc_path'", ")", "if", "key", "in", "registry", ":", "exc_args", "=", "data", ".", "get", "(", "'exc_args'", ",", "(", ")", ")", "return", "registry", "[", "key", "...
Deserialize `data` to an exception instance. If the `exc_path` value matches an exception registered as ``deserializable``, return an instance of that exception type. Otherwise, return a `RemoteError` instance describing the exception that occurred.
[ "Deserialize", "data", "to", "an", "exception", "instance", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L97-L112
train
nameko/nameko
nameko/utils/__init__.py
import_from_path
def import_from_path(path): """ Import and return the object at `path` if it exists. Raises an :exc:`ImportError` if the object is not found. """ if path is None: return obj = locate(path) if obj is None: raise ImportError( "`{}` could not be imported".format(path) ...
python
def import_from_path(path): """ Import and return the object at `path` if it exists. Raises an :exc:`ImportError` if the object is not found. """ if path is None: return obj = locate(path) if obj is None: raise ImportError( "`{}` could not be imported".format(path) ...
[ "def", "import_from_path", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "obj", "=", "locate", "(", "path", ")", "if", "obj", "is", "None", ":", "raise", "ImportError", "(", "\"`{}` could not be imported\"", ".", "format", "(", "path", ...
Import and return the object at `path` if it exists. Raises an :exc:`ImportError` if the object is not found.
[ "Import", "and", "return", "the", "object", "at", "path", "if", "it", "exists", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/utils/__init__.py#L110-L124
train
nameko/nameko
nameko/utils/__init__.py
sanitize_url
def sanitize_url(url): """Redact password in urls.""" parts = urlparse(url) if parts.password is None: return url host_info = parts.netloc.rsplit('@', 1)[-1] parts = parts._replace(netloc='{}:{}@{}'.format( parts.username, REDACTED, host_info)) return parts.geturl()
python
def sanitize_url(url): """Redact password in urls.""" parts = urlparse(url) if parts.password is None: return url host_info = parts.netloc.rsplit('@', 1)[-1] parts = parts._replace(netloc='{}:{}@{}'.format( parts.username, REDACTED, host_info)) return parts.geturl()
[ "def", "sanitize_url", "(", "url", ")", ":", "parts", "=", "urlparse", "(", "url", ")", "if", "parts", ".", "password", "is", "None", ":", "return", "url", "host_info", "=", "parts", ".", "netloc", ".", "rsplit", "(", "'@'", ",", "1", ")", "[", "-"...
Redact password in urls.
[ "Redact", "password", "in", "urls", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/utils/__init__.py#L127-L135
train
nameko/nameko
nameko/web/websocket.py
WebSocketHub.get_subscriptions
def get_subscriptions(self, socket_id): """Returns a list of all the subscriptions of a socket.""" con = self._get_connection(socket_id, create=False) if con is None: return [] return sorted(con.subscriptions)
python
def get_subscriptions(self, socket_id): """Returns a list of all the subscriptions of a socket.""" con = self._get_connection(socket_id, create=False) if con is None: return [] return sorted(con.subscriptions)
[ "def", "get_subscriptions", "(", "self", ",", "socket_id", ")", ":", "con", "=", "self", ".", "_get_connection", "(", "socket_id", ",", "create", "=", "False", ")", "if", "con", "is", "None", ":", "return", "[", "]", "return", "sorted", "(", "con", "."...
Returns a list of all the subscriptions of a socket.
[ "Returns", "a", "list", "of", "all", "the", "subscriptions", "of", "a", "socket", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L189-L194
train
nameko/nameko
nameko/web/websocket.py
WebSocketHub.subscribe
def subscribe(self, socket_id, channel): """Subscribes a socket to a channel.""" con = self._get_connection(socket_id) self.subscriptions.setdefault(channel, set()).add(socket_id) con.subscriptions.add(channel)
python
def subscribe(self, socket_id, channel): """Subscribes a socket to a channel.""" con = self._get_connection(socket_id) self.subscriptions.setdefault(channel, set()).add(socket_id) con.subscriptions.add(channel)
[ "def", "subscribe", "(", "self", ",", "socket_id", ",", "channel", ")", ":", "con", "=", "self", ".", "_get_connection", "(", "socket_id", ")", "self", ".", "subscriptions", ".", "setdefault", "(", "channel", ",", "set", "(", ")", ")", ".", "add", "(",...
Subscribes a socket to a channel.
[ "Subscribes", "a", "socket", "to", "a", "channel", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L196-L200
train
nameko/nameko
nameko/web/websocket.py
WebSocketHub.unsubscribe
def unsubscribe(self, socket_id, channel): """Unsubscribes a socket from a channel.""" con = self._get_connection(socket_id, create=False) if con is not None: con.subscriptions.discard(channel) try: self.subscriptions[channel].discard(socket_id) except Key...
python
def unsubscribe(self, socket_id, channel): """Unsubscribes a socket from a channel.""" con = self._get_connection(socket_id, create=False) if con is not None: con.subscriptions.discard(channel) try: self.subscriptions[channel].discard(socket_id) except Key...
[ "def", "unsubscribe", "(", "self", ",", "socket_id", ",", "channel", ")", ":", "con", "=", "self", ".", "_get_connection", "(", "socket_id", ",", "create", "=", "False", ")", "if", "con", "is", "not", "None", ":", "con", ".", "subscriptions", ".", "dis...
Unsubscribes a socket from a channel.
[ "Unsubscribes", "a", "socket", "from", "a", "channel", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L202-L210
train
nameko/nameko
nameko/web/websocket.py
WebSocketHub.broadcast
def broadcast(self, channel, event, data): """Broadcasts an event to all sockets listening on a channel.""" payload = self._server.serialize_event(event, data) for socket_id in self.subscriptions.get(channel, ()): rv = self._server.sockets.get(socket_id) if rv is not None...
python
def broadcast(self, channel, event, data): """Broadcasts an event to all sockets listening on a channel.""" payload = self._server.serialize_event(event, data) for socket_id in self.subscriptions.get(channel, ()): rv = self._server.sockets.get(socket_id) if rv is not None...
[ "def", "broadcast", "(", "self", ",", "channel", ",", "event", ",", "data", ")", ":", "payload", "=", "self", ".", "_server", ".", "serialize_event", "(", "event", ",", "data", ")", "for", "socket_id", "in", "self", ".", "subscriptions", ".", "get", "(...
Broadcasts an event to all sockets listening on a channel.
[ "Broadcasts", "an", "event", "to", "all", "sockets", "listening", "on", "a", "channel", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L212-L218
train
nameko/nameko
nameko/web/websocket.py
WebSocketHub.unicast
def unicast(self, socket_id, event, data): """Sends an event to a single socket. Returns `True` if that worked or `False` if not. """ payload = self._server.serialize_event(event, data) rv = self._server.sockets.get(socket_id) if rv is not None: rv.socket.sen...
python
def unicast(self, socket_id, event, data): """Sends an event to a single socket. Returns `True` if that worked or `False` if not. """ payload = self._server.serialize_event(event, data) rv = self._server.sockets.get(socket_id) if rv is not None: rv.socket.sen...
[ "def", "unicast", "(", "self", ",", "socket_id", ",", "event", ",", "data", ")", ":", "payload", "=", "self", ".", "_server", ".", "serialize_event", "(", "event", ",", "data", ")", "rv", "=", "self", ".", "_server", ".", "sockets", ".", "get", "(", ...
Sends an event to a single socket. Returns `True` if that worked or `False` if not.
[ "Sends", "an", "event", "to", "a", "single", "socket", ".", "Returns", "True", "if", "that", "worked", "or", "False", "if", "not", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/websocket.py#L220-L229
train
nameko/nameko
nameko/log_helpers.py
make_timing_logger
def make_timing_logger(logger, precision=3, level=logging.DEBUG): """ Return a timing logger. Usage:: >>> logger = logging.getLogger('foobar') >>> log_time = make_timing_logger( ... logger, level=logging.INFO, precision=2) >>> >>> with log_time("hello %s", "world"):...
python
def make_timing_logger(logger, precision=3, level=logging.DEBUG): """ Return a timing logger. Usage:: >>> logger = logging.getLogger('foobar') >>> log_time = make_timing_logger( ... logger, level=logging.INFO, precision=2) >>> >>> with log_time("hello %s", "world"):...
[ "def", "make_timing_logger", "(", "logger", ",", "precision", "=", "3", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "@", "contextmanager", "def", "log_time", "(", "msg", ",", "*", "args", ")", ":", "\"\"\" Log `msg` and `*args` with (naive wallclock) t...
Return a timing logger. Usage:: >>> logger = logging.getLogger('foobar') >>> log_time = make_timing_logger( ... logger, level=logging.INFO, precision=2) >>> >>> with log_time("hello %s", "world"): ... time.sleep(1) INFO:foobar:hello world in 1.00s
[ "Return", "a", "timing", "logger", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/log_helpers.py#L8-L36
train
nameko/nameko
nameko/web/server.py
WebServer.get_wsgi_server
def get_wsgi_server( self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False ): """Get the WSGI server used to process requests.""" return wsgi.Server( sock, sock.getsockname(), wsgi_app, protocol=protocol, debug=debug, ...
python
def get_wsgi_server( self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False ): """Get the WSGI server used to process requests.""" return wsgi.Server( sock, sock.getsockname(), wsgi_app, protocol=protocol, debug=debug, ...
[ "def", "get_wsgi_server", "(", "self", ",", "sock", ",", "wsgi_app", ",", "protocol", "=", "HttpOnlyProtocol", ",", "debug", "=", "False", ")", ":", "return", "wsgi", ".", "Server", "(", "sock", ",", "sock", ".", "getsockname", "(", ")", ",", "wsgi_app",...
Get the WSGI server used to process requests.
[ "Get", "the", "WSGI", "server", "used", "to", "process", "requests", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/web/server.py#L125-L136
train
nameko/nameko
nameko/standalone/events.py
get_event_exchange
def get_event_exchange(service_name): """ Get an exchange for ``service_name`` events. """ exchange_name = "{}.events".format(service_name) exchange = Exchange( exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT ) return exchange
python
def get_event_exchange(service_name): """ Get an exchange for ``service_name`` events. """ exchange_name = "{}.events".format(service_name) exchange = Exchange( exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT ) return exchange
[ "def", "get_event_exchange", "(", "service_name", ")", ":", "exchange_name", "=", "\"{}.events\"", ".", "format", "(", "service_name", ")", "exchange", "=", "Exchange", "(", "exchange_name", ",", "type", "=", "'topic'", ",", "durable", "=", "True", ",", "deliv...
Get an exchange for ``service_name`` events.
[ "Get", "an", "exchange", "for", "service_name", "events", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/events.py#L10-L18
train
nameko/nameko
nameko/standalone/events.py
event_dispatcher
def event_dispatcher(nameko_config, **kwargs): """ Return a function that dispatches nameko events. """ amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY] serializer, _ = serialization.setup(nameko_config) serializer = kwargs.pop('serializer', serializer) ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY...
python
def event_dispatcher(nameko_config, **kwargs): """ Return a function that dispatches nameko events. """ amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY] serializer, _ = serialization.setup(nameko_config) serializer = kwargs.pop('serializer', serializer) ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY...
[ "def", "event_dispatcher", "(", "nameko_config", ",", "*", "*", "kwargs", ")", ":", "amqp_uri", "=", "nameko_config", "[", "AMQP_URI_CONFIG_KEY", "]", "serializer", ",", "_", "=", "serialization", ".", "setup", "(", "nameko_config", ")", "serializer", "=", "kw...
Return a function that dispatches nameko events.
[ "Return", "a", "function", "that", "dispatches", "nameko", "events", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/events.py#L21-L48
train
nameko/nameko
nameko/timer.py
Timer._run
def _run(self): """ Runs the interval loop. """ def get_next_interval(): start_time = time.time() start = 0 if self.eager else 1 for count in itertools.count(start=start): yield max(start_time + count * self.interval - time.time(), 0) interval...
python
def _run(self): """ Runs the interval loop. """ def get_next_interval(): start_time = time.time() start = 0 if self.eager else 1 for count in itertools.count(start=start): yield max(start_time + count * self.interval - time.time(), 0) interval...
[ "def", "_run", "(", "self", ")", ":", "def", "get_next_interval", "(", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "start", "=", "0", "if", "self", ".", "eager", "else", "1", "for", "count", "in", "itertools", ".", "count", "(", "st...
Runs the interval loop.
[ "Runs", "the", "interval", "loop", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/timer.py#L58-L80
train
nameko/nameko
nameko/messaging.py
QueueConsumer.stop
def stop(self): """ Stop the queue-consumer gracefully. Wait until the last provider has been unregistered and for the ConsumerMixin's greenthread to exit (i.e. until all pending messages have been acked or requeued and all consumers stopped). """ if not self._consumers_...
python
def stop(self): """ Stop the queue-consumer gracefully. Wait until the last provider has been unregistered and for the ConsumerMixin's greenthread to exit (i.e. until all pending messages have been acked or requeued and all consumers stopped). """ if not self._consumers_...
[ "def", "stop", "(", "self", ")", ":", "if", "not", "self", ".", "_consumers_ready", ".", "ready", "(", ")", ":", "_log", ".", "debug", "(", "'stopping while consumer is starting %s'", ",", "self", ")", "stop_exc", "=", "QueueConsumerStopped", "(", ")", "# st...
Stop the queue-consumer gracefully. Wait until the last provider has been unregistered and for the ConsumerMixin's greenthread to exit (i.e. until all pending messages have been acked or requeued and all consumers stopped).
[ "Stop", "the", "queue", "-", "consumer", "gracefully", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L240-L266
train
nameko/nameko
nameko/messaging.py
QueueConsumer.kill
def kill(self): """ Kill the queue-consumer. Unlike `stop()` any pending message ack or requeue-requests, requests to remove providers, etc are lost and the consume thread is asked to terminate as soon as possible. """ # greenlet has a magic attribute ``dead`` - pylint: ...
python
def kill(self): """ Kill the queue-consumer. Unlike `stop()` any pending message ack or requeue-requests, requests to remove providers, etc are lost and the consume thread is asked to terminate as soon as possible. """ # greenlet has a magic attribute ``dead`` - pylint: ...
[ "def", "kill", "(", "self", ")", ":", "# greenlet has a magic attribute ``dead`` - pylint: disable=E1101", "if", "self", ".", "_gt", "is", "not", "None", "and", "not", "self", ".", "_gt", ".", "dead", ":", "# we can't just kill the thread because we have to give", "# Co...
Kill the queue-consumer. Unlike `stop()` any pending message ack or requeue-requests, requests to remove providers, etc are lost and the consume thread is asked to terminate as soon as possible.
[ "Kill", "the", "queue", "-", "consumer", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L268-L290
train
nameko/nameko
nameko/messaging.py
QueueConsumer.connection
def connection(self): """ Provide the connection parameters for kombu's ConsumerMixin. The `Connection` object is a declaration of connection parameters that is lazily evaluated. It doesn't represent an established connection to the broker at this point. """ heartbeat = ...
python
def connection(self): """ Provide the connection parameters for kombu's ConsumerMixin. The `Connection` object is a declaration of connection parameters that is lazily evaluated. It doesn't represent an established connection to the broker at this point. """ heartbeat = ...
[ "def", "connection", "(", "self", ")", ":", "heartbeat", "=", "self", ".", "container", ".", "config", ".", "get", "(", "HEARTBEAT_CONFIG_KEY", ",", "DEFAULT_HEARTBEAT", ")", "transport_options", "=", "self", ".", "container", ".", "config", ".", "get", "(",...
Provide the connection parameters for kombu's ConsumerMixin. The `Connection` object is a declaration of connection parameters that is lazily evaluated. It doesn't represent an established connection to the broker at this point.
[ "Provide", "the", "connection", "parameters", "for", "kombu", "s", "ConsumerMixin", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L339-L359
train
nameko/nameko
nameko/messaging.py
QueueConsumer.get_consumers
def get_consumers(self, consumer_cls, channel): """ Kombu callback to set up consumers. Called after any (re)connection to the broker. """ _log.debug('setting up consumers %s', self) for provider in self._providers: callbacks = [partial(self.handle_message, provider...
python
def get_consumers(self, consumer_cls, channel): """ Kombu callback to set up consumers. Called after any (re)connection to the broker. """ _log.debug('setting up consumers %s', self) for provider in self._providers: callbacks = [partial(self.handle_message, provider...
[ "def", "get_consumers", "(", "self", ",", "consumer_cls", ",", "channel", ")", ":", "_log", ".", "debug", "(", "'setting up consumers %s'", ",", "self", ")", "for", "provider", "in", "self", ".", "_providers", ":", "callbacks", "=", "[", "partial", "(", "s...
Kombu callback to set up consumers. Called after any (re)connection to the broker.
[ "Kombu", "callback", "to", "set", "up", "consumers", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L369-L388
train
nameko/nameko
nameko/messaging.py
QueueConsumer.on_iteration
def on_iteration(self): """ Kombu callback for each `drain_events` loop iteration.""" self._cancel_consumers_if_requested() if len(self._consumers) == 0: _log.debug('requesting stop after iteration') self.should_stop = True
python
def on_iteration(self): """ Kombu callback for each `drain_events` loop iteration.""" self._cancel_consumers_if_requested() if len(self._consumers) == 0: _log.debug('requesting stop after iteration') self.should_stop = True
[ "def", "on_iteration", "(", "self", ")", ":", "self", ".", "_cancel_consumers_if_requested", "(", ")", "if", "len", "(", "self", ".", "_consumers", ")", "==", "0", ":", "_log", ".", "debug", "(", "'requesting stop after iteration'", ")", "self", ".", "should...
Kombu callback for each `drain_events` loop iteration.
[ "Kombu", "callback", "for", "each", "drain_events", "loop", "iteration", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L390-L396
train
nameko/nameko
nameko/messaging.py
QueueConsumer.on_consume_ready
def on_consume_ready(self, connection, channel, consumers, **kwargs): """ Kombu callback when consumers are ready to accept messages. Called after any (re)connection to the broker. """ if not self._consumers_ready.ready(): _log.debug('consumer started %s', self) ...
python
def on_consume_ready(self, connection, channel, consumers, **kwargs): """ Kombu callback when consumers are ready to accept messages. Called after any (re)connection to the broker. """ if not self._consumers_ready.ready(): _log.debug('consumer started %s', self) ...
[ "def", "on_consume_ready", "(", "self", ",", "connection", ",", "channel", ",", "consumers", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "_consumers_ready", ".", "ready", "(", ")", ":", "_log", ".", "debug", "(", "'consumer started %s'", ...
Kombu callback when consumers are ready to accept messages. Called after any (re)connection to the broker.
[ "Kombu", "callback", "when", "consumers", "are", "ready", "to", "accept", "messages", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L404-L411
train
nameko/nameko
nameko/cli/shell.py
make_nameko_helper
def make_nameko_helper(config): """Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage. """ module = ModuleType('nameko') module.__doc__ = """Nameko shell helper for making rpc calls and dispatching events. Usage: >>> n.rpc.se...
python
def make_nameko_helper(config): """Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage. """ module = ModuleType('nameko') module.__doc__ = """Nameko shell helper for making rpc calls and dispatching events. Usage: >>> n.rpc.se...
[ "def", "make_nameko_helper", "(", "config", ")", ":", "module", "=", "ModuleType", "(", "'nameko'", ")", "module", ".", "__doc__", "=", "\"\"\"Nameko shell helper for making rpc calls and dispatching\nevents.\n\nUsage:\n >>> n.rpc.service.method()\n \"reply\"\n\n >>> n.dispa...
Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage.
[ "Create", "a", "fake", "module", "that", "provides", "some", "convenient", "access", "to", "nameko", "standalone", "functionality", "for", "interactive", "shell", "usage", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/cli/shell.py#L58-L77
train
nameko/nameko
nameko/extensions.py
iter_extensions
def iter_extensions(extension): """ Depth-first iterator over sub-extensions on `extension`. """ for _, ext in inspect.getmembers(extension, is_extension): for item in iter_extensions(ext): yield item yield ext
python
def iter_extensions(extension): """ Depth-first iterator over sub-extensions on `extension`. """ for _, ext in inspect.getmembers(extension, is_extension): for item in iter_extensions(ext): yield item yield ext
[ "def", "iter_extensions", "(", "extension", ")", ":", "for", "_", ",", "ext", "in", "inspect", ".", "getmembers", "(", "extension", ",", "is_extension", ")", ":", "for", "item", "in", "iter_extensions", "(", "ext", ")", ":", "yield", "item", "yield", "ex...
Depth-first iterator over sub-extensions on `extension`.
[ "Depth", "-", "first", "iterator", "over", "sub", "-", "extensions", "on", "extension", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L354-L360
train
nameko/nameko
nameko/extensions.py
Extension.bind
def bind(self, container): """ Get an instance of this Extension to bind to `container`. """ def clone(prototype): if prototype.is_bound(): raise RuntimeError('Cannot `bind` a bound extension.') cls = type(prototype) args, kwargs = prototype....
python
def bind(self, container): """ Get an instance of this Extension to bind to `container`. """ def clone(prototype): if prototype.is_bound(): raise RuntimeError('Cannot `bind` a bound extension.') cls = type(prototype) args, kwargs = prototype....
[ "def", "bind", "(", "self", ",", "container", ")", ":", "def", "clone", "(", "prototype", ")", ":", "if", "prototype", ".", "is_bound", "(", ")", ":", "raise", "RuntimeError", "(", "'Cannot `bind` a bound extension.'", ")", "cls", "=", "type", "(", "protot...
Get an instance of this Extension to bind to `container`.
[ "Get", "an", "instance", "of", "this", "Extension", "to", "bind", "to", "container", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L81-L103
train
nameko/nameko
nameko/extensions.py
SharedExtension.bind
def bind(self, container): """ Bind implementation that supports sharing. """ # if there's already a matching bound instance, return that shared = container.shared_extensions.get(self.sharing_key) if shared: return shared instance = super(SharedExtension, sel...
python
def bind(self, container): """ Bind implementation that supports sharing. """ # if there's already a matching bound instance, return that shared = container.shared_extensions.get(self.sharing_key) if shared: return shared instance = super(SharedExtension, sel...
[ "def", "bind", "(", "self", ",", "container", ")", ":", "# if there's already a matching bound instance, return that", "shared", "=", "container", ".", "shared_extensions", ".", "get", "(", "self", ".", "sharing_key", ")", "if", "shared", ":", "return", "shared", ...
Bind implementation that supports sharing.
[ "Bind", "implementation", "that", "supports", "sharing", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L123-L136
train
nameko/nameko
nameko/extensions.py
DependencyProvider.bind
def bind(self, container, attr_name): """ Get an instance of this Dependency to bind to `container` with `attr_name`. """ instance = super(DependencyProvider, self).bind(container) instance.attr_name = attr_name self.attr_name = attr_name return instance
python
def bind(self, container, attr_name): """ Get an instance of this Dependency to bind to `container` with `attr_name`. """ instance = super(DependencyProvider, self).bind(container) instance.attr_name = attr_name self.attr_name = attr_name return instance
[ "def", "bind", "(", "self", ",", "container", ",", "attr_name", ")", ":", "instance", "=", "super", "(", "DependencyProvider", ",", "self", ")", ".", "bind", "(", "container", ")", "instance", ".", "attr_name", "=", "attr_name", "self", ".", "attr_name", ...
Get an instance of this Dependency to bind to `container` with `attr_name`.
[ "Get", "an", "instance", "of", "this", "Dependency", "to", "bind", "to", "container", "with", "attr_name", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L143-L150
train
nameko/nameko
nameko/extensions.py
ProviderCollector.wait_for_providers
def wait_for_providers(self): """ Wait for any providers registered with the collector to have unregistered. Returns immediately if no providers were ever registered. """ if self._providers_registered: _log.debug('waiting for providers to unregister %s', self) ...
python
def wait_for_providers(self): """ Wait for any providers registered with the collector to have unregistered. Returns immediately if no providers were ever registered. """ if self._providers_registered: _log.debug('waiting for providers to unregister %s', self) ...
[ "def", "wait_for_providers", "(", "self", ")", ":", "if", "self", ".", "_providers_registered", ":", "_log", ".", "debug", "(", "'waiting for providers to unregister %s'", ",", "self", ")", "self", ".", "_last_provider_unregistered", ".", "wait", "(", ")", "_log",...
Wait for any providers registered with the collector to have unregistered. Returns immediately if no providers were ever registered.
[ "Wait", "for", "any", "providers", "registered", "with", "the", "collector", "to", "have", "unregistered", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L231-L240
train
nameko/nameko
nameko/extensions.py
Entrypoint.bind
def bind(self, container, method_name): """ Get an instance of this Entrypoint to bind to `container` with `method_name`. """ instance = super(Entrypoint, self).bind(container) instance.method_name = method_name return instance
python
def bind(self, container, method_name): """ Get an instance of this Entrypoint to bind to `container` with `method_name`. """ instance = super(Entrypoint, self).bind(container) instance.method_name = method_name return instance
[ "def", "bind", "(", "self", ",", "container", ",", "method_name", ")", ":", "instance", "=", "super", "(", "Entrypoint", ",", "self", ")", ".", "bind", "(", "container", ")", "instance", ".", "method_name", "=", "method_name", "return", "instance" ]
Get an instance of this Entrypoint to bind to `container` with `method_name`.
[ "Get", "an", "instance", "of", "this", "Entrypoint", "to", "bind", "to", "container", "with", "method_name", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L294-L300
train
nameko/nameko
nameko/containers.py
ServiceContainer.start
def start(self): """ Start a container by starting all of its extensions. """ _log.debug('starting %s', self) self.started = True with _log_time('started %s', self): self.extensions.all.setup() self.extensions.all.start()
python
def start(self): """ Start a container by starting all of its extensions. """ _log.debug('starting %s', self) self.started = True with _log_time('started %s', self): self.extensions.all.setup() self.extensions.all.start()
[ "def", "start", "(", "self", ")", ":", "_log", ".", "debug", "(", "'starting %s'", ",", "self", ")", "self", ".", "started", "=", "True", "with", "_log_time", "(", "'started %s'", ",", "self", ")", ":", "self", ".", "extensions", ".", "all", ".", "se...
Start a container by starting all of its extensions.
[ "Start", "a", "container", "by", "starting", "all", "of", "its", "extensions", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L182-L190
train
nameko/nameko
nameko/containers.py
ServiceContainer.stop
def stop(self): """ Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have s...
python
def stop(self): """ Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have s...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_died", ".", "ready", "(", ")", ":", "_log", ".", "debug", "(", "'already stopped %s'", ",", "self", ")", "return", "if", "self", ".", "_being_killed", ":", "# this race condition can happen when a co...
Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have stopped. After all e...
[ "Stop", "the", "container", "gracefully", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L192-L252
train
nameko/nameko
nameko/containers.py
ServiceContainer.kill
def kill(self, exc_info=None): """ Kill the container in a semi-graceful way. Entrypoints are killed, followed by any active worker threads. Next, dependencies are killed. Finally, any remaining managed threads are killed. If ``exc_info`` is provided, the exception will be rais...
python
def kill(self, exc_info=None): """ Kill the container in a semi-graceful way. Entrypoints are killed, followed by any active worker threads. Next, dependencies are killed. Finally, any remaining managed threads are killed. If ``exc_info`` is provided, the exception will be rais...
[ "def", "kill", "(", "self", ",", "exc_info", "=", "None", ")", ":", "if", "self", ".", "_being_killed", ":", "# this happens if a managed thread exits with an exception", "# while the container is being killed or if multiple errors", "# happen simultaneously", "_log", ".", "d...
Kill the container in a semi-graceful way. Entrypoints are killed, followed by any active worker threads. Next, dependencies are killed. Finally, any remaining managed threads are killed. If ``exc_info`` is provided, the exception will be raised by :meth:`~wait``.
[ "Kill", "the", "container", "in", "a", "semi", "-", "graceful", "way", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L254-L303
train
nameko/nameko
nameko/containers.py
ServiceContainer.spawn_worker
def spawn_worker(self, entrypoint, args, kwargs, context_data=None, handle_result=None): """ Spawn a worker thread for running the service method decorated by `entrypoint`. ``args`` and ``kwargs`` are used as parameters for the service method. ``context_data`` is u...
python
def spawn_worker(self, entrypoint, args, kwargs, context_data=None, handle_result=None): """ Spawn a worker thread for running the service method decorated by `entrypoint`. ``args`` and ``kwargs`` are used as parameters for the service method. ``context_data`` is u...
[ "def", "spawn_worker", "(", "self", ",", "entrypoint", ",", "args", ",", "kwargs", ",", "context_data", "=", "None", ",", "handle_result", "=", "None", ")", ":", "if", "self", ".", "_being_killed", ":", "_log", ".", "info", "(", "\"Worker spawn prevented due...
Spawn a worker thread for running the service method decorated by `entrypoint`. ``args`` and ``kwargs`` are used as parameters for the service method. ``context_data`` is used to initialize a ``WorkerContext``. ``handle_result`` is an optional function which may be passed in b...
[ "Spawn", "a", "worker", "thread", "for", "running", "the", "service", "method", "decorated", "by", "entrypoint", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L318-L350
train
nameko/nameko
nameko/containers.py
ServiceContainer._kill_worker_threads
def _kill_worker_threads(self): """ Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker` """ num_workers = len(self._worker_threads) if num_workers: _log.warning('killing %s active workers(s)', num_workers) for worker_ct...
python
def _kill_worker_threads(self): """ Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker` """ num_workers = len(self._worker_threads) if num_workers: _log.warning('killing %s active workers(s)', num_workers) for worker_ct...
[ "def", "_kill_worker_threads", "(", "self", ")", ":", "num_workers", "=", "len", "(", "self", ".", "_worker_threads", ")", "if", "num_workers", ":", "_log", ".", "warning", "(", "'killing %s active workers(s)'", ",", "num_workers", ")", "for", "worker_ctx", ",",...
Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker`
[ "Kill", "any", "currently", "executing", "worker", "threads", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L439-L450
train
nameko/nameko
nameko/containers.py
ServiceContainer._kill_managed_threads
def _kill_managed_threads(self): """ Kill any currently executing managed threads. See :meth:`ServiceContainer.spawn_managed_thread` """ num_threads = len(self._managed_threads) if num_threads: _log.warning('killing %s managed thread(s)', num_threads) fo...
python
def _kill_managed_threads(self): """ Kill any currently executing managed threads. See :meth:`ServiceContainer.spawn_managed_thread` """ num_threads = len(self._managed_threads) if num_threads: _log.warning('killing %s managed thread(s)', num_threads) fo...
[ "def", "_kill_managed_threads", "(", "self", ")", ":", "num_threads", "=", "len", "(", "self", ".", "_managed_threads", ")", "if", "num_threads", ":", "_log", ".", "warning", "(", "'killing %s managed thread(s)'", ",", "num_threads", ")", "for", "gt", ",", "id...
Kill any currently executing managed threads. See :meth:`ServiceContainer.spawn_managed_thread`
[ "Kill", "any", "currently", "executing", "managed", "threads", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L452-L463
train
nameko/nameko
nameko/standalone/rpc.py
ConsumeEvent.wait
def wait(self): """ Makes a blocking call to its queue_consumer until the message with the given correlation_id has been processed. By the time the blocking call exits, self.send() will have been called with the body of the received message (see :meth:`~nameko.rpc.ReplyListener....
python
def wait(self): """ Makes a blocking call to its queue_consumer until the message with the given correlation_id has been processed. By the time the blocking call exits, self.send() will have been called with the body of the received message (see :meth:`~nameko.rpc.ReplyListener....
[ "def", "wait", "(", "self", ")", ":", "# disconnected before starting to wait", "if", "self", ".", "exception", ":", "raise", "self", ".", "exception", "if", "self", ".", "queue_consumer", ".", "stopped", ":", "raise", "RuntimeError", "(", "\"This consumer has bee...
Makes a blocking call to its queue_consumer until the message with the given correlation_id has been processed. By the time the blocking call exits, self.send() will have been called with the body of the received message (see :meth:`~nameko.rpc.ReplyListener.handle_message`). E...
[ "Makes", "a", "blocking", "call", "to", "its", "queue_consumer", "until", "the", "message", "with", "the", "given", "correlation_id", "has", "been", "processed", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/rpc.py#L37-L73
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.select_form
def select_form(self, selector="form", nr=0): """Select a form in the current page. :param selector: CSS selector or a bs4.element.Tag object to identify the form to select. If not specified, ``selector`` defaults to "form", which is useful if, e.g., there is only on...
python
def select_form(self, selector="form", nr=0): """Select a form in the current page. :param selector: CSS selector or a bs4.element.Tag object to identify the form to select. If not specified, ``selector`` defaults to "form", which is useful if, e.g., there is only on...
[ "def", "select_form", "(", "self", ",", "selector", "=", "\"form\"", ",", "nr", "=", "0", ")", ":", "if", "isinstance", "(", "selector", ",", "bs4", ".", "element", ".", "Tag", ")", ":", "if", "selector", ".", "name", "!=", "\"form\"", ":", "raise", ...
Select a form in the current page. :param selector: CSS selector or a bs4.element.Tag object to identify the form to select. If not specified, ``selector`` defaults to "form", which is useful if, e.g., there is only one form on the page. For ``selector`` syntax, ...
[ "Select", "a", "form", "in", "the", "current", "page", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L177-L210
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.links
def links(self, url_regex=None, link_text=None, *args, **kwargs): """Return links in the page, as a list of bs4.element.Tag objects. To return links matching specific criteria, specify ``url_regex`` to match the *href*-attribute, or ``link_text`` to match the *text*-attribute of the Tag...
python
def links(self, url_regex=None, link_text=None, *args, **kwargs): """Return links in the page, as a list of bs4.element.Tag objects. To return links matching specific criteria, specify ``url_regex`` to match the *href*-attribute, or ``link_text`` to match the *text*-attribute of the Tag...
[ "def", "links", "(", "self", ",", "url_regex", "=", "None", ",", "link_text", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "all_links", "=", "self", ".", "get_current_page", "(", ")", ".", "find_all", "(", "'a'", ",", "href", "...
Return links in the page, as a list of bs4.element.Tag objects. To return links matching specific criteria, specify ``url_regex`` to match the *href*-attribute, or ``link_text`` to match the *text*-attribute of the Tag. All other arguments are forwarded to the `.find_all() method in Bea...
[ "Return", "links", "in", "the", "page", "as", "a", "list", "of", "bs4", ".", "element", ".", "Tag", "objects", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L249-L266
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.find_link
def find_link(self, *args, **kwargs): """Find and return a link, as a bs4.element.Tag object. The search can be refined by specifying any argument that is accepted by :func:`links`. If several links match, return the first one found. If no link is found, raise :class:`LinkNotFoundError...
python
def find_link(self, *args, **kwargs): """Find and return a link, as a bs4.element.Tag object. The search can be refined by specifying any argument that is accepted by :func:`links`. If several links match, return the first one found. If no link is found, raise :class:`LinkNotFoundError...
[ "def", "find_link", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "links", "=", "self", ".", "links", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "len", "(", "links", ")", "==", "0", ":", "raise", "LinkNotFoundError"...
Find and return a link, as a bs4.element.Tag object. The search can be refined by specifying any argument that is accepted by :func:`links`. If several links match, return the first one found. If no link is found, raise :class:`LinkNotFoundError`.
[ "Find", "and", "return", "a", "link", "as", "a", "bs4", ".", "element", ".", "Tag", "object", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L268-L280
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.follow_link
def follow_link(self, link=None, *args, **kwargs): """Follow a link. If ``link`` is a bs4.element.Tag (i.e. from a previous call to :func:`links` or :func:`find_link`), then follow the link. If ``link`` doesn't have a *href*-attribute or is None, treat ``link`` as a url_regex a...
python
def follow_link(self, link=None, *args, **kwargs): """Follow a link. If ``link`` is a bs4.element.Tag (i.e. from a previous call to :func:`links` or :func:`find_link`), then follow the link. If ``link`` doesn't have a *href*-attribute or is None, treat ``link`` as a url_regex a...
[ "def", "follow_link", "(", "self", ",", "link", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "link", "=", "self", ".", "_find_link_internal", "(", "link", ",", "args", ",", "kwargs", ")", "referer", "=", "self", ".", "get_url", ...
Follow a link. If ``link`` is a bs4.element.Tag (i.e. from a previous call to :func:`links` or :func:`find_link`), then follow the link. If ``link`` doesn't have a *href*-attribute or is None, treat ``link`` as a url_regex and look it up with :func:`find_link`. Any additional a...
[ "Follow", "a", "link", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L312-L333
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/form.py
Form.set_input
def set_input(self, data): """Fill-in a set of fields in a form. Example: filling-in a login/password form .. code-block:: python form.set_input({"login": username, "password": password}) This will find the input element named "login" and give it the value ``userna...
python
def set_input(self, data): """Fill-in a set of fields in a form. Example: filling-in a login/password form .. code-block:: python form.set_input({"login": username, "password": password}) This will find the input element named "login" and give it the value ``userna...
[ "def", "set_input", "(", "self", ",", "data", ")", ":", "for", "(", "name", ",", "value", ")", "in", "data", ".", "items", "(", ")", ":", "i", "=", "self", ".", "form", ".", "find", "(", "\"input\"", ",", "{", "\"name\"", ":", "name", "}", ")",...
Fill-in a set of fields in a form. Example: filling-in a login/password form .. code-block:: python form.set_input({"login": username, "password": password}) This will find the input element named "login" and give it the value ``username``, and the input element named "pas...
[ "Fill", "-", "in", "a", "set", "of", "fields", "in", "a", "form", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L52-L70
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/form.py
Form.new_control
def new_control(self, type, name, value, **kwargs): """Add a new input element to the form. The arguments set the attributes of the new element. """ old_input = self.form.find_all('input', {'name': name}) for old in old_input: old.decompose() old_textarea = s...
python
def new_control(self, type, name, value, **kwargs): """Add a new input element to the form. The arguments set the attributes of the new element. """ old_input = self.form.find_all('input', {'name': name}) for old in old_input: old.decompose() old_textarea = s...
[ "def", "new_control", "(", "self", ",", "type", ",", "name", ",", "value", ",", "*", "*", "kwargs", ")", ":", "old_input", "=", "self", ".", "form", ".", "find_all", "(", "'input'", ",", "{", "'name'", ":", "name", "}", ")", "for", "old", "in", "...
Add a new input element to the form. The arguments set the attributes of the new element.
[ "Add", "a", "new", "input", "element", "to", "the", "form", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L280-L303
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/form.py
Form.print_summary
def print_summary(self): """Print a summary of the form. May help finding which fields need to be filled-in. """ for input in self.form.find_all( ("input", "textarea", "select", "button")): input_copy = copy.copy(input) # Text between the opening ...
python
def print_summary(self): """Print a summary of the form. May help finding which fields need to be filled-in. """ for input in self.form.find_all( ("input", "textarea", "select", "button")): input_copy = copy.copy(input) # Text between the opening ...
[ "def", "print_summary", "(", "self", ")", ":", "for", "input", "in", "self", ".", "form", ".", "find_all", "(", "(", "\"input\"", ",", "\"textarea\"", ",", "\"select\"", ",", "\"button\"", ")", ")", ":", "input_copy", "=", "copy", ".", "copy", "(", "in...
Print a summary of the form. May help finding which fields need to be filled-in.
[ "Print", "a", "summary", "of", "the", "form", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L370-L383
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.__looks_like_html
def __looks_like_html(response): """Guesses entity type when Content-Type header is missing. Since Content-Type is not strictly required, some servers leave it out. """ text = response.text.lstrip().lower() return text.startswith('<html') or text.startswith('<!doctype')
python
def __looks_like_html(response): """Guesses entity type when Content-Type header is missing. Since Content-Type is not strictly required, some servers leave it out. """ text = response.text.lstrip().lower() return text.startswith('<html') or text.startswith('<!doctype')
[ "def", "__looks_like_html", "(", "response", ")", ":", "text", "=", "response", ".", "text", ".", "lstrip", "(", ")", ".", "lower", "(", ")", "return", "text", ".", "startswith", "(", "'<html'", ")", "or", "text", ".", "startswith", "(", "'<!doctype'", ...
Guesses entity type when Content-Type header is missing. Since Content-Type is not strictly required, some servers leave it out.
[ "Guesses", "entity", "type", "when", "Content", "-", "Type", "header", "is", "missing", ".", "Since", "Content", "-", "Type", "is", "not", "strictly", "required", "some", "servers", "leave", "it", "out", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L58-L63
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.add_soup
def add_soup(response, soup_config): """Attaches a soup object to a requests response.""" if ("text/html" in response.headers.get("Content-Type", "") or Browser.__looks_like_html(response)): response.soup = bs4.BeautifulSoup(response.content, **soup_config) else: ...
python
def add_soup(response, soup_config): """Attaches a soup object to a requests response.""" if ("text/html" in response.headers.get("Content-Type", "") or Browser.__looks_like_html(response)): response.soup = bs4.BeautifulSoup(response.content, **soup_config) else: ...
[ "def", "add_soup", "(", "response", ",", "soup_config", ")", ":", "if", "(", "\"text/html\"", "in", "response", ".", "headers", ".", "get", "(", "\"Content-Type\"", ",", "\"\"", ")", "or", "Browser", ".", "__looks_like_html", "(", "response", ")", ")", ":"...
Attaches a soup object to a requests response.
[ "Attaches", "a", "soup", "object", "to", "a", "requests", "response", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L66-L72
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.set_user_agent
def set_user_agent(self, user_agent): """Replaces the current user agent in the requests session headers.""" # set a default user_agent if not specified if user_agent is None: requests_ua = requests.utils.default_user_agent() user_agent = '%s (%s/%s)' % (requests_ua, __ti...
python
def set_user_agent(self, user_agent): """Replaces the current user agent in the requests session headers.""" # set a default user_agent if not specified if user_agent is None: requests_ua = requests.utils.default_user_agent() user_agent = '%s (%s/%s)' % (requests_ua, __ti...
[ "def", "set_user_agent", "(", "self", ",", "user_agent", ")", ":", "# set a default user_agent if not specified", "if", "user_agent", "is", "None", ":", "requests_ua", "=", "requests", ".", "utils", ".", "default_user_agent", "(", ")", "user_agent", "=", "'%s (%s/%s...
Replaces the current user agent in the requests session headers.
[ "Replaces", "the", "current", "user", "agent", "in", "the", "requests", "session", "headers", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L89-L97
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser._request
def _request(self, form, url=None, **kwargs): """Extract input data from the form to pass to a Requests session.""" method = str(form.get("method", "get")) action = form.get("action") url = urllib.parse.urljoin(url, action) if url is None: # This happens when both `action` and `...
python
def _request(self, form, url=None, **kwargs): """Extract input data from the form to pass to a Requests session.""" method = str(form.get("method", "get")) action = form.get("action") url = urllib.parse.urljoin(url, action) if url is None: # This happens when both `action` and `...
[ "def", "_request", "(", "self", ",", "form", ",", "url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "method", "=", "str", "(", "form", ".", "get", "(", "\"method\"", ",", "\"get\"", ")", ")", "action", "=", "form", ".", "get", "(", "\"action...
Extract input data from the form to pass to a Requests session.
[ "Extract", "input", "data", "from", "the", "form", "to", "pass", "to", "a", "Requests", "session", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L142-L226
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.submit
def submit(self, form, url=None, **kwargs): """Prepares and sends a form request. NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is recommended to use :func:`StatefulBrowser.submit_selected` instead of this method so that the browser state is correctly updated. ...
python
def submit(self, form, url=None, **kwargs): """Prepares and sends a form request. NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is recommended to use :func:`StatefulBrowser.submit_selected` instead of this method so that the browser state is correctly updated. ...
[ "def", "submit", "(", "self", ",", "form", ",", "url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "form", ",", "Form", ")", ":", "form", "=", "form", ".", "form", "response", "=", "self", ".", "_request", "(", "form"...
Prepares and sends a form request. NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is recommended to use :func:`StatefulBrowser.submit_selected` instead of this method so that the browser state is correctly updated. :param form: The filled-out form. :param u...
[ "Prepares", "and", "sends", "a", "form", "request", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L228-L249
train
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.close
def close(self): """Close the current session, if still open.""" if self.session is not None: self.session.cookies.clear() self.session.close() self.session = None
python
def close(self): """Close the current session, if still open.""" if self.session is not None: self.session.cookies.clear() self.session.close() self.session = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "session", "is", "not", "None", ":", "self", ".", "session", ".", "cookies", ".", "clear", "(", ")", "self", ".", "session", ".", "close", "(", ")", "self", ".", "session", "=", "None" ]
Close the current session, if still open.
[ "Close", "the", "current", "session", "if", "still", "open", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L260-L265
train
MechanicalSoup/MechanicalSoup
setup.py
requirements_from_file
def requirements_from_file(filename): """Parses a pip requirements file into a list.""" return [line.strip() for line in open(filename, 'r') if line.strip() and not line.strip().startswith('--')]
python
def requirements_from_file(filename): """Parses a pip requirements file into a list.""" return [line.strip() for line in open(filename, 'r') if line.strip() and not line.strip().startswith('--')]
[ "def", "requirements_from_file", "(", "filename", ")", ":", "return", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "open", "(", "filename", ",", "'r'", ")", "if", "line", ".", "strip", "(", ")", "and", "not", "line", ".", "strip", "(", ...
Parses a pip requirements file into a list.
[ "Parses", "a", "pip", "requirements", "file", "into", "a", "list", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/setup.py#L9-L12
train
MechanicalSoup/MechanicalSoup
setup.py
read
def read(fname, URL, URLImage): """Read the content of a file.""" readme = open(path.join(path.dirname(__file__), fname)).read() if hasattr(readme, 'decode'): # In Python 3, turn bytes into str. readme = readme.decode('utf8') # turn relative links into absolute ones readme = re.sub(r...
python
def read(fname, URL, URLImage): """Read the content of a file.""" readme = open(path.join(path.dirname(__file__), fname)).read() if hasattr(readme, 'decode'): # In Python 3, turn bytes into str. readme = readme.decode('utf8') # turn relative links into absolute ones readme = re.sub(r...
[ "def", "read", "(", "fname", ",", "URL", ",", "URLImage", ")", ":", "readme", "=", "open", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "fname", ")", ")", ".", "read", "(", ")", "if", "hasattr", "(", "readme",...
Read the content of a file.
[ "Read", "the", "content", "of", "a", "file", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/setup.py#L15-L27
train
DmitryUlyanov/Multicore-TSNE
tsne-embedding.py
imscatter
def imscatter(images, positions): ''' Creates a scatter plot, where each plot is shown by corresponding image ''' positions = np.array(positions) bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images]) tops = bottoms + np.array([im.shape[1] for im in images]) lefts =...
python
def imscatter(images, positions): ''' Creates a scatter plot, where each plot is shown by corresponding image ''' positions = np.array(positions) bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images]) tops = bottoms + np.array([im.shape[1] for im in images]) lefts =...
[ "def", "imscatter", "(", "images", ",", "positions", ")", ":", "positions", "=", "np", ".", "array", "(", "positions", ")", "bottoms", "=", "positions", "[", ":", ",", "1", "]", "-", "np", ".", "array", "(", "[", "im", ".", "shape", "[", "1", "]"...
Creates a scatter plot, where each plot is shown by corresponding image
[ "Creates", "a", "scatter", "plot", "where", "each", "plot", "is", "shown", "by", "corresponding", "image" ]
62dedde52469f3a0aeb22fdd7bce2538f17f77ef
https://github.com/DmitryUlyanov/Multicore-TSNE/blob/62dedde52469f3a0aeb22fdd7bce2538f17f77ef/tsne-embedding.py#L9-L42
train
Blueqat/Blueqat
blueqat/opt.py
pauli
def pauli(qubo): """ Convert to pauli operators of universal gate model. Requires blueqat. """ from blueqat.pauli import qubo_bit h = 0.0 assert all(len(q) == len(qubo) for q in qubo) for i in range(len(qubo)): h += qubo_bit(i) * qubo[i][i] for j in range(i + 1, len(qubo)): h += qubo_bit(i)*qubo_bit(j) *...
python
def pauli(qubo): """ Convert to pauli operators of universal gate model. Requires blueqat. """ from blueqat.pauli import qubo_bit h = 0.0 assert all(len(q) == len(qubo) for q in qubo) for i in range(len(qubo)): h += qubo_bit(i) * qubo[i][i] for j in range(i + 1, len(qubo)): h += qubo_bit(i)*qubo_bit(j) *...
[ "def", "pauli", "(", "qubo", ")", ":", "from", "blueqat", ".", "pauli", "import", "qubo_bit", "h", "=", "0.0", "assert", "all", "(", "len", "(", "q", ")", "==", "len", "(", "qubo", ")", "for", "q", "in", "qubo", ")", "for", "i", "in", "range", ...
Convert to pauli operators of universal gate model. Requires blueqat.
[ "Convert", "to", "pauli", "operators", "of", "universal", "gate", "model", ".", "Requires", "blueqat", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L18-L30
train
Blueqat/Blueqat
blueqat/opt.py
opt.plot
def plot(self): """ Draws energy chart using matplotlib. """ import matplotlib.pyplot as plt plt.plot(self.E) plt.show()
python
def plot(self): """ Draws energy chart using matplotlib. """ import matplotlib.pyplot as plt plt.plot(self.E) plt.show()
[ "def", "plot", "(", "self", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "plt", ".", "plot", "(", "self", ".", "E", ")", "plt", ".", "show", "(", ")" ]
Draws energy chart using matplotlib.
[ "Draws", "energy", "chart", "using", "matplotlib", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L366-L372
train
Blueqat/Blueqat
blueqat/opt.py
Opt.run
def run(self,shots=1,targetT=0.02,verbose=False): """ Run SA with provided QUBO. Set qubo attribute in advance of calling this method. """ if self.qubo != []: self.qi() J = self.reJ() N = len(J) itetemp = 100 Rtemp = 0.75 self.E = [] qq = [] for i in range(shots): T = self.Ts q = np....
python
def run(self,shots=1,targetT=0.02,verbose=False): """ Run SA with provided QUBO. Set qubo attribute in advance of calling this method. """ if self.qubo != []: self.qi() J = self.reJ() N = len(J) itetemp = 100 Rtemp = 0.75 self.E = [] qq = [] for i in range(shots): T = self.Ts q = np....
[ "def", "run", "(", "self", ",", "shots", "=", "1", ",", "targetT", "=", "0.02", ",", "verbose", "=", "False", ")", ":", "if", "self", ".", "qubo", "!=", "[", "]", ":", "self", ".", "qi", "(", ")", "J", "=", "self", ".", "reJ", "(", ")", "N"...
Run SA with provided QUBO. Set qubo attribute in advance of calling this method.
[ "Run", "SA", "with", "provided", "QUBO", ".", "Set", "qubo", "attribute", "in", "advance", "of", "calling", "this", "method", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L554-L594
train
Blueqat/Blueqat
blueqat/gate.py
Gate._str_targets
def _str_targets(self): """Returns printable string of targets.""" def _slice_to_str(obj): if isinstance(obj, slice): start = "" if obj.start is None else str(obj.start.__index__()) stop = "" if obj.stop is None else str(obj.stop.__index__()) i...
python
def _str_targets(self): """Returns printable string of targets.""" def _slice_to_str(obj): if isinstance(obj, slice): start = "" if obj.start is None else str(obj.start.__index__()) stop = "" if obj.stop is None else str(obj.stop.__index__()) i...
[ "def", "_str_targets", "(", "self", ")", ":", "def", "_slice_to_str", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "slice", ")", ":", "start", "=", "\"\"", "if", "obj", ".", "start", "is", "None", "else", "str", "(", "obj", ".", "star...
Returns printable string of targets.
[ "Returns", "printable", "string", "of", "targets", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/gate.py#L36-L53
train
Blueqat/Blueqat
blueqat/vqe.py
get_scipy_minimizer
def get_scipy_minimizer(**kwargs): """Get minimizer which uses `scipy.optimize.minimize`""" def minimizer(objective, n_params): params = [random.random() for _ in range(n_params)] result = scipy_minimizer(objective, params, **kwargs) return result.x return minimizer
python
def get_scipy_minimizer(**kwargs): """Get minimizer which uses `scipy.optimize.minimize`""" def minimizer(objective, n_params): params = [random.random() for _ in range(n_params)] result = scipy_minimizer(objective, params, **kwargs) return result.x return minimizer
[ "def", "get_scipy_minimizer", "(", "*", "*", "kwargs", ")", ":", "def", "minimizer", "(", "objective", ",", "n_params", ")", ":", "params", "=", "[", "random", ".", "random", "(", ")", "for", "_", "in", "range", "(", "n_params", ")", "]", "result", "...
Get minimizer which uses `scipy.optimize.minimize`
[ "Get", "minimizer", "which", "uses", "scipy", ".", "optimize", ".", "minimize" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L158-L164
train
Blueqat/Blueqat
blueqat/vqe.py
expect
def expect(qubits, meas): "For the VQE simulation without sampling." result = {} i = np.arange(len(qubits)) meas = tuple(meas) def to_mask(n): return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0) def to_key(k): return tuple(1 if k & (1 ...
python
def expect(qubits, meas): "For the VQE simulation without sampling." result = {} i = np.arange(len(qubits)) meas = tuple(meas) def to_mask(n): return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0) def to_key(k): return tuple(1 if k & (1 ...
[ "def", "expect", "(", "qubits", ",", "meas", ")", ":", "result", "=", "{", "}", "i", "=", "np", ".", "arange", "(", "len", "(", "qubits", ")", ")", "meas", "=", "tuple", "(", "meas", ")", "def", "to_mask", "(", "n", ")", ":", "return", "reduce"...
For the VQE simulation without sampling.
[ "For", "the", "VQE", "simulation", "without", "sampling", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L166-L185
train
Blueqat/Blueqat
blueqat/vqe.py
non_sampling_sampler
def non_sampling_sampler(circuit, meas): """Calculate the expectations without sampling.""" meas = tuple(meas) n_qubits = circuit.n_qubits return expect(circuit.run(returns="statevector"), meas)
python
def non_sampling_sampler(circuit, meas): """Calculate the expectations without sampling.""" meas = tuple(meas) n_qubits = circuit.n_qubits return expect(circuit.run(returns="statevector"), meas)
[ "def", "non_sampling_sampler", "(", "circuit", ",", "meas", ")", ":", "meas", "=", "tuple", "(", "meas", ")", "n_qubits", "=", "circuit", ".", "n_qubits", "return", "expect", "(", "circuit", ".", "run", "(", "returns", "=", "\"statevector\"", ")", ",", "...
Calculate the expectations without sampling.
[ "Calculate", "the", "expectations", "without", "sampling", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L187-L191
train
Blueqat/Blueqat
blueqat/vqe.py
get_measurement_sampler
def get_measurement_sampler(n_sample, run_options=None): """Returns a function which get the expectations by sampling the measured circuit""" if run_options is None: run_options = {} def sampling_by_measurement(circuit, meas): def reduce_bits(bits, meas): bits = [int(x) for x in...
python
def get_measurement_sampler(n_sample, run_options=None): """Returns a function which get the expectations by sampling the measured circuit""" if run_options is None: run_options = {} def sampling_by_measurement(circuit, meas): def reduce_bits(bits, meas): bits = [int(x) for x in...
[ "def", "get_measurement_sampler", "(", "n_sample", ",", "run_options", "=", "None", ")", ":", "if", "run_options", "is", "None", ":", "run_options", "=", "{", "}", "def", "sampling_by_measurement", "(", "circuit", ",", "meas", ")", ":", "def", "reduce_bits", ...
Returns a function which get the expectations by sampling the measured circuit
[ "Returns", "a", "function", "which", "get", "the", "expectations", "by", "sampling", "the", "measured", "circuit" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L193-L209
train
Blueqat/Blueqat
blueqat/vqe.py
get_state_vector_sampler
def get_state_vector_sampler(n_sample): """Returns a function which get the expectations by sampling the state vector""" def sampling_by_measurement(circuit, meas): val = 0.0 e = expect(circuit.run(returns="statevector"), meas) bits, probs = zip(*e.items()) dists = np.random.mult...
python
def get_state_vector_sampler(n_sample): """Returns a function which get the expectations by sampling the state vector""" def sampling_by_measurement(circuit, meas): val = 0.0 e = expect(circuit.run(returns="statevector"), meas) bits, probs = zip(*e.items()) dists = np.random.mult...
[ "def", "get_state_vector_sampler", "(", "n_sample", ")", ":", "def", "sampling_by_measurement", "(", "circuit", ",", "meas", ")", ":", "val", "=", "0.0", "e", "=", "expect", "(", "circuit", ".", "run", "(", "returns", "=", "\"statevector\"", ")", ",", "mea...
Returns a function which get the expectations by sampling the state vector
[ "Returns", "a", "function", "which", "get", "the", "expectations", "by", "sampling", "the", "state", "vector" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L211-L219
train
Blueqat/Blueqat
blueqat/vqe.py
get_qiskit_sampler
def get_qiskit_sampler(backend, **execute_kwargs): """Returns a function which get the expectation by sampling via Qiskit. This function requires `qiskit` module. """ try: import qiskit except ImportError: raise ImportError("blueqat.vqe.get_qiskit_sampler() requires qiskit. Please i...
python
def get_qiskit_sampler(backend, **execute_kwargs): """Returns a function which get the expectation by sampling via Qiskit. This function requires `qiskit` module. """ try: import qiskit except ImportError: raise ImportError("blueqat.vqe.get_qiskit_sampler() requires qiskit. Please i...
[ "def", "get_qiskit_sampler", "(", "backend", ",", "*", "*", "execute_kwargs", ")", ":", "try", ":", "import", "qiskit", "except", "ImportError", ":", "raise", "ImportError", "(", "\"blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.\""...
Returns a function which get the expectation by sampling via Qiskit. This function requires `qiskit` module.
[ "Returns", "a", "function", "which", "get", "the", "expectation", "by", "sampling", "via", "Qiskit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L221-L273
train
Blueqat/Blueqat
blueqat/vqe.py
AnsatzBase.get_energy
def get_energy(self, circuit, sampler): """Calculate energy from circuit and sampler.""" val = 0.0 for meas in self.hamiltonian: c = circuit.copy() for op in meas.ops: if op.op == "X": c.h[op.n] elif op.op == "Y": ...
python
def get_energy(self, circuit, sampler): """Calculate energy from circuit and sampler.""" val = 0.0 for meas in self.hamiltonian: c = circuit.copy() for op in meas.ops: if op.op == "X": c.h[op.n] elif op.op == "Y": ...
[ "def", "get_energy", "(", "self", ",", "circuit", ",", "sampler", ")", ":", "val", "=", "0.0", "for", "meas", "in", "self", ".", "hamiltonian", ":", "c", "=", "circuit", ".", "copy", "(", ")", "for", "op", "in", "meas", ".", "ops", ":", "if", "op...
Calculate energy from circuit and sampler.
[ "Calculate", "energy", "from", "circuit", "and", "sampler", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L36-L52
train
Blueqat/Blueqat
blueqat/vqe.py
AnsatzBase.get_objective
def get_objective(self, sampler): """Get an objective function to be optimized.""" def objective(params): circuit = self.get_circuit(params) circuit.make_cache() return self.get_energy(circuit, sampler) return objective
python
def get_objective(self, sampler): """Get an objective function to be optimized.""" def objective(params): circuit = self.get_circuit(params) circuit.make_cache() return self.get_energy(circuit, sampler) return objective
[ "def", "get_objective", "(", "self", ",", "sampler", ")", ":", "def", "objective", "(", "params", ")", ":", "circuit", "=", "self", ".", "get_circuit", "(", "params", ")", "circuit", ".", "make_cache", "(", ")", "return", "self", ".", "get_energy", "(", ...
Get an objective function to be optimized.
[ "Get", "an", "objective", "function", "to", "be", "optimized", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L54-L60
train
Blueqat/Blueqat
blueqat/vqe.py
VqeResult.get_probs
def get_probs(self, sampler=None, rerun=None, store=True): """Get probabilities.""" if rerun is None: rerun = sampler is not None if self._probs is not None and not rerun: return self._probs if sampler is None: sampler = self.vqe.sampler probs ...
python
def get_probs(self, sampler=None, rerun=None, store=True): """Get probabilities.""" if rerun is None: rerun = sampler is not None if self._probs is not None and not rerun: return self._probs if sampler is None: sampler = self.vqe.sampler probs ...
[ "def", "get_probs", "(", "self", ",", "sampler", "=", "None", ",", "rerun", "=", "None", ",", "store", "=", "True", ")", ":", "if", "rerun", "is", "None", ":", "rerun", "=", "sampler", "is", "not", "None", "if", "self", ".", "_probs", "is", "not", ...
Get probabilities.
[ "Get", "probabilities", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L113-L124
train
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend._run_gates
def _run_gates(self, gates, n_qubits, ctx): """Iterate gates and call backend's action for each gates""" for gate in gates: action = self._get_action(gate) if action is not None: ctx = action(gate, ctx) else: ctx = self._run_gates(gate....
python
def _run_gates(self, gates, n_qubits, ctx): """Iterate gates and call backend's action for each gates""" for gate in gates: action = self._get_action(gate) if action is not None: ctx = action(gate, ctx) else: ctx = self._run_gates(gate....
[ "def", "_run_gates", "(", "self", ",", "gates", ",", "n_qubits", ",", "ctx", ")", ":", "for", "gate", "in", "gates", ":", "action", "=", "self", ".", "_get_action", "(", "gate", ")", "if", "action", "is", "not", "None", ":", "ctx", "=", "action", "...
Iterate gates and call backend's action for each gates
[ "Iterate", "gates", "and", "call", "backend", "s", "action", "for", "each", "gates" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L45-L53
train
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend._run
def _run(self, gates, n_qubits, args, kwargs): """Default implementation of `Backend.run`. Backend developer shouldn't override this function, but override `run` instead of this. The default flow of running is: 1. preprocessing 2. call the gate action which defined in ba...
python
def _run(self, gates, n_qubits, args, kwargs): """Default implementation of `Backend.run`. Backend developer shouldn't override this function, but override `run` instead of this. The default flow of running is: 1. preprocessing 2. call the gate action which defined in ba...
[ "def", "_run", "(", "self", ",", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")", ":", "gates", ",", "ctx", "=", "self", ".", "_preprocess_run", "(", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")", "self", ".", "_run_gates", "(",...
Default implementation of `Backend.run`. Backend developer shouldn't override this function, but override `run` instead of this. The default flow of running is: 1. preprocessing 2. call the gate action which defined in backend 3. postprocessing Backend devel...
[ "Default", "implementation", "of", "Backend", ".", "run", ".", "Backend", "developer", "shouldn", "t", "override", "this", "function", "but", "override", "run", "instead", "of", "this", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L55-L73
train
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend.run
def run(self, gates, n_qubits, *args, **kwargs): """Run the backend.""" return self._run(gates, n_qubits, args, kwargs)
python
def run(self, gates, n_qubits, *args, **kwargs): """Run the backend.""" return self._run(gates, n_qubits, args, kwargs)
[ "def", "run", "(", "self", ",", "gates", ",", "n_qubits", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_run", "(", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")" ]
Run the backend.
[ "Run", "the", "backend", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L82-L84
train
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend._resolve_fallback
def _resolve_fallback(self, gates, n_qubits): """Resolve fallbacks and flatten gates.""" flattened = [] for g in gates: if self._has_action(g): flattened.append(g) else: flattened += self._resolve_fallback(g.fallback(n_qubits), n_qubits) ...
python
def _resolve_fallback(self, gates, n_qubits): """Resolve fallbacks and flatten gates.""" flattened = [] for g in gates: if self._has_action(g): flattened.append(g) else: flattened += self._resolve_fallback(g.fallback(n_qubits), n_qubits) ...
[ "def", "_resolve_fallback", "(", "self", ",", "gates", ",", "n_qubits", ")", ":", "flattened", "=", "[", "]", "for", "g", "in", "gates", ":", "if", "self", ".", "_has_action", "(", "g", ")", ":", "flattened", ".", "append", "(", "g", ")", "else", "...
Resolve fallbacks and flatten gates.
[ "Resolve", "fallbacks", "and", "flatten", "gates", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L95-L103
train
Blueqat/Blueqat
blueqat/backends/numpy_backend.py
_NumPyBackendContext.prepare
def prepare(self, cache): """Prepare to run next shot.""" if cache is not None: np.copyto(self.qubits, cache) else: self.qubits.fill(0.0) self.qubits[0] = 1.0 self.cregs = [0] * self.n_qubits
python
def prepare(self, cache): """Prepare to run next shot.""" if cache is not None: np.copyto(self.qubits, cache) else: self.qubits.fill(0.0) self.qubits[0] = 1.0 self.cregs = [0] * self.n_qubits
[ "def", "prepare", "(", "self", ",", "cache", ")", ":", "if", "cache", "is", "not", "None", ":", "np", ".", "copyto", "(", "self", ".", "qubits", ",", "cache", ")", "else", ":", "self", ".", "qubits", ".", "fill", "(", "0.0", ")", "self", ".", "...
Prepare to run next shot.
[ "Prepare", "to", "run", "next", "shot", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/numpy_backend.py#L38-L45
train
Blueqat/Blueqat
blueqat/backends/numpy_backend.py
_NumPyBackendContext.store_shot
def store_shot(self): """Store current cregs to shots_result""" def to_str(cregs): return ''.join(str(b) for b in cregs) key = to_str(self.cregs) self.shots_result[key] = self.shots_result.get(key, 0) + 1
python
def store_shot(self): """Store current cregs to shots_result""" def to_str(cregs): return ''.join(str(b) for b in cregs) key = to_str(self.cregs) self.shots_result[key] = self.shots_result.get(key, 0) + 1
[ "def", "store_shot", "(", "self", ")", ":", "def", "to_str", "(", "cregs", ")", ":", "return", "''", ".", "join", "(", "str", "(", "b", ")", "for", "b", "in", "cregs", ")", "key", "=", "to_str", "(", "self", ".", "cregs", ")", "self", ".", "sho...
Store current cregs to shots_result
[ "Store", "current", "cregs", "to", "shots_result" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/numpy_backend.py#L47-L52
train
Blueqat/Blueqat
blueqat/circuit.py
Circuit.copy
def copy(self, copy_backends=True, copy_default_backend=True, copy_cache=None, copy_history=None): """Copy the circuit. :params copy_backends :bool copy backends if True. copy_default_backend :bool copy default_backend if True. """ copied = Circuit(self.n_qu...
python
def copy(self, copy_backends=True, copy_default_backend=True, copy_cache=None, copy_history=None): """Copy the circuit. :params copy_backends :bool copy backends if True. copy_default_backend :bool copy default_backend if True. """ copied = Circuit(self.n_qu...
[ "def", "copy", "(", "self", ",", "copy_backends", "=", "True", ",", "copy_default_backend", "=", "True", ",", "copy_cache", "=", "None", ",", "copy_history", "=", "None", ")", ":", "copied", "=", "Circuit", "(", "self", ".", "n_qubits", ",", "self", ".",...
Copy the circuit. :params copy_backends :bool copy backends if True. copy_default_backend :bool copy default_backend if True.
[ "Copy", "the", "circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L127-L148
train
Blueqat/Blueqat
blueqat/circuit.py
Circuit.run
def run(self, *args, backend=None, **kwargs): """Run the circuit. `Circuit` have several backends. When `backend` parameter is specified, use specified backend, and otherwise, default backend is used. Other parameters are passed to the backend. The meaning of parameters are dep...
python
def run(self, *args, backend=None, **kwargs): """Run the circuit. `Circuit` have several backends. When `backend` parameter is specified, use specified backend, and otherwise, default backend is used. Other parameters are passed to the backend. The meaning of parameters are dep...
[ "def", "run", "(", "self", ",", "*", "args", ",", "backend", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "backend", "is", "None", ":", "if", "self", ".", "_default_backend", "is", "None", ":", "backend", "=", "self", ".", "__get_backend", ...
Run the circuit. `Circuit` have several backends. When `backend` parameter is specified, use specified backend, and otherwise, default backend is used. Other parameters are passed to the backend. The meaning of parameters are depends on the backend specifications. However, foll...
[ "Run", "the", "circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L150-L180
train
Blueqat/Blueqat
blueqat/circuit.py
Circuit.make_cache
def make_cache(self, backend=None): """Make a cache to reduce the time of run. Some backends may implemented it. This is temporary API. It may changed or deprecated.""" if backend is None: if self._default_backend is None: backend = DEFAULT_BACKEND_NAME e...
python
def make_cache(self, backend=None): """Make a cache to reduce the time of run. Some backends may implemented it. This is temporary API. It may changed or deprecated.""" if backend is None: if self._default_backend is None: backend = DEFAULT_BACKEND_NAME e...
[ "def", "make_cache", "(", "self", ",", "backend", "=", "None", ")", ":", "if", "backend", "is", "None", ":", "if", "self", ".", "_default_backend", "is", "None", ":", "backend", "=", "DEFAULT_BACKEND_NAME", "else", ":", "backend", "=", "self", ".", "_def...
Make a cache to reduce the time of run. Some backends may implemented it. This is temporary API. It may changed or deprecated.
[ "Make", "a", "cache", "to", "reduce", "the", "time", "of", "run", ".", "Some", "backends", "may", "implemented", "it", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L182-L191
train
Blueqat/Blueqat
blueqat/circuit.py
Circuit.set_default_backend
def set_default_backend(self, backend_name): """Set the default backend of this circuit. This setting is only applied for this circuit. If you want to change the default backend of all gates, use `BlueqatGlobalSetting.set_default_backend()`. After set the default backend by thi...
python
def set_default_backend(self, backend_name): """Set the default backend of this circuit. This setting is only applied for this circuit. If you want to change the default backend of all gates, use `BlueqatGlobalSetting.set_default_backend()`. After set the default backend by thi...
[ "def", "set_default_backend", "(", "self", ",", "backend_name", ")", ":", "if", "backend_name", "not", "in", "BACKENDS", ":", "raise", "ValueError", "(", "f\"Unknown backend '{backend_name}'.\"", ")", "self", ".", "_default_backend", "=", "backend_name" ]
Set the default backend of this circuit. This setting is only applied for this circuit. If you want to change the default backend of all gates, use `BlueqatGlobalSetting.set_default_backend()`. After set the default backend by this method, global setting is ignored even if `Blu...
[ "Set", "the", "default", "backend", "of", "this", "circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L201-L221
train
Blueqat/Blueqat
blueqat/circuit.py
BlueqatGlobalSetting.register_macro
def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None: """Register new macro to Circuit. Args: name (str): The name of macro. func (callable): The function to be called. allow_overwrite (bool, optional): If True, allow to overwrite the ...
python
def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None: """Register new macro to Circuit. Args: name (str): The name of macro. func (callable): The function to be called. allow_overwrite (bool, optional): If True, allow to overwrite the ...
[ "def", "register_macro", "(", "name", ":", "str", ",", "func", ":", "Callable", ",", "allow_overwrite", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "hasattr", "(", "Circuit", ",", "name", ")", ":", "if", "allow_overwrite", ":", "warnings", ...
Register new macro to Circuit. Args: name (str): The name of macro. func (callable): The function to be called. allow_overwrite (bool, optional): If True, allow to overwrite the existing macro. Otherwise, raise the ValueError. Raises: Val...
[ "Register", "new", "macro", "to", "Circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L267-L295
train
Blueqat/Blueqat
blueqat/circuit.py
BlueqatGlobalSetting.register_gate
def register_gate(name, gateclass, allow_overwrite=False): """Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. ...
python
def register_gate(name, gateclass, allow_overwrite=False): """Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. ...
[ "def", "register_gate", "(", "name", ",", "gateclass", ",", "allow_overwrite", "=", "False", ")", ":", "if", "hasattr", "(", "Circuit", ",", "name", ")", ":", "if", "allow_overwrite", ":", "warnings", ".", "warn", "(", "f\"Circuit has attribute `{name}`.\"", "...
Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. Otherwise, raise the ValueError. Raises: ValueE...
[ "Register", "new", "gate", "to", "gate", "set", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L312-L340
train
Blueqat/Blueqat
blueqat/circuit.py
BlueqatGlobalSetting.register_backend
def register_backend(name, backend, allow_overwrite=False): """Register new backend. Args: name (str): The name of backend. gateclass (type): The type object of backend allow_overwrite (bool, optional): If True, allow to overwrite the existing backend. ...
python
def register_backend(name, backend, allow_overwrite=False): """Register new backend. Args: name (str): The name of backend. gateclass (type): The type object of backend allow_overwrite (bool, optional): If True, allow to overwrite the existing backend. ...
[ "def", "register_backend", "(", "name", ",", "backend", ",", "allow_overwrite", "=", "False", ")", ":", "if", "hasattr", "(", "Circuit", ",", "\"run_with_\"", "+", "name", ")", ":", "if", "allow_overwrite", ":", "warnings", ".", "warn", "(", "f\"Circuit has ...
Register new backend. Args: name (str): The name of backend. gateclass (type): The type object of backend allow_overwrite (bool, optional): If True, allow to overwrite the existing backend. Otherwise, raise the ValueError. Raises: ValueEr...
[ "Register", "new", "backend", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L357-L378
train
Blueqat/Blueqat
examples/maxcut_qaoa.py
maxcut_qaoa
def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True): """Setup QAOA. :param n_step: The number of step of QAOA :param n_sample: The number of sampling time of each measurement in VQE. If None, use calculated ideal value. :param edges: The edges list of the gra...
python
def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True): """Setup QAOA. :param n_step: The number of step of QAOA :param n_sample: The number of sampling time of each measurement in VQE. If None, use calculated ideal value. :param edges: The edges list of the gra...
[ "def", "maxcut_qaoa", "(", "n_step", ",", "edges", ",", "minimizer", "=", "None", ",", "sampler", "=", "None", ",", "verbose", "=", "True", ")", ":", "sampler", "=", "sampler", "or", "vqe", ".", "non_sampling_sampler", "minimizer", "=", "minimizer", "or", ...
Setup QAOA. :param n_step: The number of step of QAOA :param n_sample: The number of sampling time of each measurement in VQE. If None, use calculated ideal value. :param edges: The edges list of the graph. :returns Vqe object
[ "Setup", "QAOA", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/examples/maxcut_qaoa.py#L3-L22
train
Blueqat/Blueqat
blueqat/pauli.py
pauli_from_char
def pauli_from_char(ch, n=0): """Make Pauli matrix from an character. Args: ch (str): "X" or "Y" or "Z" or "I". n (int, optional): Make Pauli matrix as n-th qubits. Returns: If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I Raises: ValueError: When ch is not "X", "Y", "Z...
python
def pauli_from_char(ch, n=0): """Make Pauli matrix from an character. Args: ch (str): "X" or "Y" or "Z" or "I". n (int, optional): Make Pauli matrix as n-th qubits. Returns: If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I Raises: ValueError: When ch is not "X", "Y", "Z...
[ "def", "pauli_from_char", "(", "ch", ",", "n", "=", "0", ")", ":", "ch", "=", "ch", ".", "upper", "(", ")", "if", "ch", "==", "\"I\"", ":", "return", "I", "if", "ch", "==", "\"X\"", ":", "return", "X", "(", "n", ")", "if", "ch", "==", "\"Y\""...
Make Pauli matrix from an character. Args: ch (str): "X" or "Y" or "Z" or "I". n (int, optional): Make Pauli matrix as n-th qubits. Returns: If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I Raises: ValueError: When ch is not "X", "Y", "Z" nor "I".
[ "Make", "Pauli", "matrix", "from", "an", "character", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L28-L50
train
Blueqat/Blueqat
blueqat/pauli.py
is_commutable
def is_commutable(expr1, expr2, eps=0.00000001): """Test whether expr1 and expr2 are commutable. Args: expr1 (Expr, Term or Pauli operator): Pauli's expression. expr2 (Expr, Term or Pauli operator): Pauli's expression. eps (float, optional): Machine epsilon. If |[expr1, expr...
python
def is_commutable(expr1, expr2, eps=0.00000001): """Test whether expr1 and expr2 are commutable. Args: expr1 (Expr, Term or Pauli operator): Pauli's expression. expr2 (Expr, Term or Pauli operator): Pauli's expression. eps (float, optional): Machine epsilon. If |[expr1, expr...
[ "def", "is_commutable", "(", "expr1", ",", "expr2", ",", "eps", "=", "0.00000001", ")", ":", "return", "sum", "(", "(", "x", "*", "x", ".", "conjugate", "(", ")", ")", ".", "real", "for", "x", "in", "commutator", "(", "expr1", ",", "expr2", ")", ...
Test whether expr1 and expr2 are commutable. Args: expr1 (Expr, Term or Pauli operator): Pauli's expression. expr2 (Expr, Term or Pauli operator): Pauli's expression. eps (float, optional): Machine epsilon. If |[expr1, expr2]| < eps, consider it is commutable. Returns: ...
[ "Test", "whether", "expr1", "and", "expr2", "are", "commutable", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L103-L115
train
Blueqat/Blueqat
blueqat/pauli.py
Term.from_pauli
def from_pauli(pauli, coeff=1.0): """Make new Term from an Pauli operator""" if pauli.is_identity or coeff == 0: return Term((), coeff) return Term((pauli,), coeff)
python
def from_pauli(pauli, coeff=1.0): """Make new Term from an Pauli operator""" if pauli.is_identity or coeff == 0: return Term((), coeff) return Term((pauli,), coeff)
[ "def", "from_pauli", "(", "pauli", ",", "coeff", "=", "1.0", ")", ":", "if", "pauli", ".", "is_identity", "or", "coeff", "==", "0", ":", "return", "Term", "(", "(", ")", ",", "coeff", ")", "return", "Term", "(", "(", "pauli", ",", ")", ",", "coef...
Make new Term from an Pauli operator
[ "Make", "new", "Term", "from", "an", "Pauli", "operator" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L281-L285
train
Blueqat/Blueqat
blueqat/pauli.py
Term.simplify
def simplify(self): """Simplify the Term.""" def mul(op1, op2): if op1 == "I": return 1.0, op2 if op2 == "I": return 1.0, op1 if op1 == op2: return 1.0, "I" if op1 == "X": return (-1j, "Z") if...
python
def simplify(self): """Simplify the Term.""" def mul(op1, op2): if op1 == "I": return 1.0, op2 if op2 == "I": return 1.0, op1 if op1 == op2: return 1.0, "I" if op1 == "X": return (-1j, "Z") if...
[ "def", "simplify", "(", "self", ")", ":", "def", "mul", "(", "op1", ",", "op2", ")", ":", "if", "op1", "==", "\"I\"", ":", "return", "1.0", ",", "op2", "if", "op2", "==", "\"I\"", ":", "return", "1.0", ",", "op1", "if", "op1", "==", "op2", ":",...
Simplify the Term.
[ "Simplify", "the", "Term", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L423-L460
train
Blueqat/Blueqat
blueqat/pauli.py
Term.append_to_circuit
def append_to_circuit(self, circuit, simplify=True): """Append Pauli gates to `Circuit`.""" if simplify: term = self.simplify() else: term = self for op in term.ops[::-1]: gate = op.op.lower() if gate != "i": getattr(circuit...
python
def append_to_circuit(self, circuit, simplify=True): """Append Pauli gates to `Circuit`.""" if simplify: term = self.simplify() else: term = self for op in term.ops[::-1]: gate = op.op.lower() if gate != "i": getattr(circuit...
[ "def", "append_to_circuit", "(", "self", ",", "circuit", ",", "simplify", "=", "True", ")", ":", "if", "simplify", ":", "term", "=", "self", ".", "simplify", "(", ")", "else", ":", "term", "=", "self", "for", "op", "in", "term", ".", "ops", "[", ":...
Append Pauli gates to `Circuit`.
[ "Append", "Pauli", "gates", "to", "Circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L470-L479
train
Blueqat/Blueqat
blueqat/pauli.py
Term.get_time_evolution
def get_time_evolution(self): """Get the function to append the time evolution of this term. Returns: function(circuit: Circuit, t: float): Add gates for time evolution to `circuit` with time `t` """ term = self.simplify() coeff = term.coeff i...
python
def get_time_evolution(self): """Get the function to append the time evolution of this term. Returns: function(circuit: Circuit, t: float): Add gates for time evolution to `circuit` with time `t` """ term = self.simplify() coeff = term.coeff i...
[ "def", "get_time_evolution", "(", "self", ")", ":", "term", "=", "self", ".", "simplify", "(", ")", "coeff", "=", "term", ".", "coeff", "if", "coeff", ".", "imag", ":", "raise", "ValueError", "(", "\"Not a real coefficient.\"", ")", "ops", "=", "term", "...
Get the function to append the time evolution of this term. Returns: function(circuit: Circuit, t: float): Add gates for time evolution to `circuit` with time `t`
[ "Get", "the", "function", "to", "append", "the", "time", "evolution", "of", "this", "term", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L481-L513
train
Blueqat/Blueqat
blueqat/pauli.py
Expr.is_identity
def is_identity(self): """If `self` is I, returns True, otherwise False.""" if not self.terms: return True return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0
python
def is_identity(self): """If `self` is I, returns True, otherwise False.""" if not self.terms: return True return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0
[ "def", "is_identity", "(", "self", ")", ":", "if", "not", "self", ".", "terms", ":", "return", "True", "return", "len", "(", "self", ".", "terms", ")", "==", "1", "and", "not", "self", ".", "terms", "[", "0", "]", ".", "ops", "and", "self", ".", ...
If `self` is I, returns True, otherwise False.
[ "If", "self", "is", "I", "returns", "True", "otherwise", "False", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L565-L569
train
Blueqat/Blueqat
blueqat/pauli.py
Expr.max_n
def max_n(self): """Returns the maximum index of Pauli matrices in the Term.""" return max(term.max_n() for term in self.terms if term.ops)
python
def max_n(self): """Returns the maximum index of Pauli matrices in the Term.""" return max(term.max_n() for term in self.terms if term.ops)
[ "def", "max_n", "(", "self", ")", ":", "return", "max", "(", "term", ".", "max_n", "(", ")", "for", "term", "in", "self", ".", "terms", "if", "term", ".", "ops", ")" ]
Returns the maximum index of Pauli matrices in the Term.
[ "Returns", "the", "maximum", "index", "of", "Pauli", "matrices", "in", "the", "Term", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L707-L709
train
Blueqat/Blueqat
blueqat/pauli.py
Expr.is_all_terms_commutable
def is_all_terms_commutable(self): """Test whether all terms are commutable. This function may very slow.""" return all(is_commutable(a, b) for a, b in combinations(self.terms, 2))
python
def is_all_terms_commutable(self): """Test whether all terms are commutable. This function may very slow.""" return all(is_commutable(a, b) for a, b in combinations(self.terms, 2))
[ "def", "is_all_terms_commutable", "(", "self", ")", ":", "return", "all", "(", "is_commutable", "(", "a", ",", "b", ")", "for", "a", ",", "b", "in", "combinations", "(", "self", ".", "terms", ",", "2", ")", ")" ]
Test whether all terms are commutable. This function may very slow.
[ "Test", "whether", "all", "terms", "are", "commutable", ".", "This", "function", "may", "very", "slow", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L724-L726
train
Blueqat/Blueqat
blueqat/pauli.py
Expr.simplify
def simplify(self): """Simplify the Expr.""" d = defaultdict(float) for term in self.terms: term = term.simplify() d[term.ops] += term.coeff return Expr.from_terms_iter( Term.from_ops_iter(k, d[k]) for k in sorted(d, key=repr) if d[k])
python
def simplify(self): """Simplify the Expr.""" d = defaultdict(float) for term in self.terms: term = term.simplify() d[term.ops] += term.coeff return Expr.from_terms_iter( Term.from_ops_iter(k, d[k]) for k in sorted(d, key=repr) if d[k])
[ "def", "simplify", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "float", ")", "for", "term", "in", "self", ".", "terms", ":", "term", "=", "term", ".", "simplify", "(", ")", "d", "[", "term", ".", "ops", "]", "+=", "term", ".", "coeff", ...
Simplify the Expr.
[ "Simplify", "the", "Expr", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L728-L735
train