text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.run.v1alpha1.model;

/**
 * k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta is metadata that all persisted resources must
 * have, which includes all objects users must create.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Run Admin API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ObjectMeta extends com.google.api.client.json.GenericJson {

  /**
   * (Optional) Annotations is an unstructured key value map stored with a resource that may be set
   * by external tools to store and retrieve arbitrary metadata. They are not queryable and should
   * be preserved when modifying objects. More info: https://kubernetes.io/docs/user-
   * guide/annotations
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> annotations;

  /**
   * (Optional) Not supported by Cloud Run The name of the cluster which the object belongs to. This
   * is used to distinguish resources with same name and namespace in different clusters. This field
   * is not set anywhere right now and apiserver is going to ignore it if set in create or update
   * request.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String clusterName;

  /**
   * (Optional) CreationTimestamp is a timestamp representing the server time when this object was
   * created. It is not guaranteed to be set in happens-before order across separate operations.
   * Clients may not set this value. It is represented in RFC3339 form and is in UTC. Populated by
   * the system. Read-only. Null for lists. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String creationTimestamp;

  /**
   * (Optional) Not supported by Cloud Run Number of seconds allowed for this object to gracefully
   * terminate before it will be removed from the system. Only set when deletionTimestamp is also
   * set. May only be shortened. Read-only.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer deletionGracePeriodSeconds;

  /**
   * (Optional) Not supported by Cloud Run DeletionTimestamp is RFC 3339 date and time at which this
   * resource will be deleted. This field is set by the server when a graceful deletion is requested
   * by the user, and is not directly settable by a client. The resource is expected to be deleted
   * (no longer visible from resource lists, and not reachable by name) after the time in this
   * field, once the finalizers list is empty. As long as the finalizers list contains items,
   * deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set
   * further into the future, although it may be shortened or the resource may be deleted prior to
   * this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet
   * will react by sending a graceful termination signal to the containers in the pod. After that 30
   * seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after
   * cleanup, remove the pod from the API. In the presence of network partitions, this object may
   * still exist after this timestamp, until an administrator or automated process can determine the
   * resource is fully terminated. If not set, graceful deletion of the object has not been
   * requested. Populated by the system when a graceful deletion is requested. Read-only. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String deletionTimestamp;

  /**
   * (Optional) Not supported by Cloud Run Must be empty before the object is deleted from the
   * registry. Each entry is an identifier for the responsible component that will remove the entry
   * from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only
   * be removed. +patchStrategy=merge
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> finalizers;

  /**
   * (Optional) Not supported by Cloud Run GenerateName is an optional prefix, used by the server,
   * to generate a unique name ONLY IF the Name field has not been provided. If this field is used,
   * the name returned to the client will be different than the name passed. This value will also be
   * combined with a unique suffix. The provided value has the same validation rules as the Name
   * field, and may be truncated by the length of the suffix required to make the value unique on
   * the server. If this field is specified and the generated name exists, the server will NOT
   * return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout
   * indicating a unique name could not be found in the time allotted, and the client should retry
   * (optionally after the time indicated in the Retry-After header). Applied only if Name is not
   * specified. More info: https://git.k8s.io/community/contributors/devel/api-
   * conventions.md#idempotency string generateName = 2;
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String generateName;

  /**
   * (Optional) A sequence number representing a specific generation of the desired state. Populated
   * by the system. Read-only.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer generation;

  /**
   * (Optional) Map of string keys and values that can be used to organize and categorize (scope and
   * select) objects. May match selectors of replication controllers and routes. More info:
   * https://kubernetes.io/docs/user-guide/labels
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> labels;

  /**
   * Name must be unique within a namespace, within a Cloud Run region. Is required when creating
   * resources, although some resources may allow a client to request the generation of an
   * appropriate name automatically. Name is primarily intended for creation idempotence and
   * configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/user-
   * guide/identifiers#names +optional
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * Namespace defines the space within each name must be unique, within a Cloud Run region. In
   * Cloud Run the namespace must be equal to either the project ID or project number.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String namespace;

  /**
   * (Optional) Not supported by Cloud Run List of objects that own this object. If ALL objects in
   * the list have been deleted, this object will be garbage collected.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<OwnerReference> ownerReferences;

  /**
   * Optional. An opaque value that represents the internal version of this object that can be used
   * by clients to determine when objects have changed. May be used for optimistic concurrency,
   * change detection, and the watch operation on a resource or set of resources. Clients must treat
   * these values as opaque and passed unmodified back to the server or omit the value to disable
   * conflict-detection. They may only be valid for a particular resource or set of resources.
   * Populated by the system. Read-only. Value must be treated as opaque by clients or omitted. More
   * info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
   * #concurrency-control-and-consistency
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String resourceVersion;

  /**
   * (Optional) SelfLink is a URL representing this object. Populated by the system. Read-only.
   * string selfLink = 4;
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String selfLink;

  /**
   * (Optional) UID is the unique in time and space value for this object. It is typically generated
   * by the server on successful creation of a resource and is not allowed to change on PUT
   * operations. Populated by the system. Read-only. More info: https://kubernetes.io/docs/user-
   * guide/identifiers#uids
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String uid;

  /**
   * (Optional) Annotations is an unstructured key value map stored with a resource that may be set
   * by external tools to store and retrieve arbitrary metadata. They are not queryable and should
   * be preserved when modifying objects. More info: https://kubernetes.io/docs/user-
   * guide/annotations
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getAnnotations() {
    return annotations;
  }

  /**
   * (Optional) Annotations is an unstructured key value map stored with a resource that may be set
   * by external tools to store and retrieve arbitrary metadata. They are not queryable and should
   * be preserved when modifying objects. More info: https://kubernetes.io/docs/user-
   * guide/annotations
   * @param annotations annotations or {@code null} for none
   */
  public ObjectMeta setAnnotations(java.util.Map<String, java.lang.String> annotations) {
    this.annotations = annotations;
    return this;
  }

  /**
   * (Optional) Not supported by Cloud Run The name of the cluster which the object belongs to. This
   * is used to distinguish resources with same name and namespace in different clusters. This field
   * is not set anywhere right now and apiserver is going to ignore it if set in create or update
   * request.
   * @return value or {@code null} for none
   */
  public java.lang.String getClusterName() {
    return clusterName;
  }

  /**
   * (Optional) Not supported by Cloud Run The name of the cluster which the object belongs to. This
   * is used to distinguish resources with same name and namespace in different clusters. This field
   * is not set anywhere right now and apiserver is going to ignore it if set in create or update
   * request.
   * @param clusterName clusterName or {@code null} for none
   */
  public ObjectMeta setClusterName(java.lang.String clusterName) {
    this.clusterName = clusterName;
    return this;
  }

  /**
   * (Optional) CreationTimestamp is a timestamp representing the server time when this object was
   * created. It is not guaranteed to be set in happens-before order across separate operations.
   * Clients may not set this value. It is represented in RFC3339 form and is in UTC. Populated by
   * the system. Read-only. Null for lists. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
   * @return value or {@code null} for none
   */
  public String getCreationTimestamp() {
    return creationTimestamp;
  }

  /**
   * (Optional) CreationTimestamp is a timestamp representing the server time when this object was
   * created. It is not guaranteed to be set in happens-before order across separate operations.
   * Clients may not set this value. It is represented in RFC3339 form and is in UTC. Populated by
   * the system. Read-only. Null for lists. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
   * @param creationTimestamp creationTimestamp or {@code null} for none
   */
  public ObjectMeta setCreationTimestamp(String creationTimestamp) {
    this.creationTimestamp = creationTimestamp;
    return this;
  }

  /**
   * (Optional) Not supported by Cloud Run Number of seconds allowed for this object to gracefully
   * terminate before it will be removed from the system. Only set when deletionTimestamp is also
   * set. May only be shortened. Read-only.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getDeletionGracePeriodSeconds() {
    return deletionGracePeriodSeconds;
  }

  /**
   * (Optional) Not supported by Cloud Run Number of seconds allowed for this object to gracefully
   * terminate before it will be removed from the system. Only set when deletionTimestamp is also
   * set. May only be shortened. Read-only.
   * @param deletionGracePeriodSeconds deletionGracePeriodSeconds or {@code null} for none
   */
  public ObjectMeta setDeletionGracePeriodSeconds(java.lang.Integer deletionGracePeriodSeconds) {
    this.deletionGracePeriodSeconds = deletionGracePeriodSeconds;
    return this;
  }

  /**
   * (Optional) Not supported by Cloud Run DeletionTimestamp is RFC 3339 date and time at which this
   * resource will be deleted. This field is set by the server when a graceful deletion is requested
   * by the user, and is not directly settable by a client. The resource is expected to be deleted
   * (no longer visible from resource lists, and not reachable by name) after the time in this
   * field, once the finalizers list is empty. As long as the finalizers list contains items,
   * deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set
   * further into the future, although it may be shortened or the resource may be deleted prior to
   * this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet
   * will react by sending a graceful termination signal to the containers in the pod. After that 30
   * seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after
   * cleanup, remove the pod from the API. In the presence of network partitions, this object may
   * still exist after this timestamp, until an administrator or automated process can determine the
   * resource is fully terminated. If not set, graceful deletion of the object has not been
   * requested. Populated by the system when a graceful deletion is requested. Read-only. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
   * @return value or {@code null} for none
   */
  public String getDeletionTimestamp() {
    return deletionTimestamp;
  }

  /**
   * (Optional) Not supported by Cloud Run DeletionTimestamp is RFC 3339 date and time at which this
   * resource will be deleted. This field is set by the server when a graceful deletion is requested
   * by the user, and is not directly settable by a client. The resource is expected to be deleted
   * (no longer visible from resource lists, and not reachable by name) after the time in this
   * field, once the finalizers list is empty. As long as the finalizers list contains items,
   * deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set
   * further into the future, although it may be shortened or the resource may be deleted prior to
   * this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet
   * will react by sending a graceful termination signal to the containers in the pod. After that 30
   * seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after
   * cleanup, remove the pod from the API. In the presence of network partitions, this object may
   * still exist after this timestamp, until an administrator or automated process can determine the
   * resource is fully terminated. If not set, graceful deletion of the object has not been
   * requested. Populated by the system when a graceful deletion is requested. Read-only. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
   * @param deletionTimestamp deletionTimestamp or {@code null} for none
   */
  public ObjectMeta setDeletionTimestamp(String deletionTimestamp) {
    this.deletionTimestamp = deletionTimestamp;
    return this;
  }

  /**
   * (Optional) Not supported by Cloud Run Must be empty before the object is deleted from the
   * registry. Each entry is an identifier for the responsible component that will remove the entry
   * from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only
   * be removed. +patchStrategy=merge
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getFinalizers() {
    return finalizers;
  }

  /**
   * (Optional) Not supported by Cloud Run Must be empty before the object is deleted from the
   * registry. Each entry is an identifier for the responsible component that will remove the entry
   * from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only
   * be removed. +patchStrategy=merge
   * @param finalizers finalizers or {@code null} for none
   */
  public ObjectMeta setFinalizers(java.util.List<java.lang.String> finalizers) {
    this.finalizers = finalizers;
    return this;
  }

  /**
   * (Optional) Not supported by Cloud Run GenerateName is an optional prefix, used by the server,
   * to generate a unique name ONLY IF the Name field has not been provided. If this field is used,
   * the name returned to the client will be different than the name passed. This value will also be
   * combined with a unique suffix. The provided value has the same validation rules as the Name
   * field, and may be truncated by the length of the suffix required to make the value unique on
   * the server. If this field is specified and the generated name exists, the server will NOT
   * return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout
   * indicating a unique name could not be found in the time allotted, and the client should retry
   * (optionally after the time indicated in the Retry-After header). Applied only if Name is not
   * specified. More info: https://git.k8s.io/community/contributors/devel/api-
   * conventions.md#idempotency string generateName = 2;
   * @return value or {@code null} for none
   */
  public java.lang.String getGenerateName() {
    return generateName;
  }

  /**
   * (Optional) Not supported by Cloud Run GenerateName is an optional prefix, used by the server,
   * to generate a unique name ONLY IF the Name field has not been provided. If this field is used,
   * the name returned to the client will be different than the name passed. This value will also be
   * combined with a unique suffix. The provided value has the same validation rules as the Name
   * field, and may be truncated by the length of the suffix required to make the value unique on
   * the server. If this field is specified and the generated name exists, the server will NOT
   * return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout
   * indicating a unique name could not be found in the time allotted, and the client should retry
   * (optionally after the time indicated in the Retry-After header). Applied only if Name is not
   * specified. More info: https://git.k8s.io/community/contributors/devel/api-
   * conventions.md#idempotency string generateName = 2;
   * @param generateName generateName or {@code null} for none
   */
  public ObjectMeta setGenerateName(java.lang.String generateName) {
    this.generateName = generateName;
    return this;
  }

  /**
   * (Optional) A sequence number representing a specific generation of the desired state. Populated
   * by the system. Read-only.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getGeneration() {
    return generation;
  }

  /**
   * (Optional) A sequence number representing a specific generation of the desired state. Populated
   * by the system. Read-only.
   * @param generation generation or {@code null} for none
   */
  public ObjectMeta setGeneration(java.lang.Integer generation) {
    this.generation = generation;
    return this;
  }

  /**
   * (Optional) Map of string keys and values that can be used to organize and categorize (scope and
   * select) objects. May match selectors of replication controllers and routes. More info:
   * https://kubernetes.io/docs/user-guide/labels
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getLabels() {
    return labels;
  }

  /**
   * (Optional) Map of string keys and values that can be used to organize and categorize (scope and
   * select) objects. May match selectors of replication controllers and routes. More info:
   * https://kubernetes.io/docs/user-guide/labels
   * @param labels labels or {@code null} for none
   */
  public ObjectMeta setLabels(java.util.Map<String, java.lang.String> labels) {
    this.labels = labels;
    return this;
  }

  /**
   * Name must be unique within a namespace, within a Cloud Run region. Is required when creating
   * resources, although some resources may allow a client to request the generation of an
   * appropriate name automatically. Name is primarily intended for creation idempotence and
   * configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/user-
   * guide/identifiers#names +optional
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Name must be unique within a namespace, within a Cloud Run region. Is required when creating
   * resources, although some resources may allow a client to request the generation of an
   * appropriate name automatically. Name is primarily intended for creation idempotence and
   * configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/user-
   * guide/identifiers#names +optional
   * @param name name or {@code null} for none
   */
  public ObjectMeta setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * Namespace defines the space within each name must be unique, within a Cloud Run region. In
   * Cloud Run the namespace must be equal to either the project ID or project number.
   * @return value or {@code null} for none
   */
  public java.lang.String getNamespace() {
    return namespace;
  }

  /**
   * Namespace defines the space within each name must be unique, within a Cloud Run region. In
   * Cloud Run the namespace must be equal to either the project ID or project number.
   * @param namespace namespace or {@code null} for none
   */
  public ObjectMeta setNamespace(java.lang.String namespace) {
    this.namespace = namespace;
    return this;
  }

  /**
   * (Optional) Not supported by Cloud Run List of objects that own this object. If ALL objects in
   * the list have been deleted, this object will be garbage collected.
   * @return value or {@code null} for none
   */
  public java.util.List<OwnerReference> getOwnerReferences() {
    return ownerReferences;
  }

  /**
   * (Optional) Not supported by Cloud Run List of objects that own this object. If ALL objects in
   * the list have been deleted, this object will be garbage collected.
   * @param ownerReferences ownerReferences or {@code null} for none
   */
  public ObjectMeta setOwnerReferences(java.util.List<OwnerReference> ownerReferences) {
    this.ownerReferences = ownerReferences;
    return this;
  }

  /**
   * Optional. An opaque value that represents the internal version of this object that can be used
   * by clients to determine when objects have changed. May be used for optimistic concurrency,
   * change detection, and the watch operation on a resource or set of resources. Clients must treat
   * these values as opaque and passed unmodified back to the server or omit the value to disable
   * conflict-detection. They may only be valid for a particular resource or set of resources.
   * Populated by the system. Read-only. Value must be treated as opaque by clients or omitted. More
   * info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
   * #concurrency-control-and-consistency
   * @return value or {@code null} for none
   */
  public java.lang.String getResourceVersion() {
    return resourceVersion;
  }

  /**
   * Optional. An opaque value that represents the internal version of this object that can be used
   * by clients to determine when objects have changed. May be used for optimistic concurrency,
   * change detection, and the watch operation on a resource or set of resources. Clients must treat
   * these values as opaque and passed unmodified back to the server or omit the value to disable
   * conflict-detection. They may only be valid for a particular resource or set of resources.
   * Populated by the system. Read-only. Value must be treated as opaque by clients or omitted. More
   * info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
   * #concurrency-control-and-consistency
   * @param resourceVersion resourceVersion or {@code null} for none
   */
  public ObjectMeta setResourceVersion(java.lang.String resourceVersion) {
    this.resourceVersion = resourceVersion;
    return this;
  }

  /**
   * (Optional) SelfLink is a URL representing this object. Populated by the system. Read-only.
   * string selfLink = 4;
   * @return value or {@code null} for none
   */
  public java.lang.String getSelfLink() {
    return selfLink;
  }

  /**
   * (Optional) SelfLink is a URL representing this object. Populated by the system. Read-only.
   * string selfLink = 4;
   * @param selfLink selfLink or {@code null} for none
   */
  public ObjectMeta setSelfLink(java.lang.String selfLink) {
    this.selfLink = selfLink;
    return this;
  }

  /**
   * (Optional) UID is the unique in time and space value for this object. It is typically generated
   * by the server on successful creation of a resource and is not allowed to change on PUT
   * operations. Populated by the system. Read-only. More info: https://kubernetes.io/docs/user-
   * guide/identifiers#uids
   * @return value or {@code null} for none
   */
  public java.lang.String getUid() {
    return uid;
  }

  /**
   * (Optional) UID is the unique in time and space value for this object. It is typically generated
   * by the server on successful creation of a resource and is not allowed to change on PUT
   * operations. Populated by the system. Read-only. More info: https://kubernetes.io/docs/user-
   * guide/identifiers#uids
   * @param uid uid or {@code null} for none
   */
  public ObjectMeta setUid(java.lang.String uid) {
    this.uid = uid;
    return this;
  }

  @Override
  public ObjectMeta set(String fieldName, Object value) {
    return (ObjectMeta) super.set(fieldName, value);
  }

  @Override
  public ObjectMeta clone() {
    return (ObjectMeta) super.clone();
  }

}

redpajama_set_name: RedPajamaGithub


text:
---
layout: jsdoc
title: "Source: packages/workbox-precaching/src/index.js"
jsdocNav:
  - Modules:
    - workbox-background-sync
    - workbox-broadcast-cache-update
    - workbox-build
    - workbox-cache-expiration
    - workbox-cacheable-response
    - workbox-google-analytics
    - workbox-precaching
    - workbox-routing
    - workbox-runtime-caching
    - workbox-sw
---

/**
 * # workbox-precaching
 *
 * The precaching module provides helpers that make it easy to cache files
 * during the install step of your service worker.
 *
 * **Install:** `npm install --save-dev workbox-precaching`
 *
 * The revisioned caching will cache bust requests where appropriate and
 * only cache assets that have a changed revision asset compared to
 * the currently cached value.
 *
 * @example
 * importScripts('/<Path to Module>/build/workbox-precaching.min.js');
 *
 * const revCacheManager = new workbox.precaching.RevisionedCacheManager();
 * revCacheManager.addToCacheList({
 *   revisionedFiles: [
 *     '/styles/main.1234.css',
 *     {
 *       url: '/',
 *       revision: '1234'
 *     }
 *   ],
 * });
 *
 * const unrevCacheManager = new workbox.precaching.UnrevisionedCacheManager();
 * unrevCacheManager.addToCacheList({
 *   unrevisionedFiles: [
 *     '/',
 *     '/images/logo.png'
 *   ]
 * });
 *
 * self.addEventListener('install', (event) => {
 *   const promiseChain = Promise.all([
 *     revCacheManager.install(),
 *     unrevCacheManager.install(),
 *   ]);
 *   event.waitUntil(promiseChain);
 * });
 *
 * self.addEventListener('activate', (event) => {
 *   const promiseChain = Promise.all([
 *     revCacheManager.cleanup(),
 *     unrevCacheManager.cleanup()
 *   ]);
 *   event.waitUntil(promiseChain);
 * });
 *
 * @module workbox-precaching
 */
import ErrorFactory from './lib/error-factory';
import RevisionedCacheManager from
  './lib/controllers/revisioned-cache-manager.js';
import UnrevisionedCacheManager from
  './lib/controllers/unrevisioned-cache-manager.js';

import environment from '../../../lib/environment.js';

if (!environment.isServiceWorkerGlobalScope()) {
  // We are not running in a service worker, print error message
  throw ErrorFactory.createError('not-in-sw');
}

export {
  RevisionedCacheManager,
  UnrevisionedCacheManager,
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />

    <title>Conducting an Identifier Lookup</title>
    <link rel="StyleSheet" href="css/i-spy_ID_Lookup.css" type="text/css" media="all" />
    <link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" />

Conducting an Identifier Lookup

Conducting an Identifier Lookup

This section describes how to use I-SPY to look up patient identifiers or sample identifiers.

Topics in this section include:

•

ID Lookup Overview

•

Looking Up a Patient or Sample Identifier


text:
package org.kie.workbench.common.stunner.core.util;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class StringUtilsTest {

    @Test
    public void testNull() {
        assertTrue(StringUtils.isEmpty(null));
        assertFalse(StringUtils.nonEmpty(null));
    }

    @Test
    public void testEmpty() {
        assertTrue(StringUtils.isEmpty(""));
        assertFalse(StringUtils.nonEmpty(""));
    }

    @Test
    public void testNonNullNonEmpty() {
        assertFalse(StringUtils.isEmpty("string"));
        assertTrue(StringUtils.nonEmpty("string"));
    }

    @Test
    public void testHasNonEmpty() {
        assertFalse(StringUtils.hasNonEmpty((String[]) null));
        assertFalse(StringUtils.hasNonEmpty((String) null));
        assertFalse(StringUtils.hasNonEmpty(null, null, null));
        assertFalse(StringUtils.hasNonEmpty(null, "", null));
        assertTrue(StringUtils.hasNonEmpty(null, "", "someValue"));
    }
}


text:
  class PasswordController < ApplicationController

  LINK_EXPIRED = "Your reset link has expired, Please generate a new one"
  PASSWORD_RESET = "Your password has been successfully reset."

  def edit
    unless @user = User.find_by_code( params[:code] )
      redirect_to login_url, notice: LINK_EXPIRED
    end
  end

  def update
    if @user = User.find_by_code( params[:code] )
    # if user is found
      if PasswordResetter.new(flash).update_password( @user, user_params )
        return if log_user_in( @user, PASSWORD_RESET )
        # redirect_to( root_url, notice: PASSWORD_RESET ) and return
      else
        flash.now[:alert] = @user.errors
      end

    # otherwise show a message not found
    else
      flash.now[:alert] = LINK_EXPIRED
    end
    render :edit

  end

  private

  def user_params
    params.require(:user).permit(:password, :password_confirmation)
  end

end


text:
namespace MassTransit.SagaStateMachine
{
    using System;
    using System.Threading.Tasks;
    using RetryPolicies;

    public class RetryActivity<TInstance> :
        IStateMachineActivity<TInstance>
        where TInstance : class, ISaga
    {
        readonly IBehavior<TInstance> _retryBehavior;
        readonly IRetryPolicy _retryPolicy;

        public RetryActivity(IRetryPolicy retryPolicy, IBehavior<TInstance> retryBehavior)
        {
            _retryPolicy = retryPolicy;
            _retryBehavior = retryBehavior;
        }

        public void Probe(ProbeContext context)
        {
            var scope = context.CreateScope("retry");

            _retryBehavior.Probe(scope);
        }

        public void Accept(StateMachineVisitor visitor)
        {
            visitor.Visit(this, x => _retryBehavior.Accept(visitor));
        }

        public async Task Execute(BehaviorContext<TInstance> context, IBehavior<TInstance> next)
        {
            await _retryPolicy.Retry(() => _retryBehavior.Execute(context), context.CancellationToken);

            await next.Execute(context).ConfigureAwait(false);
        }

        public async Task Execute<T>(BehaviorContext<TInstance, T> context, IBehavior<TInstance, T> next)
            where T : class
        {
            await _retryPolicy.Retry(() => _retryBehavior.Execute(context), context.CancellationToken);

            await next.Execute(context).ConfigureAwait(false);
        }

        public Task Faulted<TException>(BehaviorExceptionContext<TInstance, TException> context, IBehavior<TInstance> next)
            where TException : Exception
        {
            return next.Faulted(context);
        }

        public Task Faulted<T, TException>(BehaviorExceptionContext<TInstance, T, TException> context, IBehavior<TInstance, T> next)
            where T : class
            where TException : Exception
        {
            return next.Faulted(context);
        }
    }

    public class RetryActivity<TInstance, TMessage> :
        IStateMachineActivity<TInstance>
        where TInstance : class, ISaga
        where TMessage : class
    {
        readonly IBehavior<TInstance> _retryBehavior;
        readonly IRetryPolicy _retryPolicy;

        public RetryActivity(IRetryPolicy retryPolicy, IBehavior<TInstance> retryBehavior)
        {
            _retryPolicy = retryPolicy;
            _retryBehavior = retryBehavior;
        }

        public void Probe(ProbeContext context)
        {
            var scope = context.CreateScope("retry");

            _retryBehavior.Probe(scope);
        }

        public void Accept(StateMachineVisitor visitor)
        {
            visitor.Visit(this, x => _retryBehavior.Accept(visitor));
        }

        public Task Execute(BehaviorContext<TInstance> context, IBehavior<TInstance> next)
        {
            throw new SagaStateMachineException("This activity requires a body with the event, but no body was specified.");
        }

        public async Task Execute<T>(BehaviorContext<TInstance, T> context, IBehavior<TInstance, T> next)
            where T : class
        {
            if (context is BehaviorContext<TInstance, TMessage> behaviorContext)
                await _retryPolicy.Retry(() => _retryBehavior.Execute(behaviorContext), context.CancellationToken);

            await next.Execute(context).ConfigureAwait(false);
        }

        public Task Faulted<TException>(BehaviorExceptionContext<TInstance, TException> context, IBehavior<TInstance> next)
            where TException : Exception
        {
            return next.Faulted(context);
        }

        public Task Faulted<T, TException>(BehaviorExceptionContext<TInstance, T, TException> context, IBehavior<TInstance, T> next)
            where T : class
            where TException : Exception
        {
            return next.Faulted(context);
        }
    }
}


text:
using System.Collections.ObjectModel;

namespace Newbe.Mahua
{
    /// <summary>
    /// Mahua 传入参数
    /// </summary>
    public interface IInput
    {
        string TypeCode { get; }
        MahuaPlatform MahuaPlatform { get; }
        ReadOnlyDictionary<string, object> Data { get; }
    }
}


text:
import * as chalk from 'chalk';
import { Cursor } from './db/datastore/cursor/cursor';
import * as util from 'util';

export let repl = require('repl').start({
  prompt: chalk.green('> '),
  useGlobal: true,
  ignoreUndefined: true,
  writer: (output: Cursor) => {
    if(output instanceof Cursor) {
      return output.pretty();
    }
    else {
      return util.inspect(output);
    }
  }
});


text:
"""This module provides a JSON-based codec implementation that uses the
:mod:`zlib` module to reduce the encoded flash footprint.
"""

import zlib

from djangoflash.codec.json_impl import CodecClass as JSONCodecClass
from djangoflash.models import FlashScope

class CodecClass(JSONCodecClass):
    """JSON/zlib-based codec implementation.
    """
    def __init__(self):
        """Returns a new JSON/zlib-based codec.
        """
        JSONCodecClass.__init__(self)

    def encode(self, flash):
        """Encodes the given *flash* as a zlib compressed JSON string.
        """
        return zlib.compress(JSONCodecClass.encode(self, flash))

    def decode(self, encoded_flash):
        """Restores the *flash* from the given zlib compressed JSON string.
        """
        return JSONCodecClass.decode(self, zlib.decompress(encoded_flash))


text:
package com.microsoft.azure.management.datamigration.v2018_03_31_preview.implementation;

import com.microsoft.azure.management.datamigration.v2018_03_31_preview.AvailableServiceSkuSku;
import com.microsoft.azure.management.datamigration.v2018_03_31_preview.AvailableServiceSkuCapacity;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Describes the available service SKU.
 */
public class AvailableServiceSkuInner {
    /**
     * The resource type, including the provider namespace.
     */
    @JsonProperty(value = "resourceType")
    private String resourceType;

    /**
     * SKU name, tier, etc.
     */
    @JsonProperty(value = "sku")
    private AvailableServiceSkuSku sku;

    /**
     * A description of the scaling capacities of the SKU.
     */
    @JsonProperty(value = "capacity")
    private AvailableServiceSkuCapacity capacity;

    /**
     * Get the resource type, including the provider namespace.
     *
     * @return the resourceType value
     */
    public String resourceType() {
        return this.resourceType;
    }

    /**
     * Set the resource type, including the provider namespace.
     *
     * @param resourceType the resourceType value to set
     * @return the AvailableServiceSkuInner object itself.
     */
    public AvailableServiceSkuInner withResourceType(String resourceType) {
        this.resourceType = resourceType;
        return this;
    }

    /**
     * Get sKU name, tier, etc.
     *
     * @return the sku value
     */
    public AvailableServiceSkuSku sku() {
        return this.sku;
    }

    /**
     * Set sKU name, tier, etc.
     *
     * @param sku the sku value to set
     * @return the AvailableServiceSkuInner object itself.
     */
    public AvailableServiceSkuInner withSku(AvailableServiceSkuSku sku) {
        this.sku = sku;
        return this;
    }

    /**
     * Get a description of the scaling capacities of the SKU.
     *
     * @return the capacity value
     */
    public AvailableServiceSkuCapacity capacity() {
        return this.capacity;
    }

    /**
     * Set a description of the scaling capacities of the SKU.
     *
     * @param capacity the capacity value to set
     * @return the AvailableServiceSkuInner object itself.
     */
    public AvailableServiceSkuInner withCapacity(AvailableServiceSkuCapacity capacity) {
        this.capacity = capacity;
        return this;
    }

}


text:
var _ = require('lodash');
var Chance = require('chance');

// Declare internals

var internals = {
    localStorageKey: 'clientId'
};

exports = module.exports = internals.ClientIdGenerator = {};

internals.ClientIdGenerator.generate = function () {

    var chance = new Chance();

    var word = chance.word({ length: 3 });
    var numbers = chance.string({ length: 3, pool: '1234567890' });

    return word + numbers;
};


text:
package org.kie.workbench.common.dmn.client.shape.factory;

import java.util.function.Supplier;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.api.definition.DMNDefinition;
import org.kie.workbench.common.dmn.api.definition.model.Association;
import org.kie.workbench.common.dmn.api.definition.model.AuthorityRequirement;
import org.kie.workbench.common.dmn.api.definition.model.BusinessKnowledgeModel;
import org.kie.workbench.common.dmn.api.definition.model.DMNDiagram;
import org.kie.workbench.common.dmn.api.definition.model.Decision;
import org.kie.workbench.common.dmn.api.definition.model.DecisionService;
import org.kie.workbench.common.dmn.api.definition.model.InformationRequirement;
import org.kie.workbench.common.dmn.api.definition.model.InputData;
import org.kie.workbench.common.dmn.api.definition.model.KnowledgeRequirement;
import org.kie.workbench.common.dmn.api.definition.model.KnowledgeSource;
import org.kie.workbench.common.dmn.api.definition.model.TextAnnotation;
import org.kie.workbench.common.dmn.client.shape.def.DMNConnectorShapeDefImpl;
import org.kie.workbench.common.dmn.client.shape.def.DMNSVGShapeDefImpl;
import org.kie.workbench.common.stunner.core.client.shape.Shape;
import org.kie.workbench.common.stunner.core.client.shape.factory.DelegateShapeFactory;
import org.kie.workbench.common.stunner.core.client.shape.factory.ShapeFactory;
import org.kie.workbench.common.stunner.core.definition.shape.ShapeDef;
import org.kie.workbench.common.stunner.svg.client.shape.factory.SVGShapeFactory;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class DMNShapeFactoryTest {

    private static final String DEFINITION_ID = "definition-id";

    @Mock
    private SVGShapeFactory svgShapeFactory;

    @Mock
    private DMNConnectorShapeFactory dmnConnectorShapeFactory;

    @Mock
    private DMNDecisionServiceShapeFactory dmnDecisionServiceShapeFactory;

    @Mock
    private DelegateShapeFactory<DMNDefinition, Shape> delegateShapeFactory;

    @Mock
    private DMNDefinition definition;

    @Captor
    private ArgumentCaptor<Supplier> shapeDefFactoryCaptor;

    private DMNShapeFactory factory;

    @Before
    @SuppressWarnings("unchecked")
    public void setup() {
        this.factory = new DMNShapeFactory(svgShapeFactory,
                                           dmnConnectorShapeFactory,
                                           dmnDecisionServiceShapeFactory,
                                           delegateShapeFactory);

        when(delegateShapeFactory.delegate(any(Class.class),
                                           any(ShapeDef.class),
                                           any(Supplier.class))).thenReturn(delegateShapeFactory);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testInit() {
        factory.init();

        verify(delegateShapeFactory).delegate(eq(DMNDiagram.class),
                                              any(DMNSVGShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(svgShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(InputData.class),
                                              any(DMNSVGShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(svgShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(KnowledgeSource.class),
                                              any(DMNSVGShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(svgShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(BusinessKnowledgeModel.class),
                                              any(DMNSVGShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(svgShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(Decision.class),
                                              any(DMNSVGShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(svgShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(TextAnnotation.class),
                                              any(DMNSVGShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(svgShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(Association.class),
                                              any(DMNConnectorShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(dmnConnectorShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(AuthorityRequirement.class),
                                              any(DMNConnectorShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(dmnConnectorShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(InformationRequirement.class),
                                              any(DMNConnectorShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(dmnConnectorShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(KnowledgeRequirement.class),
                                              any(DMNConnectorShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(dmnConnectorShapeFactory, shapeDefFactoryCaptor.getValue().get());

        verify(delegateShapeFactory).delegate(eq(DecisionService.class),
                                              any(DMNSVGShapeDefImpl.class),
                                              shapeDefFactoryCaptor.capture());
        assertEquals(dmnDecisionServiceShapeFactory, shapeDefFactoryCaptor.getValue().get());
    }

    @Test
    public void testNewShape() {
        factory.newShape(definition);

        verify(delegateShapeFactory).newShape(definition);
    }

    @Test
    public void testGetGlyph() {
        factory.getGlyph(DEFINITION_ID);

        verify(delegateShapeFactory).getGlyph(DEFINITION_ID);
    }

    @Test
    public void testGetGlyphWithConsumer() {
        factory.getGlyph(DEFINITION_ID, ShapeFactory.GlyphConsumer.class);

        verify(delegateShapeFactory).getGlyph(DEFINITION_ID, ShapeFactory.GlyphConsumer.class);
    }
}


text:
package com.github.sixro.ch4r63.adapter.webhook;

import static com.github.tomakehurst.wiremock.client.WireMock.*;

import java.net.*;
import java.time.LocalDateTime;

import org.junit.*;

import com.github.tomakehurst.wiremock.junit.WireMockRule;

public class WebHookFactoryTest {

	public static final int LOCAL_PORT = 12345;

	@Rule public WireMockRule wireMockRule = new WireMockRule(LOCAL_PORT);

	private URL notificationURL;

	@Before public void setup() throws MalformedURLException
	{
		notificationURL = new URL(String.format("http://localhost:%s/webhooks", LOCAL_PORT));
	}

	@Test
	public void handle_call() throws MalformedURLException
	{
		stubFor(
			post(urlEqualTo("/webhooks"))
			.willReturn(aResponse().withStatus(200))
		);

		TestListener listener = WebHookFactory.newWebHookAs(TestListener.class, new WebHook(notificationURL));

		listener.callExecuted(new ExecutionData(LocalDateTime.parse("2017-02-07T10:20:30.456")));

		verify(
			postRequestedFor(urlEqualTo("/webhooks"))
			.withRequestBody(equalToJson(
				"{ \"event\": \"call_executed\", " +
					"\"data\": {" +
					  "\"execution_data\": { \"timestamp\": \"2017-02-07T10:20:30.456\" } " +
					"  }" +
				"}", true, true))
		);
	}

	// TODO does nothing when method is not void

	public interface TestListener {

		void callExecuted(ExecutionData executionData);

	}

}


text:
package org.shirolang.functions;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.shirolang.functions.conditionals.SConditionalReturnTest;
import org.shirolang.functions.finance.FinanceSuite;
import org.shirolang.functions.lists.SMapTest;
import org.shirolang.functions.math.MathSuite;

/**
 * Tests the internal runtime functions
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
        SConditionalReturnTest.class,
        FinanceSuite.class,
        SMapTest.class,
        MathSuite.class
})
public class FunctionsSuite {
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using Microsoft.CodeAnalysis.Internal.Log;

namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers
{
    internal static class FxCopAnalyzersInstallLogger
    {
        private const string Name = "FxCopAnalyzersInstall";

        public static void Log(string action)
        {
            Logger.Log(FunctionId.FxCopAnalyzersInstall, KeyValueLogMessage.Create(LogType.UserAction, m =>
            {
                m[nameof(Name)] = Name;
                m[nameof(action)] = action;
            }));
        }

        public static void LogVsixInstallationStatus(Workspace workspace, FxCopAnalyzersInstallStatus installStatus)
        {
            var installed = workspace.Options.GetOption(FxCopAnalyzersInstallOptions.VsixInstalled);
            if (!installed && installStatus == FxCopAnalyzersInstallStatus.Installed)
            {
                // first time after vsix installed
                workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
                    .WithChangedOption(FxCopAnalyzersInstallOptions.VsixInstalled, true)));
                Log("VsixInstalled");
            }

            if (installed && installStatus == FxCopAnalyzersInstallStatus.NotInstalled)
            {
                // first time after vsix is uninstalled
                workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
                    .WithChangedOption(FxCopAnalyzersInstallOptions.VsixInstalled, false)));
                Log("VsixUninstalled");
            }
        }

        public static void LogCandidacyRequirementsTracking(long lastTriggeredTimeBinary)
        {
            if (lastTriggeredTimeBinary == FxCopAnalyzersInstallOptions.LastDateTimeUsedSuggestionAction.DefaultValue)
            {
                Log("StartCandidacyRequirementsTracking");
            }
        }
    }
}


text:
`rest-io` supports adding custom actions on resources.

## Quick Start
To create a Custom Resource you extend the Resource class:

```javascript
import { Resource } from 'rest-io';

export default class BananaResource extends Resource {
  ...
}
```

Now you can overwrite the standard calls:

```javascript
export default class BananaResource extends Resource {
  getAll(req, res) {
    res.status(200).send('awesome!');
  }
}
```

## API
These are the functions you can overwrite or use:

### getAll(req, res, next)
This is the callback of the [express route handler](http://expressjs.com/guide/routing.html).

### getById(req, res, next)
This is the callback of the [express route handler](http://expressjs.com/guide/routing.html).

### create(req, res, next)
This is the callback of the [express route handler](http://expressjs.com/guide/routing.html).

### update(req, res, next)
This is the callback of the [express route handler](http://expressjs.com/guide/routing.html).

### del(req, res, next)
This is the callback of the [express route handler](http://expressjs.com/guide/routing.html).

### errorHandler(error, res)
The error that is triggered and the express `res` object to handle the result.

### setupRoutes()
Make use of `this.router` to setup new routes.


text:
import json
import os
import tempfile
import traceback
import urllib2
import M2Crypto

# TODO:
# - Change get_inside_cert_and_key to use GID.py to get URN and UUID from cert
# --- caller needs to pass in _server.pem_cert
#        user_certstr = addMACert(self._server.pem_cert, self.logger, self.macert)
#
#        try:
#            user_gid = gid.GID(string=user_certstr)
#        except Exception, exc:
#            self.logger.error("GetCredential failed to create user_gid from SSL client cert: %s", traceback.format_exc())
#            raise Exception("Failed to GetCredential. Cant get user GID from SSL client certificate." % exc)
#
#        try:
#            user_gid.verify_chain(self.trusted_roots)
#        except Exception, exc:
#            self.logger.error("GetCredential got unverifiable experimenter cert: %s", exc)
#            raise

# Then getting a UUID or URN is something like this:
#        user_uuid = str(uuid.UUID(int=user_gid.get_uuid()))
#        user_urn = user_gid.get_urn()

# FIXME: The CH APIs have, I believe, evolved since this was written. Must update!

# Helper function to get the insert cert/key for a given connection
# Based on the SSL cert on the given connection
def get_inside_cert_and_key(peercert, ma_url, logger):

#   print(str(peercert))
    san = peercert.get('subjectAltName');
    uri = None
    uuid = None
    for e in san:
        key = e[0];
        value = e[1];
        if(key == 'URI' and "IDN+" in value):
            uri = value;
        if(key == 'URI' and 'uuid' in value):
            uuid_parts = value.split(':');
            uuid = uuid_parts[2];
#           print "URI = " + str(uri) +  " UUID = " + str(uuid)
            args = dict(member_id = uuid)
            row = invokeCH(ma_url, 'lookup_keys_and_certs', logger, args)

#    logger.info("ROW = " + str(row))
    result = dict();
    if(row['code'] == 0):
        row_raw = row['value'];
        private_key = row_raw['private_key']
        certificate = row_raw['certificate']
        (key_fid, key_fname) = tempfile.mkstemp()
        os.write(key_fid, private_key);
        os.close(key_fid);
        (cert_fid, cert_fname) = tempfile.mkstemp();
        os.write(cert_fid, certificate);
        os.close(cert_fid);
        result = {'key': key_fname, 'cert':cert_fname};

    return result;

# Force the unicode strings python creates to be ascii
def _decode_list(data):
    rv = []
    for item in data:
        if isinstance(item, unicode):
            item = item.encode('utf-8')
        elif isinstance(item, list):
            item = _decode_list(item)
        elif isinstance(item, dict):
            item = _decode_dict(item)
        rv.append(item)
    return rv

# Force the unicode strings python creates to be ascii
def _decode_dict(data):
    rv = {}
    for key, value in data.iteritems():
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        elif isinstance(value, list):
            value = _decode_list(value)
        elif isinstance(value, dict):
            value = _decode_dict(value)
        rv[key] = value
    return rv

def decodeCHResponse(msg, logger):
    """Decode the response from the Clearinghouse. It might be encrypted,
    and it might be signed, and it's certainly JSON. Figure out what's what
    and return the decoded JSON.

    See http://svn.osafoundation.org/m2crypto/trunk/doc/howto.smime.html
    """
    #--------------------------------------------------
    # FIXME: Add support for encryption.
    # FIXME: Add signature verfication (see FIXME below)
    #--------------------------------------------------
    #logger.debug("Entering decodeCHResponse with msg=%s", msg);
    # Remove whitespace -- it seems to negatively impact SMIME decoding.
    msg = msg.strip()
    # Load the message into an OpenSSL IO buffer
    p7_bio = M2Crypto.BIO.MemoryBuffer(msg)
    # Try to load the msg as a PKCS7 (SMIME) message.
    json_data = None
    try:
        p7, data = M2Crypto.SMIME.smime_load_pkcs7_bio(p7_bio)
        #logger.debug("decodeCHResponse: SMIME loaded");
        # FIXME: Should verify here
        json_data = data.read()
    except M2Crypto.SMIME.SMIME_Error, err:
        logger.error("SMIME_Error: %s", err)
        #logger.debug("decodeCHResponse: Handling SMIME exception");
        json_data = msg
    result = json.loads(json_data, encoding='ascii', object_hook=_decode_dict)
    return result

def sign_message(key, certs, msg):
    """Signs 'msg' and returns the multipart S/MIME signed message.
    More info can be found in the "howto.smime.html" file in the
    M2Crypto source.
    """
    # Create an SMIME signer
    smime = M2Crypto.SMIME.SMIME()
    # Load the key and cert to use for signing
    smime.load_key_bio(M2Crypto.BIO.MemoryBuffer(key),
                       M2Crypto.BIO.MemoryBuffer(certs[0]))
    # Add the cert chain, if there is one
    if len(certs) > 1:
        sk = M2Crypto.X509.X509_Stack()
        for c in certs[1:]:
            # Load up a cert chain
            sk.push(M2Crypto.X509.load_cert_bio(M2Crypto.BIO.MemoryBuffer(c)))
        # Add the chain certs to the smime signer
        smime.set_x509_stack(sk)
    # Load the msg into a BIO
    msg_bio = M2Crypto.BIO.MemoryBuffer(msg)
    # get the signature
    p7 = smime.sign(msg_bio)
    # Create a temporary BIO to hold the multipart message
    tmp_bio = M2Crypto.BIO.MemoryBuffer()
    # Load the msg into a BIO again -- wish I could rewind instead
    msg_bio = M2Crypto.BIO.MemoryBuffer(msg)
    # Write the multipart message to the temporary BIO
    smime.write(tmp_bio, p7, msg_bio)
    # Extract the multipart message from the temporary BIO
    signed_message = tmp_bio.read()
    return signed_message

def invokeCH(url, operation, logger, argsdict, mycerts=None, mykey=None):
    # Invoke the real CH
    # for now, this should json encode the args and operation, do an http put
    # entry 1 in dict is named operation and is the operation, rest are args
    # json decode result, getting a dict
    # return the result
    if not operation or operation.strip() == '':
        raise Exception("missing operation")
    if not url or url.strip() == '':
        raise Exception("missing url")
    if not argsdict:
        raise Exception("missing argsdict")

    # Put operation in front of argsdict
    toencode = dict(operation=operation)
    for (k,v) in argsdict.items():
        toencode[k]=v
    argstr = json.dumps(toencode)
    if (mycerts and mykey):
        argstr = sign_message(mykey, mycerts, argstr)
    logger.debug("Will do put of %s", argstr)
#    print ("Doing  put of %s" % argstr)

    # now http put this, grab result into putres
    # This is the most trivial put client. This appears to be harder to do / less common than you would expect.
    # See httplib2 for an alternative approach using another library.
    # This approach isn't very robust, may have other issues
    opener = urllib2.build_opener(urllib2.HTTPSHandler)
    req = urllib2.Request(url, data=argstr)
    req.add_header('Content-Type', 'application/json')
    req.get_method = lambda: 'PUT'

    putres = None
    putresHandle = None
    try:
        putresHandle = opener.open(req)
    except Exception, e:
        logger.error("invokeCH failed to open conn to %s: %s", url, e)
        raise Exception("invokeCH failed to open conn to %s: %s" % (url, e))

    if putresHandle:
        try:
            putres=putresHandle.read()
        except Exception, e:
            logger.error("invokeCH failed to read result of put to %s: %s", url, e)
            raise Exception("invokeCH failed to read result of put to %s: %s" % (url, e))

    resdict = None
    if putres:
        logger.debug("invokeCH Got result of %s" % putres)
        resdict = decodeCHResponse(putres, logger)

    # FIXME: Check for code, value, output keys?
    return resdict

def getValueFromTriple(triple, logger, opname, unwrap=False):
    if not triple:
        logger.error("Got empty result triple after %s" % opname)
        raise Exception("Return struct was null for %s" % opname)
    if not triple.has_key('value'):
        logger.error("Malformed return from %s: %s" % (opname, triple))
        raise Exception("malformed return from %s: %s" % (opname, triple))
    if unwrap:
        return triple['value']
    else:
        return triple

# Wait for pyOpenSSL v0.13 which will let us get the client cert chain from the SSL connection
# for now, assume all experimenters are issued by the local MA
def addMACert(experimenter_cert, logger, macertpath):
#/usr/share/geni-ch/ma/ma-cert.pem
    if macertpath is None or macertpath.strip() == '':
        return experimenter_cert

    mc = ''
    add = False
    try:
        with open(macertpath) as macert:
            for line in macert:
                if add or ("BEGIN CERT" in line):
                    add = True
                    mc += line
#            mc = macert.read()
    except:
        logger.error("Failed to read MA cert: %s", traceback.format_exc())
    logger.debug("Resulting PEM: %s" % (experimenter_cert + mc))
    return experimenter_cert + mc


text:
"""
What do we know about diagnostics and surveillance?

Task Details

What do we know about diagnostics and surveillance? What has been published concerning systematic, holistic approach to diagnostics (from the public health surveillance perspective to being able to predict clinical outcomes)?

Specifically, we want to know what the literature reports about:

    How widespread current exposure is to be able to make immediate policy recommendations on mitigation measures. Denominators for testing and a mechanism for rapidly sharing that information, including demographics, to the extent possible. Sampling methods to determine asymptomatic disease (e.g., use of serosurveys (such as convalescent samples) and early detection of disease (e.g., use of screening of neutralizing antibodies such as ELISAs).

	Efforts to increase capacity on existing diagnostic platforms and tap into existing surveillance platforms.

	Recruitment, support, and coordination of local expertise and capacity (public, private—commercial, and non-profit, including academic), including legal, ethical, communications, and operational issues.

	National guidance and guidelines about best practices to states (e.g., how states might leverage universities and private laboratories for testing purposes, communications to public health officials and the public).

	Development of a point-of-care test (like a rapid influenza test) and rapid bed-side tests, recognizing the tradeoffs between speed, accessibility, and accuracy.

	Rapid design and execution of targeted surveillance experiments calling for all potential testers using PCR in a defined area to start testing and report to a specific entity. These experiments could aid in collecting longitudinal samples, which are critical to understanding the impact of ad hoc local interventions (which also need to be recorded).

	Separation of assay development issues from instruments, and the role of the private sector to help quickly migrate assays onto those devices.

	Efforts to track the evolution of the virus (i.e., genetic drift or mutations) and avoid locking into specific reagents and surveillance/detection schemes.

	Latency issues and when there is sufficient viral load to detect the pathogen, and understanding of what is needed in terms of biological and environmental sampling.

	Use of diagnostics such as host response markers (e.g., cytokines) to detect early disease or predict severe disease progression, which would be important to understanding best clinical practice and efficacy of therapeutic interventions.

	Policies and protocols for screening and testing.

	Policies to mitigate the effects on supplies associated with mass testing, including swabs and reagents.

	Technology roadmap for diagnostics.

	Barriers to developing and scaling up new diagnostic tests (e.g., market forces), how future coalition and accelerator models (e.g., Coalition for Epidemic Preparedness Innovations) could provide critical funding for diagnostics, and opportunities for a streamlined regulatory environment.

	New platforms and technology (e.g., CRISPR) to improve response times and employ more holistic approaches to COVID-19 and future diseases.

	Coupling genomics and diagnostic testing on a large scale.

	Enhance capabilities for rapid sequencing and bioinformatics to target regions of the genome that will allow specificity for a particular variant.

	Enhance capacity (people, technology, data) for sequencing with advanced analytics for unknown pathogens, and explore capabilities for distinguishing naturally-occurring pathogens from intentional.

	One Health surveillance of humans and potential sources of future spillover or ongoing exposure for this organism and future pathogens, including both evolutionary hosts (e.g., bats) and transmission hosts (e.g., heavily trafficked and farmed wildlife and domestic food and companion species), inclusive of environmental, demographic, and occupational risk factors.
"""


text:
package model.dtos

/**
 * Created by pisaris on 17/8/2015.
 */
case class AnnotationTagWithComments (annotationTag:AnnotationTags, numberOfComments:Int)


text:
<?php
namespace Api\Processor;

use Zend\Http\PhpEnvironment\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;

/**
 * Responsável por fazer o pré-processamento das requisições da APi
 *
 * @category Api
 * @package PreProcessor
 */
class PreProcessor
{
    /**
     * Executado no pré-processamento, antes de qualquer action
     * Verifica se o usuário tem permissão de acessar o recurso
     *
     * @param MvcEvent $e
     * @return null|\Zend\Http\PhpEnvironment\Response
     */
    public function process(MvcEvent $e)
    {
        $this->configureEnvironment($e);
        $serviceLocator = $e->getTarget()->getServiceLocator();
        $config = $serviceLocator->get('Config');
        $apiConfig = $config['api'];
        //acesso requer um token válido e permissões de acesso
        if (false !== $apiConfig['authorization']) {
            //return $this->checkAuthorization($e, $apiConfig);
        }
        return true;
    }

    /**
     * @param MvcEvent $event
     * @param array $apiConfig
     * @return bool|Response
     */
    private function checkAuthorization(MvcEvent $event, array $apiConfig)
    {
        /** @var Request $request */
        $request = $event->getRequest();
        $origin = $request->getServer('HTTP_ORIGIN');
        if(!in_array($origin, $apiConfig['domains'])) {
            /** @var Response $response */
            $response = $event->getResponse();
            $response->setStatusCode(Response::STATUS_CODE_401);
            return $response;
        }
        return true;
    }

    /**
     * Verifica se a api está sendo acessada de um ambiente de testes
     * e configura o ambiente
     * @param  MvcEvent $e Evento
     * @return void
     */
    private function configureEnvironment(MvcEvent $e)
    {
        if ( !method_exists($e->getRequest(), 'getHeaders')) {
            return;
        }

        $env = $e->getRequest()->getHeaders('Environment');
        if ($env) {
            switch ($env->getFieldValue()) {
                case 'testing':
                    putenv("ENV=testing");
                    break;
                case 'jenkins':
                    putenv("ENV=jenkins");
                    break;

            }
        }
        return;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using VkNet.Exception;

// ReSharper disable once CheckNamespace
namespace VkNet.Utils;

/// <summary>
/// WEB форма
/// </summary>
[Obsolete(ObsoleteText.ObsoleteClass)]
internal sealed class WebForm
{
	/// <summary>
	/// HTML документ
	/// </summary>
	private readonly HtmlDocument _html;

	/// <summary>
	/// Коллекция input на форме
	/// </summary>
	private readonly Dictionary<string, string> _inputs;

	/// <summary>
	/// Базовый URL-ответ
	/// </summary>
	/// <remarks>
	/// Если форма имеет относительный URL
	/// </remarks>
	private readonly string _responseBaseUrl;

	/// <summary>
	/// Наименование поля
	/// </summary>
	private string _lastName;

	/// <summary>
	/// WEB форма.
	/// </summary>
	/// <param name="result"> Результат. </param>
	private WebForm(HttpResponse<string> result)
	{
		if (!result.IsSuccess)
		{
			throw new VkApiException(result.Message);
		}

		OriginalUrl = result.ResponseUri.ToString();

		_responseBaseUrl = $"{result.ResponseUri.Scheme}://{result.RequestUri.Host}";

		_html = new();
		_html.LoadHtml(result.Value);

		_inputs = ParseInputs();
	}

	/// <summary>
	/// Cookies.
	/// </summary>
	public Cookies Cookies { get; }

	/// <summary>
	/// URL действия.
	/// </summary>
	public string ActionUrl
	{
		get {
			var formNode = GetFormNode();

			if (formNode.Attributes["action"] == null)
			{
				return OriginalUrl;
			}

			var link = formNode.Attributes["action"]
				.Value;

			if (!string.IsNullOrWhiteSpace(link) && !link.StartsWith("http", StringComparison.Ordinal)
				) // относительный URL
			{
				link = _responseBaseUrl + link;
			}

			return link; // абсолютный путь
		}
	}

	/// <summary>
	/// Gets the original URL.
	/// </summary>
	/// <value>
	/// The original URL.
	/// </value>
	public string OriginalUrl { get; }

	/// <summary>
	/// Из результата.
	/// </summary>
	/// <param name="result"> Результат. </param>
	/// <returns> WEB форма. </returns>
	public static WebForm From(HttpResponse<string> result) => new(result);

	/// <summary>
	/// Проверка на отсутствие двухфакторной авторизации.
	/// </summary>
	/// <param name="result"> Результат. </param>
	/// <returns> WEB форма. </returns>
	public static bool IsOAuthBlank(WebCallResult result)
	{
		var html = new HtmlDocument();
		html.LoadHtml(result.Response);
		var title = html.DocumentNode.SelectSingleNode("//head/title");

		return title.InnerText.ToLowerInvariant() == "oauth blank";
	}

	/// <summary>
	/// И.
	/// </summary>
	/// <returns> WEB форма. </returns>
	public WebForm And() => this;

	/// <summary>
	/// С полем.
	/// </summary>
	/// <param name="name"> Наименование поля. </param>
	/// <returns> WEB форма. </returns>
	public WebForm WithField(string name)
	{
		_lastName = name;

		return this;
	}

	/// <summary>
	/// С полем.
	/// </summary>
	/// <param name="name"> Наименование поля. </param>
	/// <returns> WEB форма. </returns>
	public string GetFieldValue(string name) => _inputs.TryGetValue(name, out var result)
		? result
		: default;

	/// <summary>
	/// Заполнить поле с.
	/// </summary>
	/// <param name="value"> Значение. </param>
	/// <returns> WEB форма. </returns>
	/// <exception cref="System.InvalidOperationException"> Field name not set! </exception>
	public WebForm FilledWith(string value)
	{
		if (string.IsNullOrEmpty(_lastName))
		{
			throw new InvalidOperationException("Field name not set!");
		}

		var encodedValue = value;

		if (_inputs.ContainsKey(_lastName))
		{
			_inputs[_lastName] = encodedValue;
		} else
		{
			_inputs.Add(_lastName, encodedValue);
		}

		return this;
	}

	/// <summary>
	/// Получить запрос.
	/// </summary>
	/// <returns> Массив байт </returns>
	public byte[] GetRequest() => Encoding.UTF8.GetBytes(GetRequestAsStringArray()
		.JoinNonEmpty("&"));

	/// <summary>
	/// Получить запрос.
	/// </summary>
	/// <returns> Массив байт </returns>
	public IEnumerable<string> GetRequestAsStringArray() => _inputs.Select(x => $"{x.Key}={x.Value}");

	/// <summary>
	/// Получить значения полей.
	/// </summary>
	/// <returns> Словарь значений по именам полей. </returns>
	public IDictionary<string, string> GetFormFields() => new Dictionary<string, string>(_inputs, _inputs.Comparer);

	/// <summary>
	/// Разобрать поля ввода.
	/// </summary>
	/// <returns> Коллекция полей ввода </returns>
	private Dictionary<string, string> ParseInputs()
	{
		var inputs = new Dictionary<string, string>();

		var form = GetFormNode();

		foreach (var node in form.SelectNodes("//input"))
		{
			var nameAttribute = node.Attributes["name"];
			var valueAttribute = node.Attributes["value"];

			var name = nameAttribute != null
				? nameAttribute.Value
				: string.Empty;

			var value = valueAttribute != null
				? valueAttribute.Value
				: string.Empty;

			if (string.IsNullOrEmpty(name))
			{
				continue;
			}

			inputs.Add(name, Uri.EscapeDataString(value));
		}

		return inputs;
	}

	/// <summary>
	/// Получить из HTML элемента.
	/// </summary>
	/// <returns> HTML элемент </returns>
	/// <exception cref="VkApiException"> Элемент не найден на форме. </exception>
	private HtmlNode GetFormNode()
	{
		HtmlNode.ElementsFlags.Remove("form");
		var form = _html.DocumentNode.SelectSingleNode("//form");

		if (form == null)
		{
			throw new VkApiException("Form element not found.");
		}

		return form;
	}
}


text:
Hubot redirect to help if he doesn't understand a command.

See [`src/helpful-hubot.coffee`](src/helpful-hubot.coffee) for full documentation.

## Installation

In hubot project repo, run:

`npm install jobot-helpful --save`

Then add **jobot-helpful** to your `external-scripts.json`:

```json
["jobot-helpful"]
```

## Sample Interaction

```
user1>> hubot typo
hubot>> Sorry I don't understand
hubot>> hubot typo
hubot>> Try hubot help typo

```


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Cards [v2]</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="lib/pure/pure.css">
    <link rel="stylesheet" href="styles/skin.css">

        <link rel="stylesheet" href="styles/main.css">

            Cards
            <form class="pure-form pure-menu-right">
                <input type="text" placeholder="Search">
                <button class="pure-button pure-button-primary">Go</button>
            </form>

Add area

Options

        https://github.com/netxph/cards


text:
+function () { 'use strict';

  (function (o_o) {
    typeof define  == 'function' && define.amd ? define(['jquery'], o_o) :
    typeof exports == 'object' ? o_o(require('jquery')) : o_o(jQuery)
  })(function ($) {

    // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
    // ============================================================

    function transitionEnd() {
      var el = document.createElement('bootstrap')

      var transEndEventNames = {
        WebkitTransition : 'webkitTransitionEnd',
        MozTransition    : 'transitionend',
        OTransition      : 'oTransitionEnd otransitionend',
        transition       : 'transitionend'
      }

      for (var name in transEndEventNames) {
        if (el.style[name] !== undefined) {
          return { end: transEndEventNames[name] }
        }
      }

      return false // explicit for ie8 (  ._.)
    }

    // http://blog.alexmaccaw.com/css-transitions
    $.fn.emulateTransitionEnd = function (duration) {
      var called = false
      var $el = this
      $(this).one('bsTransitionEnd', function () { called = true })
      var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
      setTimeout(callback, duration)
      return this
    }

    $(function () {
      $.support.transition = transitionEnd()

      if (!$.support.transition) return

      $.event.special.bsTransitionEnd = {
        bindType: $.support.transition.end,
        delegateType: $.support.transition.end,
        handle: function (e) {
          if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
        }
      }
    })

  })

}();


text:
<?php namespace System\Cache;

class File implements Driver {

	/**
	 * Determine if an item exists in the cache.
	 *
	 * @param  string  $key
	 * @return bool
	 */
	public function has($key)
	{
		return ( ! is_null($this->get($key)));
	}

	/**
	 * Get an item from the cache.
	 *
	 * @param  string  $key
	 * @param  mixed   $default
	 * @return mixed
	 */
	public function get($key)
	{
		if ( ! file_exists(CACHE_PATH.$key))
		{
			return null;
		}

		$cache = file_get_contents(CACHE_PATH.$key);

		// The cache expiration date is stored as a UNIX timestamp at the beginning
		// of the cache file. We'll extract it out and check it here.
		if (time() >= substr($cache, 0, 10)) return $this->forget($key);

		return unserialize(substr($cache, 10));
	}

	/**
	 * Write an item to the cache.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @param  int     $minutes
	 * @return void
	 */
	public function put($key, $value, $minutes)
	{
		file_put_contents(CACHE_PATH.$key, (time() + ($minutes * 60)).serialize($value), LOCK_EX);
	}

	/**
	 * Delete an item from the cache.
	 *
	 * @param  string  $key
	 * @return void
	 */
	public function forget($key)
	{
		@unlink(CACHE_PATH.$key);
	}

}


text:
module Conjure
  class Firewall
    def initialize(server)
      @server = server
    end

    def install
      if exists?
        puts "Firewall detected."
      else
        puts "Firewall not detected, installing..."
        open_ports.each { |port| @server.run "ufw allow #{port}/tcp" }
        @server.run "ufw --force enable"
        puts "Firewall installed."
      end
    end

    def pending_files
      []
    end

    private

    def open_ports
      [22, 80, 443, 2222]
    end

    def exists?
      @server.run("ufw status").include? "Status: active"
    end
  end
end


text:
package lockermap

import (
	"fmt"
	"strconv"
	"sync"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestMapTryStoreReturnsFalseOnDuplicates(t *testing.T) {
	require := require.New(t)
	var m Map

	require.True(m.TryStore("k", new(sync.Mutex)))
	require.False(m.TryStore("k", new(sync.Mutex)))
}

type testValue struct {
	sync.Mutex
	n int
}

func TestMapLoadHoldsLock(t *testing.T) {
	require := require.New(t)
	var m Map

	require.True(m.TryStore("k", new(testValue)))

	// Only a single goroutine should be able to increment n.
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go require.True(m.Load("k", func(l sync.Locker) {
			defer wg.Done()
			v := l.(*testValue)
			if v.n == 0 {
				v.n++
			} else {
				require.Equal(1, v.n)
			}
		}))
	}
	wg.Wait()
}

type testValueCoordinatedLock struct {
	mu      sync.Mutex
	loading bool
	locking chan bool
	deleted chan bool
}

func (v *testValueCoordinatedLock) Lock() {
	if v.loading {
		v.locking <- true
		<-v.deleted
	}
	v.mu.Lock()
}

func (v *testValueCoordinatedLock) Unlock() { v.mu.Unlock() }

func newTestValueCoordinatedLock() *testValueCoordinatedLock {
	return &testValueCoordinatedLock{
		locking: make(chan bool),
		deleted: make(chan bool),
	}
}

func TestMapLoadReturnsFalseWhenKeyDeletedBeforeValueLocked(t *testing.T) {
	require := require.New(t)
	var m Map

	v := newTestValueCoordinatedLock()

	require.True(m.TryStore("k", v))

	var wg sync.WaitGroup
	wg.Add(1)

	// The goroutine should be able to load k, but k is deleted before it can
	// acquire the value lock.
	v.loading = true
	go func() {
		defer wg.Done()
		require.False(m.Load("k", func(l sync.Locker) {}))
	}()

	<-v.locking
	v.loading = false
	m.Delete("k")
	v.deleted <- true

	wg.Wait()
}

func TestMapRange(t *testing.T) {
	require := require.New(t)
	var m Map

	var wg sync.WaitGroup

	for i := 0; i < 10; i++ {
		v := newTestValueCoordinatedLock()
		require.True(m.TryStore(strconv.Itoa(i), v))
		wg.Add(1)
	}

	go func() {
		m.Range(func(k interface{}, v sync.Locker) bool {
			fmt.Println("Iterating - ", k)
			wg.Done()
			return true
		})
	}()

	wg.Wait()
}

func TestMapRangeSkipsWhenKeyDeletedBeforeValueLocked(t *testing.T) {
	require := require.New(t)
	var m Map

	v := newTestValueCoordinatedLock()

	require.True(m.TryStore("k", v))

	var wg sync.WaitGroup
	wg.Add(1)

	// The goroutine should be able to load k, but k is deleted before it can
	// acquire the value lock, and thus range should never execute on anything.
	v.loading = true
	go func() {
		defer wg.Done()
		m.Range(func(k interface{}, v sync.Locker) bool {
			require.Fail("Should not be able to execute Range iteration")
			return true
		})
	}()

	<-v.locking
	v.loading = false
	m.Delete("k")
	v.deleted <- true

	wg.Wait()
}


text:
package org.mindtrails.domain.questionnaire;

import lombok.Data;

@Data
public class Measure {
    protected final String name;
    protected final String desc;
    private boolean error = false;
    private String errorMessage;

}


text:
package crypto

// xlCrypto_go/aes_cbc_test.go

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"fmt"
	xr "github.com/jddixon/rnglib_go"
	. "gopkg.in/check.v1"
)

var _ = fmt.Print

func (s *XLSuite) makeAESIV(rng *xr.PRNG) (iv []byte) {
	iv = make([]byte, aes.BlockSize)
	rng.NextBytes(iv)
	return
}
func (s *XLSuite) makeAESKey(rng *xr.PRNG) (iv []byte) {
	iv = make([]byte, 2*aes.BlockSize)
	rng.NextBytes(iv)
	return
}

func (s *XLSuite) checkOneMessage(c *C, rng *xr.PRNG, size int) {

	msg := make([]byte, size)
	rng.NextBytes(msg)
	iv := s.makeAESIV(rng)
	key := s.makeAESKey(rng)

	// padding ------------------------------------------------------
	padded, err := AddPKCS7Padding(msg, aes.BlockSize)
	c.Assert(err, IsNil)
	paddedLen := len(padded) // it's been padded to block size
	nBlocks := paddedLen / aes.BlockSize
	c.Assert(nBlocks*aes.BlockSize, Equals, paddedLen)

	// encryption ---------------------------------------------------
	cryptoLen := paddedLen
	ciphertext := make([]byte, cryptoLen)

	engineA, err := aes.NewCipher(key) // cipher.Block
	c.Assert(err, IsNil)
	encrypterA := cipher.NewCBCEncrypter(engineA, iv)
	encrypterA.CryptBlocks(ciphertext, padded) // dest <- src

	// decryption ---------------------------------------------------
	plaintext := make([]byte, paddedLen)
	engineB, err := aes.NewCipher(key) // cipher.Block
	c.Assert(err, IsNil)
	decrypterB := cipher.NewCBCDecrypter(engineB, iv)
	decrypterB.CryptBlocks(plaintext, ciphertext)          // dest <- src
	c.Assert(bytes.Equal(plaintext, padded), Equals, true) // FAILS XXX

	// unpadding ----------------------------------------------------
	reply, err := StripPKCS7Padding(plaintext, aes.BlockSize)
	c.Assert(err, IsNil)
	c.Assert(bytes.Equal(reply, msg), Equals, true)
}

// Verify that AES/CBC/PKCS7 works as expected.  In practical use, the
// IV is sent down the communications channel in clear before the padded
// and encrypted message.  The receiver reads the IV and then uses that
// to decrypt the message proper before stripping off the padding.
func (s *XLSuite) TestAESCipher(c *C) {
	rng := xr.MakeSimpleRNG() // cheap random bits

	REP_COUNT := 4

	for i := 0; i < REP_COUNT; i++ {
		count := rng.Intn(2 * 1024)
		s.checkOneMessage(c, rng, count)
	}

}


text:
RestItem::RestItem(QVariantMap object, QString idField) :
	m_object(object),
	m_idField(idField),
	m_isUpdated(false),
	m_isValid(true),
	m_isHidden(false),
	m_isClickable(true)
{
}

QVariant RestItem::value(QString key) const {
    return m_object.value(key);
}

QStringList RestItem::keys() const {
    return m_object.keys();
}

QVariantMap RestItem::object() const {
	//qDebug() << this << m_object;
	return m_object;
}

QString RestItem::id() const {
    return m_object.value(m_idField).toString();
}

bool RestItem::isUpdated() const {
    return m_isUpdated;
}

bool RestItem::isValid() const
{
    return m_isValid;
}

void RestItem::update(QVariantMap value) {
    QMapIterator<QString, QVariant> i(value);
    while (i.hasNext()) {
        i.next();
        m_object.insert(i.key(), i.value());
    }
    m_isUpdated = true;
}

void RestItem::setFieldValue(QString fieldName, QVariant value) {
	this->m_object[fieldName] = value;

	return;
}

bool RestItem::operator==(const RestItem &other) {
    return id() == other.id();
}

bool RestItem::isHidden() const
{
	return this->m_isHidden;
}

void RestItem::setIsHidden(bool isHidden)
{
	this->m_isHidden = isHidden;
}

bool RestItem::isClickable() const
{
	return this->m_isClickable;
}

void RestItem::setIsClickable(bool isClickable)
{
	this->m_isClickable = isClickable;
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace Renci.SshNet.Tests.Common
{
    public static class DictionaryAssert
    {
        public static void AreEqual<TKey, TValue>(IDictionary<TKey, TValue> expected, IDictionary<TKey, TValue> actual)
        {
            if (ReferenceEquals(expected, actual))
                return;

            if (expected == null)
                throw new AssertFailedException("Expected dictionary to be null, but was not null.");

            if (actual == null)
                throw new AssertFailedException("Expected dictionary not to be null, but was null.");

            if (expected.Count != actual.Count)
                throw new AssertFailedException(string.Format("Expected dictionary to contain {0} entries, but was {1}.",
                                                              expected.Count, actual.Count));

            foreach (var expectedEntry in expected)
            {
                TValue actualValue;
                if (!actual.TryGetValue(expectedEntry.Key, out actualValue))
                {
                    throw new AssertFailedException(string.Format("Dictionary contains no entry with key '{0}'.", expectedEntry.Key));
                }

                if (!Equals(expectedEntry.Value, actualValue))
                {
                    throw new AssertFailedException(string.Format("Value for key '{0}' does not match.", expectedEntry.Key));
                }
            }
        }
    }
}


text:
package thaumicenergistics.config;

import java.util.HashMap;
import java.util.Map;

import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.ConfigManager;

import appeng.api.config.TerminalStyle;

import thaumicenergistics.api.IThEConfig;
import thaumicenergistics.api.config.PrefixSetting;
import thaumicenergistics.init.ModGlobals;

import static net.minecraftforge.common.config.Config.Comment;
import static net.minecraftforge.common.config.Config.Name;

/**
 * TODO: Allow config being changed from api
 *
 * @author BrockWS
 */
@SuppressWarnings("ALL")
@Config(modid = ModGlobals.MOD_ID)
public class ThEConfig implements IThEConfig {

    @Name("Essentia Container Capacity")
    @Comment("Specifies how much a item that holds essentia can hold\nFor filling with Essentia Terminal\nBest to set it to how much the item can actually store")
    public static Map<String, Integer> essentiaContainerCapacity = new HashMap<>();

    @Name("Tick Rates")
    public static TickRates tickRates = new TickRates();

    @Name("Client Config")
    public static Client client = new Client();

    public static class Client {

        @Name("Terminal Style")
        public TerminalStyle terminalStyle = TerminalStyle.TALL;

        @Name("Mod Search Prefix")
        public String modSearchPrefix = "@";

        @Name("Mod Search Setting")
        public PrefixSetting modSearchSetting = PrefixSetting.REQUIRE_PREFIX;

        @Name("Aspect Search Prefix")
        public String aspectSearchPrefix = "#";

        @Name("Aspect Search Setting")
        public PrefixSetting aspectSearchSetting = PrefixSetting.REQUIRE_PREFIX;

        private Client() {

        }
    }

    public static class TickRates {
        @Name("Essentia Import Bus Min")
        public int tickTimeEssentiaImportBusMin = 5;
        @Name("Essentia Import Bus Max")
        public int tickTimeEssentiaImportBusMax = 40;

        @Name("Essentia Export Bus Min")
        public int tickTimeEssentiaExportBusMin = 5;
        @Name("Essentia Export Bus Max")
        public int tickTimeEssentiaExportBusMax = 60;

        @Name("Essentia Storage Bus Min")
        public int tickTimeEssentiaStorageBusMin = 5;
        @Name("Essentia Storage Bus Max")
        public int tickTimeEssentiaStorageBusMax = 60;

        private TickRates() {

        }
    }

    static {
        essentiaContainerCapacity.put("thaumcraft:phial", 10);
    }

    public ThEConfig() {

    }

    @Override
    public Map<String, Integer> essentiaContainerCapacity() {
        return new HashMap<>(this.essentiaContainerCapacity);
    }

    @Override
    public int tickTimeEssentiaImportBusMin() {
        return tickRates.tickTimeEssentiaImportBusMin;
    }

    @Override
    public int tickTimeEssentiaImportBusMax() {
        return tickRates.tickTimeEssentiaImportBusMax;
    }

    @Override
    public int tickTimeEssentiaExportBusMin() {
        return tickRates.tickTimeEssentiaExportBusMin;
    }

    @Override
    public int tickTimeEssentiaExportBusMax() {
        return tickRates.tickTimeEssentiaExportBusMax;
    }

    @Override
    public int tickTimeEssentiaStorageBusMin() {
        return tickRates.tickTimeEssentiaStorageBusMin;
    }

    @Override
    public int tickTimeEssentiaStorageBusMax() {
        return tickRates.tickTimeEssentiaStorageBusMax;
    }

    @Override
    public TerminalStyle terminalStyle() {
        return client.terminalStyle;
    }

    @Override
    public String modSearchPrefix() {
        return client.modSearchPrefix;
    }

    @Override
    public PrefixSetting modSearchSetting() {
        return client.modSearchSetting;
    }

    @Override
    public String aspectSearchPrefix() {
        return client.aspectSearchPrefix;
    }

    @Override
    public PrefixSetting aspectSearchSetting() {
        return client.aspectSearchSetting;
    }

    public static void save() {
        ConfigManager.sync(ModGlobals.MOD_ID, Config.Type.INSTANCE);
    }
}


text:
package com.ruijc.shiro;

import org.apache.shiro.authc.UsernamePasswordToken;

/**
 * 增强版UsernamePassword授权令牌
 *
 * @author Storezhang
 */
public class EncryptToken extends UsernamePasswordToken {

    private boolean encrypted;

    public EncryptToken(String username, String password) {
        super(username, password);
    }

    public EncryptToken(String username, char[] password, String host) {
        super(username, password, host);
    }

    public EncryptToken(String username, String password, String host) {
        super(username, password, host);
    }

    public EncryptToken(String username, char[] password, boolean rememberMe) {
        super(username, password, rememberMe);
    }

    public EncryptToken(String username, String password, boolean rememberMe) {
        super(username, password, rememberMe);
    }

    public EncryptToken(String username, char[] password, boolean rememberMe, String host) {
        super(username, password, rememberMe, host);
    }

    public EncryptToken(String username, String password, boolean rememberMe, String host) {
        super(username, password, rememberMe, host);
    }

    public EncryptToken() {
        this("", "");
    }

    public EncryptToken(String username, char[] password) {
        super(username, password);
    }

    public boolean isEncrypted() {
        return encrypted;
    }

    public void setEncrypted(boolean encrypted) {
        this.encrypted = encrypted;
    }
}


text:
DELETE [dbo].[DocmahPageUrls]
WHERE [PageId] = @pageId


text:
from . import qat
from .qat import *

from . import ptq
from .ptq import *

from . import ptq_config
from .ptq_config import *

from . import ptq_quantizer
from .ptq_quantizer import *

from . import ptq_registry
from .ptq_registry import *

__all__ = []
__all__ += qat.__all__
__all__ += ptq.__all__
__all__ += ptq_config.__all__
__all__ += ptq_quantizer.__all__
__all__ += ptq_registry.__all__


text:
<?php

namespace Google\Service\AndroidPublisher;

class DeviceSpec extends \Google\Collection
{
  protected $collection_key = 'supportedLocales';
  /**
   * @var string
   */
  public $screenDensity;
  /**
   * @var string[]
   */
  public $supportedAbis;
  /**
   * @var string[]
   */
  public $supportedLocales;

  /**
   * @param string
   */
  public function setScreenDensity($screenDensity)
  {
    $this->screenDensity = $screenDensity;
  }
  /**
   * @return string
   */
  public function getScreenDensity()
  {
    return $this->screenDensity;
  }
  /**
   * @param string[]
   */
  public function setSupportedAbis($supportedAbis)
  {
    $this->supportedAbis = $supportedAbis;
  }
  /**
   * @return string[]
   */
  public function getSupportedAbis()
  {
    return $this->supportedAbis;
  }
  /**
   * @param string[]
   */
  public function setSupportedLocales($supportedLocales)
  {
    $this->supportedLocales = $supportedLocales;
  }
  /**
   * @return string[]
   */
  public function getSupportedLocales()
  {
    return $this->supportedLocales;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(DeviceSpec::class, 'Google_Service_AndroidPublisher_DeviceSpec');