text:
#include <errno.h>
#include <math.h>

#include "sol-flow/jhd1313m1.h"

#include "sol-flow-internal.h"
#include "sol-flow-static.h"
#include "sol-mainloop.h"
#include "sol-util-internal.h"
#include "sol-vector.h"
#include "sol-i2c.h"

#define COL_MIN (0)
#define COL_MAX (15)
#define COL_EXTRA (16) /* when writing RTL, the cursor must be past
                        * the screen to start in the last cell
                        * right */
#define ROW_MIN (0)
#define ROW_MAX (1)

static const uint8_t RGB_ADDR = 0xc4 >> 1; //0x62 = 98dec
static const uint8_t COLOR_ADDR[3] = { 0x04, 0x03, 0x02 };
static const uint8_t DISPLAY_ADDR = 0x7c >> 1; //0x3E = 62dec
static const uint8_t ROW_ADDR[2] = { 0x80, 0xc0 };

static const uint8_t SEND_DATA = 0x40;
static const uint8_t SEND_COMMAND = 0x80;

enum command_status {
    COMMAND_STATUS_WAITING = 0,
    COMMAND_STATUS_SENDING,
    COMMAND_STATUS_DONE
};

#define FLAG_SPECIAL_CMD (1 << 0)
#define FLAG_STRING (1 << 1)
#define FLAG_CURSOR_COL (1 << 2)
#define FLAG_CURSOR_ROW (1 << 3)

struct command {
    struct lcd_data *mdata;
    char *string;
    uint8_t chip_addr, data_addr, value;
    enum command_status status;
    uint8_t flags;
};

struct lcd_data {
    struct sol_i2c *i2c;
    struct sol_i2c_pending *i2c_pending;
    struct sol_ptr_vector cmd_queue;
    struct sol_timeout *timer;
    uint8_t row, col, display_mode, display_control;
    bool error : 1;
    bool ready : 1;
};

#define LCD_BLINK_ON (0x01)
#define LCD_CURSOR_ON (0x02)
#define LCD_MODE_SET_LTR (0x02)
#define LCD_MODE_SET_AUTO_SCROLL (0x01)

static struct command *
command_new(struct lcd_data *mdata)
{
    struct command *cmd;
    int r;

    if (mdata->error)
        return NULL;

    cmd = calloc(1, sizeof(*cmd));
    SOL_NULL_CHECK(cmd, NULL);
    cmd->mdata = mdata;
    cmd->flags = 0;

    r = sol_ptr_vector_append(&mdata->cmd_queue, cmd);
    SOL_INT_CHECK_GOTO(r, < 0, err);

    return cmd;

err:
    free(cmd);
    return NULL;
}

static int
command_queue_append(struct lcd_data *mdata,
    uint8_t chip_addr,
    uint8_t data_addr,
    uint8_t value)
{
    struct command *cmd = command_new(mdata);

    SOL_NULL_CHECK(cmd, -ENOMEM);

    cmd->chip_addr = chip_addr;
    cmd->data_addr = data_addr;
    cmd->value = value;
    cmd->status = COMMAND_STATUS_WAITING;
    cmd->string = NULL;

    return 0;
}

static int
command_string_queue_append(struct lcd_data *mdata, char *string)
{
    struct command *cmd = command_new(mdata);

    SOL_NULL_CHECK(cmd, -ENOMEM);

    cmd->chip_addr = DISPLAY_ADDR;
    cmd->data_addr = SEND_COMMAND;
    cmd->value = 0;
    cmd->status = COMMAND_STATUS_WAITING;
    cmd->string = string;
    cmd->flags = FLAG_SPECIAL_CMD | FLAG_STRING;

    return 0;
}

/* update only one of row/col */
static int
command_cursor_position_queue_append(struct lcd_data *mdata, int row, int col)
{
    struct command *cmd = command_new(mdata);

    SOL_NULL_CHECK(cmd, -ENOMEM);

    cmd->chip_addr = DISPLAY_ADDR;
    cmd->data_addr = SEND_COMMAND;
    cmd->status = COMMAND_STATUS_WAITING;
    cmd->string = NULL;
    cmd->flags = FLAG_SPECIAL_CMD;

    if (row > -1) {
        cmd->flags |= FLAG_CURSOR_ROW;
        cmd->value = row & 0xFF;
    } else {
        cmd->flags |= FLAG_CURSOR_COL;
        cmd->value = col & 0xFF;
    }

    return 0;
}

/* update both row and col */
static int
pos_cmd_queue(struct lcd_data *mdata, uint8_t row, uint8_t col)
{
    uint8_t command = col | ROW_ADDR[row];

    return command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND, command);
}

static int
char_cmd_queue(struct lcd_data *mdata, uint8_t value)
{
    return command_queue_append(mdata, DISPLAY_ADDR, SEND_DATA, value);
}

/* Returns the number of chars behind the current cursor position, if
 * in LTR, or after that, if in RTL. If autoscroll is on, it will
 * return 0 on success. */
static int
write_char(struct lcd_data *mdata, char value)
{
    bool right_to_left = false, autoscroll = false, newline = false;
    int r;

    right_to_left = !(mdata->display_mode & LCD_MODE_SET_LTR);

    if (value != '\n') {
        r = char_cmd_queue(mdata, value);
        SOL_INT_CHECK(r, < 0, r);
    } else {
        mdata->row++;
        if (mdata->row > ROW_MAX)
            mdata->row = ROW_MAX;
        if (right_to_left)
            mdata->col = COL_MAX;
        else
            mdata->col = COL_MIN;
        newline = true;
    }

    autoscroll = mdata->display_mode & LCD_MODE_SET_AUTO_SCROLL;
    /* When autoscrolling, don't advance in either way */
    if (autoscroll)
        return 0;

    if (newline) {
        r = pos_cmd_queue(mdata, mdata->row, mdata->col);
        if (r < 0) {
            SOL_WRN("Failed to change cursor position");
            return r;
        }
        goto end;
    }

    if (right_to_left) {
        mdata->col--;
        /* Going RTL case (checking underflow on unsigned): jump to
         * end of 1st line or keep overriding first col */
        if (mdata->col == UINT8_MAX) {
            if (mdata->row < ROW_MAX) {
                mdata->col = COL_MAX;
                mdata->row++;
                r = pos_cmd_queue(mdata, mdata->row, mdata->col);
                if (r < 0) {
                    SOL_WRN("Failed to change cursor position");
                    return r;
                }
            } else
                mdata->col = COL_MIN;
        }
    } else {
        if (mdata->col < UINT8_MAX)
            mdata->col++;
        /* Going LTR case: jump to start of next line or keep
         * overriding last col */
        if (mdata->col > COL_MAX) {
            if (mdata->row < ROW_MAX) {
                mdata->col = COL_MIN;
                mdata->row++;
                r = pos_cmd_queue(mdata, mdata->row, mdata->col);
                if (r < 0) {
                    SOL_WRN("Failed to change cursor position");
                    return r;
                }
            } else
                mdata->col = COL_MAX;
        }
    }

end:
    if (right_to_left)
        return mdata->col + (1 + COL_MAX) * mdata->row;
    else
        return (ROW_MAX - mdata->row) * (1 + COL_MAX) + (COL_MAX - mdata->col);
}

static int
write_string(struct lcd_data *mdata, char *str)
{
    int r;

    while (*str) {
        r = write_char(mdata, *str++);
        SOL_INT_CHECK(r, < 0, r);
        /* stop if the whole display was used */
        if (r >= (COL_MAX + 1) * (ROW_MAX + 1) - 1)
            return 0;
    }

    return 0;
}

#define LCD_CLEAR (0x01)
#define LCD_ENTRY_MODE_SET (0x04)
#define LCD_DISPLAY_CONTROL (0x08)
#define LCD_FUNCTION_SET (0x20)
#define LCD_DISPLAY_ON (0x04)
#define LCD_FUNCTION_SET_2_LINES (0x08)

#define LCD_CURSOR_SHIFT (0x10)
#define LCD_DISPLAY_MOVE (0x08)
#define LCD_MOVE_RIGHT (0x04)
#define LCD_MOVE_LEFT (0x00)

#define LCD_RGB_MODE1 (0x00)
#define LCD_RGB_MODE2 (0x01)
#define LCD_RGB_OUTPUT (0x08)

#define LCD_COLOR_R (0)
#define LCD_COLOR_G (1)
#define LCD_COLOR_B (2)

#define TIME_TO_CLEAR (15)
#define I2C_STEP_TIME (1)
#define TIME_TO_TURN_ON (55)

static int command_queue_process(struct lcd_data *mdata);

static bool
timer_cb(void *data)
{
    int r;
    struct lcd_data *mdata = data;

    mdata->timer = NULL;
    r = command_queue_process(data);
    if (r < 0)
        SOL_ERR("Error processing LCD's I2C command queue: %s\n",
            sol_util_strerrora(r));

    return false;
}

static int
timer_reschedule(struct lcd_data *mdata,
    uint32_t timeout_ms,
    bool delete_prev)
{
    if (mdata->timer) {
        if (!delete_prev)
            return 0;
        else
            sol_timeout_del(mdata->timer);
    }

    mdata->timer = sol_timeout_add(timeout_ms, timer_cb, mdata);
    SOL_NULL_CHECK(mdata->timer, -ENOMEM);

    return 0;
}

static void
i2c_write_cb(void *cb_data,
    struct sol_i2c *i2c,
    uint8_t reg,
    uint8_t *data,
    ssize_t status)
{
    struct command *cmd = cb_data;
    struct lcd_data *mdata = cmd->mdata;

    mdata->i2c_pending = NULL;
    if (status < 0)
        SOL_WRN("LCD command %p failed: %s", cmd, sol_util_strerrora(-status));

    cmd->status = COMMAND_STATUS_DONE;

    if (cmd->value != LCD_CLEAR)
        command_queue_process(mdata);
}

static int
command_send(struct lcd_data *mdata, struct command *cmd)
{
    int r;

    r = sol_i2c_set_slave_address(mdata->i2c, cmd->chip_addr);

    if (r < 0) {
        SOL_WRN("Failed to set slave at address 0x%02x\n", cmd->chip_addr);
        return -EIO;
    }

    cmd->status = COMMAND_STATUS_SENDING;
    mdata->i2c_pending = sol_i2c_write_register(mdata->i2c, cmd->data_addr,
        &cmd->value, 1, i2c_write_cb, cmd);
    if (!mdata->i2c_pending) {
        SOL_WRN("Failed to write on I2C register 0x%02x\n", cmd->data_addr);
        cmd->status = COMMAND_STATUS_WAITING;
        return -EIO;
    }

    return 0;
}

static void
command_free(struct command *cmd)
{
    if (cmd->string)
        free(cmd->string);
    free(cmd);
}

static void
free_commands(struct sol_ptr_vector *cmd_queue, bool done_only)
{
    struct command *cmd;
    uint16_t i;

    /* Traverse backwards so deletion doesn't impact the indexes. */
    SOL_PTR_VECTOR_FOREACH_REVERSE_IDX (cmd_queue, cmd, i) {
        if (done_only && cmd->status != COMMAND_STATUS_DONE)
            continue;
        command_free(cmd);
        sol_ptr_vector_del(cmd_queue, i);
    }
}

static int
lcd_string_write_process(struct lcd_data *mdata, char *string, uint16_t i)
{
    struct sol_ptr_vector old_vector;
    struct sol_ptr_vector final_vector;
    struct command *cmd;
    uint16_t j;
    int r;

    /*
     * The commands that will be queued by write_string() must be
     * right after the command that triggered this function, to
     * accomplish this with vector:
     * - Copy mdata->cmd_queue vector to old_vector
     * - Initialize mdata->cmd_queue
     * - Call write_string() to queue the commands to mdata->cmd_queue
     * - Initialize the final_vector
     * - Append all processed(0..i) commands on old_vector to final_vector
     * - Append all commands queued by write_string() to final_vector
     * - Append all non-processed(i+1..len) commands on old_vector to
     *   final_vector
     * - Set final_vector as mdata->cmd_queue
     */

    old_vector = mdata->cmd_queue;
    sol_ptr_vector_init(&mdata->cmd_queue);

    /* mdata->cmd_queue now contains the expanded string commands */
    r = write_string(mdata, string);
    if (r < 0) {
        free_commands(&mdata->cmd_queue, true);
        sol_ptr_vector_clear(&mdata->cmd_queue);
        goto err;
    }

    /* copy original commands up to 'i' */
    sol_ptr_vector_init(&final_vector);
    SOL_PTR_VECTOR_FOREACH_IDX (&old_vector, cmd, j) {
        /* 'i' is included back because it is marked as done before
         * this function is called
         */
        if (j > i) break;

        r = sol_ptr_vector_append(&final_vector, cmd);
        SOL_INT_CHECK_GOTO(r, < 0, err_cmds);
    }

    /* copy commands of the string command expansion */
    SOL_PTR_VECTOR_FOREACH_IDX (&mdata->cmd_queue, cmd, j) {
        r = sol_ptr_vector_append(&final_vector, cmd);
        SOL_INT_CHECK_GOTO(r, < 0, err_cmds);
    }

    /* only clear, since we moved them to final_vector */
    sol_ptr_vector_clear(&mdata->cmd_queue);

    /* copy original commands past 'i' */
    SOL_PTR_VECTOR_FOREACH_IDX (&old_vector, cmd, j) {
        if (j <= i) continue;

        r = sol_ptr_vector_append(&final_vector, cmd);
        SOL_INT_CHECK_GOTO(r, < 0, err_final);
    }
    /* only clear, since we moved them to final_vector */
    sol_ptr_vector_clear(&old_vector);

    mdata->cmd_queue = final_vector;

    return 0;

err_cmds:
    free_commands(&mdata->cmd_queue, false);
    sol_ptr_vector_clear(&mdata->cmd_queue);

err_final:
    free_commands(&final_vector, false);
    sol_ptr_vector_clear(&final_vector);

err:
    mdata->cmd_queue = old_vector;
    return r;
}

static inline bool
is_processing(struct lcd_data *mdata)
{
    return mdata->i2c_pending != NULL || !mdata->ready;
}

static int
command_queue_start(struct lcd_data *mdata)
{
    if (is_processing(mdata))
        return 0;

    return command_queue_process(mdata);
}

/* commit buffered changes */
static int
command_queue_process(struct lcd_data *mdata)
{
    struct command *cmd;
    uint16_t i;
    int r;

    if (mdata->i2c_pending) {
        r = timer_reschedule(mdata, I2C_STEP_TIME, false);
        SOL_INT_CHECK_GOTO(r, < 0, sched_err);
        goto end;
    }

    SOL_PTR_VECTOR_FOREACH_IDX (&mdata->cmd_queue, cmd, i) {
        /* done, left to be cleaned after the loop */
        if (cmd->status == COMMAND_STATUS_DONE) break;

        /* COMMAND_STATUS_WAITING cases, since COMMAND_STATUS_SENDING
         * can't happen at this point */
        if (!(cmd->flags & FLAG_SPECIAL_CMD)) {
            r = command_send(mdata, cmd);
            SOL_INT_CHECK_GOTO(r, < 0, err);

            if (cmd->chip_addr == DISPLAY_ADDR && cmd->value == LCD_CLEAR) {
                /* command_send() on a clear one will not link back to
                 * command_queue_process(), we do this by a timer */
                mdata->row = ROW_MIN;
                mdata->col = COL_MIN;

                r = timer_reschedule(mdata, TIME_TO_CLEAR, true);
                SOL_INT_CHECK_GOTO(r, < 0, sched_err);
                cmd->status = COMMAND_STATUS_DONE;
            }
            return 0;
        }

        /* FLAG_SPECIAL_CMD cases */
        if (cmd->flags & FLAG_STRING) {
            /* Being a fake command, we expand it to real,
             * intermediate commands (and mark this one as done). We
             * *have* to expand string commands JIT-like, because we
             * can't know beforehand the state of row/col that each
             * write_char() call will find while traversing the
             * string's individual char commands. */
            cmd->status = COMMAND_STATUS_DONE;

            r = lcd_string_write_process(mdata, cmd->string, i);
            SOL_INT_CHECK_GOTO(r, < 0, err);
            /* proceed to the 1st expanded command */
            continue;
        }

        /* Just col/row as special commands left. Since we do the
         * trick of passing pure row/col on value, store it on mdata
         * and fix the expected value for the I2C wire. */
        if (cmd->flags & FLAG_CURSOR_COL) {
            mdata->col = cmd->value;
        } else {
            mdata->row = cmd->value;
        }
        cmd->value = mdata->col | ROW_ADDR[mdata->row];
        r = command_send(mdata, cmd);
        SOL_INT_CHECK_GOTO(r, < 0, err);
        return 0;
    }

    free_commands(&mdata->cmd_queue, true);

    if (mdata->cmd_queue.base.len)
        return command_queue_process(mdata);

end:
    return 0;

err:
    SOL_ERR("Failed to process LCD command,"
        " no new commands will be executed.");
    mdata->error = true;
    return r;

sched_err:
    SOL_WRN("Fail to reschedule LCD command queue,"
        " no new commands will be executed");
    mdata->error = true;
    return r;
}

static int
clear_cmd_queue(struct lcd_data *mdata)
{
    return command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND, LCD_CLEAR);
}

static bool
start(void *data)
{
    struct lcd_data *mdata = data;
    int r;

    mdata->ready = true;

    r = command_queue_start(mdata);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    return false;

fail:
    SOL_WRN("Unable to start LCD command queue");
    return false;
}

static int
append_setup_commands(struct lcd_data *mdata)
{
    int r;
    struct sol_timeout *timer;

    SOL_DBG("About to append 8 initial cmds");

    /* set display to 2 lines */
    r = command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND,
        LCD_FUNCTION_SET | LCD_FUNCTION_SET_2_LINES);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    /* turn on display */
    r = command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND,
        LCD_DISPLAY_CONTROL | LCD_DISPLAY_ON);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    r = command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND,
        mdata->display_mode);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    r = command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND,
        mdata->display_control);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    r = command_queue_append(mdata, RGB_ADDR, LCD_RGB_MODE1, 0);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    r = command_queue_append(mdata, RGB_ADDR, LCD_RGB_MODE2, 0);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    r = command_queue_append(mdata, RGB_ADDR, LCD_RGB_OUTPUT, 0xAA);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    /* clear display */
    r = clear_cmd_queue(mdata);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    timer = sol_timeout_add(TIME_TO_TURN_ON, start, mdata);
    SOL_NULL_CHECK(timer, -ENOMEM);

    return 0;

fail:
    SOL_WRN("Unable to queue initial LCD commands");
    return r;
}

#undef LCD_FUNCTION_SET
#undef LCD_FUNCTION_SET_2_LINES
#undef LCD_RGB_MODE1
#undef LCD_RGB_MODE2
#undef LCD_RGB_OUTPUT
#undef LCD_COLOR_R
#undef LCD_COLOR_G
#undef LCD_COLOR_B

static int
lcd_open(struct lcd_data *mdata, uint8_t bus)
{
    mdata->i2c = sol_i2c_open(bus, SOL_I2C_SPEED_10KBIT);
    SOL_NULL_CHECK_MSG(mdata->i2c, -EIO, "Failed to open i2c bus %d", bus);

    sol_ptr_vector_init(&mdata->cmd_queue);

    return append_setup_commands(mdata);
}

static void
lcd_close(struct sol_flow_node *node, void *data)
{
    struct lcd_data *mdata = data;

    if (mdata->timer)
        sol_timeout_del(mdata->timer);

    if (mdata->i2c_pending)
        sol_i2c_pending_cancel(mdata->i2c, mdata->i2c_pending);
    if (mdata->i2c)
        sol_i2c_close(mdata->i2c);

    free_commands(&mdata->cmd_queue, false);
    sol_ptr_vector_clear(&mdata->cmd_queue);
}

/* LCD API */
static int
set_row(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    struct sol_irange in_value;
    int r;

    r = sol_flow_packet_get_irange(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (in_value.val < ROW_MIN || in_value.val > ROW_MAX) {
        SOL_WRN("Row range for this lcd display is %d-%d", ROW_MIN, ROW_MAX);
        return -EINVAL;
    }

    r = command_cursor_position_queue_append(mdata, in_value.val, -1);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* LCD API */
static int
set_col(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    struct sol_irange in_value;
    int r;

    r = sol_flow_packet_get_irange(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (in_value.val < COL_MIN || in_value.val > COL_EXTRA) {
        SOL_WRN("Column range for this lcd display is %d-%d",
            COL_MIN, COL_EXTRA);
        return -EINVAL;
    }

    r = command_cursor_position_queue_append(mdata, -1, in_value.val);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* serves cursor blink/underline and display on/off cmds */
static int
char_display_cmd_queue(struct lcd_data *mdata)
{
    return command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND,
        mdata->display_control);
}

/* LCD API */
static int
set_display_on(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    bool in_value;
    int r;

    r = sol_flow_packet_get_boolean(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (in_value)
        mdata->display_control |= LCD_DISPLAY_ON;
    else
        mdata->display_control &= ~LCD_DISPLAY_ON;

    r = char_display_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* LCD API */
static int
set_underline_cursor(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    bool in_value;
    int r;

    r = sol_flow_packet_get_boolean(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (in_value)
        mdata->display_control |= LCD_CURSOR_ON;
    else
        mdata->display_control &= ~LCD_CURSOR_ON;

    r = char_display_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* LCD API */
static int
set_blinking_cursor(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    bool in_value;
    int r;

    r = sol_flow_packet_get_boolean(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (in_value)
        mdata->display_control |= LCD_BLINK_ON;
    else
        mdata->display_control &= ~LCD_BLINK_ON;

    r = char_display_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* serves both set_ltr() and set_autoscroll() */
static int
char_entry_cmd_queue(struct lcd_data *mdata)
{
    return command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND,
        mdata->display_mode);
}

/* LCD API */
static int
set_ltr(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    bool in_value;
    int r;

    r = sol_flow_packet_get_boolean(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (in_value)
        mdata->display_mode |= LCD_MODE_SET_LTR;
    else
        mdata->display_mode &= ~LCD_MODE_SET_LTR;

    r = char_entry_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* LCD API */
static int
set_autoscroll(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    bool in_value;
    int r;

    r = sol_flow_packet_get_boolean(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (in_value)
        mdata->display_mode |= LCD_MODE_SET_AUTO_SCROLL;
    else
        mdata->display_mode &= ~LCD_MODE_SET_AUTO_SCROLL;

    r = char_entry_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* LCD API */
static int
put_char(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    unsigned char in_value;
    int r;

    r = sol_flow_packet_get_byte(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    r = char_cmd_queue(mdata, in_value);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

#undef LCD_CLEAR

/* LCD API */
static int
display_clear(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    int r;

    r = clear_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    return command_queue_start(mdata);
}

/* LCD API */
/* insert a sequence of chars where the cursor is at */
static int
put_string(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    const char *in_value;
    char *string;
    int r;

    r = sol_flow_packet_get_string(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    string = strdup(in_value);
    SOL_NULL_CHECK(string, -ENOMEM);

    r = command_string_queue_append(mdata, string);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    return command_queue_start(mdata);

fail:
    free(string);
    return r;
}

/* LCD API */
/* clear screen and write sequence of chars from (0, 0) position */
static int
set_string(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    const char *in_value;
    char *string;
    int r;

    r = sol_flow_packet_get_string(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    string = strdup(in_value);
    SOL_NULL_CHECK(string, -ENOMEM);

    r = clear_cmd_queue(mdata);
    SOL_INT_CHECK_GOTO(r, < 0, fail);

    r = command_string_queue_append(mdata, string);
    SOL_INT_CHECK_GOTO(r, < 0, fail);
    command_queue_start(mdata);

    return 0;

fail:
    free(string);
    return r;
}

static int
color_cmd_queue(struct lcd_data *mdata,
    uint32_t red,
    uint32_t green,
    uint32_t blue)
{
    uint32_t colors[] = { red, green, blue };
    uint32_t *color = colors;
    unsigned i;

    for (i = 0; i < sol_util_array_size(colors); i++) {
        int r = command_queue_append(mdata, RGB_ADDR, COLOR_ADDR[i], *color++);
        SOL_INT_CHECK(r, < 0, r);
    }

    return 0;
}

/* LCD API */
static int
set_color(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    struct lcd_data *mdata = data;
    struct sol_rgb in_value;
    int r;

    r = sol_flow_packet_get_rgb(packet, &in_value);
    SOL_INT_CHECK(r, < 0, r);

    if (sol_rgb_set_max(&in_value, 255) < 0) {
        SOL_WRN("Invalid color");
        return -EINVAL;
    }

    r = color_cmd_queue(mdata, in_value.red, in_value.green, in_value.blue);
    SOL_INT_CHECK(r, < 0, r);
    command_queue_start(mdata);

    return 0;
}

static int
display_scroll_cmd_queue(struct lcd_data *mdata, uint8_t value)
{
    return command_queue_append(mdata, DISPLAY_ADDR, SEND_COMMAND, value);
}

/* LCD API */
static int
scroll_display(struct sol_flow_node *node,
    void *data,
    uint16_t port,
    uint16_t conn_id,
    const struct sol_flow_packet *packet)
{
    uint8_t value = LCD_CURSOR_SHIFT | LCD_DISPLAY_MOVE;
    struct lcd_data *mdata = data;
    int r;

    value |= (port == SOL_FLOW_NODE_TYPE_JHD1313M1_CHAR__IN__SCROLL_RIGHT ?
        LCD_MOVE_RIGHT : LCD_MOVE_LEFT);

    r = display_scroll_cmd_queue(mdata, value);
    SOL_INT_CHECK(r, < 0, r);
    command_queue_start(mdata);

    return 0;
}

static int
lcd_string_open(struct sol_flow_node *node,
    void *data,
    const struct sol_flow_node_options *options)
{
    int r;
    struct lcd_data *mdata = data;
    const struct sol_flow_node_type_jhd1313m1_string_options *opts =
        (const struct sol_flow_node_type_jhd1313m1_string_options *)options;

    SOL_FLOW_NODE_OPTIONS_SUB_API_CHECK
        (opts, SOL_FLOW_NODE_TYPE_JHD1313M1_STRING_OPTIONS_API_VERSION,
        -EINVAL);

    mdata->display_mode = LCD_ENTRY_MODE_SET | LCD_MODE_SET_LTR;
    mdata->display_control = (LCD_DISPLAY_CONTROL | LCD_DISPLAY_ON)
        & (~LCD_BLINK_ON | ~LCD_CURSOR_ON);

    r = lcd_open(mdata, (uint8_t)opts->bus);
    SOL_INT_CHECK(r, < 0, r);

    return color_cmd_queue(mdata,
        opts->color.red, opts->color.green, opts->color.blue);
}

static int
lcd_char_open(struct sol_flow_node *node,
    void *data,
    const struct sol_flow_node_options *options)
{
    struct lcd_data *mdata = data;
    const struct sol_flow_node_type_jhd1313m1_char_options *opts =
        (const struct sol_flow_node_type_jhd1313m1_char_options *)options;
    int r;

    SOL_FLOW_NODE_OPTIONS_SUB_API_CHECK
        (opts, SOL_FLOW_NODE_TYPE_JHD1313M1_CHAR_OPTIONS_API_VERSION, -EINVAL);

    mdata->display_mode = LCD_ENTRY_MODE_SET | LCD_MODE_SET_LTR;
    mdata->display_control = (LCD_DISPLAY_CONTROL | LCD_DISPLAY_ON)
        & (~LCD_BLINK_ON | ~LCD_CURSOR_ON);

    if (!opts->ltr)
        mdata->display_mode &= ~LCD_MODE_SET_LTR;

    if (opts->auto_scroll)
        mdata->display_mode |= LCD_MODE_SET_AUTO_SCROLL;
    else
        mdata->display_mode &= ~LCD_MODE_SET_AUTO_SCROLL;

    if (opts->blink_cursor)
        mdata->display_control |= LCD_BLINK_ON;
    else
        mdata->display_control &= ~LCD_BLINK_ON;

    if (opts->underline_cursor)
        mdata->display_control |= LCD_CURSOR_ON;
    else
        mdata->display_control &= ~LCD_CURSOR_ON;

    r = lcd_open(mdata, (uint8_t)opts->bus);
    SOL_INT_CHECK(r, < 0, r);

    r = command_cursor_position_queue_append(mdata, -1, opts->init_col);
    SOL_INT_CHECK(r, < 0, r);

    r = command_cursor_position_queue_append(mdata, opts->init_row, -1);
    SOL_INT_CHECK(r, < 0, r);

    r = char_entry_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    r = char_display_cmd_queue(mdata);
    SOL_INT_CHECK(r, < 0, r);

    return color_cmd_queue(mdata,
        opts->color.red, opts->color.green, opts->color.blue);
}
#undef LCD_DISPLAY_CONTROL
#undef LCD_ENTRY_MODE_SET
#undef LCD_BLINK_ON
#undef LCD_CURSOR_ON
#undef LCD_DISPLAY_ON
#undef LCD_MODE_SET_LTR
#undef LCD_MODE_SET_AUTO_SCROLL

#include "jhd1313m1-gen.c"


text:
require "chef/exceptions"
require "chef/dsl/resources"
require "chef/dsl/definitions"
require "chef/dsl/data_query"
require "chef/dsl/include_recipe"
require "chef/dsl/registry_helper"
require "chef/dsl/reboot_pending"
require "chef/dsl/audit"
require "chef/dsl/powershell"
require "chef/dsl/core"
require "chef/mixin/lazy_module_include"

class Chef
  module DSL
    # Part of a family of DSL mixins.
    #
    # Chef::DSL::Recipe mixes into Recipes and LWRP Providers.
    #   - this does not target core chef resources and providers.
    #   - this is restricted to recipe/resource/provider context where a resource collection exists.
    #   - cookbook authors should typically include modules into here.
    #
    # Chef::DSL::Core mixes into Recipes, LWRP Providers and Core Providers
    #   - this adds cores providers on top of the Recipe DSL.
    #   - this is restricted to recipe/resource/provider context where a resource collection exists.
    #   - core chef authors should typically include modules into here.
    #
    # Chef::DSL::Universal mixes into Recipes, LWRP Resources+Providers, Core Resources+Providers, and Attributes files.
    #   - this adds resources and attributes files.
    #   - do not add helpers which manipulate the resource collection.
    #   - this is for general-purpose stuff that is useful nearly everywhere.
    #   - it also pollutes the namespace of nearly every context, watch out.
    #
    module Recipe
      include Chef::DSL::Core
      include Chef::DSL::DataQuery
      include Chef::DSL::IncludeRecipe
      include Chef::DSL::RegistryHelper
      include Chef::DSL::RebootPending
      include Chef::DSL::Audit
      include Chef::DSL::Powershell
      include Chef::DSL::Resources
      include Chef::DSL::Definitions
      extend Chef::Mixin::LazyModuleInclude

      def resource_class_for(snake_case_name)
        Chef::Resource.resource_for_node(snake_case_name, run_context.node)
      end

      def have_resource_class_for?(snake_case_name)
        not resource_class_for(snake_case_name).nil?
      rescue NameError
        false
      end

      def exec(args)
        raise Chef::Exceptions::ResourceNotFound, "exec was called, but you probably meant to use an execute resource.  If not, please call Kernel#exec explicitly.  The exec block called was \"#{args}\""
      end
    end
  end
end

# Avoid circular references for things that are only used in instance methods
require "chef/resource"

redpajama_set_name: RedPajamaGithub


text:
package net.java.sip.communicator.impl.protocol.jabber;

import java.beans.*;
import java.util.*;
import java.util.regex.*;

import net.java.sip.communicator.service.argdelegation.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

import org.osgi.framework.*;

/**
 * The jabber implementation of the URI handler. This class handles xmpp URIs by
 * trying to establish a chat with them or add you to a chatroom.
 *
 * @author Emil Ivov
 * @author Damian Minkov
 */
public class UriHandlerJabberImpl
    implements UriHandler, ServiceListener, AccountManagerListener
{
    /**
     * The logger of this class.
     */
    private static final Logger logger =
        Logger.getLogger(UriHandlerJabberImpl.class);

    /**
     * The protocol provider factory that created us.
     */
    private final ProtocolProviderFactory protoFactory;

    /**
     * A reference to the OSGi registration we create with this handler.
     */
    private ServiceRegistration ourServiceRegistration = null;

    /**
     * The object that we are using to synchronize our service registration.
     */
    private final Object registrationLock = new Object();

    /**
     * The AccountManager which loads the stored accounts of
     * {@link #protoFactory} and to be monitored when the mentioned loading is
     * complete so that any pending {@link #uris} can be handled
     */
    private AccountManager accountManager;

    /**
     * The indicator (and its synchronization lock) which determines whether the
     * stored accounts of {@link #protoFactory} have already been loaded.
     *

     * Before the loading of the stored accounts (even if there're none) of the
     * protoFactory is complete, no handling of URIs is to be
     * performed because there's neither information which account to handle the
     * URI in case there're stored accounts available nor ground for warning the
     * user a registered account is necessary to handle URIs at all in case
     * there're no stored accounts.
     *

     */
    private final boolean[] storedAccountsAreLoaded = new boolean[1];

    /**
     * The list of URIs which have received requests for handling before the
     * stored accounts of the {@link #protoFactory} have been loaded. They will
     * be handled as soon as the mentioned loading completes.
     */
    private List<String> uris;

    /**
     * Marks network fails in order to avoid endless loops.
     */
    private boolean networkFailReceived = false;

    /**
     * Creates an instance of this uri handler, so that it would start handling
     * URIs by passing them to the providers registered by <tt>protoFactory</tt>
     * .
     *
     * @param protoFactory the provider that created us.
     *
     * @throws NullPointerException if <tt>protoFactory</tt> is <tt>null</tt>.
     */
    public UriHandlerJabberImpl(ProtocolProviderFactory protoFactory)
        throws NullPointerException
    {
        if (protoFactory == null)
        {
            throw new NullPointerException(
                "The ProtocolProviderFactory that a UriHandler is created with "
                    + " cannot be null.");
        }

        this.protoFactory = protoFactory;

        hookStoredAccounts();

        this.protoFactory.getBundleContext().addServiceListener(this);
        /*
         * Registering the UriHandler isn't strictly necessary if the
         * requirement to register the protoFactory after creating this instance
         * is met.
         */
        registerHandlerService();
    }

    /**
     * Disposes of this UriHandler by, for example, removing the
     * listeners it has added in its constructor (in order to prevent memory
     * leaks, for one).
     */
    public void dispose()
    {
        protoFactory.getBundleContext().removeServiceListener(this);
        unregisterHandlerService();

        unhookStoredAccounts();
    }

    /**
     * Sets up (if not set up already) listening for the loading of the stored
     * accounts of {@link #protoFactory} in order to make it possible to
     * discover when the prerequisites for handling URIs are met.
     */
    private void hookStoredAccounts()
    {
        if (accountManager == null)
        {
            BundleContext bundleContext = protoFactory.getBundleContext();

            accountManager =
                (AccountManager) bundleContext.getService(bundleContext
                    .getServiceReference(AccountManager.class.getName()));
            accountManager.addListener(this);
        }
    }

    /**
     * Reverts (if not reverted already) the setup performed by a previous chat
     * to {@link #hookStoredAccounts()}.
     */
    private void unhookStoredAccounts()
    {
        if (accountManager != null)
        {
            accountManager.removeListener(this);
            accountManager = null;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * net.java.sip.communicator.service.protocol.event.AccountManagerListener
     * #handleAccountManagerEvent
     * (net.java.sip.communicator.service.protocol.event.AccountManagerEvent)
     */
    public void handleAccountManagerEvent(AccountManagerEvent event)
    {

        /*
         * When the loading of the stored accounts of protoFactory is complete,
         * the prerequisites for handling URIs have been met so it's time to
         * load any handling requests which have come before the loading and
         * were thus delayed in uris.
         */
        if ((AccountManagerEvent.STORED_ACCOUNTS_LOADED == event.getType())
            && (protoFactory == event.getFactory()))
        {
            List<String> uris = null;

            synchronized (storedAccountsAreLoaded)
            {
                storedAccountsAreLoaded[0] = true;

                if (this.uris != null)
                {
                    uris = this.uris;
                    this.uris = null;
                }
            }

            unhookStoredAccounts();

            if (uris != null)
            {
                for (Iterator<String> uriIter = uris.iterator(); uriIter
                    .hasNext();)
                {
                    handleUri(uriIter.next());
                }
            }
        }
    }

    /**
     * Registers this UriHandler with the bundle context so that it could start
     * handling URIs
     */
    public void registerHandlerService()
    {
        synchronized (registrationLock)
        {
            if (ourServiceRegistration != null)
            {
                // ... we are already registered (this is probably
                // happening during startup)
                return;
            }

            Hashtable<String, String> registrationProperties =
                new Hashtable<String, String>();

            for (String protocol : getProtocol())
            {
                registrationProperties.put(UriHandler.PROTOCOL_PROPERTY,
                    protocol);
            }

            ourServiceRegistration =
                JabberActivator.bundleContext.registerService(UriHandler.class
                    .getName(), this, registrationProperties);
        }

    }

    /**
     * Unregisters this UriHandler from the bundle context.
     */
    public void unregisterHandlerService()
    {
        synchronized (registrationLock)
        {
            if (ourServiceRegistration != null)
            {
                ourServiceRegistration.unregister();
                ourServiceRegistration = null;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String[] getProtocol()
    {
        return new String[]
        { "xmpp" };
    }

    /**
     * Parses the specified URI and creates a chat with the currently active
     * im operation set.
     *
     * @param uri the xmpp URI that we have to handle.
     */
    public void handleUri(String uri)
    {
        /*
         * TODO If the requirement to register the factory service after
         * creating this instance is broken, we'll end up not handling the URIs.
         */
        synchronized (storedAccountsAreLoaded)
        {
            if (!storedAccountsAreLoaded[0])
            {
                if (uris == null)
                {
                    uris = new LinkedList<String>();
                }
                uris.add(uri);
                return;
            }
        }

        ProtocolProviderService provider;
        try
        {
            provider = selectHandlingProvider(uri);
        }
        catch (OperationFailedException exc)
        {
            // The operation has been canceled by the user. Bail out.
            if (logger.isTraceEnabled())
                logger.trace("User canceled handling of uri " + uri);
            return;
        }

        // if provider is null then we need to tell the user to create an
        // account
        if (provider == null)
        {
            showErrorMessage(
                "You need to configure at least one XMPP account \n"
                    + "to be able to call " + uri, null);
            return;
        }

        if(!uri.contains("?"))
        {
            OperationSetPersistentPresence presenceOpSet
                = provider
                    .getOperationSet(OperationSetPersistentPresence.class);

            String contactId = uri.substring(uri.indexOf(':') + 1);

            //todo check url!!
            //Set the email pattern string
            Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
            if(!p.matcher(contactId).matches())
            {
                showErrorMessage(
                "Wrong contact id : " + uri, null);
                return;
            }

            Contact contact = presenceOpSet.findContactByID(contactId);
            if(contact == null)
            {
                Object result =
                    JabberActivator.getUIService().getPopupDialog()
                            .showConfirmPopupDialog(
                                    "Do you want to add the contact : "
                                        + contactId + " ?",
                                    "Add contact",
                                    PopupDialog.YES_NO_OPTION);

                if(result.equals(PopupDialog.YES_OPTION))
                {
                    ExportedWindow ex = JabberActivator.getUIService().
                            getExportedWindow(ExportedWindow.ADD_CONTACT_WINDOW,
                                new String[]{contactId});
                    ex.setVisible(true);
                }

                return;
            }

            JabberActivator.getUIService().
                    getChat(contact).setChatVisible(true);
        }
        else
        {
            String croom = uri.replaceFirst(getProtocol() + ":", "");
            int ix = croom.indexOf("?");
            String param = croom.substring(ix + 1, croom.length());
            croom = croom.substring(0, ix);

            if(param.equalsIgnoreCase("join"))
            {
                OperationSetMultiUserChat mchatOpSet
                    = provider
                        .getOperationSet(OperationSetMultiUserChat.class);

                try
                {
                    ChatRoom room = mchatOpSet.findRoom(croom);

                    if(room != null)
                    {
                        room.join();
                    }
                }
                catch (OperationFailedException exc)
                {
                    // if we are not online we get this error
                    // will wait for it and then will try to handle once again
                    if((exc.getErrorCode()
                                == OperationFailedException.NETWORK_FAILURE)
                            && !networkFailReceived)
                    {
                        networkFailReceived = true;
                        OperationSetPresence presenceOpSet
                            = provider
                                .getOperationSet(OperationSetPresence.class);
                        presenceOpSet.addProviderPresenceStatusListener(
                                new ProviderStatusListener(uri, presenceOpSet));
                    }
                    else
                        showErrorMessage("Error joining to  " + croom, exc);
                }
                catch (OperationNotSupportedException exc)
                {
                    showErrorMessage(
                            "Join to " + croom + ", not supported!",
                            exc);
                }
            }
            else
                showErrorMessage(
                "Unknown param : " + param, null);
        }
    }

    /**
     * Informs the user that they need to be registered before chatting and
     * asks them whether they would like us to do it for them.
     *
     * @param uri the uri that the user would like us to chat with after
     * registering.
     * @param provider the provider that we may have to reregister.
     */
    private void promptForRegistration(
            String uri,
            ProtocolProviderService provider)
    {
        int answer
            = JabberActivator
                .getUIService()
                    .getPopupDialog()
                        .showConfirmPopupDialog(
                                "You need to be online in order to chat and"
                                    + " your account is currently offline. Do"
                                    + " you want to connect now?",
                                "Account is currently offline",
                                PopupDialog.YES_NO_OPTION);

        if (answer == PopupDialog.YES_OPTION)
            new ProtocolRegistrationThread(uri, provider).start();
    }

    /**
     * The point of implementing a service listener here is so that we would
     * only register our own uri handling service and thus only handle URIs
     * while the factory is available as an OSGi service. We remove ourselves
     * when our factory unregisters its service reference.
     *
     * @param event the OSGi <tt>ServiceEvent</tt>
     */
    public void serviceChanged(ServiceEvent event)
    {
        Object sourceService =
            JabberActivator.bundleContext.
                getService(event.getServiceReference());

        // ignore anything but our protocol factory.
        if (sourceService != protoFactory)
        {
            return;
        }

        switch (event.getType())
        {
            case ServiceEvent.REGISTERED:
                // our factory has just been registered as a service ...
                registerHandlerService();
                break;
            case ServiceEvent.UNREGISTERING:
                // our factory just died - seppuku.
                unregisterHandlerService();
                break;
            default:
                // we don't care.
                break;
        }
    }

    /**
     * Uses the <tt>UIService</tt> to show an error <tt>message</tt> and log and
     * <tt>exception</tt>.
     *
     * @param message the message that we'd like to show to the user.
     * @param exc the exception that we'd like to log
     */
    private void showErrorMessage(String message, Exception exc)
    {
        JabberActivator.getUIService().getPopupDialog().showMessagePopupDialog(
            message, "Failed to create chat!", PopupDialog.ERROR_MESSAGE);
        logger.error(message, exc);
    }

    /**
     * We use this class when launching a provider registration by ourselves in
     * order to track for provider registration states and retry uri handling,
     * once the provider is registered.
     *
     */
    private class ProtocolRegistrationThread
        extends Thread
        implements RegistrationStateChangeListener
    {

        private ProtocolProviderService handlerProvider = null;

        /**
         * The URI that we'd need to chat.
         */
        private String uri = null;

        /**
         * Configures this thread register our parent provider and re-attempt
         * connection to the specified <tt>uri</tt>.
         *
         * @param uri the uri that we need to handle.
         * @param handlerProvider the provider that we are going to make
         *            register and that we are going to use to handle the
         *            <tt>uri</tt>.
         */
        public ProtocolRegistrationThread(String uri,
            ProtocolProviderService handlerProvider)
        {
            super("UriHandlerProviderRegistrationThread:uri=" + uri);
            this.uri = uri;
            this.handlerProvider = handlerProvider;
        }

        /**
         * Starts the registration process, ads this class as a registration
         * listener and then tries to rehandle the uri this thread was initiated
         * with.
         */
        @Override
        public void run()
        {
            handlerProvider.addRegistrationStateChangeListener(this);

            try
            {
                handlerProvider.register(JabberActivator.getUIService()
                    .getDefaultSecurityAuthority(handlerProvider));
            }
            catch (OperationFailedException exc)
            {
                logger.error("Failed to manually register provider.");
                logger.warn(exc.getMessage(), exc);
            }
        }

        /**
         * If the parent provider passes into the registration state, the method
         * re-handles the URI that this thread was initiated with. The method
         * would only rehandle the uri if the event shows successful
         * registration. It would ignore intermediate states such as
         * REGISTERING. Disconnection and failure events would simply cause this
         * listener to remove itself from the list of registration listeners.
         *
         * @param evt the <tt>RegistrationStateChangeEvent</tt> that this thread
         *            was initiated with.
         */
        public void registrationStateChanged(RegistrationStateChangeEvent evt)
        {
            if (evt.getNewState() == RegistrationState.REGISTERED)
            {
                Thread uriRehandleThread = new Thread()
                {
                    @Override
                    public void run()
                    {
                        handleUri(uri);
                    }
                };

                uriRehandleThread.setName("UriRehandleThread:uri=" + uri);
                uriRehandleThread.start();
            }

            // we're only interested in a single event so we stop listening
            // (unless this was a REGISTERING notification)
            if (evt.getNewState() == RegistrationState.REGISTERING)
                return;

            handlerProvider.removeRegistrationStateChangeListener(this);
        }
    }

    /**
     * Returns the default provider that we are supposed to handle URIs through
     * or null if there aren't any. Depending on the implementation this method
     * may require user intervention so make sure you don't rely on a quick
     * outcome when chatting it.
     *
     * @param uri the uri that we'd like to handle with the provider that we are
     *            about to select.
     *
     * @return the provider that we should handle URIs through.
     *
     * @throws OperationFailedException with code <tt>OPERATION_CANCELED</tt> if
     *             the users.
     */
    public ProtocolProviderService selectHandlingProvider(String uri)
        throws OperationFailedException
    {
        ArrayList<AccountID> registeredAccounts =
            protoFactory.getRegisteredAccounts();

        // if we don't have any providers - return null.
        if (registeredAccounts.size() == 0)
        {
            return null;
        }

        // if we only have one provider - select it
        if (registeredAccounts.size() == 1)
        {
            ServiceReference providerReference =
                protoFactory.getProviderForAccount(registeredAccounts.get(0));

            ProtocolProviderService provider =
                (ProtocolProviderService) JabberActivator.bundleContext
                    .getService(providerReference);

            return provider;
        }

        // otherwise - ask the user.
        ArrayList<ProviderComboBoxEntry> providers =
            new ArrayList<ProviderComboBoxEntry>();
        for (AccountID accountID : registeredAccounts)
        {
            ServiceReference providerReference =
                protoFactory.getProviderForAccount(accountID);

            ProtocolProviderService provider =
                (ProtocolProviderService) JabberActivator.bundleContext
                    .getService(providerReference);

            providers.add(new ProviderComboBoxEntry(provider));
        }

        Object result
            = JabberActivator.getUIService().getPopupDialog()
                    .showInputPopupDialog(
                            "Please select the account that you would like \n"
                                + "to use to chat with " + uri,
                            "Account Selection",
                            PopupDialog.OK_CANCEL_OPTION,
                            providers.toArray(),
                            providers.get(0));

        if (result == null)
        {
            throw new OperationFailedException("Operation cancelled",
                OperationFailedException.OPERATION_CANCELED);
        }

        return ((ProviderComboBoxEntry) result).provider;
    }

    /**
     * A class that we use to wrap providers before showing them to the user
     * through a selection popup dialog from the UIService.
     */
    private static class ProviderComboBoxEntry
    {
        public final ProtocolProviderService provider;

        public ProviderComboBoxEntry(ProtocolProviderService provider)
        {
            this.provider = provider;
        }

        /**
         * Returns a human readable <tt>String</tt> representing the provider
         * encapsulated by this class.
         *
         * @return a human readable string representing the provider.
         */
        @Override
        public String toString()
        {
            return provider.getAccountID().getAccountAddress();
        }
    }

    /**
     * Waiting for the provider to become online and then handle the uri.
     */
    private class ProviderStatusListener
        implements ProviderPresenceStatusListener
    {
        private final String uri;
        private final OperationSetPresence parentOpSet;

        public ProviderStatusListener(
                String uri,
                OperationSetPresence parentOpSet)
        {
            this.uri = uri;
            this.parentOpSet = parentOpSet;
        }

        public void providerStatusChanged(ProviderPresenceStatusChangeEvent ev)
        {
            if(ev.getNewStatus().isOnline())
            {
                parentOpSet.removeProviderPresenceStatusListener(this);
                handleUri(uri);
            }
        }

        public void providerStatusMessageChanged(PropertyChangeEvent ev) {}
    }
}


text:
<?php
namespace Respect\Validation\Rules;

class HexaTest extends \PHPUnit_Framework_TestCase
{
    protected $hexaValidator;

    protected function setUp()
    {
        set_error_handler(function () { }, E_USER_DEPRECATED);
        $this->hexaValidator = new Hexa;
    }

    protected function tearDown()
    {
        restore_error_handler();
    }

    /**
     * @dataProvider providerForHexa
     */
    public function testValidateValidHexadecimalNumbers($input)
    {
        $this->assertTrue($this->hexaValidator->assert($input));
        $this->assertTrue($this->hexaValidator->check($input));
        $this->assertTrue($this->hexaValidator->__invoke($input));
    }

    /**
     * @dataProvider providerForNotHexa
     * @expectedException Respect\Validation\Exceptions\HexaException
     */
    public function testInvalidHexadecimalNumbersShouldThrowHexaException($input)
    {
        $this->assertFalse($this->hexaValidator->__invoke($input));
        $this->assertFalse($this->hexaValidator->assert($input));
    }

    public function providerForHexa()
    {
        return array(
            array(''),
            array('FFF'),
            array('15'),
            array('DE12FA'),
            array('1234567890abcdef'),
            array(0x123),
        );
    }

    public function providerForNotHexa()
    {
        return array(
            array(null),
            array('j'),
            array(' '),
            array('Foo'),
            array('1.5'),
        );
    }
}


text:
- infos = Information about the zeromqsend plugin is in keys below
- infos/author = Thomas Wahringer <waht@libelektra.org>
- infos/licence = BSD
- infos/provides = notification
- infos/needs =
- infos/recommends =
- infos/placements = postgetstorage postcommit
- infos/status = maintained unittest libc global experimental
- infos/description = Sends notifications over ZeroMq publish sockets when a key is changed

## Introduction

This plugin is a notification plugin, which sends notifications using ZeroMq
publish (`ZMQ_PUB`) sockets when the key database (KDB) has been modified.
It is compatible with the sending zeromqrecv plugin.

## Dependencies

- `libzmq3-dev` (ZeroMQ C bindings > 3.2)

## Usage

The recommended way is to globally mount the plugin together with the zeromqrecv plugin:

> kdb global-mount zeromqsend zeromqrecv

This plugin is designed to be used as a transport plugin for Elektra's
notification feature.
Since ZeroMq creates threads for asynchronous I/O this plugin always operates
asynchronously.

Since ZeroMQ sockets only provide a 1:n mapping (i.e. one publisher with many
subscribers or one subscriber and many publishers) the `zeromqsend` and
`zeromqrecv` plugins require a XPUB/XSUB endpoint.
The kdb tool ["hub-zeromq"](https://www.libelektra.org/tools/hub-zeromq)
provides these endpoints.

# Transport Plugin

Mount this plugin globally with default settings to use it as _sending_
transport plugin for Elektra's notification feature:

> kdb global-mount zeromqsend

# Configuration

This plugin supports the following configuration options when mounting:

- **endpoint**: ZeroMQ XSUB or SUB socket to connect to. The
  [`ipc`](http://api.zeromq.org/4-2:zmq-ipc) and
  [`tcp`](http://api.zeromq.org/4-2:zmq-tcp) ZeroMQ transports are recommended.
  The default value is "tcp://localhost:6000".
- **connectTimeout**: Timeout for establishing connections in milliseconds. The default value is "1000".
- **subscribeTimeout**: Timeout for waiting for subscribers in milliseconds. The default value is "200".

# Notification Format

The ZeroMQ transport plugins use the publish/subscribe sockets (`ZMQ_PUB` and
`ZMQ_SUB`) for notification transport.

Each notification is a multipart message. The first part contains the type of
change, the second part contains the name of the changed key.

Possible only current change is `Commit`.


text:
package org.teknux.jettybootstrap.servlets;

/** No Source and no Javadoc */
public class README {}


text:
export class IOC {
  constructor() {
    this._readHandlers = { };
    this._writeHandlers = { };
  }

  reset() { }

  readFromAddress(addr, iak) {
    if (addr >= this.constructor.IO_FIRST_ADDRESS && addr <= this.constructor.IO_LAST_ADDRESS) {
      if (this._readHandlers[addr]) {
        return this._readHandlers[addr].call(this) << 16 >> 16;
      }
      return -1;
    }
  }

  writeToAddress(addr, val) {
    if (addr >= this.constructor.IO_FIRST_ADDRESS && addr <= this.constructor.IO_LAST_ADDRESS) {
      if (this._writeHandlers[addr]) {
        this._writeHandlers[addr].call(this, val & 0xffff);
      }
      return true;
    }
  }

  registerReadHandler(addr, fn) {
    if (addr >= this.constructor.IO_FIRST_ADDRESS && addr <= this.constructor.IO_LAST_ADDRESS && typeof fn === 'function') {
      this._readHandlers[addr] = fn;
    }
  }

  registerWriteHandler(addr, fn) {
    if (addr >= this.constructor.IO_FIRST_ADDRESS && addr <= this.constructor.IO_LAST_ADDRESS && typeof fn === 'function') {
      this._writeHandlers[addr] = fn;
    }
  }
}

IOC.IO_FIRST_ADDRESS = 0xff00;
IOC.IO_LAST_ADDRESS = 0xffff;


text:
var $ = require('jquery');
var cdb = require('cartodb.js');
cdb.admin = require('cdb.admin');
var Backbone = require('backbone');

/**
 *  Categories view.
 *
 *  Select a category of the data library
 *
 */

module.exports = cdb.core.View.extend({

  initialize: function() {
    this.router = this.options.router;
    this.localStorage = this.options.localStorage;
    // TODO: Get categories using an API.
    this.collection = new Backbone.Collection();
    this.template = cdb.templates.getTemplate('new_dashboard/views/categories');

    this._initBinds();
  },

  render: function() {
    this.clearSubViews();

    var currentCategory = this.router.model.get('category');
    var categories =  this.collection.models;

    this.$el.html(
      this.template({
        currentCategory:  currentCategory,
        categories:       categories
      })
    );

    this._initViews();

    return this;
  },

  _initBinds: function() {
    this.router.model.bind('change:category', this.render, this);
    this.add_related_model(this.router.model);
  },

  _initViews: function() {
    // Tipsys?
    var self = this;
    this.$('.Categories-option[data-title]').each(function(i,el){
      self.addView(
        new cdb.common.TipsyTooltip({
          el: $(el),
          title: function(e) {
            return $(this).attr('data-title')
          }
        })
      )
    });
  },

});


text:
package claims.bold.intellij.avro.idl;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;

/**
 * Created by abigail on 06/10/15.
 */
public class AvroIdlFileTypeFactory extends FileTypeFactory {
    @Override
    public void createFileTypes(FileTypeConsumer consumer) {
        consumer.consume(AvroIdlFileType.INSTANCE, "avdl");
    }
}


text:
package mx.emite.sdk.enums.sat;

import org.apache.commons.lang3.StringUtils;
import org.beanio.types.TypeConversionException;

import lombok.Getter;
import mx.emite.sdk.errores.ApiException;
import mx.emite.sdk.errores.I_Api_Errores;
import mx.emite.sdk.utils.Utilerias;

@Getter
public enum OrigenRecurso implements Sat<String>{

	INGRESOSPROPIOS("IP","Ingresos Propios"),
	INGRESOSFEDERALES("IF","Ingresos Federales"),
	INGRESOSMIXTOS("IM","Ingresos Mixtos")

	;

	final String idSat;
	final String descripcion;
	final String[] sinonimos;

	OrigenRecurso(String idSat,String descripcion){
		this(idSat,descripcion,null);
	}

	OrigenRecurso(String idSat,String descripcion,String[] sinonimos){
		this.idSat=idSat;
		this.descripcion=descripcion;
		this.sinonimos=sinonimos;

	}

	public static OrigenRecurso busca(String metodo) {
		for(OrigenRecurso m:values()){
			if(m.idSat.equals(metodo))
				return m;
			else if(Utilerias.compara(m.descripcion,metodo))
				return m;
			else if(m.sinonimos!=null){
				for(String s:m.sinonimos){
					if(Utilerias.compara(s,metodo))
						return m;
				}
			}
		}
		return null;
	}

	public static OrigenRecurso unmarshall(String metodo) throws ApiException{
		if(StringUtils.isEmpty(metodo))
			return null;
		final OrigenRecurso estado =  OrigenRecurso.busca(metodo);
		if(estado==null)
			throw new ApiException(I_Api_Errores.CLIENTE_XML_INVALIDO,"El tipo de horas "+metodo+" no se encuentra en el catálogo de Tipos de Horas del SAT");
		else
			return estado;
	}

	public static String marshall(OrigenRecurso v) throws Exception {
		if(v==null)
			return null;
		return v.getIdSat();
	}

	public static Object parse(String text) throws TypeConversionException, ApiException {
		return unmarshall(text);
	}

	public static OrigenRecurso getOrigenRecurso(String origenRecurso) {
		for(OrigenRecurso m:values()){
			if(m.idSat.equals(origenRecurso))
				return m;
		}
		return null;
	}

}


text:
using System;

namespace Framework
{
    /// <summary>
    /// This property belongs in a Base Class Library Extension project,
    /// as it's just a convenience method we wish were already included in
    /// the .NET BCL.
    /// </summary>
    public static class TimeSpanX
    {
        public static bool IsPositive(this TimeSpan timeSpan)
        {
            return timeSpan.Ticks > 0;
        }
    }
}


text:
<!-- HTML footer for doxygen 1.8.8-->
<!-- start footer part -->
<!--BEGIN GENERATE_TREEVIEW-->
<!--END GENERATE_TREEVIEW-->

<!--BEGIN !GENERATE_TREEVIEW-->
<!--END !GENERATE_TREEVIEW-->
</body>
</html>


text:
<Alloy>
	<Window class="container">

		<TableView id="table" onClick="onTableClick">
			<TableViewRow eztiwin="screen2">
				test
			</TableViewRow>
			<TableViewRow eztiwin="screen3">
				test
			</TableViewRow>
			<TableViewRow eztiwin="screen2">
				test
			</TableViewRow>
		</TableView>
	</Window>
</Alloy>


text:
#region [R# naming]
// ReSharper disable ArrangeTypeModifiers
// ReSharper disable UnusedMember.Local
// ReSharper disable FieldCanBeMadeReadOnly.Local
// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable InconsistentNaming
#endregion
using System.Collections.Generic;
using FluentAssertions;
using NSpectator;

namespace SampleSpecs.WebSite
{
    public abstract class Describe_ICollection : Spec
    {
        protected ICollection<string> collection;

        void adding_to_collection()
        {
            Before = () => collection.Add("Item 1");

            It["contains the entry"] = () =>
                collection.Contains("Item 1").Should().Be(true);
        }
    }

    public class Describe_LinkedList : Describe_ICollection
    {
        LinkedList<string> linkedList;

        void before_each()
        {
            linkedList = new LinkedList<string>();
            collection = linkedList;
        }

        void specific_actions()
        {
            Before = () => collection.Add("Item 1");

            It["can add an item at the begining with ease"] = () =>
            {
                linkedList.AddFirst("Item 2");
                linkedList.First.Value.Should().Be("Item 2");
            };
        }
    }

    public class Describe_List : Describe_ICollection
    {
        List<string> list;

        void before_each()
        {
            list = new List<string>();
            collection = list;
        }

        void specific_actions()
        {
            Before = () => collection.Add("Item 1");

            It["an item can be referenced by index"] = () =>
                list[0].Should().Be("Item 1");
        }
    }

    public static class Describe_ICollection_output
    {
        public static string Output = @"
describe LinkedList
  adding to collection
    contains the entry
  specific actions
    can add an item at the begining with ease

describe List
  adding to collection
    contains the entry
  specific actions
    an item can be referenced by index

4 Examples, 0 Failed, 0 Pending
";
        public static int ExitCode = 0;
    }
}


text:
export class AppContants {
  static firebaseServerTime = {'.sv': "timestamp"};
}


text:
/*
 * @author Ramesh Lingappa
 */
package com.jmandrillapi.utils;

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

/**
 * The Class ObjectUtils.
 */
public class ObjectUtils {

	/**
	 * Checks if is null or empty.
	 *
	 * @param value
	 *            the value
	 * @return true, if is null or empty
	 */
	public static boolean isNullOrEmpty(String value) {
		return (value == null || value.length() <= 0);
	}

	/**
	 * Checks if is blank.
	 *
	 * @param value
	 *            the value
	 * @return true, if is blank
	 */
	public static boolean isBlank(String value) {
		return (value == null || value.trim().length() <= 0);
	}

	/**
	 * Checks if is null or empty.
	 *
	 * @param obj
	 *            the obj
	 * @return true, if is null or empty
	 */
	public static boolean isNullOrEmpty(Collection<?> obj) {
		return (obj == null || obj.isEmpty());
	}

	/**
	 * Checks if is null or empty.
	 *
	 * @param map
	 *            the map
	 * @return true, if is null or empty
	 */
	public static boolean isNullOrEmpty(Map<?, ?> map) {
		return (map == null || map.isEmpty());
	}

	/**
	 * Null to empty.
	 *
	 * @param value
	 *            the value
	 * @return the string
	 */
	public static String nullToEmpty(String value) {
		return value == null ? "" : value;
	}

	/**
	 * Check and adds elements to list (create new ArrayList if list is null)
	 *
	 * @param <T>
	 *            the generic type
	 * @param list
	 *            the list
	 * @param value
	 *            the value
	 * @return the list (if list is null, create new array list)
	 */
	public static <T> List<T> addToList(List<T> list, T value) {
		if (value == null)
			return list;
		if (list == null)
			list = new ArrayList<T>();
		list.add(value);
		return list;
	}

	public static <K, V> Map<K, V> addToMap(Map<K, V> map, K key, V value) {
		if (key == null)
			return map;
		if (map == null)
			map = new HashMap<K, V>();
		map.put(key, value);
		return map;
	}
}


text:
define(['module', 'backbone', 'models/models'], function(module, Backbone) {

    App.Collections.Canvas = Backbone.Collection.extend({
        model: function(attrs) {
            return new App.Models[attrs.type](attrs);
        }
    });

    App.Collections.Threads = Backbone.Collection.extend({
        model: App.Models.Thread
    });

    return App.Collections;

});


text:
import * as St from '@gi-types/st1';
import * as GLib from '@gi-types/glib2';
import * as GdkPixbuf from '@gi-types/gdkpixbuf2';

export function setImage(pixbuf: GdkPixbuf.Pixbuf): void {
  const [ok, buffer] = pixbuf.save_to_bufferv('png', [], []);
  if (!ok) {
    throw new Error('error in save_to_bufferv');
  }
  const bytes = GLib.Bytes.new(buffer);
  St.Clipboard.get_default().set_content(St.ClipboardType.CLIPBOARD, 'image/png', bytes);
}

export function setText(text: string): void {
  St.Clipboard.get_default().set_text(St.ClipboardType.CLIPBOARD, text);
}


text:
<!DOCTYPE html>

    <meta name="encoding" charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>INMOBI ITLA</title>
    <meta name="application-name" content="ITLA te ayuda a mudarte" />
    <meta name="description" content="ventas y alquiler de departamentos, casas, fincas">
    <meta name="author" content="Pedro Torres, Juan Matos">
    <link rel="stylesheet" href="<?= base_url() ?>plantilla/css/bootstrap.min.css">
    <link rel="stylesheet" href="<?= base_url() ?>plantilla/css/signin.css">

Bienvenidos a INMOBI ITLA

- Iniciar Sesión -

        <?php $error = $this->session->flashdata("error"); ?>
        <div class="alert alert-<?php echo $error ? 'warning' : 'info' ?> alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
          <?php echo $error ? $error : 'Introduzca su Usuario y Contraseña' ?>

        <?php echo form_open(); ?>
        <form class="form-signin" autocomplete="off" method="post" action="<?php echo base_url('/login/identify')?>">

              <?php $error = form_error("usuario", "
", '
'); ?>
              <div class="form-group input-group" <?php echo $error ? 'has-error' : '' ?>>

                  <input type="text" name="usuario" autocomplete="on" value="<?php echo set_value("usuario") ?>" id="username" class="form-control" placeholder="Correo electrónico" autofocus>

              <?php echo $error; ?>
              <?php $error = form_error("clave", "
", '
'); ?>
              <div class="form-group input-group" <?php echo $error ? 'has-error' : '' ?>>

                <input type="password" name="clave" class="form-control" placeholder="Contraseña" id="password">

                <?php echo $error; ?>
              <button type="submit" class="btn btn-ss btn-block btn-success">Iniciar Sesion</button>
              ¿Aun no tienes una cuenta?
              <a href="<?= base_url('/signup')?>"class="btn btn-ss btn-block btn-info" role="button">Registrar

        </form>
        <?php echo form_close(); ?>


text:
package com.drivers.weixin.service.impl;

import com.drivers.entity.WxFans;
import com.drivers.entity.WxMerchant;
import com.drivers.router.repository.WxFansRepository;
import com.drivers.router.repository.WxMerchantRepository;
import com.drivers.weixin.service.WeixinOAuthService;
import com.medal.weixin.sdk.client.AdvancedClient;
import com.medal.weixin.sdk.pojo.SNSUserInfo;
import com.medal.weixin.sdk.pojo.WeixinOauth2Token;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by xhuji on 2016/11/22.
 */
@Slf4j
@Service
@Transactional
public class WeixinOAuthServiceImpl implements WeixinOAuthService {
    @Autowired
    private WxMerchantRepository wxMerchantRepository;
    @Autowired
    private WxFansRepository wxFansRepository;
    @Override
    public SNSUserInfo getSNSUserInfo(String code) {
        // 获取网页授权access_token
        WxMerchant wxMerchant = wxMerchantRepository.findAll();
        WeixinOauth2Token weixinOauth2Token = new WeixinOauth2Token();
        if (wxMerchant != null){
            weixinOauth2Token = AdvancedClient.getOauth2AccessToken(wxMerchant.getAppId(),wxMerchant.getAppSecret(), code);
        }
        // 获取用户信息
        SNSUserInfo snsUserInfo = AdvancedClient.getSNSUserInfo(weixinOauth2Token.getAccessToken(), weixinOauth2Token.getOpenId());

        //保存微信关注者信息
        Long count = wxFansRepository.countByOpenid(snsUserInfo.getOpenId());
        if (!count.equals(1L)){
            WxFans wxFans = new WxFans();
            BeanUtils.copyProperties(snsUserInfo,wxFans);
            wxFansRepository.save(wxFans);
        }
        return snsUserInfo;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <prerequisites>
        <maven>3.0</maven>
    </prerequisites>
    <parent>
        <groupId>org.eclipse</groupId>
        <artifactId>eclipse-parent</artifactId>
        <version>3</version>
    </parent>
    <groupId>org.openbel.editor</groupId>
    <artifactId>editor</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>BEL Editor</name>

    <licenses>
        <license>
            <name>Eclipse Public License v1.0</name>
            <comments>
       All rights reserved.

       This program and the accompanying materials are made
       available under the terms of the Eclipse Public License v1.0
       which accompanies this distribution, and is available at
       http://www.eclipse.org/legal/epl-v10.htm
      </comments>
        </license>
    </licenses>
    <scm>
        <connection>scm:git:git://github.com/OpenBEL/bel-editor.git</connection>
        <developerConnection>scm:git:git://github.com/OpenBEL/bel-editor.git</developerConnection>
        <url>https://github.com/OpenBEL/bel-editor</url>
    </scm>
    <properties>
        <tycho-version>0.14.1</tycho-version>
        <platform-version-name>indigo</platform-version-name>
        <platform-version>[3.7,3.8)</platform-version>
    </properties>
    <modules>
        <module>org.openbel.editor.antlr</module>
        <module>org.openbel.editor.core</module>
        <module>org.openbel.editor.ui</module>
        <module>org.openbel.editor.doc</module>
        <module>org.openbel.editor-feature</module>
        <module>org.openbel.editor-site</module>
    </modules>
    <repositories>
        <repository>
            <id>indigo</id>
            <layout>p2</layout>
            <url>http://download.eclipse.org/releases/indigo</url>
        </repository>
        <repository>
            <id>maven.eclipse.org</id>
            <url>http://maven.eclipse.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-ssh</artifactId>
                <version>1.0</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.eclipse.tycho</groupId>
                <artifactId>tycho-maven-plugin</artifactId>
                <version>${tycho-version}</version>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <groupId>org.eclipse.tycho</groupId>
                <artifactId>target-platform-configuration</artifactId>
                <version>${tycho-version}</version>
                <configuration>
                    <resolver>p2</resolver>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptors>
                        <descriptor>src.xml</descriptor>
                    </descriptors>
                </configuration>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.tycho</groupId>
                    <artifactId>tycho-compiler-plugin</artifactId>
                    <version>${tycho-version}</version>
                    <configuration>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.eclipse.tycho</groupId>
                    <artifactId>tycho-surefire-plugin</artifactId>
                    <version>${tycho-version}</version>
                    <configuration>
                        <useUIHarness>true</useUIHarness>
                        <useUIThread>true</useUIThread>
                        <product>org.eclipse.sdk.ide</product>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.eclipse.tycho</groupId>
                    <artifactId>tycho-source-plugin</artifactId>
                    <version>${tycho-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.3</version>
                    <configuration>
                        <encoding>ISO-8859-1</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.2.1</version>
                    <configuration>
                        <tarLongFileMode>gnu</tarLongFileMode>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.0</version>
                </plugin>
                <plugin>
                    <groupId>org.eclipse.tycho</groupId>
                    <artifactId>tycho-packaging-plugin</artifactId>
                    <configuration>
                        <strictVersions>false</strictVersions>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <url>http://www.openbel.org</url>
    <description>BEL Editor</description>
    <issueManagement>
        <system>GitHubtrac</system>
        <url>https://github.com/OpenBEL/bel-editor/issues</url>
    </issueManagement>
    <distributionManagement>
        <site>
            <id>www.openbel.org</id>
            <url></url>
        </site>
    </distributionManagement>
</project>


text:
<?php

/**
 * Here, we are connecting '/' (base path) to controller called 'Pages',
 * its action called 'display', and we pass a param to select the view file
 * to use (in this case, /app/views/pages/home.ctp)...
 */

    Router::parseExtensions('rss');

    Router::connect('/', array('controller' => 'home', 'action' => 'welcome'));

	Router::connect('/entries/category/:id', array('controller' => 'entry_categories', 'action' => 'view'),
                                    array('pass' => array('id'),
                                          'id' => '[0-9]+'));

	Router::connect('/entries/:id', array('controller' => 'entries', 'action' => 'view'),
                                    array('pass' => array('id'),
                                          'id' => '[0-9]+'));

	Router::connect('/ads/:id', array('controller' => 'ads', 'action' => 'view'),
                                    array('pass' => array('id'),
                                          'id' => '[0-9]+'));

	Router::connect('/announcements/:id', array('controller' => 'announcements', 'action' => 'view'),
                                    array('pass' => array('id'),
                                          'id' => '[0-9]+'));

	Router::connect('/news/archive/:year', array('controller' => 'news', 'action' => 'archive'),
                                    array('pass' => array('year'),
                                          'year' => '[0-9]+'));

	Router::connect('/news/:id', array('controller' => 'news', 'action' => 'view'),
                                    array('pass' => array('id'),
                                          'id' => '[0-9]+'));

/**
 * ...and connect the rest of 'Pages' controller's urls.
 */
	Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));


text:
FROM <IMAGE>
MAINTAINER <AUTHOR>

# Declare your dockerfile here


text:
package models

import (
	"container/list"
	"fmt"
	"os/exec"
	"strings"

	git "github.com/gogits/git-module"

	"github.com/gogits/gogs/modules/log"
)

type UpdateTask struct {
	ID          int64  `xorm:"pk autoincr"`
	UUID        string `xorm:"index"`
	RefName     string
	OldCommitID string
	NewCommitID string
}

func AddUpdateTask(task *UpdateTask) error {
	_, err := x.Insert(task)
	return err
}

// GetUpdateTaskByUUID returns update task by given UUID.
func GetUpdateTaskByUUID(uuid string) (*UpdateTask, error) {
	task := &UpdateTask{
		UUID: uuid,
	}
	has, err := x.Get(task)
	if err != nil {
		return nil, err
	} else if !has {
		return nil, ErrUpdateTaskNotExist{uuid}
	}
	return task, nil
}

func DeleteUpdateTaskByUUID(uuid string) error {
	_, err := x.Delete(&UpdateTask{UUID: uuid})
	return err
}

// CommitToPushCommit transforms a git.Commit to PushCommit type.
func CommitToPushCommit(commit *git.Commit) *PushCommit {
	return &PushCommit{
		Sha1:           commit.ID.String(),
		Message:        commit.Message(),
		AuthorEmail:    commit.Author.Email,
		AuthorName:     commit.Author.Name,
		CommitterEmail: commit.Committer.Email,
		CommitterName:  commit.Committer.Name,
		Timestamp:      commit.Author.When,
	}
}

func ListToPushCommits(l *list.List) *PushCommits {
	commits := make([]*PushCommit, 0)
	var actEmail string
	for e := l.Front(); e != nil; e = e.Next() {
		commit := e.Value.(*git.Commit)
		if actEmail == "" {
			actEmail = commit.Committer.Email
		}
		commits = append(commits, CommitToPushCommit(commit))
	}
	return &PushCommits{l.Len(), commits, "", nil}
}

type PushUpdateOptions struct {
	PusherID     int64
	PusherName   string
	RepoUserName string
	RepoName     string
	RefFullName  string
	OldCommitID  string
	NewCommitID  string
}

// PushUpdate must be called for any push actions in order to
// generates necessary push action history feeds.
func PushUpdate(opts PushUpdateOptions) (err error) {
	isNewRef := opts.OldCommitID == git.EMPTY_SHA
	isDelRef := opts.NewCommitID == git.EMPTY_SHA
	if isNewRef && isDelRef {
		return fmt.Errorf("Old and new revisions are both %s", git.EMPTY_SHA)
	}

	repoPath := RepoPath(opts.RepoUserName, opts.RepoName)

	gitUpdate := exec.Command("git", "update-server-info")
	gitUpdate.Dir = repoPath
	if err = gitUpdate.Run(); err != nil {
		return fmt.Errorf("Fail to call 'git update-server-info': %v", err)
	}

	if isDelRef {
		log.GitLogger.Info("Reference '%s' has been deleted from '%s/%s' by %d",
			opts.RefFullName, opts.RepoUserName, opts.RepoName, opts.PusherName)
		return nil
	}

	gitRepo, err := git.OpenRepository(repoPath)
	if err != nil {
		return fmt.Errorf("OpenRepository: %v", err)
	}

	owner, err := GetUserByName(opts.RepoUserName)
	if err != nil {
		return fmt.Errorf("GetUserByName: %v", err)
	}

	repo, err := GetRepositoryByName(owner.ID, opts.RepoName)
	if err != nil {
		return fmt.Errorf("GetRepositoryByName: %v", err)
	}

	// Push tags.
	if strings.HasPrefix(opts.RefFullName, git.TAG_PREFIX) {
		if err := CommitRepoAction(CommitRepoActionOptions{
			PusherName:  opts.PusherName,
			RepoOwnerID: owner.ID,
			RepoName:    repo.Name,
			RefFullName: opts.RefFullName,
			OldCommitID: opts.OldCommitID,
			NewCommitID: opts.NewCommitID,
			Commits:     &PushCommits{},
		}); err != nil {
			return fmt.Errorf("CommitRepoAction (tag): %v", err)
		}
		return nil
	}

	newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
	if err != nil {
		return fmt.Errorf("gitRepo.GetCommit: %v", err)
	}

	// Push new branch.
	var l *list.List
	if isNewRef {
		l, err = newCommit.CommitsBeforeLimit(10)
		if err != nil {
			return fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
		}
	} else {
		l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
		if err != nil {
			return fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
		}
	}

	if err := CommitRepoAction(CommitRepoActionOptions{
		PusherName:  opts.PusherName,
		RepoOwnerID: owner.ID,
		RepoName:    repo.Name,
		RefFullName: opts.RefFullName,
		OldCommitID: opts.OldCommitID,
		NewCommitID: opts.NewCommitID,
		Commits:     ListToPushCommits(l),
	}); err != nil {
		return fmt.Errorf("CommitRepoAction (branch): %v", err)
	}
	return nil
}


text:
<%!
    import string, re, cgi
    from mako import filters

    def plainfilter(f):
        f = re.sub(r'\n[\s\t]*\n[\s\t]*', '
\n
', f)
        f = "
" + f + "
"
        return f

%>

<%namespace name="nav" file="nav.html"/>

<%def name="section(toc, path, paged, extension, description=None)">
    ## Main section formatting element.
    <%
        item = toc.get_by_path(path)
        subsection = item.depth > 1
    %>

    <%
        content = capture(caller.body)
    %>

${description or item.description}

    ${content}

    % if (subsection and item.next and item.next.depth >= item.depth) or not subsection:
        % if paged:
            back to section top
        % else:
            back to section top
        % endif
    % endif

</%def>

<%def name="formatplain()" filter="plainfilter">
    ${ caller.body() | h}
</%def>

<%def name="codeline()" filter="trim,h">
    ${ caller.body() }
</%def>

<%def name="code(title=None, syntaxtype='mako', html_escape=False, use_sliders=False)">
    <%!
        import pygments
        from pygments.formatters import HtmlFormatter
        from pygments.lexers import PythonLexer, HtmlLexer, IniLexer
        from mako.ext.pygmentplugin import MakoHtmlLexer
        lexers = {'mako':MakoHtmlLexer(), 'python':PythonLexer(), 'html':HtmlLexer(),
                  'ini':IniLexer()}
    %>
    <%
        lexer = lexers.get(syntaxtype, None)
        # dumb hack to print a </%text> tag inside of a <%text> section
        content = re.sub(r'%CLOSETEXT', '</%text>', capture(caller.body))

        if lexer is not None:
            content = pygments.highlight(content, lexer, HtmlFormatter())
        else:
            content = "
" + content + "
"
    %>

        % if title is not None:
            ${title}
        % endif
        ${ content }

</%def>


text:
package uk.gov.dstl.baleen.consumers.print;

import org.apache.uima.UIMAException;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.fit.pipeline.SimplePipeline;
import org.junit.Test;

import uk.gov.dstl.baleen.annotators.testing.AnnotatorTestBase;
import uk.gov.dstl.baleen.graph.JCasTestGraphUtil;

public class RdfEntityGraphPrintTest extends AnnotatorTestBase {

  // NOTE: These don't actually check anything is written, just no null
  // pointers etc

  @Test
  public void testGraph() throws UIMAException {

    JCasTestGraphUtil.populateJcas(jCas);
    SimplePipeline.runPipeline(jCas, AnalysisEngineFactory.createEngine(RdfEntityGraph.class));
  }
}


text:
#ifndef __RESPONSE_HPP__
# define __RESPONSE_HPP__

# include <vector>
# include <string>

# include "server/utils/NonCopyable.hpp"
# include "view/IViewable.hpp"

namespace types
{
    class Response : public view::IViewable, public zhttpd::NonCopyable
    {
    public:
        typedef std::pair<std::string, std::string> pair_t;
        typedef std::vector<pair_t> fields_t;

    protected:
        fields_t _fields;
        fields_t _details;

    public:
        virtual void addField(std::string const& key, std::string const& val);
        virtual fields_t const& getFields() const;
        virtual void addDetail(std::string const& key, std::string const& val);
        virtual fields_t const& getDetails() const;
        virtual viewable_types::Type getViewableTypeId() const;
        virtual ~Response();
    };
}
#endif /* !__RESPONSE_HPP__ */


text:
require 'spec_helper'

describe 'Badges' do
  let(:user) { User.create! }
  let(:post) { Post.create! user: user }
  let(:card) { Scorecard::Card.new user }

  before :each do
    Scorecard.configure do |config|
      config.badges.add :new_post do |badge|
        badge.name     = 'Beginner'
        badge.locked   = 'Write a post'
        badge.unlocked = 'You wrote a post!'
        badge.check    = lambda { |user| Post.where(user_id: user.id).any? }
      end
    end

    post
  end

  it 'assigns badges to users' do
    Scorecard::Scorer.refresh user: user

    expect(card.badges.collect(&:name)).to eq(['Beginner'])
  end

  it "fires a badge notification when the badge is awarded" do
    fired = false

    subscriber = ActiveSupport::Notifications.subscribe 'badge.scorecard' do |*args|
      payload = ActiveSupport::Notifications::Event.new(*args).payload
      fired = (payload[:user] == user) && (payload[:badge].identifier == :new_post)
    end

    Scorecard::Scorer.refresh user: user

    ActiveSupport::Notifications.unsubscribe(subscriber)

    expect(fired).to be_true
  end

  it "doesn't repeat badges with different identifiers" do
    Scorecard::Scorer.refresh user: user
    Scorecard::Scorer.refresh user: user

    expect(card.badges.collect(&:name)).to eq(['Beginner'])
  end

  it "fires a badge notification only when the badge is awarded" do
    count = 0

    subscriber = ActiveSupport::Notifications.subscribe 'badge.scorecard' do |*args|
      count += 1
    end

    Scorecard::Scorer.refresh user: user
    Scorecard::Scorer.refresh user: user

    ActiveSupport::Notifications.unsubscribe(subscriber)

    expect(count).to eq(1)
  end

  it "repeats repeatable badges with different identifiers" do
    Scorecard.badges.find(:new_post).gameables = lambda { |user|
      Post.where(user_id: user.id)
    }
    second = Post.create! user: user

    Scorecard::Scorer.refresh user: user

    badge = card.badges.first
    expect(badge.name).to eq('Beginner')
    expect(badge.count).to eq(2)
    expect(badge.gameables).to match_array([post, second])
  end

  it "fires a badge notification each time it is awarded" do
    Scorecard.badges.find(:new_post).gameables = lambda { |user|
      Post.where(user_id: user.id)
    }
    Post.create! user: user

    count = 0

    subscriber = ActiveSupport::Notifications.subscribe 'badge.scorecard' do |*args|
      count += 1
    end

    Scorecard::Scorer.refresh user: user

    ActiveSupport::Notifications.unsubscribe(subscriber)

    expect(count).to eq(2)
  end

  it 'assigns badges to users via Sidekiq' do
    Scorecard::Scorer.refresh_async user: user

    expect(card.badges.collect(&:name)).to eq(['Beginner'])
  end
end


text:
public class Telnet {

	public static void main(String[] args) {
		Worker w = new Worker(args);
		w.start();
		try {
			w.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


text:
<?php
require_once("static/includes/sessions.php");
require_once("static/includes/functions.php");
if(!isset($_SESSION["username"])){
	redirect_to('index.php');
}
require_once("static/includes/dbsetup.php");
require_once("static/includes/validation_functions.php");

if(isset($_POST['submit'])){
  $required_fields = array("menu_name","position","visible","content");
  validate_presences($required_fields);
  $fields_with_max_lengths = array("menu_name" => 30);
  validate_max_lengths($fields_with_max_lengths);

  if (empty($errors)){
    $id = $_GET["page"];
    $menu_name = $_POST["menu_name"];
    $position = (int) $_POST["position"];
    $visible = (int) $_POST["visible"];
    $content = mysqli_real_escape_string($conn,$_POST["content"]);
    $menu_name = mysqli_real_escape_string($conn,$menu_name);
    //UPDATE subjects SET menu_name = 'rashtreeyam',position = 1,visible = 1 WHERE id = 1;
    $query = "UPDATE pages SET menu_item = '".$menu_name."', position = ".$position.", visible = ".$visible.", content = '".$content."' WHERE id = ".$id." LIMIT 1";
    $result = mysqli_query($conn,$query);
    if($result && mysqli_affected_rows($conn) >= 0){
      $_SESSION["message"] = "Page Updated!";
      redirect_to("manage_content.php");
    }
    else{
      $message = "Page Updation Failed!";
    }
  }
}

if(isset($_GET["page"])){
	$selected_page_id = $_GET["page"];
	if(!is_numeric($selected_page_id)){
    redirect_to("manage_content.php");
  }
  $selected_page_id = mysqli_real_escape_string($conn,$selected_page_id);
  $query = "SELECT * FROM pages WHERE id = {$selected_page_id} LIMIT 1";
  $result = mysqli_query($conn,$query);
  if( (!$result) || mysqli_num_rows($result) < 1){
      redirect_to("manage_content.php");
  }
  $a = mysqli_fetch_assoc($result);
  $_SESSION["ID"] = $a["ID"];

}
else{
	redirect_to("manage_content.php");
}

include "static/includes/layouts/open.php";
?>

 Edit Page <?php echo htmlentities($a["menu_item"]); ?>

          <?php
            if(!empty($message)){
              echo "
".htmlentities($message)."
";
            }
          ?>

        <form action="edit_page.php?page=<?php echo urlencode($a["ID"])?>" method="post">

				<input type="text" name="menu_name" value="<?php echo htmlentities($a["menu_item"]);?>" />
				Subject Name

Position:
              <select name="position" class="browser-default">
                <?php
                  $subject = find_subject_by_id($a["subject_id"]);
                  $page_set = get_all_pages_for_sub($subject);
                  $page_count = mysqli_num_rows($page_set);
                  for($count=1;$count<= $page_count;$count++){
                    if($count === intval($a["position"]))
                      echo "<option value='$count' selected='selected'>$count</option>";
                    else
                      echo "<option value='$count'>$count</option>";
                  }
                ?>
              </select>

Visible:
          <input type="radio" name="visible" id="test1" value="0" <?php if($a["visible"] == 0) echo "checked"; ?>>
			No

            <input type="radio" name="visible" id="test2" value="1" <?php if($a["visible"] == 1) echo "checked"; ?>>
			Yes

            <textarea id="content" class="materialize-textarea" name="content" ><?php echo htmlentities($a['content']);?> </textarea>
			Content

           <button type="submit" name="submit" class="btn">Confirm Edit</button>

        </form>

	Cancel and go back

        <a href="delete_page.php?page=<?php echo urlencode($a["ID"])?>" onclick="return confirm('Are you Sure?'); "> Delete this Page

<?php
include "static/includes/layouts/close.php";
?>


text:
"""Converts an old version's data base to the recent format.

The database of the rc-1 did not have a priority field. This script
just adds this to all issues."""

import os
import pickle

ISSUE_FILE = '.issues'

if __name__ == "__main__":
    with open(ISSUE_FILE,'r') as issues:
        DB = pickle.load(issues)
        for issue in DB.values():
            if not hasattr(issue, 'priority'):
                issue.priority = 3
    with open(ISSUE_FILE, 'w') as issues:
        pickle.dump(DB, issues, -1)


text:
/**
 * Контроллер блока бумажной публикации.
 *
 * @author dew1983@mail.ru <Suvorov Andrey M.>
 */

Ext.define(
	'FBEditor.view.form.desc.fieldset.publishInfo.PublishInfoController',
	{
		extend: 'FBEditor.view.form.desc.fieldset.AbstractFieldsetController',
		alias: 'controller.desc.fieldset.publishInfo',

		resetFieldset:  function (data)
		{
			var me = this,
				view = me.getView(),
				title;

			// сбрасываем флаг изменения поля названия
			title = view.getPublishTitle();
			title.isChanged = false;

			me.callParent(arguments);
		},

		onExpand: function ()
		{
			var me = this,
				view = me.getView(),
				title;

			title = view.getPublishTitle();

			if (!title.isChanged && !title.getValue())
			{
				title.fireEvent('copyTitle');
			}
		}
	}
);


text:
<?php
namespace InsaLan\PizzaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 */
class Pizza
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=50)
     * @Assert\NotBlank()
     */
    protected $name;

    /**
     * @ORM\Column(type="float")
     */
    protected $price;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    public function __toString() {
        return $this->getName();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Pizza
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param float $price
     * @return Pizza
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Pizza
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}