text:
// Copyright 2018 Google Inc.
//
// 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
//
//     https://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.

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INSTANCE_ADMIN_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INSTANCE_ADMIN_H

#include "google/cloud/bigtable/admin/bigtable_instance_admin_connection.h"
#include "google/cloud/bigtable/admin/bigtable_instance_admin_options.h"
#include "google/cloud/bigtable/app_profile_config.h"
#include "google/cloud/bigtable/cluster_config.h"
#include "google/cloud/bigtable/cluster_list_responses.h"
#include "google/cloud/bigtable/completion_queue.h"
#include "google/cloud/bigtable/iam_policy.h"
#include "google/cloud/bigtable/instance_admin_client.h"
#include "google/cloud/bigtable/instance_config.h"
#include "google/cloud/bigtable/instance_list_responses.h"
#include "google/cloud/bigtable/instance_update_config.h"
#include "google/cloud/bigtable/internal/convert_policies.h"
#include "google/cloud/bigtable/polling_policy.h"
#include "google/cloud/bigtable/resource_names.h"
#include "google/cloud/bigtable/version.h"
#include "google/cloud/future.h"
#include "google/cloud/project.h"
#include "google/cloud/status_or.h"
#include <future>
#include <memory>
#include <string>
#include <vector>

namespace google {
namespace cloud {
namespace bigtable_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
class InstanceAdminTester;
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace bigtable_internal
namespace bigtable {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

/**
 * Implements the APIs to administer Cloud Bigtable instances.
 *
 * @par Thread-safety
 * Instances of this class created via copy-construction or copy-assignment
 * share the underlying pool of connections. Access to these copies via multiple
 * threads is guaranteed to work. Two threads operating concurrently on the same
 * instance of this class is not guaranteed to work.
 *
 * @par Cost
 * Creating a new object of type `InstanceAdmin` is comparable to creating a few
 * objects of type `std::string` or a few objects of type
 * `std::shared_ptr<int>`. The class represents a shallow handle to a remote
 * object.
 *
 * @par Error Handling
 * This class uses `StatusOr<T>` to report errors. When an operation fails to
 * perform its work the returned `StatusOr<T>` contains the error details. If
 * the `ok()` member function in the `StatusOr<T>` returns `true` then it
 * contains the expected result. Operations that do not return a value simply
 * return a `google::cloud::Status` indicating success or the details of the
 * error Please consult the [`StatusOr<T>`
 * documentation](#google::cloud::StatusOr) for more details.
 *
 * @code
 * namespace cbt = google::cloud::bigtable;
 * namespace btadmin = google::bigtable::admin::v2;
 * cbt::InstanceAdmin admin = ...;
 * google::cloud::StatusOr<btadmin::Instance> instance = admin.GetInstance(...);
 *
 * if (!instance) {
 *   std::cerr << "Error fetching instance\n";
 *   return;
 * }
 *
 * // Use `instance` as a smart pointer here, e.g.:
 * std::cout << "The full instance name is " << instance->name() << "\n";
 * @endcode
 *
 * In addition, the @ref index "main page" contains examples using `StatusOr<T>`
 * to handle errors.
 *
 * @par Retry, Backoff, and Idempotency Policies
 * The library automatically retries requests that fail with transient errors,
 * and uses [truncated exponential backoff][backoff-link] to backoff between
 * retries. The default policies are to continue retrying for up to 10 minutes.
 * On each transient failure the backoff period is doubled, starting with an
 * initial backoff of 100 milliseconds. The backoff period growth is truncated
 * at 60 seconds. The default idempotency policy is to only retry idempotent
 * operations. Note that most operations that change state are **not**
 * idempotent.
 *
 * The application can override these policies when constructing objects of this
 * class. The documentation for the constructors show examples of this in
 * action.
 *
 * [backoff-link]: https://cloud.google.com/storage/docs/exponential-backoff
 *
 * @see https://cloud.google.com/bigtable/ for an overview of Cloud Bigtable.
 *
 * @see https://cloud.google.com/bigtable/docs/overview for an overview of the
 *     Cloud Bigtable data model.
 *
 * @see https://cloud.google.com/bigtable/docs/instances-clusters-nodes for an
 *     introduction of the main APIs into Cloud Bigtable.
 *
 * @see https://cloud.google.com/bigtable/docs/reference/service-apis-overview
 *     for an overview of the underlying Cloud Bigtable API.
 *
 * @see #google::cloud::StatusOr for a description of the error reporting class
 *     used by this library.
 *
 * @see `LimitedTimeRetryPolicy` and `LimitedErrorCountRetryPolicy` for
 *     alternative retry policies.
 *
 * @see `ExponentialBackoffPolicy` to configure different parameters for the
 *     exponential backoff policy.
 *
 * @see `SafeIdempotentMutationPolicy` and `AlwaysRetryMutationPolicy` for
 *     alternative idempotency policies.
 */
class InstanceAdmin {
 public:
  explicit InstanceAdmin(
      std::shared_ptr<bigtable_admin::BigtableInstanceAdminConnection>
          connection,
      std::string project)
      : connection_(std::move(connection)),
        project_id_(std::move(project)),
        project_name_(Project(project_id_).FullName()),
        retry_prototype_(
            DefaultRPCRetryPolicy(internal::kBigtableInstanceAdminLimits)),
        backoff_prototype_(
            DefaultRPCBackoffPolicy(internal::kBigtableInstanceAdminLimits)),
        polling_prototype_(
            DefaultPollingPolicy(internal::kBigtableInstanceAdminLimits)),
        options_(google::cloud::internal::MergeOptions(
            bigtable_internal::MakeInstanceAdminOptions(
                retry_prototype_, backoff_prototype_, polling_prototype_),
            connection_->options())) {}

  /**
   * @param client the interface to create grpc stubs, report errors, etc.
   */
  // NOLINTNEXTLINE(performance-unnecessary-value-param)
  explicit InstanceAdmin(std::shared_ptr<InstanceAdminClient> client)
      : InstanceAdmin(client->connection_, client->project()) {}

  /**
   * Create a new InstanceAdmin using explicit policies to handle RPC errors.
   *
   * @param client the interface to create grpc stubs, report errors, etc.
   * @param policies the set of policy overrides for this object.
   * @tparam Policies the types of the policies to override, the types must
   *     derive from one of the following types:
   *     - `RPCBackoffPolicy` how to backoff from a failed RPC. Currently only
   *       `ExponentialBackoffPolicy` is implemented. You can also create your
   *       own policies that backoff using a different algorithm.
   *     - `RPCRetryPolicy` for how long to retry failed RPCs. Use
   *       `LimitedErrorCountRetryPolicy` to limit the number of failures
   *       allowed. Use `LimitedTimeRetryPolicy` to bound the time for any
   *       request. You can also create your own policies that combine time and
   *       error counts.
   *     - `PollingPolicy` for how long will the class wait for
   *       `google.longrunning.Operation` to complete. This class combines both
   *       the backoff policy for checking long running operations and the
   *       retry policy.
   *
   * @see GenericPollingPolicy, ExponentialBackoffPolicy,
   *     LimitedErrorCountRetryPolicy, LimitedTimeRetryPolicy.
   */
  template <typename... Policies>
  // NOLINTNEXTLINE(performance-unnecessary-value-param)
  explicit InstanceAdmin(std::shared_ptr<InstanceAdminClient> client,
                         Policies&&... policies)
      : connection_(client->connection_),
        project_id_(client->project()),
        project_name_(Project(project_id_).FullName()),
        retry_prototype_(
            DefaultRPCRetryPolicy(internal::kBigtableInstanceAdminLimits)),
        backoff_prototype_(
            DefaultRPCBackoffPolicy(internal::kBigtableInstanceAdminLimits)),
        polling_prototype_(
            DefaultPollingPolicy(internal::kBigtableInstanceAdminLimits)) {
    ChangePolicies(std::forward<Policies>(policies)...);
    options_ = google::cloud::internal::MergeOptions(
        bigtable_internal::MakeInstanceAdminOptions(
            retry_prototype_, backoff_prototype_, polling_prototype_),
        connection_->options());
  }

  /// The full name (`projects/<project_id>`) of the project.
  std::string const& project_name() const { return project_name_; }
  /// The project id, i.e., `project_name()` without the `projects/` prefix.
  std::string const& project_id() const { return project_id_; }

  /**
   * Returns an InstanceAdmin that reuses the connection and configuration of
   * this InstanceAdmin, but with a different resource name.
   */
  InstanceAdmin WithNewTarget(std::string project_id) const {
    auto admin = *this;
    admin.project_id_ = std::move(project_id);
    admin.project_name_ = Project(admin.project_id_).FullName();
    return admin;
  }

  /// Return the fully qualified name of the given instance_id.
  std::string InstanceName(std::string const& instance_id) const {
    return google::cloud::bigtable::InstanceName(project_id_, instance_id);
  }

  /// Return the fully qualified name of the given cluster_id in give
  /// instance_id.
  std::string ClusterName(std::string const& instance_id,
                          std::string const& cluster_id) const {
    return google::cloud::bigtable::ClusterName(project_id_, instance_id,
                                                cluster_id);
  }

  std::string AppProfileName(std::string const& instance_id,
                             std::string const& profile_id) const {
    return google::cloud::bigtable::AppProfileName(project_id_, instance_id,
                                                   profile_id);
  }

  /**
   * Create a new instance of Cloud Bigtable.
   *
   * @warning Note that this is operation can take seconds or minutes to
   * complete. The application may prefer to perform other work while waiting
   * for this operation.
   *
   * @param instance_config a description of the new instance to be created.
   *   instance_id and a display_name parameters must be set in instance_config,
   *   - instance_id : must be between 6 and 33 characters.
   *   - display_name : must be between 4 and 30 characters.
   * @return a future that becomes satisfied when (a) the operation has
   *   completed successfully, in which case it returns a proto with the
   *   Instance details, (b) the operation has failed, in which case the future
   *   contains an `google::cloud::Status` with the details of the failure, or
   *   (c) the state of the operation is unknown after the time allocated by the
   *   retry policies has expired, in which case the future contains the last
   *   error status.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc create instance
   */
  future<StatusOr<google::bigtable::admin::v2::Instance>> CreateInstance(
      InstanceConfig instance_config);

  /**
   * Create a new Cluster of Cloud Bigtable.
   *
   * @param cluster_config a description of the new cluster to be created.
   * @param instance_id the id of the instance in the project
   * @param cluster_id the id of the cluster in the project that needs to be
   *   created. It must be between 6 and 30 characters.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc create cluster
   */
  future<StatusOr<google::bigtable::admin::v2::Cluster>> CreateCluster(
      ClusterConfig cluster_config, std::string const& instance_id,
      std::string const& cluster_id);

  /**
   * Update an existing instance of Cloud Bigtable.
   *
   * @warning Note that this is operation can take seconds or minutes to
   * complete. The application may prefer to perform other work while waiting
   * for this operation.
   *
   * @param instance_update_config config with modified instance.
   * @return a future that becomes satisfied when (a) the operation has
   *   completed successfully, in which case it returns a proto with the
   *   Instance details, (b) the operation has failed, in which case the future
   *   contains an exception (typically `bigtable::GrpcError`) with the details
   *   of the failure, or (c) the state of the operation is unknown after the
   *   time allocated by the retry policies has expired, in which case the
   *   future contains an exception of type `bigtable::PollTimeout`.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc update instance
   */
  future<StatusOr<google::bigtable::admin::v2::Instance>> UpdateInstance(
      InstanceUpdateConfig instance_update_config);

  /**
   * Obtain the list of instances in the project.
   *
   * @note In some circumstances Cloud Bigtable may be unable to obtain the full
   *   list of instances, typically because some transient failure has made
   *   specific zones unavailable. In this cases the service returns a separate
   *   list of `failed_locations` that represent the unavailable zones.
   *   Applications may want to retry the operation after the transient
   *   conditions have cleared.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc list instances
   */
  StatusOr<InstanceList> ListInstances();

  /**
   * Return the details of @p instance_id.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc get instance
   */
  StatusOr<google::bigtable::admin::v2::Instance> GetInstance(
      std::string const& instance_id);

  /**
   * Deletes the instances in the project.
   *
   * @param instance_id the id of the instance in the project that needs to be
   * deleted
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc delete instance
   */
  Status DeleteInstance(std::string const& instance_id);

  /**
   * Obtain the list of clusters in an instance.
   *
   * @note In some circumstances Cloud Bigtable may be unable to obtain the full
   *   list of clusters, typically because some transient failure has made
   *   specific zones unavailable. In this cases the service returns a separate
   *   list of `failed_locations` that represent the unavailable zones.
   *   Applications may want to retry the operation after the transient
   *   conditions have cleared.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc list clusters
   */
  StatusOr<ClusterList> ListClusters();

  /**
   * Obtain the list of clusters in an instance.
   *
   * @note In some circumstances Cloud Bigtable may be unable to obtain the full
   *   list of clusters, typically because some transient failure has made
   *   specific zones unavailable. In this cases the service returns a separate
   *   list of `failed_locations` that represent the unavailable zones.
   *   Applications may want to retry the operation after the transient
   *   conditions have cleared.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc list clusters
   */
  StatusOr<ClusterList> ListClusters(std::string const& instance_id);

  /**
   * Update an existing cluster of Cloud Bigtable.
   *
   * @warning Note that this is operation can take seconds or minutes to
   * complete. The application may prefer to perform other work while waiting
   * for this operation.
   *
   * @param cluster_config cluster with updated values.
   * @return a future that becomes satisfied when (a) the operation has
   *   completed successfully, in which case it returns a proto with the
   *   Instance details, (b) the operation has failed, in which case the future
   *   contains an exception (typically `bigtable::GrpcError`) with the details
   *   of the failure, or (c) the state of the operation is unknown after the
   *   time allocated by the retry policies has expired, in which case the
   *   future contains an exception of type `bigtable::PollTimeout`.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc update cluster
   */
  future<StatusOr<google::bigtable::admin::v2::Cluster>> UpdateCluster(
      ClusterConfig cluster_config);

  /**
   * Deletes the specified cluster of an instance in the project.
   *
   * @param instance_id the id of the instance in the project
   * @param cluster_id the id of the cluster in the project that needs to be
   *   deleted
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc delete cluster
   */
  Status DeleteCluster(std::string const& instance_id,
                       std::string const& cluster_id);

  /**
   * Gets the specified cluster of an instance in the project.
   *
   * @param instance_id the id of the instance in the project
   * @param cluster_id the id of the cluster in the project that needs to be
   *   deleted
   * @return a Cluster for given instance_id and cluster_id.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc get cluster
   */
  StatusOr<google::bigtable::admin::v2::Cluster> GetCluster(
      std::string const& instance_id, std::string const& cluster_id);

  /**
   * Create a new application profile.
   *
   * @param instance_id the instance for the new application profile.
   * @param config the configuration for the new application profile.
   * @return The proto describing the new application profile.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Multi-cluster Routing Example
   * @snippet bigtable_instance_admin_snippets.cc create app profile
   *
   * @par Single Cluster Routing Example
   * @snippet bigtable_instance_admin_snippets.cc create app profile cluster
   */
  StatusOr<google::bigtable::admin::v2::AppProfile> CreateAppProfile(
      std::string const& instance_id, AppProfileConfig config);

  /**
   * Fetch the detailed information about an existing application profile.
   *
   * @param instance_id the instance to look the profile in.
   * @param profile_id the id of the profile within that instance.
   * @return The proto describing the application profile.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc get app profile
   */
  StatusOr<google::bigtable::admin::v2::AppProfile> GetAppProfile(
      std::string const& instance_id, std::string const& profile_id);

  /**
   * Updates an existing application profile.
   *
   * @param instance_id the instance for the new application profile.
   * @param profile_id the id (not the full name) of the profile to update.
   * @param config the configuration for the new application profile.
   * @return The proto describing the new application profile.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Change Description Example
   * @snippet bigtable_instance_admin_snippets.cc update app profile description
   *
   * @par Change Routing to Any Cluster Example
   * @snippet bigtable_instance_admin_snippets.cc update app profile routing any
   *
   * @par Change Routing to a Specific Cluster Example
   * @snippet bigtable_instance_admin_snippets.cc update app profile routing
   */
  future<StatusOr<google::bigtable::admin::v2::AppProfile>> UpdateAppProfile(
      std::string const& instance_id, std::string const& profile_id,
      AppProfileUpdateConfig config);

  /**
   * List the application profiles in an instance.
   *
   * @param instance_id the instance to list the profiles for.
   * @return a std::vector with the protos describing any profiles.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc list app profiles
   */
  StatusOr<std::vector<google::bigtable::admin::v2::AppProfile>>
  ListAppProfiles(std::string const& instance_id);

  /**
   * Delete an existing application profile.
   *
   * @param instance_id the instance to look the profile in.
   * @param profile_id the id of the profile within that instance.
   * @param ignore_warnings if true, ignore safety checks when deleting the
   *     application profile. This value is to to `true` by default. Passing
   *     `false` causes this function to fail even when no operations are
   *     pending.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc delete app profile
   */
  Status DeleteAppProfile(std::string const& instance_id,
                          std::string const& profile_id,
                          bool ignore_warnings = true);

  /**
   * Gets the native policy for @p instance_id.
   *
   * @param instance_id the instance to query.
   * @return google::iam::v1::Policy the full IAM policy for the instance.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc get native iam policy
   */
  StatusOr<google::iam::v1::Policy> GetNativeIamPolicy(
      std::string const& instance_id);

  /**
   * Sets the IAM policy for an instance.
   *
   * @param instance_id which instance to set the IAM policy for.
   * @param iam_policy google::iam::v1::Policy object containing role and
   * members.
   * @return google::iam::v1::Policy the current IAM policy for the instance.
   *
   * @warning ETags are currently not used by Cloud Bigtable.
   *
   * @par Idempotency
   * This operation is always treated as non-idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc set native iam policy
   */
  StatusOr<google::iam::v1::Policy> SetIamPolicy(
      std::string const& instance_id,
      google::iam::v1::Policy const& iam_policy);

  /**
   * Returns a permission set that the caller has on the specified instance.
   *
   * @param instance_id the ID of the instance to query.
   * @param permissions set of permissions to check for the resource.
   *
   * @par Idempotency
   * This operation is read-only and therefore it is always idempotent.
   *
   * @par Thread-safety
   * Two threads concurrently calling this member function on the same instance
   * of this class are **not** guaranteed to work. Consider copying the object
   * and using different copies in each thread.
   *
   * @par Example
   * @snippet bigtable_instance_admin_snippets.cc test iam permissions
   *
   * @see https://cloud.google.com/bigtable/docs/access-control for a list of
   *     valid permissions on Google Cloud Bigtable.
   */
  StatusOr<std::vector<std::string>> TestIamPermissions(
      std::string const& instance_id,
      std::vector<std::string> const& permissions);

 private:
  friend class bigtable_internal::InstanceAdminTester;

  //@{
  /// @name Helper functions to implement constructors with changed policies.
  void ChangePolicy(RPCRetryPolicy const& policy) {
    retry_prototype_ = policy.clone();
  }

  void ChangePolicy(RPCBackoffPolicy const& policy) {
    backoff_prototype_ = policy.clone();
  }

  void ChangePolicy(PollingPolicy const& policy) {
    polling_prototype_ = policy.clone();
  }

  template <typename Policy, typename... Policies>
  void ChangePolicies(Policy&& policy, Policies&&... policies) {
    ChangePolicy(policy);
    ChangePolicies(std::forward<Policies>(policies)...);
  }
  void ChangePolicies() {}
  //@}

  std::shared_ptr<bigtable_admin::BigtableInstanceAdminConnection> connection_;
  std::string project_id_;
  std::string project_name_;
  //@{
  /// These prototypes are only used as temporary storage during construction of
  /// the class, where they are consolidated as common policies in `options_`.
  std::shared_ptr<RPCRetryPolicy> retry_prototype_;
  std::shared_ptr<RPCBackoffPolicy> backoff_prototype_;
  std::shared_ptr<PollingPolicy> polling_prototype_;
  //}
  Options options_;
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace bigtable
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INSTANCE_ADMIN_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NullGuard;

namespace Json.Comparer.Filters
{
    public class FilterPropertyByName : IComparrisonFilter
    {
        private readonly string propertyName;

        public FilterPropertyByName(string propertyName)
        {
            this.propertyName = propertyName;
        }

        public bool ShouldBeFiltered(string key, [AllowNull]JToken token1, [AllowNull]JToken token2)
        {
            var type = GetTokenType(token1, token2);
            if (type == JTokenType.Property)
            {
                var property = (JProperty)FirstNonNullValue(token1, token2);
                return String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase);
            }
            return false;
        }

        private static JTokenType GetTokenType(JToken token1, JToken token2)
        {
            if (token1?.Type == null || token1?.Type == JTokenType.Null)
            {
                return token2.Type;
            }
            else
            {
                return token1.Type;
            }
        }

        private static T FirstNonNullValue<T>(params T[] values)
    where T : class
        {
            return values.First(x => x != null);
        }

        private static T FirstNonNullValueOrDefault<T>(T defaultValue, params T[] values)
            where T : class
        {
            var value = values.FirstOrDefault(x => x != null);
            if (value == null)
            {
                return defaultValue;
            }
            else
            {
                return value;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: guides_navigation
section_id: navigating-between-views
subsection_id: using-modals
---

# Using modals

The **modal screen** is a special kind of container for a `supersonic.ui.View` object. A modal screen gets overlayed on top of the whole app. If the navigation bar or the tab bar are in use, the modal screen covers them also.

## Programmatic APIs

{% assign method = site.data.supersonic.ui.modal.show %}
{% include api_method.md method=method %}

{% assign method = site.data.supersonic.ui.modal.hide %}
{% include api_method.md method=method %}

{% assign method = site.data.supersonic.ui.modal.hideAll %}
{% include api_method.md method=method %}


text:
    Height

      <input type="number" ng-model="visualization.options.height" min="1" class="form-control">

    This visualization expects the query result to have rows in one of the following formats:

    Option 1:

sequence - sequence id

stage - what stage in sequence this is (1, 2, ...)

node - stage name

value - number of times this sequence occurred

    Option 2:

stage1 - stage 1 value

stage1 - stage 2 value (or null)

stage3 - stage 3 value (or null)

stage4 - stage 4 value (or null)

stage5 - stage 5 value (or null)

value - number of times this sequence occurred


text:
<?php
use yii\helpers\Html;
use yii\widgets\Menu;
use yii\widgets\Breadcrumbs;

/**
 * @var $this \yii\base\View
 * @var $content string
 */
$this->registerAssetBundle('app');
?>
<?php $this->beginPage(); ?>
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<title><?php echo Html::encode($this->title); ?></title>
	<?php $this->head(); ?>

	<?php $this->beginBody(); ?>

My Company

					<?php echo Menu::widget(array(
						'options' => array('class' => 'nav'),
						'items' => array(
							array('label' => 'Home', 'url' => array('/site/index')),
							array('label' => 'About', 'url' => array('/site/about')),
							array('label' => 'Contact', 'url' => array('/site/contact')),
							Yii::$app->user->isGuest ?
								array('label' => 'Login', 'url' => array('/site/login')) :
								array('label' => 'Logout (' . Yii::$app->user->identity->username .')' , 'url' => array('/site/logout')),
						),
					)); ?>

	<?php echo Breadcrumbs::widget(array(
		'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : array(),
	)); ?>
	<?php echo $content; ?>

© My Company <?php echo date('Y'); ?>

			<?php echo Yii::powered(); ?>
			Template by Twitter Bootstrap

	<?php $this->endBody(); ?>

<?php $this->endPage(); ?>


text:
export default {
  header: {
    id: 'app.containers.AboutPage.header',
    defaultMessage: 'ABOUT',
  },
  description: {
    id: 'app.containers.AboutPage.description',
    defaultMessage: 'Beautiful Rising harnesses the insights of changemakers worldwide to help make our movements more strategic, creative and effective.'
  },
  inspiration: {
    id: 'app.components.AboutPageComponents.inspiration',
    defaultMessage: `# INSPIRATION
This toolbox was inspired by the [Beautiful Trouble book and website](http://beautifultrouble.org/). The scope has been expanded to involve a more diverse group of activists as both makers and users of the toolkit.
    `,
  },
  definition: {
    id: 'app.components.AboutPageComponents.definition',
    defaultMessage: `# DEFINITION
We've conducted six 'jam sessions' around the world with diverse groups of activists to better understand the problems they're facing and generate locally relevant content for the toolbox.`,
  },
  prototyping: {
    id: 'app.components.AboutPageComponents.prototyping',
    defaultMessage: `# PROTOTYPING
In each jam session, low-fidelity prototypes of the toolbox were presented to activists to take apart and put back together based on their needs and challenges.`,
  },
  realization: {
    id: 'app.components.AboutPageComponents.realization',
    defaultMessage: `# REALIZATION
Early prototypes evolved into multiple iterations of what's currently a [game](https://beautifulrising.org/platforms/game), [chatbot](https://beautifulrising.org/platforms/chatbot), and website. With your help, the content and the form will continue to evolve!`,
  },
  theToolboxHeader: {
    id: 'app.components.AboutPageComponents.theToolboxHeader',
    defaultMessage: 'The Toolbox',
  },
  ourProcessHeader: {
    id: 'app.components.AboutPageComponents.ourProcessHeader',
    defaultMessage: 'HOW DID WE MAKE THE TOOLBOX?'
  },
  participantsHeader: {
    id: 'app.components.AboutPageComponents.participantsHeader',
    defaultMessage: 'PARTICIPANTS + WORKSHOPS INVOLVED'
  },
  ourValuesHeader: {
    id: 'app.components.AboutPageComponents.ourValuesHeader',
    defaultMessage: 'WHAT ARE OUR VALUES?'
  },
  ourAdvisoryNetworkHeader: {
    id: 'app.components.AboutPageComponents.ourAdvisoryNetworkHeader',
    defaultMessage: 'Our Advisory Network'
  },
  ourTeamHeader: {
    id: 'app.components.AboutPageComponents.ourTeamHeader',
    defaultMessage: 'Our Team'
  },
  beautifulTroubleAAHeader: {
    id: 'app.components.AboutPageComponents.beautifulTroubleAAHeader',
    defaultMessage: 'What's the connection with Beautiful Trouble + ActionAid?'
  },
  partnersHeader: {
    id: 'app.components.AboutPageComponents.partnersHeader',
    defaultMessage: 'Partners'
  },
  faqHeader: {
    id: 'app.components.AboutPageComponents.faqHeader',
    defaultMessage: 'FAQ'
  }
};


text:
import os
import sys

is_py2 = (sys.version_info[0] == 2)
is_py3 = (sys.version_info[0] == 3)
is_py33 = (sys.version_info[0] == 3 and sys.version_info[1] == 3)
is_win32 = os.name == "nt"

if is_py2:
    _str = str
    str = unicode
    range = xrange

    def bytes(b, enc="ascii"):
        return _str(b)

elif is_py3:
    bytes = bytes
    str = str
    range = range

try:
    from urllib.parse import urlparse, urljoin, quote, unquote, parse_qsl
    import queue
except ImportError:
    from urlparse import urlparse, urljoin, parse_qsl
    from urllib import quote, unquote
    import Queue as queue

__all__ = ["is_py2", "is_py3", "is_py33", "is_win32", "str", "bytes",
           "urlparse", "urljoin", "parse_qsl", "quote", "unquote", "queue",
           "range"]


text:
const Statistic = require('mongoose').model('Statistic');
const TelegramBot = require('node-telegram-bot-api');
const config = require('config');
const bot = new TelegramBot(config.get('telegram_bot_token'));

module.exports = (() => {
  'use strict';

  const botName = 'KadseBot';
  let ohKadseMap= new Map();
  function contains(origstring, compare) {
    return origstring.indexOf(compare) > -1;
  }

  function getCommand(inputData) {
    console.log(inputData);
    let command = inputData.toLowerCase();
    if (contains(inputData, ' ')) {
      command = command.split(' ')[0];
    }
    if (contains(command, '@'.concat(botName.toLowerCase()))) {
      return command.replace('@'.concat(botName.toLowerCase()), '');
    } else if (contains(command, ' @'.concat(botName.toLowerCase()))) {
      return command.replace(' @'.concat(botName.toLowerCase()), '');
    }
    return command;
  }

  function getParams(inputData) {
    const params = inputData.split(' ');
    if (contains(inputData, ' @'.concat(botName))) {
      return params.slice(2);
    } else {
      return params.slice(1);
    }
  }

  function executeCommand(JsonData) {
 //   incrementUsage(JsonData);
    let command;
    if (typeof JsonData.message.text === 'undefined') {
      command = 'undefined';
    } else {
      command = getCommand(JsonData.message.text);
    }
    console.log('after getCommand'.concat(command));
    switch (command) {
      case '/echo':
        bot.sendMessage(JsonData.message.chat.id, getParams(JsonData.message.text).join(' '));
        break;
      case '/debug':
        bot.sendMessage(JsonData.message.chat.id, JSON.stringify(JsonData));
        break;
      case '/decide':
        bot.sendMessage(JsonData.message.chat.id, decide(getParams(JsonData.message.text)));
        break;
      case '/ohkadsewasessenwirheute':
        ohKadseWasEssenWirHeute(JsonData.message.chat.id);
        //bot.sendMessage(JsonData.message.chat.id, decide(['Mensa', 'Fresh', 'Smileys', 'Penny', 'Dinos', 'Hack']));
        break;
      case '/engage':
        engage(JsonData.message.chat.id, getParams(JsonData.message.text).join(' '));
        break;
      case '/roulette':
        roulette(JsonData.message.chat.id);
        break;
      case 'undefined':
        bot.sendMessage(JsonData.message.chat.id, errorMessage('No message text supplied'));
        break;

      default:
        bot.sendMessage(JsonData.message.chat.id, 'Kadse verwirrt. Kadse kennt nicht');
        break;
    }
  }

  function decide(Params) {
    if (Params.length > 0) {
      return Params[generateRandomNumber(0, Params.length)];
    } else {
      return errorMessage('No options specified');
    }
  }

  function roulette(chatID){
    if(generateRandomNumber(1,5)===1){
      sendMessage(chatID, "Peng! Du bist Tod. Miau")
    }else {
      sendMessage(chatID, "Glück gehabt du Penner")
    }
  }

  function errorMessage(ErrorMessage) {
    return 'Error: '.concat(ErrorMessage);
  }

  function generateRandomNumber(min, max) {
    return Math.floor((Math.random() * max) + min);
  }

  function executeTest() {
    bot.sendMessage(49897717, 'haaaack');
  }

  function sendMessage(chatID, Message) {
    bot.sendMessage(chatID, Message);
  }

  function engage(chatID, message){
    let i = 1;
    function engageLoop () {
       setTimeout(function () {
          bot.sendMessage(chatID, 'Meow '.concat(message));
          i++;
          if (i < 6) {
             engageLoop();
          }
       }, 1000)
    }
    engageLoop();
  //    bot.sendMessage(chatID,message);
  }

  // Timeout in milliseconds
  function waitForMessage(userID, callback) {
    bot.on('message', function(msg) {
      const userId = msg.from.id;
      if (userId.equals(userID)) {
        callback(msg);
      }
    });
  }

  function ohKadseWasEssenWirHeute(chatID) {
    if (!ohKadseMap.has(chatID) || ohKadseMap.get(chatID) !== new Date().getDate()) {
      const decision = decide(['Mensa', 'Fresh', 'Smileys', 'Penny', 'Dinos', 'Hack']);
      if (decision !== 'Hack') {
        ohKadseMap.set(chatID, new Date().getDate());
      } else {
        ohKadseMap.delete(chatID);
      }
      bot.sendMessage(chatID, decision);
    } else {
      bot.sendMessage(chatID, 'Ob du behindert bist. Kadse hat entschieden!');
    }
  }

  function incrementUsage(inputData){
      Statistic.findOne({chat_id: inputdata.message.chat.id}, function(err, statisticEntry) {
          if (!err) {
            if (!statisticEntry) {
              statisticEntry = new Statistic();
              statisticEntry.chat_id = inputData.message.chat.id;
              statisticEntry.used = 0;
            }
            statisticEntry.used = statisticEntry.used + 1;
            statisticEntry.save(function(err) {
              if (!err) {
                // console.log("contact " + statisticEntry.phone + " created at " + statisticEntry.createdAt + " updated at " + statisticEntry.updatedAt);
              }
              else {
               // console.log("Error: could not save contact " + statisticEntry.phone);
              }
            });
          }
      });
  }

  return {
    executeCommand,
    executeTest,
    sendMessage,
    waitForMessage
  };
})();


text:
Container Docker to run PHP!
===================

![PHP Logo](https://raw.githubusercontent.com/docker-library/docs/01c12653951b2fe592c1f93a13b4e289ada0e3a1/php/logo.png)

----------

Supported tags
-------------

 - lastest [![Build Status](https://travis-ci.org/cbsan/docker-php.svg?branch=master)](https://travis-ci.org/cbsan/docker-php)  [![](https://images.microbadger.com/badges/image/cbsan/php.svg)](https://microbadger.com/images/cbsan/php) [![](https://images.microbadger.com/badges/version/cbsan/php.svg)](https://microbadger.com/images/cbsan/php "Get your own version badge on microbadger.com")

### Using container

> - docker run -d cbsan/php:5.6


text:
package nuesoft.repositorysample.exception;

/**
 * Created by mysterious on 8/14/17.
 */

public class StoreException extends Exception {

    public StoreException() {
        super();
    }

    public StoreException(String exception) {
        super(exception);
    }
}


text:
package rapidandroidsdk.eway.com.rapidandroidsdk.event;

import com.ewaypayments.sdk.android.entities.EncryptItemsResponse;

/**
 * Created by alexanderparra on 31/10/15.
 */

public class EncryptValuesEvent {
    public EncryptItemsResponse encryptItemsResponse;

    public EncryptValuesEvent(EncryptItemsResponse encryptResp){
        this.encryptItemsResponse = encryptResp;
    }

}


text:
START_ATF_NAMESPACE
    struct _gettextlengthex
    {
        unsigned int flags;
        unsigned int codepage;
    };
END_ATF_NAMESPACE


text:
#include "PathOpsExtendedTest.h"
#include "PathOpsTestCommon.h"
#include "PathOpsThreadedCommon.h"
#include "SkIntersections.h"
#include "SkPathOpsLine.h"
#include "SkPathOpsQuad.h"
#include "SkReduceOrder.h"
#include "SkString.h"

#include <utility>

static int doIntersect(SkIntersections& intersections, const SkDQuad& quad, const SkDLine& line,
                       bool& flipped) {
    int result;
    flipped = false;
    if (line[0].fX == line[1].fX) {
        double top = line[0].fY;
        double bottom = line[1].fY;
        flipped = top > bottom;
        if (flipped) {
            using std::swap;
            swap(top, bottom);
        }
        result = intersections.vertical(quad, top, bottom, line[0].fX, flipped);
    } else if (line[0].fY == line[1].fY) {
        double left = line[0].fX;
        double right = line[1].fX;
        flipped = left > right;
        if (flipped) {
            using std::swap;
            swap(left, right);
        }
        result = intersections.horizontal(quad, left, right, line[0].fY, flipped);
    } else {
        intersections.intersect(quad, line);
        result = intersections.used();
    }
    return result;
}

static void testLineIntersect(skiatest::Reporter* reporter, const SkDQuad& quad,
                              const SkDLine& line, const double x, const double y) {
    SkString pathStr;
    pathStr.appendf("    path.moveTo(%1.9g, %1.9g);\n", quad[0].fX, quad[0].fY);
    pathStr.appendf("    path.quadTo(%1.9g, %1.9g, %1.9g, %1.9g);\n", quad[1].fX,
            quad[1].fY, quad[2].fX, quad[2].fY);
    pathStr.appendf("    path.moveTo(%1.9g, %1.9g);\n", line[0].fX, line[0].fY);
    pathStr.appendf("    path.lineTo(%1.9g, %1.9g);\n", line[1].fX, line[1].fY);

    SkIntersections intersections;
    bool flipped = false;
    int result = doIntersect(intersections, quad, line, flipped);
    bool found = false;
    for (int index = 0; index < result; ++index) {
        double quadT = intersections[0][index];
        SkDPoint quadXY = quad.ptAtT(quadT);
        double lineT = intersections[1][index];
        SkDPoint lineXY = line.ptAtT(lineT);
        if (quadXY.approximatelyEqual(lineXY)) {
            found = true;
        }
    }
    REPORTER_ASSERT(reporter, found);
}

// find a point on a quad by choosing a t from 0 to 1
// create a vertical span above and below the point
// verify that intersecting the vertical span and the quad returns t
// verify that a vertical span starting at quad[0] intersects at t=0
// verify that a vertical span starting at quad[2] intersects at t=1
static void testQuadLineIntersectMain(PathOpsThreadState* data)
{
    PathOpsThreadState& state = *data;
    REPORTER_ASSERT(state.fReporter, data);
    int ax = state.fA & 0x03;
    int ay = state.fA >> 2;
    int bx = state.fB & 0x03;
    int by = state.fB >> 2;
    int cx = state.fC & 0x03;
    int cy = state.fC >> 2;
    QuadPts q = {{{(double) ax, (double) ay}, {(double) bx, (double) by},
            {(double) cx, (double) cy}}};
    SkDQuad quad;
    quad.debugSet(q.fPts);
    SkReduceOrder reducer;
    int order = reducer.reduce(quad);
    if (order < 3) {
        return;
    }
    for (int tIndex = 0; tIndex <= 4; ++tIndex) {
        SkDPoint xy = quad.ptAtT(tIndex / 4.0);
        for (int h = -2; h <= 2; ++h) {
            for (int v = -2; v <= 2; ++v) {
                if (h == v && SkTAbs(h) != 1) {
                    continue;
                }
                double x = xy.fX;
                double y = xy.fY;
                SkDLine line = {{{x - h, y - v}, {x, y}}};
                testLineIntersect(state.fReporter, quad, line, x, y);
                state.fReporter->bumpTestCount();
                SkDLine line2 = {{{x, y}, {x + h, y + v}}};
                testLineIntersect(state.fReporter, quad, line2, x, y);
                state.fReporter->bumpTestCount();
                SkDLine line3 = {{{x - h, y - v}, {x + h, y + v}}};
                testLineIntersect(state.fReporter, quad, line3, x, y);
                state.fReporter->bumpTestCount();
            }
        }
    }
}

DEF_TEST(PathOpsQuadLineIntersectionThreaded, reporter) {
    initializeTests(reporter, "testQuadLineIntersect");
    PathOpsThreadedTestRunner testRunner(reporter);
    for (int a = 0; a < 16; ++a) {
        for (int b = 0 ; b < 16; ++b) {
            for (int c = 0 ; c < 16; ++c) {
                *testRunner.fRunnables.append() = new PathOpsThreadedRunnable(
                        &testQuadLineIntersectMain, a, b, c, 0, &testRunner);
            }
            if (!reporter->allowExtendedTest()) goto finish;
        }
    }
finish:
    testRunner.render();
}


text:
/*	$NetBSD: mach_port.h,v 1.34.2.1 2004/08/25 21:27:39 he Exp $ */

/*-
 * Copyright (c) 2002-2003 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Emmanuel Dreyfus
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by the NetBSD
 *        Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef	_MACH_PORT_H_
#define	_MACH_PORT_H_

#define MACH_PORT_REF(mp)	(mp)->mp_refcount++
#define MACH_PORT_UNREF(mp)	if (--(mp)->mp_refcount <= 0) mach_port_put(mp)

#define MACH_PORT_NULL			(struct mach_right *)0
#define MACH_PORT_DEAD			(struct mach_right *)-1

#define MACH_PORT_RIGHT_SEND		0
#define MACH_PORT_RIGHT_RECEIVE		1
#define MACH_PORT_RIGHT_SEND_ONCE	2
#define MACH_PORT_RIGHT_PORT_SET	3
#define MACH_PORT_RIGHT_DEAD_NAME	4
#define MACH_PORT_RIGHT_NUMBER		5

#define MACH_PORT_TYPE_SEND		(1 << (MACH_PORT_RIGHT_SEND + 16))
#define MACH_PORT_TYPE_RECEIVE		(1 << (MACH_PORT_RIGHT_RECEIVE + 16))
#define MACH_PORT_TYPE_SEND_ONCE	(1 << (MACH_PORT_RIGHT_SEND_ONCE + 16))
#define MACH_PORT_TYPE_PORT_SET		(1 << (MACH_PORT_RIGHT_PORT_SET + 16))
#define MACH_PORT_TYPE_DEAD_NAME	(1 << (MACH_PORT_RIGHT_DEAD_NAME + 16))
#define MACH_PORT_TYPE_PORT_RIGHTS \
    (MACH_PORT_TYPE_SEND | MACH_PORT_TYPE_RECEIVE | MACH_PORT_TYPE_SEND_ONCE)
#define MACH_PORT_TYPE_PORT_OR_DEAD \
    (MACH_PORT_TYPE_PORT_RIGHTS | MACH_PORT_TYPE_DEAD_NAME)
#define MACH_PORT_TYPE_ALL_RIGHTS \
    (MACH_PORT_TYPE_PORT_OR_DEAD|MACH_PORT_TYPE_PORT_SET)
#define MACH_PORT_TYPE_REF_RIGHTS \
    (MACH_PORT_TYPE_SEND | MACH_PORT_TYPE_SEND_ONCE | MACH_PORT_TYPE_DEAD_NAME)

/* port_deallocate */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
} mach_port_deallocate_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_msg_trailer_t rep_trailer;
} mach_port_deallocate_reply_t;

/* port_allocate */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_right_t req_right;
} mach_port_allocate_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_port_name_t rep_name;
	mach_msg_trailer_t rep_trailer;
} mach_port_allocate_reply_t;

/* port_insert_right */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_msg_body_t req_body;
	mach_msg_port_descriptor_t req_poly;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
} mach_port_insert_right_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_msg_trailer_t rep_trailer;
} mach_port_insert_right_reply_t;

/* port_type */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
} mach_port_type_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_port_type_t rep_ptype;
	mach_msg_trailer_t rep_trailer;
} mach_port_type_reply_t;

/* port_set_attributes */

#define MACH_PORT_LIMITS_INFO 1
#define MACH_PORT_RECEIVE_STATUS 2
#define MACH_PORT_DNREQUESTS_SIZE 3

typedef struct mach_port_status {
	mach_port_name_t	mps_pset;
	mach_port_seqno_t	mps_seqno;
	mach_port_mscount_t	mps_mscount;
	mach_port_msgcount_t	mps_qlimit;
	mach_port_msgcount_t	mps_msgcount;
	mach_port_rights_t	mps_sorights;
	mach_boolean_t		mps_srights;
	mach_boolean_t		mps_pdrequest;
	mach_boolean_t		mps_nsrequest;
	unsigned int		mps_flags;
} mach_port_status_t;

typedef struct mach_port_limits {
	mach_port_msgcount_t	mpl_qlimit;
} mach_port_limits_t;

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
	mach_port_flavor_t req_flavor;
	mach_msg_type_number_t req_count;
	mach_integer_t req_port_info[0];
} mach_port_set_attributes_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_msg_trailer_t rep_trailer;
} mach_port_set_attributes_reply_t;

/* port_get_attributes */

#define MACH_PORT_QLIMIT_DEFAULT ((mach_port_msgcount_t) 5)
#define MACH_PORT_QLIMIT_MAX ((mach_port_msgcount_t) 16)

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
	mach_port_flavor_t req_flavor;
	mach_msg_type_number_t req_count;
} mach_port_get_attributes_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_msg_type_number_t rep_count;
	mach_integer_t rep_info[10];
	mach_msg_trailer_t rep_trailer;
} mach_port_get_attributes_reply_t;

/* port_insert_member */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
	mach_port_name_t req_pset;
} mach_port_insert_member_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_msg_trailer_t rep_trailer;
} mach_port_insert_member_reply_t;

/* port_move_member */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_member;
	mach_port_name_t req_after;
} mach_port_move_member_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_msg_trailer_t rep_trailer;
} mach_port_move_member_reply_t;

/* port_destroy */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
} mach_port_destroy_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_ndr_record_t rep_ndr;
	mach_kern_return_t rep_retval;
	mach_msg_trailer_t rep_trailer;
} mach_port_destroy_reply_t;

/* port_request_notification */

typedef struct {
	mach_msg_header_t req_msgh;
	mach_msg_body_t req_body;
	mach_msg_port_descriptor_t req_notify;
	mach_ndr_record_t req_ndr;
	mach_port_name_t req_name;
	mach_msg_id_t req_msgid;
	mach_port_mscount_t req_count;
} mach_port_request_notification_request_t;

typedef struct {
	mach_msg_header_t rep_msgh;
	mach_msg_body_t rep_body;
	mach_msg_port_descriptor_t rep_previous;
	mach_msg_trailer_t rep_trailer;
} mach_port_request_notification_reply_t;

/* Kernel-private structures */

extern struct mach_port *mach_clock_port;
extern struct mach_port *mach_io_master_port;
extern struct mach_port *mach_bootstrap_port;
extern struct mach_port *mach_saved_bootstrap_port;

/* In-kernel Mach port right description */
struct mach_right {
	mach_port_t mr_name;		/* The right name */
	struct lwp *mr_lwp;		/* points back to struct lwp */
	int mr_type;			/* right type (recv, send, sendonce) */
	LIST_ENTRY(mach_right) mr_list; /* Right list for a process */
	int mr_refcount;		/* Reference count */
	struct mach_right *mr_notify_destroyed;		/* notify destroyed */
	struct mach_right *mr_notify_dead_name;		/* notify dead name */
	struct mach_right *mr_notify_no_senders;	/* notify no senders */

	/* Revelant only if the right is on a port set */
	LIST_HEAD(mr_set, mach_right) mr_set;
					/* The right set list */

	/* Revelant only if the right is not on a port set */
	struct mach_port *mr_port;	/* Port we have the right on */
	LIST_ENTRY(mach_right) mr_setlist; /* Set list */

	/* Revelant only if the right is part of a port set */
	struct mach_right *mr_sethead;	/* Points back to right set */
};

mach_port_t mach_right_newname(struct lwp *, mach_port_t);
struct mach_right *mach_right_get(struct mach_port *,
    struct lwp *, int, mach_port_t);
void mach_right_put(struct mach_right *, int);
void mach_right_put_shlocked(struct mach_right *, int);
void mach_right_put_exclocked(struct mach_right *, int);
struct mach_right *mach_right_check(mach_port_t, struct lwp *, int);

/* In-kernel Mach port description */
struct mach_port {
	struct mach_right *mp_recv;	/* The receive right on this port */
	int mp_count;			/* Count of queued messages */
	TAILQ_HEAD(mp_msglist,		/* Queue pending messages */
	    mach_message) mp_msglist;
	struct lock mp_msglock;		/* Lock for the queue */
	int mp_refcount;		/* Reference count */
	int mp_flags;			/* Flags, see below */
	int mp_datatype;		/* Type of field mp_data, see below */
	void *mp_data;			/* Data attached to the port */
};

/* mp_flags for struct mach_port */
#define MACH_MP_INKERNEL	0x01	/* Receiver is inside the kernel */
#define MACH_MP_DATA_ALLOCATED	0x02	/* mp_data was malloc'ed */

/* mp_datatype for struct mach_port */
#define	MACH_MP_NONE		0x0	/* No data */
#define MACH_MP_LWP		0x1	/* (struct lwp *) */
#define MACH_MP_DEVICE_ITERATOR	0x2	/* (struct mach_device_iterator *) */
#define MACH_MP_IOKIT_DEVCLASS	0x3	/* (struct mach_iokit_devclass *) */
#define MACH_MP_PROC		0x4	/* (struct proc *) */
#define MACH_MP_NOTIFY_SYNC	0x5	/* int */
#define MACH_MP_MEMORY_ENTRY	0x6	/* (struct mach_memory_entry *) */
#define MACH_MP_EXC_INFO	0x7	/* (struct mach_exc_info *) */
#define MACH_MP_SEMAPHORE	0x8	/* (struct mach_semaphore *) */

void mach_port_init(void);
struct mach_port *mach_port_get(void);
void mach_port_put(struct mach_port *);
void mach_remove_recvport(struct mach_port *);
void mach_add_recvport(struct mach_port *, struct lwp *);
int mach_port_check(struct mach_port *);
#ifdef DEBUG_MACH
void mach_debug_port(void);
#endif

#endif /* _MACH_PORT_H_ */


text:
using System;

namespace R4Mvc.ModelUnbinders
{
    public interface IModelUnbinderProvider
    {
        IModelUnbinder GetUnbinder(Type routeValueType);
    }
}


text:
using namespace std;

void showValues(int [], int); // Function prototype

int main()
{
   const int SIZE1 = 8; // Size of set1 array
   const int SIZE2 = 5; // Size of set2 array
   int set1[SIZE1] = {5, 10, 15, 20, 25, 30, 35, 40};
   int set2[SIZE2] = {2, 4, 6, 8, 10};

   // Pass set1 to showValues.
   showValues(set1, SIZE1);

   // Pass set2 to showValues.
   showValues(set2, SIZE2);
   return 0;
}

//**************************************************
// Definition of function showValues.              *
// This function accepts an array of integers and  *
// the array's size as its arguments. The contents *
// of the array are displayed.                     *
//**************************************************

void showValues(int nums[], int size)
{
   for (int index = 0; index < size; index++)
      cout << nums[index] << " ";
   cout << endl;
}


text:
namespace blink {

class V8UnionDoubleOrDoubleSequence;

class SequenceTest final : public ScriptWrappable {
  DEFINE_WRAPPERTYPEINFO();

 public:
  SequenceTest();
  ~SequenceTest() override;

  Vector<Vector<String>> identityByteStringSequenceSequence(
      const Vector<Vector<String>>& arg) const;
  Vector<double> identityDoubleSequence(const Vector<double>& arg) const;
  Vector<V8FoodEnum> identityFoodEnumSequence(
      const Vector<V8FoodEnum>& arg) const;
  Vector<int32_t> identityLongSequence(const Vector<int32_t>& arg) const;
  absl::optional<Vector<uint8_t>> identityOctetSequenceOrNull(
      const absl::optional<Vector<uint8_t>>& arg) const;

  HeapVector<Member<Element>> getElementSequence() const;
  void setElementSequence(const HeapVector<Member<Element>>& arg);

  bool unionReceivedSequence(const V8UnionDoubleOrDoubleSequence* arg);

  void Trace(Visitor*) const override;

 private:
  HeapVector<Member<Element>> element_sequence_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_SEQUENCE_TEST_H_


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.customatics</groupId>
    <artifactId>leaptest-integration-for-bamboo</artifactId>
    <version>3.0.0</version>

    <organization>
        <name>Customatics</name>
        <url>http://customatics.com/</url>
    </organization>

    <name>Leapwork Integration</name>
    <description>Integrates Leapwork codeless test automation with Bamboo. Run tests, get results, generate reports.</description>
    <packaging>atlassian-plugin</packaging>

    <properties>
         <bamboo.version>6.8.0</bamboo.version>
        <bamboo.data.version>6.8.0</bamboo.data.version>
        <amps.version>8.0.0</amps.version>
        <plugin.testrunner.version>2.0.1</plugin.testrunner.version>
        <atlassian.spring.scanner.version>1.2.13</atlassian.spring.scanner.version>
        <!-- This property ensures consistency between the key in atlassian-plugin.xml and the OSGi bundle's key. -->
        <atlassian.plugin.key>${project.groupId}.${project.artifactId}</atlassian.plugin.key>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

     <dependencies>
        <dependency>
            <groupId>com.atlassian.bamboo</groupId>
            <artifactId>atlassian-bamboo-web</artifactId>
            <version>${bamboo.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.atlassian.plugin</groupId>
            <artifactId>atlassian-spring-scanner-annotation</artifactId>
            <version>${atlassian.spring.scanner.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.atlassian.sal</groupId>
            <artifactId>sal-api</artifactId>
            <version>3.0.8</version>
            <scope>provided</scope> <!-- Uses the application's SAL instead of bundling it into the plugin. -->
        </dependency>

        <!-- WIRED TEST RUNNER DEPENDENCIES -->
        <dependency>
            <groupId>com.atlassian.plugins</groupId>
            <artifactId>atlassian-plugins-osgi-testrunner</artifactId>
            <version>${plugin.testrunner.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.2-atlassian-1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.ning</groupId>
            <artifactId>async-http-client</artifactId>
            <version>1.4.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.atlassian.bamboo.plugins.testresultparser</groupId>
            <artifactId>atlassian-bamboo-plugin-testresultparser</artifactId>
            <version>6.6.3</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
             <plugin>
                <groupId>com.atlassian.maven.plugins</groupId>
                <artifactId>bamboo-maven-plugin</artifactId>
                <version>${amps.version}</version>
                <extensions>true</extensions>
                <configuration>

                    <productVersion>${bamboo.version}</productVersion>
                    <productDataVersion>${bamboo.data.version}</productDataVersion>
                    <enableQuickReload>true</enableQuickReload>

                    <!-- See here for an explanation of default instructions: -->
                    <!-- https://developer.atlassian.com/docs/advanced-topics/configuration-of-instructions-in-atlassian-plugins -->
                    <instructions>
                        <Atlassian-Plugin-Key>${atlassian.plugin.key}</Atlassian-Plugin-Key>

                        <!-- Add package import here -->
                        <Import-Package>
                            org.springframework.osgi.*;resolution:="optional",
                            com.ning.http.client.*;resolution:="optional",
                            com.google.code.gson.*;resolution:="optional",
                            com.google.protobuf.*;resolution:="optional",
                            org.glassfish.grizzly.*;resolution:="optional",
                            org.osgi.service.log;resolution:="optional",
                            com.sun.org.apache.xerces.internal.dom;resolution:="optional",
                            com.atlassian.util.concurrent.NotNull;resolution:="optional",
                            org.eclipse.gemini.blueprint.*;resolution:="optional",
                            *
                        </Import-Package>

                        <!-- Ensure plugin is spring powered -->
                        <Spring-Context>*</Spring-Context>
                    </instructions>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.atlassian.plugin</groupId>
                <artifactId>atlassian-spring-scanner-maven-plugin</artifactId>
                <version>${atlassian.spring.scanner.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>atlassian-spring-scanner</goal>
                        </goals>
                        <phase>process-classes</phase>
                    </execution>
                </executions>
                <configuration>
                    <scannedDependencies>
                        <dependency>
                            <groupId>com.atlassian.plugin</groupId>
                            <artifactId>atlassian-spring-scanner-external-jar</artifactId>
                        </dependency>
                    </scannedDependencies>
                    <verbose>false</verbose>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>Description__c</fullName>
    <description>More details about the credential or student Attribute.</description>
    <externalId>false</externalId>
    <inlineHelpText>More details about the credential or student Attribute.</inlineHelpText>
    <label>Description</label>
    <length>32768</length>
    <trackTrending>false</trackTrending>
    <type>LongTextArea</type>
    <visibleLines>3</visibleLines>
</CustomField>


text:
using System.Collections.Generic;
using Newtonsoft.Json;
using NUnit.Framework;
using SuccincT.JSON;
using SuccincT.Unions;
using static Newtonsoft.Json.JsonConvert;
using static NUnit.Framework.Assert;

namespace SuccincTTests.SuccincT.JSON
{
    [TestFixture]
    public static class UnionOf2ConverterTests
    {
        [Test]
        public static void WhenProvidedWithNoCase_DeserializeFailsWithJsonException()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new UnionOf2Converter());

            _ = Throws<JsonException>(() => {
                _ = DeserializeObject<Union<List<int>, string> > ("{k:1, value:2}", settings);
            });
        }

        [Test]
        public static void WhenProvidedWithNoValue_DeserializeFailsWithJsonException()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new UnionOf2Converter());

            _ = Throws<JsonException>(() => {
                _ = DeserializeObject<Union<List<int>, string>>("{case:\"Case1\", k:2}", settings);
            });
        }

        [Test]
        public static void ConvertingUnionToJsonAndBack_PreservesUnionState()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new UnionOf2Converter());
            var union = new Union<List<int>, string>(new List<int> { 1, 2 });
            var json = SerializeObject(union, settings);
            var newUnion = DeserializeObject<Union<List<int>, string>>(json, settings);

            AreEqual(2, newUnion.Case1.Count);
            AreEqual(Variant.Case1, newUnion.Case);
            AreEqual(1, newUnion.Case1[0]);
            AreEqual(2, newUnion.Case1[1]);
        }

        [Test]
        public static void ConvertingListOfUnionsToJsonAndBack_PreservesUnionState()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new UnionOf2Converter());
            var union1 = new Union<int, string>(1);
            var union2 = new Union<int, string>("a");
            var list = new List<Union<int, string>> { union1, union2 };
            var json = SerializeObject(list, settings);
            var newList = DeserializeObject<List<Union<int, string>>>(json, settings);

            AreEqual(2, newList.Count);
            AreEqual(Variant.Case1, newList[0].Case);
            AreEqual(Variant.Case2, newList[1].Case);
            AreEqual(1, newList[0].Case1);
            AreEqual("a", newList[1].Case2);
        }
    }
}


text:
package org.i3xx.util.client.dns;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;

import org.xbill.DNS.DClass;
import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Message;
import org.xbill.DNS.NSRecord;
import org.xbill.DNS.Name;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.ReverseMap;
import org.xbill.DNS.Section;
import org.xbill.DNS.Type;
import org.xbill.DNS.ZoneTransferException;

public class DnsDomainInfo {

	/**  */
	private final String strDomain;

	/**  */
	private final String[] nameServer;

	/**
	 * Gets the domain and the nameserver
	 *
	 * @throws IOException
	 */
	public DnsDomainInfo() throws IOException {

		InetAddress addr = InetAddress.getByName(InetAddress.getLocalHost().getHostName());
		String dm = addr.getCanonicalHostName();

		String[] namesrv = null;

		while(dm.contains(".")) {
			dm = dm.substring(dm.indexOf('.')+1);
			Record [] records = new Lookup(dm, Type.NS).run();

			if(records!=null) {
				namesrv = new String[records.length];
				for(int i=0;i<records.length;i++) {
					NSRecord r = (NSRecord)records[i];
					namesrv[i] = r.getTarget().toString(true);
				}
				break;
			}//fi
		}//
		Arrays.sort(namesrv);

		nameServer = namesrv;
		strDomain = dm;
	}

	/**
	 * Gets the domain, but not the nameserver
	 * From various code examples
	 *
	 * @param hostIp
	 * @throws IOException
	 * @throws ZoneTransferException
	 */
	public DnsDomainInfo(String hostIp) throws IOException, ZoneTransferException {

		Resolver res = new ExtendedResolver();
		Name name = ReverseMap.fromAddress(hostIp);

		int type = Type.PTR;
		int dclass = DClass.IN;

		Record rec = Record.newRecord(name, type, dclass);
		Message query = Message.newQuery(rec);
		Message response = res.send(query);

		Record[] answers = response.getSectionArray(Section.ANSWER);
		if (answers.length == 0) {
			strDomain = null;
			nameServer = null;
		}else{
			String s = answers[0].rdataToString();
			int n = s.indexOf('.');
			String dm = n<0 ? s : s.substring(n+1);
			if(dm.endsWith("."))
				dm = dm.substring(0, dm.length()-1);

			strDomain = dm;

			String[] namesrv = null;
			Record [] records = new Lookup(strDomain, Type.NS).run();
			if(records!=null) {
				namesrv = new String[records.length];
				for(int i=0;i<records.length;i++) {
					NSRecord r = (NSRecord)records[i];
					namesrv[i] = r.getTarget().toString(true);
				}
				Arrays.sort(namesrv);
			}//fi

			nameServer = namesrv;
		}//fi

	}

	/**
	 * @return the domain
	 */
	public String getDomain() {
		return strDomain;
	}

	/**
	 * @return
	 */
	public String[] getNameserver() {
		return nameServer;
	}

}


text: <!DOCTYPE html>


text:
package com.adyen.serializer;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class DateSerializer implements JsonSerializer<Date> {
    public static final String DATE_FORMAT = "yyyy-MM-dd";

    @Override
    public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) {
        SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
        return new JsonPrimitive(formatter.format(date));
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="../paginas/css/bootstrap.min.css">

    <title>Registro</title>

Registro

Rellena los datos

              <form action="reg.php" method="post">

                  *Nombre:
                  <input class="form-control" type="text" id="nombre" name="nombre" value="" required>

                  *Apellido paterno:
                  <input class="form-control" type="text" id="a_paterno" name="a_paterno" value="" required>

                  *Apellido materno:
                  <input class="form-control" type="text" id="a_materno" name="a_materno" value="" required>

                  CURP:
                  <input class="form-control" type="text" id="curp" name="curp" value="" maxlength="18">

                  Telefono
                  <input class="form-control" type="text" id="telefono" name="telefono" value="" maxlength="10">

Estado actual

(Integridad,lesiones ,etc)

(max250 caracteres)

                  <select class="form-control" name="estado" id="estado">
                    <option value="sano">Sano</option>
                    <option value="lesion_leve">Lesion leve </option>
                    <option value="lesion_de_gravedad">Lesion de gravedad</option>
                    <option value="fallecido">fallecido</option>
                  </select>

Ubicacion

                  <textarea class="form-control" rows="8" cols="20" id="ubicacion" name="ubicacion"></textarea>

                  <input class="btn btn-danger" type="submit" value="Registrar" onclick="agregar()">

              </form>


text:
CREATE TABLE [dbo].[CategoryTemp] (
    [CategoryId]   BIGINT       NOT NULL,
    [RecipeId]     BIGINT       NULL,
    [DisplayOrder] BIGINT       NULL,
    [Description]  VARCHAR (50) NULL
);


text:
module Interactors
  module Search
    class All
      include Pavlov::Interactor
      include Util::CanCan

      arguments :keywords

      def execute
        row_count = 20 # WARNING: coupling with ReactSearchResults

        Backend::Search.search_all keywords: keywords, page: 1,
                                   row_count: row_count, types: [:factdata, :user]
      end

      def validate
        validate_nonempty_string :keywords, keywords
      end

      def authorized?
        true
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>CSS1 Test Suite: 5.5.15 border-width</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<META http-equiv="Content-Style-Type" content="text/css">

<LINK rel="stylesheet" type="text/css" media="screen" href="../resources/base.css">

The style declarations which apply to the text below are:

.zero {background-color: silver; border-width: 0;}
.one {border-width: 50px; border-style: solid;}
.two {border-width: thick; border-style: solid;}
.three {border-width: medium; border-style: solid;}
.four {border-width: thin; border-style: solid;}
.five {border-width: 25px;}

(These will only work if border-style is supported.)

This element has a class of zero.

This element should have an overall border width of 50 pixels.

This element should have a thick overall border width.

This element should have a medium overall border width.

This element should have a thin overall border width.

This element should have no border and no extra "padding" on any side, as no border-style was set.

TABLE Testing Section

(These will only work if border-style is supported.)

This element has a class of zero.

This element should have an overall border width of 50 pixels.

This element should have a thick overall border width.

This element should have a medium overall border width.

This element should have a thin overall border width.

This element should have no border and no extra "padding" on any side, as no border-style was set.


text:
package coreServerThreads;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import common.Message;

import coreServer.Request;
import coreServer.RequestQueue;

public class MessageReceiveWorkerThread extends Thread
{
	private Socket clientSocket;
	private ObjectInputStream ois;
	private Message msgObj;
	private RequestQueue queue;
	private int retryCount;

	public MessageReceiveWorkerThread(Socket client, RequestQueue queue)
	{
		super();
		this.clientSocket = client;
		this.queue = queue;
		this.retryCount = 3;
	}

	public void run()
	{
		System.out.println("Spawned a message receiver worker thread.");
		try
		{
			ois = new ObjectInputStream(clientSocket.getInputStream());
		}
		catch (IOException e)
		{
			System.out
					.println("Couldn't get OIS from client socket. Terminating thread.");
			return;
		}
		System.out.println("Got OIS / MsgRcvWorkerThread.");
		while (retryCount > 0)
		{
			try
			{
				msgObj = (Message) ois.readObject();
				break;
			}
			catch (ClassNotFoundException | IOException e)
			{
				System.out
						.println("Invalid object received from client. Retrying..");
				retryCount--;
			}
		}
		if (msgObj.destNick == null)
			return;
		else if (msgObj.destNick.equals(""))
			return;
		System.out.println("rcv: " + msgObj.sourceNick + " -> "
				+ msgObj.destNick + " : " + msgObj.content);
		synchronized (queue)
		{
			queue.addRequest(new Request(msgObj));

			queue.notify();
		}
		System.out.println("Added new request Obj.");
		return;
	}

}


text:
<?php

namespace Mothership\StateMachine;

use Mothership\StateMachine\Exception\StateMachineException;
use Mothership\StateMachine\Exception\WorkflowException;
use Symfony\Component\Yaml\Yaml;

/**
 * Class AbstractMagentoCommand.
 *
 * @author    Don Bosco van Hoi <vanhoi@mothership.de>
 * @author    Maurizio Brioschi <brioschi@mothership.de>
 * @copyright 2016 Mothership GmbH
 *
 * @link      http://www.mothership.de/
 */
abstract class StateMachineAbstract implements StateMachineInterface
{
    /**
     * The original configuration for the state machine.
     *
     * @var mixed
     */
    protected $configuration;

    /**
     * The workflow configuration onlycontains the parsed
     * configuration
     *
     * @var mixed
     */
    protected $workflowConfiguration;

    /**
     * @var \Mothership\StateMachine\WorkflowAbstract
     */
    protected $workflow;

    /**
     * Pass the.
     *
     * @param array $configuration
     *
     * @throws StateMachineException
     */
    public function __construct(array $configuration)
    {
        $this->configuration = $configuration;
        if (empty($configuration)) {
            throw new StateMachineException('Empty configuration file', 98, null);
        }

        //read the file
        try {
            $this->workflowConfiguration = $this->parseYAML();
            if ($this->workflowConfiguration === false || $this->workflowConfiguration === null) {
                throw new StateMachineException('Error parsing the configuration', 98, null);
            }
        } catch (\Symfony\Component\Yaml\Exception\ParseException $ex) {
            throw new StateMachineException('Error parsing the configuration', 98, $ex);
        }

        $this->initWorkflow();
    }

    /**
     * Parse the yaml configuration.
     *
     * @return array
     *
     * @throws \Symfony\Component\Yaml\Exception\ParseException
     * @throws \Exception
     */
    protected function parseYAML()
    {
        try {
            $yaml                = $this->configuration;
            $yaml_fixed          = [];
            $yaml_fixed['class'] = $yaml['class'];
            foreach ($yaml['states'] as $key => $value) {
                if ($value['type'] != \Mothership\StateMachine\StatusInterface::TYPE_INITIAL && $value['type'] != \Mothership\StateMachine\StatusInterface::TYPE_EXCEPTION) {
                    $state                  = [
                        'name'             => $key,
                        'type'             => $value['type'],
                        'transitions_from' => $value['transitions_from'],
                        'transitions_to'   => $value['transitions_to'],
                    ];
                    $yaml_fixed['states'][] = $state;
                } else {
                    $state                  = [
                        'name' => $key,
                        'type' => $value['type'],
                    ];
                    $yaml_fixed['states'][] = $state;
                }
            }

            $yaml_fixed['yaml'] = $this->configuration;

            return $yaml_fixed;
        } catch (\Symfony\Component\Yaml\Exception\ParseException $ex) {
            throw $ex;
        }
    }

    /**
     * Create the workflow.
     *
     * @throws \Mothership\StateMachine\Exception\StateMachineException
     */
    protected function initWorkflow()
    {
        $className = $this->workflowConfiguration['class']['name'];

        if (!class_exists($className, true)) {
            throw new StateMachineException('The class ' . $className . ' does not exist!', 100);
        }

        try {
            $this->workflow = new $className($this->workflowConfiguration);
        } catch (WorkflowException $ex) {
            throw new StateMachineException('Workflow with some problems', 90, $ex);
        }
    }

    /**
     * create a graph for the state machine.
     *
     * @param string     $outputPath         relative path of the generated image
     * @param bool|false $stopAfterExecution if we want to exit after graphic generation
     *
     * @return void
     */
    public function renderGraph($outputPath = './workflow.png', $stopAfterExecution = true)
    {
        /*
         * This example is based on http://martin-thoma.com/how-to-draw-a-finite-state-machine/
         * Feel free to tweak the rendering output. I have decided do use the most simple
         * implementation over the fancy stuff to avoid additional complexity.
         */
        $template
            = '
            digraph finite_state_machine {
                rankdir=LR;
                size="%d"

                node [shape = doublecircle]; start;
                node [shape = circle];

                %s
            }
        ';

        $pattern = ' %s  -> %s [ label = "%s" ];';

        $_transitions = [];
        foreach ($this->workflowConfiguration['states'] as $state) {
            if (array_key_exists('transitions_from', $state)) {
                $transitions_from = $state['transitions_from'];
                foreach ($transitions_from as $from) {
                    if (is_array($from)) {
                        $_transitions[] = sprintf(
                            $pattern,
                            $from['status'],
                            $state['name'],
                            '<< IF '
                            . $this->convertToStringCondition($from['result']) . ' >>' . $state['name']
                        );
                    } else {
                        $_transitions[] = sprintf($pattern, $from, $state['name'], $state['name']);
                    }
                }
            } else {
                if ('type' == 'exception') {
                    $_transitions[] = 'node [shape = doublecircle]; exception;';
                }
            }
        }
        file_put_contents('/tmp/sm.gv', sprintf($template, count($_transitions) * 2, implode("\n", $_transitions)));
        shell_exec('dot -Tpng /tmp/sm.gv -o ' . $outputPath);

        if ($stopAfterExecution) {
            //exit;
        }
    }

    /**
     * Run the state machine with optional arguments.
     *
     * @param array $args
     * @param bool  $enableLog
     *
     * @return mixed
     *
     * @throws StateMachineException
     */
    public function run(array $args = [], $enableLog = false)
    {
        try {
            return $this->workflow->run($args, $enableLog);
        } catch (WorkflowException $ex) {
            throw new StateMachineException('Error running State Machine', 100, $ex);
        }
    }

    /**
     * Wrapper for running the acceptance test.
     *
     * @param mixed $states
     * @param bool  $verbose
     */
    public function acceptance($states, $verbose = false)
    {
        $this->workflow->acceptance($states, $verbose);
    }

    /**
     * Retreive the workflow implementation.
     *
     * @return \Mothership\StateMachine\WorkflowAbstract
     */
    public function getWorkflow()
    {
        return $this->workflow;
    }

    /**
     * Internal method required for the rendering.
     *
     * @param $condition
     *
     * @return string
     */
    private function convertToStringCondition($condition)
    {
        if (is_bool($condition)) {
            if ($condition) {
                return 'TRUE';
            } else {
                return 'FALSE';
            }
        }

        return (string) $condition;
    }
}


text:
function usage {
  echo "Usage: $0 [OPTION]..."
  echo "Run Glance's test suite(s)"
  echo ""
  echo "  -V, --virtual-env        Always use virtualenv.  Install automatically if not present"
  echo "  -N, --no-virtual-env     Don't use virtualenv.  Run tests in local environment"
  echo "  -f, --force              Force a clean re-build of the virtual environment. Useful when dependencies have been added."
  echo "  --unittests-only         Run unit tests only, exclude functional tests."
  echo "  -p, --pep8               Just run pep8"
  echo "  -h, --help               Print this usage message"
  echo ""
  echo "Note: with no options specified, the script will try to run the tests in a virtual environment,"
  echo "      If no virtualenv is found, the script will ask if you would like to create one.  If you "
  echo "      prefer to run tests NOT in a virtual environment, simply pass the -N option."
  exit
}

function process_option {
  case "$1" in
    -h|--help) usage;;
    -V|--virtual-env) let always_venv=1; let never_venv=0;;
    -N|--no-virtual-env) let always_venv=0; let never_venv=1;;
    -p|--pep8) let just_pep8=1;;
    -f|--force) let force=1;;
    --unittests-only) noseargs="$noseargs --exclude-dir=glance/tests/functional";;
    -c|--coverage) noseargs="$noseargs --with-coverage --cover-package=glance";;
    *) noseargs="$noseargs $1"
  esac
}

venv=.venv
with_venv=tools/with_venv.sh
always_venv=0
never_venv=0
force=0
noseargs=
wrapper=""
just_pep8=0

export NOSE_WITH_OPENSTACK=1
export NOSE_OPENSTACK_COLOR=1
export NOSE_OPENSTACK_RED=0.05
export NOSE_OPENSTACK_YELLOW=0.025
export NOSE_OPENSTACK_SHOW_ELAPSED=1
export NOSE_OPENSTACK_STDOUT=1

for arg in "$@"; do
  process_option $arg
done

function run_tests {
  # Cleanup *pyc
  ${wrapper} find . -type f -name "*.pyc" -delete
  # Just run the test suites in current environment
  ${wrapper} rm -f tests.sqlite
  ${wrapper} $NOSETESTS
}

function run_pep8 {
  echo "Running pep8 ..."
  PEP8_EXCLUDE=".venv,.tox,dist,doc,openstack"
  PEP8_OPTIONS="--exclude=$PEP8_EXCLUDE --repeat"
  PEP8_INCLUDE="."
  ${wrapper} pep8 $PEP8_OPTIONS $PEP8_INCLUDE
}

NOSETESTS="nosetests $noseargs"

if [ $never_venv -eq 0 ]
then
  # Remove the virtual environment if --force used
  if [ $force -eq 1 ]; then
    echo "Cleaning virtualenv..."
    rm -rf ${venv}
  fi
  if [ -e ${venv} ]; then
    wrapper="${with_venv}"
  else
    if [ $always_venv -eq 1 ]; then
      # Automatically install the virtualenv
      python tools/install_venv.py
      wrapper="${with_venv}"
    else
      echo -e "No virtual environment found...create one? (Y/n) \c"
      read use_ve
      if [ "x$use_ve" = "xY" -o "x$use_ve" = "x" -o "x$use_ve" = "xy" ]; then
        # Install the virtualenv and run the test suite in it
        python tools/install_venv.py
		    wrapper=${with_venv}
      fi
    fi
  fi
fi

if [ $just_pep8 -eq 1 ]; then
    run_pep8
    exit
fi

run_tests || exit

if [ -z "$noseargs" ]; then
  run_pep8
fi


text:
import { ColumnModel } from '../column-type/column.model';
import { Command } from '../command/command';
import { GridPlugin } from '../plugin/grid.plugin';

export class GroupLet {
  readonly toggleStatus: Command<[any, ColumnModel]>;
  readonly toggleAllStatus: Command;

  constructor(plugin: GridPlugin, shortcut: { register: (commands: Command[]) => void });

  count(node: Node, column: ColumnModel): number;
  status(node: Node, column: ColumnModel): 'expand' | 'collapse';
  offset(node: Node, column: ColumnModel): number;
  value(node: Node, column: ColumnModel): string;
  isVisible(node: Node, column: ColumnModel): boolean;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >

    <EditText
            android:id="@+id/search_box"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="hello"
            />

    <Button
            android:id="@+id/search_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="search"
            />
</LinearLayout>


text:
/**
 * SECTION:gstformat
 * @title: GstFormat
 * @short_description: Dynamically register new data formats
 * @see_also: #GstPad, #GstElement
 *
 * GstFormats functions are used to register a new format to the gstreamer
 * core.  Formats can be used to perform seeking or conversions/query
 * operations.
 */

#include "gst_private.h"
#include <string.h>
#include "gstformat.h"
#include "gstenumtypes.h"

static GMutex mutex;
static GList *_gst_formats = NULL;
static GHashTable *_nick_to_format = NULL;
static GHashTable *_format_to_nick = NULL;
static guint32 _n_values = 1;   /* we start from 1 because 0 reserved for UNDEFINED */

static GstFormatDefinition standard_definitions[] = {
  {GST_FORMAT_DEFAULT, "default", "Default format for the media type", 0},
  {GST_FORMAT_BYTES, "bytes", "Bytes", 0},
  {GST_FORMAT_TIME, "time", "Time", 0},
  {GST_FORMAT_BUFFERS, "buffers", "Buffers", 0},
  {GST_FORMAT_PERCENT, "percent", "Percent", 0},
  {GST_FORMAT_UNDEFINED, NULL, NULL, 0}
};

void
_priv_gst_format_initialize (void)
{
  GstFormatDefinition *standards = standard_definitions;

  g_mutex_lock (&mutex);
  if (_nick_to_format == NULL) {
    _nick_to_format = g_hash_table_new (g_str_hash, g_str_equal);
    _format_to_nick = g_hash_table_new (NULL, NULL);
  }

  while (standards->nick) {
    standards->quark = g_quark_from_static_string (standards->nick);
    g_hash_table_insert (_nick_to_format, (gpointer) standards->nick,
        standards);
    g_hash_table_insert (_format_to_nick, GINT_TO_POINTER (standards->value),
        standards);

    _gst_formats = g_list_append (_gst_formats, standards);
    standards++;
    _n_values++;
  }
  /* getting the type registers the enum */
  g_type_class_ref (gst_format_get_type ());
  g_mutex_unlock (&mutex);
}

/**
 * gst_format_get_name:
 * @format: a #GstFormat
 *
 * Get a printable name for the given format. Do not modify or free.
 *
 * Returns: (nullable): a reference to the static name of the format
 * or %NULL if the format is unknown.
 */
const gchar *
gst_format_get_name (GstFormat format)
{
  const GstFormatDefinition *def;
  const gchar *result;

  if ((def = gst_format_get_details (format)) != NULL)
    result = def->nick;
  else
    result = NULL;

  return result;
}

/**
 * gst_format_to_quark:
 * @format: a #GstFormat
 *
 * Get the unique quark for the given format.
 *
 * Returns: the quark associated with the format or 0 if the format
 * is unknown.
 */
GQuark
gst_format_to_quark (GstFormat format)
{
  const GstFormatDefinition *def;
  GQuark result;

  if ((def = gst_format_get_details (format)) != NULL)
    result = def->quark;
  else
    result = 0;

  return result;
}

/**
 * gst_format_register:
 * @nick: The nick of the new format
 * @description: The description of the new format
 *
 * Create a new GstFormat based on the nick or return an
 * already registered format with that nick.
 *
 * Returns: A new GstFormat or an already registered format
 * with the same nick.
 *
 * MT safe.
 */
GstFormat
gst_format_register (const gchar * nick, const gchar * description)
{
  GstFormatDefinition *format;
  GstFormat query;

  g_return_val_if_fail (nick != NULL, GST_FORMAT_UNDEFINED);
  g_return_val_if_fail (description != NULL, GST_FORMAT_UNDEFINED);

  query = gst_format_get_by_nick (nick);
  if (query != GST_FORMAT_UNDEFINED)
    return query;

  g_mutex_lock (&mutex);
  format = g_slice_new (GstFormatDefinition);
  format->value = (GstFormat) _n_values;
  format->nick = g_strdup (nick);
  format->description = g_strdup (description);
  format->quark = g_quark_from_static_string (format->nick);

  g_hash_table_insert (_nick_to_format, (gpointer) format->nick, format);
  g_hash_table_insert (_format_to_nick, GINT_TO_POINTER (format->value),
      format);
  _gst_formats = g_list_append (_gst_formats, format);
  _n_values++;
  g_mutex_unlock (&mutex);

  return format->value;
}

/**
 * gst_format_get_by_nick:
 * @nick: The nick of the format
 *
 * Return the format registered with the given nick.
 *
 * Returns: The format with @nick or GST_FORMAT_UNDEFINED
 * if the format was not registered.
 */
GstFormat
gst_format_get_by_nick (const gchar * nick)
{
  GstFormatDefinition *format;

  g_return_val_if_fail (nick != NULL, GST_FORMAT_UNDEFINED);

  g_mutex_lock (&mutex);
  format = g_hash_table_lookup (_nick_to_format, nick);
  g_mutex_unlock (&mutex);

  if (format != NULL)
    return format->value;
  else
    return GST_FORMAT_UNDEFINED;
}

/**
 * gst_formats_contains:
 * @formats: (array zero-terminated=1): The format array to search
 * @format: the format to find
 *
 * See if the given format is inside the format array.
 *
 * Returns: %TRUE if the format is found inside the array
 */
gboolean
gst_formats_contains (const GstFormat * formats, GstFormat format)
{
  if (!formats)
    return FALSE;

  while (*formats) {
    if (*formats == format)
      return TRUE;

    formats++;
  }
  return FALSE;
}

/**
 * gst_format_get_details:
 * @format: The format to get details of
 *
 * Get details about the given format.
 *
 * Returns: (nullable): The #GstFormatDefinition for @format or %NULL
 * on failure.
 *
 * MT safe.
 */
const GstFormatDefinition *
gst_format_get_details (GstFormat format)
{
  const GstFormatDefinition *result;

  g_mutex_lock (&mutex);
  result = g_hash_table_lookup (_format_to_nick, GINT_TO_POINTER (format));
  g_mutex_unlock (&mutex);

  return result;
}

/**
 * gst_format_iterate_definitions:
 *
 * Iterate all the registered formats. The format definition is read
 * only.
 *
 * Returns: (transfer full): a GstIterator of #GstFormatDefinition.
 */
GstIterator *
gst_format_iterate_definitions (void)
{
  GstIterator *result;

  g_mutex_lock (&mutex);
  /* FIXME: register a boxed type for GstFormatDefinition */
  result = gst_iterator_new_list (G_TYPE_POINTER,
      &mutex, &_n_values, &_gst_formats, NULL, NULL);
  g_mutex_unlock (&mutex);

  return result;
}