text:
using namespace rapidjson;

namespace chrono {
namespace sensor {

// -----------------------------------------------------------------------------

void ReadFileJSON(const std::string& filename, Document& d) {
    std::ifstream ifs(filename);
    if (!ifs.good()) {
        GetLog() << "ERROR: Could not open JSON file: " << filename << "\n";
    } else {
        IStreamWrapper isw(ifs);
        d.ParseStream<ParseFlag::kParseCommentsFlag>(isw);
        if (d.IsNull()) {
            GetLog() << "ERROR: Invalid JSON file: " << filename << "\n";
        }
    }
}

// -----------------------------------------------------------------------------

ChVector<> ReadVectorJSON(const Value& a) {
    assert(a.IsArray());
    assert(a.Size() == 3);
    return ChVector<>(a[0u].GetDouble(), a[1u].GetDouble(), a[2u].GetDouble());
}

ChQuaternion<> ReadQuaternionJSON(const Value& a) {
    assert(a.IsArray());
    assert(a.Size() == 4);
    return ChQuaternion<>(a[0u].GetDouble(), a[1u].GetDouble(), a[2u].GetDouble(), a[3u].GetDouble());
}

ChFrame<> ReadFrameJSON(const Value& a) {
    assert(a.HasMember("Location"));
    assert(a.HasMember("Orientation"));
    return ChFrame<>(ReadVectorJSON(a["Location"]), ReadQuaternionJSON(a["Orientation"]));
}

// -----------------------------------------------------------------------------

std::shared_ptr<ChSensor> ReadSensorJSON(const std::string& filename,
                                         std::shared_ptr<chrono::ChBody> parent,
                                         chrono::ChFrame<double> offsetPose) {
    std::shared_ptr<ChSensor> sensor;

    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string sensor_type = d["Template"].GetString();

    // Create the sensor using the appropriate template.
    if (sensor_type.compare("Camera") == 0) {
        sensor = ReadCameraSensorJSON(filename, parent, offsetPose);
    } else if (sensor_type.compare("GPS") == 0) {
        sensor = ReadGPSSensorJSON(filename, parent, offsetPose);
    } else if (sensor_type.compare("Accelerometer") == 0) {
        sensor = ReadAccelerometerSensorJSON(filename, parent, offsetPose);
    } else if (sensor_type.compare("Gyroscope") == 0) {
        sensor = ReadGyroscopeSensorJSON(filename, parent, offsetPose);
    } else if (sensor_type.compare("Magnetometer") == 0) {
        sensor = ReadMagnetometerSensorJSON(filename, parent, offsetPose);
    } else if (sensor_type.compare("Lidar") == 0) {
        sensor = ReadLidarSensorJSON(filename, parent, offsetPose);
    } else {
        throw ChException("Sensor type of " + sensor_type + " not supported in ReadSensorJSON.");
    }

    return sensor;
}

std::shared_ptr<ChCameraSensor> ReadCameraSensorJSON(const std::string& filename,
                                                     std::shared_ptr<chrono::ChBody> parent,
                                                     chrono::ChFrame<double> offsetPose) {
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string subtype = d["Template"].GetString();
    if (subtype.compare("Camera") != 0) {
        throw ChException("ChUtilsJSON::ReadCameraSensorJSON: Sensor type of " + subtype + " must be Camera.");
    }

    // Read sensor properties
    assert(d.HasMember("Properties"));
    const Value& properties = d["Properties"];

    // Create the camera sensor.
    float updateRate = properties["Update Rate"].GetFloat();
    // ChFrame<> offsetPose = ReadFrameJSON(properties["Offset Pose"]);
    unsigned int w = properties["Width"].GetUint();
    unsigned int h = properties["Height"].GetUint();
    float hFOV = properties["Horizontal Field of View"].GetFloat();
    unsigned int supersample_factor = 1;
    CameraLensModelType lens_model = CameraLensModelType::PINHOLE;

    if (properties.HasMember("Supersample Factor")) {
        supersample_factor = properties["Supersample Factor"].GetInt();
    }
    if (properties.HasMember("Lens Type")) {
        std::string l = properties["Lens Model"].GetString();
        if (l == "FOV_LENS") {
            lens_model = CameraLensModelType::FOV_LENS;
        }
    }

    auto camera = chrono_types::make_shared<ChCameraSensor>(parent, updateRate, offsetPose, w, h, hFOV,
                                                            supersample_factor, lens_model);
    if (properties.HasMember("Lag")) {
        float lag = properties["Lag"].GetFloat();
        camera->SetLag(lag);
    }
    if (properties.HasMember("Exposure Time")) {
        float collection = properties["Exposure Time"].GetFloat();
        camera->SetCollectionWindow(collection);
    }
    return camera;
}

std::shared_ptr<ChGPSSensor> ReadGPSSensorJSON(const std::string& filename,
                                               std::shared_ptr<chrono::ChBody> parent,
                                               chrono::ChFrame<double> offsetPose) {
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string subtype = d["Template"].GetString();
    if (subtype.compare("GPS") != 0) {
        throw ChException("ChUtilsJSON::ReadGPSSensorJSON: Sensor type of " + subtype + " must be GPS.");
    }

    // Read sensor properties
    assert(d.HasMember("Properties"));
    const Value& properties = d["Properties"];

    // Create the gps sensor.
    float updateRate = properties["Update Rate"].GetFloat();
    // ChFrame<> offsetPose = ReadFrameJSON(properties["Offset Pose"]);
    ChVector<> gps_reference = ReadVectorJSON(properties["GPS Reference"]);
    std::shared_ptr<ChNoiseModel> noise_model = CreateNoiseJSON(properties["Noise Model"]);

    auto gps = chrono_types::make_shared<ChGPSSensor>(parent, updateRate, offsetPose, gps_reference, noise_model);
    if (properties.HasMember("Lag")) {
        float lag = properties["Lag"].GetFloat();
        gps->SetLag(lag);
    }
    if (properties.HasMember("Collection Window")) {
        float collection = properties["Collection Window"].GetFloat();
        gps->SetCollectionWindow(collection);
    }

    return gps;
}

std::shared_ptr<ChAccelerometerSensor> ReadAccelerometerSensorJSON(const std::string& filename,
                                                                   std::shared_ptr<chrono::ChBody> parent,
                                                                   chrono::ChFrame<double> offsetPose) {
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string subtype = d["Template"].GetString();
    if (subtype.compare("Accelerometer") != 0) {
        throw ChException("ChUtilsJSON::ReadAccelerometerSensorJSON: Sensor type of " + subtype +
                          " must be Accelerometer.");
    }

    // Read sensor properties
    assert(d.HasMember("Properties"));
    const Value& properties = d["Properties"];

    // Create the gps sensor.
    float updateRate = properties["Update Rate"].GetFloat();
    // ChFrame<> offsetPose = ReadFrameJSON(properties["Offset Pose"]);
    std::shared_ptr<ChNoiseModel> noise_model = CreateNoiseJSON(properties["Noise Model"]);
    auto acc = chrono_types::make_shared<ChAccelerometerSensor>(parent, updateRate, offsetPose, noise_model);

    if (properties.HasMember("Lag")) {
        float lag = properties["Lag"].GetFloat();
        acc->SetLag(lag);
    }
    if (properties.HasMember("Collection Window")) {
        float collection = properties["Collection Window"].GetFloat();
        acc->SetCollectionWindow(collection);
    }
    return acc;
}

std::shared_ptr<ChGyroscopeSensor> ReadGyroscopeSensorJSON(const std::string& filename,
                                                           std::shared_ptr<chrono::ChBody> parent,
                                                           chrono::ChFrame<double> offsetPose) {
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string subtype = d["Template"].GetString();
    if (subtype.compare("Gyroscope") != 0) {
        throw ChException("ChUtilsJSON::ReadGyroscopeSensorJSON: Sensor type of " + subtype + " must be Gyroscope.");
    }

    // Read sensor properties
    assert(d.HasMember("Properties"));
    const Value& properties = d["Properties"];

    // Create the gps sensor.
    float updateRate = properties["Update Rate"].GetFloat();
    // ChFrame<> offsetPose = ReadFrameJSON(properties["Offset Pose"]);
    std::shared_ptr<ChNoiseModel> noise_model = CreateNoiseJSON(properties["Noise Model"]);
    auto gyro = chrono_types::make_shared<ChGyroscopeSensor>(parent, updateRate, offsetPose, noise_model);

    if (properties.HasMember("Lag")) {
        float lag = properties["Lag"].GetFloat();
        gyro->SetLag(lag);
    }
    if (properties.HasMember("Collection Window")) {
        float collection = properties["Collection Window"].GetFloat();
        gyro->SetCollectionWindow(collection);
    }
    return gyro;
}

std::shared_ptr<ChMagnetometerSensor> ReadMagnetometerSensorJSON(const std::string& filename,
                                                                 std::shared_ptr<chrono::ChBody> parent,
                                                                 chrono::ChFrame<double> offsetPose) {
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string subtype = d["Template"].GetString();
    if (subtype.compare("Magnetometer") != 0) {
        throw ChException("ChUtilsJSON::ReadMagnetometerSensorJSON: Sensor type of " + subtype +
                          " must be Magnetometer.");
    }

    // Read sensor properties
    assert(d.HasMember("Properties"));
    const Value& properties = d["Properties"];

    // Create the gps sensor.
    float updateRate = properties["Update Rate"].GetFloat();
    // ChFrame<> offsetPose = ReadFrameJSON(properties["Offset Pose"]);
    std::shared_ptr<ChNoiseModel> noise_model = CreateNoiseJSON(properties["Noise Model"]);
    ChVector<> gps_reference = ReadVectorJSON(properties["GPS Reference"]);
    auto mag =
        chrono_types::make_shared<ChMagnetometerSensor>(parent, updateRate, offsetPose, noise_model, gps_reference);

    if (properties.HasMember("Lag")) {
        float lag = properties["Lag"].GetFloat();
        mag->SetLag(lag);
    }
    if (properties.HasMember("Collection Window")) {
        float collection = properties["Collection Window"].GetFloat();
        mag->SetCollectionWindow(collection);
    }
    return mag;
}

std::shared_ptr<ChLidarSensor> ReadLidarSensorJSON(const std::string& filename,
                                                   std::shared_ptr<chrono::ChBody> parent,
                                                   chrono::ChFrame<double> offsetPose) {
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string subtype = d["Template"].GetString();
    if (subtype.compare("Lidar") != 0) {
        throw ChException("ChUtilsJSON::ReadLidarSensorJSON: Sensor type of " + subtype + " must be Lidar.");
    }

    // Read sensor properties
    assert(d.HasMember("Properties"));
    const Value& properties = d["Properties"];

    // Create the gps sensor.
    float updateRate = properties["Update Rate"].GetFloat();
    // ChFrame<> offsetPose = ReadFrameJSON(properties["Offset Pose"]);
    unsigned int w = properties["Width"].GetUint();
    unsigned int h = properties["Height"].GetUint();
    float hfov = properties["Horizontal Field of View"].GetFloat();
    float max_v_angle = properties["Max Vertical Angle"].GetFloat();
    float min_v_angle = properties["Min Vertical Angle"].GetFloat();
    float max_distance = properties["Max Distance"].GetFloat();
    // float lag = properties["Lag"].GetFloat();
    // float exposure_time = properties["Collection Window"].GetFloat();

    unsigned int sample_radius = 1;
    LidarBeamShape beam_shape = LidarBeamShape::RECTANGULAR;
    float vert_divergence_angle = .003f;
    float hori_divergence_angle = .003f;
    LidarReturnMode return_mode = LidarReturnMode::STRONGEST_RETURN;
    float near_clip = 0.f;

    if (properties.HasMember("Sample Radius")) {
        sample_radius = properties["Sample Radius"].GetInt();
    }
    if (properties.HasMember("Vertical Divergence Angle")) {
        vert_divergence_angle = properties["Vertical Divergence Angle"].GetFloat();
    }
    if (properties.HasMember("Horizontal Divergence Angle")) {
        hori_divergence_angle = properties["Horizontal Divergence Angle"].GetFloat();
    }
    if (properties.HasMember("Return Mode")) {
        std::string s = properties["Return Mode"].GetString();
        if (s == "MEAN_RETURN") {
            return_mode = LidarReturnMode::MEAN_RETURN;
        } else if (s == "FIRST_RETURN") {
            return_mode = LidarReturnMode::FIRST_RETURN;
        } else if (s == "LAST_RETURN") {
            return_mode = LidarReturnMode::LAST_RETURN;
        }
    }
    if (properties.HasMember("Near Clip")) {
        near_clip = properties["Near Clip"].GetFloat();
    }

    auto lidar = chrono_types::make_shared<ChLidarSensor>(
        parent, updateRate, offsetPose, w, h, hfov, max_v_angle, min_v_angle, max_distance, beam_shape, sample_radius,
        vert_divergence_angle, hori_divergence_angle, return_mode, near_clip);

    if (properties.HasMember("Lag")) {
        float lag = properties["Lag"].GetFloat();
        lidar->SetLag(lag);
    }
    if (properties.HasMember("Collection Window")) {
        float exposure_time = properties["Collection Window"].GetFloat();
        lidar->SetCollectionWindow(exposure_time);
    }

    return lidar;
}

std::shared_ptr<ChRadarSensor> ReadRadarSensorJSON(const std::string& filename,
                                                   std::shared_ptr<chrono::ChBody> parent,
                                                   chrono::ChFrame<double> offsetPose){
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return nullptr;

    // Check that the given file is a sensor specification file.
    assert(d.HasMember("Type"));
    std::string type = d["Type"].GetString();
    assert(type.compare("Sensor") == 0);

    // Extract the sensor type.
    assert(d.HasMember("Template"));
    std::string subtype = d["Template"].GetString();
    if (subtype.compare("Radar") != 0){
        throw ChException("ChUtilsJSON::ReadRdarSensorJSON: Sensor type of " + subtype + " must be Radar");
    }

    // Read sensor properties
    assert(d.HasMember("Properties"));
    const Value& properties = d["Properties"];

    // Create the radar sensor.
    float updateRate = properties["Update Rate"].GetFloat();
    unsigned int w = properties["Width"].GetUint();
    unsigned int h = properties["Height"].GetUint();
    float hfov = properties["Horizontal Field of View"].GetFloat();
    float vfov = properties["Vertical Field of View"].GetFloat();
    float max_distance = properties["Max Distance"].GetFloat();

    float near_clip = 0.f;

    if (properties.HasMember("Near Clip")) {
        near_clip = properties["Near Clip"].GetFloat();
    }

    auto radar = chrono_types::make_shared<ChRadarSensor>(
        parent, updateRate, offsetPose, w, h, hfov, vfov, max_distance, near_clip
    );

    if (properties.HasMember("Collection Window")) {
        float exposure_time = properties["Collection Window"].GetFloat();
    radar->SetCollectionWindow(exposure_time);
    }

    return radar;
}

void ReadFilterListJSON(const std::string& filename, std::shared_ptr<ChSensor> sensor) {
    Document d;
    ReadFileJSON(filename, d);
    if (d.IsNull())
        return;

    // Read inertia properties for all sub-components
    // and calculate composite inertia properties
    assert(d.HasMember("Filters"));
    assert(d["Filters"].IsArray());
    int num_filters = d["Filters"].Size();
    // std::cout << "Num Filters :: " << num_filters << std::endl;

    for (int i = 0; i < num_filters; i++) {
        // Create the filter.
        auto filter = CreateFilterJSON(d["Filters"][i]);
        sensor->PushFilter(filter);
    }
    // std::cout << "Successfully Loaded FilterList" << std::endl;
}

// -----------------------------------------------------------------------------

std::shared_ptr<ChFilter> CreateFilterJSON(const Value& value) {
    std::string type = value["Filter"].GetString();
    // std::cout << "Filter Type :: " << type << "." << std::endl;

    // Create the filter
    std::shared_ptr<ChFilter> filter;
    if (type.compare("ChFilterCameraNoiseConstNormal") == 0) {
        float mean = value["Mean"].GetFloat();
        float stdev = value["Standard Deviation"].GetFloat();
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterCameraNoiseConstNormal>(mean, stdev, name);
    } else if (type.compare("ChFilterCameraNoisePixDep") == 0) {
        float gain = value["Gain"].GetFloat();
        float sigma_read = value["Sigma Read"].GetFloat();
        float sigma_adc = value["Sigma ADC"].GetFloat();
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterCameraNoisePixDep>(gain, sigma_read, sigma_adc, name);
    } else if (type.compare("ChFilterLidarNoiseXYZI") == 0) {
        float stdev_range = value["Standard Deviation Range"].GetFloat();
        float stdev_v_angle = value["Standard Deviation Vertical Angle"].GetFloat();
        float stdev_h_angle = value["Standard Deviation Horizontal Angle"].GetFloat();
        float stdev_intensity = value["Standard Deviation Intensity"].GetFloat();
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterLidarNoiseXYZI>(stdev_range, stdev_v_angle, stdev_h_angle,
                                                                   stdev_intensity, name);
    } else if (type.compare("ChFilterVisualize") == 0) {
        int w = value["Width"].GetInt();
        int h = value["Height"].GetInt();
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterVisualize>(w, h, name);
    } else if (type.compare("ChFilterSave") == 0) {
        std::string data_path = GetStringMemberWithDefault(value, "Data Path");
        filter = chrono_types::make_shared<ChFilterSave>(data_path);
    } else if (type.compare("ChFilterSavePtCloud") == 0) {
        std::string data_path = GetStringMemberWithDefault(value, "Data Path");
        filter = chrono_types::make_shared<ChFilterSavePtCloud>(data_path);
    } else if (type.compare("ChFilterGrayscale") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterGrayscale>(name);
    } else if (type.compare("ChFilterR8Access") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterR8Access>(name);
    } else if (type.compare("ChFilterRGBA8Access") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterRGBA8Access>(name);
    } else if (type.compare("ChFilterXYZIAccess") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterXYZIAccess>(name);
    } else if (type.compare("ChFilterDIAccess") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterDIAccess>(name);
    } else if (type.compare("ChFilterAccelAccess") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterAccelAccess>(name);
    } else if (type.compare("ChFilterGyroAccess") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterGyroAccess>(name);
    } else if (type.compare("ChFilterMagnetAccess") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterMagnetAccess>(name);
    } else if (type.compare("ChFilterGPSAccess") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterGPSAccess>(name);
    } else if (type.compare("ChFilterPCfromDepth") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterPCfromDepth>(name);
    } else if (type.compare("ChFilterVisualizePointCloud") == 0) {
        std::string name = GetStringMemberWithDefault(value, "Name");
        int w = value["Width"].GetInt();
        int h = value["Height"].GetInt();
        float zoom = value["Zoom"].GetFloat();
        filter = chrono_types::make_shared<ChFilterVisualizePointCloud>(w, h, zoom, name);
    } else if (type.compare("ChFilterImageResize") == 0) {
        int w = value["Width"].GetInt();
        int h = value["Height"].GetInt();
        std::string name = GetStringMemberWithDefault(value, "Name");
        filter = chrono_types::make_shared<ChFilterImageResize>(w, h, name);
    } else {
        throw ChException("Filter type of \"" + type + "\" not supported in ReadFilterJSON.");
    }

    return filter;
}

std::shared_ptr<ChNoiseModel> CreateNoiseJSON(const Value& value) {
    std::string type = value["Noise Type"].GetString();
    // std::cout << "Noise Model Type :: " << type << "." << std::endl;

    // Create the filter
    std::shared_ptr<ChNoiseModel> model;
    if (type.compare("ChNoiseNone") == 0) {
        model = chrono_types::make_shared<ChNoiseNone>();
    } else if (type.compare("ChNoiseNormal") == 0) {
        ChVector<float> mean = ReadVectorJSON(value["Mean"]);
        ChVector<float> stdev = ReadVectorJSON(value["Mean"]);
        model = chrono_types::make_shared<ChNoiseNormal>(mean, stdev);
    } else if (type.compare("ChNoiseNormalDrift") == 0) {
        float updateRate = value["Update Rate"].GetFloat();
        ChVector<float> mean = ReadVectorJSON(value["Mean"]);
        ChVector<float> stdev = ReadVectorJSON(value["Mean"]);
        float drift_bias = value["Drift Bias"].GetFloat();
        float tau_drift = value["Tau Drift"].GetFloat();
        model = chrono_types::make_shared<ChNoiseNormalDrift>(updateRate, mean, stdev, drift_bias, tau_drift);
    } else {
        throw ChException("Noise model type of \"" + type + "\" not supported in ReadNoiseJSON.");
    }

    return model;
}

std::string GetStringMemberWithDefault(const Value& value, const char* member, const char* def) {
    if (value.HasMember(member))
        return value[member].GetString();
    return def;
}

}  // namespace sensor
}  // namespace chrono


text:
FOUNDATION_EXPORT double SSLNavigationBarVersionNumber;
FOUNDATION_EXPORT const unsigned char SSLNavigationBarVersionString[];

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/pinpoint/Pinpoint_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/pinpoint/model/Format.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Pinpoint
{
namespace Model
{

  /**
   * Import job resource

See Also:
   AWS
   * API Reference

   */
  class AWS_PINPOINT_API ImportJobResource
  {
  public:
    ImportJobResource();
    ImportJobResource(Aws::Utils::Json::JsonView jsonValue);
    ImportJobResource& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     * Sets whether the endpoints create a segment when they are imported.
     */
    inline bool GetDefineSegment() const{ return m_defineSegment; }

    /**
     * Sets whether the endpoints create a segment when they are imported.
     */
    inline void SetDefineSegment(bool value) { m_defineSegmentHasBeenSet = true; m_defineSegment = value; }

    /**
     * Sets whether the endpoints create a segment when they are imported.
     */
    inline ImportJobResource& WithDefineSegment(bool value) { SetDefineSegment(value); return *this;}

    /**
     * (Deprecated) Your AWS account ID, which you assigned to the ExternalID key in an
     * IAM trust policy. Used by Amazon Pinpoint to assume an IAM role. This
     * requirement is removed, and external IDs are not recommended for IAM roles
     * assumed by Amazon Pinpoint.
     */
    inline const Aws::String& GetExternalId() const{ return m_externalId; }

    /**
     * (Deprecated) Your AWS account ID, which you assigned to the ExternalID key in an
     * IAM trust policy. Used by Amazon Pinpoint to assume an IAM role. This
     * requirement is removed, and external IDs are not recommended for IAM roles
     * assumed by Amazon Pinpoint.
     */
    inline void SetExternalId(const Aws::String& value) { m_externalIdHasBeenSet = true; m_externalId = value; }

    /**
     * (Deprecated) Your AWS account ID, which you assigned to the ExternalID key in an
     * IAM trust policy. Used by Amazon Pinpoint to assume an IAM role. This
     * requirement is removed, and external IDs are not recommended for IAM roles
     * assumed by Amazon Pinpoint.
     */
    inline void SetExternalId(Aws::String&& value) { m_externalIdHasBeenSet = true; m_externalId = std::move(value); }

    /**
     * (Deprecated) Your AWS account ID, which you assigned to the ExternalID key in an
     * IAM trust policy. Used by Amazon Pinpoint to assume an IAM role. This
     * requirement is removed, and external IDs are not recommended for IAM roles
     * assumed by Amazon Pinpoint.
     */
    inline void SetExternalId(const char* value) { m_externalIdHasBeenSet = true; m_externalId.assign(value); }

    /**
     * (Deprecated) Your AWS account ID, which you assigned to the ExternalID key in an
     * IAM trust policy. Used by Amazon Pinpoint to assume an IAM role. This
     * requirement is removed, and external IDs are not recommended for IAM roles
     * assumed by Amazon Pinpoint.
     */
    inline ImportJobResource& WithExternalId(const Aws::String& value) { SetExternalId(value); return *this;}

    /**
     * (Deprecated) Your AWS account ID, which you assigned to the ExternalID key in an
     * IAM trust policy. Used by Amazon Pinpoint to assume an IAM role. This
     * requirement is removed, and external IDs are not recommended for IAM roles
     * assumed by Amazon Pinpoint.
     */
    inline ImportJobResource& WithExternalId(Aws::String&& value) { SetExternalId(std::move(value)); return *this;}

    /**
     * (Deprecated) Your AWS account ID, which you assigned to the ExternalID key in an
     * IAM trust policy. Used by Amazon Pinpoint to assume an IAM role. This
     * requirement is removed, and external IDs are not recommended for IAM roles
     * assumed by Amazon Pinpoint.
     */
    inline ImportJobResource& WithExternalId(const char* value) { SetExternalId(value); return *this;}

    /**
     * The format of the files that contain the endpoint definitions.
Valid values:
     * CSV, JSON
     */
    inline const Format& GetFormat() const{ return m_format; }

    /**
     * The format of the files that contain the endpoint definitions.
Valid values:
     * CSV, JSON
     */
    inline void SetFormat(const Format& value) { m_formatHasBeenSet = true; m_format = value; }

    /**
     * The format of the files that contain the endpoint definitions.
Valid values:
     * CSV, JSON
     */
    inline void SetFormat(Format&& value) { m_formatHasBeenSet = true; m_format = std::move(value); }

    /**
     * The format of the files that contain the endpoint definitions.
Valid values:
     * CSV, JSON
     */
    inline ImportJobResource& WithFormat(const Format& value) { SetFormat(value); return *this;}

    /**
     * The format of the files that contain the endpoint definitions.
Valid values:
     * CSV, JSON
     */
    inline ImportJobResource& WithFormat(Format&& value) { SetFormat(std::move(value)); return *this;}

    /**
     * Sets whether the endpoints are registered with Amazon Pinpoint when they are
     * imported.
     */
    inline bool GetRegisterEndpoints() const{ return m_registerEndpoints; }

    /**
     * Sets whether the endpoints are registered with Amazon Pinpoint when they are
     * imported.
     */
    inline void SetRegisterEndpoints(bool value) { m_registerEndpointsHasBeenSet = true; m_registerEndpoints = value; }

    /**
     * Sets whether the endpoints are registered with Amazon Pinpoint when they are
     * imported.
     */
    inline ImportJobResource& WithRegisterEndpoints(bool value) { SetRegisterEndpoints(value); return *this;}

    /**
     * The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access
     * to the Amazon S3 location that contains the endpoints to import.
     */
    inline const Aws::String& GetRoleArn() const{ return m_roleArn; }

    /**
     * The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access
     * to the Amazon S3 location that contains the endpoints to import.
     */
    inline void SetRoleArn(const Aws::String& value) { m_roleArnHasBeenSet = true; m_roleArn = value; }

    /**
     * The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access
     * to the Amazon S3 location that contains the endpoints to import.
     */
    inline void SetRoleArn(Aws::String&& value) { m_roleArnHasBeenSet = true; m_roleArn = std::move(value); }

    /**
     * The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access
     * to the Amazon S3 location that contains the endpoints to import.
     */
    inline void SetRoleArn(const char* value) { m_roleArnHasBeenSet = true; m_roleArn.assign(value); }

    /**
     * The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access
     * to the Amazon S3 location that contains the endpoints to import.
     */
    inline ImportJobResource& WithRoleArn(const Aws::String& value) { SetRoleArn(value); return *this;}

    /**
     * The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access
     * to the Amazon S3 location that contains the endpoints to import.
     */
    inline ImportJobResource& WithRoleArn(Aws::String&& value) { SetRoleArn(std::move(value)); return *this;}

    /**
     * The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access
     * to the Amazon S3 location that contains the endpoints to import.
     */
    inline ImportJobResource& WithRoleArn(const char* value) { SetRoleArn(value); return *this;}

    /**
     * The URL of the S3 bucket that contains the segment information to import. The
     * location can be a folder or a single file. The URL should use the following
     * format: s3://bucket-name/folder-name/file-name

Amazon Pinpoint imports
     * endpoints from this location and any subfolders it contains.
     */
    inline const Aws::String& GetS3Url() const{ return m_s3Url; }

    /**
     * The URL of the S3 bucket that contains the segment information to import. The
     * location can be a folder or a single file. The URL should use the following
     * format: s3://bucket-name/folder-name/file-name

Amazon Pinpoint imports
     * endpoints from this location and any subfolders it contains.
     */
    inline void SetS3Url(const Aws::String& value) { m_s3UrlHasBeenSet = true; m_s3Url = value; }

    /**
     * The URL of the S3 bucket that contains the segment information to import. The
     * location can be a folder or a single file. The URL should use the following
     * format: s3://bucket-name/folder-name/file-name

Amazon Pinpoint imports
     * endpoints from this location and any subfolders it contains.
     */
    inline void SetS3Url(Aws::String&& value) { m_s3UrlHasBeenSet = true; m_s3Url = std::move(value); }

    /**
     * The URL of the S3 bucket that contains the segment information to import. The
     * location can be a folder or a single file. The URL should use the following
     * format: s3://bucket-name/folder-name/file-name

Amazon Pinpoint imports
     * endpoints from this location and any subfolders it contains.
     */
    inline void SetS3Url(const char* value) { m_s3UrlHasBeenSet = true; m_s3Url.assign(value); }

    /**
     * The URL of the S3 bucket that contains the segment information to import. The
     * location can be a folder or a single file. The URL should use the following
     * format: s3://bucket-name/folder-name/file-name

Amazon Pinpoint imports
     * endpoints from this location and any subfolders it contains.
     */
    inline ImportJobResource& WithS3Url(const Aws::String& value) { SetS3Url(value); return *this;}

    /**
     * The URL of the S3 bucket that contains the segment information to import. The
     * location can be a folder or a single file. The URL should use the following
     * format: s3://bucket-name/folder-name/file-name

Amazon Pinpoint imports
     * endpoints from this location and any subfolders it contains.
     */
    inline ImportJobResource& WithS3Url(Aws::String&& value) { SetS3Url(std::move(value)); return *this;}

    /**
     * The URL of the S3 bucket that contains the segment information to import. The
     * location can be a folder or a single file. The URL should use the following
     * format: s3://bucket-name/folder-name/file-name

Amazon Pinpoint imports
     * endpoints from this location and any subfolders it contains.
     */
    inline ImportJobResource& WithS3Url(const char* value) { SetS3Url(value); return *this;}

    /**
     * The ID of the segment to update if the import job is meant to update an existing
     * segment.
     */
    inline const Aws::String& GetSegmentId() const{ return m_segmentId; }

    /**
     * The ID of the segment to update if the import job is meant to update an existing
     * segment.
     */
    inline void SetSegmentId(const Aws::String& value) { m_segmentIdHasBeenSet = true; m_segmentId = value; }

    /**
     * The ID of the segment to update if the import job is meant to update an existing
     * segment.
     */
    inline void SetSegmentId(Aws::String&& value) { m_segmentIdHasBeenSet = true; m_segmentId = std::move(value); }

    /**
     * The ID of the segment to update if the import job is meant to update an existing
     * segment.
     */
    inline void SetSegmentId(const char* value) { m_segmentIdHasBeenSet = true; m_segmentId.assign(value); }

    /**
     * The ID of the segment to update if the import job is meant to update an existing
     * segment.
     */
    inline ImportJobResource& WithSegmentId(const Aws::String& value) { SetSegmentId(value); return *this;}

    /**
     * The ID of the segment to update if the import job is meant to update an existing
     * segment.
     */
    inline ImportJobResource& WithSegmentId(Aws::String&& value) { SetSegmentId(std::move(value)); return *this;}

    /**
     * The ID of the segment to update if the import job is meant to update an existing
     * segment.
     */
    inline ImportJobResource& WithSegmentId(const char* value) { SetSegmentId(value); return *this;}

    /**
     * A custom name for the segment created by the import job. Use if DefineSegment is
     * true.
     */
    inline const Aws::String& GetSegmentName() const{ return m_segmentName; }

    /**
     * A custom name for the segment created by the import job. Use if DefineSegment is
     * true.
     */
    inline void SetSegmentName(const Aws::String& value) { m_segmentNameHasBeenSet = true; m_segmentName = value; }

    /**
     * A custom name for the segment created by the import job. Use if DefineSegment is
     * true.
     */
    inline void SetSegmentName(Aws::String&& value) { m_segmentNameHasBeenSet = true; m_segmentName = std::move(value); }

    /**
     * A custom name for the segment created by the import job. Use if DefineSegment is
     * true.
     */
    inline void SetSegmentName(const char* value) { m_segmentNameHasBeenSet = true; m_segmentName.assign(value); }

    /**
     * A custom name for the segment created by the import job. Use if DefineSegment is
     * true.
     */
    inline ImportJobResource& WithSegmentName(const Aws::String& value) { SetSegmentName(value); return *this;}

    /**
     * A custom name for the segment created by the import job. Use if DefineSegment is
     * true.
     */
    inline ImportJobResource& WithSegmentName(Aws::String&& value) { SetSegmentName(std::move(value)); return *this;}

    /**
     * A custom name for the segment created by the import job. Use if DefineSegment is
     * true.
     */
    inline ImportJobResource& WithSegmentName(const char* value) { SetSegmentName(value); return *this;}

  private:

    bool m_defineSegment;
    bool m_defineSegmentHasBeenSet;

    Aws::String m_externalId;
    bool m_externalIdHasBeenSet;

    Format m_format;
    bool m_formatHasBeenSet;

    bool m_registerEndpoints;
    bool m_registerEndpointsHasBeenSet;

    Aws::String m_roleArn;
    bool m_roleArnHasBeenSet;

    Aws::String m_s3Url;
    bool m_s3UrlHasBeenSet;

    Aws::String m_segmentId;
    bool m_segmentIdHasBeenSet;

    Aws::String m_segmentName;
    bool m_segmentNameHasBeenSet;
  };

} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
	local suite = test.declare("vstudio_vs2010_rule_xml")

	local vc2010 = premake.vstudio.vc2010
	local m = premake.vstudio.vs2010.rules.xml

--
-- Setup
--

	function suite.setup()
		premake.action.set("vs2010")
		rule "MyRule"
		wks, prj = test.createWorkspace()
		rules { "MyRule" }
	end

	local function createVar(def)
		rule "MyRule"
		propertydefinition(def)
		project "MyProject"
	end

---
-- Property definitions
---

	function suite.properties_onString()
		createVar { name="MyVar", kind="string" }
		local r = test.getRule("MyRule")
		m.properties(r)
		test.capture [[
<StringProperty
	Name="MyVar"
	HelpContext="0"
	DisplayName="MyVar"
	Switch="[value]" />
		]]
	end

	function suite.properties_onStringWithNoKind()
		createVar { name="MyVar" }
		local r = test.getRule("MyRule")
		m.properties(r)
		test.capture [[
<StringProperty
	Name="MyVar"
	HelpContext="0"
	DisplayName="MyVar"
	Switch="[value]" />
		]]
	end


text:
package org.jboss.bus.simple;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lenka Večeřa
 */
public class SimpleFederatedBusTest {

   @Test
   public void testSimpleBus() {
      DummyMessageTranslator t1 = new DummyMessageTranslator();
      DummyMessageTranslator t2 = new DummyMessageTranslator();
      DummyMessageTranslator t3 = new DummyMessageTranslator();

      SimpleFederatedBus federatedBus = new SimpleFederatedBus();

      federatedBus.registerTranslator(t1);
      federatedBus.registerTranslator(t2);
      federatedBus.registerTranslator(t3);

      federatedBus.start();

      t1.generateMessage("hello1");
      t2.generateMessage("hello2");
      t1.generateMessage("hello3");

      federatedBus.stop();

      verifyMessages(t1);
      verifyMessages(t2);
      verifyMessages(t3);
   }

   private void verifyMessages(final DummyMessageTranslator translator) {
      List<String> messages = translator.getMessages().stream().map(m -> m.getPayload().toString()).collect(Collectors.toList());
      Assert.assertEquals(messages.size(), 3);
      Assert.assertTrue(messages.contains("hello1"));
      Assert.assertTrue(messages.contains("hello2"));
      Assert.assertTrue(messages.contains("hello3"));
   }
}


text:
package me.codeboy.android.cycleviewpager.example.base;

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

/**
 * base activity
 * Created by YD on 14/01/2017.
 */

public class BaseActivity extends AppCompatActivity {
    protected String TAG;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setDisplayHomeAsUpEnabled(true);
            bar.setDisplayShowHomeEnabled(true);
        }

        TAG = getClass().getSimpleName();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
class AddNewUserReminder < ActiveRecord::Migration
  def up
    add_column :employees, :new_user_reminder, :boolean, :default => true
  end

  def down
    remove_column :employees, :new_user_reminder
  end
end


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.objectProperty = void 0;
const util_1 = require("../utils/util");
const decorators_1 = require("./decorators");
function objectProperty(object, propertyName) {
    return (0, decorators_1.addDefinitionProperty)("injectObjectProperty", [util_1.Util.getClassNameOrId(object), propertyName], true);
}
exports.objectProperty = objectProperty;
//# sourceMappingURL=objectProperty.js.map


text:
//----------------------------------------------------------------------------
//
// "Copyright Centre National d'Etudes Spatiales"
//
// License:  LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
//----------------------------------------------------------------------------
// $Id$

#include <otb/RadarSat2NoiseLevel.h>
#include <ossim/base/ossimDpt3d.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimString.h>

using namespace std;

namespace ossimplugins
{
static const char NOISE[] = "referenceNoiseLevel";

static const char BETA_NOUGHT[] ="BetaNought";
static const char SIGMA_NOUGHT[] ="SigmaNought";
static const char GAMMA[] ="Gamma";

static const char INCIDENCE_ANGLE_CORRECTION_NAME_KW[] = "incidenceAngleCorrectionName";
static const char PIXEL_FIRST_NOISE_VALUE_KW[] = "pixelFirstNoiseValue";
static const char STEP_SIZE_KW[] = "stepSize";
static const char NUMBER_OF_NOISE_LEVEL_VALUE_KW[] = "numberOfNoiseLevelValues";
static const char NOISE_LEVEL_VALUES_KW[] = "noiseLevelValues";
static const char UNITS_KW[] = "units";
static const char OFFSET_KW[] = "offset";
static const char GAIN_KW[] = "gain";
static const char SIZE_KW[] = "size";

RadarSat2NoiseLevel::RadarSat2NoiseLevel():
  _incidenceAngleCorrectionName("Unknown"),
  _pixelFirstNoiseValue(0),
  _stepSize(0),
  _numberOfNoiseLevelValues(0),
  _noiseLevelValues(),
  _units("Unknown"),
  _offset(0.0),
  _gain()
{
}

RadarSat2NoiseLevel::~RadarSat2NoiseLevel()
{
}

RadarSat2NoiseLevel::RadarSat2NoiseLevel(const RadarSat2NoiseLevel& rhs):
  _incidenceAngleCorrectionName(rhs._incidenceAngleCorrectionName),
  _pixelFirstNoiseValue(rhs._pixelFirstNoiseValue),
  _stepSize(rhs._stepSize),
  _numberOfNoiseLevelValues(rhs._numberOfNoiseLevelValues),
  _noiseLevelValues(rhs._noiseLevelValues),
  _units(rhs._units),
  _offset(rhs._offset),
  _gain(rhs._gain)
{
}

RadarSat2NoiseLevel& RadarSat2NoiseLevel::operator=(const RadarSat2NoiseLevel& rhs)
{
  _incidenceAngleCorrectionName = rhs._incidenceAngleCorrectionName;
  _pixelFirstNoiseValue = rhs._pixelFirstNoiseValue;
  _stepSize = rhs._stepSize;
  _numberOfNoiseLevelValues = rhs._numberOfNoiseLevelValues;
  _noiseLevelValues = rhs._noiseLevelValues;
  _units = rhs._units;
  _offset = rhs._offset;
  _gain = rhs._gain;
  return *this;
}

bool RadarSat2NoiseLevel::saveState(ossimKeywordlist& kwl, const char* prefix) const
{
   std::string pfx;
   if (prefix)
   {
      pfx = prefix;
   }
   pfx += NOISE;

   if(_incidenceAngleCorrectionName == "Gamma")
   {
   		pfx = pfx + "["+ GAMMA +"]";
   }
   if(_incidenceAngleCorrectionName == "Sigma Nought")
   {
   		pfx = pfx + "["+ SIGMA_NOUGHT +"]";
   }
   if(_incidenceAngleCorrectionName == "Beta Nought")
   {
   		pfx = pfx + "["+ BETA_NOUGHT +"]";
   }

   pfx +=".";

   std::string s = pfx + INCIDENCE_ANGLE_CORRECTION_NAME_KW;
   kwl.add(prefix, s.c_str(), _incidenceAngleCorrectionName);

   s = pfx + PIXEL_FIRST_NOISE_VALUE_KW;
   kwl.add(prefix, s.c_str(), _pixelFirstNoiseValue);

   s = pfx + STEP_SIZE_KW;
   kwl.add(prefix, s.c_str(), _stepSize);

   s = pfx + NUMBER_OF_NOISE_LEVEL_VALUE_KW;
   kwl.add(prefix, s.c_str(), _numberOfNoiseLevelValues);

   s = pfx + UNITS_KW;
   kwl.add(prefix, s.c_str(), _units);

   for (unsigned int i = 0; i < _noiseLevelValues.size(); ++i)
   {
      	s = pfx + NOISE_LEVEL_VALUES_KW + "[" + ossimString::toString(i).chars() + "]";
   		kwl.add(prefix, s.c_str(), _noiseLevelValues[i]);
   }

   s = pfx + OFFSET_KW;
   kwl.add(prefix, s.c_str(), _offset);

   s = pfx + GAIN_KW;
   kwl.add(prefix, s.c_str(), _gain);

   return true;
}

bool RadarSat2NoiseLevel::loadState(const ossimKeywordlist& kwl, const char* prefix)
{
   static const char MODULE[] = "RadarSat2NoiseLevel::loadState";

   //bool         result = true;
   ossimString  s;
   const char*  lookup = 0;

   std::string pfx("");
   if (prefix)
   {
      pfx = prefix;
   }

   pfx += NOISE;

   if(_incidenceAngleCorrectionName == "Gamma")
   {
   		pfx = pfx + "["+ GAMMA +"]";
   }
   if(_incidenceAngleCorrectionName == "Sigma Nought")
   {
   		pfx = pfx + "["+ SIGMA_NOUGHT +"]";
   }
   if(_incidenceAngleCorrectionName == "Beta Nought")
   {
   		pfx = pfx + "["+ BETA_NOUGHT +"]";
   }

  std::string s1 = pfx + "["+ GAMMA +"]";
  lookup = kwl.find(s1.c_str(), INCIDENCE_ANGLE_CORRECTION_NAME_KW);
  if (!lookup)
  {
  		std::string s1 = pfx + "["+ SIGMA_NOUGHT +"]";
  		lookup = kwl.find(s1.c_str(), INCIDENCE_ANGLE_CORRECTION_NAME_KW);
  		if (!lookup)
  		{
  			std::string s1 = pfx + "["+ BETA_NOUGHT +"]";
  			lookup = kwl.find(s1.c_str(), INCIDENCE_ANGLE_CORRECTION_NAME_KW);
  			if (!lookup)
  			{
    				ossimNotify(ossimNotifyLevel_WARN)
         				<< MODULE << " Keyword not found: " << INCIDENCE_ANGLE_CORRECTION_NAME_KW << "\n";
    				return false;
  			}
  		}
  }

  _incidenceAngleCorrectionName = lookup;
  pfx= s1;

  lookup = kwl.find(s1.c_str(), PIXEL_FIRST_NOISE_VALUE_KW);
  if (lookup)
  {
    s = lookup;
    _pixelFirstNoiseValue = s.toUInt32();
  }
  else
  {
    ossimNotify(ossimNotifyLevel_WARN)
         << MODULE << " Keyword not found: " << PIXEL_FIRST_NOISE_VALUE_KW << "\n";
    return false;
  }

  lookup = kwl.find(s1.c_str(), STEP_SIZE_KW);
  if (lookup)
  {
    s = lookup;
    _stepSize = s.toUInt32();
  }
  else
  {
    ossimNotify(ossimNotifyLevel_WARN)
         << MODULE << " Keyword not found: " << STEP_SIZE_KW << "\n";
    return false;
  }

  lookup = kwl.find(s1.c_str(), NUMBER_OF_NOISE_LEVEL_VALUE_KW);
  if (lookup)
  {
    s = lookup;
    _numberOfNoiseLevelValues = s.toUInt32();
  }
  else
  {
    ossimNotify(ossimNotifyLevel_WARN)
         << MODULE << " Keyword not found: " << NUMBER_OF_NOISE_LEVEL_VALUE_KW << "\n";
    return false;
  }

  lookup = kwl.find(s1.c_str(), UNITS_KW);
  if (lookup)
  {
    _units = lookup;
  }
  else
  {
    ossimNotify(ossimNotifyLevel_WARN)
         << MODULE << " Keyword not found: " << UNITS_KW << "\n";
    return false;
  }

   _noiseLevelValues.clear();
   for (unsigned int i = 0; i < _numberOfNoiseLevelValues; ++i)
   {
      	s = pfx + NOISE_LEVEL_VALUES_KW + "[" + ossimString::toString(i) + "]";
  	  	lookup = kwl.find(s.c_str(), "");
  	  	if (lookup)
  		{
    		s = lookup;
    		_noiseLevelValues.push_back( s.toDouble() );
  		}
   }

   if( _numberOfNoiseLevelValues != _noiseLevelValues.size() )
   {
    	ossimNotify(ossimNotifyLevel_WARN)
        		 	<< MODULE
        		  	<< " Keyword " << NOISE_LEVEL_VALUES_KW
        		  	<< " is different with the number of noise level values"
        		  	<< std::endl;
        return false;
   }

  lookup = kwl.find(s1.c_str(), GAIN_KW);
  if (lookup)
  {
    _gain = lookup;;
  }
  else
  {
    ossimNotify(ossimNotifyLevel_WARN)
         << MODULE << " Keyword not found: " << GAIN_KW << "\n";
    return false;
  }

  lookup = kwl.find(s1.c_str(), OFFSET_KW);
  if (lookup)
  {
    s = lookup;
    _offset = s.toFloat64();
  }
  else
  {
    ossimNotify(ossimNotifyLevel_WARN)
         << MODULE << " Keyword not found: " << OFFSET_KW << "\n";
    return false;
  }

  if( _numberOfNoiseLevelValues != _noiseLevelValues.size() )
  {
    	ossimNotify(ossimNotifyLevel_WARN)
        		 	<< MODULE
        		  	<< " Keyword " << NOISE_LEVEL_VALUES_KW
        		  	<< " is different with the number of noise level values"
        		  	<< std::endl;
        return false;
  }

  return true;
}

std::ostream& RadarSat2NoiseLevel::print(std::ostream& out) const
{
   out << setprecision(15) << setiosflags(ios::fixed)
       << "\n RadarSat2NoiseLevel class data members:\n";

   //const char* prefix = 0;
   //ossimKeywordlist kwl;
   //ossimString pfx;

   /* TODO Add print method*/

   //out << kwl;

   return out;
}

}


text:
      <form role="form" id="renamePageForm" onsubmit="return false;">

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

{{ t('Rename page') }}

              {{ t('Current page name') }}

              {{ page.path }}

              {{ t('New page name') }}

                {{ config.crowi['app:url'] }}
                <input type="text" class="form-control" name="new_path" id="newPageName" value="{{ page.path }}">

                 <input name="create_redirect" value="1"  type="checkbox"> {{ t('Redirect') }}

 {{ t('modal_rename.help.redirect', page.path) }}

            {#
 #}
            {#     #}
            {#      <input name="moveUnderTrees" value="1" type="checkbox"> 下層ページも全部移動する #}
            {#     #}
            {#
チェックを入れると、{{ page.path }}以下の階層以下もすべて移動します。
 #}
            {#
例: /hoge/fuga/move を /foo/bar/move に移動すると、/hoge/fuga/move/page1 も /foo/bar/move/page1 に。
 #}
            {#
 #}

          <input type="hidden" name="_csrf" value="{{ csrf() }}">
          <input type="hidden" name="path" value="{{ page.path }}">
          <input type="hidden" name="page_id" value="{{ page._id.toString() }}">
          <input type="hidden" name="revision_id" value="{{ page.revision._id.toString() }}">
          <input type="submit" class="btn btn-primary" value="Rename!">

      </form>


text:
package com.latitude.seventimer.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.latitude.seventimer.R;

public class YYCommonItemLayout extends ConstraintLayout {

    private View topBorder;
    private View bottomBorder;

    public YYCommonItemLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public YYCommonItemLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public YYCommonItemLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        if (getBackground() == null) {
            setBackgroundResource(R.drawable.mx_item_background);
        }

        int defaultBorderColor = context.getColor(R.color.mxGrey04);
        View view = LayoutInflater.from(context).inflate(R.layout.layout_common_item, this);
        topBorder = view.findViewById(R.id.mxprofile_item_top_border);
        bottomBorder = view.findViewById(R.id.mxprofile_item_bottom_border);

        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.YYCommonItemLayout, defStyle, 0);
        if (a.hasValue(R.styleable.YYCommonItemLayout_mx_border_color)) {
            int borderColor = a.getColor(R.styleable.YYCommonItemLayout_mx_border_color, defaultBorderColor);
            topBorder.setBackgroundColor(borderColor);
            bottomBorder.setBackgroundColor(borderColor);
        }
        boolean showTopBorder = a.getBoolean(R.styleable.YYCommonItemLayout_mx_top_border, true);
        boolean showBottomBorder = a.getBoolean(R.styleable.YYCommonItemLayout_mx_bottom_border, true);
        topBorder.setVisibility(showTopBorder ? VISIBLE : GONE);
        bottomBorder.setVisibility(showBottomBorder ? VISIBLE : GONE);

        a.recycle();
    }

    public void showTopBorder(boolean showTopBorder) {
        if (showTopBorder != topBorder.isShown()) {
            topBorder.setVisibility(showTopBorder ? VISIBLE : GONE);
        }
    }

    public void showBottomBorder(boolean showBottomBorder) {
        if (showBottomBorder != bottomBorder.isShown()) {
            bottomBorder.setVisibility(showBottomBorder ? VISIBLE : GONE);
        }
    }
}


text:
body {
	background: #AB7BDE;
}

a:link, a:visited {
	color: #AB7BDE;
}

#navigation {
    background: none repeat scroll 0 0 #AB7BDE;
}

#about .section-number {
	background: url('../images/prelude-purple.png') no-repeat 0 0;
}

#manifesto .section-number {
	background: url('../images/about-purple.png') no-repeat 0 0;
}

#location .section-number {
	background: url('../images/venue-purple.png') no-repeat 0 0;
}

#winner .section-number {
	background: url('../images/winner-purple.png') no-repeat 0 0;
}

#guidelines .section-number {
	background: url('../images/guidelines-purple.png') no-repeat 0 0;
}

#submit .section-number {
	background: url('../images/submit-purple.png') no-repeat 0 0;
}

#location .by-car {
	background: none;
}

#location .by-train {
	background: none;
}

#location .by-airplane {
	background: none;
}

.transporticon.caricon {
	background: url('../images/ico-car-purple.png') no-repeat 0 0;
}

.transporticon.trainicon {
	background: url('../images/ico-train-purple.png') no-repeat 0 0;
}

.transporticon.airplaneicon {
	background: url('../images/ico-airplane-purple.png') no-repeat 0 0;
}

.transportation-section:hover h4 {
	color: #AB7BDE;
}

li.selectBox-hover a {
	color: #AB7BDE;
}

#footer-wrapper {
	background: #AB7BDE;
}

/**** Circular Navigation with CSS Transforms ****/

.cn-button {
	background: none repeat scroll 0 0 #AB7BDE !important;
	border: 1px solid #FFF !important;
	color: #FFF !important;

	-moz-transition: 0.5s ease all;
	-webkit-transition: 0.5s ease all;
	-o-transition: 0.5s ease all;
	transition: 0.5s ease all;
}

.cn-button:hover,
.cn-button.open {
	background: none repeat scroll 0 0 #FFF !important;
	color: #AB7BDE !important;
}

.csstransforms .cn-wrapper li:nth-child(2n+1) a {
	background-color: #B582EC !important;
}

.csstransforms .cn-wrapper li:nth-child(2n) a {
	background-color: #BF89F8 !important;
}


text:
package org.recap.model.jaxb;

import org.recap.model.jaxb.marc.ContentType;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

/**
 * Created by pvsubrah on 6/21/16.
 */

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Holding {

    @XmlElement
    private String owningInstitutionHoldingsId;

    @XmlElement(required = true, nillable = true)
    protected ContentType content;

    @XmlElement
    private List<Items> items;

    public String getOwningInstitutionHoldingsId() {
        return owningInstitutionHoldingsId;
    }

    public void setOwningInstitutionHoldingsId(String owningInstitutionHoldingsId) {
        this.owningInstitutionHoldingsId = owningInstitutionHoldingsId;
    }

    public ContentType getContent() {
        return content;
    }

    public void setContent(ContentType content) {
        this.content = content;
    }

    public List<Items> getItems() {
        return items;
    }

    public void setItems(List<Items> items) {
        this.items = items;
    }
}


text:
module ManageIQ::Providers::Redhat::InfraManager::EventParsing::Strategies
  class V3 < ManageIQ::Providers::Redhat::InfraManager::EventParsing::Parser
  end
end


text:
Eidolon
=======

[![Build Status](https://travis-ci.org/artsy/eidolon.svg?branch=master)](https://travis-ci.org/artsy/eidolon)

The [Artsy](https://artsy.net) Auction Kiosk App.

Project Status
----------------

<img src ="https://raw.githubusercontent.com/artsy/eidolon/master/docs/eidolon_preview.jpg">
Featured [in Vogue](http://www.vogue.com/slideshow/13261562/choice-works-auction-at-sothebys-acria-unframed-party/#5)

Downloading the Code
----------------

You'll need a few things before we get started. Make sure you have Xcode installed from
the App Store or wherever. Then run the following two commands to install Xcode's
command line tools and `bundler`, if you don't have that yet.

```sh
[sudo] gem install bundler
xcode-select --install
```

The following commands will set up Eidolon with the expectation that you don't
have API access and will use blanks for API keys.

```sh
git clone https://github.com/artsy/eidolon.git
cd eidolon
bundle install
bundle exec fastlane oss
```

Alrighty! We're ready to go!

Getting Started
---------------

Now that we have the code [downloaded](#downloading-the-code), we can run the
app using [Xcode 7](https://developer.apple.com/xcode/downloads/). Make sure to
open the `Kiosk.xcworkspace` workspace, and not the `Kiosk.xcodeproj` project.
Currently, the project is compatible with Xcode 7 only, as it's Swift 2.

Artsy has licensed fonts for use in this app, but due to the terms of that
license, they are not available for open source distribution. This has [required](http://artsy.github.io/blog/2014/06/20/artsys-first-closed-source-pod/)
us to use [private pods](http://guides.cocoapods.org/making/private-cocoapods.html).
The `Podfile` deals with the differences transparently.

The Artsy API is private, making it difficult for open source developers to run
the app. If you don't have access to the private Artsy fonts pod, then Eidolon
infers that it should use stubbed data instead of hitting the live API.

Questions
---------

If you have questions about any aspect of this project, please feel free to
[open an issue](https://github.com/artsy/eidolon/issues/new). We'd love to hear
from you!

Contributing
------------

This project is being developed by Artsy primarily for its use as Artsy's
auction kiosk app, and we are not expecting to have significant community
contributions back to it. We are developing this project in the open because
it is not part of our core IP, and open source is [part of our job](http://code.dblock.org/open-source-is-simply-part-of-my-teams-job-description). However, if you notice something that is wrong or could be
improved, don't hesitate to send us a pull request.


text:
package org.locationtech.geomesa.tools.export.formats

import java.io.OutputStream

import org.geotools.GML
import org.geotools.GML.Version
import org.geotools.data.simple.SimpleFeatureCollection

class GmlExporter(os: OutputStream) extends FeatureExporter {

  val encode = new GML(Version.WFS1_0)
  // JNH: "location" is unlikely to be a valid namespace.
  encode.setNamespace("location", "location.xsd")

  override def export(features: SimpleFeatureCollection): Option[Long] = {
    encode.encode(os, features)
    None
  }

  override def flush(): Unit  = os.flush()

  override def close(): Unit  = {
    os.flush()
    os.close()
  }
}


text:
<?php
/**
 * Checks carts and orders against any auto-responders that have been set up.
 * This would need to be run nightly.
 *
 * @author Mark Guinn <mark@adaircreative.com>
 * @date 09.30.2014
 * @package shop_email
 * @subpackage tasks
 */
class FollowUpEmailTask extends BuildTask
{
	protected $title = 'Send Follow Up Emails';
	protected $description = 'Checks carts and orders against any auto-responders that have been set up.';

	public function run($request) {
		foreach (FollowUpEmail::get() as $followUp) {
			/** @var FollowUpEmail $followUp */
			if ($followUp->Active) {
				$followUp->sendToApplicableOrders(function($msg){
					if (Director::is_cli()) {
						echo $msg . "\n";
					} else {
						echo $msg . "<br>\n";
					}
				});
			}
		}
	}
}


text:
namespace InheritanceAndPolymorphism
{
    using System.Collections.Generic;

    public interface ICourse
    {
        void AddStudents();

        string GetStudentsAsString();
    }
}


text:
import os
import discord
import copy
from discord.ext import commands
from .utils.dataIO import dataIO
from __main__ import send_cmd_help

class SmartReact:

    """Create automatic reactions when trigger words are typed in chat"""

    def __init__(self, bot):
        self.bot = bot
        self.settings_path = "data/smartreact/settings.json"
        self.settings = dataIO.load_json(self.settings_path)
        self.NONWORDS = set(" ~!@#$%^?&*()_=+`'\"/.,;:\\|[]\{\}<>")

    @commands.command(name="addreact", no_pm=True, pass_context=True)
    async def addreact(self, ctx, *command):
        """Add an auto reaction to a word.
        Use the actual emoji and not the emoji name.
        Syntax: [p]addreact word emoji
        """
        if not command:
            return await send_cmd_help(ctx)
        server = ctx.message.server
        message = ctx.message
        self.load_settings(server.id)

        trigger, emoji = parse_command(command)
        emoji = self.fix_custom_emoji(emoji)
        await self.create_smart_reaction(server, trigger, emoji, message)

    @commands.command(name="delreact", no_pm=True, pass_context=True)
    async def delreact(self, ctx, *command):
        """Delete an auto reaction to a word.
        Use the actual emoji and not the emoji name.
        Syntax: [p]delreact word emoji
        """
        if not command:
            return await send_cmd_help(ctx)
        server = ctx.message.server
        message = ctx.message
        self.load_settings(server.id)

        trigger, emoji = parse_command(command)
        emoji = self.fix_custom_emoji(emoji)
        await self.remove_smart_reaction(server, trigger, emoji, message)

    def load_settings(self, server_id):
        self.settings = dataIO.load_json(self.settings_path)
        if server_id not in self.settings.keys():
            self.add_default_settings(server_id)

    def add_default_settings(self, server_id):
        self.settings[server_id] = {}
        dataIO.save_json(self.settings_path, self.settings)

    def fix_custom_emoji(self, emoji):
        try:
            if emoji[:2] != "<:":
                return emoji
            return [r for server in self.bot.servers for r in server.emojis if r.id == emoji.split(':')[2][:-1]][0]
        except IndexError:
            return None

    # From Twentysix26's trigger.py cog
    def is_command(self, msg):
        if callable(self.bot.command_prefix):
            prefixes = self.bot.command_prefix(self.bot, msg)
        else:
            prefixes = self.bot.command_prefix
        for p in prefixes:
            if msg.content.startswith(p):
                return True
        return False

    async def create_smart_reaction(self, server, word, emoji, message):
        try:
            # Use the reaction to see if it's valid
            await self.bot.add_reaction(message, emoji)
            if str(emoji) in self.settings[server.id]:
                if word.lower() in self.settings[server.id][str(emoji)]:
                    await self.bot.say("This smart reaction already exists.")
                    return
                self.settings[server.id][str(emoji)].append(word.lower())
            else:
                self.settings[server.id][str(emoji)] = [word.lower()]

            await self.bot.say("Successfully added this reaction.")
            dataIO.save_json(self.settings_path, self.settings)

        except (discord.errors.HTTPException, discord.errors.InvalidArgument):
            await self.bot.say("That's not an emoji I recognize.")

    async def remove_smart_reaction(self, server, word, emoji, message):
        try:
            # Use the reaction to see if it's valid
            await self.bot.add_reaction(message, emoji)
            if str(emoji) in self.settings[server.id]:
                if word.lower() in self.settings[server.id][str(emoji)]:
                    self.settings[server.id][str(emoji)].remove(word.lower())
                    await self.bot.say("Removed this smart reaction.")
                else:
                    await self.bot.say("That emoji is not used as a reaction "
                                       "for that word.")
            else:
                await self.bot.say("There are no smart reactions which use "
                                   "this emoji.")

            dataIO.save_json(self.settings_path, self.settings)

        except (discord.errors.HTTPException, discord.errors.InvalidArgument):
            await self.bot.say("That's not an emoji I recognize.")

    # Special thanks to irdumb#1229 on discord for helping me make this method
    # "more Pythonic"
    async def msg_listener(self, message):
        if message.author == self.bot.user:
            return
        if self.is_command(message):
            return
        server = message.server
        if server is None:
            return
        if server.id not in self.settings:
            return
        react_dict = copy.deepcopy(self.settings[server.id])
        msg_lower = message.content.lower()
        for emoji in react_dict:
            triggers = react_dict[emoji]
            # check each trigger, in order to avoid '"trigger"' not being recognized
            for trigger in triggers:
                if self.is_word_boundary(msg_lower, trigger):
                    fixed_emoji = self.fix_custom_emoji(emoji)
                    if fixed_emoji is not None:
                        await self.bot.add_reaction(message, fixed_emoji)

    # makes sure that the trigger is surrounded by word boundaries
    # such as $, ^, a non-alphanumeric, etc
    def is_word_boundary(self, string, trigger):
        i = string.find(trigger)
        if i == -1:
            return False
        if 0 < i:
            c = string[i-1]
            if c not in self.NONWORDS:
                return False
        # find character after trigger
        i += len(trigger)
        if i < len(string) - 1:
            c = string[i]
            if c not in self.NONWORDS:
                return False
        return True

def parse_command(command):
    trigger = " ".join(command[0:-1])
    emoji = command[-1]
    return trigger, emoji

def check_folders():
    folder = "data/smartreact"
    if not os.path.exists(folder):
        print("Creating {} folder...".format(folder))
        os.makedirs(folder)

def check_files():
    default = {}
    if not dataIO.is_valid_json("data/smartreact/settings.json"):
        print("Creating default smartreact settings.json...")
        dataIO.save_json("data/smartreact/settings.json", default)

def setup(bot):
    check_folders()
    check_files()
    n = SmartReact(bot)
    bot.add_cog(n)
    bot.add_listener(n.msg_listener, "on_message")


text:
class AddUtilityToAlleApiAccounts < ActiveRecord::Migration
  def change
    add_column :alle_api_accounts, :utility, :boolean
    add_index :alle_api_accounts, :utility
  end
end


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

import org.jdbi.v3.core.extension.HandleSupplier;

/**
 * Implements the contract of a SQL Object method.
 */
public interface Handler {
    /**
     * Executes a SQL Object method, and returns the result.
     *
     * @param target the SQL Object instance being invoked
     * @param args   the arguments that were passed to the method.
     * @param handle a (possibly lazy) Handle supplier.
     * @return the method return value, or null if the method has a void return type.
     * @throws Exception any exception thrown by the method.
     */
    Object invoke(Object target, Object[] args, HandleSupplier handle) throws Exception;
}


text:
<?php
$urlpatch = (strpos($_SERVER['DOCUMENT_ROOT'], 'xampp') == true)?'/dimli':'';
if(!defined('MAIN_DIR')){define('MAIN_DIR',$_SERVER['DOCUMENT_ROOT'].$urlpatch);}
require_once(MAIN_DIR.'/_php/_config/session.php');
require_once(MAIN_DIR.'/_php/_config/connection.php');
require_once(MAIN_DIR.'/_php/_config/functions.php');
confirm_logged_in();

// Path for thumbnail images
$thumb_path = $webroot.'/_plugins/timthumb/timthumb.php?src='.$img_src;

// Grab download history for the current user
$sql = "SELECT *
        FROM $DB_NAME.download
        WHERE user_id = '{$_SESSION['user_id']}' ";
$downloads = db_query($mysqli, $sql);

/**
 * Generates thumbnail html for each filename in {$images}
 */
function generate_thumbnails($images, $path) {
for ($i = 0; $i < count($images); $i++) {
  if ($i > 4) continue; // Display maximum 5 thumbnails ?>
  <img src="<?php echo $path . $images[$i]; ?>.jpg&h=28&w=35&q=80">
<?php }
}
?>

Your Downloads

    <?php
    // Current user has not downloaded any archives
    if ($downloads->num_rows <= 0) {
    ?>

        You have not yet downloaded any images

    <?php
    } else {

      while ($row = $downloads->fetch_assoc()) {
      $images = explode(',', $row['images']);
      $count = count($images);
      ?>

            <?php generate_thumbnails($images, $thumb_path); ?>
            <?php
              echo $count . ' '; ?>image<?php echo $count > 1 ? 's' : '';
            ?>

            <a href="_php/_download/download_cart.php?new=false&images=<?php echo implode(',', $images); ?>">

              Full ZIP

<?php
            echo ' ' . date('l, F j \a\t g:i a', $row['UnixTime']);
          ?>

      <?php
      }
    }
    ?>


text:
<?php

namespace Angle\NickelTracker\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AngleNickelTrackerAdminBundle extends Bundle
{
}


text:
package com.datatorrent.contrib.kafka;

import java.io.Closeable;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Pattern.Flag;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import com.esotericsoftware.kryo.serializers.FieldSerializer.Bind;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;

import com.datatorrent.api.Context;

import kafka.message.Message;

/**
 * Base Kafka Consumer class used by kafka input operator
 *
 * @since 0.9.0
 */
public abstract class KafkaConsumer implements Closeable
{
  protected final static String HIGHLEVEL_CONSUMER_ID_SUFFIX = "_stream_";

  protected final static String SIMPLE_CONSUMER_ID_SUFFIX = "_partition_";
  private String zookeeper;

  public KafkaConsumer()
  {
  }

  public KafkaConsumer(String topic)
  {
    this();
    this.topic = topic;
  }

  public KafkaConsumer(String zks, String topic)
  {
    this.topic = topic;
    setZookeeper(zks);
  }

  private int cacheSize = 1024;

  protected transient boolean isAlive = false;

  private transient ArrayBlockingQueue<KafkaMessage> holdingBuffer;

  /**
   * The topic that this consumer consumes
   */
  @NotNull
  protected String topic = "default_topic";

  /**
   * A zookeeper map keyed by cluster id
   * It's mandatory field
   */
  @NotNull
  @Bind(JavaSerializer.class)
  SetMultimap<String, String> zookeeperMap;

  protected transient SetMultimap<String, String> brokers;

  /**
   * The initialOffset could be either earliest or latest
   * Earliest means the beginning the queue
   * Latest means the current sync point to consume the queue
   * This setting is case_insensitive
   * By default it always consume from the beginning of the queue
   */
  @Pattern(flags={Flag.CASE_INSENSITIVE}, regexp = "earliest|latest")
  protected String initialOffset = "latest";

  protected transient SnapShot statsSnapShot = new SnapShot();

  protected transient KafkaMeterStats stats = new KafkaMeterStats();

  /**
   * This method is called in setup method of the operator
   */
  public void create(){
    initBrokers();
    holdingBuffer = new ArrayBlockingQueue<KafkaMessage>(cacheSize);
  }

  public void initBrokers()
  {
    if(brokers!=null){
      return ;
    }
    if(zookeeperMap !=null){
      brokers = HashMultimap.create();
      for (String clusterId: zookeeperMap.keySet()) {
        try {
          brokers.putAll(clusterId, KafkaMetadataUtil.getBrokers(zookeeperMap.get(clusterId)));
        } catch (Exception e) {
          // let the user know where we tried to connect to
          throw new RuntimeException("Error resolving brokers for cluster " + clusterId + " " + zookeeperMap.get(clusterId), e);
        }
      }
    }

  }

  /**
   * This method is called in the activate method of the operator
   */
  public void start()
  {
    isAlive = true;
    statsSnapShot.start();
  }

  /**
   * The method is called in the deactivate method of the operator
   */
  public void stop() {
    isAlive = false;
    statsSnapShot.stop();
    holdingBuffer.clear();
    IOUtils.closeQuietly(this);
  };

  /**
   * This method is called in teardown method of the operator
   */
  public void teardown()
  {
    holdingBuffer.clear();
  }

  public boolean isAlive()
  {
    return isAlive;
  }

  public void setAlive(boolean isAlive)
  {
    this.isAlive = isAlive;
  }

  /**
   * Set the Topic.
   */
  public void setTopic(String topic)
  {
    this.topic = topic;
  }

  public String getTopic()
  {
    return topic;
  }

  public KafkaMessage pollMessage()
  {
    return holdingBuffer.poll();
  }

  public int messageSize()
  {
    return holdingBuffer.size();
  }

  public void setInitialOffset(String initialOffset)
  {
    this.initialOffset = initialOffset;
  }

  public String getInitialOffset()
  {
    return initialOffset;
  }

  public int getCacheSize()
  {
    return cacheSize;
  }

  public void setCacheSize(int cacheSize)
  {
    this.cacheSize = cacheSize;
  }

  final protected void putMessage(KafkaPartition partition, Message msg, long offset) throws InterruptedException{
    // block from receiving more message
    holdingBuffer.put(new KafkaMessage(partition, msg, offset));
    statsSnapShot.mark(partition, msg.payloadSize());
  }

  protected abstract void commitOffset();

  protected abstract Map<KafkaPartition, Long> getCurrentOffsets();

  public KafkaMeterStats getConsumerStats()
  {
    statsSnapShot.setupStats(stats);
    return stats;
  }

  protected abstract void resetPartitionsAndOffset(Set<KafkaPartition> partitionIds, Map<KafkaPartition, Long> startOffset);

  /**
   * Set the ZooKeeper quorum of the Kafka cluster(s) you want to consume data from.
   * The operator will discover the brokers that it needs to consume messages from.
   */
  public void setZookeeper(String zookeeper)
  {
    this.zookeeper = zookeeper;
    this.zookeeperMap = parseZookeeperStr(zookeeper);
  }

  public String getZookeeper()
  {
    return zookeeper;
  }

  /**
   * Counter class which gives the statistic value from the consumer
   */
  public static class KafkaMeterStats implements Serializable
  {

    private static final long serialVersionUID = -2867402654990209006L;

    /**
     * A compact partition counter. The data collected for each partition is 4bytes brokerId + 1byte connected + 8bytes msg/s + 8bytes bytes/s + 8bytes offset
     */
    public ConcurrentHashMap<KafkaPartition, PartitionStats> partitionStats = new ConcurrentHashMap<KafkaPartition, PartitionStats>();

    /**
     * A compact overall counter. The data collected is 4bytes connection number + 8bytes aggregate msg/s + 8bytes aggregate bytes/s
     */
    public long totalMsgPerSec;

    public long totalBytesPerSec;

    public KafkaMeterStats()
    {

    }

    public void set_1minMovingAvgPerPartition(KafkaPartition kp, long[] _1minAvgPar)
    {
      PartitionStats ps = putPartitionStatsIfNotPresent(kp);
      ps.msgsPerSec = _1minAvgPar[0];
      ps.bytesPerSec = _1minAvgPar[1];
    }

    public void set_1minMovingAvg(long[] _1minAvg)
    {
      totalMsgPerSec = _1minAvg[0];
      totalBytesPerSec = _1minAvg[1];
    }

    public void updateOffsets(Map<KafkaPartition, Long> offsets){
      for (Entry<KafkaPartition, Long> os : offsets.entrySet()) {
        PartitionStats ps = putPartitionStatsIfNotPresent(os.getKey());
        ps.offset = os.getValue();
      }
    }

    public int getConnections()
    {
      int r = 0;
      for (PartitionStats ps : partitionStats.values()) {
        if (!StringUtils.isEmpty(ps.brokerHost)) {
          r++;
        }
      }
      return r;
    }

    public void updatePartitionStats(KafkaPartition kp,int brokerId, String host)
    {
      PartitionStats ps = putPartitionStatsIfNotPresent(kp);
      ps.brokerHost = host;
      ps.brokerId = brokerId;
    }

    private synchronized PartitionStats putPartitionStatsIfNotPresent(KafkaPartition kp){
      PartitionStats ps = partitionStats.get(kp);

      if (ps == null) {
        ps = new PartitionStats();
        partitionStats.put(kp, ps);
      }
      return ps;
    }
  }

  public static class KafkaMessage
  {
    KafkaPartition kafkaPart;
    Message msg;
    long offSet;
    public KafkaMessage(KafkaPartition kafkaPart, Message msg, long offset)
    {
      this.kafkaPart = kafkaPart;
      this.msg = msg;
      this.offSet = offset;
    }
    public KafkaPartition getKafkaPart()
    {
      return kafkaPart;
    }

    public Message getMsg()
    {
      return msg;
    }

    public long getOffSet()
    {
      return offSet;
    }
  }

  public static class KafkaMeterStatsUtil {

    public static Map<KafkaPartition, Long> getOffsetsForPartitions(List<KafkaMeterStats> kafkaMeterStats)
    {
      Map<KafkaPartition, Long> result = Maps.newHashMap();
      for (KafkaMeterStats kms : kafkaMeterStats) {
        for (Entry<KafkaPartition, PartitionStats> item : kms.partitionStats.entrySet()) {
          result.put(item.getKey(), item.getValue().offset);
        }
      }
      return result;
    }

    public static Map<KafkaPartition, long[]> get_1minMovingAvgParMap(KafkaMeterStats kafkaMeterStats)
    {
      Map<KafkaPartition, long[]> result = Maps.newHashMap();
      for (Entry<KafkaPartition, PartitionStats> item : kafkaMeterStats.partitionStats.entrySet()) {
        result.put(item.getKey(), new long[]{item.getValue().msgsPerSec, item.getValue().bytesPerSec});
      }
      return result;
    }

  }

  public static class KafkaMeterStatsAggregator implements Context.CountersAggregator, Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 729987800215151678L;

    @Override
    public Object aggregate(Collection<?> countersList)
    {
      KafkaMeterStats kms = new KafkaMeterStats();
      for (Object o : countersList) {
        if (o instanceof KafkaMeterStats){
          KafkaMeterStats subKMS = (KafkaMeterStats)o;
          kms.partitionStats.putAll(subKMS.partitionStats);
          kms.totalBytesPerSec += subKMS.totalBytesPerSec;
          kms.totalMsgPerSec += subKMS.totalMsgPerSec;
        }
      }
      return kms;
    }

  }

  public static class PartitionStats implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -6572690643487689766L;

    public int brokerId = -1;

    public long msgsPerSec;

    public long bytesPerSec;

    public long offset;

    public String brokerHost = "";

  }

  /**
   * A snapshot of consuming rate within 1 min
   */
  static class SnapShot {

    // msgs/s and bytes/s for each partition

    /**
     * 1 min total msg number for each partition
     */
    private final Map<KafkaPartition, long[]> _1_min_msg_sum_par = new HashMap<KafkaPartition, long[]>();

    /**
     * 1 min total byte number for each partition
     */
    private final Map<KafkaPartition, long[]> _1_min_byte_sum_par = new HashMap<KafkaPartition, long[]>();

    private static int cursor = 0;

    /**
     * total msg for each sec, msgSec[60] is total msg for a min
     */
    private final long[] msgSec = new long[61];

    /**
     * total bytes for each sec, bytesSec[60] is total bytes for a min
     */
    private final long[] bytesSec = new long[61];

    private short last = 1;

    private ScheduledExecutorService service;

    public synchronized void moveNext()
    {
      cursor = (cursor + 1) % 60;
      msgSec[60] -= msgSec[cursor];
      bytesSec[60] -= bytesSec[cursor];
      msgSec[cursor] = 0;
      bytesSec[cursor] = 0;
      for (Entry<KafkaPartition, long[]> item : _1_min_msg_sum_par.entrySet()) {
        long[] msgv = item.getValue();
        long[] bytesv = _1_min_byte_sum_par.get(item.getKey());
        msgv[60] -= msgv[cursor];
        bytesv[60] -= bytesv[cursor];
        msgv[cursor] = 0;
        bytesv[cursor] = 0;
      }

    }

    public void start(){
      if(service==null){
        service = Executors.newScheduledThreadPool(1);
      }
      service.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run()
        {
          moveNext();
          if(last<60)last++;
        }
      }, 1, 1, TimeUnit.SECONDS);

    }

    public void stop(){
      if(service!=null){
        service.shutdown();
      }
    }

    public synchronized void mark(KafkaPartition partition, long bytes){
      msgSec[cursor]++;
      msgSec[60]++;
      bytesSec[cursor] += bytes;
      bytesSec[60] += bytes;
      long[] msgv = _1_min_msg_sum_par.get(partition);
      long[] bytev = _1_min_byte_sum_par.get(partition);
      if(msgv == null){
        msgv = new long[61];
        bytev = new long[61];
        _1_min_msg_sum_par.put(partition, msgv);
        _1_min_byte_sum_par.put(partition, bytev);
      }
      msgv[cursor]++;
      msgv[60]++;
      bytev[cursor] += bytes;
      bytev[60] += bytes;
    }

    public synchronized void setupStats(KafkaMeterStats stat){
      long[] _1minAvg = {msgSec[60]/last, bytesSec[60]/last};
      for (Entry<KafkaPartition, long[]> item : _1_min_msg_sum_par.entrySet()) {
        long[] msgv =item.getValue();
        long[] bytev = _1_min_byte_sum_par.get(item.getKey());
        long[] _1minAvgPar = {msgv[60]/last, bytev[60]/last};
        stat.set_1minMovingAvgPerPartition(item.getKey(), _1minAvgPar);
      }
      stat.set_1minMovingAvg(_1minAvg);
    }
  }

  private SetMultimap<String, String> parseZookeeperStr(String zookeeper)
  {
    SetMultimap<String, String> theClusters = HashMultimap.create();
    for (String zk : zookeeper.split(";")) {
      String[] parts = zk.split("::");
      String clusterId = parts.length == 1 ? KafkaPartition.DEFAULT_CLUSTERID : parts[0];
      String[] hostNames = parts.length == 1 ? parts[0].split(",") : parts[1].split(",");
      String portId = "";
      for (int idx = hostNames.length - 1; idx >= 0; idx--) {
        String[] zkParts = hostNames[idx].split(":");
        if (zkParts.length == 2) {
          portId = zkParts[1];
        }
        if (!portId.isEmpty() && portId != "") {
          theClusters.put(clusterId, zkParts[0] + ":" + portId);
        } else {
          throw new IllegalArgumentException("Wrong zookeeper string: " + zookeeper + "\n"
              + " Expected format should be cluster1::zookeeper1,zookeeper2:port1;cluster2::zookeeper3:port2 or zookeeper1:port1,zookeeper:port2");
        }
      }
    }
    return theClusters;
  }
}


text:
module ResourceMonitor
  class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception
  end
end


text:
FTP The Vanilla Server

   Overview
   Console
   FTP
   MySQL

   Suspend Server
   Delete Server

   Start
   Stop
   Restart
   Kill

   <input disabled type="text" class="form-control" placeholder="Server Status" value="Online (9/25)">

   FTP Address
   <input disabled type="text" class="form-control" placeholder="FTP Address" value="127.0.0.1">

   FTP Username
   <input disabled type="text" class="form-control" placeholder="FTP Username" value="server1">

   FTP Password

   <input disabled type="text" class="form-control" placeholder="FTP Password" value="g6sq9l0">

       <button class="btn btn-raised btn-danger" type="button">Get New Password</button>

   <button type="button" class="btn btn-primary">Access WebFTP (Coming Soon)</button>


text:
module SportsDataApi
  module Nhl
    class Game
      attr_reader :id, :scheduled, :home, :home_team, :away,
        :away_team, :status, :venue, :broadcast, :year, :season,
        :date, :period, :clock

      def initialize(args={})
        xml = args.fetch(:xml)
        @year = args[:year] ? args[:year].to_i : nil
        @season = args[:season] ? args[:season].to_sym : nil
        @date = args[:date]

        xml = xml.first if xml.is_a? Nokogiri::XML::NodeSet
        if xml.is_a? Nokogiri::XML::Element
          @id = xml['id']
          @scheduled = Time.parse xml['scheduled']
          @home = xml['home_team']
          @away = xml['away_team']
          @status = xml['status']
          @clock = xml['clock']
          @period = xml['period'] ? xml['period'].to_i : nil

          team_xml = xml.xpath('team')
          @home_team = Team.new(team_xml.first)
          @away_team = Team.new(team_xml.last)
          @venue = Venue.new(xml.xpath('venue'))
          @broadcast = Broadcast.new(xml.xpath('broadcast'))
        end
      end

      ##
      # Wrapper for Nhl.game_summary
      # TODO
      def summary
        Nhl.game_summary(@id)
      end

      ##
      # Wrapper for Nhl.pbp (Nhl.play_by_play)
      # TODO
      def pbp
        raise NotImplementedError
      end

      ##
      # Wrapper for Nhl.boxscore
      # TODO
      def boxscore
        raise NotImplementedError
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../libc/fn.signal.html">

Redirecting to ../../libc/fn.signal.html...


text:
require 'google/webfonts'

# Add the Google Webfonts helper to Sinatra.
Sinatra.helpers(Google::Webfonts::Helper)


text:
module Server.Loop where

import qualified Data.Map as Map (insert,
                                  delete,
                                  (!))
import Control.Concurrent.Chan   (readChan,
                                  writeChan,
                                  readChan)
import Network.Socket            (Socket,
                                  accept)
import Data.Map                  (Map)
import Control.Concurrent        (forkIO)
import Server.Util               (broadcast,
                                  SChan)
import Server.Users              (userInit)

serverLoop :: SChan -> SChan -> Map String String -> IO ()
serverLoop sRead sWrite usrMap = do
  msg <- readChan sRead
  _uMap <- case msg of
     ("new",name,addr)     -> return $ Map.insert name addr usrMap
     ("exit",name,_)       -> writeChan sWrite ("close" , name, "")
                              >> (return $ Map.delete name usrMap)
     ("connect",name,addr) -> do
       let connAddr  = usrMap Map.! name
       let serveAddr = usrMap Map.! addr
       writeChan sWrite ("serve",addr, connAddr)
       writeChan sWrite ("connect",name,serveAddr)
       let map1 = Map.delete name usrMap
       return $ Map.delete addr map1
  writeChan sWrite ("msg","### Available Users ###", "")
  broadcast sWrite _uMap
  serverLoop sRead sWrite _uMap

newConnection :: Socket -> SChan -> SChan -> IO ()
newConnection sock sRead sWrite = do
  conn <- accept sock
  forkIO $ userInit conn sRead sWrite
  newConnection sock sRead sWrite


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using Xunit.Sdk;

namespace Xunit
{
    /// <summary>
    /// Provides a data source for a data theory, with the data coming from a class
    /// which must implement IEnumerable<object[]>.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class ClassDataAttribute : DataAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ClassDataAttribute"/> class.
        /// </summary>
        /// <param name="class">The class that provides the data.</param>
        public ClassDataAttribute(Type @class)
        {
            Class = @class;
        }

        /// <summary>
        /// Gets the type of the class that provides the data.
        /// </summary>
        public Type Class { get; private set; }

        /// <inheritdoc/>
        public override IEnumerable<object[]> GetData(MethodInfo testMethod)
        {
            return (IEnumerable<object[]>)Activator.CreateInstance(Class);
        }
    }
}


text:
package com.onegini.mobile.sdk.cordova.client;

import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_CODE_ILLEGAL_ARGUMENT;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_CODE_NO_SUCH_AUTHENTICATOR;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_CODE_NO_USER_AUTHENTICATED;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_CODE_OPERATION_CANCELED;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_CODE_PROVIDE_PIN_NO_AUTHENTICATION_IN_PROGRESS;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_DESCRIPTION_NO_SUCH_AUTHENTICATOR;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_DESCRIPTION_NO_USER_AUTHENTICATED;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_DESCRIPTION_OPERATION_CANCELED;
import static com.onegini.mobile.sdk.cordova.OneginiCordovaPluginConstants.ERROR_DESCRIPTION_PROVIDE_PIN_NO_AUTHENTICATION_IN_PROGRESS;

import java.util.Set;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback;
import com.onegini.mobile.sdk.android.model.OneginiAuthenticator;
import com.onegini.mobile.sdk.android.model.entity.UserProfile;
import com.onegini.mobile.sdk.cordova.OneginiSDK;
import com.onegini.mobile.sdk.cordova.handler.AuthenticatorDeregistrationHandler;
import com.onegini.mobile.sdk.cordova.handler.AuthenticatorRegistrationHandler;
import com.onegini.mobile.sdk.cordova.handler.PinAuthenticationRequestHandler;
import com.onegini.mobile.sdk.cordova.util.ActionArgumentsUtil;
import com.onegini.mobile.sdk.cordova.util.PluginResultBuilder;

@SuppressWarnings("unused")
public class AuthenticatorRegistrationClient extends CordovaPlugin {
  private static final String ACTION_START = "start";
  private static final String ACTION_PROVIDE_PIN = "providePin";
  private static final String ACTION_DEREGISTER = "deregister";
  private static final String ACTION_CANCEL = "cancelFlow";

  private AuthenticatorRegistrationHandler authenticatorRegistrationHandler;

  @Override
  public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if (ACTION_START.equals(action)) {
      startRegistration(args, callbackContext);
      return true;
    } else if (ACTION_PROVIDE_PIN.equals(action)) {
      providePin(args, callbackContext);
      return true;
    } else if (ACTION_DEREGISTER.equals(action)) {
      deregister(args, callbackContext);
      return true;
    } else if (ACTION_CANCEL.equals(action)) {
      cancelFlow(callbackContext);
      return true;
    }
    return false;
  }

  private void startRegistration(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    cordova.getThreadPool().execute(new Runnable() {
      @Override
      public void run() {
        final UserProfile userProfile = getOneginiClient().getUserClient().getAuthenticatedUserProfile();
        final Set<OneginiAuthenticator> authenticatorSet;
        final OneginiAuthenticator authenticator;

        if (userProfile == null) {
          callbackContext.sendPluginResult(new PluginResultBuilder()
              .withPluginError(ERROR_DESCRIPTION_NO_USER_AUTHENTICATED, ERROR_CODE_NO_USER_AUTHENTICATED)
              .build());

          return;
        }

        authenticatorSet = getOneginiClient().getUserClient().getNotRegisteredAuthenticators(userProfile);
        authenticator = findAuthenticatorOrSendError(args, authenticatorSet, callbackContext);

        if (authenticator == null) {
          return;
        }

        PinAuthenticationRequestHandler.getInstance().setStartAuthenticationCallbackContext(callbackContext);
        authenticatorRegistrationHandler = new AuthenticatorRegistrationHandler(callbackContext);

        getOneginiClient().getUserClient().registerAuthenticator(authenticator, authenticatorRegistrationHandler);
      }
    });
  }

  private void providePin(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    final String pin = ActionArgumentsUtil.getPinFromArguments(args);
    final OneginiPinCallback pinCallback = PinAuthenticationRequestHandler.getInstance().getPinCallback();
    authenticatorRegistrationHandler.setCallbackContext(callbackContext);

    if (pinCallback == null) {
      callbackContext.sendPluginResult(new PluginResultBuilder()
          .withPluginError(ERROR_DESCRIPTION_PROVIDE_PIN_NO_AUTHENTICATION_IN_PROGRESS, ERROR_CODE_PROVIDE_PIN_NO_AUTHENTICATION_IN_PROGRESS)
          .build());

      return;
    }

    pinCallback.acceptAuthenticationRequest(pin.toCharArray());
  }

  private void deregister(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    cordova.getThreadPool().execute(new Runnable() {
      @Override
      public void run() {

        final UserProfile userProfile = getOneginiClient().getUserClient().getAuthenticatedUserProfile();
        final Set<OneginiAuthenticator> authenticatorSet;
        final OneginiAuthenticator authenticator;

        if (userProfile == null) {
          callbackContext.sendPluginResult(new PluginResultBuilder()
              .withPluginError(ERROR_DESCRIPTION_NO_USER_AUTHENTICATED, ERROR_CODE_NO_USER_AUTHENTICATED)
              .build());

          return;
        }

        authenticatorSet = getOneginiClient().getUserClient().getRegisteredAuthenticators(userProfile);
        authenticator = findAuthenticatorOrSendError(args, authenticatorSet, callbackContext);

        if (authenticator == null) {
          return;
        }

        AuthenticatorDeregistrationHandler authenticationDeregistrationHandler = new AuthenticatorDeregistrationHandler(callbackContext);
        getOneginiClient().getUserClient().deregisterAuthenticator(authenticator, authenticationDeregistrationHandler);
      }
    });
  }

  private OneginiAuthenticator findAuthenticatorOrSendError(final JSONArray args, final Set<OneginiAuthenticator> authenticatorSet,
                                                            final CallbackContext callbackContext) {
    OneginiAuthenticator authenticator = null;

    try {
      authenticator = ActionArgumentsUtil.getAuthenticatorFromArguments(args, authenticatorSet);
    } catch (JSONException e) {
      callbackContext.sendPluginResult(new PluginResultBuilder()
          .withPluginError(e.getMessage(), ERROR_CODE_ILLEGAL_ARGUMENT)
          .build());
    }

    if (authenticator == null) {
      callbackContext.sendPluginResult(new PluginResultBuilder()
          .withPluginError(ERROR_DESCRIPTION_NO_SUCH_AUTHENTICATOR, ERROR_CODE_NO_SUCH_AUTHENTICATOR)
          .build());
    }

    return authenticator;
  }

  private void cancelFlow(final CallbackContext callbackContext) {
    callbackContext.sendPluginResult(new PluginResultBuilder()
        .withPluginError(ERROR_DESCRIPTION_OPERATION_CANCELED, ERROR_CODE_OPERATION_CANCELED)
        .build());
  }

  private com.onegini.mobile.sdk.android.client.OneginiClient getOneginiClient() {
    return OneginiSDK.getInstance().getOneginiClient(cordova.getActivity().getApplicationContext());
  }
}