text:
#include "precomp.hpp"

#ifdef HAVE_GPHOTO2

#include <gphoto2/gphoto2.h>

#include <algorithm>
#include <clocale>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <deque>
#include <exception>
#include <map>
#include <ostream>
#include <string>

namespace cv
{

namespace gphoto2 {

/**
 * \brief Map gPhoto2 return code into this exception.
 */
class GPhoto2Exception: public std::exception
{
private:
    int result;
    const char * method;
public:
    /**
     * @param methodStr libgphoto2 method name
     * @param gPhoto2Result libgphoto2 method result, should be less than GP_OK
     */
    GPhoto2Exception(const char * methodStr, int gPhoto2Result)
    {
        result = gPhoto2Result;
        method = methodStr;
    }
    virtual const char * what() const throw ()
    {
        return gp_result_as_string(result);
    }
    friend std::ostream & operator<<(std::ostream & ostream,
            GPhoto2Exception & e)
    {
        return ostream << e.method << ": " << e.what();
    }
};

/**
 * \brief Capture using your camera device via digital camera library - gPhoto2.
 *
 *  For library description and list of supported cameras, go to
 *  @url http://gphoto.sourceforge.net/
 *
 * Because gPhoto2 configuration is based on a widgets
 * and OpenCV CvCapture property settings are double typed
 * some assumptions and tricks has to be made.
 * 1. Device properties can be changed by IDs, use @method setProperty(int, double)
 *      and @method getProperty(int) with __additive inversed__
 *      camera setting ID as propertyId. (If you want to get camera setting
 *      with ID == x, you want to call #getProperty(-x)).
 * 2. Digital camera settings IDs are device dependent.
 * 3. You can list them by getting property CAP_PROP_GPHOTO2_WIDGET_ENUMERATE.
 * 3.1. As return you will get pointer to char array (with listed properties)
 *      instead of double. This list is in CSV type.
 * 4. There are several types of widgets (camera settings).
 * 4.1. For "menu" and "radio", you can get/set choice number.
 * 4.2. For "toggle" you can get/set int type.
 * 4.3. For "range" you can get/set float.
 * 4.4. For any other pointer will be fetched/set.
 * 5. You can fetch camera messages by using CAP_PROP_GPHOTO2_COLLECT_MSGS
 *      and CAP_PROP_GPHOTO2_FLUSH_MSGS (will return pointer to char array).
 * 6. Camera settings are fetched from device as lazy as possible.
 *      It creates problem with situation when change of one setting
 *      affects another setting. You can use CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE
 *      or CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG to be sure that property you are
 *      planning to get will be actual.
 *
 * Capture can work in 2 main modes: preview and final.
 * Where preview is an output from digital camera "liveview".
 * Change modes with CAP_PROP_GPHOTO2_PREVIEW property.
 *
 * Moreover some generic properties are mapped to widgets, or implemented:
 *  * CV_CAP_PROP_SPEED,
 *  * CV_CAP_PROP_APERATURE,
 *  * CV_CAP_PROP_EXPOSUREPROGRAM,
 *  * CV_CAP_PROP_VIEWFINDER,
 *  * CV_CAP_PROP_POS_MSEC,
 *  * CV_CAP_PROP_POS_FRAMES,
 *  * CV_CAP_PROP_FRAME_WIDTH,
 *  * CV_CAP_PROP_FRAME_HEIGHT,
 *  * CV_CAP_PROP_FPS,
 *  * CV_CAP_PROP_FRAME_COUNT
 *  * CV_CAP_PROP_FORMAT,
 *  * CV_CAP_PROP_EXPOSURE,
 *  * CV_CAP_PROP_TRIGGER_DELAY,
 *  * CV_CAP_PROP_ZOOM,
 *  * CV_CAP_PROP_FOCUS,
 *  * CV_CAP_PROP_ISO_SPEED.
 */
class DigitalCameraCapture: public IVideoCapture
{
public:
    static const char * separator;
    static const char * lineDelimiter;

    DigitalCameraCapture();
    DigitalCameraCapture(int index);
    DigitalCameraCapture(const String &deviceName);
    virtual ~DigitalCameraCapture();

    virtual bool isOpened() const;
    virtual double getProperty(int) const;
    virtual bool setProperty(int, double);
    virtual bool grabFrame();
    virtual bool retrieveFrame(int, OutputArray);
    virtual int getCaptureDomain()
    {
        return CV_CAP_GPHOTO2;
    } // Return the type of the capture object: CV_CAP_VFW, etc...

    bool open(int index);
    void close();
    bool deviceExist(int index) const;
    int findDevice(const char * deviceName) const;

protected:
    // Known widget names
    static const char * PROP_EXPOSURE_COMPENSACTION;
    static const char * PROP_SELF_TIMER_DELAY;
    static const char * PROP_MANUALFOCUS;
    static const char * PROP_AUTOFOCUS;
    static const char * PROP_ISO;
    static const char * PROP_SPEED;
    static const char * PROP_APERTURE_NIKON;
    static const char * PROP_APERTURE_CANON;
    static const char * PROP_EXPOSURE_PROGRAM;
    static const char * PROP_VIEWFINDER;

    // Instance
    GPContext * context = NULL;
    int numDevices;
    void initContext();

    // Selected device
    bool opened;
    Camera * camera = NULL;
    Mat frame;

    // Properties
    CameraWidget * rootWidget = NULL;
    CameraWidget * getGenericProperty(int propertyId, double & output) const;
    CameraWidget * setGenericProperty(int propertyId, double value,
            bool & output) const;

    // Widgets
    void reloadConfig() throw (GPhoto2Exception);
    CameraWidget * getWidget(int widgetId) const;
    CameraWidget * findWidgetByName(const char * name) const;

    // Loading
    void readFrameFromFile(CameraFile * file, OutputArray outputFrame) throw (GPhoto2Exception);

    // Context feedback
    friend void ctxErrorFunc(GPContext *, const char *, void *);
    friend void ctxStatusFunc(GPContext *, const char *, void *);
    friend void ctxMessageFunc(GPContext *, const char *, void *);

    // Messages / debug
    enum MsgType
    {
        ERROR = (int) 'E',
        WARNING = (int) 'W',
        STATUS = (int) 'S',
        OTHER = (int) 'O'
    };
    template<typename OsstreamPrintable>
    void message(MsgType msgType, const char * msg,
            OsstreamPrintable & arg) const;

private:
    // Instance
    CameraAbilitiesList * abilitiesList = NULL;
    GPPortInfoList * capablePorts = NULL;
    CameraList * allDevices = NULL;

    // Selected device
    CameraAbilities cameraAbilities;
    std::deque<CameraFile *> grabbedFrames;

    // Properties
    bool preview; // CV_CAP_PROP_GPHOTO2_PREVIEW
    std::string widgetInfo; // CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE
    std::map<int, CameraWidget *> widgets;
    bool reloadOnChange; // CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE
    time_t firstCapturedFrameTime;
    unsigned long int capturedFrames;

    DigitalCameraCapture(const DigitalCameraCapture&); // Disable copying
    DigitalCameraCapture& operator=(DigitalCameraCapture const&); // Disable assigning

    // Widgets
    int noOfWidgets;
    int widgetDescription(std::ostream &os, CameraWidget * widget) const
            throw (GPhoto2Exception);
    int collectWidgets(std::ostream &os, CameraWidget * widget)
            throw (GPhoto2Exception);

    // Messages / debug
    mutable std::ostringstream msgsBuffer; // CV_CAP_PROP_GPHOTO2_FLUSH_MSGS
    mutable std::string lastFlush; // CV_CAP_PROP_GPHOTO2_FLUSH_MSGS
    bool collectMsgs; // CV_CAP_PROP_GPHOTO2_COLLECT_MSGS
};

/**
 * \brief Check if gPhoto2 function ends successfully. If not, throw an exception.
 */
#define CR(GPHOTO2_FUN) do {\
    int r_0629c47b758;\
    if ((r_0629c47b758 = (GPHOTO2_FUN)) < GP_OK) {\
        throw GPhoto2Exception(#GPHOTO2_FUN, r_0629c47b758);\
    };\
} while(0)

/**
 * \brief gPhoto2 context error feedback function.
 * @param thatGPhotoCap is required to be pointer to DigitalCameraCapture object.
 */
void ctxErrorFunc(GPContext *, const char * str, void * thatGPhotoCap)
{
    const DigitalCameraCapture * self =
            (const DigitalCameraCapture *) thatGPhotoCap;
    self->message(self->ERROR, "context feedback", str);
}

/**
 * \brief gPhoto2 context status feedback function.
 * @param thatGPhotoCap is required to be pointer to DigitalCameraCapture object.
 */
void ctxStatusFunc(GPContext *, const char * str, void * thatGPhotoCap)
{
    const DigitalCameraCapture * self =
            (const DigitalCameraCapture *) thatGPhotoCap;
    self->message(self->STATUS, "context feedback", str);
}

/**
 * \brief gPhoto2 context message feedback function.
 * @param thatGPhotoCap is required to be pointer to DigitalCameraCapture object.
 */
void ctxMessageFunc(GPContext *, const char * str, void * thatGPhotoCap)
{
    const DigitalCameraCapture * self =
            (const DigitalCameraCapture *) thatGPhotoCap;
    self->message(self->OTHER, "context feedback", str);
}

/**
 * \brief Separator used while creating CSV.
 */
const char * DigitalCameraCapture::separator = ",";
/**
 * \brief Line delimiter used while creating any readable output.
 */
const char * DigitalCameraCapture::lineDelimiter = "\n";
/**
 * \bief Some known widget names.
 *
 * Those are actually substrings of widget name.
 * ie. for VIEWFINDER, Nikon uses "viewfinder", while Canon can use "eosviewfinder".
 */
const char * DigitalCameraCapture::PROP_EXPOSURE_COMPENSACTION =
        "exposurecompensation";
const char * DigitalCameraCapture::PROP_SELF_TIMER_DELAY = "selftimerdelay";
const char * DigitalCameraCapture::PROP_MANUALFOCUS = "manualfocusdrive";
const char * DigitalCameraCapture::PROP_AUTOFOCUS = "autofocusdrive";
const char * DigitalCameraCapture::PROP_ISO = "iso";
const char * DigitalCameraCapture::PROP_SPEED = "shutterspeed";
const char * DigitalCameraCapture::PROP_APERTURE_NIKON = "f-number";
const char * DigitalCameraCapture::PROP_APERTURE_CANON = "aperture";
const char * DigitalCameraCapture::PROP_EXPOSURE_PROGRAM = "expprogram";
const char * DigitalCameraCapture::PROP_VIEWFINDER = "viewfinder";

/**
 * Initialize gPhoto2 context, search for all available devices.
 */
void DigitalCameraCapture::initContext()
{
    capturedFrames = noOfWidgets = numDevices = 0;
    opened = preview = reloadOnChange = false;
    firstCapturedFrameTime = 0;

    context = gp_context_new();

    gp_context_set_error_func(context, ctxErrorFunc, (void*) this);
    gp_context_set_status_func(context, ctxStatusFunc, (void*) this);
    gp_context_set_message_func(context, ctxMessageFunc, (void*) this);

    try
    {
        // Load abilities
        CR(gp_abilities_list_new(&abilitiesList));
        CR(gp_abilities_list_load(abilitiesList, context));

        // Load ports
        CR(gp_port_info_list_new(&capablePorts));
        CR(gp_port_info_list_load(capablePorts));

        // Auto-detect devices
        CR(gp_list_new(&allDevices));
        CR(gp_camera_autodetect(allDevices, context));
        CR(numDevices = gp_list_count(allDevices));
    }
    catch (GPhoto2Exception & e)
    {
        numDevices = 0;
    }
}

/**
 * Search for all devices while constructing.
 */
DigitalCameraCapture::DigitalCameraCapture()
{
    initContext();
}

/**
 * @see open(int)
 */
DigitalCameraCapture::DigitalCameraCapture(int index)
{
    initContext();
    if (deviceExist(index))
        open(index);
}

/**
 * @see findDevice(const char*)
 * @see open(int)
 */
DigitalCameraCapture::DigitalCameraCapture(const String & deviceName)
{
    initContext();
    int index = findDevice(deviceName.c_str());
    if (deviceExist(index))
        open(index);
}

/**
 * Always close connection to the device.
 */
DigitalCameraCapture::~DigitalCameraCapture()
{
    close();
    try
    {
        CR(gp_abilities_list_free(abilitiesList));
        abilitiesList = NULL;
        CR(gp_port_info_list_free(capablePorts));
        capablePorts = NULL;
        CR(gp_list_unref(allDevices));
        allDevices = NULL;
        gp_context_unref(context);
        context = NULL;
    }
    catch (GPhoto2Exception & e)
    {
        message(ERROR, "destruction error", e);
    }
}

/**
 * Connects to selected device.
 */
bool DigitalCameraCapture::open(int index)
{
    const char * model = 0, *path = 0;
    int m, p;
    GPPortInfo portInfo;

    if (isOpened()) {
        close();
    }

    try
    {
        CR(gp_camera_new(&camera));
        CR(gp_list_get_name(allDevices, index, &model));
        CR(gp_list_get_value(allDevices, index, &path));

        // Set model abilities.
        CR(m = gp_abilities_list_lookup_model(abilitiesList, model));
        CR(gp_abilities_list_get_abilities(abilitiesList, m, &cameraAbilities));
        CR(gp_camera_set_abilities(camera, cameraAbilities));

        // Set port
        CR(p = gp_port_info_list_lookup_path(capablePorts, path));
        CR(gp_port_info_list_get_info(capablePorts, p, &portInfo));
        CR(gp_camera_set_port_info(camera, portInfo));

        // Initialize connection to the camera.
        CR(gp_camera_init(camera, context));

        message(STATUS, "connected camera", model);
        message(STATUS, "connected using", path);

        // State initialization
        firstCapturedFrameTime = 0;
        capturedFrames = 0;
        preview = false;
        reloadOnChange = false;
        collectMsgs = false;

        reloadConfig();

        opened = true;
        return true;
    }
    catch (GPhoto2Exception & e)
    {
        message(WARNING, "opening device failed", e);
        return false;
    }
}

/**
 *
 */
bool DigitalCameraCapture::isOpened() const
{
    return opened;
}

/**
 * Close connection to the camera. Remove all unread frames/files.
 */
void DigitalCameraCapture::close()
{
    try
    {
        if (!frame.empty())
        {
            frame.release();
        }
        if (camera)
        {
            CR(gp_camera_exit(camera, context));
            CR(gp_camera_unref(camera));
            camera = NULL;
        }
        opened = false;
        if (int frames = grabbedFrames.size() > 0)
        {
            while (frames--)
            {
                CameraFile * file = grabbedFrames.front();
                grabbedFrames.pop_front();
                CR(gp_file_unref(file));
            }
        }
        if (rootWidget)
        {
            widgetInfo.clear();
            CR(gp_widget_unref(rootWidget));
            rootWidget = NULL;
        }
    }
    catch (GPhoto2Exception & e)
    {
        message(ERROR, "cannot close device properly", e);
    }
}

/**
 * @param output will be changed if possible, return 0 if changed,
 * @return widget, or NULL if output value was found (saved in argument),
 */
CameraWidget * DigitalCameraCapture::getGenericProperty(int propertyId,
        double & output) const
{
    switch (propertyId)
    {
        case CV_CAP_PROP_POS_MSEC:
        {
            // Only seconds level precision, FUTURE: cross-platform milliseconds
            output = (time(0) - firstCapturedFrameTime) * 1e2;
            return NULL;
        }
        case CV_CAP_PROP_POS_FRAMES:
        {
            output = capturedFrames;
            return NULL;
        }
        case CV_CAP_PROP_FRAME_WIDTH:
        {
            if (!frame.empty())
            {
                output = frame.cols;
            }
            return NULL;
        }
        case CV_CAP_PROP_FRAME_HEIGHT:
        {
            if (!frame.empty())
            {
                output = frame.rows;
            }
            return NULL;
        }
        case CV_CAP_PROP_FORMAT:
        {
            if (!frame.empty())
            {
                output = frame.type();
            }
            return NULL;
        }
        case CV_CAP_PROP_FPS: // returns average fps from the begin
        {
            double wholeProcessTime = 0;
            getGenericProperty(CV_CAP_PROP_POS_MSEC, wholeProcessTime);
            wholeProcessTime /= 1e2;
            output = capturedFrames / wholeProcessTime;
            return NULL;
        }
        case CV_CAP_PROP_FRAME_COUNT:
        {
            output = capturedFrames;
            return NULL;
        }
        case CV_CAP_PROP_EXPOSURE:
            return findWidgetByName(PROP_EXPOSURE_COMPENSACTION);
        case CV_CAP_PROP_TRIGGER_DELAY:
            return findWidgetByName(PROP_SELF_TIMER_DELAY);
        case CV_CAP_PROP_ZOOM:
            return findWidgetByName(PROP_MANUALFOCUS);
        case CV_CAP_PROP_FOCUS:
            return findWidgetByName(PROP_AUTOFOCUS);
        case CV_CAP_PROP_ISO_SPEED:
            return findWidgetByName(PROP_ISO);
        case CV_CAP_PROP_SPEED:
            return findWidgetByName(PROP_SPEED);
        case CV_CAP_PROP_APERTURE:
        {
            CameraWidget * widget = findWidgetByName(PROP_APERTURE_NIKON);
            return (widget == 0) ? findWidgetByName(PROP_APERTURE_CANON) : widget;
        }
        case CV_CAP_PROP_EXPOSUREPROGRAM:
            return findWidgetByName(PROP_EXPOSURE_PROGRAM);
        case CV_CAP_PROP_VIEWFINDER:
            return findWidgetByName(PROP_VIEWFINDER);
    }
    return NULL;
}

/**
 * Get property.
 * @see DigitalCameraCapture for more information about returned double type.
 */
double DigitalCameraCapture::getProperty(int propertyId) const
{
    CameraWidget * widget = NULL;
    double output = 0;
    if (propertyId < 0)
    {
        widget = getWidget(-propertyId);
    }
    else
    {
        switch (propertyId)
        {
            // gphoto2 cap featured
            case CV_CAP_PROP_GPHOTO2_PREVIEW:
                return preview;
            case CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE:
                if (rootWidget == NULL)
                    return 0;
                return (intptr_t) widgetInfo.c_str();
            case CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG:
                return 0; // Trigger, only by set
            case CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE:
                return reloadOnChange;
            case CV_CAP_PROP_GPHOTO2_COLLECT_MSGS:
                return collectMsgs;
            case CV_CAP_PROP_GPHOTO2_FLUSH_MSGS:
                lastFlush = msgsBuffer.str();
                msgsBuffer.str("");
                msgsBuffer.clear();
                return (intptr_t) lastFlush.c_str();
            default:
                widget = getGenericProperty(propertyId, output);
                /* no break */
        }
    }
    if (widget == NULL)
        return output;
    try
    {
        CameraWidgetType type;
        CR(gp_widget_get_type(widget, &type));
        switch (type)
        {
            case GP_WIDGET_MENU:
            case GP_WIDGET_RADIO:
            {
                int cnt = 0, i;
                const char * current;
                CR(gp_widget_get_value(widget, &current));
                CR(cnt = gp_widget_count_choices(widget));
                for (i = 0; i < cnt; i++)
                {
                    const char *choice;
                    CR(gp_widget_get_choice(widget, i, &choice));
                    if (std::strcmp(choice, current) == 0)
                    {
                        return i;
                    }
                }
                return -1;
            }
            case GP_WIDGET_TOGGLE:
            {
                int value;
                CR(gp_widget_get_value(widget, &value));
                return value;
            }
            case GP_WIDGET_RANGE:
            {
                float value;
                CR(gp_widget_get_value(widget, &value));
                return value;
            }
            default:
            {
                char* value;
                CR(gp_widget_get_value(widget, &value));
                return (intptr_t) value;
            }
        }
    }
    catch (GPhoto2Exception & e)
    {
        char buf[128] = "";
        sprintf(buf, "cannot get property: %d", propertyId);
        message(WARNING, (const char *) buf, e);
        return 0;
    }
}

/**
 * @param output will be changed if possible, return 0 if changed,
 * @return widget, or 0 if output value was found (saved in argument),
 */
CameraWidget * DigitalCameraCapture::setGenericProperty(int propertyId,
        double /*FUTURE: value*/, bool & output) const
{
    switch (propertyId)
    {
        case CV_CAP_PROP_POS_MSEC:
        case CV_CAP_PROP_POS_FRAMES:
        case CV_CAP_PROP_FRAME_WIDTH:
        case CV_CAP_PROP_FRAME_HEIGHT:
        case CV_CAP_PROP_FPS:
        case CV_CAP_PROP_FRAME_COUNT:
        case CV_CAP_PROP_FORMAT:
            output = false;
            return NULL;
        case CV_CAP_PROP_EXPOSURE:
            return findWidgetByName(PROP_EXPOSURE_COMPENSACTION);
        case CV_CAP_PROP_TRIGGER_DELAY:
            return findWidgetByName(PROP_SELF_TIMER_DELAY);
        case CV_CAP_PROP_ZOOM:
            return findWidgetByName(PROP_MANUALFOCUS);
        case CV_CAP_PROP_FOCUS:
            return findWidgetByName(PROP_AUTOFOCUS);
        case CV_CAP_PROP_ISO_SPEED:
            return findWidgetByName(PROP_ISO);
        case CV_CAP_PROP_SPEED:
            return findWidgetByName(PROP_SPEED);
        case CV_CAP_PROP_APERTURE:
        {
            CameraWidget * widget = findWidgetByName(PROP_APERTURE_NIKON);
            return (widget == NULL) ? findWidgetByName(PROP_APERTURE_CANON) : widget;
        }
        case CV_CAP_PROP_EXPOSUREPROGRAM:
            return findWidgetByName(PROP_EXPOSURE_PROGRAM);
        case CV_CAP_PROP_VIEWFINDER:
            return findWidgetByName(PROP_VIEWFINDER);
    }
    return NULL;
}

/**
 * Set property.
 * @see DigitalCameraCapture for more information about value, double typed, argument.
 */
bool DigitalCameraCapture::setProperty(int propertyId, double value)
{
    CameraWidget * widget = NULL;
    bool output = false;
    if (propertyId < 0)
    {
        widget = getWidget(-propertyId);
    }
    else
    {
        switch (propertyId)
        {
            // gphoto2 cap featured
            case CV_CAP_PROP_GPHOTO2_PREVIEW:
                preview = value != 0;
                return true;
            case CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE:
                return false;
            case CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG:
                reloadConfig();
                return true;
            case CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE:
                reloadOnChange = value != 0;
                return true;
            case CV_CAP_PROP_GPHOTO2_COLLECT_MSGS:
                collectMsgs = value != 0;
                return true;
            case CV_CAP_PROP_GPHOTO2_FLUSH_MSGS:
                return false;
            default:
                widget = setGenericProperty(propertyId, value, output);
                /* no break */
        }
    }
    if (widget == NULL)
        return output;
    try
    {
        CameraWidgetType type;
        CR(gp_widget_get_type(widget, &type));
        switch (type)
        {
            case GP_WIDGET_RADIO:
            case GP_WIDGET_MENU:
            {
                int i = static_cast<int>(value);
                char *choice;
                CR(gp_widget_get_choice(widget, i, (const char**)&choice));
                CR(gp_widget_set_value(widget, choice));
                break;
            }
            case GP_WIDGET_TOGGLE:
            {
                int i = static_cast<int>(value);
                CR(gp_widget_set_value(widget, &i));
                break;
            }
            case GP_WIDGET_RANGE:
            {
                float v = static_cast<float>(value);
                CR(gp_widget_set_value(widget, &v));
                break;
            }
            default:
            {
                CR(gp_widget_set_value(widget, (void* )(intptr_t )&value));
                break;
            }
        }
        if (!reloadOnChange)
        {
            // force widget change
            CR(gp_widget_set_changed(widget, 1));
        }

        // Use the same locale setting as while getting rootWidget.
        char * localeTmp = setlocale(LC_ALL, "C");
        CR(gp_camera_set_config(camera, rootWidget, context));
        setlocale(LC_ALL, localeTmp);

        if (reloadOnChange)
        {
            reloadConfig();
        } else {
            CR(gp_widget_set_changed(widget, 0));
        }
    }
    catch (GPhoto2Exception & e)
    {
        char buf[128] = "";
        sprintf(buf, "cannot set property: %d to %f", propertyId, value);
        message(WARNING, (const char *) buf, e);
        return false;
    }
    return true;
}

/**
 * Capture image, and store file in @field grabbedFrames.
 * Do not read a file. File will be deleted from camera automatically.
 */
bool DigitalCameraCapture::grabFrame()
{
    CameraFilePath filePath;
    CameraFile * file = NULL;
    try
    {
        CR(gp_file_new(&file));

        if (preview)
        {
            CR(gp_camera_capture_preview(camera, file, context));
        }
        else
        {
            // Capture an image
            CR(gp_camera_capture(camera, GP_CAPTURE_IMAGE, &filePath, context));
            CR(gp_camera_file_get(camera, filePath.folder, filePath.name, GP_FILE_TYPE_NORMAL,
                    file, context));
            CR(gp_camera_file_delete(camera, filePath.folder, filePath.name, context));
        }
        // State update
        if (firstCapturedFrameTime == 0)
        {
            firstCapturedFrameTime = time(0);
        }
        capturedFrames++;
        grabbedFrames.push_back(file);
    }
    catch (GPhoto2Exception & e)
    {
        if (file)
            gp_file_unref(file);
        message(WARNING, "cannot grab new frame", e);
        return false;
    }
    return true;
}

/**
 * Read stored file with image.
 */
bool DigitalCameraCapture::retrieveFrame(int, OutputArray outputFrame)
{
    if (grabbedFrames.size() > 0)
    {
        CameraFile * file = grabbedFrames.front();
        grabbedFrames.pop_front();
        try
        {
            readFrameFromFile(file, outputFrame);
            CR(gp_file_unref(file));
        }
        catch (GPhoto2Exception & e)
        {
            message(WARNING, "cannot read file grabbed from device", e);
            return false;
        }
    }
    else
    {
        return false;
    }
    return true;
}

/**
 * @return true if device exists
 */
bool DigitalCameraCapture::deviceExist(int index) const
{
    return (numDevices > 0) && (index < numDevices);
}

/**
 * @return device index if exists, otherwise -1
 */
int DigitalCameraCapture::findDevice(const char * deviceName) const
{
    const char * model = 0;
    try
    {
        if (deviceName != 0)
        {
            for (int i = 0; i < numDevices; ++i)
            {
                CR(gp_list_get_name(allDevices, i, &model));
                if (model != 0 && strstr(model, deviceName))
                {
                    return i;
                }
            }
        }
    }
    catch (GPhoto2Exception & e)
    {
        ; // pass
    }
    return -1;
}

/**
 * Load device settings.
 */
void DigitalCameraCapture::reloadConfig() throw (GPhoto2Exception)
{
    std::ostringstream widgetInfoListStream;

    if (rootWidget != NULL)
    {
        widgetInfo.clear();
        CR(gp_widget_unref(rootWidget));
        rootWidget = NULL;
        widgets.clear();
    }
    // Make sure, that all configs (getting setting) will use the same locale setting.
    char * localeTmp = setlocale(LC_ALL, "C");
    CR(gp_camera_get_config(camera, &rootWidget, context));
    setlocale(LC_ALL, localeTmp);
    widgetInfoListStream << "id,label,name,info,readonly,type,value,"
            << lineDelimiter;
    noOfWidgets = collectWidgets(widgetInfoListStream, rootWidget) + 1;
    widgetInfo = widgetInfoListStream.str();
}

/**
 * Get widget which was fetched in time of last call to @reloadConfig().
 */
CameraWidget * DigitalCameraCapture::getWidget(int widgetId) const
{
    CameraWidget * widget;
    std::map<int, CameraWidget *>::const_iterator it = widgets.find(widgetId);
    if (it == widgets.end())
        return 0;
    widget = it->second;
    return widget;
}

/**
 * Search for widget with name which has @param subName substring.
 */
CameraWidget * DigitalCameraCapture::findWidgetByName(
        const char * subName) const
{
    if (subName != NULL)
    {
        try
        {
            const char * name;
            typedef std::map<int, CameraWidget *>::const_iterator it_t;
            it_t it = widgets.begin(), end = widgets.end();
            while (it != end)
            {
                CR(gp_widget_get_name(it->second, &name));
                if (strstr(name, subName))
                    break;
                it++;
            }
            return (it != end) ? it->second : NULL;
        }
        catch (GPhoto2Exception & e)
        {
            message(WARNING, "error while searching for widget", e);
        }
    }
    return 0;
}

/**
 * Image file reader.
 *
 * @FUTURE: RAW format reader.
 */
void DigitalCameraCapture::readFrameFromFile(CameraFile * file, OutputArray outputFrame)
        throw (GPhoto2Exception)
{
    // FUTURE: OpenCV cannot read RAW files right now.
    const char * data;
    unsigned long int size;
    CR(gp_file_get_data_and_size(file, &data, &size));
    if (size > 0)
    {
        Mat buf = Mat(1, size, CV_8UC1, (void *) data);
        if(!buf.empty())
        {
            frame = imdecode(buf, CV_LOAD_IMAGE_UNCHANGED);
        }
        frame.copyTo(outputFrame);
    }
}

/**
 * Print widget description in @param os.
 * @return real widget ID (if config was reloaded couple of times
 *         then IDs won't be the same)
 */
int DigitalCameraCapture::widgetDescription(std::ostream &os,
        CameraWidget * widget) const throw (GPhoto2Exception)
{
    const char * label, *name, *info;
    int id, readonly;
    CameraWidgetType type;

    CR(gp_widget_get_id(widget, &id));
    CR(gp_widget_get_label(widget, &label));
    CR(gp_widget_get_name(widget, &name));
    CR(gp_widget_get_info(widget, &info));
    CR(gp_widget_get_type(widget, &type));
    CR(gp_widget_get_readonly(widget, &readonly));

    if ((type == GP_WIDGET_WINDOW) || (type == GP_WIDGET_SECTION)
            || (type == GP_WIDGET_BUTTON))
    {
        readonly = 1;
    }
    os << (id - noOfWidgets) << separator << label << separator << name
            << separator << info << separator << readonly << separator;

    switch (type)
    {
        case GP_WIDGET_WINDOW:
        {
            os << "window" << separator /* no value */<< separator;
            break;
        }
        case GP_WIDGET_SECTION:
        {
            os << "section" << separator /* no value */<< separator;
            break;
        }
        case GP_WIDGET_TEXT:
        {
            os << "text" << separator;
            char *txt;
            CR(gp_widget_get_value(widget, &txt));
            os << txt << separator;
            break;
        }
        case GP_WIDGET_RANGE:
        {
            os << "range" << separator;
            float f, t, b, s;
            CR(gp_widget_get_range(widget, &b, &t, &s));
            CR(gp_widget_get_value(widget, &f));
            os << "(" << b << ":" << t << ":" << s << "):" << f << separator;
            break;
        }
        case GP_WIDGET_TOGGLE:
        {
            os << "toggle" << separator;
            int t;
            CR(gp_widget_get_value(widget, &t));
            os << t << separator;
            break;
        }
        case GP_WIDGET_RADIO:
        case GP_WIDGET_MENU:
        {
            if (type == GP_WIDGET_RADIO)
            {
                os << "radio" << separator;
            }
            else
            {
                os << "menu" << separator;
            }
            int cnt = 0, i;
            char *current;
            CR(gp_widget_get_value(widget, &current));
            CR(cnt = gp_widget_count_choices(widget));
            os << "(";
            for (i = 0; i < cnt; i++)
            {
                const char *choice;
                CR(gp_widget_get_choice(widget, i, &choice));
                os << i << ":" << choice;
                if (i + 1 < cnt)
                {
                    os << ";";
                }
            }
            os << "):" << current << separator;
            break;
        }
        case GP_WIDGET_BUTTON:
        {
            os << "button" << separator /* no value */<< separator;
            break;
        }
        case GP_WIDGET_DATE:
        {
            os << "date" << separator;
            int t;
            time_t xtime;
            struct tm *xtm;
            char timebuf[200];
            CR(gp_widget_get_value(widget, &t));
            xtime = t;
            xtm = localtime(&xtime);
            strftime(timebuf, sizeof(timebuf), "%c", xtm);
            os << t << ":" << timebuf << separator;
            break;
        }
    }
    return id;
}

/**
 * Write all widget descriptions to @param os.
 * @return maximum of widget ID
 */
int DigitalCameraCapture::collectWidgets(std::ostream & os,
        CameraWidget * widget) throw (GPhoto2Exception)
{
    int id = widgetDescription(os, widget);
    os << lineDelimiter;

    widgets[id - noOfWidgets] = widget;

    CameraWidget * child;
    CameraWidgetType type;
    CR(gp_widget_get_type(widget, &type));
    if ((type == GP_WIDGET_WINDOW) || (type == GP_WIDGET_SECTION))
    {
        for (int x = 0; x < gp_widget_count_children(widget); x++)
        {
            CR(gp_widget_get_child(widget, x, &child));
            id = std::max(id, collectWidgets(os, child));
        }
    }
    return id;
}

/**
 * Write message to @field msgsBuffer if user want to store them
 * (@field collectMsgs).
 * Print debug informations on screen.
 */
template<typename OsstreamPrintable>
void DigitalCameraCapture::message(MsgType msgType, const char * msg,
        OsstreamPrintable & arg) const
{
#if defined(NDEBUG)
    if (collectMsgs)
    {
#endif
    std::ostringstream msgCreator;
    std::string out;
    char type = (char) msgType;
    msgCreator << "[gPhoto2][" << type << "]: " << msg << ": " << arg
            << lineDelimiter;
    out = msgCreator.str();
#if !defined(NDEBUG)
    if (collectMsgs)
    {
#endif
        msgsBuffer << out;
    }
#if !defined(NDEBUG)
#if defined(WIN32) || defined(_WIN32)
    ::OutputDebugString(out.c_str());
#else
    fputs(out.c_str(), stderr);
#endif
#endif
}

} // namespace gphoto2

/**
 * \brief IVideoCapture creator form device index.
 */
Ptr<IVideoCapture> createGPhoto2Capture(int index)
{
    Ptr<IVideoCapture> capture = makePtr<gphoto2::DigitalCameraCapture>(index);

    if (capture->isOpened())
        return capture;

    return Ptr<gphoto2::DigitalCameraCapture>();
}

/**
 * IVideoCapture creator, from device name.
 *
 * @param deviceName is a substring in digital camera model name.
 */
Ptr<IVideoCapture> createGPhoto2Capture(const String & deviceName)
{
    Ptr<IVideoCapture> capture = makePtr<gphoto2::DigitalCameraCapture>(deviceName);

    if (capture->isOpened())
        return capture;

    return Ptr<gphoto2::DigitalCameraCapture>();
}

} // namespace cv

#endif


text:
package com.alibaba.otter.canal.server.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.commons.lang.StringUtils;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.alibaba.otter.canal.common.AbstractCanalLifeCycle;
import com.alibaba.otter.canal.server.CanalServer;
import com.alibaba.otter.canal.server.embeded.CanalServerWithEmbeded;
import com.alibaba.otter.canal.server.netty.handler.ClientAuthenticationHandler;
import com.alibaba.otter.canal.server.netty.handler.FixedHeaderFrameDecoder;
import com.alibaba.otter.canal.server.netty.handler.HandshakeInitializationHandler;
import com.alibaba.otter.canal.server.netty.handler.SessionHandler;

/**
 * 基于netty网络服务的server实现
 *
 * @author jianghang 2012-7-12 下午01:34:49
 * @version 1.0.0
 */
public class CanalServerWithNetty extends AbstractCanalLifeCycle implements CanalServer {

    private CanalServerWithEmbeded embededServer;       // 嵌入式server
    private String                 ip;
    private int                    port;
    private Channel                serverChannel = null;
    private ServerBootstrap        bootstrap     = null;

    public CanalServerWithNetty(){
    }

    public CanalServerWithNetty(CanalServerWithEmbeded embededServer){
        this.embededServer = embededServer;
    }

    public void start() {
        super.start();

        if (!embededServer.isStart()) {
            embededServer.start();
        }

        this.bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
                                                                               Executors.newCachedThreadPool()));

        // 构造对应的pipeline
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipelines = Channels.pipeline();
                pipelines.addLast(FixedHeaderFrameDecoder.class.getName(), new FixedHeaderFrameDecoder());
                pipelines.addLast(HandshakeInitializationHandler.class.getName(), new HandshakeInitializationHandler());
                pipelines.addLast(ClientAuthenticationHandler.class.getName(),
                                  new ClientAuthenticationHandler(embededServer));

                SessionHandler sessionHandler = new SessionHandler(embededServer);
                pipelines.addLast(SessionHandler.class.getName(), sessionHandler);
                return pipelines;
            }
        });

        // 启动
        if (StringUtils.isNotEmpty(ip)) {
            this.serverChannel = bootstrap.bind(new InetSocketAddress(this.ip, this.port));
        } else {
            this.serverChannel = bootstrap.bind(new InetSocketAddress(this.port));
        }
    }

    public void stop() {
        super.stop();

        if (this.serverChannel != null) {
            this.serverChannel.close().awaitUninterruptibly(1000);
        }

        if (this.bootstrap != null) {
            this.bootstrap.releaseExternalResources();
        }

        if (embededServer.isStart()) {
            embededServer.stop();
        }
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setEmbededServer(CanalServerWithEmbeded embededServer) {
        this.embededServer = embededServer;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.sakaiproject.metaobj.security.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.metaobj.security.AuthorizationFacade;
import org.sakaiproject.metaobj.security.AuthorizationFailedException;
import org.sakaiproject.metaobj.shared.model.Agent;
import org.sakaiproject.metaobj.shared.model.Id;
import org.sakaiproject.thread_local.cover.ThreadLocalManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.UserDirectoryService;

/**
 * Created by IntelliJ IDEA.
 * User: John Ellis
 * Date: Jun 30, 2005
 * Time: 4:57:18 PM
 * To change this template use File | Settings | File Templates.
 */
public class AuthzShim implements AuthorizationFacade {
   protected final transient Log logger = LogFactory.getLog(getClass());

   private static final String AUTHZ_GROUPS_LIST =
      "org.sakaiproject.metaobj.security.impl.AuthzShim.groups";

   private AuthzGroupService realmService;
   private UserDirectoryService userDirectoryService;

   public void checkPermission(String function, Id id) throws AuthorizationFailedException {
      if (!isAuthorized(function, id)) {
         throw new AuthorizationFailedException(function, id);
      }
   }

   public void checkPermission(Agent agent, String function, Id id) throws AuthorizationFailedException {
      if (!isAuthorized(agent, function, id)) {
         throw new AuthorizationFailedException(agent, function, id);
      }
   }

   public boolean isAuthorized(String function, Id id) {
      return isAuthorized(null, function, id);
   }

   public boolean isAuthorized(Agent agent, String function, Id id) {
      String agentId = null;
      if (agent == null) {
         agentId = getUserDirectoryService().getCurrentUser().getId();
      }
      else {
         agentId = agent.getId().getValue();
      }
      if (function.equals("maintain")) {
         return checkMaintain(agentId);
      }
      return getRealmService().isAllowed(agentId, function, getCurrentRealm());
   }

   protected boolean checkMaintain(String agentId) {
      AuthzGroup siteRealm = null;
      try {
         siteRealm = getRealmService().getAuthzGroup(getCurrentRealm());
      }
      catch (GroupNotDefinedException e) {
         throw new RuntimeException("unkown realm", e);
      }
      String maintain = siteRealm.getMaintainRole();

      return siteRealm.hasRole(agentId, maintain);
   }

   protected String getCurrentRealm() {
      if (getAuthzGroupsList().size() == 0) {
         return "/site/" + ToolManager.getCurrentPlacement().getContext();
      }
      else {
         return "/site/" + getAuthzGroupsList().get(0);
      }
   }

   protected String getReference(Id id) {
      return null;
   }

   public List getAuthorizations(Agent agent, String function, Id id) {
      return new ArrayList();
   }

   public void createAuthorization(Agent agent, String function, Id id) {
   }

   public void deleteAuthorization(Agent agent, String function, Id id) {
   }

   public void deleteAuthorizations(Id qualifier) {
   }

   public void pushAuthzGroups(Collection authzGroups) {
      List authzGroupList = getAuthzGroupsList();
      authzGroupList.addAll(authzGroups);
   }

   public void pushAuthzGroups(String siteId) {
      getAuthzGroupsList().add(siteId);
   }

   public AuthzGroupService getRealmService() {
      return realmService;
   }

   public void setRealmService(AuthzGroupService realmService) {
      this.realmService = realmService;
   }

   public UserDirectoryService getUserDirectoryService() {
      return userDirectoryService;
   }

   public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
      this.userDirectoryService = userDirectoryService;
   }

   protected List getAuthzGroupsList() {
      List returned = (List) ThreadLocalManager.get(AUTHZ_GROUPS_LIST);

      if (returned == null) {
         returned = new ArrayList();
         ThreadLocalManager.set(AUTHZ_GROUPS_LIST, returned);
      }
      return returned;
   }

}


text:
namespace riakboost{} namespace boost = riakboost; namespace riakboost{ namespace mpl { namespace aux {
BOOST_MPL_HAS_XXX_TRAIT_NAMED_DEF(has_tag, tag, false)
}}}

#endif // BOOST_MPL_AUX_HAS_TAG_HPP_INCLUDED


text:
package v1

const (
	// MediaTypeDescriptor specifies the media type for a content descriptor.
	MediaTypeDescriptor = "application/vnd.oci.descriptor.v1+json"

	// MediaTypeImageManifest specifies the media type for an image manifest.
	MediaTypeImageManifest = "application/vnd.oci.image.manifest.v1+json"

	// MediaTypeImageManifestList specifies the media type for an image manifest list.
	MediaTypeImageManifestList = "application/vnd.oci.image.manifest.list.v1+json"

	// MediaTypeImageLayer is the media type used for layers referenced by the manifest.
	MediaTypeImageLayer = "application/vnd.oci.image.layer.tar+gzip"

	// MediaTypeImageLayerNonDistributable is the media type for layers referenced by
	// the manifest but with distribution restrictions.
	MediaTypeImageLayerNonDistributable = "application/vnd.oci.image.layer.nondistributable.tar+gzip"

	// MediaTypeImageConfig specifies the media type for the image configuration.
	MediaTypeImageConfig = "application/vnd.oci.image.config.v1+json"
)


text:
<?php

namespace Melp\Cg\Php\Parser;

use Melp\Cg\Common\Node\Raw;
use Melp\Cg\Common\NodeInterface;
use Melp\Cg\Common\ScannerInterface;
use Melp\Cg\Php\Node\Arg;
use Melp\Cg\Php\Node\Functionx;
use Melp\Cg\Php\Node\Method;
use Melp\Cg\Php\Node\Property;

class FunctionParser extends Parser
{
    private $pattern = '#function\s+#A';

    public function match(ScannerInterface $scanner)
    {
        return $scanner->matchr($this->pattern);
    }

    public function parse(ScannerInterface $scanner)
    {
        $scanner->expectr($this->pattern);
        $node = $this->parseFunc($scanner, new Functionx());
        return $node;
    }

    /**
     * @param ScannerInterface $scanner
     * @param $node
     * @return mixed
     */
    protected function parseFunc(ScannerInterface $scanner, NodeInterface $node)
    {
        if ($scanner->match('&', true)) {
            $node['byref'] = true;
        }
        $node['name'] = $scanner->expectr(Parser::NAME, true)[0];
        $scanner->skip();
        $scanner->expect('(');
        $scanner->skip();
        while (!$scanner->match(')', true)) {
            $arg = new Arg();
            if ($typehint = $scanner->matchr(self::TYPENAME, true)[0]) {
                $arg['typehint']= $typehint;
            }
            $scanner->skip();
            if ($scanner->match('&', true)) {
                $arg['byref'] = true;
            }
            $arg['name']= $scanner->expectr(self::VARNAME)[1];
            $scanner->skip();

            if ($scanner->match('=', true)) {
                $scanner->skip();
                $arg['default'] = $scanner->scanUntil(array(',', ')'), '(');
            }
            $node->appendChild($arg);
            $scanner->skip();
            if ($scanner->match(',', true)) {
                $scanner->skip();
                continue;
            }
        }
        $scanner->skip();
        if ($scanner->match(';', true)) {
            $node['abstract'] = true;
        } else {
            $scanner->expect('{');
            $node->appendChild(new Raw($scanner->block(), true));
            $scanner->expect('}');
        }
        return $node;
    }
}


text:
"""
Exchanges chain ID for segment ID in a PDB file.

usage: python pdb_segxchain.py <pdb file>
example: python pdb_segxchain.py 1CTF.pdb

Author: {0} ({1})

This program is part of the PDB tools distributed with HADDOCK
or with the HADDOCK tutorial. The utilities in this package
can be used to quickly manipulate PDB files, with the benefit
of 'piping' several different commands. This is a rewrite of old
FORTRAN77 code that was taking too much effort to compile. RIP.
"""

__author__ = "Joao Rodrigues"
__email__ = "j.p.g.l.m.rodrigues@gmail.com"

import os
import re
import sys

USAGE = __doc__.format(__author__, __email__)

def check_input(args):
    """Checks whether to read from stdin/file and validates user input/options."""

    if not len(args):
        # Read from pipe
        if not sys.stdin.isatty():
            pdbfh = sys.stdin
        else:
            sys.stderr.write(USAGE)
            sys.exit(1)
    elif len(args) == 1:
        # Read from file
        if not os.path.isfile(args[0]):
            sys.stderr.write('File not found: ' + args[0] + '\n')
            sys.stderr.write(USAGE)
            sys.exit(1)
        pdbfh = open(args[0], 'r')
    else:
        sys.stderr.write(USAGE)
        sys.exit(1)

    return pdbfh

def _swap_segxchain(fhandle):
    """Enclosing logic in a function to speed up a bit"""

    coord_re = re.compile('^(ATOM|HETATM)')
    fhandle = fhandle

    for line in fhandle:
        line = line.strip()
        if coord_re.match(line):
            yield line[:21] + line[72:76][0] + line[22:] + '\n'
        else:
            yield line + '\n'

if __name__ == '__main__':
    # Check Input
    pdbfh = check_input(sys.argv[1:])

    # Do the job
    new_pdb = _swap_segxchain(pdbfh)

    try:
        sys.stdout.write(''.join(new_pdb))
        sys.stdout.flush()
    except IOError:
        # This is here to catch Broken Pipes
        # for example to use 'head' or 'tail' without
        # the error message showing up
        pass

    # last line of the script
    # We can close it even if it is sys.stdin
    pdbfh.close()
    sys.exit(0)


text:
from celery import Celery

from fs.filefinder import FileFinder
from fs.filemover import FileMover
from fs.subtitler import Subtitler
from fs.saver import Saver

import common.configurator as config

#Specify mongodb host and datababse to connect to
BROKER_URL = 'mongodb://server:27017/gustaf_fs'

celery_fs = Celery('gustaf_fs',broker=BROKER_URL)

#Loads settings for Backend to store results of jobs
celery_fs.config_from_object('fs.celeryconfig')

@celery_fs.task
def refresh():
    settings = config.get()

    ff = FileFinder(settings['source_dirs'], tuple(settings['source_extensions']))
    fm = FileMover(settings['dest_dir'])
    subtitler = Subtitler(settings['subtitle_languages'], settings['subtitle_providers'])
    saver = Saver()

    episodes = ff.find()
    fm.move(episodes, keep_original=False)
    subtitler.subtitle(episodes)
    saver.save(episodes)


text:
/*global define*/
define(['can', 'app/models/model', 'app/models/api-path'], function (can, Model, API) {
    'use strict';

    /**
     * User related
     * @author dorajistyle
     * @namespace user-email-verification
     */

    /**
     * UserEmailVerification model.
     *  @constructor
     * @type {*}
     * @name user-email-verification#UserEmailVerification
     */
    var UserEmailVerification = Model({
      create: 'POST '+API+'/user/send/email/verification/token',
      update: function(data){
        return $.ajax({
          type: 'PUT',
          url: API+'/user/verify/email',
          data: data
        });
      }
    }, {
    });

    return UserEmailVerification;
});


text:
<?php
namespace Dkd\Populate;

/**
 * Populate Exception
 *
 * Thrown in cases of input error.
 */
class Exception extends \RuntimeException
{

}


text:
package org.bdgenomics.adam.cli

import htsjdk.samtools.ValidationStringency
import org.apache.spark.SparkContext
import org.bdgenomics.adam.rdd.ADAMContext._
import org.bdgenomics.utils.cli._
import org.bdgenomics.utils.misc.Logging
import org.kohsuke.args4j.{ Option => Args4jOption, Argument }

object Vcf2ADAM extends BDGCommandCompanion {
  val commandName = "vcf2adam"
  val commandDescription = "Convert a VCF file to the corresponding ADAM format"

  def apply(cmdLine: Array[String]) = {
    new Vcf2ADAM(Args4j[Vcf2ADAMArgs](cmdLine))
  }
}

class Vcf2ADAMArgs extends Args4jBase with ParquetSaveArgs {

  @Argument(required = true, metaVar = "VCF", usage = "The VCF file to convert", index = 0)
  var vcfPath: String = _

  @Argument(required = true, metaVar = "ADAM", usage = "Location to write ADAM Variant data", index = 1)
  var outputPath: String = null

  @Args4jOption(required = false, name = "-coalesce", usage = "Set the number of partitions written to the ADAM output directory")
  var coalesce: Int = -1

  @Args4jOption(required = false, name = "-force_shuffle_coalesce", usage = "Even if the repartitioned RDD has fewer partitions, force a shuffle.")
  var forceShuffle: Boolean = false

  @Args4jOption(required = false, name = "-only_variants", usage = "Output Variant objects instead of Genotypes")
  var onlyVariants: Boolean = false

  @Args4jOption(required = false, name = "-stringency", usage = "Stringency level for various checks; can be SILENT, LENIENT, or STRICT. Defaults to STRICT")
  var stringency: String = "STRICT"
}

class Vcf2ADAM(val args: Vcf2ADAMArgs) extends BDGSparkCommand[Vcf2ADAMArgs] with Logging {
  val companion = Vcf2ADAM
  val stringency = ValidationStringency.valueOf(args.stringency)

  def run(sc: SparkContext) {

    val variantContextRdd = sc.loadVcf(args.vcfPath, stringency)
    val variantContextsToSave = if (args.coalesce > 0) {
      variantContextRdd.transform(
        _.coalesce(args.coalesce, shuffle = args.coalesce > variantContextRdd.rdd.partitions.length || args.forceShuffle)
      )
    } else {
      variantContextRdd
    }

    if (args.onlyVariants) {
      variantContextsToSave
        .toVariantRDD
        .saveAsParquet(args)
    } else {
      variantContextsToSave
        .toGenotypeRDD
        .saveAsParquet(args)
    }
  }
}


text:
import {
  IMAGE_TYPES,
  DISK_TYPES,
  IMAGE_STATES,
  STATES,
  Image,
  DiskSnapshot,
} from 'client/constants'
import { prettyBytes } from 'client/utils'

/**
 * Returns the image type.
 *
 * @param {Image} image - Image
 * @returns {IMAGE_TYPES} - Image type
 */
export const getType = ({ TYPE } = {}) =>
  isNaN(+TYPE) ? TYPE : IMAGE_TYPES[+TYPE]

/**
 * Returns the image state.
 *
 * @param {Image} image - Image
 * @returns {STATES.StateInfo} - Image state information
 */
export const getState = ({ STATE } = {}) => IMAGE_STATES[+STATE]

/**
 * Returns the disk type.
 *
 * @param {Image} image - Image
 * @returns {DISK_TYPES} - Disk type
 */
export const getDiskType = ({ DISK_TYPE } = {}) =>
  isNaN(+DISK_TYPE) ? DISK_TYPE : DISK_TYPES[+DISK_TYPE]

/**
 * Returns the disk name.
 *
 * @param {Image} image - Image
 * @returns {string} - Disk name
 */
export const getDiskName = ({ IMAGE, SIZE, TYPE, FORMAT } = {}) => {
  const size = +SIZE ? prettyBytes(+SIZE, 'MB') : '-'
  const type = String(TYPE).toLowerCase()

  return IMAGE ?? { fs: `${FORMAT} - ${size}`, swap: size }[type]
}

/**
 * @param {Image} image - Image
 * @returns {DiskSnapshot[]} List of snapshots from resource
 */
export const getSnapshots = (image) => {
  const {
    SNAPSHOTS: { SNAPSHOT },
  } = image ?? {}

  return [SNAPSHOT].flat().filter(Boolean)
}


text:
package vz.log.management.util;

import java.text.SimpleDateFormat;
import java.util.Map;

import org.elasticsearch.common.joda.time.DateTime;
import org.elasticsearch.common.joda.time.DateTimeZone;
import org.elasticsearch.common.joda.time.format.DateTimeFormat;

import com.joestelmach.natty.Parser;

public class LogElasticUtil {

	private final static String formatTime = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"; //A formatter that combines a full date and time, separated by a T (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).

	private static String sourceTimestamp = "";

	private static String offsetSourceTimestamp = "";

	static String getUTCTime(){
		return (new DateTime()
				.withZone(DateTimeZone.UTC))
					.toString(DateTimeFormat.forPattern(formatTime));
	}

	static String getServeTime(){
		return (new DateTime()
				.withZone(DateTimeZone.getDefault()))
					.toString(DateTimeFormat.forPattern(formatTime));
	}

	static String getUTCOffsetTime(String offset){
		return (new DateTime()
		.withZone(DateTimeZone.forOffsetHours(Integer.parseInt(offset))))
			.toString(DateTimeFormat.forPattern(formatTime));
	}

	public static String obtainSourceTimestamp(Map<Object,Object> logElasticRequest){
		sourceTimestamp = (logElasticRequest.get("sourceTimestamp")==null)?"":logElasticRequest.get("sourceTimestamp").toString();
		offsetSourceTimestamp = (logElasticRequest.get("offsetSourceTimestamp")==null)?"0":logElasticRequest.get("offsetSourceTimestamp").toString();

		//if the user define a date timestamp, then, our app should use that
		if (!"".equals(sourceTimestamp)) {
			//first we need to format the date received
			sourceTimestamp = exchangeDateFormatAtoDateFormatBByNatty(offsetSourceTimestamp);
		} else {
			if (!"".equals(offsetSourceTimestamp)) {
				sourceTimestamp = getUTCOffsetTime(offsetSourceTimestamp);
			} else {
				//if the user don't specify a time, then, our app should initialize a server default timestamp
				sourceTimestamp = getServeTime();
			}
		}

		return sourceTimestamp;
	}

	//[FIXME]: do a check to support multi-environment date log time
	static String exchangeDateFormatAtoDateFormatBByNatty(String sourceTimestamp){
		return (new SimpleDateFormat(formatTime))
					.format(
							(new Parser())
								.parse(sourceTimestamp)
									.get(0)
										.getDates()
											.get(0)
							);
	}
}


text:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class File
   {
      /// <summary>Sets the attributes for a Non-/Transacted file or directory.</summary>
      /// <remarks>
      ///   Certain file attributes, such as <see cref="FileAttributes.Hidden"/> and <see cref="FileAttributes.ReadOnly"/>, can be combined.
      ///   Other attributes, such as <see cref="FileAttributes.Normal"/>, must be used alone.
      /// </remarks>
      /// <remarks>
      ///   It is not possible to change the <see cref="FileAttributes.Compressed"/> status of a File object using the SetAttributes method.
      /// </remarks>
      /// <exception cref="ArgumentException">path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid.</exception>
      /// <exception cref="DirectoryNotFoundException">The specified path is invalid, (for example, it is on an unmapped drive).</exception>
      /// <exception cref="FileNotFoundException">The file cannot be found.</exception>
      /// <exception cref="NotSupportedException">path is in an invalid format.</exception>
      /// <exception cref="UnauthorizedAccessException">path specified a file that is read-only. -or- This operation is not supported on the current platform. -or- path specified a directory. -or- The caller does not have the required permission.</exception>
      /// <param name="transaction">The transaction.</param>
      /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
      /// <param name="path">The name of the file or directory whose attributes are to be set.</param>
      /// <param name="fileAttributes">
      ///    The attributes to set for the file or directory. Note that all other values override <see cref="FileAttributes.Normal"/>.
      /// </param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void SetAttributesCore(KernelTransaction transaction, bool isFolder, string path, FileAttributes fileAttributes, PathFormat pathFormat)
      {
         if (pathFormat != PathFormat.LongFullPath)
            path = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         var success = null == transaction || !NativeMethods.IsAtLeastWindowsVista

            // SetFileAttributes()
            // 2013-01-13: MSDN confirms LongPath usage.

            ? NativeMethods.SetFileAttributes(path, fileAttributes)

            : NativeMethods.SetFileAttributesTransacted(path, fileAttributes, transaction.SafeHandle);

         var lastError = Marshal.GetLastWin32Error();

         if (!success)
         {
            // MSDN: .NET 3.5+: ArgumentException: FileSystemInfo().Attributes

            if (lastError == Win32Errors.ERROR_INVALID_PARAMETER)

               throw new ArgumentException(Resources.Invalid_File_Attribute, "fileAttributes");

            NativeError.ThrowException(lastError, isFolder, path);
         }
      }
   }
}


text:
default['dnsmasq']['install_type']        = 'package'
default['dnsmasq']['version']             = '2.66'

default['dnsmasq']['interfaces']          = []
default['dnsmasq']['excepted_interfaces'] = []  # note: if :limit_interfaces is set to true, these values will be ignored
default['dnsmasq']['addn_configs']        = ''  # i.e. /etc/dnsmasq.d

# DNS
default['dnsmasq']['domain_needed']       = true
default['dnsmasq']['bogus_priv']          = false  # Never forward addresses in the non-routed address spaces
default['dnsmasq']['filter_win2k']        = false
default['dnsmasq']['enable_upstream']     = true
default['dnsmasq']['enable_polling']      = true
default['dnsmasq']['alt_upstream']        = ''  # alternate file to query for upstream DNS servers
default['dnsmasq']['strict_order']        = true
default['dnsmasq']['addn_hosts']          = true   # note: it is not suggested that you set this to false, as it may lead to a confusing /etc/hosts file
default['dnsmasq']['addn_hosts_file']     = '/etc/banner_hosts'
default['dnsmasq']['entries_strict']      = false  # note: will restrict dns entries to those specified in node[:dnsmasq][:entries]
default['dnsmasq']['entries']             = []
default['dnsmasq']['excluded_entries']    = []

# DHCP
default['dnsmasq']['dhcp_range']          = ''  # blank disables dhcp
default['dnsmasq']['dhcp_gate']           = '192.168.0.1'
default['dnsmasq']['dhcp_lease_time']     = ''
default['dnsmasq']['pxe_boot']            = false
default['dnsmasq']['pxe_file']            = ''
default['dnsmasq']['tftp_root_dir']       = '/srv/tftpboot/'


text:
package org.apache.flink.streaming.connectors.kafka;

import org.apache.flink.streaming.connectors.kafka.partitioner.FixedPartitioner;
import org.apache.flink.streaming.connectors.kafka.partitioner.KafkaPartitioner;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchema;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchemaWrapper;
import org.apache.flink.streaming.util.serialization.SerializationSchema;

import java.util.Properties;

/**
 * Flink Sink to produce data into a Kafka topic. This producer is compatible with Kafka 0.9.
 *
 * Please note that this producer does not have any reliability guarantees.
 *
 * @param <IN> Type of the messages to write into Kafka.
 */
public class FlinkKafkaProducer09<IN> extends FlinkKafkaProducerBase<IN> {

	private static final long serialVersionUID = 1L;

	// ------------------- Keyless serialization schema constructors ----------------------

	/**
	 * Creates a FlinkKafkaProducer for a given topic. The sink produces a DataStream to
	 * the topic.
	 *
	 * @param brokerList
	 *			Comma separated addresses of the brokers
	 * @param topicId
	 * 			ID of the Kafka topic.
	 * @param serializationSchema
	 * 			User defined (keyless) serialization schema.
	 */
	public FlinkKafkaProducer09(String brokerList, String topicId, SerializationSchema<IN> serializationSchema) {
		this(topicId, new KeyedSerializationSchemaWrapper<>(serializationSchema), getPropertiesFromBrokerList(brokerList), new FixedPartitioner<IN>());
	}

	/**
	 * Creates a FlinkKafkaProducer for a given topic. the sink produces a DataStream to
	 * the topic.
	 *
	 * @param topicId
	 * 			ID of the Kafka topic.
	 * @param serializationSchema
	 * 			User defined (keyless) serialization schema.
	 * @param producerConfig
	 * 			Properties with the producer configuration.
	 */
	public FlinkKafkaProducer09(String topicId, SerializationSchema<IN> serializationSchema, Properties producerConfig) {
		this(topicId, new KeyedSerializationSchemaWrapper<>(serializationSchema), producerConfig, new FixedPartitioner<IN>());
	}

	/**
	 * Creates a FlinkKafkaProducer for a given topic. the sink produces a DataStream to
	 * the topic.
	 *
	 * @param topicId The topic to write data to
	 * @param serializationSchema A (keyless) serializable serialization schema for turning user objects into a kafka-consumable byte[]
	 * @param producerConfig Configuration properties for the KafkaProducer. 'bootstrap.servers.' is the only required argument.
	 * @param customPartitioner A serializable partitioner for assigning messages to Kafka partitions (when passing null, we'll use Kafka's partitioner)
	 */
	public FlinkKafkaProducer09(String topicId, SerializationSchema<IN> serializationSchema, Properties producerConfig, KafkaPartitioner<IN> customPartitioner) {
		this(topicId, new KeyedSerializationSchemaWrapper<>(serializationSchema), producerConfig, customPartitioner);

	}

	// ------------------- Key/Value serialization schema constructors ----------------------

	/**
	 * Creates a FlinkKafkaProducer for a given topic. The sink produces a DataStream to
	 * the topic.
	 *
	 * @param brokerList
	 *			Comma separated addresses of the brokers
	 * @param topicId
	 * 			ID of the Kafka topic.
	 * @param serializationSchema
	 * 			User defined serialization schema supporting key/value messages
	 */
	public FlinkKafkaProducer09(String brokerList, String topicId, KeyedSerializationSchema<IN> serializationSchema) {
		this(topicId, serializationSchema, getPropertiesFromBrokerList(brokerList), new FixedPartitioner<IN>());
	}

	/**
	 * Creates a FlinkKafkaProducer for a given topic. The sink produces a DataStream to
	 * the topic.
	 *
	 * @param topicId
	 * 			ID of the Kafka topic.
	 * @param serializationSchema
	 * 			User defined serialization schema supporting key/value messages
	 * @param producerConfig
	 * 			Properties with the producer configuration.
	 */
	public FlinkKafkaProducer09(String topicId, KeyedSerializationSchema<IN> serializationSchema, Properties producerConfig) {
		this(topicId, serializationSchema, producerConfig, new FixedPartitioner<IN>());
	}

	/**
	 * Creates a FlinkKafkaProducer for a given topic. The sink produces a DataStream to
	 * the topic.
	 *
	 * @param topicId The topic to write data to
	 * @param serializationSchema A serializable serialization schema for turning user objects into a kafka-consumable byte[] supporting key/value messages
	 * @param producerConfig Configuration properties for the KafkaProducer. 'bootstrap.servers.' is the only required argument.
	 * @param customPartitioner A serializable partitioner for assigning messages to Kafka partitions.
	 */
	public FlinkKafkaProducer09(String topicId, KeyedSerializationSchema<IN> serializationSchema, Properties producerConfig, KafkaPartitioner<IN> customPartitioner) {
		super(topicId, serializationSchema, producerConfig, customPartitioner);
	}

	@Override
	protected void flush() {
		if (this.producer != null) {
			producer.flush();
		}
	}
}


text:
<!doctype html>

<meta charset="utf-8">
<title>Embedded SDR transceiver</title>
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/css/pygments.css">

Back to all apps

Source
Issues

Embedded SDR transceiver

The SDR transceiver is ready.

More details about this application can be found at this link.


text:
<?xml version="1.0" encoding="utf-8"?>
<Weavers VerifyAssembly="true">
  <Caseless />
  <Scalpel RemoveReferences="NServiceBus.Core" />
</Weavers>


text:
import os
print(os.sep)
path=os.path.abspath(__file__)
path=os.path.dirname(path)
print(path)
path=os.path.join(path,"t\\")  ##路径的拼接
print(path)


text:
/**
 * KBase widget to display table of BIOM data
 */
(function($, undefined) {
    $.KBWidget({
        name: 'AbundanceDataTable',
        parent: "kbaseAuthenticatedWidget",
        version: '1.0.0',
        token: null,
        options: {
	        id: null,
	        ws: null,
	        name: 0
        },
	    ws_url: window.kbconfig.urls.workspace,
	    loading_image: "static/kbase/images/ajax-loader.gif",

	    init: function(options) {
            this._super(options);
            return this;
        },

        render: function() {
	        var self = this;
	        var pref = this.uuidv4();

	        var container = this.$elem;
	        container.empty();
            if (self.token == null) {
                container.append("
[Error] You're not logged in
");
                return;
            }
            container.append("
  loading data...
");

	        var kbws = new Workspace(self.ws_url, {'token': self.token});
	        kbws.get_objects([{ref: self.options.ws+"/"+self.options.id}], function(data) {
	            container.empty();
		        // parse data
		        if (data.length == 0) {
		            var msg = "[Error] Object "+self.options.id+" does not exist in workspace "+self.options.ws;
		            container.append('

'+msg+'>/p>
');
		        } else {
		            var biom = data[0]['data'];
		            var matrix = [];
		            var tdata = [];
		            // get matrix
		            if (biom['matrix_type'] == 'sparse') {
			            matrix = self.sparse2dense(biom['data'], biom['shape'][0], biom['shape'][1]);
		            } else {
			            matrix = biom['data'];
		            }
		            // get column names
		            var clength = biom['columns'].length + 1;
		            var cnames = new Array(clength)
		            cnames[0] = "Annotation";
		            for (var c = 0; c < biom['columns'].length; c++) {
		                if (self.options.name == 0) {
			                cnames[c+1] = biom['columns'][c]['id'];
		                } else {
		                    if (biom['columns'][c].hasOwnProperty('name')) {
		                        cnames[c+1] = biom['columns'][c]['name'];
		                    } else {
		                        cnames[c+1] = biom['columns'][c]['id'];
	                        }
		                }
		            }
		            // add values
		            var tdata = new Array(matrix.length);
		            for (var r = 0; r < matrix.length; r++) {
			            tdata[r] = new Array(clength);
			            tdata[r][0] = biom['rows'][r]['id'];
			            for (var c = 0; c < matrix[r].length; c++) {
                            var value = Math.round(matrix[r][c] * 1000) / 1000;
			                if (! value) {
				                value = "0";
			                }
                            tdata[r][c+1] = value;
			            }
		            }
			        // TABLE
                    var tlen = 0;
	    		    if (window.hasOwnProperty('rendererTable') && rendererTable.length) {
				        tlen = rendererTable.length;
			        }
	   		        container.append("

");
	   		        var tableTest = standaloneTable.create({index: tlen});
	  		        tableTest.settings.target = document.getElementById("outputTable"+tlen);
	    		    tableTest.settings.data = { header: cnames, data: tdata };
			        tableTest.settings.filter = { 0: { type: "text" } };
			        var mw = [ 120 ];
			        for (var i=1; i<cnames.length; i++) {
				        mw.push(130);
			        }
			        tableTest.settings.minwidths = mw;
			        tableTest.render(tlen);
		        }
	        }, function(data) {
		        container.empty();
		        var main = $('
');
		        main.append($('
')
		            .css({'padding': '10px 20px'})
		            .text('[Error] '+data.error.message));
		        container.append(main);
	        });
	        return self;
        },

        loggedInCallback: function(event, auth) {
            this.token = auth.token;
            this.render();
            return this;
        },

        loggedOutCallback: function(event, auth) {
            this.token = null;
            this.render();
            return this;
        },

	    sparse2dense: function(sparse, rmax, cmax) {
	        var dense = new Array(rmax);
	        // dense matrix of 0's
	        for (var i = 0; i < rmax; i++) {
		        dense[i] = Array.apply(null, new Array(cmax)).map(Number.prototype.valueOf, 0);
	        }
	        for (var i = 0; i < sparse.length; i++) {
		        dense[ sparse[i][0] ][ sparse[i][1] ] = sparse[i][2];
	        }
	        return dense;
	    },

	    uuidv4: function(a,b) {
	        for (b=a=''; a++<36; b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');
	        return b;
	    }
    });
})(jQuery);


text:
'use strict';

var helper = require('./helpers.authentication.e2e.client.Spec');
var moment = require('moment');
//clickDate clicks a date on the ui-bootstrap datePicker
/* Due to the complexity of the datepicker, I had to do this tedious steps to
    be able to click dates in the datepicker
    -1 finds rows by protractor repeater, which will return all rows
    -2 find the row where the first character is the present weekNo in the year
        with protractor filter
    -3 find all table cells(td) in the row, which will includes the week no
    -4 find the cell that contains the day of the month and click
*/
var clickDate = function(weekNo, todayNo, next) {
  //converts to string, for it to have .length prototype
  todayNo = todayNo.toString();
  //date picker adds preceeding 0 to their days, and moment doesn't return such
  //so added tenary operator to add it .length is 1
  todayNo = todayNo.length === 1 ? '0' + todayNo : todayNo;
  var datepicker = element(by.css('.calendar'));
  datepicker.click();
  var re = new RegExp('^' + weekNo);
  //to check for above limit, there would be need to go the next month
  if (next) {
    element(by.css('.glyphicon.glyphicon-chevron-right')).click();
  }
  var weeks = element.all(by.repeater('row in rows'));
  var currentWeek = weeks.filter(function(week, index) {
    return week.getText().then(function(text) {
      return Boolean(text.match(re)) === true;
    });
  });
  var allDaysInWeek = currentWeek.all(by.tagName('td'));
  var today = allDaysInWeek.filter(function(day, index) {
    return day.getText().then(function(no) {
      //what if the week day and the day no is the same, like Jan 1
      return no === todayNo.toString();
    });
  });
  today.click();
};

describe('Add Campaign', function() {
  beforeEach(function() {
    helper.loadApp('/');
  });
  //***********buttons************/
  var signInButton = element(by.id('signIn'));
  var myCampaign = element(by.id('myCampaign'));
  var datepicker = element(by.css('.calendar'));
  var dueDate = element(by.model('campaign.dueDate'));
  var submit = element(by.id('addCampaignBtn'));
  var youtubeUrl = element(by.model('campaign.youtubeUrl'));

  /****TESTS*********/
  it('should load the addCampaign page', function() {
    helper.logoutifLoggedIn();
    helper.login();
    myCampaign.click();
    expect(element(by.id('title')).isDisplayed()).toBe(true);
  });

  describe('Add Campaign form validation', function() {
    beforeEach(function() {
      myCampaign.click();
    });

    it('should not accept Title with Less Than 5 Characters or', function() {
      var title = element(by.model('campaign.title'));
      title.sendKeys('TEST');
      expect(element(by.id('lessThan5')).isDisplayed()).toBe(true);
      title.clear();
      //sending an a string of empty characters
      title.sendKeys('         ');
      expect(element(by.id('campaignIsRequired')).isDisplayed()).toBe(true);
    });

    it('should not accept description with Less Than 20 Characters', function() {
      var description = element(by.model('campaign.description'));
      description.sendKeys('These Characters');
      expect(element(by.id('lessThan20')).isDisplayed()).toBe(true);
      description.clear();
      //sending an a string of empty characters
      description.sendKeys('                                   ');
      expect(element(by.id('descriptionErr')).isDisplayed()).toBe(true);
    });

    it('should accept only numbers', function() {
      //TYPE NUMBER FIELD NOT CLEARING PROBLEM WITH PROTRACTOR https://github.com/angular/protractor/issues/1583
      var amount = element(by.model('campaign.amount'));
      amount.sendKeys('asdfghjkl');
      expect(element(by.id('isInvalidErr')).isDisplayed()).toBe(true);
    });

    it('should validate wrong youtube url', function() {
      youtubeUrl.sendKeys('wrong url format');
      expect(submit.isEnabled()).toBe(false);
      expect(youtubeUrl.getAttribute('class')).toContain('ng-invalid-url');
      expect(element(by.id('invalid-url')).isDisplayed()).toBe(true);
    });

    it('should validate wrong youtube url', function() {
      expect(youtubeUrl.getAttribute('class')).toContain('ng-pristine');
      youtubeUrl.sendKeys('www.youtube.com');
      expect(submit.isEnabled()).toBe(false);
      expect(youtubeUrl.getAttribute('class')).toContain('ng-invalid-url');
      expect(element(by.id('invalid-url')).isDisplayed()).toBe(true);
    });

    it('should validate incomplete youtube video id', function() {
      youtubeUrl.sendKeys('https://www.youtube.com/watch?v=mq59iE3');
      expect(element(by.binding('youtubeError')).isDisplayed()).toBe(true);
    });

    it('should validate wrong youtube video id via youtube API', function() {
      youtubeUrl.sendKeys('https://www.youtube.com/watch?v=mq59iE4MhaM');
      expect(element(by.binding('youtubeError')).isDisplayed()).toBe(true);
    });

    it('should allow correct input youtube url', function() {
      youtubeUrl.sendKeys('https://www.youtube.com/watch?v=mq59iE3MhXM');
      expect(element(by.binding('youtubeError')).isDisplayed()).toBe(false);
      expect(youtubeUrl.getAttribute('class')).toContain('ng-valid');
      expect(youtubeUrl.getAttribute('class')).toContain('ng-valid-url');
    });

    it('should disabled date field on page load', function() {
      expect(dueDate.isEnabled()).toBe(false);
    });

    it('should be able to pick date via the datepicker', function() {
      datepicker = element(by.css('.calendar'));
      expect(datepicker.isDisplayed()).toBe(true);
      expect(element(by.css('ul.dropdown-menu')).isDisplayed()).toBe(false);
      datepicker.click();
      expect(element(by.css('ul.dropdown-menu')).isDisplayed()).toBe(true);
    });

    it('should allow users to pick valid date from the datepicker', function() {
      // what of when the day of the weeks falls on the last week,
      // a new week would be on another page or another month
      var weekNo = moment().add(7, 'days').isoWeek();
      var todayNo = moment().add(7, 'days').date();
      clickDate(weekNo, todayNo);
      expect(dueDate.getAttribute('value')).toContain(todayNo);
    });

    it('should not allow users to pick a date below the limit', function() {
      var weekNo = moment().subtract(7, 'days').isoWeek();
      var todayNo = moment().subtract(7, 'days').date();
      clickDate(weekNo, todayNo);
      expect(dueDate.getAttribute('value')).not.toContain(todayNo);
    });

    it('should not allow users to pick a date above the limit', function() {
      var weekNo = moment().add(31, 'days').isoWeek();
      var todayNo = moment().add(31, 'days').date();
      clickDate(weekNo, todayNo, true);
      expect(dueDate.getAttribute('value')).not.toContain(todayNo);
    });
  });
  //add more tests, not comprehensive enough
});


text:
#include <stdint.h>
#include <stddef.h>

#ifndef NULL
#define NULL ((void*) 0)
#endif

void* memchr(const void* s, int c, size_t n);
int memcmp(const unsigned char* s1, const unsigned char* s2, size_t n);
void *memcpy(void* s1, const void* s2, size_t n);
void* memrchr(const void* s, int c, size_t n);
void* memset(void *s, int c, size_t n);

char* strcat( char* destination, const char* source);
char* strchr(const char* s, int c);
int strcmp(const char *s1, const char* s2);
char* strcpy(char *dest, const char *src);
char* strerror(int err);
size_t strlen(const char* s);
char* strncat(char * destination, const char* source, size_t n);
int strncmp(const char* s1, const char* s2, size_t n);
char* strncpy(char *dest, const char *src, size_t n);
char* strpbrk(char* s, const char* delim);
char* strrev(char* s);
int strspn(const char* s1, const char* s2);
char* strstr(char* s1, const char* s2);
char* strtok(char* s, const char* delim);

#endif


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jqGrid Demos</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.8.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.multiselect.css" />

jqGrid 3.6

 Many Thanks to Mark Williams which do the most of the new things added in 3.6

			Enjoy


text:
All notable changes to this project will be documented in this file.

## [v0.13.1][v0.13.1] (2015-09-29)
### Fixed
- Remove hardcoded source name when using (key,value) syntax [#1217](https://github.com/angular-ui/ui-select/pull/1217)
- Modify regex to accept a full 'collection expression' when not using (key,value) syntax [#1216](https://github.com/angular-ui/ui-select/pull/1216)
- Avoid to recalculate position when set 'down' [#1214](https://github.com/angular-ui/ui-select/issues/1214#issuecomment-144271352)

## [v0.13.0][v0.13.0] (2015-09-29)
### Added
- Allow to configure default dropdown position [#1213](https://github.com/angular-ui/ui-select/pull/1213)
- Can use object as source with (key,value) syntax [#1208](https://github.com/angular-ui/ui-select/pull/1208)
- CHANGELOG.md file created

### Changed
- Do not run bower after install automatically [#982](https://github.com/angular-ui/ui-select/pull/982)
- Avoid setting activeItem on mouseenter to improve performance [#1211](https://github.com/angular-ui/ui-select/pull/1211)

### Fixed
- Position dropdown UP or DOWN correctly depending on the available space [#1212](https://github.com/angular-ui/ui-select/pull/1212)
- Scroll to selected item [#976](https://github.com/angular-ui/ui-select/issues/976)
- Change `autocomplete='off'` to `autocomplete='false'` [#1210](https://github.com/angular-ui/ui-select/pull/1210)
- Fix to work correctly with debugInfoEnabled(false) [#1131](https://github.com/angular-ui/ui-select/pull/1131)
- Limit the maximum number of selections allowed in multiple mode [#1110](https://github.com/angular-ui/ui-select/pull/1110)

[v0.13.1]: https://github.com/angular-ui/ui-select/compare/v0.13.0...v0.13.1
[v0.13.0]: https://github.com/angular-ui/ui-select/compare/v0.12.1...v0.13.0


text:
package com.glaf.base.modules.workspace.mapper;

import java.util.*;
import org.springframework.stereotype.Component;
import com.glaf.base.modules.workspace.model.*;
import com.glaf.base.modules.workspace.query.*;

@Component
public interface MessageMapper {

	void deleteMessages(MessageQuery query);

	void deleteMessageById(Long id);

	Message getMessageById(Long id);

	int getMessageCount(MessageQuery query);

	List<Message> getMessages(MessageQuery query);

	void insertMessage(Message model);

	void updateMessage(Message model);

}


text:
// -----------------------------------------------------------------------------
// Export
// -----------------------------------------------------------------------------

function exportDataValue()
{
    selectAllById( "selectedDataSets" );

	if ( validateDataValueExportForm() )
	{
	   document.getElementById( "exportForm" ).submit();
	}
}

function toggleOptions()
{
	$( ".moreOptions" ).toggle();
}

// -----------------------------------------------------------------------------
// MetaDataExport
// -----------------------------------------------------------------------------

function submitMetaDataExportForm()
{
    if ( validateMetaDataExportForm() )
    {
       document.getElementById( "exportForm" ).submit();
    }
}

function toggle( knob )
{
    var toggle = (knob == "all" ? true : false);

	jQuery.each( jQuery("input[type=checkbox]"), function(i, item){
		item.checked = toggle;
	});
}

// -----------------------------------------------------------------------------
// DataExport
// -----------------------------------------------------------------------------

function submitDataExportForm()
{
    if ( validateDataExportForm() )
    {
       document.getElementById( "exportForm" ).submit();
    }
}

// -----------------------------------------------------------------------------
// Validation
// -----------------------------------------------------------------------------

function validateMetaDataExportForm()
{
	if ( jQuery("input:checked").length == 0 )
	{
		setMessage( i18n_select_one_or_more_object_types );
		return false;
	}

	hideHeaderMessage();
	return true;
}

function validateDataValueExportForm()
{
    if ( !selectionTreeSelection.isSelected() )
    {
        setHeaderDelayMessage( i18n_select_organisation_unit );
        return false;
    }
    if ( !hasText( "startDate" ) )
    {
        setHeaderDelayMessage( i18n_select_startdate );
        return false;
    }
    if ( !hasText( "endDate" ) )
    {
        setHeaderDelayMessage( i18n_select_enddate );
        return false;
    }
    if ( !hasElements( "selectedDataSets" ) )
    {
        setHeaderDelayMessage( i18n_select_datasets );
        return false;
    }

    hideHeaderMessage();
    return true;
}

function validateDataExportForm()
{

	if ( jQuery("input:checked").length == 0 )
	{
		setMessage( i18n_select_one_or_more_object_types );
		return false;
	}

    if ( !hasText( "startDate" ) )
    {
        setHeaderDelayMessage( i18n_select_startdate );
        return false;
    }
    if ( !hasText( "endDate" ) )
    {
        setHeaderDelayMessage( i18n_select_enddate );
        return false;
    }

    hideHeaderMessage();
    return true;
}


text:
package org.apache.shardingsphere.test.sql.parser.parameterized.asserts.statement.dal.impl;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.sql.parser.sql.dialect.statement.mysql.dal.MySQLRestartStatement;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.SQLCaseAssertContext;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.dal.RestartStatementTestCase;

/**
 * restart statement assert.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class RestartStatementAssert {

    /**
     * Assert restart statement is correct with expected parser result.
     *
     * @param assertContext assert context
     * @param actual actual restart statement
     * @param expected expected restart statement test case
     */
    public static void assertIs(final SQLCaseAssertContext assertContext, final MySQLRestartStatement actual, final RestartStatementTestCase expected) {
    }
}


text:
create index ZSTG_MICLITE_RELATIVE_P_lwr on ZSTG_MICROSATELLITE(lower(RELATIVE_POSITION)) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_MICLITE_MARKER_lwr on ZSTG_MICROSATELLITE(lower(MARKER)) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
create index ZSTG_MICLITE_PROBE_SET__lwr on ZSTG_MICROSATELLITE(lower(PROBE_SET_ID)) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;

--EXIT;


text:
package com.intellij.compiler.options;

import com.intellij.ui.RawCommandLineEditor;

import javax.swing.*;

/**
 * @author Eugene Zhuravlev
 *         Date: Mar 30, 2004
 */
public class ComparingUtils {
  public static boolean isModified(JCheckBox checkBox, boolean value) {
    return checkBox.isSelected() != value;
  }

  public static boolean isModified(JTextField textField, int value) {
    try {
      int fieldValue = Integer.parseInt(textField.getText().trim());
      return fieldValue != value;
    }
    catch(NumberFormatException e) {
      return false;
    }
  }

  public static boolean isModified(RawCommandLineEditor editor, String value) {
    return !editor.getText().equals(value);
  }

  public static boolean isModified(JTextField textField, String value) {
    return !textField.getText().equals(value);
  }
}


text:
package io.spine.server.model;

import io.spine.base.Identifier;
import io.spine.model.contexts.projects.ProjectId;
import io.spine.model.contexts.projects.command.SigCreateProject;
import io.spine.server.BoundedContextBuilder;
import io.spine.server.command.model.AssigneeSignature;
import io.spine.server.model.given.map.CompletionWatch;
import io.spine.server.model.given.map.DupEventFilterValue;
import io.spine.server.model.given.map.DuplicateCommandHandlers;
import io.spine.server.model.given.map.ProjectAgg;
import io.spine.server.model.given.map.TwoFieldsInSubscription;
import io.spine.string.StringifierRegistry;
import io.spine.string.Stringifiers;
import io.spine.testing.server.blackbox.ContextAwareTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import static io.spine.server.projection.model.ProjectionClass.asProjectionClass;
import static io.spine.testing.server.model.ModelTests.dropAllModels;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;

@DisplayName("`HandlerMap` should")
class ReceptorMapTest {

    /**
     * Registers the stringifier for {@code Integer}, which is used for parsing filter field values.
     */
    @BeforeAll
    static void prepare() {
        StringifierRegistry.instance()
                           .register(Stringifiers.forInteger(), Integer.TYPE);
    }

    @AfterEach
    void clearModel() {
        dropAllModels();
    }

    @Nested
    @DisplayName("not allow")
    class DuplicateHandler {

        @Test
        @DisplayName("duplicate message classes in handlers")
        void rejectDuplicateHandlers() {
            assertDuplicate(() -> ReceptorMap.create(
                    DuplicateCommandHandlers.class, new AssigneeSignature()
            ));
        }

        @Test
        @DisplayName("the same value of the filtered event field (Where)")
        void rejectFilterFieldDuplicationWhere() {
            assertDuplicate(() -> asProjectionClass(DupEventFilterValue.class));
        }

        @Test
        @DisplayName("the same event filtering by different fields")
        void failToSubscribeByDifferentFields() {
            assertThrows(
                    HandlerFieldFilterClashError.class,
                    () -> asProjectionClass(TwoFieldsInSubscription.class)
            );
        }

        void assertDuplicate(Runnable runnable) {
            assertThrows(DuplicateReceptorError.class, runnable::run);
        }
    }

    @Nested
    @DisplayName("gracefully handle a missing handler for a rejection with a specific origin")
    class SpecificRejection extends ContextAwareTest {

        @Override
        protected BoundedContextBuilder contextBuilder() {
            return BoundedContextBuilder
                    .assumingTests()
                    .add(ProjectAgg.class)
                    .addEventDispatcher(new CompletionWatch());
        }

        @Test
        void handleThrownRejectionGracefully() {
            var project = ProjectId.newBuilder()
                    .setId(Identifier.newUuid())
                    .build();
            var createProject = SigCreateProject.newBuilder()
                    .setId(project)
                    .build();
            assertDoesNotThrow(() -> context().receivesCommand(createProject));
        }
    }
}


text:
class Array
  def accumulate
    return [] if self.length == 0

    return self.map { |x| x * x }
  end

  def accumulate(&operation)
    self.reduce([]) { |result, object| result << operation.(object) }
  end
end


text:
/*..............................................................................
   Name: Sumit Patidar
   Roll no: B15237
   Purpose: Assignment 06, part C
   Date: 21/09/2016
   ..............................................................................*/
#include "my_library.h"

int main(int argc, char const *argv[]) {
        struct randomListNode *head = NULL, *head_copy = NULL;
        int size = 0, count = 0, random_label = 0;

        clear();
        printf("Enter the size of doubly linked list: ");
        scanf("%d", &size);

        /* create the singly linked list */
        for(int i = 0; i<size; i++) {
                count++;
                createOriginalSinglyList(&head, count);
        }

        /* asked for random relations */
        for(int i = 0; i<size; i++) {
                printf("[%d] random -> ", i+1);
                scanf("%d", &random_label);
                insertRandomLinks(head, i + 1, random_label);
                printf("\n");
        }

        count = 0;
        struct randomListNode *iterator = NULL;
        iterator = head;

        printf("Original Linked List:\n");
        /* print the original doubly linked list */
        while(iterator != NULL) {
                count++;
                printf("[%d] random -> %d\n", count, iterator->random->label);
                iterator = iterator->next;
        }

        head_copy = copyRandomList(head);
        count = 0;
        iterator = head_copy;

        printf("\n\nDeep Copied Linked List:\n");
        /* print the copied doubly linked list */
        while(iterator != NULL) {
                count++;
                printf("[%d] random -> %d\n", count, iterator->random->label);
                iterator = iterator->next;
        }
        printf("\n\n");

        return 0;
}


text:
layout: post
title:  "Serving scripts with Jekyll and GitHub pages"
date:   2016-06-02 20:00:00 +0100
categories: [ application-physical_building-blocks ]
abstract: How to make a (bash) script downloadable from GitHub, for easy "bootstrapping".
---

There exists a (dubious) popularity to download scripts with curl and executing them with bash. With a little trickery this even works on GitHub pages.

Two files are needed: The script itself, usually with a file extension .sh, and a .html file including this in raw mode.

The trick with these .html files instead of .md is the latter wraps the first line in a p paragraph tag.

In such a html file there may be frontmatter, and the tag include_relative tag makes it easy to serve a script from another folder.

Here the example of `bootstrap-arch.sh.html` in the root folder of the GitHub repository:

```html
{% raw %}
---
title: Bootstrap
---

{% include_relative application/physical/scripts/bootstrap-arch.sh %}
{% endraw %}
```

Of course this only works for the same branch of the repository but that seems like no real limitation.

The Jekyll plugin for redirections, which is included in the GitHub pages installation, works with JavaScript redirects and cannot be used in the typical workflow with curl or wget (following JaveScript redirects is a browser implementation).


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/pink_nuances"
    android:paddingLeft="18dp"
    android:paddingRight="18dp"
    tools:context="com.example.sethcohen.javaforeveryone3.MethodsAndRecursion">

        <TextView
            android:id="@+id/title_methods"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"

            android:text="@string/methodsNrecursion"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1"
            android:textColor="#0097A7"
            android:textSize="32sp" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/is_picchanger_methods"
                android:layout_gravity="center"
                android:src="@drawable/methods1" />
        </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_horizontal">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

        </LinearLayout>
        <Button
            android:id="@+id/btn_prev_1_methods"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_weight="1"
            android:layout_marginBottom="20dp"
            android:background="@drawable/button_not_clicked_next"
            android:text="@string/previous"
            android:textColor="?attr/colorButtonNormal" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:orientation="vertical">

        </LinearLayout>

        <Button
            android:id="@+id/btn_next_1_methods"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginBottom="20dp"
            android:layout_weight="1"
            android:background="@drawable/button_not_clicked_next"
            android:text="@string/next"
            android:textColor="?attr/colorButtonNormal" />
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">
        </LinearLayout>
        </LinearLayout>
</LinearLayout>


text:
namespace Azure.ResourceManager.DataBoxEdge.Models
{
    /// <summary> Details related to the IPv6 address configuration. </summary>
    public partial class DataBoxEdgeIPv6Config
    {
        /// <summary> Initializes a new instance of DataBoxEdgeIPv6Config. </summary>
        internal DataBoxEdgeIPv6Config()
        {
        }

        /// <summary> Initializes a new instance of DataBoxEdgeIPv6Config. </summary>
        /// <param name="ipAddress"> The IPv6 address of the network adapter. </param>
        /// <param name="prefixLength"> The IPv6 prefix of the network adapter. </param>
        /// <param name="gateway"> The IPv6 gateway of the network adapter. </param>
        internal DataBoxEdgeIPv6Config(string ipAddress, int? prefixLength, string gateway)
        {
            IPAddress = ipAddress;
            PrefixLength = prefixLength;
            Gateway = gateway;
        }

        /// <summary> The IPv6 address of the network adapter. </summary>
        public string IPAddress { get; }
        /// <summary> The IPv6 prefix of the network adapter. </summary>
        public int? PrefixLength { get; }
        /// <summary> The IPv6 gateway of the network adapter. </summary>
        public string Gateway { get; }
    }
}


text:
@interface UIView (AdjustFrame)
@property (nonatomic, assign) CGFloat adjustHeight;
- (BOOL) hintAdjustSupreView;
- (void) handleAdjustFrame;
@end


text:
from openstack.tests.unit import base

from openstack.identity.v2 import role

IDENTIFIER = 'IDENTIFIER'
EXAMPLE = {
    'enabled': 'True',
    'description': '1',
    'id': IDENTIFIER,
    'name': '3',
}

class TestRole(base.TestCase):

    def test_basic(self):
        sot = role.Role()
        self.assertEqual('role', sot.resource_key)
        self.assertEqual('roles', sot.resources_key)
        self.assertEqual('/OS-KSADM/roles', sot.base_path)
        self.assertTrue(sot.allow_create)
        self.assertTrue(sot.allow_fetch)
        self.assertTrue(sot.allow_commit)
        self.assertTrue(sot.allow_delete)
        self.assertTrue(sot.allow_list)

    def test_make_it(self):
        sot = role.Role(**EXAMPLE)
        self.assertEqual(EXAMPLE['description'], sot.description)
        self.assertEqual(EXAMPLE['id'], sot.id)
        self.assertEqual(EXAMPLE['name'], sot.name)
        self.assertTrue(sot.is_enabled)