<commit_before>function draw(){
    if(key_left){
        rotation -= speed / 10 + 1;
    }
    if(key_right){
        rotation += speed / 10 + 1;
    }

    if(key_speedminus && speed > 0){
        speed -= 1;
    }
    if(key_speedplus){
        speed += 1;
    }

    var temp_blink_fix = 0;
    do_split = 0;

    /* move wall split location */
    i = 3;
    do{
        wall_splits[i * 2] += wall_splits[i * 2] >= 0 ? speed : -speed;
        wall_splits[i * 2 + 1] += wall_splits[i * 2 + 1] >= 0 ? speed : -speed;

        /* check if wall split reached edge of screen */
        if(wall_splits[i * 2] < -x || wall_splits[i * 2] > x){
            /* this temporary variable prevents blinking bug */
            temp_blink_fix = 1;

            /* reset wall splits */
            wall_splits[i * 2] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2];
            wall_splits[i * 2 + 1] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2 + 1];

            do_split = 1;
        }
    }while(i--);

    if(settings[5]){/* clear? */
        buffer.clearRect(
            0,
            0,
            width,
            height
        );
    }

    buffer.translate(
        x,
        y
    );
    buffer.rotate(rotation * (Math.PI / 180));

    /* draw walls */
    if(temp_blink_fix){

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            x,
            -x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][0];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            -x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][1];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            x,
            -x
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][2];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            x
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][3];
        buffer.fill();

        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[1][i];
            buffer.fill();
        }while(i--);

    }else{
        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[0][i];
            buffer.fill();
        }while(i--);

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            x,
            -x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][0];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            -x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][1];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            x,
            -x
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][2];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            x
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][3];
        buffer.fill();
    }

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex()
        ];
    }

    /* undo rotate/translate */
    buffer.rotate(-rotation * (Math.PI / 180));
    buffer.translate(
        -x,
        -y
    );

    /* draw current speed */
    buffer.font = '23pt sans-serif';
    buffer.textAlign = 'left';
    buffer.textBaseline = 'top';
    buffer.fillStyle = '#fff';
    buffer.fillText(
        speed + ' m/s',
        5,
        5
    );

    if(settings[5]){/* clear? */
        canvas.clearRect(
            0,
            0,
            width,
            height
        );
    }
    canvas.drawImage(
        get('buffer'),
        0,
        0
    );
}

function get(i){
    return document.getElementById(i);
}

function random_hex(){
    return '0123456789abcdef'.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    if(mode > 0){
        width = get('buffer').width = get('canvas').width = window.innerWidth;
        height = get('buffer').height = get('canvas').height = window.innerHeight;

        x = width / 2;
        y = height / 2;
    }
}

function save(){
    i = 1;
    do{
        j = [
            'audio-volume',
            'ms-per-frame'
        ][i];

        if(get(j).value == [1, 30][i] || isNaN(get(j).value) || get(j).value < [0, 1][i]){
            ls.removeItem('tubes-' + i);
            settings[i] = [
                1,
                30
            ][i];
            get(j).value = settings[i];

        }else{
            settings[i] = parseFloat(get(j).value);
            ls.setItem(
                'tubes-' + i,
                settings[i]
            );
        }
    }while(i--);

    i = 2;
    do{
        if(get(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value == ['AD', 'S', 'W'][i]){
            ls.removeItem('tubes-' + (i + 2));
            settings[i + 2] = [
                'AD',
                'S',
                'W'
            ][i];

        }else{
            settings[i + 2] = get(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value;
            ls.setItem(
                'tubes-' + (i + 2),
                settings[i + 2]
            );
        }
    }while(i--);

    settings[5] = get('clear').checked;
    if(settings[5]){
        ls.removeItem('tubes-5');

    }else{
        ls.setItem(
            'tubes-5',
            0
        );
    }
}

function setmode(newmode){
    clearInterval(interval);

    mode = newmode;

    /* new game mode */
    if(mode > 0){
        save();

        key_left = 0;
        key_right = 0;
        key_speedminus = 0;
        key_speedplus = 0;
        p = 10;
        rotation = 0;

        get('page').innerHTML = '<canvas id=canvas></canvas>';

        buffer = get('buffer').getContext('2d');
        canvas = get('canvas').getContext('2d');

        resize();

        /**/
        wall_splits = [
            -2,
            -2,
             2,
            -2,
            -2,
             2,
             2,
             2
        ];

        /* set initial tube colors */
        colors = [
            ['#f0f', '#06f', '#ff0', '#f60'],/* initial */
            ['#0f0', '#f00', '#00f', '#0ff']/* first swap */
        ];

        interval = setInterval('draw()', settings[1]);/* milliseconds per frame */

    /* main menu mode */
    }else{
        buffer = 0;
        canvas = 0;

        get('page').innerHTML = '

Tubes

SEIZURE WARNING!
FLASHING LIGHTS!

Make Mama Sick

<input disabled size=3 style=border:0 type=text value=ESC>Main Menu
<input id=movement-keys maxlength=2 size=3 type=text value='
            + settings[2] + '>Move ←→
<input id=key-slowdown maxlength=1 size=3 type=text value='
            + settings[3] + '>Speed--
<input id=key-speedup maxlength=1 size=3 type=text value='
            + settings[4] + '>Speed++

<input id=audio-volume max=1 min=0 step=.01 type=range value='
            + settings[0] + '>Audio
<input '
            + (settings[5] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=ms-per-frame size=1 type=text value='
            + settings[1] + '>ms/Frame
Reset Settings

'
    }
}

var buffer = 0;
var canvas = 0;
var colors = [];
var do_split = 0;
var height = 0;
var i = 0;
var interval = 0;
var j = 0;
var key_left = 0;
var key_right = 0;
var key_speedminus = 0;
var key_speedplus = 0;
var ls = window.localStorage;
var mode = 0;
var mx = 0;
var my = 0;
var px = 0;
var py = 0;
var rotation = 0;
var settings = [
    ls.getItem('tubes-0') === null ?    1 : parseFloat(ls.getItem('tubes-0')),/* audio volume */
    ls.getItem('tubes-1') === null ?   30 : parseInt(ls.getItem('tubes-1')),/* milliseconds per frame */
    ls.getItem('tubes-2') === null ? 'AD' : ls.getItem('tubes-2'),/* movement keys */
    ls.getItem('tubes-3') === null ?  'S' : ls.getItem('tubes-3'),/* slowdown key */
    ls.getItem('tubes-4') === null ?  'W' : ls.getItem('tubes-4'),/* speedup key */
    ls.getItem('tubes-5') === null/* clear? */
];
var speed = 0;
var wall_splits = [];
var width = 0;
var x = 0;
var y = 0;

setmode(0);

window.onkeydown=function(e){
    if(mode > 0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;

        if(String.fromCharCode(i) === settings[2][0]){
            key_left = 1;

        }else if(String.fromCharCode(i) === settings[2][1]){
            key_right = 1;

        }else if(String.fromCharCode(i) === settings[3]){
            key_speedminus = 1;

        }else if(String.fromCharCode(i) === settings[4]){
            key_speedplus = 1;

        }else if(i === 27){/* ESC */
            setmode(0);
        }
    }
};

window.onkeyup = function(e){
    i = window.event ? event : e;
    i = i.charCode ? i.charCode : i.keyCode;

    if(String.fromCharCode(i) === settings[2][0]){
        key_left = 0;

    }else if(String.fromCharCode(i) === settings[2][1]){
        key_right = 0;

    }else if(String.fromCharCode(i) === settings[3]){
        key_speedminus = 0;

    }else if(String.fromCharCode(i) === settings[4]){
        key_speedplus = 0;
    }
};

window.onresize = resize;
<commit_msg>improved formatting<commit_after>function draw(){
    if(key_left){
        rotation -= speed / 10 + 1;
    }
    if(key_right){
        rotation += speed / 10 + 1;
    }

    if(key_speedminus && speed > 0){
        speed -= 1;
    }
    if(key_speedplus){
        speed += 1;
    }

    var temp_blink_fix = 0;
    do_split = 0;

    /* move wall split location */
    i = 3;
    do{
        wall_splits[i * 2] += wall_splits[i * 2] >= 0 ? speed : -speed;
        wall_splits[i * 2 + 1] += wall_splits[i * 2 + 1] >= 0 ? speed : -speed;

        /* check if wall split reached edge of screen */
        if(wall_splits[i * 2] < -x || wall_splits[i * 2] > x){
            /* this temporary variable prevents blinking bug */
            temp_blink_fix = 1;

            /* reset wall splits */
            wall_splits[i * 2] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2];
            wall_splits[i * 2 + 1] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2 + 1];

            do_split = 1;
        }
    }while(i--);

    if(settings[5]){/* clear? */
        buffer.clearRect(
            0,
            0,
            width,
            height
        );
    }

    buffer.translate(
        x,
        y
    );
    buffer.rotate(rotation * (Math.PI / 180));

    /* draw walls */
    if(temp_blink_fix){

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            x,
            -x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][0];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            -x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][1];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            x,
            -x
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][2];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            x
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[0][3];
        buffer.fill();

        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[1][i];
            buffer.fill();
        }while(i--);

    }else{
        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[0][i];
            buffer.fill();
        }while(i--);

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            x,
            -x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][0];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            -x
        );
        buffer.lineTo(
            wall_splits[0],
            wall_splits[1]
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            -x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][1];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            x,
            -x
        );
        buffer.lineTo(
            wall_splits[2],
            wall_splits[3]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][2];
        buffer.fill();

        buffer.beginPath();
        buffer.moveTo(
            -x,
            x
        );
        buffer.lineTo(
            wall_splits[4],
            wall_splits[5]
        );
        buffer.lineTo(
            wall_splits[6],
            wall_splits[7]
        );
        buffer.lineTo(
            x,
            x
        );
        buffer.closePath();
        buffer.fillStyle = colors[1][3];
        buffer.fill();
    }

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex()
        ];
    }

    /* undo rotate/translate */
    buffer.rotate(-rotation * (Math.PI / 180));
    buffer.translate(
        -x,
        -y
    );

    /* draw current speed */
    buffer.font = '23pt sans-serif';
    buffer.textAlign = 'left';
    buffer.textBaseline = 'top';
    buffer.fillStyle = '#fff';
    buffer.fillText(
        speed + ' m/s',
        5,
        5
    );

    if(settings[5]){/* clear? */
        canvas.clearRect(
            0,
            0,
            width,
            height
        );
    }
    canvas.drawImage(
        get('buffer'),
        0,
        0
    );
}

function get(i){
    return document.getElementById(i);
}

function random_hex(){
    return '0123456789abcdef'.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    if(mode > 0){
        width = get('buffer').width = get('canvas').width = window.innerWidth;
        height = get('buffer').height = get('canvas').height = window.innerHeight;

        x = width / 2;
        y = height / 2;
    }
}

function save(){
    i = 1;
    do{
        j = [
            'audio-volume',
            'ms-per-frame'
        ][i];

        if(get(j).value == [1, 30][i] || isNaN(get(j).value) || get(j).value < [0, 1][i]){
            ls.removeItem('tubes-' + i);
            settings[i] = [
                1,
                30
            ][i];
            get(j).value = settings[i];

        }else{
            settings[i] = parseFloat(get(j).value);
            ls.setItem(
                'tubes-' + i,
                settings[i]
            );
        }
    }while(i--);

    i = 2;
    do{
        if(get(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value == ['AD', 'S', 'W'][i]){
            ls.removeItem('tubes-' + (i + 2));
            settings[i + 2] = [
                'AD',
                'S',
                'W'
            ][i];

        }else{
            settings[i + 2] = get(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value;
            ls.setItem(
                'tubes-' + (i + 2),
                settings[i + 2]
            );
        }
    }while(i--);

    settings[5] = get('clear').checked;
    if(settings[5]){
        ls.removeItem('tubes-5');

    }else{
        ls.setItem(
            'tubes-5',
            0
        );
    }
}

function setmode(newmode){
    clearInterval(interval);

    mode = newmode;

    /* new game mode */
    if(mode > 0){
        save();

        key_left = 0;
        key_right = 0;
        key_speedminus = 0;
        key_speedplus = 0;
        speed = 10;
        rotation = 0;

        get('page').innerHTML = '<canvas id=canvas></canvas>';

        buffer = get('buffer').getContext('2d');
        canvas = get('canvas').getContext('2d');

        resize();

        /**/
        wall_splits = [
            -2,
            -2,
             2,
            -2,
            -2,
             2,
             2,
             2
        ];

        /* set initial tube colors */
        colors = [
            ['#f0f', '#06f', '#ff0', '#f60'],/* initial */
            ['#0f0', '#f00', '#00f', '#0ff']/* first swap */
        ];

        interval = setInterval('draw()', settings[1]);/* milliseconds per frame */

    /* main menu mode */
    }else{
        buffer = 0;
        canvas = 0;

        get('page').innerHTML = '

Tubes

SEIZURE WARNING!
FLASHING LIGHTS!

Make Mama Sick

<input disabled size=3 style=border:0 type=text value=ESC>Main Menu
<input id=movement-keys maxlength=2 size=3 type=text value='
            + settings[2] + '>Move ←→
<input id=key-slowdown maxlength=1 size=3 type=text value='
            + settings[3] + '>Speed--
<input id=key-speedup maxlength=1 size=3 type=text value='
            + settings[4] + '>Speed++

<input id=audio-volume max=1 min=0 step=.01 type=range value='
            + settings[0] + '>Audio
<input '
            + (settings[5] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=ms-per-frame size=1 type=text value='
            + settings[1] + '>ms/Frame
Reset Settings

'
    }
}

var buffer = 0;
var canvas = 0;
var colors = [];
var do_split = 0;
var height = 0;
var i = 0;
var interval = 0;
var j = 0;
var key_left = 0;
var key_right = 0;
var key_speedminus = 0;
var key_speedplus = 0;
var ls = window.localStorage;
var mode = 0;
var mx = 0;
var my = 0;
var px = 0;
var py = 0;
var rotation = 0;
var settings = [
    ls.getItem('tubes-0') === null ?    1 : parseFloat(ls.getItem('tubes-0')),/* audio volume */
    ls.getItem('tubes-1') === null ?   30 : parseInt(ls.getItem('tubes-1')),/* milliseconds per frame */
    ls.getItem('tubes-2') === null ? 'AD' : ls.getItem('tubes-2'),/* movement keys */
    ls.getItem('tubes-3') === null ?  'S' : ls.getItem('tubes-3'),/* slowdown key */
    ls.getItem('tubes-4') === null ?  'W' : ls.getItem('tubes-4'),/* speedup key */
    ls.getItem('tubes-5') === null/* clear? */
];
var speed = 0;
var wall_splits = [];
var width = 0;
var x = 0;
var y = 0;

setmode(0);

window.onkeydown = function(e){
    if(mode > 0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;

        if(String.fromCharCode(i) === settings[2][0]){
            key_left = 1;

        }else if(String.fromCharCode(i) === settings[2][1]){
            key_right = 1;

        }else if(String.fromCharCode(i) === settings[3]){
            key_speedminus = 1;

        }else if(String.fromCharCode(i) === settings[4]){
            key_speedplus = 1;

        }else if(i === 27){/* ESC */
            setmode(0);
        }
    }
};

window.onkeyup = function(e){
    i = window.event ? event : e;
    i = i.charCode ? i.charCode : i.keyCode;

    if(String.fromCharCode(i) === settings[2][0]){
        key_left = 0;

    }else if(String.fromCharCode(i) === settings[2][1]){
        key_right = 0;

    }else if(String.fromCharCode(i) === settings[3]){
        key_speedminus = 0;

    }else if(String.fromCharCode(i) === settings[4]){
        key_speedplus = 0;
    }
};

window.onresize = resize;
<|endoftext|>


<commit_before>import {handlersMap, getConfig} from "./config";
import {validate} from "validate.js";
import flow from "lodash/flow";
import {PAGE_TYPES, TRACKING_IDS} from "./constants";

//Important: This should be defined as 'function' and not as ES6 arrow function
//because arrow functions don't have 'arguments' object
//This function is used to mainly suppress the default validation messages
//shown by validate.js which prepends the name of the attribute in the messagese
//the first parameter passed is the object to be validated, the other object is constraint
//the third object is options (dealing with error messages format, grouping etc.)
const custValidate = function() {
    //Array.from(arguments) 's equivalent to in ES5/ES3 is Array.prototype.slice.call(arguments)
    //const args = Array.from(arguments);
    const args = Array.prototype.slice.call(arguments);

    if (args[2] === undefined) {
        args[2] = {
            fullMessages: false
        }
    } else { //if present
        args[2].fullMessages === undefined ? args[2].fullMessages = false : '';
    }

    //fullMessages false is required, otherwise following message gets printed
    //Main Object Check 'Code' key is not allowed in the config
    //instead of
    //'Code' key is not allowed in the config

    return validate.apply(null, args);

};

const enhanceWithValidation = (schema, func) => {

    return (confObj) => {
        const validationResult = custValidate(confObj, schema);
        if (validationResult) {
            handlersMap['errorHandler'](validationResult);
            throw JSON.stringify(validationResult);
        }
        return func(confObj); //func returns promise
    };
};

const callBackify = (promiseReturningFunc) => {
    return function() {
        //Array.from(arguments) 's equivalent to in ES5/ES3 is Array.prototype.slice.call(arguments)
        //let args = Array.from(arguments);
        let args = Array.prototype.slice.call(arguments);

        if (typeof args[args.length - 1] === 'function') {
            let cb = args.pop();
            promiseReturningFunc.apply(promiseReturningFunc, args)
                .then(function(success) {
                    cb(undefined, success)
                }, function(err) {
                    cb(err);
                });
        } else {
            return promiseReturningFunc.apply(promiseReturningFunc, args);
        }
    }
};

const validateAndCallbackify = flow(enhanceWithValidation, callBackify);

const getMerchantAccessKey = (optionsObj) => {
    const merchantAccessKey = optionsObj.merchantAccessKey || getConfig().merchantAccessKey;
    if (!merchantAccessKey) {
        return handlersMap.errorHandler(new Error('merchantAccessKey is not set'));
    }
    return merchantAccessKey;
};

//logic from jquery payment plugin
const defaultFormat = /(\d{1,4})/g;
const cards = [{
    type: 'forbrugsforeningen',
    patterns: [600],
    format: /^600/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'visa',
    patterns: [4],
    format: /^4/,
    length: [13, 16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'mastercard',
    patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27],
    format: /^(5[1-5]|222[1-9]\d{2}|22[3-9]\d{3}|23\d{4}|24\d{4}|25\d{4}|26\d{4}|27[0-1]\d{3}|272000|2720[0-9][0-9])/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'amex',
    patterns: [34, 37],
    format: /^3[47]/,
    length: [15],
    cvcLength: [3, 4],
    luhn: true,
    groupingFormat: /(\d{1,4})(\d{1,6})?(\d{1,5})?/
}, {
    type: 'rupay',
    patterns: [60, 50, 65, 55, 69],
    format: /^(508[5-9][0-9][0-9]|60698[5-9]|60699[0-9]|607[0-8][0-9][0-9]|607[9][0-7][0-9]|60798[0-4]|608[0-4][0-9][0-9]|608500|6521[5-9][0-9]|652[2-7][0-9][0-9]|6528[0-9][0-9]|6529[0-9][0-9]|6530[0-9][0-9]|6531[0-4][0-9])/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'maestro',
    patterns: [5018, 502, 503, 504, 545, 56, 58, 639, 6220, 67],
    format: /^(?:5[0678]\d\d|6304|6390|6220|67\d\d)\d{8,15}$/,
    length: [12, 13, 14, 15, 16, 17, 18, 19],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'dinersclub',
    patterns: [30, 36, 38, 39],
    format: /^(36|38|30[0-5])/,
    length: [14],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'discover',
    patterns: [6011, 64, 65, 622],
    format: /^(6011|65|64[4-9]|622)/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'unionpay',
    patterns: [62, 88],
    format: /^62/,
    length: [16, 17, 18, 19],
    cvcLength: [3],
    luhn: false,
    groupingFormat: defaultFormat
}, {
    type: 'jcb',
    patterns: [35],
    format: /^35/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}];

const schemeFromNumber = (num) => {
    //if(!num)
    //throw new Error('Card number can not be blank.');
    var card, _i, _len, _ref;
    num = (num + '').replace(/\D/g, '');
    for (_i = 0, _len = cards.length; _i < _len; _i++) {
        card = cards[_i];
        _ref = card.patterns;
        if (card.format.test(num)) {
            return card.type;
        }
    }
};

const cardFromNumber = (num) => {
    var card, _i, _len;
    num = (num + '').replace(/\D/g, '');
    for (_i = 0, _len = cards.length; _i < _len; _i++) {
        card = cards[_i];
        //_ref = card.patterns;
        if (card.format.test(num)) {
            return card;
        }
    }
};

const appDataStore = {};

const setAppData = (key, data) => {
    appDataStore[key] = data;
};

const getAppData = (key) => {
    return appDataStore[key]
};

const isIE = () => {
    var ua = window.navigator.userAgent;
    var ie10orless = ua.indexOf('MSIE ');
    var ie11 = ua.indexOf('Trident/');
    var edge = ua.indexOf('Edge/');
    return !!(ie10orless > -1 || ie11 > -1 || edge > -1);
};

const addListener = (element, eventName, callback, options = false) => {
    if (window.addEventListener) {
        element.addEventListener(eventName, callback, options);
    } else if (window.attachEvent) {
        element.attachEvent('on' + eventName, callback, options);
    }
};

const getElement = (selector) => {
    const invalidSelectorMessage = `invalid selector ${selector}, it should be of the form of #id or .cssClass`;
    if (!selector || selector.length <= 1)
        throw new Error(invalidSelectorMessage);
    const identifierName = selector.slice(1);
    if (selector.indexOf('#') === 0) {
        var element = document.getElementById(identifierName);
        if (!element)
            throw new Error(`no element found with selector ${selector}`);
        else
            return element;
    } else if (selector.indexOf('.') == 0) {
        var elements = document.getElementsByClassName(identifierName);
        if (elements.length == 0) {
            throw new Error(`no element found with selector ${selector} .`)
        }
        if (elements.length == 1)
            return elements[0];
        if (elements.length > 1)
            throw new Error(`more then one element found for selector ${selector}`);
    } else
        throw new Error(invalidSelectorMessage);

};

const postMessageWrapper = (win, messageObj, url) => {
    messageObj.generatedBy = 'citrus';
    win.postMessage(JSON.parse(JSON.stringify(messageObj)), url);
};

const doValidation = (confObj,schema)=>{
    const validationResult = custValidate(confObj, schema);
        if (validationResult) {
            handlersMap['errorHandler'](validationResult);
            throw JSON.stringify(validationResult);
        }
};

const isIcpRequest = ()=>{
   return getConfig().page === PAGE_TYPES.ICP;
};

const isV3Request = (requestOrigin)=>{
   return (requestOrigin === TRACKING_IDS.SSLV3Guest || requestOrigin === TRACKING_IDS.SSLV3Wallet || requestOrigin === TRACKING_IDS.SSLV3Nitro);
};

const isIOS = ()=>{
    return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
};

const isUrl = (data) => {
    //regex for url
    const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(data);
};

export {
    validateAndCallbackify,
    getMerchantAccessKey,
    schemeFromNumber,
    cardFromNumber,
    setAppData,
    getAppData,
    isIE,
    addListener,
    getElement,
    postMessageWrapper,
    doValidation,
    isIcpRequest,
    isV3Request,
    isIOS,
    isUrl
};<commit_msg>changes for OL<commit_after>import {handlersMap, getConfig} from "./config";
import {validate} from "validate.js";
import flow from "lodash/flow";
import {PAGE_TYPES, TRACKING_IDS} from "./constants";

//Important: This should be defined as 'function' and not as ES6 arrow function
//because arrow functions don't have 'arguments' object
//This function is used to mainly suppress the default validation messages
//shown by validate.js which prepends the name of the attribute in the messagese
//the first parameter passed is the object to be validated, the other object is constraint
//the third object is options (dealing with error messages format, grouping etc.)
const custValidate = function() {
    //Array.from(arguments) 's equivalent to in ES5/ES3 is Array.prototype.slice.call(arguments)
    //const args = Array.from(arguments);
    const args = Array.prototype.slice.call(arguments);

    if (args[2] === undefined) {
        args[2] = {
            fullMessages: false
        }
    } else { //if present
        args[2].fullMessages === undefined ? args[2].fullMessages = false : '';
    }

    //fullMessages false is required, otherwise following message gets printed
    //Main Object Check 'Code' key is not allowed in the config
    //instead of
    //'Code' key is not allowed in the config

    return validate.apply(null, args);

};

const enhanceWithValidation = (schema, func) => {

    return (confObj) => {
        const validationResult = custValidate(confObj, schema);
        if (validationResult) {
            handlersMap['errorHandler'](validationResult);
            throw JSON.stringify(validationResult);
        }
        return func(confObj); //func returns promise
    };
};

const callBackify = (promiseReturningFunc) => {
    return function() {
        //Array.from(arguments) 's equivalent to in ES5/ES3 is Array.prototype.slice.call(arguments)
        //let args = Array.from(arguments);
        let args = Array.prototype.slice.call(arguments);

        if (typeof args[args.length - 1] === 'function') {
            let cb = args.pop();
            promiseReturningFunc.apply(promiseReturningFunc, args)
                .then(function(success) {
                    cb(undefined, success)
                }, function(err) {
                    cb(err);
                });
        } else {
            return promiseReturningFunc.apply(promiseReturningFunc, args);
        }
    }
};

const validateAndCallbackify = flow(enhanceWithValidation, callBackify);

const getMerchantAccessKey = (optionsObj) => {
    const merchantAccessKey = optionsObj.merchantAccessKey || getConfig().merchantAccessKey;
    if (!merchantAccessKey) {
        return handlersMap.errorHandler(new Error('merchantAccessKey is not set'));
    }
    return merchantAccessKey;
};

//logic from jquery payment plugin
const defaultFormat = /(\d{1,4})/g;
const cards = [{
    type: 'forbrugsforeningen',
    patterns: [600],
    format: /^600/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'visa',
    patterns: [4],
    format: /^4/,
    length: [13, 16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'mastercard',
    patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27],
    format: /^(5[1-5]|222[1-9]\d{2}|22[3-9]\d{3}|23\d{4}|24\d{4}|25\d{4}|26\d{4}|27[0-1]\d{3}|272000|2720[0-9][0-9])/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'amex',
    patterns: [34, 37],
    format: /^3[47]/,
    length: [15],
    cvcLength: [3, 4],
    luhn: true,
    groupingFormat: /(\d{1,4})(\d{1,6})?(\d{1,5})?/
}, {
    type: 'rupay',
    patterns: [60, 50, 65, 55, 69],
    format: /^(508[5-9][0-9][0-9]|60698[5-9]|60699[0-9]|607[0-8][0-9][0-9]|607[9][0-7][0-9]|60798[0-4]|608[0-4][0-9][0-9]|608500|6521[5-9][0-9]|652[2-7][0-9][0-9]|6528[0-9][0-9]|6529[0-9][0-9]|6530[0-9][0-9]|6531[0-4][0-9])/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'maestro',
    patterns: [5018, 502, 503, 504, 545, 56, 58, 639, 6220, 67],
    format: /^(?:5[0678]\d\d|6304|6390|6220|67\d\d)\d{8,15}$/,
    length: [12, 13, 14, 15, 16, 17, 18, 19],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'dinersclub',
    patterns: [30, 36, 38, 39],
    format: /^(36|38|30[0-5])/,
    length: [14],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'discover',
    patterns: [6011, 64, 65, 622],
    format: /^(6011|65|64[4-9]|622)/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}, {
    type: 'unionpay',
    patterns: [62, 88],
    format: /^62/,
    length: [16, 17, 18, 19],
    cvcLength: [3],
    luhn: false,
    groupingFormat: defaultFormat
}, {
    type: 'jcb',
    patterns: [35],
    format: /^35/,
    length: [16],
    cvcLength: [3],
    luhn: true,
    groupingFormat: defaultFormat
}];

const schemeFromNumber = (num) => {
    //if(!num)
    //throw new Error('Card number can not be blank.');
    var card, _i, _len, _ref;
    num = (num + '').replace(/\D/g, '');
    for (_i = 0, _len = cards.length; _i < _len; _i++) {
        card = cards[_i];
        _ref = card.patterns;
        if (card.format.test(num)) {
            return card.type;
        }
    }
};

const cardFromNumber = (num) => {
    var card, _i, _len;
    num = (num + '').replace(/\D/g, '');
    for (_i = 0, _len = cards.length; _i < _len; _i++) {
        card = cards[_i];
        //_ref = card.patterns;
        if (card.format.test(num)) {
            return card;
        }
    }
};

const appDataStore = {};

const setAppData = (key, data) => {
    appDataStore[key] = data;
};

const getAppData = (key) => {
    return appDataStore[key]
};

const isIE = () => {
    var ua = window.navigator.userAgent;
    var ie10orless = ua.indexOf('MSIE ');
    var ie11 = ua.indexOf('Trident/');
    var edge = ua.indexOf('Edge/');
    return !!(ie10orless > -1 || ie11 > -1 || edge > -1);
};

const addListener = (element, eventName, callback, options = false) => {
    if (window.addEventListener) {
        element.addEventListener(eventName, callback, options);
    } else if (window.attachEvent) {
        element.attachEvent('on' + eventName, callback, options);
    }
};

const getElement = (selector) => {
    const invalidSelectorMessage = `invalid selector ${selector}, it should be of the form of #id or .cssClass`;
    if (!selector || selector.length <= 1)
        throw new Error(invalidSelectorMessage);
    const identifierName = selector.slice(1);
    if (selector.indexOf('#') === 0) {
        var element = document.getElementById(identifierName);
        if (!element)
            throw new Error(`no element found with selector ${selector}`);
        else
            return element;
    } else if (selector.indexOf('.') == 0) {
        var elements = document.getElementsByClassName(identifierName);
        if (elements.length == 0) {
            throw new Error(`no element found with selector ${selector} .`)
        }
        if (elements.length == 1)
            return elements[0];
        if (elements.length > 1)
            throw new Error(`more then one element found for selector ${selector}`);
    } else
        throw new Error(invalidSelectorMessage);

};

const postMessageWrapper = (win, messageObj, url) => {
    messageObj.generatedBy = 'citrus';
    win.postMessage(JSON.parse(JSON.stringify(messageObj)), url);
};

const doValidation = (confObj,schema)=>{
    const validationResult = custValidate(confObj, schema);
        if (validationResult) {
            handlersMap['errorHandler'](validationResult);
            throw JSON.stringify(validationResult);
        }
};

const isIcpRequest = ()=>{
   return getConfig().page === PAGE_TYPES.ICP;
};

const isV3Request = (requestOrigin)=>{
   return (requestOrigin === TRACKING_IDS.SSLV3Guest || requestOrigin === TRACKING_IDS.SSLV3Wallet || requestOrigin === TRACKING_IDS.SSLV3Nitro);
};

const isIOS = ()=>{
    return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
};

const isUrl = (data) => {
    //regex for url
    const regexp = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(data);
};

export {
    validateAndCallbackify,
    getMerchantAccessKey,
    schemeFromNumber,
    cardFromNumber,
    setAppData,
    getAppData,
    isIE,
    addListener,
    getElement,
    postMessageWrapper,
    doValidation,
    isIcpRequest,
    isV3Request,
    isIOS,
    isUrl
};<|endoftext|>


<commit_before>// A `yarn` is a `String` that knows how to display itself stylishly.
return (function(){ var yarn, csi;
  yarn = new(Object);

  yarn.errors = {
    unknownStyle: new(Error)("That is an invalid style")
  };

  // Constructs a new `yarn`, given a style and some other `String`s or
  // `yarns`.
  //
  // Accepts a style (or an array of styles), followed by one or more `String`
  // or `yarn` children. Order of children is preserved.
  yarn.constructor = function (styles, element1, element2) {
    arguments = Array.prototype.slice.call(arguments);
    styles = arguments.shift() || new(Array);

    this.elements = arguments;
    this.strip();
    styles.forEach(function (style) { this.style(style) });
  };

  // Applies a new style
  yarn.style = function (style) {
    if (yarn.ansiCodes[style] === 'undefined') {
      throw(yarn.errors.unknownStyle) };

    this.styles.push(style);
  };

  // Clears all styles
  yarn.strip = function () { this.styles = new(Array) };

  // Where the magic happens. Converts a `yarn` into a plain `String`,
  // converting styles into ANSI codes.
  //--
  // TODO: Support output to HTML, for inserting into a document as debugging
  //       info.
  yarn.toString = function (containing) { var used, out;
    out = new(Array), used = new(Array);

    this.styles.forEach(function (style) { var code;
      if (typeof containing === 'undefined' ||
          !containing.some(function (cStyle) {
        if (Array.isArray(cStyle)) { return(cStyle.indexOf(style) !== -1) }
                              else { return(cStyle === style) }
        })) {
          used.push(style);
          code = yarn.ansiCodes[style];
          out.push(csi + (Array.isArray(code) ? code[0] : code) + sgr);
    } });

    this.elements.forEach(function (element) {
      out.push(element.toString());
    });

    used.forEach(function (style) { var code;
      code = yarn.ansiCodes[style];
      out.push(csi + (Array.isArray(code) ? code[1] : yarn.ansiCodes['reset']) + sgr);
    });

    return out.join('');
  };

  csi = "\033[";
  sgr = 'm';
  yarn.ansiCodes = { 'reset': 0,
    'bold':          [1, 22],
    'underline':     [4, 24],
    'blink':         [5, 25],
    'negative':      [7, 27],
    'inverse':       [7, 27],

    'fg-black':      30, 'bg-black':      40,
    'fg-black-hi':   90, 'bg-black-hi':   100,
    'fg-red':        31, 'bg-red':        41,
    'fg-red-hi':     91, 'bg-red-hi':     101,
    'fg-green':      32, 'bg-green':      42,
    'fg-green-hi':   92, 'bg-green-hi':   102,
    'fg-yellow':     33, 'bg-yellow':     43,
    'fg-yellow-hi':  93, 'bg-yellow-hi':  103,
    'fg-blue':       34, 'bg-blue':       44,
    'fg-blue-hi':    94, 'bg-blue-hi':    104,
    'fg-magenta':    35, 'bg-magenta':    45,
    'fg-magenta-hi': 95, 'bg-magenta-hi': 105,
    'fg-cyan':       36, 'bg-cyan':       46,
    'fg-cyan-hi':    96, 'bg-cyan-hi':    106,
    'fg-white':      37, 'bg-white':      47,
    'fg-white-hi':   97, 'bg-white-hi':   107
  };

  yarn.constructor();

  return yarn;
})()
<commit_msg>No longer using fg-<commit_after>// A `yarn` is a `String` that knows how to display itself stylishly.
return (function(){ var yarn, csi;
  yarn = new(Object);

  yarn.errors = {
    unknownStyle: new(Error)("That is an invalid style")
  };

  // Constructs a new `yarn`, given a style and some other `String`s or
  // `yarns`.
  //
  // Accepts a style (or an array of styles), followed by one or more `String`
  // or `yarn` children. Order of children is preserved.
  yarn.constructor = function (styles, element1, element2) {
    arguments = Array.prototype.slice.call(arguments);
    styles = arguments.shift() || new(Array);

    this.elements = arguments;
    this.strip();
    styles.forEach(function (style) { this.style(style) });
  };

  // Applies a new style
  yarn.style = function (style) {
    if (yarn.ansiCodes[style] === 'undefined') {
      throw(yarn.errors.unknownStyle) };

    this.styles.push(style);
  };

  // Clears all styles
  yarn.strip = function () { this.styles = new(Array) };

  // Where the magic happens. Converts a `yarn` into a plain `String`,
  // converting styles into ANSI codes.
  //--
  // TODO: Support output to HTML, for inserting into a document as debugging
  //       info.
  yarn.toString = function (containing) { var used, out;
    out = new(Array), used = new(Array);

    this.styles.forEach(function (style) { var code;
      if (typeof containing === 'undefined' ||
          !containing.some(function (cStyle) {
        if (Array.isArray(cStyle)) { return(cStyle.indexOf(style) !== -1) }
                              else { return(cStyle === style) }
        })) {
          used.push(style);
          code = yarn.ansiCodes[style];
          out.push(csi + (Array.isArray(code) ? code[0] : code) + sgr);
    } });

    this.elements.forEach(function (element) {
      out.push(element.toString());
    });

    used.forEach(function (style) { var code;
      code = yarn.ansiCodes[style];
      out.push(csi + (Array.isArray(code) ? code[1] : yarn.ansiCodes['reset']) + sgr);
    });

    return out.join('');
  };

  csi = "\033[";
  sgr = 'm';
  yarn.ansiCodes = { 'reset': 0,
    'bold':          [1, 22],
    'underline':     [4, 24],
    'blink':         [5, 25],
    'negative':      [7, 27],
    'inverse':       [7, 27],

    'black':      30, 'bg-black':      40,
    'black-hi':   90, 'bg-black-hi':   100,
    'red':        31, 'bg-red':        41,
    'red-hi':     91, 'bg-red-hi':     101,
    'green':      32, 'bg-green':      42,
    'green-hi':   92, 'bg-green-hi':   102,
    'yellow':     33, 'bg-yellow':     43,
    'yellow-hi':  93, 'bg-yellow-hi':  103,
    'blue':       34, 'bg-blue':       44,
    'blue-hi':    94, 'bg-blue-hi':    104,
    'magenta':    35, 'bg-magenta':    45,
    'magenta-hi': 95, 'bg-magenta-hi': 105,
    'cyan':       36, 'bg-cyan':       46,
    'cyan-hi':    96, 'bg-cyan-hi':    106,
    'white':      37, 'bg-white':      47,
    'white-hi':   97, 'bg-white-hi':   107
  };

  yarn.constructor();

  return yarn;
})()
<|endoftext|>


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

/** Add new Axiom types (Implements, Constants, Topics, Properties, Methods and Listeners) to Model. */
foam.CLASS({
  refines: 'foam.core.Model',

  // documentation: 'Add new Axiom types (Implements, Constants, Topics, Properties, Methods and Listeners) to Model.',

  properties: [
    {
      class: 'AxiomArray',
      of: 'Property',
      name: 'properties',
      adaptArrayElement: function(o) {
        if ( typeof o === 'string' ) {
          var p = foam.core.Property.create();
          p.name = o;
          return p;
        }

        if ( Array.isArray(o) ) {
          var p = foam.core.Property.create();
          p.name  = o[0];
          p.value = o[1];
          return p;
        }

        if ( o.class ) {
          var m = foam.lookup(o.class);
          if ( ! m ) throw 'Unknown class : ' + o.class;
          return m.create(o);
        }

        return foam.core.Property.isInstance(o) ? o : foam.core.Property.create(o);
      }
    },
    {
      class: 'AxiomArray',
      of: 'Method',
      name: 'methods',
      adaptArrayElement: function(o) {
        if ( typeof o === 'function' ) {
          console.assert(o.name, 'Method must be named');
          var m = foam.core.Method.create();
          m.name = o.name;
          m.code = o;
          return m;
        }
        if ( foam.core.Method.isInstance(o) ) return o;
        if ( o.class ) return this.lookup(o.class).create(o);
        return foam.core.Method.create(o);
      }
    }
  ]
});

foam.boot.phase3();

foam.CLASS({
  refines: 'foam.core.FObject',

  // documentation: 'Upgrade FObject to fully bootstraped form.',

  axioms: [
    {
      name: '__context__',
      installInProto: function(p) {
        Object.defineProperty(p, '__context__', {
          get: function() {
            var x = this.getPrivate_('__context__');
            if ( ! x ) {
              var contextParent = this.getPrivate_('contextParent');
              if ( contextParent ) {
                this.setPrivate_('__context__', x = contextParent.__subContext__ || contextParent.__context__);
                this.setPrivate_('contextParent', undefined);
              } else {
                // Happens during bootstrap with Properties.
                x = foam.__context__;
              }
            }
            return x;
          },
          set: function(x) {
            if ( x ) {
              this.setPrivate_(foam.core.FObject.isInstance(x) ? 'contextParent' : '__context__', x);
            }
          }
        });

        // If no delcared exports, then sub-context is the same as context.
        Object.defineProperty(
            p,
            '__subContext__',
            { get: function() { return this.__context__; } });
      }
    }
  ],

  methods: [
    /**
      Called to process constructor arguments.
      Replaces simpler version defined in original FObject definition.
    */
    function initArgs(args, ctx) {
      this.__context__ = ctx || foam.__context__;
      if ( ! args ) return;

      this.copyFrom(args, true);
    },

    /**
      Template method used to report an unknown argument passed
      to a constructor. Is set in debug.js.
    */
    function unknownArg(key, value) {
      // NOP
    }
  ]
});

foam.boot.end();

/**
 * Map of Property property names to arrays of names of properties that they shadow.
 *
 * Ex. 'setter' has higher precedence than 'adapt', 'preSet', and 'postSet', so if
 * it is set, then it shadows those other properties if they are set, causing their
 * values to be ignored.
 *
 * Not defined as a constant, because they haven't been defined yet.
 */
foam.core.Property.SHADOW_MAP = {
  setter:     [ 'adapt', 'preSet', 'postSet' ],
  getter:     [ 'factory', 'expression', 'value' ],
  factory:    [ 'expression', 'value' ],
  expression: [ 'value' ]
};

/**
  Refine foam.core.Property to add 'transient' support.

  A transient Property is not intended to be persisted
  or transfered over the network.

  Ex. A computed Property could be made transient to avoid
  wasting disk space or network bandwidth.

  For finer control, there are also separate properties called
  'networkTransient' and 'storageTransient', which default to
  the value of 'transient' if not explicitly set.

  A networkTransient field is not marshalled over network calls.
  foam.json.Network does not encode networkTransient fields.

  A storageTransient field is not stored to persistent storage.
  foam.json.Storage does not encode storageTransient fields.
 */
foam.CLASS({
  refines: 'Property',

  properties: [
    {
      class: 'Boolean',
      name: 'transient'
    },
    {
      class: 'Boolean',
      name: 'networkTransient',
      expression: function(transient) {
        return transient;
      }
    },
    {
      class: 'Boolean',
      name: 'storageTransient',
      expression: function(transient) {
        return transient;
      }
    }
  ]
});
<commit_msg>Formatting.<commit_after>/*
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** Add new Axiom types (Implements, Constants, Topics, Properties, Methods and Listeners) to Model. */
foam.CLASS({
  refines: 'foam.core.Model',

  // documentation: 'Add new Axiom types (Implements, Constants, Topics, Properties, Methods and Listeners) to Model.',

  properties: [
    {
      class: 'AxiomArray',
      of: 'Property',
      name: 'properties',
      adaptArrayElement: function(o) {
        if ( typeof o === 'string' ) {
          var p = foam.core.Property.create();
          p.name = o;
          return p;
        }

        if ( Array.isArray(o) ) {
          var p = foam.core.Property.create();
          p.name  = o[0];
          p.value = o[1];
          return p;
        }

        if ( o.class ) {
          var m = foam.lookup(o.class);
          if ( ! m ) throw 'Unknown class : ' + o.class;
          return m.create(o);
        }

        return foam.core.Property.isInstance(o) ? o : foam.core.Property.create(o);
      }
    },
    {
      class: 'AxiomArray',
      of: 'Method',
      name: 'methods',
      adaptArrayElement: function(o) {
        if ( typeof o === 'function' ) {
          console.assert(o.name, 'Method must be named');
          var m = foam.core.Method.create();
          m.name = o.name;
          m.code = o;
          return m;
        }
        if ( foam.core.Method.isInstance(o) ) return o;
        if ( o.class ) return this.lookup(o.class).create(o);
        return foam.core.Method.create(o);
      }
    }
  ]
});

foam.boot.phase3();

foam.CLASS({
  refines: 'foam.core.FObject',

  // documentation: 'Upgrade FObject to fully bootstraped form.',

  axioms: [
    {
      name: '__context__',
      installInProto: function(p) {
        Object.defineProperty(p, '__context__', {
          get: function() {
            var x = this.getPrivate_('__context__');
            if ( ! x ) {
              var contextParent = this.getPrivate_('contextParent');
              if ( contextParent ) {
                this.setPrivate_(
                    '__context__',
                    x = contextParent.__subContext__ || contextParent.__context__);
                this.setPrivate_('contextParent', undefined);
              } else {
                // Happens during bootstrap with Properties.
                x = foam.__context__;
              }
            }
            return x;
          },
          set: function(x) {
            if ( x ) {
//              if ( x === foam.__context__ );
              this.setPrivate_(
                  foam.core.FObject.isInstance(x) ?
                      'contextParent' :
                      '__context__',
                  x);
            }
          }
        });

        // If no delcared exports, then sub-context is the same as context.
        Object.defineProperty(
            p,
            '__subContext__',
            { get: function() { return this.__context__; } });
      }
    }
  ],

  methods: [
    /**
      Called to process constructor arguments.
      Replaces simpler version defined in original FObject definition.
    */
    function initArgs(args, ctx) {
      if ( ctx  ) this.__context__ = ctx;
      if ( args ) this.copyFrom(args, true);
    },

    /**
      Template method used to report an unknown argument passed
      to a constructor. Is set in debug.js.
    */
    function unknownArg(key, value) {
      // NOP
    }
  ]
});

foam.boot.end();

/**
 * Map of Property property names to arrays of names of properties that they shadow.
 *
 * Ex. 'setter' has higher precedence than 'adapt', 'preSet', and 'postSet', so if
 * it is set, then it shadows those other properties if they are set, causing their
 * values to be ignored.
 *
 * Not defined as a constant, because they haven't been defined yet.
 */
foam.core.Property.SHADOW_MAP = {
  setter:     [ 'adapt', 'preSet', 'postSet' ],
  getter:     [ 'factory', 'expression', 'value' ],
  factory:    [ 'expression', 'value' ],
  expression: [ 'value' ]
};

/**
  Refine foam.core.Property to add 'transient' support.

  A transient Property is not intended to be persisted
  or transfered over the network.

  Ex. A computed Property could be made transient to avoid
  wasting disk space or network bandwidth.

  For finer control, there are also separate properties called
  'networkTransient' and 'storageTransient', which default to
  the value of 'transient' if not explicitly set.

  A networkTransient field is not marshalled over network calls.
  foam.json.Network does not encode networkTransient fields.

  A storageTransient field is not stored to persistent storage.
  foam.json.Storage does not encode storageTransient fields.
 */
foam.CLASS({
  refines: 'Property',

  properties: [
    {
      class: 'Boolean',
      name: 'transient'
    },
    {
      class: 'Boolean',
      name: 'networkTransient',
      expression: function(transient) {
        return transient;
      }
    },
    {
      class: 'Boolean',
      name: 'storageTransient',
      expression: function(transient) {
        return transient;
      }
    }
  ]
});
<|endoftext|>


<commit_before>import { ElementAssembler } from './element'
import { NodeAssembler } from './node'

const { prototype : { map } } = Array
const { Attr, Element, Node, document } = window
const EMPTY_STRING = ''
const VALUE_PROPERTY_NAME = 'value'
const qualifiedName = Object.getOwnPropertyDescriptor(ElementAssembler, 'qualifiedName').get

/**
 * @see https://www.w3.org/TR/dom/#interface-attr
 */
export class AttrAssembler extends NodeAssembler {
    /**
     * Remove the attribute from it's owner element
     */
    remove() {
        const ownerElement = this.node.ownerElement
        if(ownerElement) {
            ownerElement.removeAttribute(this.name)
        }
    }

    /**
     * @return {string}
     */
    get name() {
        return this.node.name
    }

    /**
     * @param {ElementAssembler|Element|*} ownerElement
     */
    set ownerElement(ownerElement) {
        const node = this.node
        if(ownerElement instanceof ElementAssembler) {
            ownerElement.setAttr(node)
        }
        else if(ownerElement instanceof Element) {
            ownerElement.attributes.setNamedItem(node)
        }
        else if(ownerElement) {
            if(node.ownerElement) {
                this.ownerElement.init(ownerElement)
            }
            else {
                const element = new this.constructor.elementAssembler(ownerElement)
                element.setAttr(node)
            }
        }
    }

    /**
     * @returns {ElementAssembler|null}
     */
    get ownerElement() {
        return this.getInstanceOf(this.node.ownerElement)
    }

    /**
     * @param {ElementAssembler|Element|*|null} parentElement
     */
    set parentElement(parentElement) {
        if(this.node.ownerElement) {
            this.ownerElement.parentElement = parentElement
        }
        else throw Error(`Failed to set 'parentElement' on '${ this.constructor.name }': the 'ownerElement' is null.`)
    }

    /**
     * @returns {ElementAssembler|*|null}
     */
    get parentElement() {
        return this.node.ownerElement && this.ownerElement.parentElement
    }

    /**
     * @param {ParentNodeAssembler|*|null} parentNode
     */
    set parentNode(parentNode) {
        if(this.node.ownerElement) {
            this.ownerElement.parentNode = parentNode
        }
        else throw Error(`Failed to set 'parentNode' on '${ this.constructor.name }': the 'ownerElement' is null.`)
    }

    /**
     * @returns {ParentNodeAssembler|*|null}
     */
    get parentNode() {
        return this.node.ownerElement && this.ownerElement.parentNode
    }

    /**
     * @param {string|*} value
     */
    set value(value) {
        if(this.constructor.removeOnValue(value)) {
            this.remove()
        }
        else this.node.value = value
    }

    /**
     * @returns {string|*}
     */
    get value() {
        return this.node.value
    }

    /**
     * @returns {Attr|*}
     * @override
     */
    static create() {
        return document.createAttributeNS(this.namespace, this.qualifiedName)
    }

    /**
     * @param {ElementAssembler|Element|*} element
     * @returns {AttrAssembler|*}
     */
    static getAttrOf(element) {
        const node = this.getNodeOf(element)
        const attr = node.attributes.getNamedItem(this.qualifiedName)
        return attr && this.getInstanceOf(attr, this)
    }

    /**
     * @param {string|Element|Document|DocumentFragment} [selectorOrContext=this.selector]
     * @param {Element|Document|DocumentFragment} [context=window.document]
     * @returns {AttrAssembler[]} array of initialized instances
     */
    static init(selectorOrContext, context = document) {
        const localName = this.localName
        if(selectorOrContext instanceof Node) {
            context = selectorOrContext
            selectorOrContext = this.selector
        }
        return map.call(context.querySelectorAll(selectorOrContext), ownerElement => {
            const node = ownerElement.attributes[localName]
            return node?
                new this({ node }) :
                new this({ ownerElement })
        })
    }

    /**
     * @param {*} value
     * @returns {boolean}
     */
    static removeOnValue(value) {
        return value === null
    }

    /**
     * @returns {string}
     * @override
     */
    static get defaultPropertyName() {
        return VALUE_PROPERTY_NAME
    }

    /**
     * @returns {null|*}
     */
    static get defaultValue() {
        return null
    }

    /**
     * @returns {interface} Attr
     * @override
     */
    static get interface() {
        return Attr
    }

    /**
     * @returns {string}
     */
    static get localName() {
        return this === AttrAssembler?
            EMPTY_STRING :
            this.name.toLowerCase()
    }

    /**
     * @returns {string}
     */
    static get namespace() {
        return EMPTY_STRING
    }

    /**
     * @returns {string}
     */
    static get prefix() {
        return EMPTY_STRING
    }

    /**
     * @returns {string}
     */
    static get qualifiedName() {
        return qualifiedName.call(this)
    }

    /**
     * @returns {string}
     */
    static get selector() {
        return `[${ this.localName }]`
    }
}

NodeAssembler.AttrAssembler = AttrAssembler
<commit_msg>AttrAssembler: get rid of the `parentElement` setter<commit_after>import { ElementAssembler } from './element'
import { NodeAssembler } from './node'

const { prototype : { map } } = Array
const { Attr, Element, Node, document } = window
const EMPTY_STRING = ''
const VALUE_PROPERTY_NAME = 'value'
const qualifiedName = Object.getOwnPropertyDescriptor(ElementAssembler, 'qualifiedName').get

/**
 * @see https://www.w3.org/TR/dom/#interface-attr
 */
export class AttrAssembler extends NodeAssembler {
    /**
     * Remove the attribute from it's owner element
     */
    remove() {
        const ownerElement = this.node.ownerElement
        if(ownerElement) {
            ownerElement.removeAttribute(this.name)
        }
    }

    /**
     * @return {string}
     */
    get name() {
        return this.node.name
    }

    /**
     * @param {ElementAssembler|Element|*} ownerElement
     */
    set ownerElement(ownerElement) {
        const node = this.node
        if(ownerElement instanceof ElementAssembler) {
            ownerElement.setAttr(node)
        }
        else if(ownerElement instanceof Element) {
            ownerElement.attributes.setNamedItem(node)
        }
        else if(ownerElement) {
            if(node.ownerElement) {
                this.ownerElement.init(ownerElement)
            }
            else {
                const element = new this.constructor.elementAssembler(ownerElement)
                element.setAttr(node)
            }
        }
    }

    /**
     * @returns {ElementAssembler|null}
     */
    get ownerElement() {
        return this.getInstanceOf(this.node.ownerElement)
    }

    /**
     * @returns {ElementAssembler|*|null}
     */
    get parentElement() {
        return this.node.ownerElement && this.ownerElement.parentElement
    }

    /**
     * @param {ParentNodeAssembler|*|null} parentNode
     */
    set parentNode(parentNode) {
        if(this.node.ownerElement) {
            this.ownerElement.parentNode = parentNode
        }
        else throw Error(`Failed to set 'parentNode' on '${ this.constructor.name }': the 'ownerElement' is null.`)
    }

    /**
     * @returns {ParentNodeAssembler|*|null}
     */
    get parentNode() {
        return this.node.ownerElement && this.ownerElement.parentNode
    }

    /**
     * @param {string|*} value
     */
    set value(value) {
        if(this.constructor.removeOnValue(value)) {
            this.remove()
        }
        else this.node.value = value
    }

    /**
     * @returns {string|*}
     */
    get value() {
        return this.node.value
    }

    /**
     * @returns {Attr|*}
     * @override
     */
    static create() {
        return document.createAttributeNS(this.namespace, this.qualifiedName)
    }

    /**
     * @param {ElementAssembler|Element|*} element
     * @returns {AttrAssembler|*}
     */
    static getAttrOf(element) {
        const node = this.getNodeOf(element)
        const attr = node.attributes.getNamedItem(this.qualifiedName)
        return attr && this.getInstanceOf(attr, this)
    }

    /**
     * @param {string|Element|Document|DocumentFragment} [selectorOrContext=this.selector]
     * @param {Element|Document|DocumentFragment} [context=window.document]
     * @returns {AttrAssembler[]} array of initialized instances
     */
    static init(selectorOrContext, context = document) {
        const localName = this.localName
        if(selectorOrContext instanceof Node) {
            context = selectorOrContext
            selectorOrContext = this.selector
        }
        return map.call(context.querySelectorAll(selectorOrContext), ownerElement => {
            const node = ownerElement.attributes[localName]
            return node?
                new this({ node }) :
                new this({ ownerElement })
        })
    }

    /**
     * @param {*} value
     * @returns {boolean}
     */
    static removeOnValue(value) {
        return value === null
    }

    /**
     * @returns {string}
     * @override
     */
    static get defaultPropertyName() {
        return VALUE_PROPERTY_NAME
    }

    /**
     * @returns {null|*}
     */
    static get defaultValue() {
        return null
    }

    /**
     * @returns {interface} Attr
     * @override
     */
    static get interface() {
        return Attr
    }

    /**
     * @returns {string}
     */
    static get localName() {
        return this === AttrAssembler?
            EMPTY_STRING :
            this.name.toLowerCase()
    }

    /**
     * @returns {string}
     */
    static get namespace() {
        return EMPTY_STRING
    }

    /**
     * @returns {string}
     */
    static get prefix() {
        return EMPTY_STRING
    }

    /**
     * @returns {string}
     */
    static get qualifiedName() {
        return qualifiedName.call(this)
    }

    /**
     * @returns {string}
     */
    static get selector() {
        return `[${ this.localName }]`
    }
}

NodeAssembler.AttrAssembler = AttrAssembler
<|endoftext|>


<commit_before>/*!
 * VerbalExpressions JavaScript Library v0.1
 * https://github.com/jehna/VerbalExpressions
 *
 *
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2013-07-19
 *
 */

// Define the collection class.
window.VerbalExpression = (function(){

    // I am the constructor function.
    function VerbalExpression(){
        var verbalExpression = Object.create( RegExp.prototype );

        // Initialize
        verbalExpression = (RegExp.apply( verbalExpression, arguments ) || verbalExpression);

        // Add all the class methods
        VerbalExpression.injectClassMethods( verbalExpression );

        // Return the new object.
        return( verbalExpression );
    }

    // Define the static methods.
    VerbalExpression.injectClassMethods = function( verbalExpression ){

        // Loop over all the prototype methods
        for (var method in VerbalExpression.prototype){

            // Make sure this is a local method.
            if (VerbalExpression.prototype.hasOwnProperty( method )){

                // Add the method
                verbalExpression[ method ] = VerbalExpression.prototype[ method ];

            }

        }

        return( verbalExpression );

    };

    // Define the class methods.
    VerbalExpression.prototype = {

        _source : "",

        lol: function( value ){
            console.log( "loL" );
            this.compile( value );
            return( this );
        },

        sanitize : function( value ) {
            return value.replace(/[^\w]/g, function(character) { return "\\" + character; });
        },

        startOfLine: function() {
            if(this.source.indexOf( "^" ) !== 0) this._source = "^" + this._source;
            this.add( "" );
            return( this );
        },

        add: function( value ) {
            this._source += value || "";
            this.compile(this._source);
            return( this );
        },

        then : function( value ) {
            value = this.sanitize(value);
            this.add( "(" + value + ")" );
            return( this );
        },

        find : function( value ) {
            return( this.then( value ) );
        },

        maybe : function( value ) {
            value = this.sanitize(value);
            this.add( "(" + value + ")?" );
            return( this );
        },

        anything : function() {
            this.add( "(.*)" );
            return( this );
        },

        endOfLine : function() {
            this.add( "$" );
            return( this );
        },

        anythingBut : function( value ) {
            value = this.sanitize(value);
            this.add( "([^" + value + "]*)" );
            return( this );
        },

        replace : function( source, value ) {
            source = source.toString();
            return source.replace( this, value );
        }

    };

    // Return the constructor.
    return( VerbalExpression );

}).call( {} );

// Create shorthand
(function(w) {
    w.VerEx = function() {
        return new VerbalExpression();
    };
})(window);<commit_msg>Added: Many new class methods<commit_after>/*!
 * VerbalExpressions JavaScript Library v0.1
 * https://github.com/jehna/VerbalExpressions
 *
 *
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2013-07-19
 *
 */

// Define the collection class.
window.VerbalExpression = (function(){

    // I am the constructor function.
    function VerbalExpression(){
        var verbalExpression = Object.create( RegExp.prototype );

        // Initialize
        verbalExpression = (RegExp.apply( verbalExpression, arguments ) || verbalExpression);

        // Add all the class methods
        VerbalExpression.injectClassMethods( verbalExpression );

        // Return the new object.
        return( verbalExpression );
    }

    // Define the static methods.
    VerbalExpression.injectClassMethods = function( verbalExpression ){

        // Loop over all the prototype methods
        for (var method in VerbalExpression.prototype){

            // Make sure this is a local method.
            if (VerbalExpression.prototype.hasOwnProperty( method )){

                // Add the method
                verbalExpression[ method ] = VerbalExpression.prototype[ method ];

            }

        }

        return( verbalExpression );

    };

    // Define the class methods.
    VerbalExpression.prototype = {

        // Variables to hold the whole
        // expression construction in order
        _prefixes : "",
        _source : "",
        _suffixes : "",
        _modifiers : "gm", // default to global multiline matching

        // Sanitation function for adding
        // anything safely to the expression
        sanitize : function( value ) {
            return value.replace(/[^\w]/g, function(character) { return "\\" + character; });
        },

        // Function to add stuff to the
        // expression. Also compiles the
        // new expression so it's ready to
        // be used.
        add: function( value ) {
            this._source += value || "";
            this.compile(this._prefixes + this._source + this._suffixes, this._modifiers);
            return( this );
        },

        // Start and end of line functions
        startOfLine: function( enable ) {
            enable = ( enable != false );
            this._prefixes = enable ? "^" : "";
            this.add( "" );
            return( this );
        },

        endOfLine : function( enable ) {
            enable = ( enable != false );
            this._suffixes = enable ? "$" : "";
            this.add( "" );
            return( this );
        },

        // We try to keep the syntax ass
        // user-friendly as possible.
        // So we can use the "normal"
        // behaviour to split the "scentences"
        // naturally.
        then : function( value ) {
            value = this.sanitize(value);
            this.add( "(" + value + ")" );
            return( this );
        },

        // And because we can't start with
        // "then" function, we create an alias
        // to be used as the first function
        // of the chain.
        find : function( value ) {
            return( this.then( value ) );
        },

        // Maybe is used to add values with ?
        maybe : function( value ) {
            value = this.sanitize(value);
            this.add( "(" + value + ")?" );
            return( this );
        },

        // Any character any times
        anything : function() {
            this.add( "(.*)" );
            return( this );
        },

        // Anything but these characters
        anythingBut : function( value ) {
            value = this.sanitize(value);
            this.add( "([^" + value + "]*)" );
            return( this );
        },

        // Shorthand function for the
        // String.replace function to
        // give more logical flow if, for
        // example, we're doing multiple
        // replacements on one regexp.
        replace : function( source, value ) {
            source = source.toString();
            return source.replace( this, value );
        },

        /// Add regular expression special ///
        /// characters                     ///

        // Line break
        lineBreak : function() {
            this.add( "(\\n|(\\r\\n))" ); // Unix + windows CLRF
            return( this );
        },
        // And a shorthand for html-minded
        br : function() {
            return this.lineBreak();
        },

        // Tab (duh?)
        tab : function() {
            this.add( "\\t" );
            return( this );
        },

        // Any alphanumeric
        word : function() {
            this.add( "\\w+" );
            return( this );
        },

        // Any given character
        anyOf : function( value ) {
            value = this.sanitize(value);
            this.add( "["+ value +"]" );
            return( this );
        },

        // Shorthand
        any : function( value ) {
            return( this.anyOf( value ) );
        },

        // Usage: .range( from, to [, from, to ...] )
        range : function() {

            var value = "[";
            console.log(arguments);

            for(var _from = 0; _from < arguments.length; _from += 2) {
                var _to = _from+1;
                if(arguments.length <= to) break;

                var from = this.sanitize( arguments[_from] );
                var to = this.sanitize( arguments[_to] );

                value += from + "-" + to;
            }

            value += "]";

            this.add( value );
            return( this );
        },

        /// Modifiers      ///

        // Modifier abstraction
        addModifier : function( modifier ) {
            if( this._modifiers.indesxOf( modifier ) == -1 ) {
                this._modifiers += modifier;
            }
            this.add("");
            return( this );
        },
        removeModifier : function( modifier ) {
            this._modifiers = this._modifiers.replace( modifier, "" );
            this.add("");
            return( this );
        },

        // Case-insensitivity modifier
        withAnyCase : function( enable ) {

            if(enable != false) this.addModifier( "i" );
            else this.removeModifier( "i" );

            this.add( "" );
            return( this );

        },

        // Default behaviour is with "g" modifier,
        // so we can turn this another way around
        // than other modifiers
        stopAtFirst : function( enable ) {

            if(enable != false) this.removeModifier( "g" );
            else this.addModifier( "g" );

            this.add( "" );
            return( this );

        },

        // Multiline, also reversed
        searhOneLine : function( enable ) {

            if(enable != false) this.removeModifier( "m" );
            else this.addModifier( "m" );

            this.add( "" );
            return( this );

        },

        /// Loops  ///

        multiple : function( value ) {
            // Use expression or string
            value = value.source ? value.source : this.sanitize(value);
            switch(value.substr(-1)) {
                case "*":
                case "+":
                    break;
                default:
                    value += "+";
            }
            this.add( value );
            return( this );
        }

    };

    // Return the constructor.
    return( VerbalExpression );

}).call( {} );

// Create shorthand
(function(w) {
    w.VerEx = function() {
        return new VerbalExpression();
    };
})(window);<|endoftext|>


<commit_before>/*!
 * Fetch All Images
 *
 * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
 * Licensed under MIT
 */

const fs = require('fs');
const csv = require('fast-csv');
const chunk = require('lodash.chunk');

const readCoordsFromFile = (coordsFile, options) => {
  const readPromise = new Promise((resolve, reject) => {
    const csvStream = fs.createReadStream(coordsFile);
    const collected = [];

    // read the values from stream and save then to the collected array
    // then resolve the promise once the stream has ended.
    csv
      .fromStream(csvStream, options)
      .on('data', (data) => {
        let processed = data
          .filter(item => item !== '') // remove any unwanted data
          .map(item => parseInt(item, 10)) // convert all items to integers
          ;

        if (processed.length > 0) {
          // group the coords by 2 so that it will form [x, y]
          processed = chunk(processed, 2);

          collected.push(processed);
        }
      })
      .on('end', () => {
        resolve(collected);
      })
      .on('error', (err) => {
        reject(err);
      })
      ;
  });

  return readPromise;
};

module.exports = readCoordsFromFile;

<commit_msg>Fix comment<commit_after>/*!
 * Read Coordinates from file
 *
 * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
 * Licensed under MIT
 */

const fs = require('fs');
const csv = require('fast-csv');
const chunk = require('lodash.chunk');

const readCoordsFromFile = (coordsFile, options) => {
  const readPromise = new Promise((resolve, reject) => {
    const csvStream = fs.createReadStream(coordsFile);
    const collected = [];

    // read the values from stream and save then to the collected array
    // then resolve the promise once the stream has ended.
    csv
      .fromStream(csvStream, options)
      .on('data', (data) => {
        let processed = data
          .filter(item => item !== '') // remove any unwanted data
          .map(item => parseInt(item, 10)) // convert all items to integers
          ;

        if (processed.length > 0) {
          // group the coords by 2 so that it will form [x, y]
          processed = chunk(processed, 2);

          collected.push(processed);
        }
      })
      .on('end', () => {
        resolve(collected);
      })
      .on('error', (err) => {
        reject(err);
      })
      ;
  });

  return readPromise;
};

module.exports = readCoordsFromFile;

<|endoftext|>


<commit_before>var Testigo = require('./testigo/Source/testigo').Testigo,
	Tests = new Testigo(),
	Runner = new Testigo.Runners.Simple('node', Tests);

// Import test cases
require('./suites/test-pd').setup(Tests);

// Run tests
Runner.run();<commit_msg>new line at the end of the file<commit_after>var Testigo = require('./testigo/Source/testigo').Testigo,
	Tests = new Testigo(),
	Runner = new Testigo.Runners.Simple('node', Tests);

// Import test cases
require('./suites/test-pd').setup(Tests);

// Run tests
Runner.run();
<|endoftext|>


<commit_before><commit_msg>pass action and method to onSubmit<commit_after><|endoftext|>


<commit_before><commit_msg>Fix TJ's assert error<commit_after><|endoftext|>


<commit_before><commit_msg>fix query browser ui local storage of queries<commit_after><|endoftext|>


<commit_before>'use babel';

import Path from 'path';
import NamedRegexp from 'named-regexp';

const AtomPackageDeps = require('atom-package-deps');
const Helpers = require('atom-linter');

module.exports = {
  activate() {
    AtomPackageDeps.install('linter-perlcritic');
  },

  provideLinter() {
    const self = this;

    return {
      name: 'perlcritic',
      grammarScopes: ['source.perl.mojolicious', 'source.perl'],
      scope: 'file',
      lintOnFly: true,
      lint: async (textEditor) => {
        const command = atom.config.get('linter-perlcritic.executablePath');

        // Parse command options, replace space by '='
        const cmdOptions = atom.config.get('linter-perlcritic.commandlineOptions');
        const parameters = self.parseCmdOptions(cmdOptions);

        // get cwd
        const filePath = textEditor.getPath();
        const cwd = self.getCwd(filePath);

        // get document text
        const fileText = textEditor.getText();

        // Execute the perlcritic command
        let result;
        await Helpers.exec(
          command,
          parameters, {
            stdin: fileText,
            cwd,
            env: process.env,
            ignoreExitCode: true,
          },
        ).then((response) => {
          result = response;
        }).catch((error) => {
          const notifications = atom.notifications.getNotifications();
          const isDisplayingNotification = notifications.some(notification => (
              notification.message === `Error: ${error.message}`
                && notification.dismissed === false
            ));

          if (!isDisplayingNotification) {
            atom.notifications.addError(`Error: ${error.message}`, {
              dismissable: true,
              stack: error.stack,
            });
          }
        });

        // Return if document has changed
        if (textEditor.getText() !== fileText) {
          return null;
        }

        // Parse result
        let regex = new RegExp(atom.config.get('linter-perlcritic.regex'), 'ig');
        regex = NamedRegexp.named(regex);

        const messages = [];
        let match = regex.exec(result);
        while (match !== null) {
          const line = parseInt(match.capture('line'), 10) - 1;
          const col = parseInt(match.capture('col'), 10) - 1;
          let text = match.capture('text');

          // Get all named captures
          const captures = match.captures;

          // Severity
          if (captures.severity) {
            text += ` (Severity ${match.capture('severity')})`;
          }

          // Trace
          if (captures.trace) {
            text += ` [${match.capture('trace')}]`;
          }

          messages.push({
            type: atom.config.get('linter-perlcritic.level'),
            text,
            filePath,
            range: Helpers.generateRange(textEditor, line, col),
          });

          match = regex.exec(result);
        }

        return messages;
      },
    };
  },

  parseCmdOptions(cmdOptions) {
    if (!cmdOptions) {
      return [];
    }

    // Parse all the options into an array
    const parameters = [];
    let cmdOptionsTemp = cmdOptions;
    const options = cmdOptions.match(/--?\w+\s*=?/ig);
    options.forEach((option) => {
      // Clean the option
      cmdOptionsTemp = cmdOptionsTemp.replace(option, '');

      // Search for the next option
      let value = cmdOptionsTemp;
      const nextOption = cmdOptionsTemp.match(/--?\w+\s*=?/i);
      if (nextOption) {
        const index = cmdOptionsTemp.indexOf(nextOption[0]);
        value = cmdOptionsTemp.substr(0, index);
      }

      // Clean the value
      cmdOptionsTemp = cmdOptionsTemp.replace(value, '');

      const cleanedOption = option.replace('=', '').trim();

      parameters.push(cleanedOption);
      parameters.push(value);
    });

    parameters.push('-');

    return parameters;
  },

  getCwd(filePath) {
    const projDir = atom.project.relativizePath(filePath)[0];
    if (projDir !== null) {
      return projDir;
    }

    return Path.dirname(filePath);
  },
};
<commit_msg>Move functions out of export<commit_after>'use babel';

import Path from 'path';
import NamedRegexp from 'named-regexp';

const AtomPackageDeps = require('atom-package-deps');
const Helpers = require('atom-linter');

const getCwd = (filePath) => {
  const projDir = atom.project.relativizePath(filePath)[0];
  if (projDir !== null) {
    return projDir;
  }

  return Path.dirname(filePath);
};

const parseCmdOptions = (cmdOptions) => {
  if (!cmdOptions) {
    return [];
  }

  // Parse all the options into an array
  const parameters = [];
  let cmdOptionsTemp = cmdOptions;
  const options = cmdOptions.match(/--?\w+\s*=?/ig);
  options.forEach((option) => {
    // Clean the option
    cmdOptionsTemp = cmdOptionsTemp.replace(option, '');

    // Search for the next option
    let value = cmdOptionsTemp;
    const nextOption = cmdOptionsTemp.match(/--?\w+\s*=?/i);
    if (nextOption) {
      const index = cmdOptionsTemp.indexOf(nextOption[0]);
      value = cmdOptionsTemp.substr(0, index);
    }

    // Clean the value
    cmdOptionsTemp = cmdOptionsTemp.replace(value, '');

    const cleanedOption = option.replace('=', '').trim();

    parameters.push(cleanedOption);
    parameters.push(value);
  });

  parameters.push('-');

  return parameters;
};

export default {
  activate() {
    AtomPackageDeps.install('linter-perlcritic');
  },

  provideLinter() {
    return {
      name: 'perlcritic',
      grammarScopes: ['source.perl.mojolicious', 'source.perl'],
      scope: 'file',
      lintOnFly: true,
      lint: async (textEditor) => {
        const command = atom.config.get('linter-perlcritic.executablePath');

        // Parse command options, replace space by '='
        const cmdOptions = atom.config.get('linter-perlcritic.commandlineOptions');
        const parameters = parseCmdOptions(cmdOptions);

        // get cwd
        const filePath = textEditor.getPath();
        const cwd = getCwd(filePath);

        // get document text
        const fileText = textEditor.getText();

        // Execute the perlcritic command
        let result;
        await Helpers.exec(
          command,
          parameters, {
            stdin: fileText,
            cwd,
            env: process.env,
            ignoreExitCode: true,
          },
        ).then((response) => {
          result = response;
        }).catch((error) => {
          const notifications = atom.notifications.getNotifications();
          const isDisplayingNotification = notifications.some(notification => (
              notification.message === `Error: ${error.message}`
                && notification.dismissed === false
            ));

          if (!isDisplayingNotification) {
            atom.notifications.addError(`Error: ${error.message}`, {
              dismissable: true,
              stack: error.stack,
            });
          }
        });

        // Return if document has changed
        if (textEditor.getText() !== fileText) {
          return null;
        }

        // Parse result
        let regex = new RegExp(atom.config.get('linter-perlcritic.regex'), 'ig');
        regex = NamedRegexp.named(regex);

        const messages = [];
        let match = regex.exec(result);
        while (match !== null) {
          const line = parseInt(match.capture('line'), 10) - 1;
          const col = parseInt(match.capture('col'), 10) - 1;
          let text = match.capture('text');

          // Get all named captures
          const captures = match.captures;

          // Severity
          if (captures.severity) {
            text += ` (Severity ${match.capture('severity')})`;
          }

          // Trace
          if (captures.trace) {
            text += ` [${match.capture('trace')}]`;
          }

          messages.push({
            type: atom.config.get('linter-perlcritic.level'),
            text,
            filePath,
            range: Helpers.generateRange(textEditor, line, col),
          });

          match = regex.exec(result);
        }

        return messages;
      },
    };
  },
};
<|endoftext|>


<commit_before><commit_msg>Fix regex to enable autocomplete on dot<commit_after><|endoftext|>


<commit_before>'use babel'

import {CompositeDisposable} from 'atom'
import {isTruthy} from './check'
import {Executor} from './executor'

export default {
  environment: null,
  locator: null,
  subscriptions: null,

  activate () {
    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(atom.commands.add('atom-workspace', 'go-config:detect', () => { }))
  },

  deactivate () {
    this.subscriptions.dispose()
    this.dispose()
  },

  dispose () {
    if (isTruthy(this.subscriptions)) {
      this.subscriptions.dispose()
    }
    this.subscriptions = null
    this.environment = null
    this.locator = null
  },

  getExecutor (options) {
    let e = new Executor({environmentFn: this.getEnvironment.bind(this)})
    return e
  },

  getLocator () {
    if (isTruthy(this.locator)) {
      return this.locator
    }
    let Locator = require('./locator').Locator
    this.locator = new Locator({
      environment: this.getEnvironment.bind(this),
      executor: this.getExecutor(),
      ready: this.ready.bind(this)
    })
    this.subscriptions.add(this.locator)
    return this.locator
  },

  ready () {
    if (isTruthy(this.environment)) {
      return true
    } else {
      return false
    }
  },

  getEnvironment () {
    if (this.ready()) {
      return this.environment
    }

    return process.env
  },

  provide () {
    return {executor: this.getExecutor(), locator: this.getLocator(), environment: this.getEnvironment.bind(this)}
  },

  consumeEnvironment (environment) {
    this.environment = environment
  }
}
<commit_msg>Fix Deactivate Bug<commit_after>'use babel'

import {CompositeDisposable} from 'atom'
import {isTruthy} from './check'
import {Executor} from './executor'

export default {
  environment: null,
  locator: null,
  subscriptions: null,

  activate () {
    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(atom.commands.add('atom-workspace', 'go-config:detect', () => { }))
  },

  deactivate () {
    this.dispose()
  },

  dispose () {
    if (isTruthy(this.subscriptions)) {
      this.subscriptions.dispose()
    }
    this.subscriptions = null
    this.environment = null
    this.locator = null
  },

  getExecutor (options) {
    let e = new Executor({environmentFn: this.getEnvironment.bind(this)})
    return e
  },

  getLocator () {
    if (isTruthy(this.locator)) {
      return this.locator
    }
    let Locator = require('./locator').Locator
    this.locator = new Locator({
      environment: this.getEnvironment.bind(this),
      executor: this.getExecutor(),
      ready: this.ready.bind(this)
    })
    this.subscriptions.add(this.locator)
    return this.locator
  },

  ready () {
    if (isTruthy(this.environment)) {
      return true
    } else {
      return false
    }
  },

  getEnvironment () {
    if (this.ready()) {
      return this.environment
    }

    return process.env
  },

  provide () {
    return {executor: this.getExecutor(), locator: this.getLocator(), environment: this.getEnvironment.bind(this)}
  },

  consumeEnvironment (environment) {
    this.environment = environment
  }
}
<|endoftext|>


<commit_before><commit_msg>Final change for now!<commit_after><|endoftext|>