text:
module CryptKey

  private

  def crypt_key(pass=Time.zone.now, salt=Time.zone.now)
    require "digest/sha1"
    3.times do |i|
      pass = Digest::SHA1.hexdigest("--#{salt}--#{pass}--")
    end
    return pass
  end
end

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function() {
    var url = window.location;
    $('.navbar .nav').find('.active').removeClass('active');
    $('.navbar .nav li a').each(function() {
        if (this.href === url.href) {
            $(this).parent().addClass('active');
        }
    });
});


text:
require 'rdf'
require 'rdf/vocab'

module BEL
  module Resource
    # Concept captures the properties available on an RDF Annotation or
    # Namespace Concept.
    module Concept
      DC   = RDF::Vocab::DC
      SKOS = RDF::Vocab::SKOS
      BELV = RDF::Vocabulary.new('http://www.openbel.org/vocabulary/')

      def type
        @rdf_repository
        .query([:subject => @uri, :predicate => RDF.type])
        .map do |solution|
          solution.object.to_s
        end
      end

      def pref_label
        @rdf_repository
        .query([:subject => @uri, :predicate => SKOS.prefLabel])
        .map do |solution|
          solution.object.to_s
        end
      end

      def identifier
        @rdf_repository
        .query([:subject => @uri, :predicate => DC.identifier])
        .map do |solution|
          solution.object.to_s
        end
      end

      def title
        @rdf_repository
        .query([:subject => @uri, :predicate => DC.title])
        .map do |solution|
          solution.object.to_s
        end
      end

      def alt_label
        @rdf_repository
        .query([:subject => @uri, :predicate => SKOS.altLabel])
        .map do |solution|
          solution.object.to_s
        end
      end

      def from_species
        @rdf_repository
        .query([:subject => @uri, :predicate => BELV.fromSpecies])
        .map do |solution|
          solution.object.to_s
        end
      end
    end
  end
end


text:
if (typeof String.prototype.startsWith != 'function') {
	// see below for better implementation!
	String.prototype.startsWith = function (str) {
		return this.slice(0, str.length) == str;
	};
}

if (typeof String.prototype.endsWith != 'function') {
	// see below for better implementation!
	String.prototype.endsWith = function (str) {
		return this.slice(-str.length) == str;
	};
}

function getUnderlyingSpot(e) {

	var clickedElement = undefined;

	// Read if it was pressed the right button of the mouse
	var isRightMB;
	if ("which" in e)  // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
		isRightMB = e.which == 3;
	else if ("button" in e)  // IE, Opera
		isRightMB = e.button == 2;

	if (!isRightMB)
		return;

	if (e.target)
		clickedElement = e.target;
	else if (e.srcElement)
		clickedElement = e.srcElement;
	if (clickedElement.nodeType == 3) // defeat Safari bug
		clickedElement = clickedElement.parentNode

	if (!clickedElement.hasAttribute('spot'))
		return;

	return clickedElement.getAttribute('spot');
}

function getSelectionCharOffsetsWithin(showAlert) {

	if (!showAlert)
		showAlert = false;

	var start = 0,
		end = 0,
		overlap = false;
	var range, priorRange, element;
	if (typeof window.getSelection != "undefined") {
		if (window.getSelection().rangeCount > 0) {
			range = window.getSelection().getRangeAt(0);
			if (range.commonAncestorContainer.childNodes.length > 0)
				overlap = true;
			// We need to check that the selection starts and stops on the same field
			var startFieldElement = range.startContainer.parentNode;
			var invalid = false;
			while (!startFieldElement.hasAttribute('field')) {
				startFieldElement = startFieldElement.parentNode;
				if (!("hasAttribute" in startFieldElement)) {
					invalid = true;
					break;
				}
			}

			var endFieldElement = range.endContainer.parentNode;
			while (!endFieldElement.hasAttribute('field')) {
				endFieldElement = endFieldElement.parentNode;
				if (!("hasAttribute" in endFieldElement)) {
					invalid = true;
					break;
				}
			}

			if (!invalid && startFieldElement == endFieldElement) {
				element = startFieldElement;
				priorRange = range.cloneRange();
				priorRange.selectNodeContents(element);
				priorRange.setEnd(range.startContainer, range.startOffset);
				start = priorRange.toString().length;
				end = start + range.toString().length;
			} else if (!invalid && startFieldElement != endFieldElement) {
				console.log('Cross-field selection is not allowed!');
				if (showAlert)
					alert("The spot you selected is across two different fields (or paragraphs), please change the selection in order to create a spot.");
			}
		}
	} else {
		alert('Feature not currently supported by your browser!');
	}

//	} else if (typeof document.selection != "undefined" && (sel = document.selection).type != "Control") {
//		range = sel.createRange();
//		if (range.text.length > 0) {
//			element = range.parentElement();
//			if (range.childNodes.length === 0) {
//				priorRange = document.body.createTextRange();
//				priorRange.moveToElementText(element);
//				priorRange.setEndPoint("EndToStart", range);
//				start = priorRange.text.length;
//				end = start + range.text.length;
//			}
//		}
//	}

	return {
		start: start,
		end: end,
		field: element != undefined ? $(element).attr('field') : undefined,
		overlap: overlap
	};
}

function selectText(containerEl, selection) {
	if (window.getSelection) {
		var charIndex = 0, range = document.createRange();
		range.setStart(containerEl, 0);
		range.collapse(true);
		var nodeStack = [containerEl], node, foundStart = false, stop = false;

		while (!stop && (node = nodeStack.pop())) {
			if (node.nodeType == 3) {
				var nextCharIndex = charIndex + node.length;
				if (!foundStart && selection.start >= charIndex && selection.start <= nextCharIndex) {
					range.setStart(node, selection.start - charIndex);
					foundStart = true;
				}
				if (foundStart && selection.end >= charIndex && selection.end <= nextCharIndex) {
					range.setEnd(node, selection.end - charIndex);
					stop = true;
				}
				charIndex = nextCharIndex;
			} else {
				var i = node.childNodes.length;
				while (i--) {
					nodeStack.push(node.childNodes[i]);
				}
			}
		}

		var sel = window.getSelection();
		sel.removeAllRanges();
		sel.addRange(range);

	} else {
		alert('Feature not currently supported by your browser!');

//		var textRange = document.body.createTextRange();
//		textRange.moveToElementText(containerEl);
//		textRange.collapse(true);
//		textRange.moveEnd("character", savedSel.end);
//		textRange.moveStart("character", savedSel.start);
//		textRange.select();
	}
}

function clearTextSelection() {
	if (window.getSelection) {
		if (window.getSelection().empty) {  // Chrome
			window.getSelection().empty();
		} else if (window.getSelection().removeAllRanges) {  // Firefox
			window.getSelection().removeAllRanges();
		}
	} else if (document.selection) {  // IE?
		document.selection.empty();
	}
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy
import hashlib
import inspect
import logging
import six
import sys
import threading

from abc import ABCMeta, abstractmethod
from collections import namedtuple

from ray.function_manager import FunctionDescriptor
import ray.ray_constants as ray_constants
import ray.signature as signature
import ray.worker
from ray import (ObjectID, ActorID, ActorHandleID, ActorClassID, TaskID,
                 DriverID)

logger = logging.getLogger(__name__)

def compute_actor_handle_id(actor_handle_id, num_forks):
    """Deterministically compute an actor handle ID.

    A new actor handle ID is generated when it is forked from another actor
    handle. The new handle ID is computed as hash(old_handle_id || num_forks).

    Args:
        actor_handle_id (common.ObjectID): The original actor handle ID.
        num_forks: The number of times the original actor handle has been
                   forked so far.

    Returns:
        An ID for the new actor handle.
    """
    assert isinstance(actor_handle_id, ActorHandleID)
    handle_id_hash = hashlib.sha1()
    handle_id_hash.update(actor_handle_id.binary())
    handle_id_hash.update(str(num_forks).encode("ascii"))
    handle_id = handle_id_hash.digest()
    return ActorHandleID(handle_id)

def compute_actor_handle_id_non_forked(actor_handle_id, current_task_id):
    """Deterministically compute an actor handle ID in the non-forked case.

    This code path is used whenever an actor handle is pickled and unpickled
    (for example, if a remote function closes over an actor handle). Then,
    whenever the actor handle is used, a new actor handle ID will be generated
    on the fly as a deterministic function of the actor ID, the previous actor
    handle ID and the current task ID.

    TODO(rkn): It may be possible to cause problems by closing over multiple
    actor handles in a remote function, which then get unpickled and give rise
    to the same actor handle IDs.

    Args:
        actor_handle_id: The original actor handle ID.
        current_task_id: The ID of the task that is unpickling the handle.

    Returns:
        An ID for the new actor handle.
    """
    assert isinstance(actor_handle_id, ActorHandleID)
    assert isinstance(current_task_id, TaskID)
    handle_id_hash = hashlib.sha1()
    handle_id_hash.update(actor_handle_id.binary())
    handle_id_hash.update(current_task_id.binary())
    handle_id = handle_id_hash.digest()
    return ActorHandleID(handle_id)

def method(*args, **kwargs):
    """Annotate an actor method.

    .. code-block:: python

        @ray.remote
        class Foo(object):
            @ray.method(num_return_vals=2)
            def bar(self):
                return 1, 2

        f = Foo.remote()

        _, _ = f.bar.remote()

    Args:
        num_return_vals: The number of object IDs that should be returned by
            invocations of this actor method.
    """
    assert len(args) == 0
    assert len(kwargs) == 1
    assert "num_return_vals" in kwargs
    num_return_vals = kwargs["num_return_vals"]

    def annotate_method(method):
        method.__ray_num_return_vals__ = num_return_vals
        return method

    return annotate_method

# Create objects to wrap method invocations. This is done so that we can
# invoke methods with actor.method.remote() instead of actor.method().
class ActorMethod(object):
    """A class used to invoke an actor method.

    Note: This class is instantiated only while the actor method is being
    invoked (so that it doesn't keep a reference to the actor handle and
    prevent it from going out of scope).

    Attributes:
        _actor: A handle to the actor.
        _method_name: The name of the actor method.
        _num_return_vals: The default number of return values that the method
            invocation should return.
        _decorator: An optional decorator that should be applied to the actor
            method invocation (as opposed to the actor method execution) before
            invoking the method. The decorator must return a function that
            takes in two arguments ("args" and "kwargs"). In most cases, it
            should call the function that was passed into the decorator and
            return the resulting ObjectIDs. For an example, see
            "test_decorated_method" in "python/ray/tests/test_actor.py".
    """

    def __init__(self, actor, method_name, num_return_vals, decorator=None):
        self._actor = actor
        self._method_name = method_name
        self._num_return_vals = num_return_vals
        # This is a decorator that is used to wrap the function invocation (as
        # opposed to the function execution). The decorator must return a
        # function that takes in two arguments ("args" and "kwargs"). In most
        # cases, it should call the function that was passed into the decorator
        # and return the resulting ObjectIDs.
        self._decorator = decorator

    def __call__(self, *args, **kwargs):
        raise Exception("Actor methods cannot be called directly. Instead "
                        "of running 'object.{}()', try "
                        "'object.{}.remote()'.".format(self._method_name,
                                                       self._method_name))

    def remote(self, *args, **kwargs):
        return self._remote(args, kwargs)

    def _remote(self, args=None, kwargs=None, num_return_vals=None):
        if args is None:
            args = []
        if kwargs is None:
            kwargs = {}
        if num_return_vals is None:
            num_return_vals = self._num_return_vals

        def invocation(args, kwargs):
            return self._actor._actor_method_call(
                self._method_name,
                args=args,
                kwargs=kwargs,
                num_return_vals=num_return_vals)

        # Apply the decorator if there is one.
        if self._decorator is not None:
            invocation = self._decorator(invocation)

        return invocation(args, kwargs)

class ActorClass(object):
    """An actor class.

    This is a decorated class. It can be used to create actors.

    Attributes:
        _modified_class: The original class that was decorated (with some
            additional methods added like __ray_terminate__).
        _class_id: The ID of this actor class.
        _class_name: The name of this class.
        _num_cpus: The default number of CPUs required by the actor creation
            task.
        _num_gpus: The default number of GPUs required by the actor creation
            task.
        _resources: The default resources required by the actor creation task.
        _actor_method_cpus: The number of CPUs required by actor method tasks.
        _last_driver_id_exported_for: The ID of the driver ID of the last Ray
            session during which this actor class definition was exported. This
            is an imperfect mechanism used to determine if we need to export
            the remote function again. It is imperfect in the sense that the
            actor class definition could be exported multiple times by
            different workers.
        _actor_methods: The actor methods.
        _method_decorators: Optional decorators that should be applied to the
            method invocation function before invoking the actor methods. These
            can be set by attaching the attribute
            "__ray_invocation_decorator__" to the actor method.
        _method_signatures: The signatures of the methods.
        _actor_method_names: The names of the actor methods.
        _actor_method_num_return_vals: The default number of return values for
            each actor method.
    """

    def __init__(self, modified_class, class_id, max_reconstructions, num_cpus,
                 num_gpus, resources):
        self._modified_class = modified_class
        self._class_id = class_id
        self._class_name = modified_class.__name__
        self._max_reconstructions = max_reconstructions
        self._num_cpus = num_cpus
        self._num_gpus = num_gpus
        self._resources = resources
        self._last_driver_id_exported_for = None

        self._actor_methods = inspect.getmembers(
            self._modified_class, ray.utils.is_function_or_method)
        self._actor_method_names = [
            method_name for method_name, _ in self._actor_methods
        ]

        constructor_name = "__init__"
        if constructor_name not in self._actor_method_names:
            # Add __init__ if it does not exist.
            # Actor creation will be executed with __init__ together.

            # Assign an __init__ function will avoid many checks later on.
            def __init__(self):
                pass

            self._modified_class.__init__ = __init__
            self._actor_method_names.append(constructor_name)
            self._actor_methods.append((constructor_name, __init__))

        # Extract the signatures of each of the methods. This will be used
        # to catch some errors if the methods are called with inappropriate
        # arguments.
        self._method_decorators = {}
        self._method_signatures = {}
        self._actor_method_num_return_vals = {}
        for method_name, method in self._actor_methods:
            # Print a warning message if the method signature is not
            # supported. We don't raise an exception because if the actor
            # inherits from a class that has a method whose signature we
            # don't support, there may not be much the user can do about it.
            signature.check_signature_supported(method, warn=True)
            self._method_signatures[method_name] = signature.extract_signature(
                method, ignore_first=not ray.utils.is_class_method(method))
            # Set the default number of return values for this method.
            if hasattr(method, "__ray_num_return_vals__"):
                self._actor_method_num_return_vals[method_name] = (
                    method.__ray_num_return_vals__)
            else:
                self._actor_method_num_return_vals[method_name] = (
                    ray_constants.DEFAULT_ACTOR_METHOD_NUM_RETURN_VALS)

            if hasattr(method, "__ray_invocation_decorator__"):
                self._method_decorators[method_name] = (
                    method.__ray_invocation_decorator__)

    def __call__(self, *args, **kwargs):
        raise Exception("Actors methods cannot be instantiated directly. "
                        "Instead of running '{}()', try '{}.remote()'.".format(
                            self._class_name, self._class_name))

    def remote(self, *args, **kwargs):
        """Create an actor.

        Args:
            args: These arguments are forwarded directly to the actor
                constructor.
            kwargs: These arguments are forwarded directly to the actor
                constructor.

        Returns:
            A handle to the newly created actor.
        """
        return self._remote(args=args, kwargs=kwargs)

    def _remote(self,
                args=None,
                kwargs=None,
                num_cpus=None,
                num_gpus=None,
                resources=None):
        """Create an actor.

        This method allows more flexibility than the remote method because
        resource requirements can be specified and override the defaults in the
        decorator.

        Args:
            args: The arguments to forward to the actor constructor.
            kwargs: The keyword arguments to forward to the actor constructor.
            num_cpus: The number of CPUs required by the actor creation task.
            num_gpus: The number of GPUs required by the actor creation task.
            resources: The custom resources required by the actor creation
                task.

        Returns:
            A handle to the newly created actor.
        """
        if args is None:
            args = []
        if kwargs is None:
            kwargs = {}

        worker = ray.worker.get_global_worker()
        if worker.mode is None:
            raise Exception("Actors cannot be created before ray.init() "
                            "has been called.")

        actor_id = ActorID.from_random()
        # The actor cursor is a dummy object representing the most recent
        # actor method invocation. For each subsequent method invocation,
        # the current cursor should be added as a dependency, and then
        # updated to reflect the new invocation.
        actor_cursor = None

        # Set the actor's default resources if not already set. First three
        # conditions are to check that no resources were specified in the
        # decorator. Last three conditions are to check that no resources were
        # specified when _remote() was called.
        if (self._num_cpus is None and self._num_gpus is None
                and self._resources is None and num_cpus is None
                and num_gpus is None and resources is None):
            # In the default case, actors acquire no resources for
            # their lifetime, and actor methods will require 1 CPU.
            cpus_to_use = ray_constants.DEFAULT_ACTOR_CREATION_CPU_SIMPLE
            actor_method_cpu = ray_constants.DEFAULT_ACTOR_METHOD_CPU_SIMPLE
        else:
            # If any resources are specified (here or in decorator), then
            # all resources are acquired for the actor's lifetime and no
            # resources are associated with methods.
            cpus_to_use = (ray_constants.DEFAULT_ACTOR_CREATION_CPU_SPECIFIED
                           if self._num_cpus is None else self._num_cpus)
            actor_method_cpu = ray_constants.DEFAULT_ACTOR_METHOD_CPU_SPECIFIED

        # Do not export the actor class or the actor if run in LOCAL_MODE
        # Instead, instantiate the actor locally and add it to the worker's
        # dictionary
        if worker.mode == ray.LOCAL_MODE:
            worker.actors[actor_id] = self._modified_class(
                *copy.deepcopy(args), **copy.deepcopy(kwargs))
        else:
            # Export the actor.
            if (self._last_driver_id_exported_for is None
                    or self._last_driver_id_exported_for !=
                    worker.task_driver_id):
                # If this actor class was exported in a previous session, we
                # need to export this function again, because current GCS
                # doesn't have it.
                self._last_driver_id_exported_for = worker.task_driver_id
                worker.function_actor_manager.export_actor_class(
                    self._modified_class, self._actor_method_names)

            resources = ray.utils.resources_from_resource_arguments(
                cpus_to_use, self._num_gpus, self._resources, num_cpus,
                num_gpus, resources)

            # If the actor methods require CPU resources, then set the required
            # placement resources. If actor_placement_resources is empty, then
            # the required placement resources will be the same as resources.
            actor_placement_resources = {}
            assert actor_method_cpu in [0, 1]
            if actor_method_cpu == 1:
                actor_placement_resources = resources.copy()
                actor_placement_resources["CPU"] += 1

            function_name = "__init__"
            function_signature = self._method_signatures[function_name]
            creation_args = signature.extend_args(function_signature, args,
                                                  kwargs)
            function_descriptor = FunctionDescriptor(
                self._modified_class.__module__, function_name,
                self._modified_class.__name__)
            [actor_cursor] = worker.submit_task(
                function_descriptor,
                creation_args,
                actor_creation_id=actor_id,
                max_actor_reconstructions=self._max_reconstructions,
                num_return_vals=1,
                resources=resources,
                placement_resources=actor_placement_resources)
            assert isinstance(actor_cursor, ObjectID)

        actor_handle = ActorHandle(
            actor_id, self._modified_class.__module__, self._class_name,
            actor_cursor, self._actor_method_names, self._method_decorators,
            self._method_signatures, self._actor_method_num_return_vals,
            actor_cursor, actor_method_cpu, worker.task_driver_id)
        # We increment the actor counter by 1 to account for the actor creation
        # task.
        actor_handle._ray_actor_counter += 1

        return actor_handle

    @property
    def class_id(self):
        return self._class_id

class ActorHandle(object):
    """A handle to an actor.

    The fields in this class are prefixed with _ray_ to hide them from the user
    and to avoid collision with actor method names.

    An ActorHandle can be created in three ways. First, by calling .remote() on
    an ActorClass. Second, by passing an actor handle into a task (forking the
    ActorHandle). Third, by directly serializing the ActorHandle (e.g., with
    cloudpickle).

    Attributes:
        _ray_actor_id: The ID of the corresponding actor.
        _ray_module_name: The module name of this actor.
        _ray_actor_handle_id: The ID of this handle. If this is the "original"
            handle for an actor (as opposed to one created by passing another
            handle into a task), then this ID must be NIL_ID. If this
            ActorHandle was created by forking an existing ActorHandle, then
            this ID must be computed deterministically via
            compute_actor_handle_id. If this ActorHandle was created by an
            out-of-band mechanism (e.g., pickling), then this must be None (in
            this case, a new actor handle ID will be generated on the fly every
            time a method is invoked).
        _ray_actor_cursor: The actor cursor is a dummy object representing the
            most recent actor method invocation. For each subsequent method
            invocation, the current cursor should be added as a dependency, and
            then updated to reflect the new invocation.
        _ray_actor_counter: The number of actor method invocations that we've
            called so far.
        _ray_actor_method_names: The names of the actor methods.
        _ray_method_decorators: Optional decorators for the function
            invocation. This can be used to change the behavior on the
            invocation side, whereas a regular decorator can be used to change
            the behavior on the execution side.
        _ray_method_signatures: The signatures of the actor methods.
        _ray_method_num_return_vals: The default number of return values for
            each method.
        _ray_class_name: The name of the actor class.
        _ray_actor_forks: The number of times this handle has been forked.
        _ray_actor_creation_dummy_object_id: The dummy object ID from the actor
            creation task.
        _ray_actor_method_cpus: The number of CPUs required by actor methods.
        _ray_original_handle: True if this is the original actor handle for a
            given actor. If this is true, then the actor will be destroyed when
            this handle goes out of scope.
        _ray_actor_driver_id: The driver ID of the job that created the actor
            (it is possible that this ActorHandle exists on a driver with a
            different driver ID).
        _ray_new_actor_handles: The new actor handles that were created from
            this handle since the last task on this handle was submitted. This
            is used to garbage-collect dummy objects that are no longer
            necessary in the backend.
    """

    def __init__(self,
                 actor_id,
                 module_name,
                 class_name,
                 actor_cursor,
                 actor_method_names,
                 method_decorators,
                 method_signatures,
                 method_num_return_vals,
                 actor_creation_dummy_object_id,
                 actor_method_cpus,
                 actor_driver_id,
                 actor_handle_id=None):
        assert isinstance(actor_id, ActorID)
        assert isinstance(actor_driver_id, DriverID)
        self._ray_actor_id = actor_id
        self._ray_module_name = module_name
        # False if this actor handle was created by forking or pickling. True
        # if it was created by the _serialization_helper function.
        self._ray_original_handle = actor_handle_id is None
        if self._ray_original_handle:
            self._ray_actor_handle_id = ActorHandleID.nil()
        else:
            assert isinstance(actor_handle_id, ActorHandleID)
            self._ray_actor_handle_id = actor_handle_id
        self._ray_actor_cursor = actor_cursor
        self._ray_actor_counter = 0
        self._ray_actor_method_names = actor_method_names
        self._ray_method_decorators = method_decorators
        self._ray_method_signatures = method_signatures
        self._ray_method_num_return_vals = method_num_return_vals
        self._ray_class_name = class_name
        self._ray_actor_forks = 0
        self._ray_actor_creation_dummy_object_id = (
            actor_creation_dummy_object_id)
        self._ray_actor_method_cpus = actor_method_cpus
        self._ray_actor_driver_id = actor_driver_id
        self._ray_new_actor_handles = []
        self._ray_actor_lock = threading.Lock()

    def _actor_method_call(self,
                           method_name,
                           args=None,
                           kwargs=None,
                           num_return_vals=None):
        """Method execution stub for an actor handle.

        This is the function that executes when
        `actor.method_name.remote(*args, **kwargs)` is called. Instead of
        executing locally, the method is packaged as a task and scheduled
        to the remote actor instance.

        Args:
            method_name: The name of the actor method to execute.
            args: A list of arguments for the actor method.
            kwargs: A dictionary of keyword arguments for the actor method.
            num_return_vals (int): The number of return values for the method.

        Returns:
            object_ids: A list of object IDs returned by the remote actor
                method.
        """
        worker = ray.worker.get_global_worker()

        worker.check_connected()

        function_signature = self._ray_method_signatures[method_name]
        if args is None:
            args = []
        if kwargs is None:
            kwargs = {}
        args = signature.extend_args(function_signature, args, kwargs)

        # Execute functions locally if Ray is run in LOCAL_MODE
        # Copy args to prevent the function from mutating them.
        if worker.mode == ray.LOCAL_MODE:
            return getattr(worker.actors[self._ray_actor_id],
                           method_name)(*copy.deepcopy(args))

        function_descriptor = FunctionDescriptor(
            self._ray_module_name, method_name, self._ray_class_name)
        with self._ray_actor_lock:
            object_ids = worker.submit_task(
                function_descriptor,
                args,
                actor_id=self._ray_actor_id,
                actor_handle_id=self._ray_actor_handle_id,
                actor_counter=self._ray_actor_counter,
                actor_creation_dummy_object_id=(
                    self._ray_actor_creation_dummy_object_id),
                execution_dependencies=[self._ray_actor_cursor],
                new_actor_handles=self._ray_new_actor_handles,
                # We add one for the dummy return ID.
                num_return_vals=num_return_vals + 1,
                resources={"CPU": self._ray_actor_method_cpus},
                placement_resources={},
                driver_id=self._ray_actor_driver_id,
            )
            # Update the actor counter and cursor to reflect the most recent
            # invocation.
            self._ray_actor_counter += 1
            # The last object returned is the dummy object that should be
            # passed in to the next actor method. Do not return it to the user.
            self._ray_actor_cursor = object_ids.pop()
            # We have notified the backend of the new actor handles to expect
            # since the last task was submitted, so clear the list.
            self._ray_new_actor_handles = []

        if len(object_ids) == 1:
            object_ids = object_ids[0]
        elif len(object_ids) == 0:
            object_ids = None

        return object_ids

    # Make tab completion work.
    def __dir__(self):
        return self._ray_actor_method_names

    def __getattribute__(self, attr):
        try:
            # Check whether this is an actor method.
            actor_method_names = object.__getattribute__(
                self, "_ray_actor_method_names")
            if attr in actor_method_names:
                # We create the ActorMethod on the fly here so that the
                # ActorHandle doesn't need a reference to the ActorMethod.
                # The ActorMethod has a reference to the ActorHandle and
                # this was causing cyclic references which were prevent
                # object deallocation from behaving in a predictable
                # manner.
                return ActorMethod(
                    self,
                    attr,
                    self._ray_method_num_return_vals[attr],
                    decorator=self._ray_method_decorators.get(attr))
        except AttributeError:
            pass

        # If the requested attribute is not a registered method, fall back
        # to default __getattribute__.
        return object.__getattribute__(self, attr)

    def __repr__(self):
        return "Actor({}, {})".format(self._ray_class_name,
                                      self._ray_actor_id.hex())

    def __del__(self):
        """Kill the worker that is running this actor."""
        # TODO(swang): Also clean up forked actor handles.
        # Kill the worker if this is the original actor handle, created
        # with Class.remote(). TODO(rkn): Even without passing handles around,
        # this is not the right policy. the actor should be alive as long as
        # there are ANY handles in scope in the process that created the actor,
        # not just the first one.
        worker = ray.worker.get_global_worker()
        if (worker.mode == ray.worker.SCRIPT_MODE
                and self._ray_actor_driver_id.binary() != worker.worker_id):
            # If the worker is a driver and driver id has changed because
            # Ray was shut down re-initialized, the actor is already cleaned up
            # and we don't need to send `__ray_terminate__` again.
            logger.warning(
                "Actor is garbage collected in the wrong driver." +
                " Actor id = %s, class name = %s.", self._ray_actor_id,
                self._ray_class_name)
            return
        if worker.connected and self._ray_original_handle:
            # TODO(rkn): Should we be passing in the actor cursor as a
            # dependency here?
            self.__ray_terminate__.remote()

    @property
    def _actor_id(self):
        return self._ray_actor_id

    @property
    def _actor_handle_id(self):
        return self._ray_actor_handle_id

    def _serialization_helper(self, ray_forking):
        """This is defined in order to make pickling work.

        Args:
            ray_forking: True if this is being called because Ray is forking
                the actor handle and false if it is being called by pickling.

        Returns:
            A dictionary of the information needed to reconstruct the object.
        """
        if ray_forking:
            actor_handle_id = compute_actor_handle_id(
                self._ray_actor_handle_id, self._ray_actor_forks)
        else:
            actor_handle_id = self._ray_actor_handle_id

        # Note: _ray_actor_cursor and _ray_actor_creation_dummy_object_id
        # could be None.
        state = {
            "actor_id": self._ray_actor_id,
            "actor_handle_id": actor_handle_id,
            "module_name": self._ray_module_name,
            "class_name": self._ray_class_name,
            "actor_cursor": self._ray_actor_cursor,
            "actor_method_names": self._ray_actor_method_names,
            "method_decorators": self._ray_method_decorators,
            "method_signatures": self._ray_method_signatures,
            "method_num_return_vals": self._ray_method_num_return_vals,
            # Actors in local mode don't have dummy objects.
            "actor_creation_dummy_object_id": self.
            _ray_actor_creation_dummy_object_id,
            "actor_method_cpus": self._ray_actor_method_cpus,
            "actor_driver_id": self._ray_actor_driver_id,
            "ray_forking": ray_forking
        }

        if ray_forking:
            self._ray_actor_forks += 1
            new_actor_handle_id = actor_handle_id
        else:
            # The execution dependency for a pickled actor handle is never safe
            # to release, since it could be unpickled and submit another
            # dependent task at any time. Therefore, we notify the backend of a
            # random handle ID that will never actually be used.
            new_actor_handle_id = ActorHandleID.from_random()
        # Notify the backend to expect this new actor handle. The backend will
        # not release the cursor for any new handles until the first task for
        # each of the new handles is submitted.
        # NOTE(swang): There is currently no garbage collection for actor
        # handles until the actor itself is removed.
        self._ray_new_actor_handles.append(new_actor_handle_id)

        return state

    def _deserialization_helper(self, state, ray_forking):
        """This is defined in order to make pickling work.

        Args:
            state: The serialized state of the actor handle.
            ray_forking: True if this is being called because Ray is forking
                the actor handle and false if it is being called by pickling.
        """
        worker = ray.worker.get_global_worker()
        worker.check_connected()

        if state["ray_forking"]:
            actor_handle_id = state["actor_handle_id"]
        else:
            # Right now, if the actor handle has been pickled, we create a
            # temporary actor handle id for invocations.
            # TODO(pcm): This still leads to a lot of actor handles being
            # created, there should be a better way to handle pickled
            # actor handles.
            # TODO(swang): Accessing the worker's current task ID is not
            # thread-safe.
            # TODO(swang): Unpickling the same actor handle twice in the same
            # task will break the application, and unpickling it twice in the
            # same actor is likely a performance bug. We should consider
            # logging a warning in these cases.
            actor_handle_id = compute_actor_handle_id_non_forked(
                state["actor_handle_id"], worker.current_task_id)

        self.__init__(
            state["actor_id"],
            state["module_name"],
            state["class_name"],
            state["actor_cursor"],
            state["actor_method_names"],
            state["method_decorators"],
            state["method_signatures"],
            state["method_num_return_vals"],
            state["actor_creation_dummy_object_id"],
            state["actor_method_cpus"],
            # This is the driver ID of the driver that owns the actor, not
            # necessarily the driver that owns this actor handle.
            state["actor_driver_id"],
            actor_handle_id=actor_handle_id)

    def __getstate__(self):
        """This code path is used by pickling but not by Ray forking."""
        return self._serialization_helper(False)

    def __setstate__(self, state):
        """This code path is used by pickling but not by Ray forking."""
        return self._deserialization_helper(state, False)

def make_actor(cls, num_cpus, num_gpus, resources, max_reconstructions):
    # Give an error if cls is an old-style class.
    if not issubclass(cls, object):
        raise TypeError(
            "The @ray.remote decorator cannot be applied to old-style "
            "classes. In Python 2, you must declare the class with "
            "'class ClassName(object):' instead of 'class ClassName:'.")

    if issubclass(cls, Checkpointable) and inspect.isabstract(cls):
        raise TypeError(
            "A checkpointable actor class should implement all abstract "
            "methods in the `Checkpointable` interface.")

    if max_reconstructions is None:
        max_reconstructions = 0

    if not (ray_constants.NO_RECONSTRUCTION <= max_reconstructions <=
            ray_constants.INFINITE_RECONSTRUCTION):
        raise Exception("max_reconstructions must be in range [%d, %d]." %
                        (ray_constants.NO_RECONSTRUCTION,
                         ray_constants.INFINITE_RECONSTRUCTION))

    # Modify the class to have an additional method that will be used for
    # terminating the worker.
    class Class(cls):
        def __ray_terminate__(self):
            worker = ray.worker.get_global_worker()
            if worker.mode != ray.LOCAL_MODE:
                ray.actor.exit_actor()

        def __ray_checkpoint__(self):
            """Save a checkpoint.

            This task saves the current state of the actor, the current task
            frontier according to the raylet, and the checkpoint index
            (number of tasks executed so far).
            """
            worker = ray.worker.global_worker
            if not isinstance(self, ray.actor.Checkpointable):
                raise Exception(
                    "__ray_checkpoint__.remote() may only be called on actors "
                    "that implement ray.actor.Checkpointable")
            return worker._save_actor_checkpoint()

    Class.__module__ = cls.__module__
    Class.__name__ = cls.__name__

    class_id = ActorClassID.from_random()

    return ActorClass(Class, class_id, max_reconstructions, num_cpus, num_gpus,
                      resources)

def exit_actor():
    """Intentionally exit the current actor.

    This function is used to disconnect an actor and exit the worker.

    Raises:
        Exception: An exception is raised if this is a driver or this
            worker is not an actor.
    """
    worker = ray.worker.global_worker
    if worker.mode == ray.WORKER_MODE and not worker.actor_id.is_nil():
        # Disconnect the worker from the raylet. The point of
        # this is so that when the worker kills itself below, the
        # raylet won't push an error message to the driver.
        worker.raylet_client.disconnect()
        ray.disconnect()
        # Disconnect global state from GCS.
        ray.state.state.disconnect()
        sys.exit(0)
        assert False, "This process should have terminated."
    else:
        raise Exception("exit_actor called on a non-actor worker.")

ray.worker.global_worker.make_actor = make_actor

CheckpointContext = namedtuple(
    "CheckpointContext",
    [
        # Actor's ID.
        "actor_id",
        # Number of tasks executed since last checkpoint.
        "num_tasks_since_last_checkpoint",
        # Time elapsed since last checkpoint, in milliseconds.
        "time_elapsed_ms_since_last_checkpoint",
    ],
)
"""A namedtuple that contains information about actor's last checkpoint."""

Checkpoint = namedtuple(
    "Checkpoint",
    [
        # ID of this checkpoint.
        "checkpoint_id",
        # The timestamp at which this checkpoint was saved,
        # represented as milliseconds elapsed since Unix epoch.
        "timestamp",
    ],
)
"""A namedtuple that represents a checkpoint."""

class Checkpointable(six.with_metaclass(ABCMeta, object)):
    """An interface that indicates an actor can be checkpointed."""

    @abstractmethod
    def should_checkpoint(self, checkpoint_context):
        """Whether this actor needs to be checkpointed.

        This method will be called after every task. You should implement this
        callback to decide whether this actor needs to be checkpointed at this
        time, based on the checkpoint context, or any other factors.

        Args:
            checkpoint_context: A namedtuple that contains info about last
                checkpoint.

        Returns:
            A boolean value that indicates whether this actor needs to be
            checkpointed.
        """
        pass

    @abstractmethod
    def save_checkpoint(self, actor_id, checkpoint_id):
        """Save a checkpoint to persistent storage.

        If `should_checkpoint` returns true, this method will be called. You
        should implement this callback to save actor's checkpoint and the given
        checkpoint id to persistent storage.

        Args:
            actor_id: Actor's ID.
            checkpoint_id: ID of this checkpoint. You should save it together
                with actor's checkpoint data. And it will be used by the
                `load_checkpoint` method.
        Returns:
            None.
        """
        pass

    @abstractmethod
    def load_checkpoint(self, actor_id, available_checkpoints):
        """Load actor's previous checkpoint, and restore actor's state.

        This method will be called when an actor is reconstructed, after
        actor's constructor.
        If the actor needs to restore from previous checkpoint, this function
        should restore actor's state and return the checkpoint ID. Otherwise,
        it should do nothing and return None.
        Note, this method must return one of the checkpoint IDs in the
        `available_checkpoints` list, or None. Otherwise, an exception will be
        raised.

        Args:
            actor_id: Actor's ID.
            available_checkpoints: A list of `Checkpoint` namedtuples that
                contains all available checkpoint IDs and their timestamps,
                sorted by timestamp in descending order.
        Returns:
            The ID of the checkpoint from which the actor was resumed, or None
            if the actor should restart from the beginning.
        """
        pass

    @abstractmethod
    def checkpoint_expired(self, actor_id, checkpoint_id):
        """Delete an expired checkpoint.

        This method will be called when an checkpoint is expired. You should
        implement this method to delete your application checkpoint data.
        Note, the maximum number of checkpoints kept in the backend can be
        configured at `RayConfig.num_actor_checkpoints_to_keep`.

        Args:
            actor_id: ID of the actor.
            checkpoint_id: ID of the checkpoint that has expired.
        Returns:
            None.
        """
        pass

def get_checkpoints_for_actor(actor_id):
    """Get the available checkpoints for the given actor ID, return a list
    sorted by checkpoint timestamp in descending order.
    """
    checkpoint_info = ray.state.state.actor_checkpoint_info(actor_id)
    if checkpoint_info is None:
        return []
    checkpoints = [
        Checkpoint(checkpoint_id, timestamp) for checkpoint_id, timestamp in
        zip(checkpoint_info["CheckpointIds"], checkpoint_info["Timestamps"])
    ]
    return sorted(
        checkpoints,
        key=lambda checkpoint: checkpoint.timestamp,
        reverse=True,
    )


text:
import { JsonHelper } from './../../utils/helpers/typed_json.helper';
import { IError, HttpType } from 'ws-format-httprequest';
import { IdentityService } from './../identity/identity.service';
import { Logger } from 'ws-logger';
import { ServerService } from './../server/server.service';
import { HttpClient } from '@angular/common/http';
import { IResponse } from './../../model/interfaces/response.interface';
import { HttpAsyncClientBase } from './../base/service.base';
import { Injectable } from '@angular/core';
import { StrictResult } from '../../utils/app.utils';

@Injectable()
export class UtilsService extends HttpAsyncClientBase<IResponse> {

    public get Root() { return this.server.ServerApiRoot; }

    public get Options() { return this.identity.Options; }

    public get FormOptions() { return this.identity.FormOptions; }

    private logger: Logger<UtilsService>;

    constructor(
        protected http: HttpClient,
        private identity: IdentityService,
        private server: ServerService) {
        super(http);
        this.logger = this.logsrv.GetLogger('UtilsService').SetModule('service');
    }

    private apiLog = (result: [boolean, IError, IResponse], title: string, method: string, descrip?: string) => {
        const [succeed, error, response] = result;
        if (succeed) {
            this.logger.Debug([`[ API ]${title}`, ...(descrip ? [descrip, response] : [response])], method);
        } else {
            this.logger.Error([`[ API ]${title}`, 'Connect To Server Failed.', error], method);
        }
    }

}


text:
<?php

/**
 * Handles sending notifications to users
 *
 * @package iThemes-Security
 * @since   4.5
 */
class ITSEC_Notify {

	private
		$queue;

	function __construct() {

		global $itsec_globals;

		$this->queue = get_site_option( 'itsec_message_queue' );

		if ( isset( $itsec_globals['settings']['digest_email'] ) && $itsec_globals['settings']['digest_email'] === true ) {

			if ( defined( 'ITSEC_NOTIFY_USE_CRON' ) && true === ITSEC_NOTIFY_USE_CRON ) {

				add_action( 'itsec_digest_email', array( $this, 'init' ) ); //Action to execute during a cron run.

				//schedule digest email
				if ( false === wp_next_scheduled( 'itsec_digest_email' ) ) {
					wp_schedule_event( time(), 'daily', 'itsec_digest_email' );
				}

			} else {

				//Send digest if it has been 24 hours
				if (
					get_site_transient( 'itsec_notification_running' ) === false && (
						$this->queue === false ||
						(
							is_array( $this->queue ) &&
							isset( $this->queue['last_sent'] ) &&
							$this->queue['last_sent'] < ( $itsec_globals['current_time_gmt'] - 86400 )
						)
					)
				) {
					add_action( 'init', array( $this, 'init' ) );
				}

			}

		}

	}

	/**
	 * Processes and sends daily digest message
	 *
	 * @since 4.5
	 *
	 * @return void
	 */
	public function init() {

		global $itsec_globals, $itsec_lockout;

		if ( is_404() || ( ( ! defined( 'ITSEC_NOTIFY_USE_CRON' ) || false === ITSEC_NOTIFY_USE_CRON ) && get_site_transient( 'itsec_notification_running' ) !== false ) ) {
			return;
		}

		if ( ( ! defined( 'ITSEC_NOTIFY_USE_CRON' ) || false === ITSEC_NOTIFY_USE_CRON ) ) {
			set_site_transient( 'itsec_notification_running', true, 3600 );
		}

		$messages     = false;
		$has_lockouts = true; //assume a lockout has occured by default

		if ( isset( $this->queue['messages'] ) && sizeof( $this->queue['messages'] ) > 0 ) {
			$messages = $this->queue['messages'];
		}

		$host_count = sizeof( $itsec_lockout->get_lockouts( 'host', true ) );
		$user_count = sizeof( $itsec_lockout->get_lockouts( 'user', true ) );

		if ( $host_count == 0 && $user_count == 0 ) {

			$has_lockouts    = false;
			$lockout_message = __( 'There have been no lockouts since the last email check.', 'it-l10n-better-wp-security' );

		} elseif ( $host_count === 0 && $user_count > 1 ) {

			$lockout_message = sprintf(
				'%s %s %s',
				__( 'There have been', 'it-l10n-better-wp-security' ),
				$user_count,
				__( 'users or usernames locked out for attempting to log in with incorrect credentials.', 'it-l10n-better-wp-security' )
			);

		} elseif ( $host_count === 0 && $user_count == 1 ) {

			$lockout_message = sprintf(
				'%s %s %s',
				__( 'There has been', 'it-l10n-better-wp-security' ),
				$user_count,
				__( 'user or username locked out for attempting to log in with incorrect credentials.', 'it-l10n-better-wp-security' )
			);

		} elseif ( $host_count == 1 && $user_count === 0 ) {

			$lockout_message = sprintf(
				'%s %s %s',
				__( 'There has been', 'it-l10n-better-wp-security' ),
				$host_count,
				__( 'host locked out.', 'it-l10n-better-wp-security' )
			);

		} elseif ( $host_count > 1 && $user_count === 0 ) {

			$lockout_message = sprintf(
				'%s %s %s',
				__( 'There have been', 'it-l10n-better-wp-security' ),
				$host_count,
				__( 'hosts locked out.', 'it-l10n-better-wp-security' )
			);

		} else {

			$lockout_message = sprintf(
				'%s %s %s %s %s %s %s',
				__( 'There have been', 'it-l10n-better-wp-security' ),
				$user_count + $host_count,
				__( 'lockout(s) including', 'it-l10n-better-wp-security' ),
				$user_count,
				__( 'user(s) and', 'it-l10n-better-wp-security' ),
				$host_count,
				__( 'host(s) locked out of your site.', 'it-l10n-better-wp-security' )
			);

		}

		if ( $has_lockouts !== false || $messages !== false ) {

			$module_message = '';

			if ( is_array( $messages ) ) {

				foreach ( $messages as $message ) {

					if ( is_string( $message ) ) {
						$module_message .= '
' . $message . '
';
					}

				}

			}

			$body = sprintf(
				'
%s,

%s %s

%s: %s
%s
%s %s

%s %s.
',
				__( 'Dear Site Admin', 'it-l10n-better-wp-security' ),
				__( 'The following is a summary of security related activity on your site. For details please visit', 'it-l10n-better-wp-security' ),
				wp_login_url( get_admin_url( '', 'admin.php?page=toplevel_page_itsec_logs' ) ),
				__( 'the security logs', 'it-l10n-better-wp-security' ),
				__( 'Lockouts', 'it-l10n-better-wp-security' ),
				$lockout_message,
				$module_message,
				__( 'This email was generated automatically by' ),
				$itsec_globals['plugin_name'],
				__( 'To change your email preferences please visit', 'it-l10n-better-wp-security' ),
				wp_login_url( get_admin_url( '', 'admin.php?page=toplevel_page_itsec_settings' ) ),
				__( 'the plugin settings', 'it-l10n-better-wp-security' )
			);

			//Setup the remainder of the email
			$subject = '[' . get_option( 'siteurl' ) . '] ' . __( 'Daily Security Digest', 'it-l10n-better-wp-security' );
			$subject = apply_filters( 'itsec_lockout_email_subject', $subject );
			$headers = 'From: ' . get_bloginfo( 'name' ) . ' <' . get_option( 'admin_email' ) . '>' . "\r\n";

			$this->send_mail( $subject, $body, $headers );

		}

		$this->queue = array(
			'last_sent' => $itsec_globals['current_time_gmt'],
			'messages'  => array(),
		);

		update_site_option( 'itsec_message_queue', $this->queue );

	}

	/**
	 * Enqueue or send notification accordingly
	 *
	 * @since 4.5
	 *
	 * @param int        $type 1 for lockout or 2 for custom message
	 * @param null|array $body Custom message information to send
	 *
	 * @return bool whether the message was successfully enqueue or sent
	 */
	public function notify( $body = null ) {

		global $itsec_globals;

		$allowed_tags = array(
			'a'      => array(
				'href' => array(),
			),
			'em'     => array(),
			'p'      => array(),
			'strong' => array(),
			'table'  => array(
				'border' => array(),
				'style'  => array(),
			),
			'tr'     => array(),
			'td'     => array(
				'colspan' => array(),
			),
			'th'     => array(),
			'br'     => array(),
			'h4'     => array(),
		);

		if ( isset( $itsec_globals['settings']['digest_email'] ) && $itsec_globals['settings']['digest_email'] === true ) {

			if ( ! in_array( wp_kses( $body, $allowed_tags ), $this->queue['messages'] ) ) {

				$this->queue['messages'][] = wp_kses( $body, $allowed_tags );

				update_site_option( 'itsec_message_queue', $this->queue );

			}

			return true;

		} elseif ( isset( $itsec_globals['settings']['email_notifications'] ) && $itsec_globals['settings']['email_notifications'] === true ) {

			$subject = trim( sanitize_text_field( $body['subject'] ) );
			$message = wp_kses( $body['message'], $allowed_tags );

			if ( isset( $body['headers'] ) ) {

				$headers = $body['headers'];

			} else {

				$headers = '';

			}

			$attachments = isset( $body['attachments'] ) && is_array( $body['attachments'] ) ? $body['attachments'] : array();

			return $this->send_mail( $subject, $message, $headers, $attachments );

		}

		return true;

	}

	/**
	 * Sends email to recipient
	 *
	 * @since 4.5
	 *
	 * @param string       $subject     Email subject
	 * @param string       $message     Message contents
	 * @param string|array $headers     Optional. Additional headers.
	 * @param string|array $attachments Optional. Files to attach.
	 *
	 * @return bool Whether the email contents were sent successfully.
	 */
	private function send_mail( $subject, $message, $headers = '', $attachments = array() ) {

		global $itsec_globals;

		$recipients  = $itsec_globals['settings']['notification_email'];
		$all_success = true;

		add_filter( 'wp_mail_content_type', array( $this, 'wp_mail_content_type' ) );

		foreach ( $recipients as $recipient ) {

			if ( is_email( trim( $recipient ) ) ) {

				if ( defined( 'ITSEC_DEBUG' ) && ITSEC_DEBUG === true ) {
					$message .= '
' . __( 'Debug info (source page): ' . esc_url( $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] ) ) . '
';
				}

				$success = wp_mail( trim( $recipient ), $subject, '' . $message . '', $headers );

				if ( $all_success === true && $success === false ) {
					$all_success = false;
				}

			}

		}

		remove_filter( 'wp_mail_content_type', array( $this, 'wp_mail_content_type' ) );

		return $all_success;

	}

	/**
	 * Set HTML content type for email
	 *
	 * @since 4.5
	 *
	 * @return string html content type
	 */
	public function wp_mail_content_type() {

		return 'text/html';

	}

}


text:
<?php
/*

	Instagram access token details

	Place your unique Instagram access token in the string below. Access tokens can be requested via:

	https://instagram.com/developer/authentication/

*/

$instagramAccessToken = "";


text:
InterceptablePrefFilter::InterceptablePrefFilter() {
}
InterceptablePrefFilter::~InterceptablePrefFilter() {
}

void InterceptablePrefFilter::FilterOnLoad(
    const PostFilterOnLoadCallback& post_filter_on_load_callback,
    std::unique_ptr<base::DictionaryValue> pref_store_contents) {
  if (filter_on_load_interceptor_.is_null()) {
    FinalizeFilterOnLoad(post_filter_on_load_callback,
                         std::move(pref_store_contents), false);
  } else {
    // Note, in practice (in the implementation as it was in May 2014) it would
    // be okay to pass an unretained |this| pointer below, but in order to avoid
    // having to augment the API everywhere to explicitly enforce the ownership
    // model as it happens to currently be: make the relationship simpler by
    // weakly binding the FinalizeFilterOnLoadCallback below to |this|.
    const FinalizeFilterOnLoadCallback finalize_filter_on_load(
        base::Bind(&InterceptablePrefFilter::FinalizeFilterOnLoad, AsWeakPtr(),
                   post_filter_on_load_callback));
    filter_on_load_interceptor_.Run(finalize_filter_on_load,
                                    std::move(pref_store_contents));
    filter_on_load_interceptor_.Reset();
  }
}

void InterceptablePrefFilter::InterceptNextFilterOnLoad(
    const FilterOnLoadInterceptor& filter_on_load_interceptor) {
  DCHECK(filter_on_load_interceptor_.is_null());
  filter_on_load_interceptor_ = filter_on_load_interceptor;
}


text:
module Awesome

  class Client

    # Define the same set of accessors as the Awesome module
    attr_accessor *Configuration::VALID_CONFIG_KEYS

    def initialize(options={})
      # Merge the config values from the module and those passed
      # to the client.
      merged_options = Awesome.options.merge(options)

      # Copy the merged values to this client and ignore those
      # not part of our configuration
      Configuration::VALID_CONFIG_KEYS.each do |key|
        send("#{key}=", merged_options[key])
      end
    end

  end # Client

end


text:
<!DOCTYPE html>
<!-- This test cannot be upstreamed to WPT because it tests the behavior of
  V8 full code cache generation (PWAFullCodeCache) which is spesific to
  Chromium. -->
<title>Service Worker: invalid JS file should not cause SW install error</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.js"></script>
<body>
<script>
// Tests that storing an invalid JS file with syntax error into cache storage in
// service worker install event handler should not cause install error. There
// was a bug that the full code cache generation can't handle the error
// correctly, so that the service worker installation failed. See
// crbug.com/832202 for details.
promise_test(function(t) {
    const scope = 'resources/invalid-code-cache-scope/';
    const script = 'resources/invalid-code-cache-worker.js';

    return service_worker_unregister_and_register(t, script, scope)
      .then(reg => wait_for_state(t, reg.installing, 'activated'))
      .then(() => service_worker_unregister_and_done(t, scope));
  }, 'Invalid JS file in CacheStorage should not cause SW install error');
</script>
</body>


text:
using NSubstitute;
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Toggl.Core.DTOs;
using Toggl.Core.Interactors;
using Toggl.Core.Models.Interfaces;
using Toggl.Storage;
using Xunit;

namespace Toggl.Core.Tests.Interactors.TimeEntry
{
    public class UpdateTimeEntryInteractorTests : BaseInteractorTests
    {
        private static DateTimeOffset now = new DateTimeOffset(2018, 05, 14, 18, 00, 00, TimeSpan.Zero);

        private readonly IThreadSafeTimeEntry timeEntry =
            Models.TimeEntry.Builder
                .Create(9)
                .SetUserId(10)
                .SetDescription("")
                .SetWorkspaceId(11)
                .SetSyncStatus(SyncStatus.InSync)
                .SetAt(now.AddDays(-1))
                .SetStart(now.AddHours(-2))
                .Build();

        private EditTimeEntryDto prepareTest()
        {
            var observable = Observable.Return(timeEntry);
            InteractorFactory.GetTimeEntryById(Arg.Is(timeEntry.Id))
                .Execute()
                .Returns(observable);

            var dto = new EditTimeEntryDto
            {
                Id = timeEntry.Id,
                Description = "New description",
                StartTime = DateTimeOffset.UtcNow,
                ProjectId = 13,
                Billable = true,
                WorkspaceId = 71,
                TagIds = new long[] { 1, 10, 34, 42 }
            };

            return dto;
        }

        private bool ensurePropertiesDidNotChange(IThreadSafeTimeEntry otherTimeEntry)
            => timeEntry.Id == otherTimeEntry.Id
            && timeEntry.UserId == otherTimeEntry.UserId
            && timeEntry.IsDeleted == otherTimeEntry.IsDeleted
            && timeEntry.ServerDeletedAt == otherTimeEntry.ServerDeletedAt;

        [Fact, LogIfTooSlow]
        public async Task UpdatesTheDescriptionProperty()
        {
            var dto = prepareTest();

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => te.Description == dto.Description));
        }

        [Fact, LogIfTooSlow]
        public async Task UpdatesTheSyncStatusProperty()
        {
            var dto = prepareTest();

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => te.SyncStatus == SyncStatus.SyncNeeded));
        }

        [Fact, LogIfTooSlow]
        public async Task UpdatesTheAtProperty()
        {
            var dto = prepareTest();
            TimeService.CurrentDateTime.Returns(DateTimeOffset.UtcNow);

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => te.At > timeEntry.At));
        }

        [Fact, LogIfTooSlow]
        public async Task UpdatesTheProjectId()
        {
            var dto = prepareTest();

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => te.ProjectId == dto.ProjectId));
        }

        [Fact, LogIfTooSlow]
        public async Task UpdatesTheBillbaleFlag()
        {
            var dto = prepareTest();

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => te.Billable == dto.Billable));
        }

        [Fact, LogIfTooSlow]
        public async Task UpdatesTheTagIds()
        {
            var dto = prepareTest();

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => te.TagIds.SequenceEqual(dto.TagIds)));
        }

        [Fact, LogIfTooSlow]
        public async Task UpdatesTheWorkspaceId()
        {
            var dto = prepareTest();

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => te.WorkspaceId == dto.WorkspaceId));
        }

        [Fact, LogIfTooSlow]
        public async Task LeavesAllOtherPropertiesUnchanged()
        {
            var dto = prepareTest();

            await new UpdateTimeEntryInteractor(TimeService, DataSource, InteractorFactory, SyncManager, dto).Execute();

            await DataSource.Received().TimeEntries.Update(Arg.Is<IThreadSafeTimeEntry>(te => ensurePropertiesDidNotChange(te)));
        }

        [Fact, LogIfTooSlow]
        public async Task TriggersPushSync()
        {
            var dto = prepareTest();

            await InteractorFactory.UpdateTimeEntry(dto).Execute();

            SyncManager.Received().PushSync();
        }
    }
}


text:
;
var tallybook = tallybook || {};

(function ($, host) {
  'use strict';
  var GridSymbols = {
    GRID_MAIN_TEMPLATE: ".template.grid-template"
  }
  var ModalStack = host.modal.stack;
  var entityProperty = host.entity.entityProperty;

  var FilterEventHandler = {
    inputChangeHandler: function (e) {
      var $el = $(this),
        inputElement = $el.closest('.input-element');

      var $delIcon = inputElement.find('i.embed-delete');
      var $input = inputElement.find('input.filter-input');
      if ($input) {
        var newVal = $input.val();
        (!!newVal) ? $delIcon.show() : $delIcon.hide();
      }
    },
    inputDelClickHandler: function (e) {
      var $el = $(this),
        inputElement = $el.closest('.input-element');

      var $delIcon = inputElement.find('i.embed-delete');
      var $input = inputElement.find('input.filter-input');
      if ($input) {
        $delIcon.hide();
        $input.val('').focus();
      }
    },
    resetFilterHandler: function (e) {
      var $el = $(e.currentTarget);
      var header = $el.closest('.column-header.dropdown');
      var $filter = header.find('.entity-filter');
      FilterHandlerManager.setValue($filter, '');
    },
    toOneEntityBtnHandler : function (e) {
      var $el = $(e.currentTarget);
      var header = $el.closest('.column-header.dropdown');
      var $filter = header.find('.entity-filter');
      if($filter.size() == 0)
        return;
      var url = $el.attr('data-select-url');
      var fieldFriendlyName = $el.attr('data-field-friendly-name');
      var doSelectModal = host.modal.makeModal({target: fieldFriendlyName}, host.entity.gridModal);
      doSelectModal.addOnHideCallback(function(modal){
        var entity = modal.selectedEntity();
        if(entity == null)
          return;
        var displayField = $el.attr('data-display-field');
        var idField = $el.attr('data-id-field');
        var id = entityProperty(entity,idField);
        var name = entityProperty(entity,displayField);
        var handler = host.entity.filterHandlerManager.getHandler('foreignkey');
        handler.addEntity($filter, id, name);
      })
      ModalStack.showModal(doSelectModal);
      doSelectModal.setContentByLink(url);
    },
    dropEntityBtnHandler : function (e) {
      var $el = $(e.currentTarget);
      var chosen = $el.closest('.chosen-entity');
      chosen.remove();
    }
  }

  var FilterHandlerManager = (function(){
    /**
     * Filter definition, define the initializer of filter, and how to access its value
     * Example:
     *      data-filter-type : string, integer-range, decimal range, foreign-key
     *      data-support-field-types : string, email, phone, boolean  (enum FieldType)
     * @param initializer: initialize the ui elements of the filter
     * @param valueaccess, define get/set (value in string) method of the filter,
     *        get: get value from the ui element, the return value in string
     *        set: set value to the ui element, input the value in string
     *        typically, the value of the ui element will be saved/restored from Column's 'input[type=hidden].filter-value' element
     * @constructor
     */
    var EmptyFilterHandler = {
      initializer : function (filter, fieldinfo){},
      //get: ui value -> string; set: string -> ui value
      get: function (entityFilter){return ""},
      set: function (entityFilter, val){}
    };
    function FilterHandler(handler) {
      $.extend(this, EmptyFilterHandler, handler);
    }
    FilterHandler.prototype={
      preInitialize : function(filter, fieldinfo, gridinfo){
        filter.data('grid-info', gridinfo);
        filter.data('field-info', fieldinfo);
      },
      getGridInfo : function(filter){return filter.data('grid-info');},
      getFieldInfo : function(filter){return filter.data('field-info');}
    }

    return {
      _handlers : { // keys are filter-types
        string: new FilterHandler({
          initializer : function (filter, fieldinfo) {
            var $input = $('input.filter-input', filter);
            $input.attr({'data-name': fieldinfo.name, 'placeholder': fieldinfo.friendlyName});
          },
          get: function (entityFilter) {
            return entityFilter.find('.filter-input').val();
          },
          set: function (entityFilter, val) {
            entityFilter.find('i.embed-delete').toggle(!!val);
            return entityFilter.find('.filter-input').val(val);
          }}),
        enumeration : new FilterHandler({
          initializer : function (filter, fieldinfo, gridinfo, valElem) {
              valElem.attr("data-multi-value", "true");
              valElem.data("multi-value", true);

            var $options = $('div.options', filter);
            var optionsVals = fieldinfo.options;
            var optionsNames = fieldinfo.optionsFriendly;
            optionsVals.forEach(function(opv){
//<input type="checkbox" name="gender" value="male">Male
              var opName = optionsNames[opv];
              var opipt = $('<input>', { 'type':"checkbox", 'name': fieldinfo.name, 'value': opv});
              var opspan = $('').text(opName);
              var op = $('',{ 'class':"option"}).append(opipt).append(opspan);
              $options.append(op);

            });
          },
          get: function (entityFilter) {
            var $options = $('.options .option input[type=checkbox]', entityFilter);
            var checkedVals = [];
            $options.filter(function(index, item){return item.checked;})
              .each(function(index, item){checkedVals.push($(item).attr('value'));});
            if(checkedVals.length == 0) return '';
            return JSON.stringify(checkedVals);
          },
          set: function (entityFilter, val) {
            var selectedVals = [];
            if(val){
              selectedVals = JSON.parse(val);
            }
            var $options = $('.options .option input[type=checkbox]', entityFilter);
            $options.each(function(index, item){
              var $item = $(item);
              var val = $item.attr('value');
              item.checked = !!(selectedVals.indexOf(val) >= 0);
            })
          }}),
        boolean : new FilterHandler({
          initializer : function (filter, fieldinfo){
            var trOpts = fieldinfo.options;
            filter.find('input[type=radio]').attr({'name' : fieldinfo.name});
            filter.find('input[type=radio][value=true]+span').text(trOpts.t);
            filter.find('input[type=radio][value=false]+span').text(trOpts.f);
          },
          //get: ui value -> string; set: string -> ui value
          get: function (entityFilter){
            var valStr = entityFilter.find('input[type=radio]:checked').val();
            if(!!valStr){
              return ('true' == valStr.toLowerCase())? 'true' : 'false';
            }else{
              return "";
            }
          },
          set: function (entityFilter, val){
            var trueRadio = entityFilter.find('input[type=radio][value=true]');
            var falseRadio = entityFilter.find('input[type=radio][value=false]');
            if(val === undefined || val === null || '' == val){
              trueRadio[0].checked=false;
              falseRadio[0].checked=false;
            }else{
              val = (val == 'true');
              trueRadio[0].checked=val;
              falseRadio[0].checked=!val;
            }}}),
        foreignkey : new FilterHandler({
          initializer : function (filter, fieldinfo, gridinfo, valElem){
            valElem.attr("data-multi-value", "true");
            valElem.data("multi-value", true);

            var fieldFriendlyName = fieldinfo.friendlyName;
            var selectUrl = fieldinfo.selectUri;
            var lookup = filter.find('.lookup-entity');
            lookup.attr({'data-field-name':fieldinfo.name,
              'data-field-friendly-name':fieldinfo.friendlyName,
              'data-display-field':fieldinfo.displayFieldName,
              'data-id-field':fieldinfo.idFieldName,
              'data-select-url':selectUrl
            });
            filter.attr('data-entity-type', fieldinfo.entityType);
            lookup.find('.with').text(fieldFriendlyName);
          },
          //get: ui value -> string; set: string -> ui value
          get: function (filter){
            var $chosens = filter.find('.chosen-entity');
            if($chosens.length == 0)
              return '';
            var chosenArray = [];
            $chosens.each(function(i,t){
              var $t = $(t);
              var id = $t.attr('data-entity-id');
              var name = $t.find('.entity-name').text();
              chosenArray.push({id:id, name : name});
            });
            return JSON.stringify(chosenArray);
          },
          set: function ($filter, val){
            var $chosens = $filter.find('.chosen-entity');
            $chosens.remove();
            if(null == val || '' == val)
              return;
            var selectedVals = [];
            if(val){
              selectedVals = JSON.parse(val);
            }
            var _this = this;
//            var arr = JSON.parse(val);
            selectedVals.forEach(function(tj,i){
              var t = JSON.parse(tj);
              var id = t.id;
              var name = t.name;
              _this.addEntity($filter, id, name);
            });
          },
          addEntity:function($filter, id, name){
            var $chosens = $filter.find('.chosen-entities');
            var exist = $chosens.find('.chosen-entity[data-entity-id='+id+']').length > 0;
            if(!exist){
              var fieldinfo = this.getFieldInfo($filter);
              var template = new UriTemplate(fieldinfo.recordUri);
              var entity4Tmp = {}; entity4Tmp[fieldinfo.idFieldName]=id;
              var url =template.fill(entity4Tmp);

              var newEle = $('

');
              var a = $('').attr('href', url);
              newEle.append(a);

              newEle.attr('data-entity-id', id);
              newEle.find('.entity-name').text(name);
              $chosens.append(newEle);
            }
          }}),
        dateRange : new FilterHandler({
          initializer : function (filter, fieldinfo){
            var datapickerops = $.extend({changeMonth: true,changeYear:true},JSON.parse(host.messages.datepicker_localization));
            var fromTb = $('.from', filter);
            var toTb = $('.to', filter);
            var fromOps = $.extend({onClose:function(selectedDate){
              toTb.datepicker('option', 'minDate', selectedDate);} }, datapickerops);
            var toOps = $.extend({onClose:function(selectedDate){
              fromTb.datepicker('option', 'maxDate', selectedDate);} }, datapickerops);

            $.timepicker.datetimeRange(
              fromTb,
              toTb,
              {
                minInterval: (1000*60*60), // 1hr
                dateFormat: host.messages.datepicker_format_date,
                timeFormat: host.messages.datepicker_format_timez,
                start: fromOps, // start picker options
                end: toOps // end picker options
              }
            );
          },
          dateToStr:function(date){
            if(date){return '' + date.getTime()}
            return '';},
          strToDate:function(dateStr){
            if(dateStr){return new Date(new Number(dateStr))}
            return null;
          },
          //get: ui value -> string; set: string -> ui value
          get: function (filter){
            var fromTb = $('.from', filter);
            var toTb = $('.to', filter);
            var fromDate = fromTb.datetimepicker('getDate')
            var toDate = toTb.datetimepicker('getDate')
            if(fromDate == null && toDate == null)
              return '';
            var vals = [];
            vals.push(this.dateToStr(fromDate));
            vals.push(this.dateToStr(toDate));
            return 'R' + vals.join('n') + 'G';
//            return JSON.stringify(['[' + vals.join(',') + ']']);
          },
          set: function (filter, val){
            if(val === undefined || val === null || '' == val){val = ['RnG'];}
            val=val[0];
            val = val.substr(1,val.length-2);
            var dateStrs = val.split('n');
            var fromDate = this.strToDate(dateStrs[0]);
            var toDate = this.strToDate(dateStrs[1]);

            var fromTb = $('.from', filter);
            var toTb = $('.to', filter);

            if(fromDate != null){
              fromTb.datetimepicker('setDate', fromDate);
            } else {
                fromTb.val('');
            }
            if(toDate != null){
                toTb.datetimepicker('setDate', toDate);
            }else{
                toTb.val('');
            }

            }})
      },
      /**
       * Get the filter template by field type
       * @param fieldType : the field type of the template
       */
      _getFilterTemplate: (function () {
        var filterMap = {};
        var $filters = $(GridSymbols.GRID_MAIN_TEMPLATE + ' table.entity-filters-table > tbody ul.entity-filter');
        $filters.each(function (index, fltr) {
          var $filter = $(fltr);
          var fldtypes = $filter.attr('data-support-field-types').split(',');
          fldtypes.forEach(function (fldtp) {
            filterMap[fldtp.trim().toLowerCase()] = $filter;
          })
        });
        return function (fieldType) {
          var filterTmplt = filterMap[fieldType];
          filterTmplt = filterTmplt? filterTmplt : filterMap['default'];
          return filterTmplt.clone();
        }
      })(),
      createFilterByFieldInfo : function(fieldinfo, gridinfo, valElem){
        var fieldType = fieldinfo.fieldType.toLowerCase();
        var filter = FilterHandlerManager._getFilterTemplate(fieldType);
        var filterType = filter.data('filter-type');
        $('input.filter-property', filter).val(fieldinfo.name);
        $('input.sort-property', filter).val('sort_' + fieldinfo.name);

        var fHandler = this._handlers[filterType];
        if(fHandler){
          fHandler.preInitialize && fHandler.preInitialize(filter, fieldinfo, gridinfo);
          fHandler.initializer && fHandler.initializer(filter, fieldinfo, gridinfo, valElem);
        }
        return filter;
      },
      getHandler : function(filterType){
        return this._handlers[filterType];
      },
      getValue : function($filter){
        var filterType = $filter.data('filter-type');
        if(filterType){
          var handler = this.getHandler(filterType);
          return handler.get($filter);
        }
      },
      setValue : function($filter, val){
        var filterType = $filter.data('filter-type');
        if(filterType){
          var handler = this.getHandler(filterType);
          return handler.set($filter, val);
        }
      },
      bindEventsOnFilterRow : function($row){
        $row.on('keyup change focusin', '.entity-filter span.input-element input.filter-input', FilterEventHandler.inputChangeHandler);
        $row.on('click', '.entity-filter span.input-element i.embed-delete', FilterEventHandler.inputDelClickHandler);
        $row.on('click', '.entity-filter .filter-reset-button', FilterEventHandler.resetFilterHandler);
        $row.on('click', '.entity-filter .lookup-entity', FilterEventHandler.toOneEntityBtnHandler);
        $row.on('click', '.entity-filter .chosen-entities .drop-entity', FilterEventHandler.dropEntityBtnHandler);
      },
      unbindEventsOnFilterRow : function($row){
        $row.off('keyup change focusin', '.entity-filter span.input-element input.filter-input', FilterEventHandler.inputChangeHandler);
        $row.off('click', '.entity-filter span.input-element i.embed-delete', FilterEventHandler.inputDelClickHandler);
        $row.off('click', '.entity-filter .filter-reset-button', FilterEventHandler.resetFilterHandler);
        $row.off('click', '.entity-filter .lookup-entity', FilterEventHandler.toOneEntityBtnHandler);
        $row.off('click', '.entity-filter .chosen-entities .drop-entity', FilterEventHandler.dropEntityBtnHandler);
      }
    }
  })();

  host.entity = $.extend({}, host.entity, {
    filterHandlerManager: FilterHandlerManager
  });

})(jQuery, tallybook);


text: <DataSource ID="JSExpression" serverConstructor="com.isomorphic.datasource.JSExpressionType"/>


text:
require "test_helper"
require "database/setup"

class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
  include ActiveJob::TestHelper

  setup { @user = User.create!(name: "DHH") }

  teardown { ActiveStorage::Blob.all.each(&:purge) }

  test "attach existing blob" do
    @user.avatar.attach create_blob(filename: "funky.jpg")
    assert_equal "funky.jpg", @user.avatar.filename.to_s
  end

  test "attach existing sgid blob" do
    @user.avatar.attach create_blob(filename: "funky.jpg").signed_id
    assert_equal "funky.jpg", @user.avatar.filename.to_s
  end

  test "attach new blob from a Hash" do
    @user.avatar.attach io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg"
    assert_equal "town.jpg", @user.avatar.filename.to_s
  end

  test "attach new blob from an UploadedFile" do
    file = file_fixture "racecar.jpg"
    @user.avatar.attach Rack::Test::UploadedFile.new file
    assert_equal "racecar.jpg", @user.avatar.filename.to_s
  end

  test "replace attached blob" do
    @user.avatar.attach create_blob(filename: "funky.jpg")

    perform_enqueued_jobs do
      assert_no_difference -> { ActiveStorage::Blob.count } do
        @user.avatar.attach create_blob(filename: "town.jpg")
      end
    end

    assert_equal "town.jpg", @user.avatar.filename.to_s
  end

  test "replace attached blob unsuccessfully" do
    @user.avatar.attach create_blob(filename: "funky.jpg")

    perform_enqueued_jobs do
      assert_raises do
        @user.avatar.attach nil
      end
    end

    assert_equal "funky.jpg", @user.reload.avatar.filename.to_s
    assert ActiveStorage::Blob.service.exist?(@user.avatar.key)
  end

  test "access underlying associations of new blob" do
    @user.avatar.attach create_blob(filename: "funky.jpg")
    assert_equal @user, @user.avatar_attachment.record
    assert_equal @user.avatar_attachment.blob, @user.avatar_blob
    assert_equal "funky.jpg", @user.avatar_attachment.blob.filename.to_s
  end

  test "purge attached blob" do
    @user.avatar.attach create_blob(filename: "funky.jpg")
    avatar_key = @user.avatar.key

    @user.avatar.purge
    assert_not @user.avatar.attached?
    assert_not ActiveStorage::Blob.service.exist?(avatar_key)
  end

  test "purge attached blob later when the record is destroyed" do
    @user.avatar.attach create_blob(filename: "funky.jpg")
    avatar_key = @user.avatar.key

    perform_enqueued_jobs do
      @user.destroy

      assert_nil ActiveStorage::Blob.find_by(key: avatar_key)
      assert_not ActiveStorage::Blob.service.exist?(avatar_key)
    end
  end

  test "attach existing blobs" do
    @user.highlights.attach create_blob(filename: "funky.jpg"), create_blob(filename: "wonky.jpg")

    assert_equal "funky.jpg", @user.highlights.first.filename.to_s
    assert_equal "wonky.jpg", @user.highlights.second.filename.to_s
  end

  test "attach new blobs" do
    @user.highlights.attach(
      { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg" },
      { io: StringIO.new("IT"), filename: "country.jpg", content_type: "image/jpg" })

    assert_equal "town.jpg", @user.highlights.first.filename.to_s
    assert_equal "country.jpg", @user.highlights.second.filename.to_s
  end

  test "find attached blobs" do
    @user.highlights.attach(
      { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg" },
      { io: StringIO.new("IT"), filename: "country.jpg", content_type: "image/jpg" })

    highlights = User.where(id: @user.id).with_attached_highlights.first.highlights

    assert_equal "town.jpg", highlights.first.filename.to_s
    assert_equal "country.jpg", highlights.second.filename.to_s
  end

  test "access underlying associations of new blobs" do
    @user.highlights.attach(
      { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg" },
      { io: StringIO.new("IT"), filename: "country.jpg", content_type: "image/jpg" })

    assert_equal @user, @user.highlights_attachments.first.record
    assert_equal @user.highlights_attachments.collect(&:blob).sort, @user.highlights_blobs.sort
    assert_equal "town.jpg", @user.highlights_attachments.first.blob.filename.to_s
  end

  test "purge attached blobs" do
    @user.highlights.attach create_blob(filename: "funky.jpg"), create_blob(filename: "wonky.jpg")
    highlight_keys = @user.highlights.collect(&:key)

    @user.highlights.purge
    assert_not @user.highlights.attached?
    assert_not ActiveStorage::Blob.service.exist?(highlight_keys.first)
    assert_not ActiveStorage::Blob.service.exist?(highlight_keys.second)
  end

  test "purge attached blobs later when the record is destroyed" do
    @user.highlights.attach create_blob(filename: "funky.jpg"), create_blob(filename: "wonky.jpg")
    highlight_keys = @user.highlights.collect(&:key)

    perform_enqueued_jobs do
      @user.destroy

      assert_nil ActiveStorage::Blob.find_by(key: highlight_keys.first)
      assert_not ActiveStorage::Blob.service.exist?(highlight_keys.first)

      assert_nil ActiveStorage::Blob.find_by(key: highlight_keys.second)
      assert_not ActiveStorage::Blob.service.exist?(highlight_keys.second)
    end
  end
end


text:
namespace boost {
namespace numeric {
namespace bindings {
namespace lapack {

//
// The detail namespace contains value-type-overloaded functions that
// dispatch to the appropriate back-end LAPACK-routine.
//
namespace detail {

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * float value-type.
//
template< typename UpLo >
inline std::ptrdiff_t spev( const char jobz, const UpLo, const fortran_int_t n,
        float* ap, float* w, float* z, const fortran_int_t ldz, float* work ) {
    fortran_int_t info(0);
    LAPACK_SSPEV( &jobz, &lapack_option< UpLo >::value, &n, ap, w, z, &ldz,
            work, &info );
    return info;
}

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * double value-type.
//
template< typename UpLo >
inline std::ptrdiff_t spev( const char jobz, const UpLo, const fortran_int_t n,
        double* ap, double* w, double* z, const fortran_int_t ldz,
        double* work ) {
    fortran_int_t info(0);
    LAPACK_DSPEV( &jobz, &lapack_option< UpLo >::value, &n, ap, w, z, &ldz,
            work, &info );
    return info;
}

} // namespace detail

//
// Value-type based template class. Use this class if you need a type
// for dispatching to spev.
//
template< typename Value >
struct spev_impl {

    typedef Value value_type;
    typedef typename remove_imaginary< Value >::type real_type;

    //
    // Static member function for user-defined workspaces, that
    // * Deduces the required arguments for dispatching to LAPACK, and
    // * Asserts that most arguments make sense.
    //
    template< typename MatrixAP, typename VectorW, typename MatrixZ,
            typename WORK >
    static std::ptrdiff_t invoke( const char jobz, MatrixAP& ap, VectorW& w,
            MatrixZ& z, detail::workspace1< WORK > work ) {
        namespace bindings = ::boost::numeric::bindings;
        typedef typename result_of::uplo_tag< MatrixAP >::type uplo;
        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixZ >::value) );
        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<
                typename bindings::value_type< MatrixAP >::type >::type,
                typename remove_const< typename bindings::value_type<
                VectorW >::type >::type >::value) );
        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<
                typename bindings::value_type< MatrixAP >::type >::type,
                typename remove_const< typename bindings::value_type<
                MatrixZ >::type >::type >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixAP >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorW >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixZ >::value) );
        BOOST_ASSERT( bindings::size(work.select(real_type())) >=
                min_size_work( bindings::size_column(ap) ));
        BOOST_ASSERT( bindings::size_column(ap) >= 0 );
        BOOST_ASSERT( bindings::size_minor(z) == 1 ||
                bindings::stride_minor(z) == 1 );
        BOOST_ASSERT( jobz == 'N' || jobz == 'V' );
        return detail::spev( jobz, uplo(), bindings::size_column(ap),
                bindings::begin_value(ap), bindings::begin_value(w),
                bindings::begin_value(z), bindings::stride_major(z),
                bindings::begin_value(work.select(real_type())) );
    }

    //
    // Static member function that
    // * Figures out the minimal workspace requirements, and passes
    //   the results to the user-defined workspace overload of the
    //   invoke static member function
    // * Enables the unblocked algorithm (BLAS level 2)
    //
    template< typename MatrixAP, typename VectorW, typename MatrixZ >
    static std::ptrdiff_t invoke( const char jobz, MatrixAP& ap, VectorW& w,
            MatrixZ& z, minimal_workspace ) {
        namespace bindings = ::boost::numeric::bindings;
        typedef typename result_of::uplo_tag< MatrixAP >::type uplo;
        bindings::detail::array< real_type > tmp_work( min_size_work(
                bindings::size_column(ap) ) );
        return invoke( jobz, ap, w, z, workspace( tmp_work ) );
    }

    //
    // Static member function that
    // * Figures out the optimal workspace requirements, and passes
    //   the results to the user-defined workspace overload of the
    //   invoke static member
    // * Enables the blocked algorithm (BLAS level 3)
    //
    template< typename MatrixAP, typename VectorW, typename MatrixZ >
    static std::ptrdiff_t invoke( const char jobz, MatrixAP& ap, VectorW& w,
            MatrixZ& z, optimal_workspace ) {
        namespace bindings = ::boost::numeric::bindings;
        typedef typename result_of::uplo_tag< MatrixAP >::type uplo;
        return invoke( jobz, ap, w, z, minimal_workspace() );
    }

    //
    // Static member function that returns the minimum size of
    // workspace-array work.
    //
    static std::ptrdiff_t min_size_work( const std::ptrdiff_t n ) {
        return 3*n;
    }
};

//
// Functions for direct use. These functions are overloaded for temporaries,
// so that wrapped types can still be passed and used for write-access. In
// addition, if applicable, they are overloaded for user-defined workspaces.
// Calls to these functions are passed to the spev_impl classes. In the
// documentation, most overloads are collapsed to avoid a large number of
// prototypes which are very similar.
//

//
// Overloaded function for spev. Its overload differs for
// * User-defined workspace
//
template< typename MatrixAP, typename VectorW, typename MatrixZ,
        typename Workspace >
inline typename boost::enable_if< detail::is_workspace< Workspace >,
        std::ptrdiff_t >::type
spev( const char jobz, MatrixAP& ap, VectorW& w, MatrixZ& z,
        Workspace work ) {
    return spev_impl< typename bindings::value_type<
            MatrixAP >::type >::invoke( jobz, ap, w, z, work );
}

//
// Overloaded function for spev. Its overload differs for
// * Default workspace-type (optimal)
//
template< typename MatrixAP, typename VectorW, typename MatrixZ >
inline typename boost::disable_if< detail::is_workspace< MatrixZ >,
        std::ptrdiff_t >::type
spev( const char jobz, MatrixAP& ap, VectorW& w, MatrixZ& z ) {
    return spev_impl< typename bindings::value_type<
            MatrixAP >::type >::invoke( jobz, ap, w, z, optimal_workspace() );
}

} // namespace lapack
} // namespace bindings
} // namespace numeric
} // namespace boost

#endif


text:
using System;

namespace Lucene.Net.Store
{

	/// <summary> Implements {@link LockFactory} for a single in-process instance,
	/// meaning all locking will take place through this one instance.
	/// Only use this {@link LockFactory} when you are certain all
	/// IndexReaders and IndexWriters for a given index are running
	/// against a single shared in-process Directory instance.  This is
	/// currently the default locking for RAMDirectory.
	///
	/// </summary>
	/// <seealso cref="LockFactory">
	/// </seealso>

	public class SingleInstanceLockFactory : LockFactory
	{

		private System.Collections.Hashtable locks = new System.Collections.Hashtable();

		public override Lock MakeLock(System.String lockName)
		{
			// We do not use the LockPrefix at all, because the private
			// HashSet instance effectively scopes the locking to this
			// single Directory instance.
			return new SingleInstanceLock(locks, lockName);
		}

		public override void  ClearLock(System.String lockName)
		{
			lock (locks)
			{
				if (locks.Contains(lockName))
				{
					locks.Remove(lockName);
				}
			}
		}
	}

	class SingleInstanceLock : Lock
	{

		internal System.String lockName;
		private System.Collections.Hashtable locks;

		public SingleInstanceLock(System.Collections.Hashtable locks, System.String lockName)
		{
			this.locks = locks;
			this.lockName = lockName;
		}

		public override bool Obtain()
		{
			lock (locks)
			{
                if (locks.Contains(lockName) == false)
                {
                    locks.Add(lockName, lockName);
                    return true;
                }
                return false;
			}
		}

		public override void  Release()
		{
			lock (locks)
			{
				locks.Remove(lockName);
			}
		}

		public override bool IsLocked()
		{
			lock (locks)
			{
				return locks.Contains(lockName);
			}
		}

		public override System.String ToString()
		{
			return "SingleInstanceLock: " + lockName;
		}
	}
}