text:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <math.h>

#include <FreeRTOS.h>
#include <task.h>

#include "ccronexpr.h"

#define CRON_MAX_SECONDS 60
#define CRON_MAX_MINUTES 60
#define CRON_MAX_HOURS 24
#define CRON_MAX_DAYS_OF_WEEK 8
#define CRON_MAX_DAYS_OF_MONTH 32
#define CRON_MAX_MONTHS 12
#define CRON_MAX_YEARS_DIFF 4

#define CRON_CF_SECOND 0
#define CRON_CF_MINUTE 1
#define CRON_CF_HOUR_OF_DAY 2
#define CRON_CF_DAY_OF_WEEK 3
#define CRON_CF_DAY_OF_MONTH 4
#define CRON_CF_MONTH 5
#define CRON_CF_YEAR 6

#define CRON_CF_ARR_LEN 7

#define CRON_INVALID_INSTANT ((time_t) -1)

static const char* const DAYS_ARR[] = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
#define CRON_DAYS_ARR_LEN 7
static const char* const MONTHS_ARR[] = { "FOO", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
#define CRON_MONTHS_ARR_LEN 13

#define CRON_MAX_STR_LEN_TO_SPLIT 256
#define CRON_MAX_NUM_TO_SRING 1000000000
/* computes number of digits in decimal number */
#define CRON_NUM_OF_DIGITS(num) (abs(num) < 10 ? 1 : \
                                (abs(num) < 100 ? 2 : \
                                (abs(num) < 1000 ? 3 : \
                                (abs(num) < 10000 ? 4 : \
                                (abs(num) < 100000 ? 5 : \
                                (abs(num) < 1000000 ? 6 : \
                                (abs(num) < 10000000 ? 7 : \
                                (abs(num) < 100000000 ? 8 : \
                                (abs(num) < 1000000000 ? 9 : 10)))))))))

#define cron_malloc(x) pvPortMalloc(x);
#define cron_free(x) vPortFree(x);

/**
 * Time functions from standard library.
 * This part defines: cron_mktime: create time_t from tm
 *                    cron_time: create tm from time_t
 */

/* forward declarations for platforms that may need them */
/* can be hidden in time.h */
#if !defined(_WIN32) && !defined(__AVR__) && !defined(ANDROID)
struct tm *gmtime_r(const time_t *timep, struct tm *result);
time_t timegm(struct tm* __tp);
struct tm *localtime_r(const time_t *timep, struct tm *result);
#endif /* PLEASE CHECK _WIN32 AND ANDROID NEEDS FOR THESE DECLARATIONS */
#ifdef __MINGW32__
/* To avoid warning when building with mingw */
time_t _mkgmtime(struct tm* tm);
#endif /* __MINGW32__ */

/* function definitions */
time_t cron_mktime_gm(struct tm* tm) {
#if defined(_WIN32)
/* http://stackoverflow.com/a/22557778 */
    return _mkgmtime(tm);
#elif defined(__AVR__)
/* https://www.nongnu.org/avr-libc/user-manual/group__avr__time.html */
    return mk_gmtime(tm);

#elif defined(ANDROID)
    /* https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/base/os_compat_android.cc#L20 */
    static const time_t kTimeMax = ~(1L << (sizeof (time_t) * CHAR_BIT - 1));
    static const time_t kTimeMin = (1L << (sizeof (time_t) * CHAR_BIT - 1));
    time64_t result = timegm64(tm);
    if (result < kTimeMin || result > kTimeMax) return -1;
    return result;
#else
    return timegm(tm);
#endif
}

struct tm* cron_time_gm(time_t* date, struct tm* out) {
#if defined(__MINGW32__)
    (void)(out); /* To avoid unused warning */
    return gmtime(date);
#elif defined(_WIN32)
    errno_t err = gmtime_s(out, date);
    return 0 == err ? out : NULL;
#elif defined(__AVR__)
    /* https://www.nongnu.org/avr-libc/user-manual/group__avr__time.html */
    gmtime_r(date, out);
    return out;
#else
    return gmtime_r(date, out);
#endif
}

time_t cron_mktime_local(struct tm* tm) {
    tm->tm_isdst = -1;
    return mktime(tm);
}

struct tm* cron_time_local(time_t* date, struct tm* out) {
#if defined(_WIN32)
    errno_t err = localtime_s(out, date);
    return 0 == err ? out : NULL;
#elif defined(__AVR__)
    /* https://www.nongnu.org/avr-libc/user-manual/group__avr__time.html */
    localtime_r(date, out);
    return out;
#else
    return localtime_r(date, out);
#endif
}

/* Defining 'cron_' time functions to use use UTC (default) or local time */
#ifndef CRON_USE_LOCAL_TIME
time_t cron_mktime(struct tm* tm) {
    return cron_mktime_gm(tm);
}

struct tm* cron_time(time_t* date, struct tm* out) {
    return cron_time_gm(date, out);
}

#else /* CRON_USE_LOCAL_TIME */
time_t cron_mktime(struct tm* tm) {
    return cron_mktime_local(tm);
}

struct tm* cron_time(time_t* date, struct tm* out) {
    return cron_time_local(date, out);
}

#endif /* CRON_USE_LOCAL_TIME */

/**
 * Functions.
 */

void cron_set_bit(uint8_t* rbyte, int idx) {
    uint8_t j = (uint8_t) (idx / 8);
    uint8_t k = (uint8_t) (idx % 8);

    rbyte[j] |= (1 << k);
}

void cron_del_bit(uint8_t* rbyte, int idx) {
    uint8_t j = (uint8_t) (idx / 8);
    uint8_t k = (uint8_t) (idx % 8);

    rbyte[j] &= ~(1 << k);
}

uint8_t cron_get_bit(uint8_t* rbyte, int idx) {
    uint8_t j = (uint8_t) (idx / 8);
    uint8_t k = (uint8_t) (idx % 8);

    if (rbyte[j] & (1 << k)) {
        return 1;
    } else {
        return 0;
    }
}

static void free_splitted(char** splitted, size_t len) {
    size_t i;
    if (!splitted) return;
    for (i = 0; i < len; i++) {
        if (splitted[i]) {
            cron_free(splitted[i]);
        }
    }
    cron_free(splitted);
}

static char* strdupl(const char* str, size_t len) {
    if (!str) return NULL;
    char* res = (char*) cron_malloc(len + 1);
    if (!res) return NULL;
    memset(res, 0, len + 1);
    memcpy(res, str, len);
    return res;
}

static unsigned int next_set_bit(uint8_t* bits, unsigned int max, unsigned int from_index, int* notfound) {
    unsigned int i;
    if (!bits) {
        *notfound = 1;
        return 0;
    }
    for (i = from_index; i < max; i++) {
        if (cron_get_bit(bits, i)) return i;
    }
    *notfound = 1;
    return 0;
}

static void push_to_fields_arr(int* arr, int fi) {
    int i;
    if (!arr || -1 == fi) {
        return;
    }
    for (i = 0; i < CRON_CF_ARR_LEN; i++) {
        if (arr[i] == fi) return;
    }
    for (i = 0; i < CRON_CF_ARR_LEN; i++) {
        if (-1 == arr[i]) {
            arr[i] = fi;
            return;
        }
    }
}

static int add_to_field(struct tm* calendar, int field, int val) {
    if (!calendar || -1 == field) {
        return 1;
    }
    switch (field) {
    case CRON_CF_SECOND:
        calendar->tm_sec = calendar->tm_sec + val;
        break;
    case CRON_CF_MINUTE:
        calendar->tm_min = calendar->tm_min + val;
        break;
    case CRON_CF_HOUR_OF_DAY:
        calendar->tm_hour = calendar->tm_hour + val;
        break;
    case CRON_CF_DAY_OF_WEEK: /* mkgmtime ignores this field */
    case CRON_CF_DAY_OF_MONTH:
        calendar->tm_mday = calendar->tm_mday + val;
        break;
    case CRON_CF_MONTH:
        calendar->tm_mon = calendar->tm_mon + val;
        break;
    case CRON_CF_YEAR:
        calendar->tm_year = calendar->tm_year + val;
        break;
    default:
        return 1; /* unknown field */
    }
    time_t res = cron_mktime(calendar);
    if (CRON_INVALID_INSTANT == res) {
        return 1;
    }
    return 0;
}

/**
 * Reset the calendar setting all the fields provided to zero.
 */
static int reset_min(struct tm* calendar, int field) {
    if (!calendar || -1 == field) {
        return 1;
    }
    switch (field) {
    case CRON_CF_SECOND:
        calendar->tm_sec = 0;
        break;
    case CRON_CF_MINUTE:
        calendar->tm_min = 0;
        break;
    case CRON_CF_HOUR_OF_DAY:
        calendar->tm_hour = 0;
        break;
    case CRON_CF_DAY_OF_WEEK:
        calendar->tm_wday = 0;
        break;
    case CRON_CF_DAY_OF_MONTH:
        calendar->tm_mday = 1;
        break;
    case CRON_CF_MONTH:
        calendar->tm_mon = 0;
        break;
    case CRON_CF_YEAR:
        calendar->tm_year = 0;
        break;
    default:
        return 1; /* unknown field */
    }
    time_t res = cron_mktime(calendar);
    if (CRON_INVALID_INSTANT == res) {
        return 1;
    }
    return 0;
}

static int reset_all_min(struct tm* calendar, int* fields) {
    int i;
    int res = 0;
    if (!calendar || !fields) {
        return 1;
    }
    for (i = 0; i < CRON_CF_ARR_LEN; i++) {
        if (-1 != fields[i]) {
            res = reset_min(calendar, fields[i]);
            if (0 != res) return res;
        }
    }
    return 0;
}

static int set_field(struct tm* calendar, int field, int val) {
    if (!calendar || -1 == field) {
        return 1;
    }
    switch (field) {
    case CRON_CF_SECOND:
        calendar->tm_sec = val;
        break;
    case CRON_CF_MINUTE:
        calendar->tm_min = val;
        break;
    case CRON_CF_HOUR_OF_DAY:
        calendar->tm_hour = val;
        break;
    case CRON_CF_DAY_OF_WEEK:
        calendar->tm_wday = val;
        break;
    case CRON_CF_DAY_OF_MONTH:
        calendar->tm_mday = val;
        break;
    case CRON_CF_MONTH:
        calendar->tm_mon = val;
        break;
    case CRON_CF_YEAR:
        calendar->tm_year = val;
        break;
    default:
        return 1; /* unknown field */
    }
    time_t res = cron_mktime(calendar);
    if (CRON_INVALID_INSTANT == res) {
        return 1;
    }
    return 0;
}

/**
 * Search the bits provided for the next set bit after the value provided,
 * and reset the calendar.
 */
static unsigned int find_next(uint8_t* bits, unsigned int max, unsigned int value, struct tm* calendar, unsigned int field, unsigned int nextField, int* lower_orders, int* res_out) {
    int notfound = 0;
    int err = 0;
    unsigned int next_value = next_set_bit(bits, max, value, &notfound);
    /* roll over if needed */
    if (notfound) {
        err = add_to_field(calendar, nextField, 1);
        if (err) goto return_error;
        err = reset_min(calendar, field);
        if (err) goto return_error;
        notfound = 0;
        next_value = next_set_bit(bits, max, 0, &notfound);
    }
    if (notfound || next_value != value) {
        err = set_field(calendar, field, next_value);
        if (err) goto return_error;
        err = reset_all_min(calendar, lower_orders);
        if (err) goto return_error;
    }
    return next_value;

    return_error:
    *res_out = 1;
    return 0;
}

static unsigned int find_next_day(struct tm* calendar, uint8_t* days_of_month, unsigned int day_of_month, uint8_t* days_of_week, unsigned int day_of_week, int* resets, int* res_out) {
    int err;
    unsigned int count = 0;
    unsigned int max = 366;
    while ((!cron_get_bit(days_of_month, day_of_month) || !cron_get_bit(days_of_week, day_of_week)) && count++ < max) {
        err = add_to_field(calendar, CRON_CF_DAY_OF_MONTH, 1);

        if (err) goto return_error;
        day_of_month = calendar->tm_mday;
        day_of_week = calendar->tm_wday;
        reset_all_min(calendar, resets);
    }
    return day_of_month;

    return_error:
    *res_out = 1;
    return 0;
}

static int do_next(cron_expr* expr, struct tm* calendar, unsigned int dot) {
    int i;
    int res = 0;
    int* resets = NULL;
    int* empty_list = NULL;
    unsigned int second = 0;
    unsigned int update_second = 0;
    unsigned int minute = 0;
    unsigned int update_minute = 0;
    unsigned int hour = 0;
    unsigned int update_hour = 0;
    unsigned int day_of_week = 0;
    unsigned int day_of_month = 0;
    unsigned int update_day_of_month = 0;
    unsigned int month = 0;
    unsigned int update_month = 0;

    resets = (int*) cron_malloc(CRON_CF_ARR_LEN * sizeof(int));
    if (!resets) goto return_result;
    empty_list = (int*) cron_malloc(CRON_CF_ARR_LEN * sizeof(int));
    if (!empty_list) goto return_result;
    for (i = 0; i < CRON_CF_ARR_LEN; i++) {
        resets[i] = -1;
        empty_list[i] = -1;
    }

    second = calendar->tm_sec;
    update_second = find_next(expr->seconds, CRON_MAX_SECONDS, second, calendar, CRON_CF_SECOND, CRON_CF_MINUTE, empty_list, &res);
    if (0 != res) goto return_result;
    if (second == update_second) {
        push_to_fields_arr(resets, CRON_CF_SECOND);
    }

    minute = calendar->tm_min;
    update_minute = find_next(expr->minutes, CRON_MAX_MINUTES, minute, calendar, CRON_CF_MINUTE, CRON_CF_HOUR_OF_DAY, resets, &res);
    if (0 != res) goto return_result;
    if (minute == update_minute) {
        push_to_fields_arr(resets, CRON_CF_MINUTE);
    } else {
        res = do_next(expr, calendar, dot);
        if (0 != res) goto return_result;
    }

    hour = calendar->tm_hour;
    update_hour = find_next(expr->hours, CRON_MAX_HOURS, hour, calendar, CRON_CF_HOUR_OF_DAY, CRON_CF_DAY_OF_WEEK, resets, &res);
    if (0 != res) goto return_result;
    if (hour == update_hour) {
        push_to_fields_arr(resets, CRON_CF_HOUR_OF_DAY);
    } else {
        res = do_next(expr, calendar, dot);
        if (0 != res) goto return_result;
    }

    day_of_week = calendar->tm_wday;
    day_of_month = calendar->tm_mday;
    update_day_of_month = find_next_day(calendar, expr->days_of_month, day_of_month, expr->days_of_week, day_of_week, resets, &res);
    if (0 != res) goto return_result;
    if (day_of_month == update_day_of_month) {
        push_to_fields_arr(resets, CRON_CF_DAY_OF_MONTH);
    } else {
        res = do_next(expr, calendar, dot);
        if (0 != res) goto return_result;
    }

    month = calendar->tm_mon; /*day already adds one if no day in same month is found*/
    update_month = find_next(expr->months, CRON_MAX_MONTHS, month, calendar, CRON_CF_MONTH, CRON_CF_YEAR, resets, &res);
    if (0 != res) goto return_result;
    if (month != update_month) {
        if (calendar->tm_year - dot > 4) {
            res = -1;
            goto return_result;
        }
        res = do_next(expr, calendar, dot);
        if (0 != res) goto return_result;
    }
    goto return_result;

    return_result:
    if (!resets || !empty_list) {
        res = -1;
    }
    if (resets) {
        cron_free(resets);
    }
    if (empty_list) {
        cron_free(empty_list);
    }
    return res;
}

static int to_upper(char* str) {
    if (!str) return 1;
    int i;
    for (i = 0; '\0' != str[i]; i++) {
        int c = (int)str[i];
        str[i] = (char) toupper(c);
    }
    return 0;
}

static char* to_string(int num) {
    if (abs(num) >= CRON_MAX_NUM_TO_SRING) return NULL;
    char* str = (char*) cron_malloc(CRON_NUM_OF_DIGITS(num) + 1);
    if (!str) return NULL;
    int res = sprintf(str, "%d", num);
    if (res < 0) {
        cron_free(str);
        return NULL;
    }
    return str;
}

static char* str_replace(char *orig, const char *rep, const char *with) {
    char *result; /* the return string */
    char *ins; /* the next insert point */
    char *tmp; /* varies */
    size_t len_rep; /* length of rep */
    size_t len_with; /* length of with */
    size_t len_front; /* distance between rep and end of last rep */
    int count; /* number of replacements */
    if (!orig) return NULL;
    if (!rep) rep = "";
    if (!with) with = "";
    len_rep = strlen(rep);
    len_with = strlen(with);

    ins = orig;
    for (count = 0; NULL != (tmp = strstr(ins, rep)); ++count) {
        ins = tmp + len_rep;
    }

    /* first time through the loop, all the variable are set correctly
     from here on,
     tmp points to the end of the result string
     ins points to the next occurrence of rep in orig
     orig points to the remainder of orig after "end of rep"
     */
    tmp = result = (char*) cron_malloc(strlen(orig) + (len_with - len_rep) * count + 1);
    if (!result) return NULL;

    while (count--) {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; /* move to next "end of rep" */
    }
    strcpy(tmp, orig);
    return result;
}

static unsigned int parse_uint(const char* str, int* errcode) {
    char* endptr;
    errno = 0;
    long int l = strtol(str, &endptr, 0);
    if (errno == ERANGE || *endptr != '\0' || l < 0 || l > INT_MAX) {
        *errcode = 1;
        return 0;
    } else {
        *errcode = 0;
        return (unsigned int) l;
    }
}

static char** split_str(const char* str, char del, size_t* len_out) {
    size_t i;
    size_t stlen = 0;
    size_t len = 0;
    int accum = 0;
    char* buf = NULL;
    char** res = NULL;
    size_t bi = 0;
    size_t ri = 0;
    char* tmp;

    if (!str) goto return_error;
    for (i = 0; '\0' != str[i]; i++) {
        stlen += 1;
        if (stlen >= CRON_MAX_STR_LEN_TO_SPLIT) goto return_error;
    }

    for (i = 0; i < stlen; i++) {
        int c = str[i];
        if (del == str[i]) {
            if (accum > 0) {
                len += 1;
                accum = 0;
            }
        } else if (!isspace(c)) {
            accum += 1;
        }
    }
    /* tail */
    if (accum > 0) {
        len += 1;
    }
    if (0 == len) return NULL;

    buf = (char*) cron_malloc(stlen + 1);
    if (!buf) goto return_error;
    memset(buf, 0, stlen + 1);
    res = (char**) cron_malloc(len * sizeof(char*));
    if (!res) goto return_error;
    memset(res, 0, len * sizeof(char*));

    for (i = 0; i < stlen; i++) {
        int c = str[i];
        if (del == str[i]) {
            if (bi > 0) {
                tmp = strdupl(buf, bi);
                if (!tmp) goto return_error;
                res[ri++] = tmp;
                memset(buf, 0, stlen + 1);
                bi = 0;
            }
        } else if (!isspace(c)) {
            buf[bi++] = str[i];
        }
    }
    /* tail */
    if (bi > 0) {
        tmp = strdupl(buf, bi);
        if (!tmp) goto return_error;
        res[ri++] = tmp;
    }
    cron_free(buf);
    *len_out = len;
    return res;

    return_error:
    if (buf) {
        cron_free(buf);
    }
    free_splitted(res, len);
    *len_out = 0;
    return NULL;
}

static char* replace_ordinals(char* value, const char* const * arr, size_t arr_len) {
    size_t i;
    char* cur = value;
    char* res = NULL;
    int first = 1;
    for (i = 0; i < arr_len; i++) {
        char* strnum = to_string((int) i);
        if (!strnum) {
            if (!first) {
                cron_free(cur);
            }
            return NULL;
        }
        res = str_replace(cur, arr[i], strnum);
        cron_free(strnum);
        if (!first) {
            cron_free(cur);
        }
        if (!res) {
            return NULL;
        }
        cur = res;
        if (first) {
            first = 0;
        }
    }
    return res;
}

static int has_char(char* str, char ch) {
    size_t i;
    size_t len = 0;
    if (!str) return 0;
    len = strlen(str);
    for (i = 0; i < len; i++) {
        if (str[i] == ch) return 1;
    }
    return 0;
}

static unsigned int* get_range(char* field, unsigned int min, unsigned int max, const char** error) {

    char** parts = NULL;
    size_t len = 0;
    unsigned int* res = (unsigned int*) cron_malloc(2 * sizeof(unsigned int));
    if (!res) goto return_error;

    res[0] = 0;
    res[1] = 0;
    if (1 == strlen(field) && '*' == field[0]) {
        res[0] = min;
        res[1] = max - 1;
    } else if (!has_char(field, '-')) {
        int err = 0;
        unsigned int val = parse_uint(field, &err);
        if (err) {
            *error = "Unsigned integer parse error 1";
            goto return_error;
        }

        res[0] = val;
        res[1] = val;
    } else {
        parts = split_str(field, '-', &len);
        if (2 != len) {
            *error = "Specified range requires two fields";
            goto return_error;
        }
        int err = 0;
        res[0] = parse_uint(parts[0], &err);
        if (err) {
            *error = "Unsigned integer parse error 2";
            goto return_error;
        }
        res[1] = parse_uint(parts[1], &err);
        if (err) {
            *error = "Unsigned integer parse error 3";
            goto return_error;
        }
    }
    if (res[0] >= max || res[1] >= max) {
        *error = "Specified range exceeds maximum";
        goto return_error;
    }
    if (res[0] < min || res[1] < min) {
        *error = "Specified range is less than minimum";
        goto return_error;
    }
    if (res[0] > res[1]) {
        *error = "Specified range start exceeds range end";
        goto return_error;
    }

    free_splitted(parts, len);
    *error = NULL;
    return res;

    return_error:
    free_splitted(parts, len);
    if (res) {
        cron_free(res);
    }

    return NULL;
}

static void set_number_hits(const char* value, uint8_t* target, unsigned int min, unsigned int max, const char** error) {
    size_t i;
    unsigned int i1;
    size_t len = 0;

    char** fields = split_str(value, ',', &len);
    if (!fields) {
        *error = "Comma split error";
        goto return_result;
    }

    for (i = 0; i < len; i++) {
        if (!has_char(fields[i], '/')) {
            /* Not an incrementer so it must be a range (possibly empty) */

            unsigned int* range = get_range(fields[i], min, max, error);

            if (*error) {
                if (range) {
                    cron_free(range);
                }
                goto return_result;

            }

            for (i1 = range[0]; i1 <= range[1]; i1++) {
                cron_set_bit(target, i1);

            }
            cron_free(range);

        } else {
            size_t len2 = 0;
            char** split = split_str(fields[i], '/', &len2);
            if (2 != len2) {
                *error = "Incrementer must have two fields";
                free_splitted(split, len2);
                goto return_result;
            }
            unsigned int* range = get_range(split[0], min, max, error);
            if (*error) {
                if (range) {
                    cron_free(range);
                }
                free_splitted(split, len2);
                goto return_result;
            }
            if (!has_char(split[0], '-')) {
                range[1] = max - 1;
            }
            int err = 0;
            unsigned int delta = parse_uint(split[1], &err);
            if (err) {
                *error = "Unsigned integer parse error 4";
                cron_free(range);
                free_splitted(split, len2);
                goto return_result;
            }
            if (0 == delta) {
                *error = "Incrementer may not be zero";
                cron_free(range);
                free_splitted(split, len2);
                goto return_result;
            }
            for (i1 = range[0]; i1 <= range[1]; i1 += delta) {
                cron_set_bit(target, i1);
            }
            free_splitted(split, len2);
            cron_free(range);

        }
    }
    goto return_result;

    return_result:
    free_splitted(fields, len);

}

static void set_months(char* value, uint8_t* targ, const char** error) {
    unsigned int i;
    unsigned int max = 12;

    char* replaced = NULL;

    to_upper(value);
    replaced = replace_ordinals(value, MONTHS_ARR, CRON_MONTHS_ARR_LEN);
    if (!replaced) {
        *error = "Invalid month format";
        return;
    }
    set_number_hits(replaced, targ, 1, max + 1, error);
    cron_free(replaced);

    /* ... and then rotate it to the front of the months */
    for (i = 1; i <= max; i++) {
        if (cron_get_bit(targ, i)) {
            cron_set_bit(targ, i - 1);
            cron_del_bit(targ, i);
        }
    }
}

static void set_days_of_week(char* field, uint8_t* targ, const char** error) {
    unsigned int max = 7;
    char* replaced = NULL;

    if (1 == strlen(field) && '?' == field[0]) {
        field[0] = '*';
    }
    to_upper(field);
    replaced = replace_ordinals(field, DAYS_ARR, CRON_DAYS_ARR_LEN);
    if (!replaced) {
        *error = "Invalid day format";
        return;
    }
    set_number_hits(replaced, targ, 0, max + 1, error);
    cron_free(replaced);
    if (cron_get_bit(targ, 7)) {
        /* Sunday can be represented as 0 or 7*/
        cron_set_bit(targ, 0);
        cron_del_bit(targ, 7);
    }
}

static void set_days_of_month(char* field, uint8_t* targ, const char** error) {
    /* Days of month start with 1 (in Cron and Calendar) so add one */
    if (1 == strlen(field) && '?' == field[0]) {
        field[0] = '*';
    }
    set_number_hits(field, targ, 1, CRON_MAX_DAYS_OF_MONTH, error);
}

void cron_parse_expr(const char* expression, cron_expr* target, const char** error) {
    const char* err_local;
    size_t len = 0;
    char** fields = NULL;
    if (!error) {
        error = &err_local;
    }
    *error = NULL;
    if (!expression) {
        *error = "Invalid NULL expression";
        goto return_res;
    }
    if (!target) {
        *error = "Invalid NULL target";
        goto return_res;
    }

    fields = split_str(expression, ' ', &len);
    if (len != 6) {
        *error = "Invalid number of fields, expression must consist of 6 fields";
        goto return_res;
    }
    memset(target, 0, sizeof(*target));
    set_number_hits(fields[0], target->seconds, 0, 60, error);
    if (*error) goto return_res;
    set_number_hits(fields[1], target->minutes, 0, 60, error);
    if (*error) goto return_res;
    set_number_hits(fields[2], target->hours, 0, 24, error);
    if (*error) goto return_res;
    set_days_of_month(fields[3], target->days_of_month, error);
    if (*error) goto return_res;
    set_months(fields[4], target->months, error);
    if (*error) goto return_res;
    set_days_of_week(fields[5], target->days_of_week, error);
    if (*error) goto return_res;

    goto return_res;

    return_res:
    free_splitted(fields, len);
}

time_t cron_next(cron_expr* expr, time_t date) {
    /*
     The plan:

     1 Round up to the next whole second

     2 If seconds match move on, otherwise find the next match:
     2.1 If next match is in the next minute then roll forwards

     3 If minute matches move on, otherwise find the next match
     3.1 If next match is in the next hour then roll forwards
     3.2 Reset the seconds and go to 2

     4 If hour matches move on, otherwise find the next match
     4.1 If next match is in the next day then roll forwards,
     4.2 Reset the minutes and seconds and go to 2

     ...
     */
    if (!expr) return CRON_INVALID_INSTANT;
    struct tm calval;
    memset(&calval, 0, sizeof(struct tm));
    struct tm* calendar = cron_time(&date, &calval);//pass date, get tm calval
    if (!calendar) return CRON_INVALID_INSTANT;
    time_t original = cron_mktime(calendar);//pass tm. get time_t
    if (CRON_INVALID_INSTANT == original) return CRON_INVALID_INSTANT;

    int res = do_next(expr, calendar, calendar->tm_year);
    if (0 != res) return CRON_INVALID_INSTANT;

    time_t calculated = cron_mktime(calendar);
    if (CRON_INVALID_INSTANT == calculated) return CRON_INVALID_INSTANT;
    if (calculated == original) {
        /* We arrived at the original timestamp - round up to the next whole second and try again... */
        res = add_to_field(calendar, CRON_CF_SECOND, 1);
        if (0 != res) return CRON_INVALID_INSTANT;
        res = do_next(expr, calendar, calendar->tm_year);
        if (0 != res) return CRON_INVALID_INSTANT;
    }

    return cron_mktime(calendar);
}

/* https://github.com/staticlibs/ccronexpr/pull/8 */

static unsigned int prev_set_bit(uint8_t* bits, int from_index, int to_index, int* notfound) {
    int i;
    if (!bits) {
        *notfound = 1;
        return 0;
    }
    for (i = from_index; i >= to_index; i--) {
        if (cron_get_bit(bits, i)) return i;
    }
    *notfound = 1;
    return 0;
}

static int last_day_of_month(int month, int year) {
    struct tm cal;
    time_t t;
    memset(&cal,0,sizeof(cal));
    cal.tm_sec=0;
    cal.tm_min=0;
    cal.tm_hour=0;
    cal.tm_mon = month+1;
    cal.tm_mday = 0;
    cal.tm_year=year;
    t=mktime(&cal);
    return gmtime(&t)->tm_mday;
}

/**
 * Reset the calendar setting all the fields provided to zero.
 */
static int reset_max(struct tm* calendar, int field) {
    if (!calendar || -1 == field) {
        return 1;
    }
    switch (field) {
    case CRON_CF_SECOND:
        calendar->tm_sec = 59;
        break;
    case CRON_CF_MINUTE:
        calendar->tm_min = 59;
        break;
    case CRON_CF_HOUR_OF_DAY:
        calendar->tm_hour = 23;
        break;
    case CRON_CF_DAY_OF_WEEK:
        calendar->tm_wday = 6;
        break;
    case CRON_CF_DAY_OF_MONTH:
        calendar->tm_mday = last_day_of_month(calendar->tm_mon, calendar->tm_year);
        break;
    case CRON_CF_MONTH:
        calendar->tm_mon = 11;
        break;
    case CRON_CF_YEAR:
        /* I don't think this is supposed to happen ... */
        fprintf(stderr, "reset CRON_CF_YEAR\n");
        break;
    default:
        return 1; /* unknown field */
    }
    time_t res = cron_mktime(calendar);
    if (CRON_INVALID_INSTANT == res) {
        return 1;
    }
    return 0;
}

static int reset_all_max(struct tm* calendar, int* fields) {
    int i;
    int res = 0;
    if (!calendar || !fields) {
        return 1;
    }
    for (i = 0; i < CRON_CF_ARR_LEN; i++) {
        if (-1 != fields[i]) {
            res = reset_max(calendar, fields[i]);
            if (0 != res) return res;
        }
    }
    return 0;
}

/**
 * Search the bits provided for the next set bit after the value provided,
 * and reset the calendar.
 */
static unsigned int find_prev(uint8_t* bits, unsigned int max, unsigned int value, struct tm* calendar, unsigned int field, unsigned int nextField, int* lower_orders, int* res_out) {
    int notfound = 0;
    int err = 0;
    unsigned int next_value = prev_set_bit(bits, value, 0, &notfound);
    /* roll under if needed */
    if (notfound) {
        err = add_to_field(calendar, nextField, -1);
        if (err) goto return_error;
        err = reset_max(calendar, field);
        if (err) goto return_error;
        notfound = 0;
        next_value = prev_set_bit(bits, max - 1, value, &notfound);
    }
    if (notfound || next_value != value) {
        err = set_field(calendar, field, next_value);
        if (err) goto return_error;
        err = reset_all_max(calendar, lower_orders);
        if (err) goto return_error;
    }
    return next_value;

    return_error:
    *res_out = 1;
    return 0;
}

static unsigned int find_prev_day(struct tm* calendar, uint8_t* days_of_month, unsigned int day_of_month, uint8_t* days_of_week, unsigned int day_of_week, int* resets, int* res_out) {
    int err;
    unsigned int count = 0;
    unsigned int max = 366;
    while ((!cron_get_bit(days_of_month, day_of_month) || !cron_get_bit(days_of_week, day_of_week)) && count++ < max) {
        err = add_to_field(calendar, CRON_CF_DAY_OF_MONTH, -1);

        if (err) goto return_error;
        day_of_month = calendar->tm_mday;
        day_of_week = calendar->tm_wday;
        reset_all_max(calendar, resets);
    }
    return day_of_month;

    return_error:
    *res_out = 1;
    return 0;
}

static int do_prev(cron_expr* expr, struct tm* calendar, unsigned int dot) {
    int i;
    int res = 0;
    int* resets = NULL;
    int* empty_list = NULL;
    unsigned int second = 0;
    unsigned int update_second = 0;
    unsigned int minute = 0;
    unsigned int update_minute = 0;
    unsigned int hour = 0;
    unsigned int update_hour = 0;
    unsigned int day_of_week = 0;
    unsigned int day_of_month = 0;
    unsigned int update_day_of_month = 0;
    unsigned int month = 0;
    unsigned int update_month = 0;

    resets = (int*) cron_malloc(CRON_CF_ARR_LEN * sizeof(int));
    if (!resets) goto return_result;
    empty_list = (int*) cron_malloc(CRON_CF_ARR_LEN * sizeof(int));
    if (!empty_list) goto return_result;
    for (i = 0; i < CRON_CF_ARR_LEN; i++) {
        resets[i] = -1;
        empty_list[i] = -1;
    }

    second = calendar->tm_sec;
    update_second = find_prev(expr->seconds, CRON_MAX_SECONDS, second, calendar, CRON_CF_SECOND, CRON_CF_MINUTE, empty_list, &res);
    if (0 != res) goto return_result;
    if (second == update_second) {
        push_to_fields_arr(resets, CRON_CF_SECOND);
    }

    minute = calendar->tm_min;
    update_minute = find_prev(expr->minutes, CRON_MAX_MINUTES, minute, calendar, CRON_CF_MINUTE, CRON_CF_HOUR_OF_DAY, resets, &res);
    if (0 != res) goto return_result;
    if (minute == update_minute) {
        push_to_fields_arr(resets, CRON_CF_MINUTE);
    } else {
        res = do_prev(expr, calendar, dot);
        if (0 != res) goto return_result;
    }

    hour = calendar->tm_hour;
    update_hour = find_prev(expr->hours, CRON_MAX_HOURS, hour, calendar, CRON_CF_HOUR_OF_DAY, CRON_CF_DAY_OF_WEEK, resets, &res);
    if (0 != res) goto return_result;
    if (hour == update_hour) {
        push_to_fields_arr(resets, CRON_CF_HOUR_OF_DAY);
    } else {
        res = do_prev(expr, calendar, dot);
        if (0 != res) goto return_result;
    }

    day_of_week = calendar->tm_wday;
    day_of_month = calendar->tm_mday;
    update_day_of_month = find_prev_day(calendar, expr->days_of_month, day_of_month, expr->days_of_week, day_of_week, resets, &res);
    if (0 != res) goto return_result;
    if (day_of_month == update_day_of_month) {
        push_to_fields_arr(resets, CRON_CF_DAY_OF_MONTH);
    } else {
        res = do_prev(expr, calendar, dot);
        if (0 != res) goto return_result;
    }

    month = calendar->tm_mon; /*day already adds one if no day in same month is found*/
    update_month = find_prev(expr->months, CRON_MAX_MONTHS, month, calendar, CRON_CF_MONTH, CRON_CF_YEAR, resets, &res);
    if (0 != res) goto return_result;
    if (month != update_month) {
        if (dot - calendar->tm_year > CRON_MAX_YEARS_DIFF) {
            res = -1;
            goto return_result;
        }
        res = do_prev(expr, calendar, dot);
        if (0 != res) goto return_result;
    }
    goto return_result;

    return_result:
    if (!resets || !empty_list) {
        res = -1;
    }
    if (resets) {
        cron_free(resets);
    }
    if (empty_list) {
        cron_free(empty_list);
    }
    return res;
}

time_t cron_prev(cron_expr* expr, time_t date) {
    /*
     The plan:

     1 Round down to a whole second

     2 If seconds match move on, otherwise find the next match:
     2.1 If next match is in the next minute then roll forwards

     3 If minute matches move on, otherwise find the next match
     3.1 If next match is in the next hour then roll forwards
     3.2 Reset the seconds and go to 2

     4 If hour matches move on, otherwise find the next match
     4.1 If next match is in the next day then roll forwards,
     4.2 Reset the minutes and seconds and go to 2

     ...
     */
    if (!expr) return CRON_INVALID_INSTANT;
    struct tm calval;
    memset(&calval, 0, sizeof(struct tm));
    struct tm* calendar = cron_time(&date, &calval);
    if (!calendar) return CRON_INVALID_INSTANT;
    time_t original = cron_mktime(calendar);
    if (CRON_INVALID_INSTANT == original) return CRON_INVALID_INSTANT;

    /* calculate the previous occurrence */
    int res = do_prev(expr, calendar, calendar->tm_year);
    if (0 != res) return CRON_INVALID_INSTANT;

    /* check for a match, try from the next second if one wasn't found */
    time_t calculated = cron_mktime(calendar);
    if (CRON_INVALID_INSTANT == calculated) return CRON_INVALID_INSTANT;
    if (calculated == original) {
        /* We arrived at the original timestamp - round up to the next whole second and try again... */
        res = add_to_field(calendar, CRON_CF_SECOND, -1);
        if (0 != res) return CRON_INVALID_INSTANT;
        res = do_prev(expr, calendar, calendar->tm_year);
        if (0 != res) return CRON_INVALID_INSTANT;
    }

    return cron_mktime(calendar);
}


text:
from google.cloud import datacatalog_v1

def sample_update_policy_tag():
    # Create a client
    client = datacatalog_v1.PolicyTagManagerClient()

    # Initialize request argument(s)
    request = datacatalog_v1.UpdatePolicyTagRequest(
    )

    # Make the request
    response = client.update_policy_tag(request=request)

    # Handle the response
    print(response)

# [END datacatalog_v1_generated_PolicyTagManager_UpdatePolicyTag_sync]

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

RSpec.describe "Hello Gem", type: :feature do
  goal_feature "Authentication", "Sign Out", "Token Expiration" do

    sstory "Various time spans" do
      sscenario "Sustains at 09 minutes" do
        x_minutes_have_passed(9)
        then_I_expect_to_be_signed_in
        Then "and my token expiracy should not be renewed" do
          expect_token_not_to_be_renewed
        end
      end

      sscenario "Renews at 11 minutes" do
        x_minutes_have_passed(11)
        then_I_expect_to_be_signed_in
        Then "and my token expiracy should be renewed" do
          expect_token_to_be_renewed
        end
      end

      sscenario "Expires at 31 minutes" do
        x_minutes_have_passed(31)
        then_I_expect_to_be_signed_out
        Then "and I should be on the root page" do
          expect(current_path).to eq root_path
        end
        Then "and my access token should be removed from the database" do
          expect(User.count).to        eq(1)
          expect(Credential.count).to  eq(1)
          expect(AccessToken.count).to eq(0)
        end
      end
    end

    def x_minutes_have_passed(minutes)
      given_I_have_signed_in
      expect_token_to_be_renewed
      expect(my_token_expiracy).to be < 31.minutes.from_now

      When "#{minutes} minutes have passed" do
        access_token = AccessToken.last
        expires_at = access_token.expires_at - minutes.minutes
        access_token.update_attribute :expires_at, expires_at
        visit root_path
      end
    end

    def my_token_expiracy
      AccessToken.last.expires_at
    end

    def expect_token_to_be_renewed
      expect(my_token_expiracy).to be > 29.minutes.from_now
    end

    def expect_token_not_to_be_renewed
      expect(my_token_expiracy).not_to be > 29.minutes.from_now
    end

  end
end


text:
<?php

// $Id: user_change_email_email.class.php 1571 2009-01-13 13:08:33Z ogrebg $

require_once(DIR_INC.'_sys/site_mailer_advanced.class.php');
require_once(DIR_INC.'modules/mailers_abstract/smtp_settings_loader.class.php');

class User_Change_Email_Email extends Tangra_Class {
	public static function send_confirmation_email(Web_Site_Config $config, Tple $tple,  $code, User_Details $user_details, $new_email) {
		$tple->assign('site_mode', $config->get_site_mode());
		$tple->assign('host', $config->get_current_host());
		$tple->assign('code', urlencode($code));
		$tple->assign('site_name', $config->get_site_name());
		$tple->assign('user_details', $user_details);
		$tple->assign('_language', $config->get_current_language());

		$subject = $tple->fetch('modules/user_registration/mails/change_email_confirm_subject.tpl');
		$body_html = $tple->fetch('modules/user_registration/mails/change_email_confirm_body.tpl');
		$body_text = str_replace('
', "\r\n", $body_html);
		$body_text = str_replace('
', "\r\n", $body_text);
		$body_text = str_replace('
', "\r\n", $body_text);
		$body_text = strip_tags($body_text);

		$smtp_settings = SMTP_Settings_Loader::load_smtp_settings($config->get_conf_dir().'machine_specific.conf');
		$mailer = new Site_Mailer_Advanced($smtp_settings, Mailer_Advanced::MSG_BOTH, $config->get_logs_dir().'mail.log');

		$to_email = compose_email($new_email, $user_details->get_first_name().' '.$user_details->get_last_name());
		$mailer->add_to($to_email);
		$mailer->set_subject($subject);
		$mailer->set_body($body_text);
		$mailer->set_body_html($body_html);

		$config_loader = new Config_Loader_File($config->get_conf_dir().'machine_specific.conf');

		$from_email = compose_email($config_loader->get_conf_value('EMAIL_FROM_ADDRESS'), $config_loader->get_conf_value('EMAIL_FROM_NAME'));

		$mailer->set_from($from_email);

		$ret = $mailer->send();

		if (!$ret) {
			printbr($mailer->get_error_msg());
		}

		return $ret;

	}
}


text:
'use strict';

let pick = require('./pick');

describe('The pick function', () => {

  it('should only keep relevant keys of source object', () => {
    let source = {
      firstName: 'John',
      lastName: 'Doe'
    };

    let picked = pick(source, ['firstName']);

    picked.should.deep.equal({firstName: 'John'});
  });

  it('should even keep deep keys', () => {
    let source = {
      firstName: 'John',
      lastName: 'Doe',
      address: {
        postalCode: '33000',
        city: 'Bordeaux'
      }
    };

    let picked = pick(source, ['firstName', {address: ['city']}]);

    picked.should.deep.equal({firstName: 'John', address: {city: 'Bordeaux'}});
  });

  it('should not add not existing key in source object', () => {
    let source = {
      firstName: 'John',
      address: {
        postalCode: '33000',
        city: 'Bordeaux'
      }
    };

    let picked = pick(source, ['firstName', {address: ['not existing']}, {not: ['existing']}]);

    picked.should.deep.equal({firstName: 'John', address: {}});
  });

  it('should even keep very deep keys', () => {
    let source = {
      a: {
        b: {
          c: {
            d: 'please dont call me again',
            e: 'keep me please'
          }
        }
      }
    };

    let picked = pick(source, [{a: [{b: [{c: ['e']}]}]}]);

    picked.should.deep.equal({a: {b: {c: {e: 'keep me please'}}}});
  });

  it('wont crash like a drunk otter if source object does not have a relevant key', () => {
    let source = {
      firstName: 'John',
      lastName: 'Doe'
    };

    let picked = pick(source, ['firstName', 'birthDate']);

    picked.should.deep.equal({firstName: 'John'});
  });

  it('should lament if keys are not an array', () => {
    let source = {
      address: {
        postalCode: '33000',
        city: 'Bordeaux'
      }
    };

    let invalidPick = () => {
      pick(source, [{address: {city: {code: 'BOR'}}}]);
    };

    invalidPick.should.throw(Error, 'The descriptions should be an array');
  });

  it('should cry if key description as object is invalid', () => {
    let source = {
      address: {
        postalCode: '33000',
        city: 'Bordeaux'
      }
    };

    let invalidPick = () => {
      pick(source, [{address: ['city'], whatAmIDoing: ['here']}]);
    };

    invalidPick.should.throw(Error, 'The description should contain exactly one key');
  });

  it('should die in pain if key description is a primitive like a number', () => {
    let source = {
      firstName: 'John'
    };

    let invalidPick = () => {
      pick(source, [3]);
    };

    invalidPick.should.throw(Error, 'The description should be a string of an object');
  });
});


text:
package jmockmongo;

import org.bson.BSONObject;
import org.bson.BasicBSONObject;

public class Result {

	// ok - true indicates the getLastError command completed successfully. This
	// does NOT indicate there wasn't a last error.
	private final boolean ok;

	private final int n;

	private final String error;

	public Result(int n) {
		ok = true;
		this.n = n;
		this.error = null;
	}

	public Result(String error) {
		ok = true;
		n = 0;
		this.error = error;
	}

	public boolean isOk() {
		return ok;
	}

	public int getN() {
		return n;
	}

	public BSONObject toBSON() {
		BasicBSONObject r = new BasicBSONObject("ok", ok ? 1 : 0)
				.append("n", n);
		if (error != null)
			r.append("err", error);
		return r;
	}

}


text:
'''
Write a Python program using ciscoconfparse that parses the 'cisco_ipsec.txt'
config file. Note, this config file is not fully valid (i.e. parts of the
configuration are missing).
The script should find all of the crypto map entries in the file (lines that
begin with 'crypto map CRYPTO') and print out the children of each crypto map.
'''

from ciscoconfparse import CiscoConfParse

def main():
    '''
    Find all of the crypto map entries in the file (lines that begin with
    'crypto map CRYPTO') and print out the children of each crypto map.
    '''
    cisco_file = 'cisco.txt'

    cisco_cfg = CiscoConfParse(cisco_file)
    crypto_maps = cisco_cfg.find_objects(r"^crypto map CRYPTO")

    for i in crypto_maps:
        print
        print i.text
        for child in i.children:
            print child.text
    print

if __name__ == "__main__":
    main()


text:
package com.kishorebabu.popularmovies;

import android.content.SharedPreferences;
import android.text.TextUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kishorebabu.popularmovies.model.Movie;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MovieSharedPref {
    private static final int PRIVATE_MODE = 0;
    private static final String PREF_NAME = "MovieSharedPref";
    private SharedPreferences pref;

    public MovieSharedPref() {
        pref = PopularMoviesApplication.getAppContext().getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    }

    public void setFavorite(Movie movie) throws JsonProcessingException {
        SharedPreferences.Editor editor = pref.edit();
        ObjectMapper objectMapper = new ObjectMapper();
        String movieJson = objectMapper.writeValueAsString(movie);
        editor.putString(String.valueOf(movie.getId()), movieJson);
        editor.apply();
    }

    public boolean isFavorite(String id) {
        String movieJson = pref.getString(id, null);
        return !TextUtils.isEmpty(movieJson);
    }

    public List<Movie> getFavorites() throws IOException {
        Map<String, ?> allEntries = pref.getAll();
        ArrayList<Movie> movies = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            String movieJson = pref.getString(entry.getKey(), null);

            if (!TextUtils.isEmpty(movieJson)) {
                Movie movie = objectMapper.readValue(movieJson, Movie.class);
                movies.add(movie);
            }
        }
        return movies;
    }

    public void unfavorite(String id) {
        SharedPreferences.Editor editor = pref.edit();
        editor.remove(id);
        editor.apply();
    }
}


text:
package de.craften.plugins.rpgplus.components.trading;

import org.bukkit.entity.Player;

import java.lang.reflect.Method;

public class NMSMerchant implements java.lang.reflect.InvocationHandler {
    private ReflectionUtils.NMSMerchantRecipeList o = new ReflectionUtils.NMSMerchantRecipeList();
    private transient Object c;
    public Object proxy;
    public String title;

    @SuppressWarnings("rawtypes")
    @Override
    public Object invoke(Object proxy, Method m, Object[] args) {
        try {
            if (m == null || m.getName() == null) return null;
            Class entityHuman = ReflectionUtils.getClassByName(ReflectionUtils.getNMSPackageName() + ".EntityHuman");
            if (m.getName().equals("a_") && args.length == 1 && args[0] != null && args[0].getClass().isInstance(entityHuman))
                this.a_(args[0]);
            else if (m.getName().equals("b") || m.getName().equals("m_") || m.getName().equals("u_") || m.getName().equals("v_")) //m_ = 1.6.4, b = 1.7.4, u_ = Spigot 1.8, v_ = Spigot 1.8.3
                return this.getEntityHuman();
            else if (m.getName().equals("getOffers") && args.length == 1)
                return this.getOffers(args[0]);
            else if (m.getName().equals("a") && args.length == 1)
                this.a(args[0]);
            else if (m.getName().equals("getScoreboardDisplayName"))
                return this.getScoreboardDisplayName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object getScoreboardDisplayName() {
        return ReflectionUtils.createNMSTextComponent(this.title);
    }

    public void a_(Object player) {  //Class = EntityHuman
        this.c = player;
    }

    public Object getEntityHuman() { // Return Class = EntityHuman
        return this.c;
    }

    public Object getOffers(Object player) {  //Return Class = MerchantRecipeList, player Class = EntityHuman
        return this.o.getHandle();
    }

    public void a(Object recipe) {  //recipe Class = MerchantRecipe
        this.o.add(new ReflectionUtils.NMSMerchantRecipe(recipe));
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public Player getBukkitEntity() {
        try {
            Class c = ReflectionUtils.getClassByName(ReflectionUtils.getNMSPackageName() + ".EntityHuman");
            Method m = c.getDeclaredMethod("getBukkitEntity");
            m.setAccessible(true);
            return (Player) m.invoke(this.c);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void clearRecipes() {
        this.o.clear();
    }

    public void setRecipes(ReflectionUtils.NMSMerchantRecipeList recipes) {
        this.o = recipes;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public void openTrading(Object player) { //player Class = EntityPlayer
        this.c = player;

        try {
            Class classs = ReflectionUtils.getClassByName(ReflectionUtils.getNMSPackageName() + ".EntityPlayer");
            Method m;
            if (this.getMethodArgs(classs, "openTrade") == 2) {
                // Older than Spigot 1.8 (maybe Bukkit 1.7.10)
                m = classs.getDeclaredMethod("openTrade", ReflectionUtils.getClassByName(ReflectionUtils.getNMSPackageName() + ".IMerchant"), String.class);
                m.setAccessible(true);
                m.invoke(player, this.proxy, this.title);
            } else {
                // Spigot 1.8 and newer
                m = classs.getDeclaredMethod("openTrade", ReflectionUtils.getClassByName(ReflectionUtils.getNMSPackageName() + ".IMerchant"));
                m.setAccessible(true);
                m.invoke(player, this.proxy);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("rawtypes")
    private int getMethodArgs(Class classs, String methodName) {
        for (Method method : classs.getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                return method.getParameterTypes().length;
            }
        }
        return -1;
    }

}


text:
========================================
Using openstack.config in an Application
========================================

Usage
-----

The simplest and least useful thing you can do is:

.. code-block:: python

  python -m openstack.config.loader

Which will print out whatever if finds for your config. If you want to use
it from python, which is much more likely what you want to do, things like:

Get a named cloud.

.. code-block:: python

  import openstack.config

  cloud_region = openstack.config.OpenStackConfig().get_one(
      'internap', region_name='ams01')
  print(cloud_region.name, cloud_region.region, cloud_region.config)

Or, get all of the clouds.

.. code-block:: python

  import openstack.config

  cloud_regions = openstack.config.OpenStackConfig().get_all()
  for cloud_region in cloud_regions:
      print(cloud_region.name, cloud_region.region, cloud_region.config)

argparse
--------

If you're using `openstack.config` from a program that wants to process
command line options, there is a registration function to register the
arguments that both `openstack.config` and keystoneauth know how to deal
with - as well as a consumption argument.

.. code-block:: python

  import argparse

  import openstack

  parser = argparse.ArgumentParser()
  cloud = openstack.connect(options=parser)


text:
<manifest package="ca.allanwang.swiperecyclerview.library">
</manifest>


text:
external help file: Microsoft.Azure.Commands.Websites.dll-Help.xml
ms.assetid: B2FDB54F-0318-4037-BC1D-6113E77DDE7E
online version:
schema: 2.0.0
---

# Get-AzureRmWebAppSlotPublishingProfile

## SYNOPSIS
Gets an Azure Web App slot publishing profile.

## SYNTAX

### S1
```
Get-AzureRmWebAppSlotPublishingProfile [-OutputFile] <String> [[-Format] <String>]
 [-ResourceGroupName] <String> [-Name] <String> [-Slot] <String> [<CommonParameters>]
```

### S2
```
Get-AzureRmWebAppSlotPublishingProfile [-OutputFile] <String> [[-Format] <String>] [-WebApp] <Site>
 [<CommonParameters>]
```

## DESCRIPTION
The **Get-AzureRmWebAppSlotPublishingProfile** cmdlet gets the Web App publishing profile for the specified slot.

## EXAMPLES

### Example 1
```
PS C:\> Get-AzureRmWebAppSlotPublishingProfile -ResourceGroupName "Default-Web-WestUS" -Name "ContosoWebApp" -Slot "slot001" -Format "Ftp" -OutputFile "C:\Users\contoso\outputfile"
```

This command gets the publishing profile in Ftp format for slot Slot001 pertaining to the Web App ContosoWebApp associated with the resource group Default-Web-WestUS
    and stores it in the specified output file.

## PARAMETERS

### -Format
Format

```yaml
Type: String
Parameter Sets: (All)
Aliases:
Accepted values: WebDeploy, FileZilla3, Ftp

Required: False
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
WebApp Name

```yaml
Type: String
Parameter Sets: S1
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -OutputFile
Output File

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceGroupName
Resource Group Name

```yaml
Type: String
Parameter Sets: S1
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Slot
WebApp Slot Name

```yaml
Type: String
Parameter Sets: S1
Aliases:

Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -WebApp
WebApp Object

```yaml
Type: Site
Parameter Sets: S2
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### Site

Parameter 'WebApp' accepts value of type 'Site' from the pipeline

## OUTPUTS

## NOTES

## RELATED LINKS

[Reset-AzureRMWebAppSlotPublishingProfile](./Reset-AzureRmWebAppSlotPublishingProfile.md)

[Get-AzureRMWebAppSlot](./Get-AzureRMWebAppSlot.md)

[Get-AzureRmWebApp](./Get-AzureRmWebApp.md)


text:
__author__ = 'Michael Montero <mcmontero@gmail.com>'

# ----- Imports ---------------------------------------------------------------

from tinyAPI.base.exception import tinyAPIException

__all__ = [
    'SchemaDifferException'
]

# ----- Public Classes --------------------------------------------------------

class SchemaDifferException(tinyAPIException):
    '''Named exception when issues with the Schema Differ arise.'''
    pass


text:
#pragma once

#include <lk/compiler.h>
#include <arch/mips.h>

static inline void arch_enable_ints(void) {
    CF;
#if 0
    uint32_t status = mips_read_c0_status();
    status |= 0x1;
    mips_write_c0_status(status);
#else
    __asm__ volatile("ei");
#endif
}

static inline void arch_disable_ints(void) {
#if 0
    uint32_t status = mips_read_c0_status();
    status &= ~0x1;
    mips_write_c0_status(status);
#else
    __asm__ volatile("di");
#endif
    CF;
}

static inline bool arch_ints_disabled(void) {
    uint32_t state;

    state = mips_read_c0_status();

    return (state & (1<<1)) || !(state & (1<<0)); // check if EXL or IE is set
}

/* use a global pointer to store the current_thread */
extern struct thread *_current_thread;

static inline struct thread *arch_get_current_thread(void) {
    return _current_thread;
}

static inline void arch_set_current_thread(struct thread *t) {
    _current_thread = t;
}

static inline ulong arch_cycle_count(void) { return 0; }

static inline uint arch_curr_cpu_num(void) {
    return 0;
}


text:
[[ "$ANDROID_HOME" == "" ]] && ANDROID_HOME=~/android/system/jellybean
[[ "$PATCHES_LOCATION" == "" ]] && PATCHES_LOCATION=~/android/OpenPDroidPatches
[[ "$PDROID_DIR" == "" ]] && PDROID_DIR=~/android/openpdroid

# If you wish to patch earlier Android versions, pass the matching branch of the OpenPDroidPatches as param.
BRANCH=4.4

LOG="$PDROID_DIR"/OpDPatch.log

# This LOCK file is used by various scripts to determine if the patches are applied to the source code
LOCK="$PDROID_DIR"/.pdroid-lock

print_error() {
     echo ""
     echo "!!! error: $@"
     echo ""
     echo "At least one patch failed to apply! You can see the problem below and in $LOG"
     echo ""
     grep FAILED "$PDROID_DIR"/"$DIR".log
     echo ""
     echo "Failures are often just import statements which are easy to resolve manually."
     echo "If there is only one or two, I recommend you take a peek at the .rej file."
     echo ""
}

patch_error() {
     echo ""
     echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
     echo "!!! error: $@"
     echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
     echo ""
     exit
}

if [ $# -gt 0 ]; then
     BRANCH=$1
elif [ $# -gt 1 ]; then
     patch_error "Only the OpenPDroidPatches branch name is accepted as a parameter!"
fi

AVAILABLE_BRANCHES=( 4.4 4.3 4.2.x 4.1.2-aosp 4.1.2-cm 4.1.1-aosp 4.1.1-cm 4.0.4-aosp 4.0.4-cm 2.3 )
VALID_BRANCH=false
for a in ${AVAILABLE_BRANCHES[@]}; do
     if [[ "$a" == $BRANCH ]]; then
          VALID_BRANCH=true
     fi
done

if [[ ! "$VALID_BRANCH" == true ]]; then
     patch_error "$BRANCH is not a valid branch! Check OpenPDroidPatch branch names for valid parameters!"
fi

if [ -f "$LOCK" ]; then
    echo ""
    echo "OpenPDroid patches are already applied."
    echo "   removePdroid.sh should be ran to remove the lock at $LOCK"
    echo ""
    exit
fi

cd "$PATCHES_LOCATION"
( git checkout "$BRANCH" || git checkout -t origin/"$BRANCH" ) || patch_error "Could not checkout the branch you designated, double-check location and branch!"

# We now wipe old logs here
echo "Patching with OpenPDroidPatches branch: $BRANCH" > "$LOG"
echo "" >> "$LOG"

# This could be significantly refactored. Lets wait until chen is succesful before we pull the rug, OK?
DIRECTORIES_TO_PATCH=( build libcore frameworks_base packages_apps_Mms frameworks_opt_telephony )

cd "$ANDROID_HOME"/build; git checkout -b pdroid; patch -p1 < "$PATCHES_LOCATION"/openpdroid_"$BRANCH"_build.patch >> "$PDROID_DIR"/${DIRECTORIES_TO_PATCH[0]}.log 2>&1
cd "$ANDROID_HOME"/libcore; git checkout -b pdroid; patch -p1 < "$PATCHES_LOCATION"/openpdroid_"$BRANCH"_libcore.patch >> "$PDROID_DIR"/${DIRECTORIES_TO_PATCH[1]}.log 2>&1
cd "$ANDROID_HOME"/frameworks/base; git checkout -b pdroid; patch -p1 < "$PATCHES_LOCATION"/openpdroid_"$BRANCH"_frameworks_base.patch >> "$PDROID_DIR"/${DIRECTORIES_TO_PATCH[2]}.log 2>&1

# Mms patch introduced in 4.1
if [ -f $PATCHES_LOCATION/*"$BRANCH"*packages_apps_Mms*h ]; then
     cd "$ANDROID_HOME"/packages/apps/Mms; git checkout -b pdroid; patch -p1 < "$PATCHES_LOCATION"/openpdroid_"$BRANCH"_packages_apps_Mms.patch >> "$PDROID_DIR"/${DIRECTORIES_TO_PATCH[3]}.log 2>&1
else
     DIRECTORIES_TO_PATCH=( ${DIRECTORIES_TO_PATCH[@]//packages_apps_Mms} )
fi

# Telephony-common introduced in 4.2
if [ -f $PATCHES_LOCATION/*"$BRANCH"*frameworks_opt_telephony*h ]; then
     cd "$ANDROID_HOME"/frameworks/opt/telephony; git checkout -b pdroid; patch -p1 < "$PATCHES_LOCATION"/openpdroid_"$BRANCH"_frameworks_opt_telephony.patch >> "$PDROID_DIR"/${DIRECTORIES_TO_PATCH[4]}.log 2>&1
else
     DIRECTORIES_TO_PATCH=( ${DIRECTORIES_TO_PATCH[@]//frameworks_opt_telephony} )
fi

#TODO Perhaps grep failures & attach it  or create a failures.log. It is useful when resolving patch errors
echo ""
for DIR in ${DIRECTORIES_TO_PATCH[@]}; do
     ( [[ $(grep FAILED "$PDROID_DIR"/"$DIR".log) != "" ]] && print_error "Failure in $DIR!" ) || echo "Patched $DIR succesfully"
     [[ $(grep "Skip this patch?" "$PDROID_DIR"/"$DIR".log) != "" ]] && print_error "Files not found! Examine ${PDROID_DIR}/${LOG} because it is very likely you are using the wrong branch!"
     echo "" >> "$LOG"
     echo "Log for $DIR:" >> "$LOG"
     echo "" >> "$LOG"
     cat "$PDROID_DIR"/"$DIR".log >> "$LOG"
     rm "$PDROID_DIR"/"$DIR".log
done
echo ""
cd "$ANDROID_HOME"; . build/envsetup.sh

# use $LOCK to pass API to decompiler
case $(echo $BRANCH) in
2.3*)
     API=10
     ;;
4.0*)
     API=15
     ;;
4.1*)
     API=16
     ;;
4.2*)
     API=17
     ;;
4.3*)
     API=18
     ;;
4.4*)
     API=19
     ;;
esac

if [ -n "$API" ]; then
     echo -n $API > $LOCK
else
     touch "$LOCK"
     patch_error "API level could not be determined!! There was a problem!"
fi


text:
namespace rmw_fastrtps_cpp
{

rmw_publisher_t *
create_publisher(
  const CustomParticipantInfo * participant_info,
  const rosidl_message_type_support_t * type_supports,
  const char * topic_name,
  const rmw_qos_profile_t * qos_policies,
  const rmw_publisher_options_t * publisher_options,
  bool keyed,
  bool create_publisher_listener);
}  // namespace rmw_fastrtps_cpp

#endif  // RMW_FASTRTPS_CPP__PUBLISHER_HPP_


text:
    {{'dashboard.popular_app.super_app'}}

{{'dashboard.popular_app.most_popular_app'}}

    175$

{{'dashboard.popular_app.total_visits'}}

47,512

{{'dashboard.popular_app.new_visits'}}

9,217

{{'dashboard.popular_app.sales'}}

2,928


text:
require_relative 'distribution'
require_relative 'conversion'
require_relative 'detection'

require_relative 'parallel_support'

module EncodingEstimator

  # Represent a function the maps a value between min and max to 0..1
  class RangeScale

    # Initialize a new object from the range minimum and maximum
    #
    # @param [Float] min The range's minimum
    # @param [Float] max The range's maximum
    def initialize( min, max )
      @min = min
      @max = max

      if max == min
        @min = min - 1.0
      end
    end

    # Map the given value to a range between 0 and 1 (min is 0, max is 1)
    #
    # @param [Float] value Value to map between 0 and 1
    #
    # @return [Float] The mapped value between 0 and 1
    def scale( value )
      ( value - @min ) / ( @max - @min )
    end
  end

  # Conversion Distribution Combination Representation
  class CDCombination
    attr_reader :conversion, :distribution

    # Initialize a new object from a conversion and a distribution
    #
    # @param [EncodingEstimator::Conversion]   conversion   Conversion to represent
    # @param [EncodingEstimator::Distribution] distribution Distribution to represent
    def initialize( conversion, distribution )
      @conversion   = conversion
      @distribution = distribution
    end
  end

  # Class to store a detection score of a single combination of a conversion and its evaluation score
  class SingleDetectionResult
    attr_reader :key, :score

    # Initialize a new object from a conversion identifier key and a score
    #
    # @param [String] key   Conversion identifier key
    # @param [Float]  score Scoring value for a combination of distribution and a conversion
    def initialize( key, score )
      @key   = key
      @score = score
    end
  end

  # Class to perform an encoding detection on strings
  class Detector
    attr_reader :conversions
    attr_reader :languages
    attr_reader :num_processes
    attr_reader :penalty

    # Create a new instance with a given configuration consisting of a list of conversions, languages and the number
    # of processes.
    #
    # @param [Array<EncodingEstimator::Conversion>]    conversions   Conversions to perform/test on the inputs.
    # @param [Array<EncodingEstimator::LanguageModel>] languages     Languages to consider when evaluating the input. Array
    #                                                                of two-letter-codes
    # @param [Float]                                   penalty       Base penalty subtracted from each char's score
    # @param [Integer]                                 num_processes Number of processes the detection will run on  -> true
    #                                                                multi-threading through the parallel gem
    def initialize( conversions, languages, penalty = 0.01, num_processes = nil )
      @conversions   = conversions
      @languages     = languages
      @num_processes = num_processes
      @penalty       = penalty
    end

    # Detect the encoding using the current configuration given an input string
    #
    # @param [String] str Input string the detection will be performed on
    #
    # @return [EncodingEstimator::Detection] Result of the detection process
    def detect( str )
      sums    = {}
      results = (num_processes.nil? or !EncodingEstimator::ParallelSupport.supported?) ?
                    detect_st( str, combinations ) : detect_mt( str, combinations )

      results.each do |result|
        sums[result.key] = sums.fetch(result.key, 0.0) + result.score
      end

      range = EncodingEstimator::RangeScale.new( sums.values.min, sums.values.max )

      scaled_scores = {}
      sums.each do |k,s|
        scaled_scores[ k ] = range.scale s
      end

      EncodingEstimator::Detection.new( scaled_scores, @conversions )
    end

    private

    # Compute the scores of all combinations of languages and conversions on a single thread.
    #
    # @param [String]      str    Input string to compute the encoding on
    # @param [Array<Hash>] matrix List of Conversion-Distribution-Combinations
    #
    # @return [Array<Hash>] Hash with the keys "key" and "score": key is the key of the conversion, score the result of
    #                       the evaluation for the input string
    def detect_st( str, matrix )
      matrix.map do |combination|
        detect_single str, combination
      end
    end

    # Compute the scores of all combinations of languages and conversions on multiple processes. See num_processes.
    #
    # @param [String]      str    Input string to compute the encoding on
    # @param [Array<Hash>] matrix List of Conversion-Distribution-Combinations
    #
    # @return [Array<Hash>] Hash with the keys "key" and "score": key is the key of the conversion, score the result of
    #                       the evaluation for the input string
    def detect_mt( str, matrix )
      Parallel.map( matrix, in_processes: num_processes ) do |combination|
        detect_single str, combination
      end
    end

    # Calculate the list of all combinations of languages and conversions
    #
    # @return [Array<EncodingEstimator::CDCombination>] Conversion-Distribution-Combinations of the current config
    def combinations
      @languages.map {
          |l| @conversions.map { |c| EncodingEstimator::CDCombination.new( c, l.distribution ) }
      }.flatten
    end

    # Perform the evaluation of a Conversion-Distribution-Combination on an input string
    #
    # @param [String]                           str         Input to evaluate
    # @param [EncodingEstimator::CDCombination] combination Distribution/Conversion to evaluate on the input
    #
    # @return [EncodingEstimator::SingleDetectionResult] Result of the evaluation of the given combination on the input
    def detect_single( str, combination )
      EncodingEstimator::SingleDetectionResult.new(
          combination.conversion.key,
          combination.distribution.evaluate( combination.conversion.perform(str), @penalty )
      )
    end

  end
end


text:
package org.hibernate.event.spi;

import org.hibernate.collection.spi.PersistentCollection;

/**
 * An event that occurs when a collection wants to be
 * initialized
 *
 * @author Gavin King
 */
public class InitializeCollectionEvent extends AbstractCollectionEvent {
	public InitializeCollectionEvent(PersistentCollection collection, EventSource source ) {
		super( getLoadedCollectionPersister( collection, source ),
				collection,
				source,
				getLoadedOwnerOrNull( collection, source ),
				getLoadedOwnerIdOrNull( collection, source ) );
	}
}


text:
"""
Tests for the twistedcaldav.client module.
"""


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */

namespace Piwik\Updates;

use Piwik\Common;
use Piwik\SettingsServer;
use Piwik\Updater;
use Piwik\Updates;
use Piwik\Updater\Migration\Factory as MigrationFactory;

/**
 */
class Updates_0_9_1 extends Updates
{
    /**
     * @var MigrationFactory
     */
    private $migration;

    public function __construct(MigrationFactory $factory)
    {
        $this->migration = $factory;
    }

    public function getMigrations(Updater $updater)
    {
        if (!SettingsServer::isTimezoneSupportEnabled()) {
            return array();
        }
        // @see http://bugs.php.net/46111
        $timezones = timezone_identifiers_list();
        $brokenTZ = array();

        foreach ($timezones as $timezone) {
            $testDate = "2008-08-19 13:00:00 " . $timezone;

            if (!strtotime($testDate)) {
                $brokenTZ[] = $timezone;
            }
        }
        $timezoneList = '"' . implode('","', $brokenTZ) . '"';

        return array(
            $this->migration->db->sql(
                'UPDATE ' . Common::prefixTable('site') . '
                 SET timezone = "UTC" WHERE timezone IN (' . $timezoneList . ')'),

            $this->migration->db->sql(
                'UPDATE `' . Common::prefixTable('option') . '`
                 SET option_value = "UTC" WHERE option_name = "SitesManager_DefaultTimezone" AND option_value IN (' . $timezoneList . ')'),
        );
    }

    public function doUpdate(Updater $updater)
    {
        if (SettingsServer::isTimezoneSupportEnabled()) {
            $updater->executeMigrations(__FILE__, $this->getMigrations($updater));
        }
    }
}


text:
package com.benberi.cadesim.server.codec.packet.in;

import com.benberi.cadesim.server.ServerContext;
import com.benberi.cadesim.server.codec.util.Packet;
import com.benberi.cadesim.server.model.player.Player;
import com.benberi.cadesim.server.model.player.vessel.Vessel;
import com.benberi.cadesim.server.codec.packet.ServerPacketExecutor;

public class ManuaverSlotChanged extends ServerPacketExecutor {

    public ManuaverSlotChanged(ServerContext ctx) {
        super(ctx);
    }

    @Override
    public void execute(Player pl, Packet p) {
        int newSlot = p.readByte();
        Vessel v = pl.getVessel();
        if (v.isManuaver()) {
            pl.getMoves().setManuaverSlot(newSlot);
        }
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>qqzq</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring/application-*.xml</param-value>
	</context-param>

	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>cn.com.qqzq</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/application-web.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet>
		<servlet-name>JerseyServlet</servlet-name>
		<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
		<init-param>
			<param-name>com.sun.jersey.config.property.packages</param-name>
			<param-value>cn.com.qqzq.rest.resource;com.wordnik.swagger.jersey.listing</param-value>
		</init-param>
		<init-param>
			<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
			<param-value>true</param-value>
		</init-param>
	</servlet>

	<servlet>
		<servlet-name>JerseyJaxrsConfig</servlet-name>
		<servlet-class>com.wordnik.swagger.jersey.config.JerseyJaxrsConfig</servlet-class>
		<init-param>
			<param-name>api.version</param-name>
			<param-value>1.0.0</param-value>
		</init-param>
		<init-param>
			<param-name>swagger.api.basepath</param-name>
			<param-value>http://localhost:8080/qqzq/rest</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet>
		<servlet-name>kaptcha</servlet-name>
		<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/api/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>JerseyServlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>kaptcha</servlet-name>
		<url-pattern>/img/kaptcha.jpg</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


text:
package com.logginghub.logging.modules.web;

import com.logginghub.analytics.ChartBuilder;
import com.logginghub.analytics.model.TimeSeriesDataContainer;
import com.logginghub.analytics.utils.TimeBucketCounter;
import com.logginghub.utils.FileUtils;
import com.logginghub.utils.Out;
import com.logginghub.utils.StringUtils;
import com.logginghub.utils.Visitor;
import com.logginghub.utils.logging.Logger;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by james on 12/05/2015.
 */
public class RailsLogReader {

    public static void main(String[] args) throws IOException, ParseException {

       final TimeBucketCounter histogram = new TimeBucketCounter(60000);

        final long start = parseTime("2015-05-06 00:00:00 +0100");
        final long end = parseTime("2015-05-06 12:00:00 +0100");

        final BufferedWriter writer = new BufferedWriter(new FileWriter("/Users/james/development/divmax/logs/production.log.txt"));
        RailsLogReader reader = new RailsLogReader();
        reader.read(new File("/Users/james/development/divmax/logs/production.log"), new Visitor<Entry>() {
            @Override
            public void visit(Entry i) {
                if (i.time > start && i.time < end) {
                    histogram.count(i.time, "Request", 1);
                }
                try {
                    writer.write(i.toString());
                    writer.newLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        writer.close();

        TimeSeriesDataContainer timeSeriesDataContainer = histogram.extractAllSeries();
        ChartBuilder.start(ChartBuilder.Type.XY)
                    .addSeries(timeSeriesDataContainer, 42)
                    .setTitle("Frequency of messages")
                    .toPng(new File("chart.png"));
    }

    class Entry {
        String method;
        String url;
        String ip;
        long time;
        double duration;
        String codeNumber;
        String statusText;

        @Override
        public String toString() {
            return String.format("%20s %20s %20s %10s %20s %10.2f ms %150s",
                                 Logger.toLocalDateString(time),
                                 method,
                                 ip,
                                 codeNumber,
                                 statusText,
                                 duration,
                                 url);
        }
    }

    public void read(File file, Visitor<Entry> visitor) throws IOException, ParseException {

        Out.out("Reading file '{}'", file.getAbsolutePath());

        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        int index = 0;

        Entry entry = null;

        while ((line = reader.readLine()) != null) {
            //            System.out.println(line);

            if (line.startsWith("Started ")) {
                String[] split = line.split(" ");

                if (entry != null) {
                    System.err.println("Rejecting unfulfilled request");
                }

                entry = new Entry();
                entry.method = split[1];
                entry.url = StringUtils.unquote(split[2]);
                entry.ip = split[4];

                String timeString = split[6];
                timeString += " " + split[7];
                timeString += " " + split[8];

                long parsed = parseTime(timeString);
                String formatted = Logger.toLocalDateString(parsed).toString();

                entry.time = parsed;

                //                System.out.println(">>>> " + line);

            } else if (line.startsWith("Completed ")) {

                if (entry == null) {
                    System.err.println("Entry is currently null - did we start the log halfway through an entry?");
                } else {
                    String[] split = line.split(" ");
                    entry.codeNumber = split[1];
                    entry.statusText = split[2];

                    // Need to do a search for the time
                    int searchIndex = 3;
                    for (; searchIndex < split.length; searchIndex++) {
                        if (split[searchIndex].equals("in")) {
                            break;
                        }
                    }

                    entry.duration = Double.parseDouble(StringUtils.before(split[searchIndex + 1], "ms"));

                    visitor.visit(entry);
                    entry = null;
                }

                //                System.out.println("<<<< " + line);

            } else {
                //System.out.println(line);
            }

            index++;

        }

        FileUtils.closeQuietly(reader);

    }

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

    private static long parseTime(String timeString) throws ParseException {
        return dateFormat.parse(timeString).getTime();
    }

}


text:
package org.apache.hadoop.mapreduce.v2.app.webapp;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.v2.api.records.JobId;
import org.apache.hadoop.mapreduce.v2.api.records.TaskId;
import org.apache.hadoop.mapreduce.v2.api.records.TaskReport;
import org.apache.hadoop.mapreduce.v2.api.records.TaskState;
import org.apache.hadoop.mapreduce.v2.api.records.TaskType;
import org.apache.hadoop.mapreduce.v2.api.records.impl.pb.JobIdPBImpl;
import org.apache.hadoop.mapreduce.v2.api.records.impl.pb.TaskIdPBImpl;
import org.apache.hadoop.mapreduce.v2.app.AppContext;
import org.apache.hadoop.mapreduce.v2.app.job.Job;
import org.apache.hadoop.mapreduce.v2.app.job.Task;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationIdPBImpl;
import org.apache.hadoop.yarn.webapp.view.BlockForTest;
import org.apache.hadoop.yarn.webapp.view.HtmlBlock;
import org.apache.hadoop.yarn.webapp.view.HtmlBlock.Block;

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class TestBlocks {
  private ByteArrayOutputStream data = new ByteArrayOutputStream();

  /**
   * Test rendering for ConfBlock
   */
  @Test
  public void testConfigurationBlock() throws Exception {
    AppContext ctx = mock(AppContext.class);
    Job job = mock(Job.class);
    Path path = new Path("conf");
    Configuration configuration = new Configuration();
    configuration.set("Key for test", "Value for test");
    when(job.getConfFile()).thenReturn(path);
    when(job.loadConfFile()).thenReturn(configuration);

    when(ctx.getJob(any(JobId.class))).thenReturn(job);

    ConfBlockForTest configurationBlock = new ConfBlockForTest(ctx);
    PrintWriter pWriter = new PrintWriter(data);
    Block html = new BlockForTest(new HtmlBlockForTest(), pWriter, 0, false);

    configurationBlock.render(html);
    pWriter.flush();
    assertTrue(data.toString().contains(
            "Sorry, can't do anything without a JobID"));

    configurationBlock.addParameter(AMParams.JOB_ID, "job_01_01");
    data.reset();
    configurationBlock.render(html);
    pWriter.flush();
    assertTrue(data.toString().contains("Key for test"));

    assertTrue(data.toString().contains("Value for test"));

  }

  /**
   * Test rendering for TasksBlock
   */
  @Test
  public void testTasksBlock() throws Exception {

    ApplicationId appId = ApplicationIdPBImpl.newInstance(0, 1);
    JobId jobId = new JobIdPBImpl();
    jobId.setId(0);
    jobId.setAppId(appId);

    TaskId taskId = new TaskIdPBImpl();
    taskId.setId(0);
    taskId.setTaskType(TaskType.MAP);
    taskId.setJobId(jobId);
    Task task = mock(Task.class);
    when(task.getID()).thenReturn(taskId);
    TaskReport report = mock(TaskReport.class);
    when(report.getProgress()).thenReturn(0.7f);
    when(report.getTaskState()).thenReturn(TaskState.SUCCEEDED);
    when(report.getStartTime()).thenReturn(100001L);
    when(report.getFinishTime()).thenReturn(100011L);

    when(task.getReport()).thenReturn(report);
    when(task.getType()).thenReturn(TaskType.MAP);

    Map<TaskId, Task> tasks = new HashMap<TaskId, Task>();
    tasks.put(taskId, task);
    AppContext ctx = mock(AppContext.class);
    Job job = mock(Job.class);
    when(job.getTasks()).thenReturn(tasks);

    App app = new App(ctx);
    app.setJob(job);
    TasksBlockForTest taskBlock = new TasksBlockForTest(app);
    taskBlock.addParameter(AMParams.TASK_TYPE, "m");

    PrintWriter pWriter = new PrintWriter(data);
    Block html = new BlockForTest(new HtmlBlockForTest(), pWriter, 0, false);

    taskBlock.render(html);
    pWriter.flush();
    assertTrue(data.toString().contains("task_0_0001_m_000000"));
    assertTrue(data.toString().contains("70.00"));
    assertTrue(data.toString().contains("SUCCEEDED"));
    assertTrue(data.toString().contains("100001"));
    assertTrue(data.toString().contains("100011"));

  }

  private class ConfBlockForTest extends ConfBlock {
    private final Map<String, String> params = new HashMap<String, String>();

    public void addParameter(String name, String value) {
      params.put(name, value);
    }

    @Override
    public String $(String key, String defaultValue) {
      String value = params.get(key);
      return value == null ? defaultValue : value;
    }

    ConfBlockForTest(AppContext appCtx) {
      super(appCtx);
    }

  }

  private class HtmlBlockForTest extends HtmlBlock {

    @Override
    protected void render(Block html) {

    }
  }

}


text:
class CreateSections < ActiveRecord::Migration
  def up
    create_table :sections do |t|
      t.string "name"
      t.integer "position"
      t.boolean "visible", :default => false
      t.timestamps
    end
  end

  def down
  	drop_table :sections
  end
end


text:
package com.scwang.smartrefresh.header;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshKernel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.util.DensityUtil;

/**
 * CircleRefresh
 * https://github.com/tuesda/CircleRefreshLayout
 * Created by zhanglei on 15/7/18.
 */
public class CircleHeader extends View implements RefreshHeader {

    //<editor-fold desc="Field">

    private static final int DURATION_FINISH = 800; //动画时长

    private Path mPath;
    private Paint mBackPaint;
    private Paint mFrontPaint;
    private Paint mOuterPaint;
    private float mWaveHeight;
    private float mHeadHeight;
    private float mSpringRatio;
    private float mFinishRatio;

    private RefreshState mState;
    private float mBollY;//弹出球体的Y坐标
    private boolean mShowBoll;//是否显示中心球体
    private boolean mShowBollTail;//是否显示球体拖拽的尾巴
    private boolean mShowOuter;
    private float mBollRadius;//球体半径

    private int mRefreshStop = 90;
    private int mRefreshStart = 90;
    private boolean mOuterIsStart = true;

    private static final int TARGET_DEGREE = 270;

    //</editor-fold>

    //<editor-fold desc="View">

    public CircleHeader(Context context) {
        super(context, null, 0);
        initView(context, null);
    }

    public CircleHeader(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        initView(context, attrs);
    }

    public CircleHeader(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public CircleHeader(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        setMinimumHeight(DensityUtil.dp2px(100));
        mBackPaint = new Paint();
        mBackPaint.setColor(0xff11bbff);
        mBackPaint.setAntiAlias(true);
        mFrontPaint = new Paint();
        mFrontPaint.setColor(0xffffffff);
        mFrontPaint.setAntiAlias(true);
        mOuterPaint = new Paint();
        mOuterPaint.setAntiAlias(true);
        mOuterPaint.setColor(0xffffffff);
        mOuterPaint.setStyle(Paint.Style.STROKE);
        mOuterPaint.setStrokeWidth(DensityUtil.dp2px(2f));
        mPath = new Path();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

    //</editor-fold>

    //<editor-fold desc="Draw">
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isInEditMode()) {
            mShowBoll = true;
            mShowOuter = true;
            mHeadHeight = getHeight();
            mRefreshStop = 270;
            mBollY = mHeadHeight / 2;
            mBollRadius = mHeadHeight / 6;
        }

        int viewWidth = getWidth();
        int viewHeight = getHeight();
        drawWave(canvas, viewWidth, viewHeight);
        drawSpringUp(canvas, viewWidth);
        drawBoll(canvas, viewWidth);
        drawOuter(canvas, viewWidth);
        drawFinish(canvas, viewWidth);
    }

    private void drawWave(Canvas canvas, int viewWidth, int viewHeight) {
        float baseHeight = Math.min(mHeadHeight, viewHeight);
        if (mWaveHeight != 0) {
            mPath.reset();
            mPath.lineTo(viewWidth, 0);
            mPath.lineTo(viewWidth, baseHeight);
            mPath.quadTo(viewWidth / 2, baseHeight + mWaveHeight * 2, 0, baseHeight);
            mPath.close();
            canvas.drawPath(mPath, mBackPaint);
        } else {
            canvas.drawRect(0, 0, viewWidth, baseHeight, mBackPaint);
        }
    }

    private void drawSpringUp(Canvas canvas, int viewWidth) {
        if (mSpringRatio > 0) {
            float leftX = (viewWidth / 2 - 4 * mBollRadius + mSpringRatio * 3 * mBollRadius);
            if (mSpringRatio < 0.9) {
                mPath.reset();
                mPath.moveTo(leftX, mBollY);
                mPath.quadTo(viewWidth / 2, mBollY - mBollRadius * mSpringRatio * 2,
                        viewWidth - leftX, mBollY);
                canvas.drawPath(mPath, mFrontPaint);
            } else {
                canvas.drawCircle(viewWidth / 2, mBollY, mBollRadius, mFrontPaint);
            }
        }
    }

    private void drawBoll(Canvas canvas, int viewWidth) {
        if (mShowBoll) {
            canvas.drawCircle(viewWidth / 2, mBollY, mBollRadius, mFrontPaint);

            drawBollTail(canvas, viewWidth, (mHeadHeight + mWaveHeight) / mHeadHeight);
        }
    }

    private void drawBollTail(Canvas canvas, int viewWidth, float fraction) {
        if (mShowBollTail) {
            final float bottom = mHeadHeight + mWaveHeight;
            final float starty = mBollY + mBollRadius * fraction / 2;
            final float startx = viewWidth / 2 + (float) Math.sqrt(mBollRadius * mBollRadius * (1 - fraction * fraction / 4));
            final float bezier1x = (viewWidth / 2 + (mBollRadius * 3 / 4) * (1 - fraction));
            final float bezier2x = bezier1x + mBollRadius;

            mPath.reset();
            mPath.moveTo(startx, starty);
            mPath.quadTo(bezier1x, bottom, bezier2x, bottom);
            mPath.lineTo(viewWidth - bezier2x, bottom);
            mPath.quadTo(viewWidth - bezier1x, bottom, viewWidth - startx, starty);
            canvas.drawPath(mPath, mFrontPaint);
        }
    }

    private void drawOuter(Canvas canvas, int viewWidth) {
        if (mShowOuter) {
            float outerR = mBollRadius + mOuterPaint.getStrokeWidth() * 2;

            mRefreshStart += mOuterIsStart ? 3 : 10;
            mRefreshStop += mOuterIsStart ? 10 : 3;
            mRefreshStart = mRefreshStart % 360;
            mRefreshStop = mRefreshStop % 360;

            int swipe = mRefreshStop - mRefreshStart;
            swipe = swipe < 0 ? swipe + 360 : swipe;

            canvas.drawArc(new RectF(viewWidth / 2 - outerR, mBollY - outerR, viewWidth / 2 + outerR, mBollY + outerR),
                    mRefreshStart, swipe, false, mOuterPaint);
            if (swipe >= TARGET_DEGREE) {
                mOuterIsStart = false;
            } else if (swipe <= 10) {
                mOuterIsStart = true;
            }
            invalidate();
        }

    }

    private void drawFinish(Canvas canvas, int viewWidth) {
        if (mFinishRatio > 0) {
            int beforeColor = mOuterPaint.getColor();
            if (mFinishRatio < 0.3) {
                canvas.drawCircle(viewWidth / 2, mBollY, mBollRadius, mFrontPaint);
                int outerR = (int) (mBollRadius + mOuterPaint.getStrokeWidth() * 2 * (1+mFinishRatio / 0.3f));
                int afterColor = Color.argb((int) (0xff * (1 - mFinishRatio / 0.3f)), Color.red(beforeColor),
                        Color.green(beforeColor), Color.blue(beforeColor));
                mOuterPaint.setColor(afterColor);
                canvas.drawArc(new RectF(viewWidth / 2 - outerR, mBollY - outerR, viewWidth / 2 + outerR, mBollY + outerR),
                        0, 360, false, mOuterPaint);
            }
            mOuterPaint.setColor(beforeColor);

            if (mFinishRatio >= 0.3 && mFinishRatio < 0.7) {
                float fraction = (mFinishRatio - 0.3f) / 0.4f;
                mBollY = (int) (mHeadHeight / 2 + (mHeadHeight - mHeadHeight / 2) * fraction);
                canvas.drawCircle(viewWidth / 2, mBollY, mBollRadius, mFrontPaint);
                if (mBollY >= mHeadHeight - mBollRadius * 2) {
                    mShowBollTail = true;
                    drawBollTail(canvas, viewWidth, fraction);
                }
                mShowBollTail = false;
            }

            if (mFinishRatio >= 0.7 && mFinishRatio <= 1) {
                float fraction = (mFinishRatio - 0.7f) / 0.3f;
                int leftX = (int) (viewWidth / 2 - mBollRadius - 2 * mBollRadius * fraction);
                mPath.reset();
                mPath.moveTo(leftX, mHeadHeight);
                mPath.quadTo(viewWidth / 2, mHeadHeight - (mBollRadius * (1 - fraction)),
                        viewWidth - leftX, mHeadHeight);
                canvas.drawPath(mPath, mFrontPaint);
            }
        }
    }

    //</editor-fold>

    //<editor-fold desc="RefreshHeader">

    @Override
    public void onInitialized(RefreshKernel kernel, int height, int extendHeight) {
    }

    @Override
    public boolean isSupportHorizontalDrag() {
        return false;
    }

    @Override
    public void onHorizontalDrag(float percentX, int offsetX, int offsetMax) {
    }

    @Override
    public void onPullingDown(float percent, int offset, int headerHeight, int extendHeight) {
        mHeadHeight = headerHeight;
        mWaveHeight = Math.max(offset - headerHeight, 0) * .8f;
    }

    @Override
    public void onRefreshReleased(RefreshLayout layout, int headerHeight, int extendHeight) {
        mHeadHeight = headerHeight;
        mBollRadius = headerHeight / 6;
        DecelerateInterpolator interpolator = new DecelerateInterpolator();
        final float reboundHeight = Math.min(mWaveHeight * 0.8f, mHeadHeight / 2);
        ValueAnimator waveAnimator = ValueAnimator.ofFloat(
                mWaveHeight, 0,
                -(reboundHeight*1.0f),0,
                -(reboundHeight*0.4f),0
        );
        waveAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            float speed = 0;
            float springBollY;
            float springRatio = 0;
            int springstatus = 0;//0 还没开始弹起 1 向上弹起 2 在弹起的最高点停住
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float curValue = (float) animation.getAnimatedValue();
                if (springstatus == 0 && curValue <= 0) {
                    springstatus = 1;
                    speed = Math.abs(curValue - mWaveHeight);
                }
                if (springstatus == 1) {
                    springRatio = -curValue / reboundHeight;
                    if (springRatio >= mSpringRatio) {
                        mSpringRatio = springRatio;
                        mBollY = mHeadHeight + curValue;
                        speed = Math.abs(curValue - mWaveHeight);
                    } else {
                        springstatus = 2;
                        mSpringRatio = 0;
                        mShowBoll = true;
                        mShowBollTail = true;
                        springBollY = mBollY;
                    }
                }
                if (springstatus == 2) {
                    if (mBollY > mHeadHeight / 2) {
                        mBollY = Math.max(mHeadHeight / 2, mBollY - speed);
                        float bolly = animation.getAnimatedFraction() * (mHeadHeight / 2 - springBollY) + springBollY;
                        if (mBollY > bolly) {
                            mBollY = bolly;
                        }
                    }
                }
                if (mShowBollTail && curValue < mWaveHeight) {
                    mShowOuter = true;
                    mShowBollTail = false;
                    mOuterIsStart = true;
                    mRefreshStart = 90;
                    mRefreshStop = 90;
                }
                mWaveHeight = curValue;
                CircleHeader.this.invalidate();
            }
        });
        waveAnimator.setInterpolator(interpolator);
        waveAnimator.setDuration(1000);
        waveAnimator.start();
    }

    @Override
    public void onReleasing(float percent, int offset, int headerHeight, int extendHeight) {
        if (mState != RefreshState.Refreshing && mState != RefreshState.RefreshReleased) {
            onPullingDown(percent, offset, headerHeight, extendHeight);
        }
    }

    @Override
    public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {
        mState = newState;
    }

    @Override
    public void onStartAnimator(RefreshLayout layout, int headerHeight, int extendHeight) {
    }

    @Override
    public int onFinish(RefreshLayout layout, boolean success) {
        mShowOuter = false;
        mShowBoll = false;
        ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mFinishRatio = (float) animation.getAnimatedValue();
                CircleHeader.this.invalidate();
            }
        });
        animator.setInterpolator(new AccelerateInterpolator());
        animator.setDuration(DURATION_FINISH);
        animator.start();
        return DURATION_FINISH;
    }

    @Override@Deprecated
    public void setPrimaryColors(@ColorInt int ... colors) {
        if (colors.length > 0) {
            mBackPaint.setColor(colors[0]);
            if (colors.length > 1) {
                mFrontPaint.setColor(colors[1]);
                mOuterPaint.setColor(colors[1]);
            }
        }
    }

    @NonNull
    @Override
    public View getView() {
        return this;
    }

    @Override
    public SpinnerStyle getSpinnerStyle() {
        return SpinnerStyle.Scale;
    }
    //</editor-fold>
}


text:
'use strict';

/**
 * A list of firewall rules.
 */
class FirewallRuleListResult extends Array {
  /**
   * Create a FirewallRuleListResult.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of FirewallRuleListResult
   *
   * @returns {object} metadata of FirewallRuleListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'FirewallRuleListResult',
      type: {
        name: 'Composite',
        className: 'FirewallRuleListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'FirewallRuleElementType',
                  type: {
                    name: 'Composite',
                    className: 'FirewallRule'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = FirewallRuleListResult;