text:
#ifndef TENSORFLOW_LITE_TESTING_JOIN_H_
#define TENSORFLOW_LITE_TESTING_JOIN_H_

#include <cstdlib>
#include <sstream>

#include "tensorflow/lite/string.h"

namespace tflite {
namespace testing {

// Join a list of data separated by delimiter.
template <typename T>
string Join(T* data, size_t len, const string& delimiter) {
  if (len == 0 || data == nullptr) {
    return "";
  }
  std::stringstream result;
  result << data[0];
  for (int i = 1; i < len; i++) {
    result << delimiter << data[i];
  }
  return result.str();
}

// Join a list of uint8 data separated by a delimiter. Cast data to int before
// placing it in the string to prevent values from being treated like chars.
template <>
inline string Join<uint8_t>(uint8_t* data, size_t len,
                            const string& delimiter) {
  if (len == 0 || data == nullptr) {
    return "";
  }
  std::stringstream result;
  result << static_cast<int>(data[0]);
  for (int i = 1; i < len; i++) {
    result << delimiter << static_cast<int>(data[i]);
  }
  return result.str();
}

}  // namespace testing
}  // namespace tflite

#endif  // TENSORFLOW_LITE_TESTING_JOIN_H_


text:
package org.apache.camel.processor.loadbalancer;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.camel.AsyncProcessor;
import org.apache.camel.Navigate;
import org.apache.camel.Processor;
import org.apache.camel.spi.IdAware;
import org.apache.camel.spi.RouteIdAware;
import org.apache.camel.support.AsyncProcessorSupport;
import org.apache.camel.support.service.ServiceHelper;

/**
 * A default base class for a {@link LoadBalancer} implementation.
 */
public abstract class LoadBalancerSupport extends AsyncProcessorSupport implements LoadBalancer, Navigate<Processor>, IdAware, RouteIdAware {

    private final AtomicReference<AsyncProcessor[]> processors = new AtomicReference<>(new AsyncProcessor[0]);
    private String id;
    private String routeId;

    @Override
    public void addProcessor(AsyncProcessor processor) {
        processors.updateAndGet(op -> doAdd(processor, op));
    }

    @Override
    public void removeProcessor(AsyncProcessor processor) {
        processors.updateAndGet(op -> doRemove(processor, op));
    }

    private AsyncProcessor[] doAdd(AsyncProcessor processor, AsyncProcessor[] op) {
        int len = op.length;
        AsyncProcessor[] np = Arrays.copyOf(op, len + 1, op.getClass());
        np[len] = processor;
        return np;
    }

    private AsyncProcessor[] doRemove(AsyncProcessor processor, AsyncProcessor[] op) {
        int len = op.length;
        for (int index = 0; index < len; index++) {
            if (op[index].equals(processor)) {
                AsyncProcessor[] np = (AsyncProcessor[]) Array.newInstance(AsyncProcessor.class, len - 1);
                System.arraycopy(op, 0, np, 0, index);
                System.arraycopy(op, index + 1, np, index, len - index - 1);
                return np;
            }
        }
        return op;
    }

    @Override
    public List<AsyncProcessor> getProcessors() {
        return Arrays.asList(processors.get());
    }

    protected AsyncProcessor[] doGetProcessors() {
        return processors.get();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Processor> next() {
        if (!hasNext()) {
            return null;
        }
        return (List) getProcessors();
    }

    @Override
    public boolean hasNext() {
        return doGetProcessors().length > 0;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getRouteId() {
        return routeId;
    }

    @Override
    public void setRouteId(String routeId) {
        this.routeId = routeId;
    }

    @Override
    protected void doStart() throws Exception {
        ServiceHelper.startService((Object[]) processors.get());
    }

    @Override
    protected void doStop() throws Exception {
        ServiceHelper.stopService((Object[]) processors.get());
    }

    @Override
    protected void doShutdown() throws Exception {
        AsyncProcessor[] p = processors.get();
        ServiceHelper.stopAndShutdownServices((Object[]) p);
        for (AsyncProcessor processor : p) {
            removeProcessor(processor);
        }
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + Arrays.toString(doGetProcessors());
    }

}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/ExcessCapacityTerminationPolicy.h>
#include <aws/ec2/model/AllocationStrategy.h>
#include <aws/ec2/model/FleetType.h>
#include <aws/ec2/model/SpotFleetLaunchSpecification.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Describes the configuration of a Spot fleet request.

See Also:

   * AWS
   * API Reference

   */
  class AWS_EC2_API SpotFleetRequestConfigData
  {
  public:
    SpotFleetRequestConfigData();
    SpotFleetRequestConfigData(const Aws::Utils::Xml::XmlNode& xmlNode);
    SpotFleetRequestConfigData& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
A unique, case-sensitive identifier you provide to ensure idempotency of your
     * listings. This helps avoid duplicate listings. For more information, see Ensuring
     * Idempotency.

     */
    inline const Aws::String& GetClientToken() const{ return m_clientToken; }

    /**
     *
A unique, case-sensitive identifier you provide to ensure idempotency of your
     * listings. This helps avoid duplicate listings. For more information, see Ensuring
     * Idempotency.

     */
    inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; }

    /**
     *
A unique, case-sensitive identifier you provide to ensure idempotency of your
     * listings. This helps avoid duplicate listings. For more information, see Ensuring
     * Idempotency.

     */
    inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); }

    /**
     *
A unique, case-sensitive identifier you provide to ensure idempotency of your
     * listings. This helps avoid duplicate listings. For more information, see Ensuring
     * Idempotency.

     */
    inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); }

    /**
     *
A unique, case-sensitive identifier you provide to ensure idempotency of your
     * listings. This helps avoid duplicate listings. For more information, see Ensuring
     * Idempotency.

     */
    inline SpotFleetRequestConfigData& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;}

    /**
     *
A unique, case-sensitive identifier you provide to ensure idempotency of your
     * listings. This helps avoid duplicate listings. For more information, see Ensuring
     * Idempotency.

     */
    inline SpotFleetRequestConfigData& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;}

    /**
     *
A unique, case-sensitive identifier you provide to ensure idempotency of your
     * listings. This helps avoid duplicate listings. For more information, see Ensuring
     * Idempotency.

     */
    inline SpotFleetRequestConfigData& WithClientToken(const char* value) { SetClientToken(value); return *this;}

    /**
     *
The bid price per unit hour.

     */
    inline const Aws::String& GetSpotPrice() const{ return m_spotPrice; }

    /**
     *
The bid price per unit hour.

     */
    inline void SetSpotPrice(const Aws::String& value) { m_spotPriceHasBeenSet = true; m_spotPrice = value; }

    /**
     *
The bid price per unit hour.

     */
    inline void SetSpotPrice(Aws::String&& value) { m_spotPriceHasBeenSet = true; m_spotPrice = std::move(value); }

    /**
     *
The bid price per unit hour.

     */
    inline void SetSpotPrice(const char* value) { m_spotPriceHasBeenSet = true; m_spotPrice.assign(value); }

    /**
     *
The bid price per unit hour.

     */
    inline SpotFleetRequestConfigData& WithSpotPrice(const Aws::String& value) { SetSpotPrice(value); return *this;}

    /**
     *
The bid price per unit hour.

     */
    inline SpotFleetRequestConfigData& WithSpotPrice(Aws::String&& value) { SetSpotPrice(std::move(value)); return *this;}

    /**
     *
The bid price per unit hour.

     */
    inline SpotFleetRequestConfigData& WithSpotPrice(const char* value) { SetSpotPrice(value); return *this;}

    /**
     *
The number of units to request. You can choose to set the target capacity in
     * terms of instances or a performance characteristic that is important to your
     * application workload, such as vCPUs, memory, or I/O.

     */
    inline int GetTargetCapacity() const{ return m_targetCapacity; }

    /**
     *
The number of units to request. You can choose to set the target capacity in
     * terms of instances or a performance characteristic that is important to your
     * application workload, such as vCPUs, memory, or I/O.

     */
    inline void SetTargetCapacity(int value) { m_targetCapacityHasBeenSet = true; m_targetCapacity = value; }

    /**
     *
The number of units to request. You can choose to set the target capacity in
     * terms of instances or a performance characteristic that is important to your
     * application workload, such as vCPUs, memory, or I/O.

     */
    inline SpotFleetRequestConfigData& WithTargetCapacity(int value) { SetTargetCapacity(value); return *this;}

    /**
     *
The start date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). The default is
     * to start fulfilling the request immediately.

     */
    inline const Aws::Utils::DateTime& GetValidFrom() const{ return m_validFrom; }

    /**
     *
The start date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). The default is
     * to start fulfilling the request immediately.

     */
    inline void SetValidFrom(const Aws::Utils::DateTime& value) { m_validFromHasBeenSet = true; m_validFrom = value; }

    /**
     *
The start date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). The default is
     * to start fulfilling the request immediately.

     */
    inline void SetValidFrom(Aws::Utils::DateTime&& value) { m_validFromHasBeenSet = true; m_validFrom = std::move(value); }

    /**
     *
The start date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). The default is
     * to start fulfilling the request immediately.

     */
    inline SpotFleetRequestConfigData& WithValidFrom(const Aws::Utils::DateTime& value) { SetValidFrom(value); return *this;}

    /**
     *
The start date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). The default is
     * to start fulfilling the request immediately.

     */
    inline SpotFleetRequestConfigData& WithValidFrom(Aws::Utils::DateTime&& value) { SetValidFrom(std::move(value)); return *this;}

    /**
     *
The end date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). At this point,
     * no new Spot instance requests are placed or enabled to fulfill the request.

     */
    inline const Aws::Utils::DateTime& GetValidUntil() const{ return m_validUntil; }

    /**
     *
The end date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). At this point,
     * no new Spot instance requests are placed or enabled to fulfill the request.

     */
    inline void SetValidUntil(const Aws::Utils::DateTime& value) { m_validUntilHasBeenSet = true; m_validUntil = value; }

    /**
     *
The end date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). At this point,
     * no new Spot instance requests are placed or enabled to fulfill the request.

     */
    inline void SetValidUntil(Aws::Utils::DateTime&& value) { m_validUntilHasBeenSet = true; m_validUntil = std::move(value); }

    /**
     *
The end date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). At this point,
     * no new Spot instance requests are placed or enabled to fulfill the request.

     */
    inline SpotFleetRequestConfigData& WithValidUntil(const Aws::Utils::DateTime& value) { SetValidUntil(value); return *this;}

    /**
     *
The end date and time of the request, in UTC format (for example,
     * YYYY-MM-DDTHH:MM:SSZ). At this point,
     * no new Spot instance requests are placed or enabled to fulfill the request.

     */
    inline SpotFleetRequestConfigData& WithValidUntil(Aws::Utils::DateTime&& value) { SetValidUntil(std::move(value)); return *this;}

    /**
     *
Indicates whether running Spot instances should be terminated when the Spot
     * fleet request expires.

     */
    inline bool GetTerminateInstancesWithExpiration() const{ return m_terminateInstancesWithExpiration; }

    /**
     *
Indicates whether running Spot instances should be terminated when the Spot
     * fleet request expires.

     */
    inline void SetTerminateInstancesWithExpiration(bool value) { m_terminateInstancesWithExpirationHasBeenSet = true; m_terminateInstancesWithExpiration = value; }

    /**
     *
Indicates whether running Spot instances should be terminated when the Spot
     * fleet request expires.

     */
    inline SpotFleetRequestConfigData& WithTerminateInstancesWithExpiration(bool value) { SetTerminateInstancesWithExpiration(value); return *this;}

    /**
     *
Grants the Spot fleet permission to terminate Spot instances on your behalf
     * when you cancel its Spot fleet request using CancelSpotFleetRequests or
     * when the Spot fleet request expires, if you set
     * terminateInstancesWithExpiration.

     */
    inline const Aws::String& GetIamFleetRole() const{ return m_iamFleetRole; }

    /**
     *
Grants the Spot fleet permission to terminate Spot instances on your behalf
     * when you cancel its Spot fleet request using CancelSpotFleetRequests or
     * when the Spot fleet request expires, if you set
     * terminateInstancesWithExpiration.

     */
    inline void SetIamFleetRole(const Aws::String& value) { m_iamFleetRoleHasBeenSet = true; m_iamFleetRole = value; }

    /**
     *
Grants the Spot fleet permission to terminate Spot instances on your behalf
     * when you cancel its Spot fleet request using CancelSpotFleetRequests or
     * when the Spot fleet request expires, if you set
     * terminateInstancesWithExpiration.

     */
    inline void SetIamFleetRole(Aws::String&& value) { m_iamFleetRoleHasBeenSet = true; m_iamFleetRole = std::move(value); }

    /**
     *
Grants the Spot fleet permission to terminate Spot instances on your behalf
     * when you cancel its Spot fleet request using CancelSpotFleetRequests or
     * when the Spot fleet request expires, if you set
     * terminateInstancesWithExpiration.

     */
    inline void SetIamFleetRole(const char* value) { m_iamFleetRoleHasBeenSet = true; m_iamFleetRole.assign(value); }

    /**
     *
Grants the Spot fleet permission to terminate Spot instances on your behalf
     * when you cancel its Spot fleet request using CancelSpotFleetRequests or
     * when the Spot fleet request expires, if you set
     * terminateInstancesWithExpiration.

     */
    inline SpotFleetRequestConfigData& WithIamFleetRole(const Aws::String& value) { SetIamFleetRole(value); return *this;}

    /**
     *
Grants the Spot fleet permission to terminate Spot instances on your behalf
     * when you cancel its Spot fleet request using CancelSpotFleetRequests or
     * when the Spot fleet request expires, if you set
     * terminateInstancesWithExpiration.

     */
    inline SpotFleetRequestConfigData& WithIamFleetRole(Aws::String&& value) { SetIamFleetRole(std::move(value)); return *this;}

    /**
     *
Grants the Spot fleet permission to terminate Spot instances on your behalf
     * when you cancel its Spot fleet request using CancelSpotFleetRequests or
     * when the Spot fleet request expires, if you set
     * terminateInstancesWithExpiration.

     */
    inline SpotFleetRequestConfigData& WithIamFleetRole(const char* value) { SetIamFleetRole(value); return *this;}

    /**
     *
Information about the launch specifications for the Spot fleet request.

     */
    inline const Aws::Vector<SpotFleetLaunchSpecification>& GetLaunchSpecifications() const{ return m_launchSpecifications; }

    /**
     *
Information about the launch specifications for the Spot fleet request.

     */
    inline void SetLaunchSpecifications(const Aws::Vector<SpotFleetLaunchSpecification>& value) { m_launchSpecificationsHasBeenSet = true; m_launchSpecifications = value; }

    /**
     *
Information about the launch specifications for the Spot fleet request.

     */
    inline void SetLaunchSpecifications(Aws::Vector<SpotFleetLaunchSpecification>&& value) { m_launchSpecificationsHasBeenSet = true; m_launchSpecifications = std::move(value); }

    /**
     *
Information about the launch specifications for the Spot fleet request.

     */
    inline SpotFleetRequestConfigData& WithLaunchSpecifications(const Aws::Vector<SpotFleetLaunchSpecification>& value) { SetLaunchSpecifications(value); return *this;}

    /**
     *
Information about the launch specifications for the Spot fleet request.

     */
    inline SpotFleetRequestConfigData& WithLaunchSpecifications(Aws::Vector<SpotFleetLaunchSpecification>&& value) { SetLaunchSpecifications(std::move(value)); return *this;}

    /**
     *
Information about the launch specifications for the Spot fleet request.

     */
    inline SpotFleetRequestConfigData& AddLaunchSpecifications(const SpotFleetLaunchSpecification& value) { m_launchSpecificationsHasBeenSet = true; m_launchSpecifications.push_back(value); return *this; }

    /**
     *
Information about the launch specifications for the Spot fleet request.

     */
    inline SpotFleetRequestConfigData& AddLaunchSpecifications(SpotFleetLaunchSpecification&& value) { m_launchSpecificationsHasBeenSet = true; m_launchSpecifications.push_back(std::move(value)); return *this; }

    /**
     *
Indicates whether running Spot instances should be terminated if the target
     * capacity of the Spot fleet request is decreased below the current size of the
     * Spot fleet.

     */
    inline const ExcessCapacityTerminationPolicy& GetExcessCapacityTerminationPolicy() const{ return m_excessCapacityTerminationPolicy; }

    /**
     *
Indicates whether running Spot instances should be terminated if the target
     * capacity of the Spot fleet request is decreased below the current size of the
     * Spot fleet.

     */
    inline void SetExcessCapacityTerminationPolicy(const ExcessCapacityTerminationPolicy& value) { m_excessCapacityTerminationPolicyHasBeenSet = true; m_excessCapacityTerminationPolicy = value; }

    /**
     *
Indicates whether running Spot instances should be terminated if the target
     * capacity of the Spot fleet request is decreased below the current size of the
     * Spot fleet.

     */
    inline void SetExcessCapacityTerminationPolicy(ExcessCapacityTerminationPolicy&& value) { m_excessCapacityTerminationPolicyHasBeenSet = true; m_excessCapacityTerminationPolicy = std::move(value); }

    /**
     *
Indicates whether running Spot instances should be terminated if the target
     * capacity of the Spot fleet request is decreased below the current size of the
     * Spot fleet.

     */
    inline SpotFleetRequestConfigData& WithExcessCapacityTerminationPolicy(const ExcessCapacityTerminationPolicy& value) { SetExcessCapacityTerminationPolicy(value); return *this;}

    /**
     *
Indicates whether running Spot instances should be terminated if the target
     * capacity of the Spot fleet request is decreased below the current size of the
     * Spot fleet.

     */
    inline SpotFleetRequestConfigData& WithExcessCapacityTerminationPolicy(ExcessCapacityTerminationPolicy&& value) { SetExcessCapacityTerminationPolicy(std::move(value)); return *this;}

    /**
     *
Indicates how to allocate the target capacity across the Spot pools specified
     * by the Spot fleet request. The default is lowestPrice.

     */
    inline const AllocationStrategy& GetAllocationStrategy() const{ return m_allocationStrategy; }

    /**
     *
Indicates how to allocate the target capacity across the Spot pools specified
     * by the Spot fleet request. The default is lowestPrice.

     */
    inline void SetAllocationStrategy(const AllocationStrategy& value) { m_allocationStrategyHasBeenSet = true; m_allocationStrategy = value; }

    /**
     *
Indicates how to allocate the target capacity across the Spot pools specified
     * by the Spot fleet request. The default is lowestPrice.

     */
    inline void SetAllocationStrategy(AllocationStrategy&& value) { m_allocationStrategyHasBeenSet = true; m_allocationStrategy = std::move(value); }

    /**
     *
Indicates how to allocate the target capacity across the Spot pools specified
     * by the Spot fleet request. The default is lowestPrice.

     */
    inline SpotFleetRequestConfigData& WithAllocationStrategy(const AllocationStrategy& value) { SetAllocationStrategy(value); return *this;}

    /**
     *
Indicates how to allocate the target capacity across the Spot pools specified
     * by the Spot fleet request. The default is lowestPrice.

     */
    inline SpotFleetRequestConfigData& WithAllocationStrategy(AllocationStrategy&& value) { SetAllocationStrategy(std::move(value)); return *this;}

    /**
     *
The number of units fulfilled by this request compared to the set target
     * capacity.

     */
    inline double GetFulfilledCapacity() const{ return m_fulfilledCapacity; }

    /**
     *
The number of units fulfilled by this request compared to the set target
     * capacity.

     */
    inline void SetFulfilledCapacity(double value) { m_fulfilledCapacityHasBeenSet = true; m_fulfilledCapacity = value; }

    /**
     *
The number of units fulfilled by this request compared to the set target
     * capacity.

     */
    inline SpotFleetRequestConfigData& WithFulfilledCapacity(double value) { SetFulfilledCapacity(value); return *this;}

    /**
     *
The type of request. Indicates whether the fleet will only
     * request the target capacity or also attempt to
     * maintain it. When you request a certain target
     * capacity, the fleet will only place the required bids. It will not attempt to
     * replenish Spot instances if capacity is diminished, nor will it submit bids in
     * alternative Spot pools if capacity is not available. When you want to
     * maintain a certain target capacity, fleet will place the required
     * bids to meet this target capacity. It will also automatically replenish any
     * interrupted instances. Default: maintain.

     */
    inline const FleetType& GetType() const{ return m_type; }

    /**
     *
The type of request. Indicates whether the fleet will only
     * request the target capacity or also attempt to
     * maintain it. When you request a certain target
     * capacity, the fleet will only place the required bids. It will not attempt to
     * replenish Spot instances if capacity is diminished, nor will it submit bids in
     * alternative Spot pools if capacity is not available. When you want to
     * maintain a certain target capacity, fleet will place the required
     * bids to meet this target capacity. It will also automatically replenish any
     * interrupted instances. Default: maintain.

     */
    inline void SetType(const FleetType& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of request. Indicates whether the fleet will only
     * request the target capacity or also attempt to
     * maintain it. When you request a certain target
     * capacity, the fleet will only place the required bids. It will not attempt to
     * replenish Spot instances if capacity is diminished, nor will it submit bids in
     * alternative Spot pools if capacity is not available. When you want to
     * maintain a certain target capacity, fleet will place the required
     * bids to meet this target capacity. It will also automatically replenish any
     * interrupted instances. Default: maintain.

     */
    inline void SetType(FleetType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of request. Indicates whether the fleet will only
     * request the target capacity or also attempt to
     * maintain it. When you request a certain target
     * capacity, the fleet will only place the required bids. It will not attempt to
     * replenish Spot instances if capacity is diminished, nor will it submit bids in
     * alternative Spot pools if capacity is not available. When you want to
     * maintain a certain target capacity, fleet will place the required
     * bids to meet this target capacity. It will also automatically replenish any
     * interrupted instances. Default: maintain.

     */
    inline SpotFleetRequestConfigData& WithType(const FleetType& value) { SetType(value); return *this;}

    /**
     *
The type of request. Indicates whether the fleet will only
     * request the target capacity or also attempt to
     * maintain it. When you request a certain target
     * capacity, the fleet will only place the required bids. It will not attempt to
     * replenish Spot instances if capacity is diminished, nor will it submit bids in
     * alternative Spot pools if capacity is not available. When you want to
     * maintain a certain target capacity, fleet will place the required
     * bids to meet this target capacity. It will also automatically replenish any
     * interrupted instances. Default: maintain.

     */
    inline SpotFleetRequestConfigData& WithType(FleetType&& value) { SetType(std::move(value)); return *this;}

    /**
     *
Indicates whether Spot fleet should replace unhealthy instances.

     */
    inline bool GetReplaceUnhealthyInstances() const{ return m_replaceUnhealthyInstances; }

    /**
     *
Indicates whether Spot fleet should replace unhealthy instances.

     */
    inline void SetReplaceUnhealthyInstances(bool value) { m_replaceUnhealthyInstancesHasBeenSet = true; m_replaceUnhealthyInstances = value; }

    /**
     *
Indicates whether Spot fleet should replace unhealthy instances.

     */
    inline SpotFleetRequestConfigData& WithReplaceUnhealthyInstances(bool value) { SetReplaceUnhealthyInstances(value); return *this;}

  private:
    Aws::String m_clientToken;
    bool m_clientTokenHasBeenSet;
    Aws::String m_spotPrice;
    bool m_spotPriceHasBeenSet;
    int m_targetCapacity;
    bool m_targetCapacityHasBeenSet;
    Aws::Utils::DateTime m_validFrom;
    bool m_validFromHasBeenSet;
    Aws::Utils::DateTime m_validUntil;
    bool m_validUntilHasBeenSet;
    bool m_terminateInstancesWithExpiration;
    bool m_terminateInstancesWithExpirationHasBeenSet;
    Aws::String m_iamFleetRole;
    bool m_iamFleetRoleHasBeenSet;
    Aws::Vector<SpotFleetLaunchSpecification> m_launchSpecifications;
    bool m_launchSpecificationsHasBeenSet;
    ExcessCapacityTerminationPolicy m_excessCapacityTerminationPolicy;
    bool m_excessCapacityTerminationPolicyHasBeenSet;
    AllocationStrategy m_allocationStrategy;
    bool m_allocationStrategyHasBeenSet;
    double m_fulfilledCapacity;
    bool m_fulfilledCapacityHasBeenSet;
    FleetType m_type;
    bool m_typeHasBeenSet;
    bool m_replaceUnhealthyInstances;
    bool m_replaceUnhealthyInstancesHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
from api_lib import APITest
import os

class VersionAPITest(APITest):
    """
    GET /version
    """

    def check(self):
        self.check_equal(self.get("/api/version").json(), {'Version': os.environ['APTLY_VERSION']})


text:
package com.ctrip.framework.apollo.portal.service;

import com.ctrip.framework.apollo.common.constants.GsonType;
import com.ctrip.framework.apollo.common.dto.PageDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseHistoryDTO;
import com.ctrip.framework.apollo.common.entity.EntityPair;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI.ReleaseHistoryAPI;
import com.ctrip.framework.apollo.portal.enricher.adapter.BaseDtoUserInfoEnrichedAdapter;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.util.RelativeDateFormat;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.util.CollectionUtils;

@Service
public class ReleaseHistoryService {

  private final static Gson GSON = new Gson();

  private final AdminServiceAPI.ReleaseHistoryAPI releaseHistoryAPI;
  private final ReleaseService releaseService;
  private final AdditionalUserInfoEnrichService additionalUserInfoEnrichService;

  public ReleaseHistoryService(final ReleaseHistoryAPI releaseHistoryAPI,
      final ReleaseService releaseService,
      AdditionalUserInfoEnrichService additionalUserInfoEnrichService) {
    this.releaseHistoryAPI = releaseHistoryAPI;
    this.releaseService = releaseService;
    this.additionalUserInfoEnrichService = additionalUserInfoEnrichService;
  }

  public ReleaseHistoryBO findLatestByReleaseIdAndOperation(Env env, long releaseId, int operation){
    PageDTO<ReleaseHistoryDTO> pageDTO = releaseHistoryAPI.findByReleaseIdAndOperation(env, releaseId, operation, 0, 1);
    if (pageDTO != null && pageDTO.hasContent()){
      ReleaseHistoryDTO releaseHistory = pageDTO.getContent().get(0);
      ReleaseDTO release = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
      return transformReleaseHistoryDTO2BO(releaseHistory, release);
    }

    return null;
  }

  public ReleaseHistoryBO findLatestByPreviousReleaseIdAndOperation(Env env, long previousReleaseId, int operation){
    PageDTO<ReleaseHistoryDTO> pageDTO = releaseHistoryAPI.findByPreviousReleaseIdAndOperation(env, previousReleaseId, operation, 0, 1);
    if (pageDTO != null && pageDTO.hasContent()){
      ReleaseHistoryDTO releaseHistory = pageDTO.getContent().get(0);
      ReleaseDTO release = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
      return transformReleaseHistoryDTO2BO(releaseHistory, release);
    }

    return null;
  }

  public List<ReleaseHistoryBO> findNamespaceReleaseHistory(String appId, Env env, String clusterName,
                                                            String namespaceName, int page, int size) {
    PageDTO<ReleaseHistoryDTO> result = releaseHistoryAPI.findReleaseHistoriesByNamespace(appId, env, clusterName,
                                                                                namespaceName, page, size);
    if (result == null || !result.hasContent()) {
      return Collections.emptyList();
    }

    List<ReleaseHistoryDTO> content = result.getContent();
    Set<Long> releaseIds = new HashSet<>();
    for (ReleaseHistoryDTO releaseHistoryDTO : content) {
      long releaseId = releaseHistoryDTO.getReleaseId();
      if (releaseId != 0) {
        releaseIds.add(releaseId);
      }
    }

    List<ReleaseDTO> releases = releaseService.findReleaseByIds(env, releaseIds);

    return transformReleaseHistoryDTO2BO(content, releases);
  }

  private List<ReleaseHistoryBO> transformReleaseHistoryDTO2BO(List<ReleaseHistoryDTO> source,
                                                               List<ReleaseDTO> releases) {
    if (CollectionUtils.isEmpty(source)) {
      return Collections.emptyList();
    }
    this.additionalUserInfoEnrichService.enrichAdditionalUserInfo(source, BaseDtoUserInfoEnrichedAdapter::new);

    Map<Long, ReleaseDTO> releasesMap = BeanUtils.mapByKey("id", releases);

    List<ReleaseHistoryBO> bos = new ArrayList<>(source.size());
    for (ReleaseHistoryDTO dto : source) {
      ReleaseDTO release = releasesMap.get(dto.getReleaseId());
      bos.add(transformReleaseHistoryDTO2BO(dto, release));
    }

    return bos;
  }

  private ReleaseHistoryBO transformReleaseHistoryDTO2BO(ReleaseHistoryDTO dto, ReleaseDTO release){
    ReleaseHistoryBO bo = new ReleaseHistoryBO();
    bo.setId(dto.getId());
    bo.setAppId(dto.getAppId());
    bo.setClusterName(dto.getClusterName());
    bo.setNamespaceName(dto.getNamespaceName());
    bo.setBranchName(dto.getBranchName());
    bo.setReleaseId(dto.getReleaseId());
    bo.setPreviousReleaseId(dto.getPreviousReleaseId());
    bo.setOperator(dto.getDataChangeCreatedBy());
    bo.setOperatorDisplayName(dto.getDataChangeCreatedByDisplayName());
    bo.setOperation(dto.getOperation());
    Date releaseTime = dto.getDataChangeLastModifiedTime();
    bo.setReleaseTime(releaseTime);
    bo.setReleaseTimeFormatted(RelativeDateFormat.format(releaseTime));
    bo.setOperationContext(dto.getOperationContext());
    //set release info
    setReleaseInfoToReleaseHistoryBO(bo, release);

    return bo;
  }
  private void setReleaseInfoToReleaseHistoryBO(ReleaseHistoryBO bo, ReleaseDTO release) {
    if (release != null) {
      bo.setReleaseTitle(release.getName());
      bo.setReleaseComment(release.getComment());
      bo.setReleaseAbandoned(release.isAbandoned());

      Map<String, String> configuration = GSON.fromJson(release.getConfigurations(), GsonType.CONFIG);
      List<EntityPair<String>> items = new ArrayList<>(configuration.size());
      for (Map.Entry<String, String> entry : configuration.entrySet()) {
        EntityPair<String> entityPair = new EntityPair<>(entry.getKey(), entry.getValue());
        items.add(entityPair);
      }
      bo.setConfiguration(items);

    } else {
      bo.setReleaseTitle("no release information");
      bo.setConfiguration(null);
    }
  }
}


text:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "../apparel21/server.php";
$start = microtime(true);
$host=$server_arr["current"]["servername"];
$username=$server_arr["current"]["username"];
$password=$server_arr["current"]["password"];
$db_name=$server_arr["current"]["dbname"];

$conn=mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($conn,"$db_name")or die("Cannot select DB");
$ext=date('Ymd');
$sql_arr=array(
	"RENAME TABLE prod_mast TO {$ext}_prod_mast",
	"RENAME TABLE prod_variation TO {$ext}_prod_variation",
	"RENAME TABLE prod_images TO {$ext}_prod_images",
	"RENAME TABLE prod_attributes TO {$ext}_prod_attributes",
	"RENAME TABLE prod_barcode TO {$ext}_prod_barcode",
	"RENAME TABLE category_assignment TO {$ext}_category_assignment",
	"RENAME TABLE live_mast TO prod_mast",
	"RENAME TABLE live_variation TO prod_variation",
	"RENAME TABLE live_images TO prod_images",
	"RENAME TABLE live_attributes TO prod_attributes",
	"RENAME TABLE live_barcode TO prod_barcode",
	"RENAME TABLE live_category_assignment TO category_assignment"
	);
foreach($sql_arr as $curr_sql):
	echo "
 $curr_sql";
	$conn->query($curr_sql);
endforeach;
echo "
 Time taken for step : " . (microtime(true) - $start) . " Seconds";
echo "
 PROCESS COMPLETE. ";
$conn->close();
exit;

?>


text:
const inquirer = require('inquirer')
const dockerUtil = require('../util/docker')

module.exports = (gulp) => {
    return gulp.task('docker-init', (cb) => {
        const initCommands = [
            'volume',
            'create',
            '--name=holistic_mongo'
        ]
        dockerUtil.exec(initCommands)
    });
}


text:
#ifndef _XRESPROTO_H
#define _XRESPROTO_H

#define XRES_MAJOR_VERSION 1
#define XRES_MINOR_VERSION 2

#define XRES_NAME "X-Resource"

/* v1.0 */
#define X_XResQueryVersion            0
#define X_XResQueryClients            1
#define X_XResQueryClientResources    2
#define X_XResQueryClientPixmapBytes  3

/* Version 1.1 has been accidentally released from the version           */
/* control and while it doesn't have differences to version 1.0, the     */
/* next version is labeled 1.2 in order to remove the risk of confusion. */

/* v1.2 */
#define X_XResQueryClientIds          4
#define X_XResQueryResourceBytes      5

typedef struct {
   CARD32 resource_base;
   CARD32 resource_mask;
} xXResClient;
#define sz_xXResClient 8

typedef struct {
   CARD32 resource_type;
   CARD32 count;
} xXResType;
#define sz_xXResType 8

/* XResQueryVersion */

typedef struct _XResQueryVersion {
   CARD8   reqType;
   CARD8   XResReqType;
   CARD16  length B16;
   CARD8   client_major;
   CARD8   client_minor;
   CARD16  unused B16;
} xXResQueryVersionReq;
#define sz_xXResQueryVersionReq 8

typedef struct {
   CARD8   type;
   CARD8   pad1;
   CARD16  sequenceNumber B16;
   CARD32  length B32;
   CARD16  server_major B16;
   CARD16  server_minor B16;
   CARD32  pad2 B32;
   CARD32  pad3 B32;
   CARD32  pad4 B32;
   CARD32  pad5 B32;
   CARD32  pad6 B32;
} xXResQueryVersionReply;
#define sz_xXResQueryVersionReply  32

/* XResQueryClients */

typedef struct _XResQueryClients {
   CARD8   reqType;
   CARD8   XResReqType;
   CARD16  length B16;
} xXResQueryClientsReq;
#define sz_xXResQueryClientsReq 4

typedef struct {
   CARD8   type;
   CARD8   pad1;
   CARD16  sequenceNumber B16;
   CARD32  length B32;
   CARD32  num_clients B32;
   CARD32  pad2 B32;
   CARD32  pad3 B32;
   CARD32  pad4 B32;
   CARD32  pad5 B32;
   CARD32  pad6 B32;
} xXResQueryClientsReply;
#define sz_xXResQueryClientsReply  32

/* XResQueryClientResources */

typedef struct _XResQueryClientResources {
   CARD8   reqType;
   CARD8   XResReqType;
   CARD16  length B16;
   CARD32  xid B32;
} xXResQueryClientResourcesReq;
#define sz_xXResQueryClientResourcesReq 8

typedef struct {
   CARD8   type;
   CARD8   pad1;
   CARD16  sequenceNumber B16;
   CARD32  length B32;
   CARD32  num_types B32;
   CARD32  pad2 B32;
   CARD32  pad3 B32;
   CARD32  pad4 B32;
   CARD32  pad5 B32;
   CARD32  pad6 B32;
} xXResQueryClientResourcesReply;
#define sz_xXResQueryClientResourcesReply  32

/* XResQueryClientPixmapBytes */

typedef struct _XResQueryClientPixmapBytes {
   CARD8   reqType;
   CARD8   XResReqType;
   CARD16  length B16;
   CARD32  xid B32;
} xXResQueryClientPixmapBytesReq;
#define sz_xXResQueryClientPixmapBytesReq 8

typedef struct {
   CARD8   type;
   CARD8   pad1;
   CARD16  sequenceNumber B16;
   CARD32  length B32;
   CARD32  bytes B32;
   CARD32  bytes_overflow B32;
   CARD32  pad2 B32;
   CARD32  pad3 B32;
   CARD32  pad4 B32;
   CARD32  pad5 B32;
} xXResQueryClientPixmapBytesReply;
#define sz_xXResQueryClientPixmapBytesReply  32

/* v1.2 XResQueryClientIds */

#define X_XResClientXIDMask      0x01
#define X_XResLocalClientPIDMask 0x02

typedef struct _XResClientIdSpec {
   CARD32  client B32;
   CARD32  mask B32;
} xXResClientIdSpec;
#define sz_xXResClientIdSpec 8

typedef struct _XResClientIdValue {
   xXResClientIdSpec spec;
   CARD32  length B32;
   // followed by length CARD32s
} xXResClientIdValue;
#define sz_xResClientIdValue (sz_xXResClientIdSpec + 4)

typedef struct _XResQueryClientIds {
   CARD8   reqType;
   CARD8   XResReqType;
   CARD16  length B16;
   CARD32  numSpecs B32;
   // followed by numSpecs times XResClientIdSpec
} xXResQueryClientIdsReq;
#define sz_xXResQueryClientIdsReq 8

typedef struct {
   CARD8   type;
   CARD8   pad1;
   CARD16  sequenceNumber B16;
   CARD32  length B32;
   CARD32  numIds B32;
   CARD32  pad2 B32;
   CARD32  pad3 B32;
   CARD32  pad4 B32;
   CARD32  pad5 B32;
   CARD32  pad6 B32;
   // followed by numIds times XResClientIdValue
} xXResQueryClientIdsReply;
#define sz_xXResQueryClientIdsReply  32

/* v1.2 XResQueryResourceBytes */

typedef struct _XResResourceIdSpec {
   CARD32  resource;
   CARD32  type;
} xXResResourceIdSpec;
#define sz_xXResResourceIdSpec 8

typedef struct _XResQueryResourceBytes {
   CARD8   reqType;
   CARD8   XResReqType;
   CARD16  length B16;
   CARD32  client B32;
   CARD32  numSpecs B32;
   // followed by numSpecs times XResResourceIdSpec
} xXResQueryResourceBytesReq;
#define sz_xXResQueryResourceBytesReq 12

typedef struct _XResResourceSizeSpec {
   xXResResourceIdSpec spec;
   CARD32  bytes B32;
   CARD32  refCount B32;
   CARD32  useCount B32;
} xXResResourceSizeSpec;
#define sz_xXResResourceSizeSpec (sz_xXResResourceIdSpec + 12)

typedef struct _XResResourceSizeValue {
   xXResResourceSizeSpec size;
   CARD32  numCrossReferences B32;
   // followed by numCrossReferences times XResResourceSizeSpec
} xXResResourceSizeValue;
#define sz_xXResResourceSizeValue (sz_xXResResourceSizeSpec + 4)

typedef struct {
   CARD8   type;
   CARD8   pad1;
   CARD16  sequenceNumber B16;
   CARD32  length B32;
   CARD32  numSizes B32;
   CARD32  pad2 B32;
   CARD32  pad3 B32;
   CARD32  pad4 B32;
   CARD32  pad5 B32;
   CARD32  pad6 B32;
   // followed by numSizes times XResResourceSizeValue
} xXResQueryResourceBytesReply;
#define sz_xXResQueryResourceBytesReply  32

#endif /* _XRESPROTO_H */


text:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace EZOper.NetSiteUtilities.AopApi
{
    /// <summary>
    /// KoubeiItemExtitemBatchqueryResponse.
    /// </summary>
    public class KoubeiItemExtitemBatchqueryResponse : AopResponse
    {
        /// <summary>
        /// 商品信息列表
        /// </summary>
        [XmlArray("model_list")]
        [XmlArrayItem("ext_item")]
        public List<ExtItem> ModelList { get; set; }

        /// <summary>
        /// 当前页码
        /// </summary>
        [XmlElement("page_num")]
        public string PageNum { get; set; }

        /// <summary>
        /// 分页大小
        /// </summary>
        [XmlElement("page_size")]
        public string PageSize { get; set; }

        /// <summary>
        /// 总记录数
        /// </summary>
        [XmlElement("total_size")]
        public string TotalSize { get; set; }
    }
}


text:
var events = require('events'),
    jsdom = require('jsdom'),
    util = require('util');

var SpecParser = function(){
};

util.inherits(SpecParser, events.EventEmitter);

SpecParser.prototype.parseSpec = function(data, specUrl){
    var that = this;
    jsdom.env(data, ['http://code.jquery.com/jquery-1.5.min.js'],
    function(errors, window){
        var $ = window.$;
        var testCases = [];
        var testCaseObjectId = 100;
        var testsTotal =  $("div[id^='::']").length;
        var found = 0;

        var commit = function(test, nocount){
            if (!nocount) found += 1;
            that.emit('onTest', test);
            if (found == testsTotal)
                that.emit('end');
        };

		$("div[id^='::']").each(function() {
			var mid = $(this).attr('id');
			var hash = '#'+mid;
			var testCaseObject = {
                id:testCaseObjectId,
                name:mid,
                definedInSpecs:[specUrl+hash]
            };
			commit(testCaseObject, false);
			testCaseObjectId += 100;
			var methods = $(this).children('.methods').children('dl').children('dt');
			for (var i = 0; i < methods.length; i += 1){
				var id = $(methods[i]).attr('id');
				hash = '#'+id;
				testCaseObject = {
					id:testCaseObjectId,
					name:mid+'-method-'+id,
					definedInSpecs:[specUrl+hash]
				};
				commit(testCaseObject, true);
				testCaseObjectId += 100;
			}
		});
    });
    return true;
};

exports.SpecParser = SpecParser;


text:
package org.apache.causeway.core.metamodel.facets.collections.collection.defaultview;

import org.apache.causeway.core.metamodel.facets.SingleStringValueFacet;

public interface DefaultViewFacet extends SingleStringValueFacet {

}


text:
// Copyright 2011 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Gallio.Icarus.Commands;
using Gallio.Icarus.Controllers.Interfaces;
using Gallio.Icarus.Models;
using Gallio.Icarus.WindowManager;
using Gallio.UI.Menus;

namespace Gallio.Icarus.TestResults
{
    public class TestResultsPackage : IPackage
    {
        private readonly IWindowManager windowManager;
        private readonly ITestResultsController testResultsController;
        private readonly IOptionsController optionsController;
        private readonly ITestTreeModel testTreeModel;
        private readonly ITestStatistics testStatistics;

        public const string WindowId = "Gallio.Icarus.TestResults";

        public TestResultsPackage(IWindowManager windowManager, ITestResultsController testResultsController, IOptionsController optionsController,
            ITestTreeModel testTreeModel, ITestStatistics testStatistics)
        {
            this.windowManager = windowManager;
            this.testResultsController = testResultsController;
            this.optionsController = optionsController;
            this.testTreeModel = testTreeModel;
            this.testStatistics = testStatistics;
        }

        public void Load()
        {
            RegisterWindow();
            AddMenuItem();
        }

        private void RegisterWindow()
        {
            windowManager.Register(WindowId, () =>
            {
                var testResults = new TestResults(testResultsController, optionsController, testTreeModel, testStatistics);
                windowManager.Add(WindowId, testResults, TestResultsResources.Test_Results);
            }, Location.Centre);
        }

        private void AddMenuItem()
        {
            windowManager.MenuManager.Add("View", () => new MenuCommand
            {
                Command = new DelegateCommand(pm => windowManager.Show(WindowId)),
                Text = TestResultsResources.Test_Results,
            });
        }

        public void Dispose() { }
    }
}


text:
import json
from os import path

class TechStockQuotesDAL:
    db_exception = None
    tech_stock_quotes = None

    def __init__(self):
        self.tech_stock_quotes_db_file = path.join(path.dirname(path.abspath(__file__)), 'database/TechStockQuotes.json')
        try:
            with open(self.tech_stock_quotes_db_file, 'r') as json_data:
                self.tech_stock_quotes = json.load(json_data)
        except Exception as general_exception:
            self.db_exception = general_exception

    def get_all_tech_stocks(self):
        """ Returns the available stock ticks """
        return self.db_exception, self.tech_stock_quotes

    def get_stock_quote_by_company_title(self, company_title):
        """ Returns the stock title of a company """
        ret_stock_key = None
        if company_title in self.tech_stock_quotes:
            ret_stock_key = self.tech_stock_quotes[company_title]
        return self.db_exception, ret_stock_key


text:
def dev_null(&block)
  begin
    orig_stdout = $stdout.dup # does a dup2() internally
    $stdout.reopen('/dev/null', 'w')
    yield
  ensure
    $stdout.reopen(orig_stdout)
  end
end


text:
define([
	"dojo/_base/kernel",	// dojo.getObject, dojo.mixin
	"dojo/_base/lang",	// dojo.extend
	"dojo/_base/sniff",	// dojo.isOpera
	 "./tokenize"
], function(dojo, lang, has, tokenize){
	var strLib = lang.getObject("string", true, dojox);

	strLib.sprintf = function(/*String*/ format, /*mixed...*/ filler){
		for(var args = [], i = 1; i < arguments.length; i++){
			args.push(arguments[i]);
		}
		var formatter = new strLib.sprintf.Formatter(format);
		return formatter.format.apply(formatter, args);
	};

	strLib.sprintf.Formatter = function(/*String*/ format){
		var tokens = [];
		this._mapped = false;
		this._format = format;
		this._tokens = tokenize(format, this._re, this._parseDelim, this);
	};

	lang.extend(strLib.sprintf.Formatter, {
		_re: /\%(?:\(([\w_]+)\)|([1-9]\d*)\$)?([0 +\-\#]*)(\*|\d+)?(\.)?(\*|\d+)?[hlL]?([\%scdeEfFgGiouxX])/g,
		_parseDelim: function(mapping, intmapping, flags, minWidth, period, precision, specifier){
			if(mapping){
				this._mapped = true;
			}
			return {
				mapping: mapping,
				intmapping: intmapping,
				flags: flags,
				_minWidth: minWidth, // May be dependent on parameters
				period: period,
				_precision: precision, // May be dependent on parameters
				specifier: specifier
			};
		},
		_specifiers: {
			b: {
				base: 2,
				isInt: true
			},
			o: {
				base: 8,
				isInt: true
			},
			x: {
				base: 16,
				isInt: true
			},
			X: {
				extend: ["x"],
				toUpper: true
			},
			d: {
				base: 10,
				isInt: true
			},
			i: {
				extend: ["d"]
			},
			u: {
				extend: ["d"],
				isUnsigned: true
			},
			c: {
				setArg: function(token){
					if(!isNaN(token.arg)){
						var num = parseInt(token.arg);
						if(num < 0 || num > 127){
							throw new Error("invalid character code passed to %c in sprintf");
						}
						token.arg = isNaN(num) ? "" + num : String.fromCharCode(num);
					}
				}
			},
			s: {
				setMaxWidth: function(token){
					token.maxWidth = (token.period == ".") ? token.precision : -1;
				}
			},
			e: {
				isDouble: true,
				doubleNotation: "e"
			},
			E: {
				extend: ["e"],
				toUpper: true
			},
			f: {
				isDouble: true,
				doubleNotation: "f"
			},
			F: {
				extend: ["f"]
			},
			g: {
				isDouble: true,
				doubleNotation: "g"
			},
			G: {
				extend: ["g"],
				toUpper: true
			}
		},
		format: function(/*mixed...*/ filler){
			if(this._mapped && typeof filler != "object"){
				throw new Error("format requires a mapping");
			}

			var str = "";
			var position = 0;
			for(var i = 0, token; i < this._tokens.length; i++){
				token = this._tokens[i];
				if(typeof token == "string"){
					str += token;
				}else{
					if(this._mapped){
						if(typeof filler[token.mapping] == "undefined"){
							throw new Error("missing key " + token.mapping);
						}
						token.arg = filler[token.mapping];
					}else{
						if(token.intmapping){
							var position = parseInt(token.intmapping) - 1;
						}
						if(position >= arguments.length){
							throw new Error("got " + arguments.length + " printf arguments, insufficient for '" + this._format + "'");
						}
						token.arg = arguments[position++];
					}

					if(!token.compiled){
						token.compiled = true;
						token.sign = "";
						token.zeroPad = false;
						token.rightJustify = false;
						token.alternative = false;

						var flags = {};
						for(var fi = token.flags.length; fi--;){
							var flag = token.flags.charAt(fi);
							flags[flag] = true;
							switch(flag){
								case " ":
									token.sign = " ";
									break;
								case "+":
									token.sign = "+";
									break;
								case "0":
									token.zeroPad = (flags["-"]) ? false : true;
									break;
								case "-":
									token.rightJustify = true;
									token.zeroPad = false;
									break;
								case "\#":
									token.alternative = true;
									break;
								default:
									throw Error("bad formatting flag '" + token.flags.charAt(fi) + "'");
							}
						}

						token.minWidth = (token._minWidth) ? parseInt(token._minWidth) : 0;
						token.maxWidth = -1;
						token.toUpper = false;
						token.isUnsigned = false;
						token.isInt = false;
						token.isDouble = false;
						token.precision = 1;
						if(token.period == '.'){
							if(token._precision){
								token.precision = parseInt(token._precision);
							}else{
								token.precision = 0;
							}
						}

						var mixins = this._specifiers[token.specifier];
						if(typeof mixins == "undefined"){
							throw new Error("unexpected specifier '" + token.specifier + "'");
						}
						if(mixins.extend){
							lang.mixin(mixins, this._specifiers[mixins.extend]);
							delete mixins.extend;
						}
						lang.mixin(token, mixins);
					}

					if(typeof token.setArg == "function"){
						token.setArg(token);
					}

					if(typeof token.setMaxWidth == "function"){
						token.setMaxWidth(token);
					}

					if(token._minWidth == "*"){
						if(this._mapped){
							throw new Error("* width not supported in mapped formats");
						}
						token.minWidth = parseInt(arguments[position++]);
						if(isNaN(token.minWidth)){
							throw new Error("the argument for * width at position " + position + " is not a number in " + this._format);
						}
						// negative width means rightJustify
						if (token.minWidth < 0) {
							token.rightJustify = true;
							token.minWidth = -token.minWidth;
						}
					}

					if(token._precision == "*" && token.period == "."){
						if(this._mapped){
							throw new Error("* precision not supported in mapped formats");
						}
						token.precision = parseInt(arguments[position++]);
						if(isNaN(token.precision)){
							throw Error("the argument for * precision at position " + position + " is not a number in " + this._format);
						}
						// negative precision means unspecified
						if (token.precision < 0) {
							token.precision = 1;
							token.period = '';
						}
					}

					if(token.isInt){
						// a specified precision means no zero padding
						if(token.period == '.'){
							token.zeroPad = false;
						}
						this.formatInt(token);
					}else if(token.isDouble){
						if(token.period != '.'){
							token.precision = 6;
						}
						this.formatDouble(token);
					}
					this.fitField(token);

					str += "" + token.arg;
				}
			}

			return str;
		},
		_zeros10: '0000000000',
		_spaces10: '          ',
		formatInt: function(token) {
			var i = parseInt(token.arg);
			if(!isFinite(i)){ // isNaN(f) || f == Number.POSITIVE_INFINITY || f == Number.NEGATIVE_INFINITY)
				// allow this only if arg is number
				if(typeof token.arg != "number"){
					throw new Error("format argument '" + token.arg + "' not an integer; parseInt returned " + i);
				}
				//return '' + i;
				i = 0;
			}

			// if not base 10, make negatives be positive
			// otherwise, (-10).toString(16) is '-a' instead of 'fffffff6'
			if(i < 0 && (token.isUnsigned || token.base != 10)){
				i = 0xffffffff + i + 1;
			}

			if(i < 0){
				token.arg = (- i).toString(token.base);
				this.zeroPad(token);
				token.arg = "-" + token.arg;
			}else{
				token.arg = i.toString(token.base);
				// need to make sure that argument 0 with precision==0 is formatted as ''
				if(!i && !token.precision){
					token.arg = "";
				}else{
					this.zeroPad(token);
				}
				if(token.sign){
					token.arg = token.sign + token.arg;
				}
			}
			if(token.base == 16){
				if(token.alternative){
					token.arg = '0x' + token.arg;
				}
				token.arg = token.toUpper ? token.arg.toUpperCase() : token.arg.toLowerCase();
			}
			if(token.base == 8){
				if(token.alternative && token.arg.charAt(0) != '0'){
					token.arg = '0' + token.arg;
				}
			}
		},
		formatDouble: function(token) {
			var f = parseFloat(token.arg);
			if(!isFinite(f)){ // isNaN(f) || f == Number.POSITIVE_INFINITY || f == Number.NEGATIVE_INFINITY)
				// allow this only if arg is number
				if(typeof token.arg != "number"){
					throw new Error("format argument '" + token.arg + "' not a float; parseFloat returned " + f);
				}
				// C99 says that for 'f':
				//	 infinity -> '[-]inf' or '[-]infinity' ('[-]INF' or '[-]INFINITY' for 'F')
				//	 NaN -> a string  starting with 'nan' ('NAN' for 'F')
				// this is not commonly implemented though.
				//return '' + f;
				f = 0;
			}

			switch(token.doubleNotation) {
				case 'e': {
					token.arg = f.toExponential(token.precision);
					break;
				}
				case 'f': {
					token.arg = f.toFixed(token.precision);
					break;
				}
				case 'g': {
					// C says use 'e' notation if exponent is < -4 or is >= prec
					// ECMAScript for toPrecision says use exponential notation if exponent is >= prec,
					// though step 17 of toPrecision indicates a test for < -6 to force exponential.
					if(Math.abs(f) < 0.0001){
						//print("forcing exponential notation for f=" + f);
						token.arg = f.toExponential(token.precision > 0 ? token.precision - 1 : token.precision);
					}else{
						token.arg = f.toPrecision(token.precision);
					}

					// In C, unlike 'f', 'gG' removes trailing 0s from fractional part, unless alternative format flag ("#").
					// But ECMAScript formats toPrecision as 0.00100000. So remove trailing 0s.
					if(!token.alternative){
						//print("replacing trailing 0 in '" + s + "'");
						token.arg = token.arg.replace(/(\..*[^0])0*/, "$1");
						// if fractional part is entirely 0, remove it and decimal point
						token.arg = token.arg.replace(/\.0*e/, 'e').replace(/\.0$/,'');
					}
					break;
				}
				default: throw new Error("unexpected double notation '" + token.doubleNotation + "'");
			}

			// C says that exponent must have at least two digits.
			// But ECMAScript does not; toExponential results in things like "1.000000e-8" and "1.000000e+8".
			// Note that s.replace(/e([\+\-])(\d)/, "e$10$2") won't work because of the "$10" instead of "$1".
			// And replace(re, func) isn't supported on IE50 or Safari1.
			token.arg = token.arg.replace(/e\+(\d)$/, "e+0$1").replace(/e\-(\d)$/, "e-0$1");

			// Ensure a '0' before the period.
			// Opera implements (0.001).toString() as '0.001', but (0.001).toFixed(1) is '.001'
			if(has("opera")){
				token.arg = token.arg.replace(/^\./, '0.');
			}

			// if alt, ensure a decimal point
			if(token.alternative){
				token.arg = token.arg.replace(/^(\d+)$/,"$1.");
				token.arg = token.arg.replace(/^(\d+)e/,"$1.e");
			}

			if(f >= 0 && token.sign){
				token.arg = token.sign + token.arg;
			}

			token.arg = token.toUpper ? token.arg.toUpperCase() : token.arg.toLowerCase();
		},
		zeroPad: function(token, /*Int*/ length) {
			length = (arguments.length == 2) ? length : token.precision;
			if(typeof token.arg != "string"){
				token.arg = "" + token.arg;
			}

			var tenless = length - 10;
			while(token.arg.length < tenless){
				token.arg = (token.rightJustify) ? token.arg + this._zeros10 : this._zeros10 + token.arg;
			}
			var pad = length - token.arg.length;
			token.arg = (token.rightJustify) ? token.arg + this._zeros10.substring(0, pad) : this._zeros10.substring(0, pad) + token.arg;
		},
		fitField: function(token) {
			if(token.maxWidth >= 0 && token.arg.length > token.maxWidth){
				return token.arg.substring(0, token.maxWidth);
			}
			if(token.zeroPad){
				this.zeroPad(token, token.minWidth);
				return;
			}
			this.spacePad(token);
		},
		spacePad: function(token, /*Int*/ length) {
			length = (arguments.length == 2) ? length : token.minWidth;
			if(typeof token.arg != 'string'){
				token.arg = '' + token.arg;
			}

			var tenless = length - 10;
			while(token.arg.length < tenless){
				token.arg = (token.rightJustify) ? token.arg + this._spaces10 : this._spaces10 + token.arg;
			}
			var pad = length - token.arg.length;
			token.arg = (token.rightJustify) ? token.arg + this._spaces10.substring(0, pad) : this._spaces10.substring(0, pad) + token.arg;
		}
	});
	return strLib.sprintf;
});


text:
<?php

namespace Google\AdsApi\AdWords\v201702\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class BiddingStrategyType
{
    const BUDGET_OPTIMIZER = 'BUDGET_OPTIMIZER';
    const CONVERSION_OPTIMIZER = 'CONVERSION_OPTIMIZER';
    const MANUAL_CPC = 'MANUAL_CPC';
    const MANUAL_CPM = 'MANUAL_CPM';
    const PAGE_ONE_PROMOTED = 'PAGE_ONE_PROMOTED';
    const TARGET_SPEND = 'TARGET_SPEND';
    const ENHANCED_CPC = 'ENHANCED_CPC';
    const TARGET_CPA = 'TARGET_CPA';
    const TARGET_ROAS = 'TARGET_ROAS';
    const TARGET_OUTRANK_SHARE = 'TARGET_OUTRANK_SHARE';
    const NONE = 'NONE';
    const UNKNOWN = 'UNKNOWN';

}


text:
<!DOCTYPE html>

    <title>Multiple Lists</title>
    <link href="list.css" rel="stylesheet" />

Compatible Lists

{{models[0].name}}

{{item.name}}

{{models[1].name}}

{{item.name}}

Json model

{{json}}

Incompatible Lists

{{models[0].name}}

{{item.name}}

{{models[1].name}}

{{item.name}}

Json model

{{json}}

One-way Lists

{{models[0].name}}

{{item.name}}

{{models[1].name}}

{{item.name}}

Json model

{{json}}

Mirrored List

List A

{{item.name}}

List A

{{item.name}}

Json model

{{json}}

Lists on Isolated Scopes (nested under parent ng-repeat)

{{model.name}}

{{item.name}}

Json model

{{model.items | json}}

Lists on Isolated Scopes (in separate controllers)

List A

{{item.name}}

Json model

{{model.items | json}}

List B

{{item.name}}

Json model

{{model.items | json}}

Lists on Isolated Scopes (in separate modules)

List A

{{item.name}}

Json model

{{model.items | json}}

List B

{{item.name}}

Json model

{{model.items | json}}


text:
  Mont-Louis est
       un village
       situé dans le département des Pyrénées-Orientales en Languedoc-Roussillon. Elle comptait 292 habitants en 2008.

Si vous pensez emmenager à Mont-Louis, vous pourrez facilement trouver une maison à vendre.

À proximité de Mont-Louis sont localisées les communes de
La Cabanasse localisée à 0 km, 756 habitants,
Eyne située à 4 km, 164 habitants,
Fontpédrouse à 4 km, 118 habitants,
Bolquère à 3 km, 808 habitants,
Saint-Pierre-dels-Forcats localisée à 1 km, 233 habitants,
Font-Romeu-Odeillo-Via à 6 km, 1 995 habitants,
 entre autres. De plus, Mont-Louis est située à seulement 27 km de Prades.

Le nombre d'habitations, à Mont-Louis, se décomposait en 2011 en 161 appartements et 62 maisons soit
une nette domination des appartements.

La commune offre de multiples  équipements sportifs, elle propose entre autres un terrain de tennis et trois boucles de randonnée.


text:
SUITE(framework_serializable_streams_bit_stream_hpp)
{
    TEST(BasicRead)
    {
        using namespace framework::serializable;

        inline_object <
            value <NAME("Field 1"), big_endian <uint32_t>>,
            value <NAME("Field 2"), uint8_t>,
            value <NAME("Field 3"), big_endian <uint16_t>>,
            value <NAME("Field 4"), unsigned char>
        > in {1, 2, 3, 4}, out;

        std::stringstream ss;
        bit_stream <std::stringstream, uint8_t> bs(ss);

        CHECK(write(in, ss));
        CHECK(read(bs, out));
        CHECK(in == out);
    }

    TEST(BasicWrite)
    {
        using namespace framework::serializable;

        inline_object <
            value <NAME("Field 1"), big_endian <uint32_t>>,
            value <NAME("Field 2"), uint8_t>,
            value <NAME("Field 3"), big_endian <uint16_t>>,
            value <NAME("Field 4"), uint8_t>
        > in {1, 2, 3, 4}, out;

        std::stringstream ss;
        bit_stream <std::stringstream, uint8_t> bs(ss);

        CHECK(write(in, bs));
        CHECK(bs.flush());
        CHECK(read(ss, out));
        CHECK(in == out);
    }
}


text:
using System;
using Ceen.Database;

namespace Ceen.PaaS.Database
{
    /// <summary>
    /// User groups
    /// </summary>
    public class UserGroup
    {
        /// <summary>
        /// The group ID
        /// </summary>
        [PrimaryKey]
        public string ID;

        /// <summary>
        /// The group name
        /// </summary>
        public string Name;

        /// <summary>
        /// The time the group was created
        /// </summary>
        [CreatedTimestamp]
        public DateTime Created;
    }

    /// <summary>
    /// A cross table with users
    /// </summary>
    public class UserGroupIndex
    {
        /// <summary>
        /// The group
        /// </summary>
        [Unique("Q")]
        public string GroupID;
        /// <summary>
        /// The user
        /// </summary>
        [Unique("Q")]
        public string UserID;
    }
}


text:
Estimating Distribution Parameters
===============

Overview
---------------

This program will be autograded.  That means that it's important to
not change function names and to not add additional functionality that
may improve the program but produce different results.  Make sure that
your unit tests pass.  This what a successful set of unit tests will
look like:

    $ python3 tests.py
    .....
    ----------------------------------------------------------------------
    Ran 5 tests in 0.002s

    OK

Districts (10 points)
----------------------------

In the US, our legislature is made up of representatives of individual
*districts* (unlike proportional representation systems).  Your task
is to characterize districts in "Red" Republican states vs. districts
in "Blue" Democratic states.

First, you'll need to extract the Republican share of the vote in a
district.  Then, you will need to compute the parameters of a Gaussian
distribution, then compute the probability of an observation given
those parameters.

You will need to implement the following functions:
* ml_mean
* ml_variance
* log_probability
* republican_share

After you've done that, the main function will then report for each of
Colorado's district whether it looks more like a red state or a blue state.

Words Presidents Use (20 points)
-------------------------------

Each year, the president of the United States is required to make a
speech to congress describing the "State of the Union".  We are going
to create a simple *bigram language model* with *add one (Laplace)*
smoothing.  Your task is to characterize Republican vs. Democrat
presidents based on their speech.

To do this, you'll need to implement the following functions:
* train_seen
* generate
* laplace
* add_train
* log_likelihood

The generate function is a little different from the other functions.
Here, you actually need to sample from a conditional distribution.
This will be random (it will give different results if you call
it multiple times).  Thus, it's hard to write effective unit tests for
it.

We discussed sampling from a single multinomial distribution in
class.  This requires computing a random number and then selecting the
cummulative multinomial bin larger than the random number.  Here
you'll do it over an over again to generate a reasonable looking
sentence.

First, you'll generate a word given a specified context.  Let's
pretend we start with the start tag.  The start tag has a distribution
over its next words (this is what you're estimating using the Laplace
function).  You need to sample from that estimated multinomial
distribution.  You've now generated a word.  You'll keep doing that
for a specified number of times (or until you generate an end sentence
tag).  This is also true of unseen contexts, in which case the
distribution is just the uniform distribution.

WARNING: Writing a unit test for generation is tricky (without
creating a testing stub for the random number generator), so make sure
you are thorough in making sure this works correctly.

The first few lines of your output file will look something like:

	Trained language model for D
	Done looking at R words, finalizing vocabulary
	Trained language model for R
	REP		DEM		Sentence
	================================================================================
	-5.555665	-5.901752	Mr. Speaker, Mr. Vice President, Members of Congress, my fellow Americans:
	-6.474396	-6.601745	And for this final one, I'm going to try to make it a little shorter.
	-5.409701	-5.095949	I've been there.
	-6.723085	-6.627878	And I understand that because it's an election season, expectations for what we will achieve this year are low.
	-6.920930	-7.094266	But, Mr. Speaker, I appreciate the constructive approach that you and the other leaders took at the end of last year to pass a 		budget and make tax cuts permanent for working families.
	-7.753715	-7.508743	So, who knows, we might surprise the cynics again.
	-6.370917	-6.343508	But tonight, I want to go easy on the traditional list of proposals for the year ahead.
	-6.160787	-6.262366	And I will keep pushing for progress on the work that I believe still needs to be done.
	-7.437942	-7.276854	Fixing a broken immigration system.

Writeup (10 points)
-----------------------

Finally, include a brief plain-text file (not PDF, not Word, just a
plain ASCII text file) that:
* Describes your approach
* Describes whether Colorado's congression districts look more like
  the congressional districts of states that Obama won or that Romeny
  won
* Plot a
  [histogram](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html)
  of both the Obama and Romney states.  Is it resonable to assume that
  these are a normal distribution?
* Gives an interesting example of a *word* that Obama said that no
  previous president said
* Gives an interesting example of a *bigram* that Obama said that no
  previous president said
* Generates a random sentence from a Republican and a Democrat.

Submitting Your Code
-----------------------

You'll need to submit your assignment (lm.py, districts.py,
histogram.png, and writeup.txt) on Moodle as an upload.


text:
{-|
Module      : Control.Monad.Bayes.Prior
Description : Probability monad that ignores conditioning
Copyright   : (c) Adam Scibior, 2016
License     : MIT
Maintainer  : ams240@cam.ac.uk
Stability   : experimental
Portability : GHC

-}

module Control.Monad.Bayes.Prior (
    Prior,
    prior,
    hoist
              ) where

import Control.Monad.Trans
import Control.Monad.Trans.Identity

import Control.Monad.Bayes.Class

-- | A simple wrapper around 'MonadDist' types that discards conditoning.
newtype Prior m a = Prior {runPrior :: IdentityT m a}
    deriving(Functor, Applicative, Monad, MonadTrans, MonadIO)

type instance CustomReal (Prior m) = CustomReal m

instance MonadDist m => MonadDist (Prior m) where
  primitive = lift . primitive

instance MonadDist m => MonadBayes (Prior m) where
    factor _ = return ()

-- | Discard conditioning and just use the prior.
prior :: Prior m a -> m a
prior = runIdentityT . runPrior

-- | Apply a transformation to the inner monad.
hoist :: (forall x. m x -> n x) -> Prior m a -> Prior n a
hoist f = Prior . IdentityT . f . runIdentityT . runPrior


text:
package org.apache.commons.jcs.admin.servlet;

import java.io.IOException;

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

import org.apache.commons.jcs.admin.JCSAdminBean;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

/**
 * A servlet which provides HTTP access to JCS. Allows a summary of regions to
 * be viewed, and removeAll to be run on individual regions or all regions. Also
 * provides the ability to remove items (any number of key arguments can be
 * provided with action 'remove'). Should be initialized with a properties file
 * that provides at least a classpath resource loader. Since this extends
 * VelocityServlet, which uses the singleton model for velocity, it will share
 * configuration with any other Velocity in the same JVM.
 *

 * Initialization in a webapp will look something like this:
 *

 *
 *

 *
 *    [servlet]
 *        [servlet-name]JCSAdminServlet[/servlet-name]
 *        [servlet-class]org.apache.commons.jcs.admin.servlet.JCSAdminServlet[/servlet-class]
 *        [init-param]
 *            [param-name]properties[/param-name]
 *            [param-value]WEB-INF/conf/JCSAdminServlet.velocity.properties[/param-value]
 *        [/init-param]
 *    [/servlet]
 *
 *

 *
 *

 * FIXME: It would be nice to use the VelocityEngine model so this can be truly
 * standalone. Right now if you run it in the same container as, say, turbine,
 * turbine must be run first to ensure it's config takes precedence.
 *

 */
public class JCSAdminServlet
    extends VelocityViewServlet
{
    private static final long serialVersionUID = -5519844149238645275L;

    private static final String DEFAULT_TEMPLATE_NAME = "/org/apache/jcs/admin/servlet/JCSAdminServletDefault.vm";

    private static final String REGION_DETAIL_TEMPLATE_NAME = "/org/apache/jcs/admin/servlet/JCSAdminServletRegionDetail.vm";

    // Keys for parameters

    private static final String CACHE_NAME_PARAM = "cacheName";

    private static final String ACTION_PARAM = "action";

    private static final String KEY_PARAM = "key";

    private static final String SILENT_PARAM = "silent";

    // Possible values for 'action' parameter

    private static final String CLEAR_ALL_REGIONS_ACTION = "clearAllRegions";

    private static final String CLEAR_REGION_ACTION = "clearRegion";

    private static final String REMOVE_ACTION = "remove";

    private static final String DETAIL_ACTION = "detail";

    /**
     * Velocity based admin servlet.
     *

     * @param request
     * @param response
     * @param context
     * @return Template
     * @throws Exception
     *
     */
    @Override
    protected Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context context )
    {
        JCSAdminBean admin = new JCSAdminBean();

        String templateName = DEFAULT_TEMPLATE_NAME;

        // Get cacheName for actions from request (might be null)

        String cacheName = request.getParameter( CACHE_NAME_PARAM );

        // If an action was provided, handle it

        String action = request.getParameter( ACTION_PARAM );

        try
        {
			if ( action != null )
			{
			    if ( action.equals( CLEAR_ALL_REGIONS_ACTION ) )
			    {
			        admin.clearAllRegions();
			    }
			    else if ( action.equals( CLEAR_REGION_ACTION ) )
			    {
			        if ( cacheName != null )
			        {
			            admin.clearRegion( cacheName );
			        }
			    }
			    else if ( action.equals( REMOVE_ACTION ) )
			    {
			        String[] keys = request.getParameterValues( KEY_PARAM );

			        for ( int i = 0; i < keys.length; i++ )
			        {
			            admin.removeItem( cacheName, keys[i] );
			        }

			        templateName = REGION_DETAIL_TEMPLATE_NAME;
			    }
			    else if ( action.equals( DETAIL_ACTION ) )
			    {
			        templateName = REGION_DETAIL_TEMPLATE_NAME;
			    }
			}
		}
        catch (IOException e)
        {
        	getLog().error("Could not execute action.", e);
        	return null;
		}

        if ( request.getParameter( SILENT_PARAM ) != null )
        {
            // If silent parameter was passed, no output should be produced.

            return null;
        }
        // Populate the context based on the template

        try
        {
			if ( templateName == REGION_DETAIL_TEMPLATE_NAME )
			{
			    context.put( "cacheName", cacheName );
			    context.put( "elementInfoRecords", admin.buildElementInfo( cacheName ) );
			}
			else if ( templateName == DEFAULT_TEMPLATE_NAME )
			{
			    context.put( "cacheInfoRecords", admin.buildCacheInfo() );
			}
		}
        catch (Exception e)
        {
        	getLog().error("Could not populate context.", e);
		}

        return getTemplate( templateName );
    }
}


text:
package querytest

import (
	"github.com/influxdata/flux/plan"
	"github.com/influxdata/flux/stdlib/influxdata/influxdb/v1"
	"github.com/influxdata/influxdb/query/influxql"
	"github.com/influxdata/influxdb/query/stdlib/influxdata/influxdb"
)

// MakeFromInfluxJSONCompiler returns a compiler that replaces all From operations with FromJSON.
func MakeFromInfluxJSONCompiler(c *influxql.Compiler, jsonFile string) {
	c.WithLogicalPlannerOptions(plan.AddLogicalRules(ReplaceFromRule{Filename: jsonFile}))
}

type ReplaceFromRule struct {
	Filename string
}

func (ReplaceFromRule) Name() string {
	return "ReplaceFromRule"
}

func (ReplaceFromRule) Pattern() plan.Pattern {
	return plan.Pat(influxdb.FromKind)
}

func (r ReplaceFromRule) Rewrite(n plan.Node) (plan.Node, bool, error) {
	if err := n.ReplaceSpec(&v1.FromInfluxJSONProcedureSpec{
		File: r.Filename,
	}); err != nil {
		return nil, false, err
	}
	return n, true, nil
}


text:
<?php

namespace PHPCompatibility\Sniffs\Syntax;

use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;

/**
 * Detect use of short array syntax which is available since PHP 5.4.
 *
 * PHP version 5.4
 *
 * @link https://wiki.php.net/rfc/shortsyntaxforarrays
 * @link https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax
 *
 * @since 7.0.0
 * @since 9.0.0 Renamed from `ShortArraySniff` to `NewShortArraySniff`.
 */
class NewShortArraySniff extends Sniff
{

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @since 7.0.0
     *
     * @return array
     */
    public function register()
    {
        return array(
            \T_OPEN_SHORT_ARRAY,
            \T_CLOSE_SHORT_ARRAY,
        );
    }

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @since 7.0.0
     *
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
     * @param int                   $stackPtr  The position of the current token in
     *                                         the stack passed in $tokens.
     *
     * @return void
     */
    public function process(File $phpcsFile, $stackPtr)
    {
        if ($this->supportsBelow('5.3') === false) {
            return;
        }

        $tokens = $phpcsFile->getTokens();
        $token  = $tokens[$stackPtr];

        $error = '%s is not supported in PHP 5.3 or lower';
        $data  = array();

        if ($token['type'] === 'T_OPEN_SHORT_ARRAY') {
            $data[] = 'Short array syntax (open)';
        } elseif ($token['type'] === 'T_CLOSE_SHORT_ARRAY') {
            $data[] = 'Short array syntax (close)';
        }

        $phpcsFile->addError($error, $stackPtr, 'Found', $data);
    }
}


text:
class TTree;

class TTreeSRedirector;
class AliExternalTrackParam;
class AliTPCtrackerSector;
class AliToyMCEvent;
class AliTPCCorrection;
class AliTPCseed;
class AliTPCtrackerRow;
class AliToyMCTrack;
class AliTPCclusterMI;
class AliRieman;
class AliTrackPoint;
class AliTPCParam;

class AliToyMCReconstruction : public TObject {
public:
  AliToyMCReconstruction();
  virtual ~AliToyMCReconstruction();

  enum ECorrType {
    kNoCorrection = 0,
    kTPCCenter,
    kAverageEta,
    kIdeal,
    kPreliminaryEta // NOT TO USE (needs fixing!!! Not yet in full code!!!)
  };

  enum EDet {
    kITS=0,
    kTPC,
    kTRD
  };

  enum ERecoFill {
    kFillSeed = 0x01,
    kFillOrig = 0x02,
    kFillTrack= 0x04,

    kFillITS  = 0x08,
    kFillITS1 = 0x10,
    kFillITS2 = 0x20,

    kFillDeltas = 0x40,
    kFillNoTrackInfo= 0x80
  };

  void RunReco(const char* file, Int_t nmaxEv=-1);
  void RunRecoAllClusters(const char* file, Int_t nmaxEv=-1);
  void RunRecoAllClustersStandardTracking(const char* file, Int_t nmaxEv=-1);

  void RunFullTracking(const char* file, Int_t nmaxEv=-1);

  // reconstruction settings
  void      SetRecoSettings(Bool_t idealTracking, Int_t clusterType, ECorrType correctionType, Int_t seedingRow=130, Int_t seedingDist=10)
                           { fIdealTracking=idealTracking; fClusterType=clusterType; fSeedingRow=seedingRow, fSeedingDist=seedingDist, fCorrectionType=correctionType; }

  void      SetClusterType(Int_t type)  { fClusterType = type;    }
  Int_t     GetClusterType()  const     { return fClusterType;    }

  void      SetSeedingRow(Int_t row)    { fSeedingRow = row;      }
  Int_t     GetSeedingRow()  const      { return fSeedingRow;     }

  void      SetSeedingDist(Int_t dist)  { fSeedingDist = dist;    }
  Int_t     GetSeedingDist()  const     { return fSeedingDist;    }

  void      SetCorrType(ECorrType type) { fCorrectionType = type; }
  ECorrType GetCorrectionType() const   { return fCorrectionType; }

  void   SetUseMaterialBudget(Bool_t mat) { fUseMaterial = mat;   }
  Bool_t GetUseMaterialBudget() const   { return fUseMaterial;    }

  void   SetIdealTracking(Bool_t tr)    { fIdealTracking = tr;    }
  Bool_t GetIdealTracking()  const      { return fIdealTracking;  }

  void   SetFillClusterRes(Bool_t res)  { fFillClusterRes=res;    }
  Bool_t GetFillClusterRes()  const     { return fFillClusterRes; }

  void   SetUseT0list(Bool_t use)       { fUseT0list=use;    }
  Bool_t GetUseT0list()  const          { return fUseT0list; }

  void   SetUseZ0list(Bool_t use)       { fUseZ0list=use;    }
  Bool_t GetUseZ0list()  const          { return fUseZ0list; }

  void   SetForceAlpha(Bool_t use)       { fForceAlpha=use;    }
  Bool_t GetForceAlpha()  const          { return fForceAlpha; }

  void SetRecoInfo(Long64_t val) { fRecoInfo = val; }
  Long64_t GetRecoInfo() const { return fRecoInfo; }

  void   SetTree(TTree *tree) { fTree=tree; }
  TTree* GetTree() const { return fTree; }

  AliExternalTrackParam* GetSeedFromTrack(const AliToyMCTrack * const tr, Bool_t forceSeed=kFALSE);
  AliExternalTrackParam* GetSeedFromTrackIdeal(const AliToyMCTrack * const tr, EDet det );
  AliExternalTrackParam* GetFittedTrackFromSeed(const AliToyMCTrack *tr, const AliExternalTrackParam *seed, TClonesArray *arrClustRes=0x0);
  AliExternalTrackParam* GetFittedTrackFromSeedAllClusters(const AliToyMCTrack *tr, const AliExternalTrackParam *seed, Int_t &nClus);
  AliExternalTrackParam* GetTrackRefit(const AliToyMCTrack * const tr, EDet det);

  AliToyMCTrack *ConvertTPCSeedToToyMCTrack(const AliTPCseed &seed);
  AliExternalTrackParam* GetRefittedTrack(const AliTPCseed &seed);

  AliTPCclusterMI* FindMiddleCluster(const AliTPCclusterMI *clInner, const AliTPCclusterMI *clOuter,
                                     Double_t roady, Double_t roadz,
                                     AliRieman &seedFit);

  void AddMiddleClusters(AliTPCseed *seed,
                         const AliTPCclusterMI *clInner, const AliTPCclusterMI *clOuter,
                         Double_t roady, Double_t roadz,
                         Int_t &nTotalClusters, AliRieman &seedFit);
  Int_t MakeSeeds2(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2);
  void MakeSeeds(TObjArray * arr, Int_t sec, Int_t i1, Int_t i2);

  void SetRieman(const AliTPCseed &seed, AliRieman &rieman);
  void CopyRieman(const AliRieman &from, AliRieman &to);

  AliExternalTrackParam* ClusterToTrackAssociation(const AliTPCseed *seed, Int_t trackID, Int_t &nClus);
  void ClusterToTrackAssociation(AliTPCseed &seed);
  void AssociateClusters(AliTPCseed &seed, Int_t firstRow, Int_t lastRow, Bool_t direction);

  void InitSpaceCharge();

  void SetLongT0seed(Bool_t l) { fLongT0seed=l; }
  Bool_t GetLongT0seed() const { return fLongT0seed; }

  static TTree* ConnectTrees(const char* files);

  Double_t GetVDrift() const;
  Double_t GetZLength(Int_t roc) const;

  void InitStreamer(TString addName, Int_t level=1);

  void ConnectInputFile(const char* file, Int_t nmaxEv=-1);
  void Cleanup();

  void DumpTracksToTree(const char* file);

 private:
  AliToyMCReconstruction(const AliToyMCReconstruction &rec);
  AliToyMCReconstruction& operator= (AliToyMCReconstruction& rec);

  void SetTrackPointFromCluster(const AliTPCclusterMI *cl, AliTrackPoint &p);
  void ClusterToSpacePoint(const AliTPCclusterMI *cl, Float_t xyz[3]);

  Int_t LoadInnerSectors();
  Int_t LoadOuterSectors();

  Int_t GetSector(AliExternalTrackParam *track);
  void FillSectorStructure(Int_t maxev);
  void FillSectorStructureAC();

  void SetupTrackMaps();

  void CookLabel(AliTPCseed *seed, Double_t fraction, Int_t info[5]=0);

  void DumpSeedInfo(TObjArray *arr);
  void DumpTrackInfo(TObjArray *arr);
  void DumpSeedInfo(const AliToyMCTrack *toyTrack, AliTPCseed *seed);

  void MarkClustersUsed(AliTPCseed *seed);
  void ResetClustersZtoTime(AliTPCseed *seed);

  Float_t FindClosestT0(const TVectorF &t0list, const TVectorF &z0list, AliExternalTrackParam &t0seed);

  // reco settings
  Int_t  fSeedingRow;            // first row used for seeding
  Int_t  fSeedingDist;           // distance of seeds
  Int_t  fClusterType;           // cluster type to use
  ECorrType fCorrectionType;     // type of space point correction
  Bool_t fDoTrackFit;            // do track fitting
  Bool_t fUseMaterial;           // use material budget in tracking
  Bool_t fIdealTracking;         // use ideal coordinates for tracking

  Int_t  fNmaxEvents;            // maximum number of events

  // current reconstruction info
  Double_t fTime0;               // current time0 used for reconstruction
  Bool_t   fCreateT0seed;        // if current seed is the T0 seed
  Bool_t   fLongT0seed;          // if we should use a t0 seed including all clusters in the seed range
  Bool_t   fFillClusterRes;      // fill cluster residuals?
  Bool_t   fUseT0list;           // if the list of T0 information should be used to guess the T0
  Bool_t   fUseZ0list;           // if the list of Z vertex information should be used to guess the T0
  Bool_t   fForceAlpha;          // force the correct alpha for the t0 seed extrapolation
  Long64_t fRecoInfo;            // what information to fill in the output trees

  TTreeSRedirector *fStreamer;   // debug streamer
  TFile *fInputFile;             // input file
  TTree *fTree;                  // input tree with ToyMC info
  AliToyMCEvent *fEvent;         // input event

  AliTPCParam *fTPCParam;            // tpc reco parameters
  AliTPCCorrection *fTPCCorrection; // space charge

  const Int_t fkNSectorInner;        //number of inner sectors
  AliTPCtrackerSector *fInnerSectorArray;  //array of inner sectors
  const Int_t fkNSectorOuter;        //number of outer sectors
  AliTPCtrackerSector *fOuterSectorArray;  //array of outer sectors

  TClonesArray fAllClusters;     //Array keeping all clusters for free seeding

  TExMap fMapTrackEvent;          // map global track number -> event number
  TExMap fMapTrackTrackInEvent;   // map global track number -> track in event

  THn    *fHnDelta;               // histogram with residuals

  Bool_t fIsAC;                     // if we are tracking with sector arrays running from 0-36 rather than 0-18

  ClassDef(AliToyMCReconstruction,0)
};

#endif


text:
<?php

namespace yii\validators;

use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;

/**
 * RangeValidator validates that the attribute value is among a list of values.
 *
 * The range can be specified via the [[range]] property.
 * If the [[not]] property is set true, the validator will ensure the attribute value
 * is NOT among the specified range.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class RangeValidator extends Validator
{
    /**
     * @var array|\Traversable|\Closure a list of valid values that the attribute value should be among or an anonymous function that returns
     * such a list. The signature of the anonymous function should be as follows,
     *
     * ```php
     * function($model, $attribute) {
     *     // compute range
     *     return $range;
     * }
     * ```
     */
    public $range;
    /**
     * @var bool whether the comparison is strict (both type and value must be the same)
     */
    public $strict = false;
    /**
     * @var bool whether to invert the validation logic. Defaults to false. If set to true,
     * the attribute value should NOT be among the list of values defined via [[range]].
     */
    public $not = false;
    /**
     * @var bool whether to allow array type attribute.
     */
    public $allowArray = false;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if (!is_array($this->range)
            && !($this->range instanceof \Closure)
            && !($this->range instanceof \Traversable)
        ) {
            throw new InvalidConfigException('The "range" property must be set.');
        }
        if ($this->message === null) {
            $this->message = Yii::t('yii', '{attribute} is invalid.');
        }
    }

    /**
     * @inheritdoc
     */
    protected function validateValue($value)
    {
        $in = false;

        if ($this->allowArray
            && ($value instanceof \Traversable || is_array($value))
            && ArrayHelper::isSubset($value, $this->range, $this->strict)
        ) {
            $in = true;
        }

        if (!$in && ArrayHelper::isIn($value, $this->range, $this->strict)) {
            $in = true;
        }

        return $this->not !== $in ? null : [$this->message, []];
    }

    /**
     * @inheritdoc
     */
    public function validateAttribute($model, $attribute)
    {
        if ($this->range instanceof \Closure) {
            $this->range = call_user_func($this->range, $model, $attribute);
        }
        parent::validateAttribute($model, $attribute);
    }

    /**
     * @inheritdoc
     */
    public function clientValidateAttribute($model, $attribute, $view)
    {
        if ($this->range instanceof \Closure) {
            $this->range = call_user_func($this->range, $model, $attribute);
        }

        $range = [];
        foreach ($this->range as $value) {
            $range[] = (string) $value;
        }
        $options = [
            'range' => $range,
            'not' => $this->not,
            'message' => Yii::$app->getI18n()->format($this->message, [
                'attribute' => $model->getAttributeLabel($attribute),
            ], Yii::$app->language),
        ];
        if ($this->skipOnEmpty) {
            $options['skipOnEmpty'] = 1;
        }
        if ($this->allowArray) {
            $options['allowArray'] = 1;
        }

        ValidationAsset::register($view);

        return 'yii.validation.range(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
    }
}


text:
package jp.teraparser.parser;

import jp.teraparser.model.Sentence;
import jp.teraparser.transition.Oracle;
import jp.teraparser.transition.State;
import jp.teraparser.util.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * jp.teraparser.parser
 *
 * @author Hiroki Teranishi
 */
public class BeamSearchDecoderTest implements BeamSearchDecoder {
    private static final int N_THREADS = 8;
    private static final int ITERATION = 10;
    private static final int BEAMWIDTH = 16;

    private ExecutorService executor;
    private Oracle oracle;
    private Perceptron classifier;
    private int iteration;
    private int beamWidth;
    private Sentence sentence;

    @Before
    public void setUp() {
        executor = Executors.newFixedThreadPool(N_THREADS);
        oracle = new Oracle(Oracle.Algorithm.STATIC);
        classifier = new Perceptron();
        iteration = ITERATION;
        beamWidth = BEAMWIDTH;
        sentence = TestUtils.getSampleSentence();
        System.out.println("Sample sentence: " + sentence);
    }

    @After
    public void tearDown() throws Exception {
        executor.shutdownNow();
    }

    @Test
    public void multithreadTest() {
        CompletionService<List<BeamItem>> completionService = new ExecutorCompletionService<>(executor);
        for (int i = 0; i < iteration; i ++) {
            trainEachWithEarlyUpdate(sentence, completionService);
        }
    }

    private void trainEachWithEarlyUpdate(Sentence sentence, CompletionService<List<BeamItem>> completionService) {
        State.StateIterator iterator = oracle.getState(sentence).getIterator();
        State oracleState = iterator.next(); // initial state
        List<BeamItem> beam = new ArrayList<>(1);
        beam.add(new BeamItem(new State(sentence), 0.0));

        boolean terminate = false;
        while (!terminate) {
            oracleState = iterator.next();
            beam = getNextBeamItems(beam, beamWidth, classifier, completionService);
            terminate = beam.stream().allMatch(item -> item.getState().isTerminal());

            final State finalOracleState = oracleState; // make a variable final to use it in lambda
            beam.stream().forEach(item -> {
                if (item.getState().equals(finalOracleState)) {
                    System.out.println("pred.hashCode: " + item.getState().hashCode() + ", oracle.hashCode: " + finalOracleState.hashCode());
                }
            });
            boolean oracleInBeam = beam.stream().anyMatch(item -> item.getState().equals(finalOracleState));;
            if (!oracleInBeam || (!terminate && !iterator.hasNext())) {
                classifier.update(oracleState, beam.get(0).getState()); // early update
                break;
            }
        }
    }

    public List<BeamItem> getNextBeamItems(List<BeamItem> beam, int beamWidth, Perceptron classifier, CompletionService<List<BeamItem>> completionService) {
        try {
            List<BeamItem> items1 = BeamSearchDecoder.super.getNextBeamItems(beam, beamWidth, classifier);
            List<BeamItem> items2 = BeamSearchDecoder.super.getNextBeamItems(beam, beamWidth, classifier, completionService);
            for (int i = 0; i < items1.size(); i++) {
                BeamItem item1 = items1.get(i);
                BeamItem item2 = items2.get(i);
                System.out.println("item1: " + item1.getState() + ": score=" + item1.getScore());
                System.out.println("item2: " + item2.getState() + ": score=" + item2.getScore());
                if (!item1.equals(item2)) {
                    throw new Exception(item1 + " != " + item2);
                }
            }
            System.out.println("========");
            return items2;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}