text
stringlengths
81
112k
Compute logarithm of the normalization constant Z, where Z = sum exp(-E) -> logZ = log sum exp(-E) =: -nlogZ def get_log_normalization_constant(self, input_energy, mask, **kwargs): """Compute logarithm of the normalization constant Z, where Z = sum exp(-E) -> logZ = log sum exp(-E) =: -nlogZ ...
Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3 def get_energy(self, y_true, input_energy, mask): """Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3 """ input_energy = K.sum(input_energy * y_true, 2) # (B, T) chain_energy = K.sum(K.do...
Compute the loss, i.e., negative log likelihood (normalize by number of time steps) likelihood = 1/Z * exp(-E) -> neg_log_like = - log(1/Z * exp(-E)) = logZ + E def get_negative_log_likelihood(self, y_true, X, mask): """Compute the loss, i.e., negative log likelihood (normalize by number of time st...
Forward (alpha) or backward (beta) recursion If `return_logZ = True`, compute the logZ, the normalization constant: \[ Z = \sum_{y1, y2, y3} exp(-E) # energy = \sum_{y1, y2, y3} exp(-(u1' y1 + y1' W y2 + u2' y2 + y2' W y3 + u3' y3)) = sum_{y2, y3} (exp(-(u2' y2 + y2' W y3 + u3' y3)) ...
Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature def extract_signature(sql): """ Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature """ ...
implementation of Queue.join which takes a 'timeout' argument returns True on success, False on timeout def _timed_queue_join(self, timeout): """ implementation of Queue.join which takes a 'timeout' argument returns True on success, False on timeout """ deadline = time...
Starts the task thread. def start(self): """ Starts the task thread. """ self._lock.acquire() try: if not self._thread: self._thread = Thread(target=self._target) self._thread.setDaemon(True) self._thread.name = "elasti...
Stops the task thread. Synchronous! def stop(self, timeout=None): """ Stops the task thread. Synchronous! """ self._lock.acquire() try: if self._thread: self._queue.put_nowait(self._terminator) self._thread.join(timeout=timeout) ...
Get version without importing from elasticapm. This avoids any side effects from importing while installing and/or building the module :return: a string, indicating the version def get_version(): """ Get version without importing from elasticapm. This avoids any side effects from importing while in...
Returns only proper HTTP headers. def get_headers(environ): """ Returns only proper HTTP headers. """ for key, value in compat.iteritems(environ): key = str(key) if key.startswith("HTTP_") and key not in ("HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"): yield key[5:].replace("_"...
A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_...
Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None def _flush(self, buffer): """ Flush the queue. This method should only be called from the event processing queue ...
Cleans up resources and closes connection :return: def close(self): """ Cleans up resources and closes connection :return: """ if self._closed: return self._closed = True self.queue("close", None) if not self._flushed.wait(timeout=self...
Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed. def flush(self): """ Trigger a flush of the queue. Note: this method will only return...
Failure handler called by the transport on send failure def handle_transport_fail(self, exception=None, **kwargs): """ Failure handler called by the transport on send failure """ message = str(exception) logger.error("Failed to submit message: %r", message, exc_info=getattr(exce...
Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available wit...
Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = requ...
Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client def get_client(client=None): """ Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client """ global _client tmp_client = client is not None if not tmp_client: ...
Generate a list of modules in settings.INSTALLED_APPS. def _get_installed_apps_paths(): """ Generate a list of modules in settings.INSTALLED_APPS. """ out = set() for app in django_settings.INSTALLED_APPS: out.add(app) return out
If the stacktrace originates within the elasticapm module, it will skip frames until some other module comes up. def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_fun...
Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``. def send(self, url, **kwargs): """ Serializes and signs ``data`` and passes the pay...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. def deprecated(alternative=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the ...
Register a new metric set :param class_path: a string with the import path of the metricset class def register(self, class_path): """ Register a new metric set :param class_path: a string with the import path of the metricset class """ if class_path in self._metricsets: ...
Collect metrics from all registered metric sets :return: def collect(self): """ Collect metrics from all registered metric sets :return: """ logger.debug("Collecting metrics") for name, metricset in compat.iteritems(self._metricsets): data = metricse...
Returns an existing or creates and returns a new counter :param name: name of the counter :return: the counter object def counter(self, name): """ Returns an existing or creates and returns a new counter :param name: name of the counter :return: the counter object ...
Returns an existing or creates and returns a new gauge :param name: name of the gauge :return: the gauge object def gauge(self, name): """ Returns an existing or creates and returns a new gauge :param name: name of the gauge :return: the gauge object """ ...
Collects all metrics attached to this metricset, and returns it as a list, together with a timestamp in microsecond precision. The format of the return value should be { "samples": {"metric.name": {"value": some_float}, ...}, "timestamp": unix epoch in micro...
Tags current transaction. Both key and value of the tag should be strings. def tag(**tags): """ Tags current transaction. Both key and value of the tag should be strings. """ transaction = execution_context.get_transaction() if not transaction: error_logger.warning("Ignored tags %s. No tran...
Begin a new span :param name: name of the span :param span_type: type of the span :param context: a context dict :param leaf: True if this is a leaf span :param tags: a flat string/string dict of tags :return: the Span object def begin_span(self, name, span_type, context...
If current trace_parent has no span_id, generate one, then return it This is used to generate a span ID which the RUM agent will use to correlate the RUM transaction with the backend transaction. def ensure_parent_id(self): """If current trace_parent has no span_id, generate one, then return i...
Tag this transaction with one or multiple key/value tags. Both the values should be strings transaction_obj.tag(key1="value1", key2="value2") Note that keys will be dedotted, replacing dot (.), star (*) and double quote (") with an underscore (_) def tag(self, **tags): """ Tag thi...
Start a new transactions and bind it in a thread-local variable :returns the Transaction object def begin_transaction(self, transaction_type, trace_parent=None): """ Start a new transactions and bind it in a thread-local variable :returns the Transaction object """ if ...
Check your settings for common misconfigurations def handle_check(self, command, **options): """Check your settings for common misconfigurations""" passed = True client = DjangoClient(metrics_interval="0ms") def is_set(x): return x and x != "None" # check if org/ap...
wrapper around self.stdout/stderr to ensure Django 1.4 compatibility def write(self, msg, style_func=None, ending=None, stream=None): """ wrapper around self.stdout/stderr to ensure Django 1.4 compatibility """ if stream is None: stream = self.stdout if OutputWrapper...
Called when an exception has been raised in the code run by ZeroRPC def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info): """Called when an exception has been raised in the code run by ZeroRPC""" # Hide the zerorpc internal frames for readability, for a REQ/REP or # REQ...
Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations. :param module: :param method: :param wrapped: :param instance: :param args: :param kwargs: :param transactio...
Auto-instruments code to get nice spans def instrument(client): """ Auto-instruments code to get nice spans """ from elasticapm.instrumentation.control import instrument instrument() try: import celery # noqa F401 from elasticapm.contrib.celery import register_instrumentation ...
Configures logging to pipe to Elastic APM. - ``exclude`` is a list of loggers that shouldn't go to ElasticAPM. For a typical Python install: >>> from elasticapm.handlers.logging import LoggingHandler >>> client = ElasticAPM(...) >>> setup_logging(LoggingHandler(client)) Within Django: >...
Given an ElasticAPM client and an RQ worker, registers exception handlers with the worker so exceptions are logged to the apm server. E.g.: from elasticapm.contrib.django.models import client from elasticapm.contrib.rq import register_elasticapm worker = Worker(map(Queue, listen)) register_el...
Get the transaction registered for the current thread. :return: :rtype: Transaction def get_transaction(self, clear=False): """ Get the transaction registered for the current thread. :return: :rtype: Transaction """ transaction = getattr(self.thread_loc...
Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_line...
Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. def iter_traceback_frames(tb): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ while ...
Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. Frames can be skipped by either providing a number, or a tuple of module names. If the module of a frame matches one of the names (using `.startswith...
Given a list of frames, returns a list of stack information dictionary objects that are JSON-ready. We have to be careful here as certain implementations of the _Frame class do not contain the necessary data to lookup all of the information we want. :param frames: a list of (Frame, lineno) tuples ...
Uses either uwsgi's atexit mechanism, or atexit from the stdlib. When running under uwsgi, using their atexit handler is more reliable, especially when using gevent :param func: the function to call at exit def atexit_register(func): """ Uses either uwsgi's atexit mechanism, or atexit from the std...
Returns library paths depending on the used platform. :return: a list of glob paths def get_default_library_patters(): """ Returns library paths depending on the used platform. :return: a list of glob paths """ python_version = platform.python_version_tuple() python_implementation = platf...
Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or MultiValueDict instance :return: a dict instance def multidict_to_dict(d): """ Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or ...
Returns True if the given request *shouldn't* notify the site managers. def _is_ignorable_404(uri): """ Returns True if the given request *shouldn't* notify the site managers. """ urls = getattr(django_settings, "IGNORABLE_404_URLS", ()) return any(pattern.search(uri) for pattern in urls)
Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup The result is a nested dictionary with the detected IDs, e.g. { "container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"}, "pod": {"uid": "90d81341_92de_11e7_8cf2_507b9d4141...
Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs. See tests.utils.docker_tests.test_cgroup_parsing for a set of test cases :param filehandle: :return: nested dictionary or None def parse_cgroups(filehandle): """ Reads lines from a file handle and tries...
:param events: list of event types Only calls wrapped function if given event_type is in list of events def for_events(*events): """ :param events: list of event types Only calls wrapped function if given event_type is in list of events """ events = set(events) def wrap(func): fu...
Removes local variables from any frames. :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def remove_stacktrace_locals(client, event): """ Removes local variables from any frames. :param client: an ElasticAPM client :param event: a...
Sanitizes local variables in all frames :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def sanitize_stacktrace_locals(client, event): """ Sanitizes local variables in all frames :param client: an ElasticAPM client :param event: a...
Sanitizes http request cookies :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def sanitize_http_request_cookies(client, event): """ Sanitizes http request cookies :param client: an ElasticAPM client :param event: a transaction or...
Sanitizes the set-cookie header of the response :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def sanitize_http_response_cookies(client, event): """ Sanitizes the set-cookie header of the response :param client: an ElasticAPM client ...
Sanitizes http request/response headers :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def sanitize_http_headers(client, event): """ Sanitizes http request/response headers :param client: an ElasticAPM client :param event: a tran...
Sanitizes WSGI environment variables :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def sanitize_http_wsgi_env(client, event): """ Sanitizes WSGI environment variables :param client: an ElasticAPM client :param event: a transacti...
Sanitizes http request query string :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def sanitize_http_request_querystring(client, event): """ Sanitizes http request query string :param client: an ElasticAPM client :param event: a ...
Sanitizes http request body. This only works if the request body is a query-encoded string. Other types (e.g. JSON) are not handled by this sanitizer. :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event def sanitize_http_request_body(client, e...
sanitizes a string that contains multiple key/value items :param unsanitized: the unsanitized string :param itemsep: string that separates items :param kvsep: string that separates key from value :return: a sanitized string def _sanitize_string(unsanitized, itemsep, kvsep): """ sanitizes a stri...
Captures and processes an event and pipes it off to Client.send. def capture(self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs): """ Captures and processes an event and pipes it off to Client.send. """ if event_type == "Exception": # ...
Creates an event from ``message``. >>> client.capture_message('My event just happened!') def capture_message(self, message=None, param_message=None, **kwargs): """ Creates an event from ``message``. >>> client.capture_message('My event just happened!') """ return self....
Creates an event from an exception. >>> try: >>> exc_info = sys.exc_info() >>> client.capture_exception(exc_info) >>> finally: >>> del exc_info If exc_info is not provided, or is set to True, then this method will perform the ``exc_info = sys.exc_inf...
Register the start of a transaction on the client def begin_transaction(self, transaction_type, trace_parent=None): """Register the start of a transaction on the client """ return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent)
Captures, processes and serializes an event into a dict object def _build_msg_for_logging( self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs ): """ Captures, processes and serializes an event into a dict object """ transaction = execu...
Overrideable in derived clients to add frames/info, e.g. templates def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """Overrideable in derived clie...
This utility executes a single notebook on a container. Papermill takes a source notebook, applies parameters to the source notebook, executes the notebook with the specified kernel, and saves the output in the destination notebook. def papermill( notebook_path, output_path, parameters, pa...
Wrapper to catch `nb` keyword arguments This helps catch `nb` keyword arguments and assign onto self when passed to the wrapped function. Used for callback methods when the caller may optionally have a new copy of the originally wrapped `nb` object. def catch_nb_assignment(func): """ Wrapper ...
Register entrypoints for an engine Load handlers provided by other packages def register_entry_points(self): """Register entrypoints for an engine Load handlers provided by other packages """ for entrypoint in entrypoints.get_group_all("papermill.engine"): self.reg...
Retrieves an engine by name. def get_engine(self, name=None): """Retrieves an engine by name.""" engine = self._engines.get(name) if not engine: raise PapermillException("No engine named '{}' found".format(name)) return engine
Fetch a named engine and execute the nb object against it. def execute_notebook_with_engine(self, engine_name, nb, kernel_name, **kwargs): """Fetch a named engine and execute the nb object against it.""" return self.get_engine(engine_name).execute_notebook(nb, kernel_name, **kwargs)
Saves the wrapped notebook state. If an output path is known, this triggers a save of the wrapped notebook state to the provided path. Can be used outside of cell state changes if execution is taking a long time to conclude but the notebook object should be synced. For example...
Initialize a notebook, clearing its metadata, and save it. When starting a notebook, this initializes and clears the metadata for the notebook and its cells, and saves the notebook to the given output path. Called by Engine when execution begins. def notebook_start(self, **kwargs): ...
Set and save a cell's start state. Optionally called by engines during execution to initialize the metadata for a cell and save the notebook to the output path. def cell_start(self, cell, cell_index=None, **kwargs): """ Set and save a cell's start state. Optionally called by e...
Set metadata when an exception is raised. Called by engines when an exception is raised within a notebook to set the metadata on the notebook indicating the location of the failure. def cell_exception(self, cell, cell_index=None, **kwargs): """ Set metadata when an exception is...
Finalize metadata for a cell and save notebook. Optionally called by engines during execution to finalize the metadata for a cell and save the notebook to the output path. def cell_complete(self, cell, cell_index=None, **kwargs): """ Finalize metadata for a cell and save notebook. ...
Finalize the metadata for a notebook and save the notebook to the output path. Called by Engine when execution concludes, regardless of exceptions. def notebook_complete(self, **kwargs): """ Finalize the metadata for a notebook and save the notebook to the output path. ...
Refresh progress bar def complete_pbar(self): """Refresh progress bar""" if hasattr(self, 'pbar') and self.pbar: self.pbar.n = len(self.nb.cells) self.pbar.refresh()
Clean up a progress bar def cleanup_pbar(self): """Clean up a progress bar""" if hasattr(self, 'pbar') and self.pbar: self.pbar.close() self.pbar = None
A wrapper to handle notebook execution tasks. Wraps the notebook object in a `NotebookExecutionManager` in order to track execution state in a uniform manner. This is meant to help simplify engine implementations. This allows a developer to just focus on iterating and executing the cell...
Performs the actual execution of the parameterized notebook locally. Args: nb (NotebookNode): Executable notebook object. kernel_name (str): Name of kernel to execute the notebook against. log_output (bool): Flag for whether or not to write notebook output to stderr. ...
see: https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 # noqa: E501 abs://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sastoken def _split_url(self, url): """ see: https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet...
Read storage at a given url def read(self, url): """Read storage at a given url""" params = self._split_url(url) output_stream = io.BytesIO() block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) block...
Returns a list of the files under the specified path def listdir(self, url): """Returns a list of the files under the specified path""" params = self._split_url(url) block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ...
Write buffer to storage at a given url def write(self, buf, url): """Write buffer to storage at a given url""" params = self._split_url(url) block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) block_blob_se...
Executes a single notebook locally. Parameters ---------- input_path : str Path to input notebook output_path : str Path to save executed notebook parameters : dict, optional Arbitrary keyword arguments to pass to the notebook parameters engine_name : str, optional ...
Prepare metadata associated with a notebook and its cells Parameters ---------- nb : NotebookNode Executable notebook object input_path : str Path to input notebook output_path : str Path to write executed notebook report_mode : bool, optional Flag to set report mod...
Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook def raise_for_execution_errors(nb, output_path): """Assigned parameters into the appropriate place...
Limits a list of Bucket's objects based on prefix and delimiter. def list(self, prefix='', delimiter=None): """Limits a list of Bucket's objects based on prefix and delimiter.""" return self.service._list( bucket=self.name, prefix=prefix, delimiter=delimiter, objects=True )
Returns an iterator for the data in the key or nothing if the key doesn't exist. Decompresses data on the fly (if compressed is True or key ends with .gz) unless raw is True. Pass None for encoding to skip encoding. def cat( self, source, buffersize=None, memsize...
Copies source string into the destination location. Parameters ---------- source: string the string with the content to copy dest: string the s3 location def cp_string(self, source, dest, **kwargs): """ Copies source string into the destination l...
Returns a list of the files under the specified path name must be in the form of `s3://bucket/prefix` Parameters ---------- keys: optional if True then this will return the actual boto keys for files that are encountered objects: optional if True...
Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Parameters ---------- keys: optional if True then t...
Iterates over a file in s3 split on newline. Yields a line in file. def read(self, source, compressed=False, encoding='UTF-8'): """ Iterates over a file in s3 split on newline. Yields a line in file. """ buf = '' for block in self.cat(source, compressed=compre...
Reusable by most interpreters def translate_escaped_str(cls, str_val): """Reusable by most interpreters""" if isinstance(str_val, string_types): str_val = str_val.encode('unicode_escape') if sys.version_info >= (3, 0): str_val = str_val.decode('utf-8') ...
Translate each of the standard json/yaml types to appropiate objects. def translate(cls, val): """Translate each of the standard json/yaml types to appropiate objects.""" if val is None: return cls.translate_none(val) elif isinstance(val, string_types): return cls.transl...
Translate dicts to scala Maps def translate_dict(cls, val): """Translate dicts to scala Maps""" escaped = ', '.join( ["{} -> {}".format(cls.translate_str(k), cls.translate(v)) for k, v in val.items()] ) return 'Map({})'.format(escaped)
Translate list to scala Seq def translate_list(cls, val): """Translate list to scala Seq""" escaped = ', '.join([cls.translate(v) for v in val]) return 'Seq({})'.format(escaped)
Returns a notebook object with papermill metadata loaded from the specified path. Args: notebook_path (str): Path to the notebook file. Returns: nbformat.NotebookNode def load_notebook_node(notebook_path): """Returns a notebook object with papermill metadata loaded from the specified path...
Sets the cwd during reads and writes def cwd(self, new_path): '''Sets the cwd during reads and writes''' old_cwd = self._cwd self._cwd = new_path return old_cwd