text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __SLAVE_HPP__
#define __SLAVE_HPP__

#include <stdint.h>

#include <list>
#include <memory>
#include <string>
#include <vector>

#include <boost/circular_buffer.hpp>

#include <mesos/attributes.hpp>
#include <mesos/resources.hpp>
#include <mesos/type_utils.hpp>

#include <mesos/agent/agent.hpp>

#include <mesos/authentication/secret_generator.hpp>

#include <mesos/executor/executor.hpp>

#include <mesos/master/detector.hpp>

#include <mesos/module/authenticatee.hpp>

#include <mesos/slave/containerizer.hpp>
#include <mesos/slave/qos_controller.hpp>
#include <mesos/slave/resource_estimator.hpp>

#include <mesos/v1/executor/executor.hpp>

#include <process/http.hpp>
#include <process/future.hpp>
#include <process/owned.hpp>
#include <process/limiter.hpp>
#include <process/process.hpp>
#include <process/protobuf.hpp>
#include <process/shared.hpp>

#include <stout/boundedhashmap.hpp>
#include <stout/bytes.hpp>
#include <stout/linkedhashmap.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/recordio.hpp>
#include <stout/uuid.hpp>

#include "common/http.hpp"
#include "common/protobuf_utils.hpp"
#include "common/recordio.hpp"

#include "files/files.hpp"

#include "internal/evolve.hpp"

#include "messages/messages.hpp"

#include "slave/constants.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/flags.hpp"
#include "slave/gc.hpp"
#include "slave/metrics.hpp"
#include "slave/paths.hpp"
#include "slave/state.hpp"

// `REGISTERING` is used as an enum value, but it's actually defined as a
// constant in the Windows SDK.
#ifdef __WINDOWS__
#undef REGISTERING
#endif // __WINDOWS__

namespace mesos {

// Forward declarations.
class Authorizer;

namespace internal {

namespace slave {

// Some forward declarations.
class StatusUpdateManager;
struct Executor;
struct Framework;
struct HttpConnection;

class Slave : public ProtobufProcess<Slave>
{
public:
  Slave(const std::string& id,
        const Flags& flags,
        mesos::master::detector::MasterDetector* detector,
        Containerizer* containerizer,
        Files* files,
        GarbageCollector* gc,
        StatusUpdateManager* statusUpdateManager,
        mesos::slave::ResourceEstimator* resourceEstimator,
        mesos::slave::QoSController* qosController,
        const Option<Authorizer*>& authorizer);

  virtual ~Slave();

  void shutdown(const process::UPID& from, const std::string& message);

  void registered(
      const process::UPID& from,
      const SlaveID& slaveId,
      const MasterSlaveConnection& connection);

  void reregistered(
      const process::UPID& from,
      const SlaveID& slaveId,
      const std::vector<ReconcileTasksMessage>& reconciliations,
      const MasterSlaveConnection& connection);

  void doReliableRegistration(Duration maxBackoff);

  // Made 'virtual' for Slave mocking.
  virtual void runTask(
      const process::UPID& from,
      const FrameworkInfo& frameworkInfo,
      const FrameworkID& frameworkId,
      const process::UPID& pid,
      const TaskInfo& task);

  void run(
      const FrameworkInfo& frameworkInfo,
      ExecutorInfo executorInfo,
      Option<TaskInfo> task,
      Option<TaskGroupInfo> taskGroup,
      const process::UPID& pid);

  // Made 'virtual' for Slave mocking.
  virtual void _run(
      const process::Future<bool>& future,
      const FrameworkInfo& frameworkInfo,
      const ExecutorInfo& executorInfo,
      const Option<TaskInfo>& task,
      const Option<TaskGroupInfo>& taskGroup);

  // Made 'virtual' for Slave mocking.
  virtual void runTaskGroup(
      const process::UPID& from,
      const FrameworkInfo& frameworkInfo,
      const ExecutorInfo& executorInfo,
      const TaskGroupInfo& taskGroupInfo);

  process::Future<bool> unschedule(const std::string& path);

  // Made 'virtual' for Slave mocking.
  virtual void killTask(
      const process::UPID& from,
      const KillTaskMessage& killTaskMessage);

  // Made 'virtual' for Slave mocking.
  virtual void shutdownExecutor(
      const process::UPID& from,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId);

  void shutdownFramework(
      const process::UPID& from,
      const FrameworkID& frameworkId);

  void schedulerMessage(
      const SlaveID& slaveId,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const std::string& data);

  void updateFramework(
      const UpdateFrameworkMessage& message);

  void checkpointResources(const std::vector<Resource>& checkpointedResources);

  void subscribe(
    HttpConnection http,
    const executor::Call::Subscribe& subscribe,
    Framework* framework,
    Executor* executor);

  void registerExecutor(
      const process::UPID& from,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId);

  // Called when an executor re-registers with a recovering slave.
  // 'tasks' : Unacknowledged tasks (i.e., tasks that the executor
  //           driver never received an ACK for.)
  // 'updates' : Unacknowledged updates.
  void reregisterExecutor(
      const process::UPID& from,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const std::vector<TaskInfo>& tasks,
      const std::vector<StatusUpdate>& updates);

  void _reregisterExecutor(
      const process::Future<Nothing>& future,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const ContainerID& containerId);

  void executorMessage(
      const SlaveID& slaveId,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const std::string& data);

  void ping(const process::UPID& from, bool connected);

  // Handles the status update.
  // NOTE: If 'pid' is a valid UPID an ACK is sent to this pid
  // after the update is successfully handled. If pid == UPID()
  // no ACK is sent. The latter is used by the slave to send
  // status updates it generated (e.g., TASK_LOST). If pid == None()
  // an ACK is sent to the corresponding HTTP based executor.
  // NOTE: StatusUpdate is passed by value because it is modified
  // to ensure source field is set.
  void statusUpdate(StatusUpdate update, const Option<process::UPID>& pid);

  // Called when the slave receives a `StatusUpdate` from an executor
  // and the slave needs to retrieve the container status for the
  // container associated with the executor.
  void _statusUpdate(
      StatusUpdate update,
      const Option<process::UPID>& pid,
      const ExecutorID& executorId,
      const process::Future<ContainerStatus>& future);

  // Continue handling the status update after optionally updating the
  // container's resources.
  void __statusUpdate(
      const Option<process::Future<Nothing>>& future,
      const StatusUpdate& update,
      const Option<process::UPID>& pid,
      const ExecutorID& executorId,
      const ContainerID& containerId,
      bool checkpoint);

  // This is called when the status update manager finishes
  // handling the update. If the handling is successful, an
  // acknowledgment is sent to the executor.
  void ___statusUpdate(
      const process::Future<Nothing>& future,
      const StatusUpdate& update,
      const Option<process::UPID>& pid);

  // This is called by status update manager to forward a status
  // update to the master. Note that the latest state of the task is
  // added to the update before forwarding.
  void forward(StatusUpdate update);

  void statusUpdateAcknowledgement(
      const process::UPID& from,
      const SlaveID& slaveId,
      const FrameworkID& frameworkId,
      const TaskID& taskId,
      const std::string& uuid);

  void _statusUpdateAcknowledgement(
      const process::Future<bool>& future,
      const TaskID& taskId,
      const FrameworkID& frameworkId,
      const UUID& uuid);

  void executorLaunched(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const ContainerID& containerId,
      const process::Future<bool>& future);

  // Made 'virtual' for Slave mocking.
  virtual void executorTerminated(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const process::Future<Option<
          mesos::slave::ContainerTermination>>& termination);

  // NOTE: Pulled these to public to make it visible for testing.
  // TODO(vinod): Make tests friends to this class instead.

  // Garbage collects the directories based on the current disk usage.
  // TODO(vinod): Instead of making this function public, we need to
  // mock both GarbageCollector (and pass it through slave's constructor)
  // and os calls.
  void _checkDiskUsage(const process::Future<double>& usage);

  // Invoked whenever the detector detects a change in masters.
  // Made public for testing purposes.
  void detected(const process::Future<Option<MasterInfo>>& _master);

  enum State
  {
    RECOVERING,   // Slave is doing recovery.
    DISCONNECTED, // Slave is not connected to the master.
    RUNNING,      // Slave has (re-)registered.
    TERMINATING,  // Slave is shutting down.
  } state;

  // Describes information about agent recovery.
  struct RecoveryInfo
  {
    // Flag to indicate if recovery, including reconciling
    // (i.e., reconnect/kill) with executors is finished.
    process::Promise<Nothing> recovered;

    // Flag to indicate that HTTP based executors can
    // subscribe with the agent. We allow them to subscribe
    // after the agent recovers the containerizer.
    bool reconnect = false;
  } recoveryInfo;

  // TODO(benh): Clang requires members to be public in order to take
  // their address which we do in tests (for things like
  // FUTURE_DISPATCH).
// protected:
  virtual void initialize();
  virtual void finalize();
  virtual void exited(const process::UPID& pid);

  void __run(
      const process::Future<std::list<bool>>& future,
      const FrameworkInfo& frameworkInfo,
      const ExecutorInfo& executorInfo,
      const Option<TaskInfo>& task,
      const Option<TaskGroupInfo>& taskGroup);

  // This is called when the resource limits of the container have
  // been updated for the given tasks and task groups. If the update is
  // successful, we flush the given tasks to the executor by sending
  // RunTaskMessages or `LAUNCH_GROUP` events.
  void ___run(
      const process::Future<Nothing>& future,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const ContainerID& containerId,
      const std::list<TaskInfo>& tasks,
      const std::list<TaskGroupInfo>& taskGroups);

  process::Future<Secret> generateSecret(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const ContainerID& containerId);

  // If an executor is launched for a task group, `taskInfo` would not be set.
  void launchExecutor(
      const Option<process::Future<Secret>>& future,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const Option<TaskInfo>& taskInfo);

  void fileAttached(const process::Future<Nothing>& result,
                    const std::string& path);

  Nothing detachFile(const std::string& path);

  // Triggers a re-detection of the master when the slave does
  // not receive a ping.
  void pingTimeout(process::Future<Option<MasterInfo>> future);

  void authenticate();

  // Helper routines to lookup a framework/executor.
  Framework* getFramework(const FrameworkID& frameworkId) const;

  Executor* getExecutor(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId) const;

  Executor* getExecutor(const ContainerID& containerId) const;

  // Returns an ExecutorInfo for a TaskInfo (possibly
  // constructing one if the task has a CommandInfo).
  ExecutorInfo getExecutorInfo(
      const FrameworkInfo& frameworkInfo,
      const TaskInfo& task) const;

  // Shuts down the executor if it did not register yet.
  void registerExecutorTimeout(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const ContainerID& containerId);

  // Cleans up all un-reregistered executors during recovery.
  void reregisterExecutorTimeout();

  // This function returns the max age of executor/slave directories allowed,
  // given a disk usage. This value could be used to tune gc.
  Duration age(double usage);

  // Checks the current disk usage and schedules for gc as necessary.
  void checkDiskUsage();

  // Recovers the slave, status update manager and isolator.
  process::Future<Nothing> recover(const Try<state::State>& state);

  // This is called after 'recover()'. If 'flags.reconnect' is
  // 'reconnect', the slave attempts to reconnect to any old live
  // executors. Otherwise, the slave attempts to shutdown/kill them.
  process::Future<Nothing> _recover();

  // This is a helper to call recover() on the containerizer at the end of
  // recover() and before __recover().
  // TODO(idownes): Remove this when we support defers to objects.
  process::Future<Nothing> _recoverContainerizer(
      const Option<state::SlaveState>& state);

  // This is called when recovery finishes.
  // Made 'virtual' for Slave mocking.
  virtual void __recover(const process::Future<Nothing>& future);

  // Helper to recover a framework from the specified state.
  void recoverFramework(
      const state::FrameworkState& state,
      const hashset<ExecutorID>& executorsToRecheckpoint,
      const hashmap<ExecutorID, hashset<TaskID>>& tasksToRecheckpoint);

  // Removes and garbage collects the executor.
  void removeExecutor(Framework* framework, Executor* executor);

  // Removes and garbage collects the framework.
  // Made 'virtual' for Slave mocking.
  virtual void removeFramework(Framework* framework);

  // Schedules a 'path' for gc based on its modification time.
  process::Future<Nothing> garbageCollect(const std::string& path);

  // Called when the slave was signaled from the specified user.
  void signaled(int signal, int uid);

  // Made 'virtual' for Slave mocking.
  virtual void qosCorrections();

  // Made 'virtual' for Slave mocking.
  virtual void _qosCorrections(
      const process::Future<std::list<
          mesos::slave::QoSCorrection>>& correction);

  // Returns the resource usage information for all executors.
  virtual process::Future<ResourceUsage> usage();

  // Handle the second phase of shutting down an executor for those
  // executors that have not properly shutdown within a timeout.
  void shutdownExecutorTimeout(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId,
      const ContainerID& containerId);

private:
  void _authenticate();
  void authenticationTimeout(process::Future<bool> future);

  // Shut down an executor. This is a two phase process. First, an
  // executor receives a shut down message (shut down phase), then
  // after a configurable timeout the slave actually forces a kill
  // (kill phase, via the isolator) if the executor has not
  // exited.
  void _shutdownExecutor(Framework* framework, Executor* executor);

  // Process creation of persistent volumes (for CREATE) and/or deletion
  // of persistent volumes (for DESTROY) as a part of handling
  // checkpointed resources, and commit the checkpointed resources on
  // successful completion of all the operations.
  Try<Nothing> syncCheckpointedResources(
      const Resources& newCheckpointedResources);

  process::Future<bool> authorizeTask(
      const TaskInfo& task,
      const FrameworkInfo& frameworkInfo);

  process::Future<bool> authorizeLogAccess(
      const Option<process::http::authentication::Principal>& principal);

  process::Future<bool> authorizeSandboxAccess(
      const Option<process::http::authentication::Principal>& principal,
      const FrameworkID& frameworkId,
      const ExecutorID& executorId);

  // Inner class used to namespace HTTP route handlers (see
  // slave/http.cpp for implementations).
  class Http
  {
  public:
    explicit Http(Slave* _slave)
      : slave(_slave),
        statisticsLimiter(new process::RateLimiter(2, Seconds(1))) {}

    // /api/v1
    process::Future<process::http::Response> api(
        const process::http::Request& request,
        const Option<process::http::authentication::Principal>&
            principal) const;

    // /api/v1/executor
    process::Future<process::http::Response> executor(
        const process::http::Request& request,
        const Option<process::http::authentication::Principal>&
            principal) const;

    // /slave/flags
    process::Future<process::http::Response> flags(
        const process::http::Request& request,
        const Option<process::http::authentication::Principal>&
            principal) const;

    // /slave/health
    process::Future<process::http::Response> health(
        const process::http::Request& request) const;

    // /slave/state
    process::Future<process::http::Response> state(
        const process::http::Request& request,
        const Option<process::http::authentication::Principal>&)
            const;

    // /slave/monitor/statistics
    // /slave/monitor/statistics.json
    process::Future<process::http::Response> statistics(
        const process::http::Request& request,
        const Option<process::http::authentication::Principal>&
            principal) const;

    // /slave/containers
    process::Future<process::http::Response> containers(
        const process::http::Request& request,
        const Option<process::http::authentication::Principal>&
            principal) const;

    static std::string API_HELP();
    static std::string EXECUTOR_HELP();
    static std::string FLAGS_HELP();
    static std::string HEALTH_HELP();
    static std::string STATE_HELP();
    static std::string STATISTICS_HELP();
    static std::string CONTAINERS_HELP();

  private:
    JSON::Object _flags() const;

    // Continuation for `/api` endpoint that handles streaming and non-streaming
    // requests. In case of a streaming request, `call` would be the first
    // record and additional records can be read using the `reader`. For
    // non-streaming requests, `reader` would be set to `None()`.
    process::Future<process::http::Response> _api(
        const agent::Call& call,
        Option<process::Owned<recordio::Reader<agent::Call>>>&& reader,
        const RequestMediaTypes& mediaTypes,
        const Option<process::http::authentication::Principal>&
            principal) const;

    // Make continuation for `statistics` `static` as it might
    // execute when the invoking `Http` is already destructed.
    process::http::Response _statistics(
        const ResourceUsage& usage,
        const process::http::Request& request) const;

    // Continuation for `/containers` endpoint
    process::Future<process::http::Response> _containers(
        const process::http::Request& request,
        const Option<process::http::authentication::Principal>&
            principal) const;

    // Helper function to collect containers status and resource statistics.
    process::Future<JSON::Array> __containers(
        Option<process::Owned<ObjectApprover>> approver) const;

    // Helper routines for endpoint authorization.
    Try<std::string> extractEndpoint(const process::http::URL& url) const;

    // Agent API handlers.

    process::Future<process::http::Response> getFlags(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> getHealth(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> getVersion(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> getMetrics(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> getLoggingLevel(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> setLoggingLevel(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> listFiles(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> getContainers(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> readFile(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> getFrameworks(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    mesos::agent::Response::GetFrameworks _getFrameworks(
        const process::Owned<ObjectApprover>& frameworksApprover) const;

    process::Future<process::http::Response> getExecutors(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    mesos::agent::Response::GetExecutors _getExecutors(
        const process::Owned<ObjectApprover>& frameworksApprover,
        const process::Owned<ObjectApprover>& executorsApprover) const;

    process::Future<process::http::Response> getTasks(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    mesos::agent::Response::GetTasks _getTasks(
        const process::Owned<ObjectApprover>& frameworksApprover,
        const process::Owned<ObjectApprover>& tasksApprover,
        const process::Owned<ObjectApprover>& executorsApprover) const;

    process::Future<process::http::Response> getAgent(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> getState(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    mesos::agent::Response::GetState _getState(
        const process::Owned<ObjectApprover>& frameworksApprover,
        const process::Owned<ObjectApprover>& taskApprover,
        const process::Owned<ObjectApprover>& executorsApprover) const;

    process::Future<process::http::Response> launchNestedContainer(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> _launchNestedContainer(
        const ContainerID& containerId,
        const CommandInfo& commandInfo,
        const Option<ContainerInfo>& containerInfo,
        const Option<mesos::slave::ContainerClass>& containerClass,
        ContentType acceptType,
        const process::Owned<ObjectApprover>& approver) const;

    process::Future<process::http::Response> waitNestedContainer(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> killNestedContainer(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> removeNestedContainer(
        const mesos::agent::Call& call,
        ContentType acceptType,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> launchNestedContainerSession(
        const mesos::agent::Call& call,
        const RequestMediaTypes& mediaTypes,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> attachContainerInput(
        const mesos::agent::Call& call,
        process::Owned<recordio::Reader<agent::Call>>&& decoder,
        const RequestMediaTypes& mediaTypes,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> _attachContainerInput(
        const mesos::agent::Call& call,
        process::Owned<recordio::Reader<agent::Call>>&& decoder,
        const RequestMediaTypes& mediaTypes) const;

    process::Future<process::http::Response> attachContainerOutput(
        const mesos::agent::Call& call,
        const RequestMediaTypes& mediaTypes,
        const Option<process::http::authentication::Principal>&
            principal) const;

    process::Future<process::http::Response> _attachContainerOutput(
        const mesos::agent::Call& call,
        const RequestMediaTypes& mediaTypes) const;

    Slave* slave;

    // Used to rate limit the statistics endpoint.
    process::Shared<process::RateLimiter> statisticsLimiter;
  };

  friend struct Framework;
  friend struct Executor;
  friend struct Metrics;

  Slave(const Slave&);              // No copying.
  Slave& operator=(const Slave&); // No assigning.

  // Gauge methods.
  double _frameworks_active()
  {
    return static_cast<double>(frameworks.size());
  }

  double _uptime_secs()
  {
    return (process::Clock::now() - startTime).secs();
  }

  double _registered()
  {
    return master.isSome() ? 1 : 0;
  }

  double _tasks_staging();
  double _tasks_starting();
  double _tasks_running();
  double _tasks_killing();

  double _executors_registering();
  double _executors_running();
  double _executors_terminating();

  double _executor_directory_max_allowed_age_secs();

  void sendExecutorTerminatedStatusUpdate(
      const TaskID& taskId,
      const process::Future<Option<
          mesos::slave::ContainerTermination>>& termination,
      const FrameworkID& frameworkId,
      const Executor* executor);

  // Forwards the current total of oversubscribed resources.
  void forwardOversubscribed();
  void _forwardOversubscribed(
      const process::Future<Resources>& oversubscribable);

  const Flags flags;

  const Http http;

  SlaveInfo info;

  // Resources that are checkpointed by the slave.
  Resources checkpointedResources;

  // The current total resources of the agent, i.e.,
  // `info.resources()` with checkpointed resources applied.
  Resources totalResources;

  Option<process::UPID> master;

  hashmap<FrameworkID, Framework*> frameworks;

  BoundedHashMap<FrameworkID, process::Owned<Framework>> completedFrameworks;

  mesos::master::detector::MasterDetector* detector;

  Containerizer* containerizer;

  Files* files;

  Metrics metrics;

  double _resources_total(const std::string& name);
  double _resources_used(const std::string& name);
  double _resources_percent(const std::string& name);

  double _resources_revocable_total(const std::string& name);
  double _resources_revocable_used(const std::string& name);
  double _resources_revocable_percent(const std::string& name);

  process::Time startTime;

  GarbageCollector* gc;

  StatusUpdateManager* statusUpdateManager;

  // Master detection future.
  process::Future<Option<MasterInfo>> detection;

  // Master's ping timeout value, updated on reregistration.
  Duration masterPingTimeout;

  // Timer for triggering re-detection when no ping is received from
  // the master.
  process::Timer pingTimer;

  // Timer for triggering agent (re)registration after detecting a new master.
  process::Timer agentRegistrationTimer;

  // Root meta directory containing checkpointed data.
  const std::string metaDir;

  // Indicates the number of errors ignored in "--no-strict" recovery mode.
  unsigned int recoveryErrors;

  Option<Credential> credential;

  // Authenticatee name as supplied via flags.
  std::string authenticateeName;

  Authenticatee* authenticatee;

  // Indicates if an authentication attempt is in progress.
  Option<process::Future<bool>> authenticating;

  // Indicates if the authentication is successful.
  bool authenticated;

  // Indicates if a new authentication attempt should be enforced.
  bool reauthenticate;

  // Indicates the number of failed authentication attempts.
  uint64_t failedAuthentications;

  // Maximum age of executor directories. Will be recomputed
  // periodically every flags.disk_watch_interval.
  Duration executorDirectoryMaxAllowedAge;

  mesos::slave::ResourceEstimator* resourceEstimator;

  mesos::slave::QoSController* qosController;

  const Option<Authorizer*> authorizer;

  // The most recent estimate of the total amount of oversubscribed
  // (allocated and oversubscribable) resources.
  Option<Resources> oversubscribedResources;

protected:
  // Made protected for testing purposes.
  mesos::SecretGenerator* secretGenerator;
};

// Represents the streaming HTTP connection to an executor.
struct HttpConnection
{
  HttpConnection(const process::http::Pipe::Writer& _writer,
                 ContentType _contentType)
    : writer(_writer),
      contentType(_contentType),
      encoder(lambda::bind(serialize, contentType, lambda::_1)) {}

  // Converts the message to an Event before sending.
  template <typename Message>
  bool send(const Message& message)
  {
    // We need to evolve the internal 'message' into a
    // 'v1::executor::Event'.
    return writer.write(encoder.encode(evolve(message)));
  }

  bool close()
  {
    return writer.close();
  }

  process::Future<Nothing> closed() const
  {
    return writer.readerClosed();
  }

  process::http::Pipe::Writer writer;
  ContentType contentType;
  ::recordio::Encoder<v1::executor::Event> encoder;
};

std::ostream& operator<<(std::ostream& stream, const Executor& executor);

// Information describing an executor.
struct Executor
{
  Executor(
      Slave* slave,
      const FrameworkID& frameworkId,
      const ExecutorInfo& info,
      const ContainerID& containerId,
      const std::string& directory,
      const Option<std::string>& user,
      bool checkpoint);

  ~Executor();

  Task* addTask(const TaskInfo& task);
  void completeTask(const TaskID& taskId);
  void checkpointExecutor();
  void checkpointTask(const TaskInfo& task);
  void checkpointTask(const Task& task);

  void recoverTask(const state::TaskState& state, bool recheckpointTask);

  Try<Nothing> updateTaskState(const TaskStatus& status);

  // Returns true if there are any queued/launched/terminated tasks.
  bool incompleteTasks();

  // Sends a message to the connected executor.
  template <typename Message>
  void send(const Message& message)
  {
    if (state == REGISTERING || state == TERMINATED) {
      LOG(WARNING) << "Attempting to send message to disconnected"
                   << " executor " << *this << " in state " << state;
    }

    if (http.isSome()) {
      if (!http->send(message)) {
        LOG(WARNING) << "Unable to send event to executor " << *this
                     << ": connection closed";
      }
    } else if (pid.isSome()) {
      slave->send(pid.get(), message);
    } else {
      LOG(WARNING) << "Unable to send event to executor " << *this
                   << ": unknown connection type";
    }
  }

  // Returns true if this is a command executor.
  bool isCommandExecutor() const;

  // Closes the HTTP connection.
  void closeHttpConnection();

  // Returns the task group associated with the task.
  Option<TaskGroupInfo> getQueuedTaskGroup(const TaskID& taskId);

  friend std::ostream& operator<<(
      std::ostream& stream,
      const Executor& executor);

// Undefine NetBios preprocessor macros used by the `State` enum.
#ifdef REGISTERING
#undef REGISTERING
#endif // REGISTERING

#ifdef REGISTERED
#undef REGISTERED
#endif // REGISTERED

  enum State
  {
    REGISTERING,  // Executor is launched but not (re-)registered yet.
    RUNNING,      // Executor has (re-)registered.
    TERMINATING,  // Executor is being shutdown/killed.
    TERMINATED,   // Executor has terminated but there might be pending updates.
  } state;

  // We store the pointer to 'Slave' to get access to its methods
  // variables. One could imagine 'Executor' as being an inner class
  // of the 'Slave' class.
  Slave* slave;

  const ExecutorID id;
  const ExecutorInfo info;

  const FrameworkID frameworkId;

  const ContainerID containerId;

  const std::string directory;

  // The sandbox will be owned by this user and the executor will
  // run as this user. This can be set to None when --switch_user
  // is false or when compiled for Windows.
  const Option<std::string> user;

  const bool checkpoint;

  // An Executor can either be connected via HTTP or by libprocess
  // message passing. The following are the possible states:
  //
  // Agent State    Executor State       http       pid    Executor Type
  // -----------    --------------       ----      ----    -------------
  //  RECOVERING       REGISTERING       None     UPID()         Unknown
  //                   REGISTERING       None       Some      Libprocess
  //                   REGISTERING       None       None            HTTP
  //
  //           *       REGISTERING       None       None   Not known yet
  //           *                 *       None       Some      Libprocess
  //           *                 *       Some       None            HTTP
  Option<HttpConnection> http;
  Option<process::UPID> pid;

  // Currently consumed resources.
  Resources resources;

  // Tasks can be found in one of the following four data structures:
  //
  // TODO(bmahler): Make these private to enforce that the task
  // lifecycle helper functions are not being bypassed, and provide
  // public views into them.

  // Not yet launched tasks. This also includes tasks from `queuedTaskGroups`.
  LinkedHashMap<TaskID, TaskInfo> queuedTasks;

  // Not yet launched task groups. This is needed for correctly sending
  // TASK_KILLED status updates for all tasks in the group if any of the
  // tasks were killed before the executor could register with the agent.
  //
  // TODO(anand): Replace this with `LinkedHashSet` when it is available.
  std::list<TaskGroupInfo> queuedTaskGroups;

  // Running.
  LinkedHashMap<TaskID, Task*> launchedTasks;

  // Terminated but pending updates.
  LinkedHashMap<TaskID, Task*> terminatedTasks;

  // Terminated and updates acked.
  // NOTE: We use a shared pointer for Task because clang doesn't like
  // Boost's implementation of circular_buffer with Task (Boost
  // attempts to do some memset's which are unsafe).
  boost::circular_buffer<std::shared_ptr<Task>> completedTasks;

  // When the slave initiates a destroy of the container, we expect a
  // termination to occur. The 'pendingTermation' indicates why the
  // slave initiated the destruction and will influence the
  // information sent in the status updates for any remaining
  // non-terminal tasks.
  Option<mesos::slave::ContainerTermination> pendingTermination;

private:
  Executor(const Executor&);              // No copying.
  Executor& operator=(const Executor&); // No assigning.

  bool commandExecutor;
};

// Information about a framework.
struct Framework
{
  Framework(
      Slave* slave,
      const Flags& slaveFlags,
      const FrameworkInfo& info,
      const Option<process::UPID>& pid);

  ~Framework();

  Executor* addExecutor(const ExecutorInfo& executorInfo);
  void destroyExecutor(const ExecutorID& executorId);
  Executor* getExecutor(const ExecutorID& executorId) const;
  Executor* getExecutor(const TaskID& taskId) const;

  void recoverExecutor(
      const state::ExecutorState& state,
      bool recheckpointExecutor,
      const hashset<TaskID>& tasksToRecheckpoint);

  void checkpointFramework() const;

  bool removePendingTask(
      const TaskInfo& task,
      const ExecutorInfo& executorInfo);

  const FrameworkID id() const { return info.id(); }

  enum State
  {
    RUNNING,      // First state of a newly created framework.
    TERMINATING,  // Framework is shutting down in the cluster.
  } state;

  // We store the pointer to 'Slave' to get access to its methods and
  // variables. One could imagine 'Framework' being an inner class of
  // the 'Slave' class.
  Slave* slave;

  FrameworkInfo info;

  protobuf::framework::Capabilities capabilities;

  // Frameworks using the scheduler driver will have a 'pid',
  // which allows us to send executor messages directly to the
  // driver. Frameworks using the HTTP API (in 0.24.0) will
  // not have a 'pid', in which case executor messages are
  // sent through the master.
  Option<process::UPID> pid;

  // Executors can be found in one of the following
  // data structures:
  //
  // TODO(bmahler): Make these private to enforce that
  // the executors lifecycle helper functions are not
  // being bypassed, and provide public views into them.

  // Executors with pending tasks.
  hashmap<ExecutorID, hashmap<TaskID, TaskInfo>> pending;

  // Current running executors.
  hashmap<ExecutorID, Executor*> executors;

  boost::circular_buffer<process::Owned<Executor>> completedExecutors;

  bool hasTask(const TaskID& taskId)
  {
    foreachkey (const ExecutorID& executorId, pending) {
      if (pending[executorId].contains(taskId)) {
        return true;
      }
    }

    foreachvalue (Executor* executor, executors) {
      if (executor->queuedTasks.contains(taskId) ||
          executor->launchedTasks.contains(taskId) ||
          executor->terminatedTasks.contains(taskId)) {
        return true;
      }
    }

    return false;
  }

private:
  Framework(const Framework&);              // No copying.
  Framework& operator=(const Framework&); // No assigning.
};

/**
 * Returns a map of environment variables necessary in order to launch
 * an executor.
 *
 * @param executorInfo ExecutorInfo being launched.
 * @param directory Path to the sandbox directory.
 * @param slaveId SlaveID where this executor is being launched.
 * @param slavePid PID of the slave launching the executor.
 * @param checkpoint Whether or not the framework is checkpointing.
 * @param flags Flags used to launch the slave.
 *
 * @return Map of environment variables (name, value).
 */
std::map<std::string, std::string> executorEnvironment(
    const Flags& flags,
    const ExecutorInfo& executorInfo,
    const std::string& directory,
    const SlaveID& slaveId,
    const process::PID<Slave>& slavePid,
    const Option<Secret>& authenticationToken,
    bool checkpoint);

// Returns the command info for default executor.
CommandInfo defaultExecutorCommandInfo(
    const std::string& launcherDir,
    const Option<std::string>& user);

std::ostream& operator<<(std::ostream& stream, Slave::State state);
std::ostream& operator<<(std::ostream& stream, Framework::State state);
std::ostream& operator<<(std::ostream& stream, Executor::State state);

// Needed for logging task/task group.
std::string taskOrTaskGroup(
    const Option<TaskInfo>& task,
    const Option<TaskGroupInfo>& taskGroup);

} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __SLAVE_HPP__


text:
require 'test/unit'
require 'rack/test'
require 'moonrope'

class Test::Unit::TestCase

  private

  def make_rack_env_hash(path, params = {}, other_env = {})
    request = Rack::Test::Session.new(nil)
    request.send :env_for, path, {:params => params, :method => 'POST'}.merge(other_env)
  end

end

#
# A fake base object for models
#
class ModelBase
  def initialize(attributes = {})
    attributes.each do |key, value|
      instance_variable_set("@#{key}", value)
    end
  end
end

class Animal < ModelBase
  attr_accessor :id, :name, :color, :user
end

class User < ModelBase
  attr_accessor :id, :username, :private_code, :admin
  def animals
    @animals ||= []
  end
end

class UserWithUnderscore < User
  class << self
    def name
      s = Struct.new(:underscore, :to_s).new
      s.to_s = 'User'
      s.underscore = 'user'
      s
    end
  end
end

#
# A fake request class for use in some tests
#
class FakeRequest

  def initialize(options = {})
    @options = options
  end

  def params
    @params ||= Moonrope::ParamSet.new(@options[:params] || {})
  end

  def version
    @options[:version]
  end

  def identity
    @options[:identity]
  end

  def action
    nil
  end

end

#
# Require all tests
#
Dir[File.expand_path("../tests/**/*.rb", __FILE__)].each do |filename|
  require filename
end

redpajama_set_name: RedPajamaGithub


text:
#include "httpdlib/header_collection.h"
#include "httpdlib/string_util/string_util.h"
#include <algorithm>
#include <numeric>

namespace httpdlib
{

using namespace string_util;

std::size_t header_collection::size() const {
    return m_headers.size();
}

bool header_collection::contains(const std::string &key) const {
    auto header = m_headers.find(to_lower(key));
    return header != m_headers.end();
}

std::string header_collection::value(const std::string &key) const {
    auto header = m_headers.find(to_lower(key));
    if (header != m_headers.end()) {
        return header->second;
    }

    return "";
}

std::string header_collection::operator[](const std::string &key) {
    return value(key);
}

void header_collection::add(const std::string &key, const std::string &value) {
    m_headers[to_lower(key)] = value;
}

void header_collection::remove(const std::string &key) {
    m_headers.erase(to_lower(key));
}

void header_collection::parse(const std::string &str) {
    auto all_rows = split_all(str, '\n');
    for (const auto &row : all_rows) {
        auto split_at_colon = split_once(row, ':');
        auto key = string_util::to_lower(trim_both(split_at_colon.first));
        auto value = trim_both(split_at_colon.second);
        if (key.size() > 0) {
            m_headers[key] = value;
        }
    }
}

void header_collection::clear() {
    m_headers.clear();
}

const std::string &header_collection::key(header_collection::iterator iter) {
    return iter->first;
}

std::string &header_collection::value(header_collection::iterator iter) {
    return iter->second;
}

const std::string &
header_collection::key(header_collection::const_iterator iter) {
    return iter->first;
}

const std::string &
header_collection::value(header_collection::const_iterator iter) {
    return iter->second;
}

const std::string &header_collection::key(const foreach_t &iter) {
    return iter.first;
}

const std::string &header_collection::value(const foreach_t &iter) {
    return iter.second;
}

header_collection::iterator header_collection::begin() {
    return m_headers.begin();
}

header_collection::iterator header_collection::end() {
    return m_headers.end();
}

header_collection::const_iterator header_collection::begin() const {
    return m_headers.begin();
}

header_collection::const_iterator header_collection::end() const {
    return m_headers.end();
}

header_collection::const_iterator header_collection::cbegin() const {
    return m_headers.cbegin();
}

header_collection::const_iterator header_collection::cend() const {
    return m_headers.cend();
}

std::string header_collection::to_string() const {
    if (m_headers.size() == 0) {
        return "\r\n";
    }
    return std::accumulate(begin(), end(), std::string(""),
                           [&](const std::string &acc, const foreach_t &iter) {
                               return acc + key(iter) + ": " + value(iter) +
                                      "\r\n";
                           });
}

} // namespace httpdlib


text:
from scrapy.selector import Selector
from scrapy.spider import Spider

from familynames.items import FontFamilyItem

class SwissTypefacesSpider(Spider):

    name = 'grillitype'
    allowed_domains = ['grillitype.com']
    start_urls = [
        'http://www.grillitype.com/typefaces'
    ]

    def parse(self, response):
        sel = Selector(response)
        items = sel.xpath('//div[re:test(@class, "view-content")]/ul/li/a/text()')
        r = []
        for item in items.extract():
            ffi = FontFamilyItem()
            ffi['title'] = item
            r.append(ffi)
        return r


text:
// ResourceBase.cs
// Version: 0.01
// Last Modified: 2012/09/16 15:59
// Created: 2012/09/05 6:19
//
// Author: Jing-Jun Wei
// Mail: jingjunwei@outlook.com
// Homepage: http://jingjunwei.github.com/unity3d-trajectory-prototypes/
//
// MIT License
// Copyright (c) 2012 Jing-Jun Wei
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#endregion

#region Usings

using UnityEngine;
using System;
using Object = UnityEngine.Object;

#endregion

namespace KeigunGi.General
{
    /// <summary>
    /// ¥ê¥½©`¥¹év'S¤Î™CÄܤ¬´îÝd¤·¤¿¥Ù©`¥¹¥¯¥é¥¹
    /// </summary>
    public class ResourceBase
    {
        protected virtual T ConvertTo<T>(Object objectOrigin) where T: Object
        {
            var objectConverted = objectOrigin as T;

            bool isConvertFailed = objectConverted == null;
            if(isConvertFailed)
            {
                throw new InvalidCastException();
            }

            return objectConverted;
        }

        /// <summary>
        /// Load a file from any "Resrouces" directories
        /// on the specified path,
        /// then output loaded object with a specified type.
        /// </summary>
        /// <typeparam name="T"> Type of loaded object </typeparam>
        /// <param name="resource"> output loaded object </param>
        /// <returns></returns>
        protected virtual T Load<T>(string path) where T: Object
        {
            Object objectLoaded = Resources.Load(path);

            bool isLoadFailed = objectLoaded == null;
            if(isLoadFailed)
            {
                throw new NullReferenceException();
            }

            var objectConverted = ConvertTo<T>(objectLoaded);
            return objectConverted;
        }
    }
}


text:
Ext.PagingToolbar.prototype.firstText = "Erste Seite";
Ext.PagingToolbar.prototype.prevText = "Vorherige Seite";
Ext.PagingToolbar.prototype.nextText = "Nächste Seite";
Ext.PagingToolbar.prototype.lastText  = "Letzte Seite";

ORYX.I18N.PropertyWindow.dateFormat = "d.m.y";

ORYX.I18N.View.East = "Attribute";
ORYX.I18N.View.West = "Modellierungselemente";

ORYX.I18N.Oryx.pleaseWait = "Der Signavio Process Editor wird geladen. Bitte warten...";
ORYX.I18N.AddDocker.add = "Docker hinzufügen";
ORYX.I18N.AddDocker.del = "Docker löschen";
ORYX.I18N.ERDFSupport.noCanvas = "Das XML Dokument enthält keinen Canvas Knoten.";
ORYX.I18N.ERDFSupport.deprText = "Der Export nach eRDF wird nicht empfohlen, da dieses Format in zukünftigen Versionen des Signavio Process Editors nicht mehr unterstützt wird. Verwenden Sie stattdessen den Export nach JSON, falls möglich. Wollen Sie dennoch das Model nach eRDF exportieren?";
ORYX.I18N.Save.unsavedData = "Das Diagramm enthält nicht gespeicherte Daten. Sind Sie sicher, dass Sie den Editor schließen möchten?";
ORYX.I18N.Save.pleaseWait = "Bitte warten Sie, während
das Diagramm gespeichert wird.";
ORYX.I18N.File.info = "Info";
ORYX.I18N.File.infoDesc = "Info";
ORYX.I18N.PropertyWindow.name = "Attribut";
ORYX.I18N.View.zoomStandard = "Zoom: Originalgröße";
ORYX.I18N.View.zoomStandardDesc = "Zoom: Originalgröße";
ORYX.I18N.View.zoomFitToModel = "Zoom: Modellgröße";
ORYX.I18N.View.zoomFitToModelDesc = "Zoom: Modellgröße";
ORYX.I18N.ShapeRepository.title = "Modellierungselemente";
ORYX.I18N.Save.dialogLabelComment = "Änderungs-\nkommentar";

ORYX.I18N.Save.saveAs = "Kopie speichern...";
ORYX.I18N.Save.saveAsDesc = "Kopie speichern...";
ORYX.I18N.Save.saveAsTitle = "Kopie speichern...";
ORYX.I18N.Save.savedAs = "Kopie gespeichert";
ORYX.I18N.Save.savedDescription = "Das kopierte Diagramm ist unter folgendem Link gespeichert";
ORYX.I18N.Save.notAuthorized = "Sie sind derzeit nicht angemeldet. Bitte melden Sie sich in einem neuen Fenstern an, damit Sie diese Model speichern können."
ORYX.I18N.Save.transAborted = "Die Anfrage zum Speichern Ihres Diagramms hat zu lange gedauert. Bitte benutzen Sie eine schnellere Internetverbindung. Wenn Sie eine kabellose Internetverbindung benutzen, dann überprüfen Sie bitte die Signalstärke.";
ORYX.I18N.Save.noRights = "Sie haben nicht die benötigten Rechte, um das Diagramm abzuspeichern. Bitte überprüfen Sie im Signavio Explorer, ob Sie noch die benötigten Rechte im Zielordner besitzen.";
ORYX.I18N.Save.comFailed = "Die Kommunikation mit dem Signavio Server ist fehlgeschlagen. Bitte überprüfen Sie Ihre Internetverbindung. Wenn das Problem weiterhin besteht, wenden Sie sich bitte an den Signavio Support über das Briefumschlagssymbol in der Toolbar.";
ORYX.I18N.Save.failed = "Beim Speichern Ihres Diagramms ist ein Problem aufgetreten. Bitte versuchen Sie es erneut. Wenn das Problem weiterhin besteht, wenden Sie sich bitte an den Signavio Support über das Briefumschlagssymbol in der Toolbar.";
ORYX.I18N.Save.exception = "Beim Speichern Ihres Diagramms sind einige Probleme aufgetreten. Bitte versuchen Sie es erneut. Wenn das Problem weiterhin besteht, wenden Sie sich bitte an den Signavio Support über das Briefumschlagssymbol in der Toolbar.";
ORYX.I18N.Save.retrieveData = "Bitte warten, Daten werden geladen";

/** New Language Properties: 10.6.09*/
if(!ORYX.I18N.ShapeMenuPlugin) ORYX.I18N.ShapeMenuPlugin = {};
ORYX.I18N.ShapeMenuPlugin.morphMsg = "Umwandeln";
ORYX.I18N.ShapeMenuPlugin.morphWarningTitleMsg = "Umwandeln";
ORYX.I18N.ShapeMenuPlugin.morphWarningMsg = "Einige Kindelemente können nicht im neuen Element enthalten sein.
Möchten Sie dennoch das Element umwandeln?";

if (!Signavio) { var Signavio = {}; }
if (!Signavio.I18N) { Signavio.I18N = {} }
if (!Signavio.I18N.Editor) { Signavio.I18N.Editor = {} }

if (!Signavio.I18N.Editor.Linking) { Signavio.I18N.Editor.Linking = {} }
Signavio.I18N.Editor.Linking.CreateDiagram = "Neues Diagramm erstellen:";
Signavio.I18N.Editor.Linking.UseDiagram = "Vorhandenes Diagramm verwenden";
Signavio.I18N.Editor.Linking.UseLink = "Web-Link verwenden";
Signavio.I18N.Editor.Linking.CreateTitle = "Verlinkung setzen";
Signavio.I18N.Editor.Linking.Close = "Schließen";
Signavio.I18N.Editor.Linking.Cancel = "Abbrechen";
Signavio.I18N.Editor.Linking.UseName = "Diagrammnamen übernehmen";
Signavio.I18N.Editor.Linking.UseNameHint = "Ersetzt den Bezeichner des aktuellen Elements ({type}) durch den Namen des zu verlinkenden Diagramms.";
Signavio.I18N.Editor.Linking.AlertSelectModel = "Bitte selektieren Sie ein Diagramm.";
Signavio.I18N.Editor.Linking.ButtonLink = "Verlinkung setzen";
Signavio.I18N.Editor.Linking.LinkNoAccess = "Sie haben keine Berechtigung für das Diagramm.";
Signavio.I18N.Editor.Linking.LinkUnavailable = "Das Diagramm ist nicht verfügbar.";
Signavio.I18N.Editor.Linking.RemoveLink = "Link löschen";
Signavio.I18N.Editor.Linking.EditLink = "Link ändern";
Signavio.I18N.Editor.Linking.OpenLink = "Öffnen";
Signavio.I18N.Editor.Linking.BrokenLink = "Der Link ist nicht verfügbar!";
Signavio.I18N.Editor.Linking.PreviewTitle = "Vorschau";

if(!ORYX.I18N.PropertyWindow) ORYX.I18N.PropertyWindow = {};
ORYX.I18N.PropertyWindow.oftenUsed = "Hauptattribute";
ORYX.I18N.PropertyWindow.moreProps = "Weitere Attribute";
ORYX.I18N.PropertyWindow.characteristicNr = "Kennzahlen";
ORYX.I18N.PropertyWindow.meta = "Eigene Attribute";

if(!ORYX.I18N.PropertyWindow.Category){ORYX.I18N.PropertyWindow.Category = {}}
ORYX.I18N.PropertyWindow.Category.popular = "Hauptattribute";
ORYX.I18N.PropertyWindow.Category.characteristicnr = "Kennzahlen";
ORYX.I18N.PropertyWindow.Category.others = "Weitere Attribute";
ORYX.I18N.PropertyWindow.Category.meta = "Eigene Attribute";

if(!ORYX.I18N.PropertyWindow.ListView) ORYX.I18N.PropertyWindow.ListView = {};
ORYX.I18N.PropertyWindow.ListView.title = "Attribut: ";
ORYX.I18N.PropertyWindow.ListView.dataViewLabel = "Bereits vorhandene Einträge";
ORYX.I18N.PropertyWindow.ListView.dataViewEmptyText = "Es sind noch keine Einträge vorhanden.";
ORYX.I18N.PropertyWindow.ListView.addEntryLabel = "Neuen Eintrag hinzufügen";
ORYX.I18N.PropertyWindow.ListView.buttonAdd = "Hinzufügen";
ORYX.I18N.PropertyWindow.ListView.save = "Speichern";
ORYX.I18N.PropertyWindow.ListView.cancel = "Abbrachen";

if(!Signavio.I18N.Buttons) Signavio.I18N.Buttons = {};
Signavio.I18N.Buttons.save		= "Speichern";
Signavio.I18N.Buttons.cancel 	= "Abbrechen";
Signavio.I18N.Buttons.remove	= "Entfernen";

if(!Signavio.I18N.btn) {Signavio.I18N.btn = {};}
Signavio.I18N.btn.btnEdit = "Editieren";
Signavio.I18N.btn.btnRemove = "Löschen";
Signavio.I18N.btn.moveUp = "Nach oben";
Signavio.I18N.btn.moveDown = "Nach unten";

if(!Signavio.I18N.field) {Signavio.I18N.field = {};}
Signavio.I18N.field.Url = "URL";
Signavio.I18N.field.UrlLabel = "Label";


text:
require "dyson_sphere/engine"

module DysonSphere
end


text:
use cassandra::consistency::Consistency;
use cassandra::util::Protected;
use cassandra::write_type::WriteType;

use cassandra_sys::CASS_OK;
use cassandra_sys::CassError as _CassError;

use cassandra_sys::CassErrorResult as _CassErrorResult;
use cassandra_sys::cass_error_desc;
use cassandra_sys::cass_error_num_arg_types;
use cassandra_sys::cass_error_result_arg_type;
use cassandra_sys::cass_error_result_code;
use cassandra_sys::cass_error_result_consistency;
use cassandra_sys::cass_error_result_data_present;
use cassandra_sys::cass_error_result_free;
use cassandra_sys::cass_error_result_function;
use cassandra_sys::cass_error_result_keyspace;
use cassandra_sys::cass_error_result_num_failures;
use cassandra_sys::cass_error_result_responses_received;
use cassandra_sys::cass_error_result_responses_required;
use cassandra_sys::cass_error_result_table;
use cassandra_sys::cass_error_result_write_type;
use errors::*;
use errors::*;
use std::{fmt, mem, slice, str};
use std::error::Error as IError;
// use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt::{Debug, Display, Formatter};
use std::os::raw::c_char;

// Simple and robust error handling with error-chain!
// Use this as a template for new projects.

// #[macro_export]
// macro_rules! err_wrap {
//    ( $s:expr,$x:expr ) => {match $x {
//                CASS_OK => Ok($s),
//                err => Err(Error::from(err.into()))
//            }
//    }
// }

error_chain! {
       // Automatic conversions between this error chain and other
    // error types not defined by the `error_chain!`. These will be
    // wrapped in a new error with, in this case, the
    // `ErrorKind::Temp` variant. The description and cause will
    // forward to the description and cause of the original error.
    //
    // Optionally, some attributes can be added to a variant.
    //
    // This section can be empty.
    foreign_links {
        Fmt(::std::fmt::Error);
        Io(::std::io::Error) #[cfg(unix)];
        Null(::std::ffi::NulError);
        Cass(_CassError);
        Utf8(::std::str::Utf8Error);
    }

    // Define additional `ErrorKind` variants. The syntax here is
    // the same as `quick_error!`, but the `from()` and `cause()`
    // syntax is not supported.
    errors {
        CassError(t: String) {
            //description("invalid toolchain name")
            //display("invalid toolchain name: '{}'", t)
        }
    }
}

/// An error returned by Cassandra or the driver
pub struct CassError(_CassError);

// ///An error generated by the C++ driver
// pub struct CassLibError {
//    err: _CassError,
//    msg: String,
// }

// impl From<_CassError> for CassError {
//    fn from(err:_CassError) -> CassError {
//        CassError
//    }
// }

// ///An error signaled by the server and sent to the client over CQL transport
// pub struct CassServerError(_CassError);
// ///An error signaled by the client-linked SSL library
// pub struct CassSslError(_CassError);

impl ::std::error::Error for CassError {
    fn description(&self) -> &str {
        unimplemented!()
        // self.desc()
        // let c_buf: *const i8 = self.desc();
        // let buf: &[u8] = unsafe { CStr::from_ptr(c_buf).to_bytes() };
        // from_utf8(buf).unwrap()
    }
}

// impl From<AddrParseError> for CassError {
//    fn from(err: AddrParseError) -> CassError {
//        CassError::Rust(CassRustError::BadAddress(err))
//    }
// }

// impl From<NulError> for CassError {
//    fn from(err: NulError) -> CassError {
//        CassError::Rust(CassRustError::NulInString(err))
//    }
// }

impl Display for CassError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
        //        let c_buf: *const i8 = self.desc();
        //        let buf: &[u8] = unsafe { CStr::from_ptr(c_buf).to_bytes() };
        //        match str::from_utf8(buf) {
        //            Ok(str_slice) => write!(f, "{}", str_slice),
        //            Err(err) => panic!("unreachable? {:?}", err),
        //        }
    }
}
//
impl Debug for CassError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
        //        let c_buf: *const i8 = self.desc();
        //        let buf: &[u8] = unsafe { CStr::from_ptr(c_buf).to_bytes() };
        //        match str::from_utf8(buf) {
        //            Ok(str_slice) => write!(f, "{:?}", str_slice),
        //            Err(err) => panic!("unreachable? {:?}", err),
        //        }
    }
}

// impl From<NulError> for CassError {
//    fn from(err: NulError) -> CassError {
//        CliError::Io(err)
//    }
// }

// impl CassError {
//   /// Takes an upstream error and wraps it into the appropriate CassError
//    pub fn wrap<T>(self, wrappee: T) -> Result<T> {
//        match self.0 {
//            CASS_OK => Ok(wrappee),
//            err => Err(Error::from(err.into())),
//        }
//    }
//    //
// }
/// An error result of a request
#[derive(Debug)]
pub struct CassErrorResult(*const _CassErrorResult);

impl Protected<*const _CassErrorResult> for CassErrorResult {
    fn inner(&self) -> *const _CassErrorResult { self.0 }
    fn build(inner: *const _CassErrorResult) -> Self { CassErrorResult(inner) }
}

// impl CassErrorResult {
//    /// Gets error code for the error result. This error code will always
//    /// have an server error source.
//    pub fn result_code(&self) -> u32 { unsafe { cass_error_result_code(self.0) as u32 } }
//
//    /// Gets consistency that triggered the error result of the
//    /// following types:
//    ///
//    ///

//    ///
CASS_ERROR_SERVER_READ_TIMEOUT

//    ///
CASS_ERROR_SERVER_WRITE_TIMEOUT

//    ///
CASS_ERROR_SERVER_READ_FAILURE

//    ///
CASS_ERROR_SERVER_WRITE_FAILURE

//    ///
CASS_ERROR_SERVER_UNAVAILABLE

//    ///

//    pub fn result_consistency(&self) -> Consistency {
//        unsafe { Consistency::build(cass_error_result_consistency(self.0)) }
//    }
//
//    /// Gets the actual number of received responses, received acknowledgments
//    /// or alive nodes for following error result types, respectively:
//    ///
//    ///

//    ///
CASS_ERROR_SERVER_READ_TIMEOUT

//    ///
CASS_ERROR_SERVER_WRITE_TIMEOUT

//    ///
CASS_ERROR_SERVER_READ_FAILURE

//    ///
CASS_ERROR_SERVER_WRITE_FAILURE

//    ///
CASS_ERROR_SERVER_UNAVAILABLE

//    ///

//    pub fn responses_received(&self) -> i32 { unsafe { cass_error_result_responses_received(self.0) } }
//
//    /// Gets required responses, required acknowledgments or required alive nodes
//    /// needed to successfully complete the request for following error result types,
//    /// respectively:
//    ///
//    ///

//    ///
CASS_ERROR_SERVER_READ_TIMEOUT

//    ///
CASS_ERROR_SERVER_WRITE_TIMEOUT

//    ///
CASS_ERROR_SERVER_READ_FAILURE

//    ///
CASS_ERROR_SERVER_WRITE_FAILURE

//    ///
CASS_ERROR_SERVER_UNAVAILABLE

//    ///

//    pub fn responses_required(&self) -> i32 { unsafe { cass_error_result_responses_required(self.0) } }
//
//    /// Gets the number of nodes that experienced failures for the following error types:
//    ///
//    ///

//    ///
CASS_ERROR_SERVER_READ_FAILURE

//    ///
CASS_ERROR_SERVER_WRITE_FAILURE

//    ///

//    pub fn num_failures(&self) -> i32 { unsafe { cass_error_result_num_failures(self.0) } }
//
//    /// Determines whether the actual data was present in the responses from the
//    /// replicas for the following error result types:
//    ///
//    ///

//    ///
CASS_ERROR_SERVER_READ_TIMEOUT

//    ///
CASS_ERROR_SERVER_READ_FAILURE

//    ///

//    pub fn data_present(&self) -> bool { unsafe { cass_error_result_data_present(self.0) as i32 > 0 } }
//
//
//    /// Gets the write type of a request for the following error result types:
//    ///
//    ///

//    ///
CASS_ERROR_SERVER_WRITE_TIMEOUT

//    ///
CASS_ERROR_SERVER_WRITE_FAILURE

//    ///

//    pub fn write_type(&self) -> WriteType { unsafe { WriteType(cass_error_result_write_type(self.0)) } }
//
//    /// Gets the affected keyspace for the following error result types:
//    ///
//    ///

//    ///
CASS_ERROR_SERVER_ALREADY_EXISTS

//    ///
CASS_ERROR_SERVER_FUNCTION_FAILURE

//    ///

//    #[allow(cast_possible_truncation)]
//    pub fn keyspace(&self) -> String {
//        unsafe {
//            let mut name = mem::zeroed();
//            let mut length = mem::zeroed();
//            match cass_error_result_keyspace(self.0, &mut name, &mut length) {
//                CASS_OK => {
//                    let slice = slice::from_raw_parts(name as *const u8, length as usize);
//                    str::from_utf8(slice).expect("must be utf8").to_owned()
//                }
//                err => panic!("impossible: {:?}", err),
//            }
//        }
//    }
//
//    /// Gets the affected table for the already exists error
//    /// (CASS_ERROR_SERVER_ALREADY_EXISTS) result type.
//    #[allow(cast_possible_truncation)]
//    pub fn table(&self) -> String {
//        unsafe {
//            let mut name = mem::zeroed();
//            let mut length = mem::zeroed();
//            match cass_error_result_table(self.0, &mut name, &mut length) {
//                CASS_OK => {
//                    let slice = slice::from_raw_parts(name as *const u8, length as usize);
//                    str::from_utf8(slice).expect("must be utf8").to_owned()
//                }
//                err => panic!("impossible: {:?}", err),
//            }
//        }
//    }
//
//    /// Gets the affected function for the function failure error
//    /// (CASS_ERROR_SERVER_FUNCTION_FAILURE) result type.
//    #[allow(cast_possible_truncation)]
//    pub fn function(&self) -> String {
//        unsafe {
//            let mut name = mem::zeroed();
//            let mut length = mem::zeroed();
//            match cass_error_result_function(self.0, &mut name, &mut length) {
//                CASS_OK => {
//                    let slice = slice::from_raw_parts(name as *const u8, length as usize);
//                    str::from_utf8(slice).expect("must be utf8").to_owned()
//                }
//                err => panic!("impossible: {:?}", err),
//            }
//        }
//    }
//
//    /// Gets the number of argument types for the function failure error
//    /// (CASS_ERROR_SERVER_FUNCTION_FAILURE) result type.
//    pub fn num_arg_types(error_result: CassErrorResult) -> usize { unsafe { cass_error_num_arg_types(error_result.0) } }
//
//    /// Gets the argument type at the specified index for the function failure
//    /// error (CASS_ERROR_SERVER_FUNCTION_FAILURE) result type.
//    pub fn arg_type(&self, index: usize, arg_type: &str) -> u32 {
//        unsafe {
//            let cstr = CString::new(arg_type).expect("must be utf8");
//            cass_error_result_arg_type(self.0,
//                                       index,
//                                       &mut cstr.as_ptr(),
//                                       &mut (cstr.to_bytes().len())) as u32
//        }
//    }
// }
// impl Drop for CassErrorResult {
//    fn drop(&mut self) { unsafe { cass_error_result_free(self.0) } }
// }
//
// impl CassError {
//    pub fn new(err:_CassError) -> Self {
//        CassError(err)
//    }
//    fn result_from<T>(self, t:T) -> Result<T> {
//          match self.0 {
//                CASS_OK => Ok(t),
//                err => Err(Error::from(err.into()))
//            }
//    }

fn pointer_to_string<'a>(c_buf: *const c_char) -> &'a str {
    let buf: &[u8] = unsafe { CStr::from_ptr(c_buf).to_bytes() };
    str::from_utf8(buf).unwrap()
}
//    /// Gets the textual description for this error
//    pub fn desc(&self) -> &str {
//        {
//            CassError::pointer_to_string(unsafe { cass_error_desc(self.0) })
//            //            match *self {
//            //                CassError::Lib(ref err) => CassError::pointer_to_string(cass_error_desc(err.err)),
//            //                CassError::Ssl(ref err) => CassError::pointer_to_string(cass_error_desc(err.0)),
//            //                CassError::Server(ref err) => CassError::pointer_to_string(cass_error_desc(err.0)),
//            //                CassError::Rust(ref err) => {
//            //                    match err {
//            //          &CassRustError::NulInString(_) => "Tried to create a CString with a nul in the middle",
//            //                        /// /FIXME how do i return a slice created from self?
//            //                        &CassRustError::BadAddress(_) => "Tried to parse an invalid ip address",
//            //                    }
//            //                }
//            //            }
//        }
//    }
// }


text:
package com.mongodb.internal.connection;

import com.mongodb.connection.BufferProvider;
import org.bson.ByteBuf;
import org.bson.ByteBufNIO;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;

/**
 * Power-of-two buffer pool implementation.
 *
 *
This class should not be considered a part of the public API.

 */
public class PowerOfTwoBufferPool implements BufferProvider {

    private final Map<Integer, ConcurrentPool<ByteBuffer>> powerOfTwoToPoolMap = new HashMap<Integer, ConcurrentPool<ByteBuffer>>();

    /**
     * Construct an instance with a highest power of two of 24.
     */
    public PowerOfTwoBufferPool() {
        this(24);
    }

    /**
     * Construct an instance.
     *
     * @param highestPowerOfTwo the highest power of two buffer size that will be pooled
     */
    public PowerOfTwoBufferPool(final int highestPowerOfTwo) {
        int powerOfTwo = 1;
        for (int i = 0; i <= highestPowerOfTwo; i++) {
            final int size = powerOfTwo;
            powerOfTwoToPoolMap.put(i, new ConcurrentPool<ByteBuffer>(Integer.MAX_VALUE,
                                                                         new ConcurrentPool.ItemFactory<ByteBuffer>() {
                                                                             @Override
                                                                             public ByteBuffer create(final boolean initialize) {
                                                                                return createNew(size);
                                                                             }

                                                                             @Override
                                                                             public void close(final ByteBuffer byteBuffer) {
                                                                             }

                                                                             @Override
                                                                             public boolean shouldPrune(final ByteBuffer byteBuffer) {
                                                                                return false;
                                                                             }
                                                                         }));
            powerOfTwo = powerOfTwo << 1;
        }
    }

    @Override
    public ByteBuf getBuffer(final int size) {
        ConcurrentPool<ByteBuffer> pool = powerOfTwoToPoolMap.get(log2(roundUpToNextHighestPowerOfTwo(size)));
        ByteBuffer byteBuffer = (pool == null) ? createNew(size) : pool.get();

        byteBuffer.clear();
        byteBuffer.limit(size);
        return new PooledByteBufNIO(byteBuffer);
    }

    private ByteBuffer createNew(final int size) {
        ByteBuffer buf = ByteBuffer.allocate(size);  // TODO: configure whether this uses allocateDirect or allocate
        buf.order(ByteOrder.LITTLE_ENDIAN);
        return buf;
    }

    private void release(final ByteBuffer buffer) {
        ConcurrentPool<ByteBuffer> pool = powerOfTwoToPoolMap.get(log2(roundUpToNextHighestPowerOfTwo(buffer.capacity())));
        if (pool != null) {
            pool.release(buffer);
        }
    }

    static int log2(final int powerOfTwo) {
        return 31 - Integer.numberOfLeadingZeros(powerOfTwo);
    }

    static int roundUpToNextHighestPowerOfTwo(final int size) {
        int v = size;
        v--;
        v |= v >> 1;
        v |= v >> 2;
        v |= v >> 4;
        v |= v >> 8;
        v |= v >> 16;
        v++;
        return v;
    }

    private class PooledByteBufNIO extends ByteBufNIO {

        PooledByteBufNIO(final ByteBuffer buf) {
            super(buf);
        }

        @Override
        public void release() {
            ByteBuffer wrapped = asNIO();
            super.release();
            if (getReferenceCount() == 0) {
                PowerOfTwoBufferPool.this.release(wrapped);
            }
        }
    }
}


text:
require 'rails_helper'

describe "assets/_equipment_configuration.html.haml", :type => :view do
  it 'info' do
    test_asset = create(:equipment_asset, :manufacturer => Manufacturer.first, :manufacturer_model => 'silverado', :manufacture_year => 2005, :serial_number => 'ABCDE12345')
    assign(:asset, test_asset)
    render

    expect(rendered).to have_content(test_asset.description)
    expect(rendered).to have_content('1 piece')
    expect(rendered).to have_content(test_asset.manufacturer.to_s)
    expect(rendered).to have_content('silverado')
    expect(rendered).to have_content('2005')
    expect(rendered).to have_content('ABCDE12345')
  end
end


text:
from __future__ import absolute_import

import unittest

import numpy

from fermilib.ops import FermionOperator
from fermilib.transforms import jordan_wigner
from fermilib.utils import count_qubits, eigenspectrum, Grid
from fermilib.utils._jellium import (
    dual_basis_jellium_model,
    dual_basis_kinetic,
    dual_basis_potential,
    jellium_model,
    jordan_wigner_dual_basis_jellium,
    momentum_vector,
    orbital_id,
    OrbitalSpecificationError,
    plane_wave_kinetic,
    plane_wave_potential,
    position_vector,
)

from projectq.ops import QubitOperator

class JelliumTest(unittest.TestCase):

    def test_orbital_id(self):

        # Test in 1D with spin.
        grid = Grid(dimensions=1, length=5, scale=1.0)
        input_coords = [0, 1, 2, 3, 4]
        tensor_factors_up = [1, 3, 5, 7, 9]
        tensor_factors_down = [0, 2, 4, 6, 8]

        test_output_up = [orbital_id(grid, i, 1) for i in input_coords]
        test_output_down = [orbital_id(grid, i, 0) for i in input_coords]

        self.assertEqual(test_output_up, tensor_factors_up)
        self.assertEqual(test_output_down, tensor_factors_down)

        with self.assertRaises(OrbitalSpecificationError):
            orbital_id(grid, 6, 1)

        # Test in 2D without spin.
        grid = Grid(dimensions=2, length=3, scale=1.0)
        input_coords = [(0, 0), (0, 1), (1, 2)]
        tensor_factors = [0, 3, 7]
        test_output = [orbital_id(grid, i) for i in input_coords]
        self.assertEqual(test_output, tensor_factors)

    def test_position_vector(self):

        # Test in 1D.
        grid = Grid(dimensions=1, length=4, scale=4.)
        test_output = [position_vector(i, grid)
                       for i in range(grid.length)]
        correct_output = [-2, -1, 0, 1]
        self.assertEqual(correct_output, test_output)

        grid = Grid(dimensions=1, length=11, scale=2. * numpy.pi)
        for i in range(grid.length):
            self.assertAlmostEqual(
                -position_vector(i, grid),
                position_vector(grid.length - i - 1, grid))

        # Test in 2D.
        grid = Grid(dimensions=2, length=3, scale=3.)
        test_input = []
        test_output = []
        for i in range(3):
            for j in range(3):
                test_input += [(i, j)]
                test_output += [position_vector((i, j), grid)]
        correct_output = numpy.array([[-1., -1.], [-1., 0.], [-1., 1.],
                                      [0., -1.], [0., 0.], [0., 1.],
                                      [1., -1.], [1., 0.], [1., 1.]])
        self.assertAlmostEqual(0., numpy.amax(test_output - correct_output))

    def test_momentum_vector(self):
        grid = Grid(dimensions=1, length=3, scale=2. * numpy.pi)
        test_output = [momentum_vector(i, grid)
                       for i in range(grid.length)]
        correct_output = [-1., 0, 1.]
        self.assertEqual(correct_output, test_output)

        grid = Grid(dimensions=1, length=11, scale=2. * numpy.pi)
        for i in range(grid.length):
            self.assertAlmostEqual(
                -momentum_vector(i, grid),
                momentum_vector(grid.length - i - 1, grid))

        # Test in 2D.
        grid = Grid(dimensions=2, length=3, scale=2. * numpy.pi)
        test_input = []
        test_output = []
        for i in range(3):
            for j in range(3):
                test_input += [(i, j)]
                test_output += [momentum_vector((i, j), grid)]
        correct_output = numpy.array([[-1, -1], [-1, 0], [-1, 1],
                                      [0, -1], [0, 0], [0, 1],
                                      [1, -1], [1, 0], [1, 1]])
        self.assertAlmostEqual(0., numpy.amax(test_output - correct_output))

    def test_kinetic_integration(self):

        # Compute kinetic energy operator in both momentum and position space.
        grid = Grid(dimensions=2, length=2, scale=3.)
        spinless = False
        momentum_kinetic = plane_wave_kinetic(grid, spinless)
        position_kinetic = dual_basis_kinetic(grid, spinless)

        # Diagonalize and confirm the same energy.
        jw_momentum = jordan_wigner(momentum_kinetic)
        jw_position = jordan_wigner(position_kinetic)
        momentum_spectrum = eigenspectrum(jw_momentum)
        position_spectrum = eigenspectrum(jw_position)

        # Confirm spectra are the same.
        difference = numpy.amax(
            numpy.absolute(momentum_spectrum - position_spectrum))
        self.assertAlmostEqual(difference, 0.)

    def test_potential_integration(self):

        # Compute potential energy operator in momentum and position space.
        grid = Grid(dimensions=2, length=3, scale=2.)
        spinless = 1
        momentum_potential = plane_wave_potential(grid, spinless)
        position_potential = dual_basis_potential(grid, spinless)

        # Diagonalize and confirm the same energy.
        jw_momentum = jordan_wigner(momentum_potential)
        jw_position = jordan_wigner(position_potential)
        momentum_spectrum = eigenspectrum(jw_momentum)
        position_spectrum = eigenspectrum(jw_position)

        # Confirm spectra are the same.
        difference = numpy.amax(
            numpy.absolute(momentum_spectrum - position_spectrum))
        self.assertAlmostEqual(difference, 0.)

    def test_model_integration(self):

        # Compute Hamiltonian in both momentum and position space.
        grid = Grid(dimensions=2, length=3, scale=1.0)
        spinless = True
        momentum_hamiltonian = jellium_model(grid, spinless, True)
        position_hamiltonian = jellium_model(grid, spinless, False)

        # Diagonalize and confirm the same energy.
        jw_momentum = jordan_wigner(momentum_hamiltonian)
        jw_position = jordan_wigner(position_hamiltonian)
        momentum_spectrum = eigenspectrum(jw_momentum)
        position_spectrum = eigenspectrum(jw_position)

        # Confirm spectra are the same.
        difference = numpy.amax(
            numpy.absolute(momentum_spectrum - position_spectrum))
        self.assertAlmostEqual(difference, 0.)

    def test_model_integration_with_constant(self):
        # Compute Hamiltonian in both momentum and position space.
        length_scale = 0.7

        grid = Grid(dimensions=2, length=3, scale=length_scale)
        spinless = True

        # Include the Madelung constant in the momentum but not the position
        # Hamiltonian.
        momentum_hamiltonian = jellium_model(grid, spinless, True,
                                             include_constant=True)
        position_hamiltonian = jellium_model(grid, spinless, False)

        # Diagonalize and confirm the same energy.
        jw_momentum = jordan_wigner(momentum_hamiltonian)
        jw_position = jordan_wigner(position_hamiltonian)
        momentum_spectrum = eigenspectrum(jw_momentum)
        position_spectrum = eigenspectrum(jw_position)

        # Confirm momentum spectrum is shifted 2.8372 / length_scale higher.
        max_difference = numpy.amax(momentum_spectrum - position_spectrum)
        min_difference = numpy.amax(momentum_spectrum - position_spectrum)
        self.assertAlmostEqual(max_difference, 2.8372 / length_scale)
        self.assertAlmostEqual(min_difference, 2.8372 / length_scale)

    def test_coefficients(self):

        # Test that the coefficients post-JW transform are as claimed in paper.
        grid = Grid(dimensions=2, length=3, scale=2.)
        spinless = 1
        n_orbitals = grid.num_points()
        n_qubits = (2 ** (1 - spinless)) * n_orbitals
        volume = grid.volume_scale()

        # Kinetic operator.
        kinetic = dual_basis_kinetic(grid, spinless)
        qubit_kinetic = jordan_wigner(kinetic)

        # Potential operator.
        potential = dual_basis_potential(grid, spinless)
        qubit_potential = jordan_wigner(potential)

        # Check identity.
        identity = tuple()
        kinetic_coefficient = qubit_kinetic.terms[identity]
        potential_coefficient = qubit_potential.terms[identity]

        paper_kinetic_coefficient = 0.
        paper_potential_coefficient = 0.
        for indices in grid.all_points_indices():
            momenta = momentum_vector(indices, grid)
            paper_kinetic_coefficient += float(
                n_qubits) * momenta.dot(momenta) / float(4. * n_orbitals)

            if momenta.any():
                potential_contribution = -numpy.pi * float(n_qubits) / float(
                    2. * momenta.dot(momenta) * volume)
                paper_potential_coefficient += potential_contribution

        self.assertAlmostEqual(
            kinetic_coefficient, paper_kinetic_coefficient)
        self.assertAlmostEqual(
            potential_coefficient, paper_potential_coefficient)

        # Check Zp.
        for p in range(n_qubits):
            zp = ((p, 'Z'),)
            kinetic_coefficient = qubit_kinetic.terms[zp]
            potential_coefficient = qubit_potential.terms[zp]

            paper_kinetic_coefficient = 0.
            paper_potential_coefficient = 0.
            for indices in grid.all_points_indices():
                momenta = momentum_vector(indices, grid)
                paper_kinetic_coefficient -= momenta.dot(
                    momenta) / float(4. * n_orbitals)

                if momenta.any():
                    potential_contribution = numpy.pi / float(
                        momenta.dot(momenta) * volume)
                    paper_potential_coefficient += potential_contribution

            self.assertAlmostEqual(
                kinetic_coefficient, paper_kinetic_coefficient)
            self.assertAlmostEqual(
                potential_coefficient, paper_potential_coefficient)

        # Check Zp Zq.
        if spinless:
            spins = [None]
        else:
            spins = [0, 1]

        for indices_a in grid.all_points_indices():
            for indices_b in grid.all_points_indices():

                paper_kinetic_coefficient = 0.
                paper_potential_coefficient = 0.

                position_a = position_vector(indices_a, grid)
                position_b = position_vector(indices_b, grid)
                differences = position_b - position_a

                for spin_a in spins:
                    for spin_b in spins:

                        p = orbital_id(grid, indices_a, spin_a)
                        q = orbital_id(grid, indices_b, spin_b)

                        if p == q:
                            continue

                        zpzq = ((min(p, q), 'Z'), (max(p, q), 'Z'))
                        if zpzq in qubit_potential.terms:
                            potential_coefficient = qubit_potential.terms[zpzq]

                        for indices_c in grid.all_points_indices():
                            momenta = momentum_vector(indices_c, grid)

                            if momenta.any():
                                potential_contribution = numpy.pi * numpy.cos(
                                    differences.dot(momenta)) / float(
                                    momenta.dot(momenta) * volume)
                                paper_potential_coefficient += (
                                    potential_contribution)

                        self.assertAlmostEqual(
                            potential_coefficient, paper_potential_coefficient)

    def test_jordan_wigner_dual_basis_jellium(self):
        # Parameters.
        grid = Grid(dimensions=2, length=3, scale=1.)
        spinless = True

        # Compute fermionic Hamiltonian. Include then subtract constant.
        fermion_hamiltonian = dual_basis_jellium_model(
            grid, spinless, include_constant=True)
        qubit_hamiltonian = jordan_wigner(fermion_hamiltonian)
        qubit_hamiltonian -= QubitOperator((), 2.8372)

        # Compute Jordan-Wigner Hamiltonian.
        test_hamiltonian = jordan_wigner_dual_basis_jellium(grid, spinless)

        # Make sure Hamiltonians are the same.
        self.assertTrue(test_hamiltonian.isclose(qubit_hamiltonian))

        # Check number of terms.
        n_qubits = count_qubits(qubit_hamiltonian)
        if spinless:
            paper_n_terms = 1 - .5 * n_qubits + 1.5 * (n_qubits ** 2)

        num_nonzeros = sum(1 for coeff in qubit_hamiltonian.terms.values() if
                           coeff != 0.0)
        self.assertTrue(num_nonzeros <= paper_n_terms)

    def test_jordan_wigner_dual_basis_jellium_constant_shift(self):
        length_scale = 0.6
        grid = Grid(dimensions=2, length=3, scale=length_scale)
        spinless = True

        hamiltonian_without_constant = jordan_wigner_dual_basis_jellium(
            grid, spinless, include_constant=False)
        hamiltonian_with_constant = jordan_wigner_dual_basis_jellium(
            grid, spinless, include_constant=True)

        difference = hamiltonian_with_constant - hamiltonian_without_constant
        expected = FermionOperator.identity() * (2.8372 / length_scale)

        self.assertTrue(expected.isclose(difference))


text:
/* eslint-env mocha */
'use strict'
var expect = require('chai').expect
var fs = require('fs')
var path = require('path')
var plugin = require('..')

var rules = fs.readdirSync(path.resolve(__dirname, '../lib/rules/'))
  .filter(function (f) { return f[0] !== '.' })
  .map(function (f) { return path.basename(f, '.js') })

describe('all rule files should be exported by the plugin', function () {
  rules.forEach(function (ruleName) {
    it('should export ' + ruleName, function () {
      expect(plugin.rules[ruleName]).to.eql(
        require(path.join('../lib/rules', ruleName))
      )
    })
  })
})


text:
local migrate_path = require "kong.db.migrations.migrate_path_280_300"

local pairs  = pairs
local ipairs = ipairs
local null   = ngx.null

return function(tbl, version)
  if not tbl or not (version == "1.1" or version == "2.1") then
    return
  end

  local routes = tbl.routes

  if not routes then
    -- no need to migrate
    return
  end

  for _, route in pairs(routes) do
    local paths = route.paths
    if not paths or paths == null then
      -- no need to migrate
      goto continue
    end

    for idx, path in ipairs(paths) do
      paths[idx] = migrate_path(path)
    end

    ::continue::
  end
end


text:
.. _dojo/isArrayLike:

================
dojo.isArrayLike
================

*Deprecated*.   Will be removed in 2.0.

See :ref:`Testing Object Types <releasenotes/migration-2.0#testing-object-types>` for advice on how to
differentiate between different types of objects without using dojo methods.


text:
<?php

namespace Valet;

use Symfony\Component\Process\Process;

class CommandLine
{
    /**
     * Simple global function to run commands.
     *
     * @param  string  $command
     * @return void
     */
    public function quietly($command)
    {
        $this->runCommand($command.' > /dev/null 2>&1');
    }

    /**
     * Simple global function to run commands.
     *
     * @param  string  $command
     * @return void
     */
    public function quietlyAsUser($command)
    {
        $this->quietly('sudo -u "'.user().'" '.$command.' > /dev/null 2>&1');
    }

    /**
     * Pass the command to the command line and display the output.
     *
     * @param  string  $command
     * @return void
     */
    public function passthru($command)
    {
        passthru($command);
    }

    /**
     * Run the given command as the non-root user.
     *
     * @param  string  $command
     * @param  callable  $onError
     * @return string
     */
    public function run($command, callable $onError = null)
    {
        return $this->runCommand($command, $onError);
    }

    /**
     * Run the given command.
     *
     * @param  string  $command
     * @param  callable  $onError
     * @return string
     */
    public function runAsUser($command, callable $onError = null)
    {
        return $this->runCommand('sudo -u "'.user().'" '.$command, $onError);
    }

    /**
     * Run the given command.
     *
     * @param  string  $command
     * @param  callable  $onError
     * @return string
     */
    public function runCommand($command, callable $onError = null)
    {
        $onError = $onError ?: function () {
        };

        // Symfony's 4.x Process component has deprecated passing a command string
        // to the constructor, but older versions (which Valet's Composer
        // constraints allow) don't have the fromShellCommandLine method.
        // For more information, see: https://github.com/laravel/valet/pull/761
        if (method_exists(Process::class, 'fromShellCommandline')) {
            $process = Process::fromShellCommandline($command);
        } else {
            $process = new Process($command);
        }

        $processOutput = '';
        $process->setTimeout(null)->run(function ($type, $line) use (&$processOutput) {
            $processOutput .= $line;
        });

        if ($process->getExitCode() > 0) {
            $onError($process->getExitCode(), $processOutput);
        }

        return $processOutput;
    }
}


text:
package com.swfarm.biz.wish.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.oa.srv.UserService;
import com.swfarm.biz.wish.bo.WishAccount;
import com.swfarm.biz.wish.srv.WishService;
import com.swfarm.pub.utils.SpringUtils;

public class AddWishAccountController extends SimpleFormController {

	private WishService wishService;

	public void setWishService(WishService wishService) {
		this.wishService = wishService;
	}

	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		String idStr = request.getParameter("id");
		WishAccount wishAccount = null;
		if (StringUtils.isNotEmpty(idStr)) {
			wishAccount = this.wishService.findWishAccount(new Long(idStr));
			Set saleManagers = wishAccount.getSaleManagerUsers();
			if (CollectionUtils.isNotEmpty(saleManagers)) {
				List saleManagerUserIds = new ArrayList();
				for (Iterator iter = saleManagers.iterator(); iter.hasNext();) {
					User saleManager = (User) iter.next();
					saleManagerUserIds.add(saleManager.getId());
				}
				Collections.sort(saleManagerUserIds);
				Long[] saleManagerUserIdArr = new Long[saleManagerUserIds.size()];
				saleManagerUserIds.toArray(saleManagerUserIdArr);
				wishAccount.setSaleManagerUserIds(saleManagerUserIdArr);
			}
			User saleManagerSupervisor = wishAccount.getSaleManagerSupervisor();
			if (saleManagerSupervisor != null) {
				wishAccount.setSaleManagerSupervisorId(saleManagerSupervisor.getId());
			}
		} else {
			wishAccount = new WishAccount();
		}
		return wishAccount;
	}

	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map dataMap = new HashMap();
		UserService userService = (UserService) SpringUtils.getBean("userService");
		List wishSaleManagers = userService.findUsersByRole("Wish");
		dataMap.put("wishSaleManagers", wishSaleManagers);
		return dataMap;
	}

	protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
			throws Exception {
		WishAccount wishAccount = (WishAccount) command;
	}

	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
		binder.registerCustomEditor(java.util.Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"), true));
	}

	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
			BindException errors) throws Exception {
		WishAccount wishAccount = (WishAccount) command;
		this.wishService.saveWishAccount(wishAccount);
		return new ModelAndView(new RedirectView(getSuccessView(), true));
	}
}