<commit_before>#!/usr/bin/env node
(function() {
    "use strict";

    var getPackageJson = require("../lib/get-package-json");
    var npmInfo = getPackageJson(__dirname + "/..");
    var Getopt = require('node-getopt');
    var getopt = new Getopt([
            ['c',   'set-cmt=FILENAME',  'set MZT file as cassette magnetic tape'],
            ['h',   'help',     'display this help'],
            ['v',   'version',  'show version']
            ]);
    var cli = getopt.parseSystem();
    var argv = require("hash-arg").get(["input_filename"], cli.argv);
    var description = "The Cli-Version MZ-700 Emulator. -- " + npmInfo.name + "@" + npmInfo.version;
    getopt.setHelp(
            "Usage: mz700-cli [OPTION] [MZT-filename]\n" +
            description + "\n" +
            "\n" +
            "[[OPTIONS]]\n" +
            "\n" +
            "Installation: npm install -g mz700-js\n" +
            "Repository: https://github.com/takamin/mz700-js");

    if(cli.options.help) {
        getopt.showHelp();
        return;
    }

    if(cli.options.version) {
        console.log(description);
        return;
    }

    console.log(description);

    var readline = require("linebyline")(process.stdin);
    var fnut = require("../lib/fnuts.js");
    require("../lib/context.js");
    require("../lib/ex_number.js");
    var FTParam = require('../lib/ft-param');
    var MZ700 = require("../MZ-700/emulator.js");
    var mztReadFile = require("../lib/mzt-read-file");

    var CliCommand = require("../lib/cli-command.js");
    var commands = new CliCommand();
    commands.install([
        require("../cli-commands/exit.js"),
        require("../cli-commands/register.js"),
        require("../cli-commands/run.js"),
        require("../cli-commands/stop.js"),
        require("../cli-commands/step.js"),
        require("../cli-commands/jump.js"),
        require("../cli-commands/breakpoint.js"),
        require("../cli-commands/mem.js")
    ]);
    var cliCommandSendKey = require("../cli-commands/sendkey.js");
    var cliCommandVram = require("../cli-commands/vram.js");
    var cliCommandCmt = require("../cli-commands/cmt.js");
    commands.install([
        cliCommandSendKey,
        cliCommandVram,
        cliCommandCmt
    ]);

    commands.install(require("../cli-commands/conf.js"));

    var mz700 = new MZ700({
        "onExecutionParameterUpdate" : function() { },
        "onBreak" : function() { },
        "onVramUpdate": function(index, dispcode, attr){
            cliCommandVram.setAt(index, dispcode, attr);
        },
        'onMmioRead': function(address, value) {
            //console.log("MMIO read addr", address.HEX(4) + "H", value.HEX(2) + "H");
            MMIO.read(address, value);
        },
        'onMmioWrite': function(address, value) {
            //console.log("MMIO write addr", address.HEX(4) + "H", value.HEX(2) + "H");
            MMIO.write(address, value);
        },
        "onPortRead": function(port, value){
            //console.log("IN ", port.HEX(2) + "H", value.HEX(2) + "H");
        },
        "onPortWrite": function(port, value){
            console.log("OUT ", port.HEX(2) + "H", value.HEX(2) + "H");
        },
        'startSound': function(freq) {
            //console.log("bz:", freq, "Hz");
        },
        'stopSound': function() {
            //console.log("bz: off");
        },
        "onStartDataRecorder": function(){
            //console.log("MOTOR: ON");
        },
        "onStopDataRecorder": function(){
            //console.log("MOTOR: OFF");
        }
    });

    mz700.setExecutionParameter(
            (new FTParam(200,10,1)).get());
    cliCommandSendKey.setMakeReleaseDurations(200,50);

    var memsetMZ = function(addr, buf, size) {
        for(var i = 0; i < size; i++) {
            mz700.memory.poke(addr + i, buf[i]);
        }
    };

    var MMIO = require("../MZ-700/mmio").create();
    var mmioMapPeripheral = function(peripheral, mapToRead, mapToWrite) {
        MMIO.entry(peripheral, mapToRead, mapToWrite);
        mz700.mmioMapToRead(mapToRead);
        mz700.mmioMapToWrite(mapToWrite);
    };

    var PCG700 = require("../lib/PCG-700").create();
    PCG700.setScreen();
    PCG700.writeMMIO(0xE010, 0x00);
    PCG700.writeMMIO(0xE011, 0x00);
    PCG700.writeMMIO(0xE012, 0x18);
    mmioMapPeripheral(PCG700, [], [0xE010, 0xE011, 0xE012]);

    (new Promise(function(resolv, reject) {
        if(cli.options["set-cmt"]) {
            var filename = cli.options["set-cmt"];
            cliCommandCmt.func.call(
                cliCommandCmt, mz700, ["set", filename]
            ).then(function(){
                resolv();
            });
        } else {
            resolv();
        }
    })).then(function() {
        readline.on("line", function(line) {
            commands.executeCommandline(line, mz700, line);
        });
        //Input file
        if(!argv.input_filename) {
            commands.runCli();
        } else {
            mztReadFile(argv.input_filename).then(function(mzt_list) {
                if(mzt_list != null && mzt_list.length > 0) {
                    mzt_list.forEach(function(mzt, i) {
                        console.log("[" + (i + 1) + "/" + mzt_list.length + "] " +
                            mzt.header.addr_load.HEX(4) + "h --- " +
                            (mzt.header.addr_load + mzt.header.file_size - 1).HEX(4) + "h " +
                            "(" + mzt.header.file_size + " bytes), " +
                            mzt.header.addr_exec.HEX(4) + "h, " + mzt.header.filename);
                        memsetMZ(
                            mzt.header.addr_load,
                            mzt.body.buffer,
                            mzt.header.file_size);
                    });
                }
                commands.runCli();
            }).catch(function(err) {
                console.log(err);
            });
        }
    }).catch(function(err) {
        console.log(err);
    });
}());
<commit_msg>Change fractionalTimer's parameter on the cli emulator<commit_after>#!/usr/bin/env node
(function() {
    "use strict";

    var getPackageJson = require("../lib/get-package-json");
    var npmInfo = getPackageJson(__dirname + "/..");
    var Getopt = require('node-getopt');
    var getopt = new Getopt([
            ['c',   'set-cmt=FILENAME',  'set MZT file as cassette magnetic tape'],
            ['h',   'help',     'display this help'],
            ['v',   'version',  'show version']
            ]);
    var cli = getopt.parseSystem();
    var argv = require("hash-arg").get(["input_filename"], cli.argv);
    var description = "The Cli-Version MZ-700 Emulator. -- " + npmInfo.name + "@" + npmInfo.version;
    getopt.setHelp(
            "Usage: mz700-cli [OPTION] [MZT-filename]\n" +
            description + "\n" +
            "\n" +
            "[[OPTIONS]]\n" +
            "\n" +
            "Installation: npm install -g mz700-js\n" +
            "Repository: https://github.com/takamin/mz700-js");

    if(cli.options.help) {
        getopt.showHelp();
        return;
    }

    if(cli.options.version) {
        console.log(description);
        return;
    }

    console.log(description);

    var readline = require("linebyline")(process.stdin);
    var fnut = require("../lib/fnuts.js");
    require("../lib/context.js");
    require("../lib/ex_number.js");
    var MZ700 = require("../MZ-700/emulator.js");
    var mztReadFile = require("../lib/mzt-read-file");

    var CliCommand = require("../lib/cli-command.js");
    var commands = new CliCommand();
    commands.install([
        require("../cli-commands/exit.js"),
        require("../cli-commands/register.js"),
        require("../cli-commands/run.js"),
        require("../cli-commands/stop.js"),
        require("../cli-commands/step.js"),
        require("../cli-commands/jump.js"),
        require("../cli-commands/breakpoint.js"),
        require("../cli-commands/mem.js")
    ]);
    var cliCommandSendKey = require("../cli-commands/sendkey.js");
    var cliCommandVram = require("../cli-commands/vram.js");
    var cliCommandCmt = require("../cli-commands/cmt.js");
    commands.install([
        cliCommandSendKey,
        cliCommandVram,
        cliCommandCmt
    ]);

    commands.install(require("../cli-commands/conf.js"));

    var mz700 = new MZ700({
        "onExecutionParameterUpdate" : function() { },
        "onBreak" : function() { },
        "onVramUpdate": function(index, dispcode, attr){
            cliCommandVram.setAt(index, dispcode, attr);
        },
        'onMmioRead': function(address, value) {
            //console.log("MMIO read addr", address.HEX(4) + "H", value.HEX(2) + "H");
            MMIO.read(address, value);
        },
        'onMmioWrite': function(address, value) {
            //console.log("MMIO write addr", address.HEX(4) + "H", value.HEX(2) + "H");
            MMIO.write(address, value);
        },
        "onPortRead": function(port, value){
            //console.log("IN ", port.HEX(2) + "H", value.HEX(2) + "H");
        },
        "onPortWrite": function(port, value){
            console.log("OUT ", port.HEX(2) + "H", value.HEX(2) + "H");
        },
        'startSound': function(freq) {
            //console.log("bz:", freq, "Hz");
        },
        'stopSound': function() {
            //console.log("bz: off");
        },
        "onStartDataRecorder": function(){
            //console.log("MOTOR: ON");
        },
        "onStopDataRecorder": function(){
            //console.log("MOTOR: OFF");
        }
    });

    mz700.setExecutionParameter(MZ700.DEFAULT_TIMER_INTERVAL);
    cliCommandSendKey.setMakeReleaseDurations(200,50);

    var memsetMZ = function(addr, buf, size) {
        for(var i = 0; i < size; i++) {
            mz700.memory.poke(addr + i, buf[i]);
        }
    };

    var MMIO = require("../MZ-700/mmio").create();
    var mmioMapPeripheral = function(peripheral, mapToRead, mapToWrite) {
        MMIO.entry(peripheral, mapToRead, mapToWrite);
        mz700.mmioMapToRead(mapToRead);
        mz700.mmioMapToWrite(mapToWrite);
    };

    var PCG700 = require("../lib/PCG-700").create();
    PCG700.setScreen();
    PCG700.writeMMIO(0xE010, 0x00);
    PCG700.writeMMIO(0xE011, 0x00);
    PCG700.writeMMIO(0xE012, 0x18);
    mmioMapPeripheral(PCG700, [], [0xE010, 0xE011, 0xE012]);

    (new Promise(function(resolv, reject) {
        if(cli.options["set-cmt"]) {
            var filename = cli.options["set-cmt"];
            cliCommandCmt.func.call(
                cliCommandCmt, mz700, ["set", filename]
            ).then(function(){
                resolv();
            });
        } else {
            resolv();
        }
    })).then(function() {
        readline.on("line", function(line) {
            commands.executeCommandline(line, mz700, line);
        });
        //Input file
        if(!argv.input_filename) {
            commands.runCli();
        } else {
            mztReadFile(argv.input_filename).then(function(mzt_list) {
                if(mzt_list != null && mzt_list.length > 0) {
                    mzt_list.forEach(function(mzt, i) {
                        console.log("[" + (i + 1) + "/" + mzt_list.length + "] " +
                            mzt.header.addr_load.HEX(4) + "h --- " +
                            (mzt.header.addr_load + mzt.header.file_size - 1).HEX(4) + "h " +
                            "(" + mzt.header.file_size + " bytes), " +
                            mzt.header.addr_exec.HEX(4) + "h, " + mzt.header.filename);
                        memsetMZ(
                            mzt.header.addr_load,
                            mzt.body.buffer,
                            mzt.header.file_size);
                    });
                }
                commands.runCli();
            }).catch(function(err) {
                console.log(err);
            });
        }
    }).catch(function(err) {
        console.log(err);
    });
}());
<|endoftext|>


<commit_before>/**
 * This file contains code for rendering (and managing) HTML forms
 * which are served via the django-drf API.
 *
 * The django DRF library provides an OPTIONS method for each API endpoint,
 * which allows us to introspect the available fields at any given endpoint.
 *
 * The OPTIONS method provides the following information for each available field:
 *
 * - Field name
 * - Field label (translated)
 * - Field help text (translated)
 * - Field type
 * - Read / write status
 * - Field required status
 * - min_value / max_value
 */

/*
 * Get the API endpoint options at the provided URL,
 * using a HTTP options request.
 */
function getApiEndpointOptions(url, options={}) {

    // Return the ajax request object
    return $.ajax({
        url: url,
        type: 'OPTIONS',
        contentType: 'application/json',
        dataType: 'json',
        accepts: {
            json: 'application/json',
        },
    });
}

<commit_msg>Adds 'constructForm' javascript function<commit_after>/**
 * This file contains code for rendering (and managing) HTML forms
 * which are served via the django-drf API.
 *
 * The django DRF library provides an OPTIONS method for each API endpoint,
 * which allows us to introspect the available fields at any given endpoint.
 *
 * The OPTIONS method provides the following information for each available field:
 *
 * - Field name
 * - Field label (translated)
 * - Field help text (translated)
 * - Field type
 * - Read / write status
 * - Field required status
 * - min_value / max_value
 */

/*
 * Return true if the OPTIONS specify that the user
 * can perform a GET method at the endpoint.
 */
function canView(OPTIONS) {

    if ('actions' in OPTIONS) {
        return ('GET' in OPTIONS.actions);
    } else {
        return false;
    }
}

/*
 * Return true if the OPTIONS specify that the user
 * can perform a POST method at the endpoint
 */
function canCreate(OPTIONS) {

    if ('actions' in OPTIONS) {
        return ('POST' in OPTIONS.actions);
    } else {
        return false;
    }
}

/*
 * Return true if the OPTIONS specify that the user
 * can perform a PUT or PATCH method at the endpoint
 */
function canChange(OPTIONS) {

    if ('actions' in OPTIONS) {
        return ('PUT' in OPTIONS.actions || 'PATCH' in OPTIONS.actions);
    } else {
        return false;
    }
}

/*
 * Return true if the OPTIONS specify that the user
 * can perform a DELETE method at the endpoint
 */
function canDelete(OPTIONS) {

    if ('actions' in OPTIONS) {
        return ('DELETE' in OPTIONS.actions);
    } else {
        return false;
    }
}

/*
 * Get the API endpoint options at the provided URL,
 * using a HTTP options request.
 */
function getApiEndpointOptions(url, callback, options={}) {

    // Return the ajax request object
    $.ajax({
        url: url,
        type: 'OPTIONS',
        contentType: 'application/json',
        dataType: 'json',
        accepts: {
            json: 'application/json',
        },
        success: callback,
    });
}

/*
 * Request API OPTIONS data from the server,
 * and construct a modal form based on the response.
 *
 * arguments:
 * - method: The HTTP method e.g. 'PUT', 'POST', 'DELETE',
 *
 * options:
 * - method:
 */
function constructForm(url, method, options={}) {

    method = method.toUpperCase();

    // Request OPTIONS endpoint from the API
    getApiEndpointOptions(url, function(OPTIONS) {

        /*
         * Determine what "type" of form we want to construct,
         * based on the requested action.
         *
         * First we must determine if the user has the correct permissions!
         */

        switch (method) {
            case 'POST':
                if (canCreate(OPTIONS)) {
                    console.log('create');
                } else {
                    // User does not have permission to POST to the endpoint
                    console.log('cannot POST');
                    // TODO
                }
                break;
            case 'PUT':
            case 'PATCH':
                if (canChange(OPTIONS)) {
                    console.log("change");
                } else {
                    // User does not have permission to PUT/PATCH to the endpoint
                    // TODO
                    console.log('cannot edit');
                }
                break;
            case 'DELETE':
                if (canDelete(OPTIONS)) {
                    console.log('delete');
                } else {
                    // User does not have permission to DELETE to the endpoint
                    // TODO
                    console.log('cannot delete');
                }
                break;
            case 'GET':
                if (canView(OPTIONS)) {
                    console.log('view');
                } else {
                    // User does not have permission to GET to the endpoint
                    // TODO
                    console.log('cannot view');
                }
                break;
            default:
                console.log(`constructForm() called with invalid method '${method}'`);
                break;
        }
    });
}<|endoftext|>


<commit_before>(function() {
    var root   = this,
        _obj   = {
            toString: Object.prototype.toString
        },
        _array = {
            map:    Array.prototype.map,
            reduce: Array.prototype.reduce,
            slice:  Array.prototype.slice,
            filter: Array.prototype.filter
        }

    // Converts an n-ary function into a variadic function.
    // Arguments:
    //      fn - n-ary function
    // Examples:
    //      var one = variadic(function(args) {
    //          return args;
    //      });
    //
    //      fn()              //=> []
    //      fn('a')           //=> ['a']
    //      fn('a', 'b')      //=> ['a', 'b']
    //      fn('a', 'b', 'c') //=> ['a', 'b', 'c']
    //
    //      var two = variadic(function(one, rest) {
    //          return [one, rest];
    //      });
    //
    //      fn()              //=> [undefined, []]
    //      fn('a')           //=> ['a', []]
    //      fn('a', 'b')      //=> ['a', ['b']]
    //      fn('a', 'b', 'c') //=> ['a', ['b', 'c']]
    //
    function variadic(fn) {
        var arity = fn.length;

        function required(list) {
            var zone      = arity - 1,
                disparity = zone - list.length,
                out       = list.slice(0, zone);

            for (var i = 0; i < disparity; i++) {
                out.push(undefined);
            }

            return out;
        }

        function rest(list) {
            return list.slice(arity - 1);
        }

        return function() {
            var args = _array.slice.call(arguments);

            if (arity === 1) {
                return fn.apply(this, [args]);
            } else {
                var applyRest  = [rest(args)],
                    applyArgs  = required(args).concat(applyRest);

                return fn.apply(this, applyArgs);
            }
        }
    }

    // Applies a given unary function to each item in a list.
    // Arguments:
    //      list - array
    //      fn   - unary function
    // Examples:
    //      map([1, 2, 3], function(x) {
    //          return x * 2;
    //      });
    //      //=> [2, 4, 6]
    //
    function map(list, fn) {
        return _array.map.call(list, fn);
    }

    // Aggregates the values in the list given by the given binary function.
    // Arguments:
    //      list    - array
    //      fn      - binary function
    //      initial - (optional) mixed
    // Examples:
    //      fold([1, 2, 3], function(last, next) {
    //          return last * next;
    //      });
    //      //=> 6
    //
    function fold(list, fn, initial) {
        return _array.reduce.call(list, fn, initial);
    }

    // Selects items from the list that pass the test function.
    // Arguments:
    //      list    - array
    //      fn      - unary function
    // Examples:
    //      filter([1, 2, 3, 4, 5, 6], function(x) {
    //          return (x % 2 === 0);
    //      });
    //      //=> [2, 4, 6]
    //
    function filter(list, fn) {
        return _array.filter.call(list, fn);
    }

    // Reverses items in a list.
    // Arguments:
    //      list    - array
    // Examples:
    //      reverse([1, 2, 3]);
    //      //=> [3, 2, 1]
    //
    function reverse(list) {
        return fold(list, function(result, item) {
            result.unshift(item);
            return result;
        }, []);
    };

    // Acts as a unary function.
    // Arguments:
    //      fn - unary function
    // Examples:
    //      var addOne = function(x) {
    //          return x + 1;
    //      };
    //      unary(addOne)(1);
    //      //=> 2
    //
    function unary(fn) {
        return function(x) {
            return fn(x);
        }
    }

    // Acts as a binary function that, if presented with only
    // one parameter will return a partial application.
    // Arguments:
    //      fn - binary function
    // Examples:
    //      var add = function(x, y) {
    //          return x + y;
    //      };
    //      binary(add)(1)(2);
    //      //=> 3
    //      binary(add)(1, 2);
    //      //=> 3
    //
    function binary(fn) {
        return function binary(x, y) {
            if (y === undefined) {
                return unary(function(x) {
                    return fn(x, y);
                });
            }
            return fn(x, y);
        }
    }

    // Acts as a ternary function that, if presented with only some
    // of the parameters will return a partial application.
    // Arguments:
    //      fn - ternary function
    // Examples:
    //      var mult = function(x, y, z) {
    //          return x * y * z;
    //      };
    //      ternary(mult)(1)(2)(3);
    //      //=> 6
    //      ternary(mult)(1, 2, 3);
    //      //=> 6
    //
    function ternary(fn) {
        return function ternary(x, y, z) {
            if (y === undefined) {
                return binary(function(y, z) {
                    return fn(x, y, z);
                });
            }
            if (z === undefined) {
                return unary(function(z) {
                    return fn(x, y, z);
                });
            }
            return fn(x, y, z);
        }
    }

    // Combine smaller functions into a more complex one.
    // The result of each function is passed as an argument ofthe next.
    // Arguments:
    //      fns - unary functions (many)
    // Examples:
    //      var one = function(x) {
    //          return x + 1;
    //      };
    //      var two = function(x) {
    //          return x + 2;
    //      };
    //      var three = function(x) {
    //          return x + 3;
    //      };
    //
    //      // three(two(one(x)))
    //      var combined = compose(one, two, three);
    //      combined(1);
    //      //=> 7
    //
    var compose = variadic(function(fns) {
        return function(value) {
            return fold(fns, function(result, fn) {
                return fn(result);
            }, value);
        };
    });

    // The same as `compose`,  but the argument order is flipped.
    // While `compose` invokes the functions from right to left, `chain`
    // invokes them from left to right.
    // Arguments:
    //      fns - unary functions (many)
    // Examples:
    //      var one = function(x) {
    //          return x + 1;
    //      };
    //      var two = function(x) {
    //          return x + 2;
    //      };
    //      var three = function(x) {
    //          return x + 3;
    //      };
    //
    //      // three(two(one(x)))
    //      var combined = compose(three, two, one);
    //      combined(1);
    //      //=> 7
    //
    var chain = variadic(function(fns) {
        return compose.apply(this, reverse(fns));
    });;

    root.funk = {
        variadic: variadic,
        map: map,
        fold: fold,
        filter: filter,
        reverse: reverse,
        unary: unary,
        binary: binary,
        ternary: ternary,
        compose: compose,
        chain: chain
    };
})()
<commit_msg>Distinguishing between a fold right and a fold left.<commit_after>(function() {
    var root   = this,
        _obj   = {
            toString: Object.prototype.toString
        },
        _array = {
            map:    Array.prototype.map,
            reduce: Array.prototype.reduce,
            slice:  Array.prototype.slice,
            filter: Array.prototype.filter
        }

    // Converts an n-ary function into a variadic function.
    // Arguments:
    //      fn - n-ary function
    // Examples:
    //      var one = variadic(function(args) {
    //          return args;
    //      });
    //
    //      fn()              //=> []
    //      fn('a')           //=> ['a']
    //      fn('a', 'b')      //=> ['a', 'b']
    //      fn('a', 'b', 'c') //=> ['a', 'b', 'c']
    //
    //      var two = variadic(function(one, rest) {
    //          return [one, rest];
    //      });
    //
    //      fn()              //=> [undefined, []]
    //      fn('a')           //=> ['a', []]
    //      fn('a', 'b')      //=> ['a', ['b']]
    //      fn('a', 'b', 'c') //=> ['a', ['b', 'c']]
    //
    function variadic(fn) {
        var arity = fn.length;

        function required(list) {
            var zone      = arity - 1,
                disparity = zone - list.length,
                out       = list.slice(0, zone);

            for (var i = 0; i < disparity; i++) {
                out.push(undefined);
            }

            return out;
        }

        function rest(list) {
            return list.slice(arity - 1);
        }

        return function() {
            var args = _array.slice.call(arguments);

            if (arity === 1) {
                return fn.apply(this, [args]);
            } else {
                var applyRest  = [rest(args)],
                    applyArgs  = required(args).concat(applyRest);

                return fn.apply(this, applyArgs);
            }
        }
    }

    // Applies a given unary function to each item in a list.
    // Arguments:
    //      list - array
    //      fn   - unary function
    // Examples:
    //      map([1, 2, 3], function(x) {
    //          return x * 2;
    //      });
    //      //=> [2, 4, 6]
    //
    function map(list, fn) {
        return _array.map.call(list, fn);
    }

    // Aggregates from left to right.
    // Arguments:
    //      list    - array
    //      fn      - binary function
    //      initial - (optional) mixed
    // Examples:
    //      foldLeft([1, 2, 3], function(last, next) {
    //          return last * next;
    //      });
    //      // (1 * 2) * 3)
    //      //=> 6
    //
    function foldLeft(list, fn, initial) {
        return _array.reduce.call(list, fn, initial);
    }

    // Aggregates from right to left.
    // Arguments:
    //      list    - array
    //      fn      - binary function
    //      initial - (optional) mixed
    // Examples:
    //      foldRight([1, 2, 3], function(last, next) {
    //          return last * next;
    //      });
    //      // (3 * 2) * 1)
    //      //=> 6
    //
    function foldRight(list, fn, initial) {
        return _array.reduce.call(reverse(list), fn, initial);
    }

    // Selects items from the list that pass the test function.
    // Arguments:
    //      list    - array
    //      fn      - unary function
    // Examples:
    //      filter([1, 2, 3, 4, 5, 6], function(x) {
    //          return (x % 2 === 0);
    //      });
    //      //=> [2, 4, 6]
    //
    function filter(list, fn) {
        return _array.filter.call(list, fn);
    }

    // Reverses items in a list.
    // Arguments:
    //      list    - array
    // Examples:
    //      reverse([1, 2, 3]);
    //      //=> [3, 2, 1]
    //
    function reverse(list) {
        return foldLeft(list, function(result, item) {
            result.unshift(item);
            return result;
        }, []);
    };

    // Acts as a unary function.
    // Arguments:
    //      fn - unary function
    // Examples:
    //      var addOne = function(x) {
    //          return x + 1;
    //      };
    //      unary(addOne)(1);
    //      //=> 2
    //
    function unary(fn) {
        return function(x) {
            return fn(x);
        }
    }

    // Acts as a binary function that, if presented with only
    // one parameter will return a partial application.
    // Arguments:
    //      fn - binary function
    // Examples:
    //      var add = function(x, y) {
    //          return x + y;
    //      };
    //      binary(add)(1)(2);
    //      //=> 3
    //      binary(add)(1, 2);
    //      //=> 3
    //
    function binary(fn) {
        return function binary(x, y) {
            if (y === undefined) {
                return unary(function(x) {
                    return fn(x, y);
                });
            }
            return fn(x, y);
        }
    }

    // Acts as a ternary function that, if presented with only some
    // of the parameters will return a partial application.
    // Arguments:
    //      fn - ternary function
    // Examples:
    //      var mult = function(x, y, z) {
    //          return x * y * z;
    //      };
    //      ternary(mult)(1)(2)(3);
    //      //=> 6
    //      ternary(mult)(1, 2, 3);
    //      //=> 6
    //
    function ternary(fn) {
        return function ternary(x, y, z) {
            if (y === undefined) {
                return binary(function(y, z) {
                    return fn(x, y, z);
                });
            }
            if (z === undefined) {
                return unary(function(z) {
                    return fn(x, y, z);
                });
            }
            return fn(x, y, z);
        }
    }

    // Combine smaller functions into a more complex one.
    // The result of each function is passed as an argument ofthe next.
    // Arguments:
    //      fns - unary functions (many)
    // Examples:
    //      var one = function(x) {
    //          return x + 1;
    //      };
    //      var two = function(x) {
    //          return x + 2;
    //      };
    //      var three = function(x) {
    //          return x + 3;
    //      };
    //
    //      // three(two(one(x)))
    //      var combined = compose(one, two, three);
    //      combined(1);
    //      //=> 7
    //
    var compose = variadic(function(fns) {
        return function(value) {
            return foldRight(fns, function(result, fn) {
                return fn(result);
            }, value);
        };
    });

    // The same as `compose`,  but the argument order is flipped.
    // While `compose` invokes the functions from right to left, `chain`
    // invokes them from left to right.
    // Arguments:
    //      fns - unary functions (many)
    // Examples:
    //      var one = function(x) {
    //          return x + 1;
    //      };
    //      var two = function(x) {
    //          return x + 2;
    //      };
    //      var three = function(x) {
    //          return x + 3;
    //      };
    //
    //      // three(two(one(x)))
    //      var combined = compose(one, two, three);
    //      combined(1);
    //      //=> 7
    //
    var chain = variadic(function(fns) {
        return function(value) {
            return foldLeft(fns, function(result, fn) {
                return fn(result);
            }, value);
        };
    });

    root.funk = {
        variadic: variadic,
        map: map,
        foldLeft: foldLeft,
        foldRight: foldRight,
        filter: filter,
        reverse: reverse,
        unary: unary,
        binary: binary,
        ternary: ternary,
        compose: compose,
        chain: chain
    };
})()
<|endoftext|>


<commit_before>/**
 * blame.js is user JavaScript file wich will be include to github page and adds new feachures on blame page.i
 *
 * @author Andrew Kulakov <avk@8xx8.ru>
 * @version 1.0.0
 * @license https://github.com/Andrew8xx8/blame.js/blob/master/MIT-LICENSE.txt
 * @copyright Andrew Kulakov (c) 2011
 */

(function (globals) {

    var apiRoot = "https://github.com/api/v2/json/",

    jsonp = function (url, callback, context) {
        script = document.createElement("script");

        var prefix = "?";
        if (url.indexOf("?") >= 0)
            prefix = "&";

        url += prefix + "callback=" + encodeURIComponent(callback);

        url += "&login=&authToken=";

        script.setAttribute("src", apiRoot + url);

        document.getElementsByTagName('head')[0].appendChild(script);
    },

    blame = globals.blame = {};

    blame.cache = {};

	blame.showTemplate = "[ show \u2193 ]";
	blame.hideTemplate = "[ hide \u2191 ]";
    blame.fileTemplate = '
{name}

';
    blame.popupTemplate =
	'
[ X ]
' +
    '
' +
        '
Commit: {commit_hash}
' +
        '
' +
            '
Committed: {committed_time} ({committed_date})
'+
            'Authored: {authored_time} ({authored_date})
'+
            'by {username}
'+
            '
Message
' +
            '
{message}
' +
       '
' +
    '
' +
    '
' +
        '
Diff
' +
		'' + blame.showTemplate + ''+
        '
' +
            '{diff}' +
       '
' +
    '
' +
    '
' +
        '
Files
' +
		'' + blame.showTemplate + ''+
        '
' +
            '
Added:
' +
            '
{added}
' +
            '
Modified
' +
            '
{modified}
' +
            '
Deleted
' +
            '
{deleted}
' +
       '
' +
    '
';

    blame.popupPosition = {x: '0px', y: '0px'};
    blame.lock = false;

    blame.loadCommit = function (data){

        var popup = ' ', added = 'none', deleted = 'none', modified = 'none';

        if ( data.commit.added != null) {
            added = '';
            for (var i in data.commit.added) {
                added += blame.fetchTemplate(blame.fileTemplate, {'name' :  data.commit.added[i], 'color': 'green'});
            }
        }

        if ( data.commit.modified != null) {
            modified = '';
            for (var i in data.commit.modified) {
                modified += blame.fetchTemplate(blame.fileTemplate, {'name' :  data.commit.modified[i].filename, 'color' : 'blue'});
            }
        }

        if ( data.commit.added != null) {
            deleted = '';
            for (var i in data.commit.added) {
                deleted += blame.fetchTemplate(blame.fileTemplate, {'name' :  data.commit.added[i], 'color':'red'});
            }
        }

        committed_date = new Date(data.commit.committed_date);
        authored_date = new Date(data.commit.authored_date);

        popup = blame.fetchTemplate(blame.popupTemplate, {
            'modified'  : modified,
            'added'     : added,
            'deleted'   : deleted,
            'username'  : data.commit.author.name,
            'email'     : data.commit.author.email,
            'userlogin' : data.commit.author.login,
            'message'   : data.commit.message,
            'committed_time' : committed_date.toLocaleTimeString(),
            'committed_date' : committed_date.toLocaleDateString(),
            'authored_time'  : authored_date.toLocaleTimeString(),
            'authored_date'  : authored_date.toLocaleDateString(),
        });

        $('#blame-popup').html(popup);

        $('#blame-popup').css({
            'right': blame.popupPosition.x,
            'top':  blame.popupPosition.y,
        });

        $('#blame-popup').fadeIn();
        blame.lock = false;
    };

	blame.showHide = function(){
			var info = $(this).parent().find('.blame-info')
			if(info.is(':visible')){
				info.slideUp(300, function(){
                    $(this).parent().find('.s-h').html(blame.showTemplate);
                });
			} else {
				info.slideDown(300, function(){
                    $(this).parent().find('.s-h').html(blame.hideTemplate);
                });
			}
	}

    blame.fetchTemplate = function(template, data){
        var result = template;

        for(var i in data) {
            name = '{' + i + '}';
            result = result.replace(name, data[i]);
        }
        return result;
    };

    blame.register = function() {
        $('.blame .commitinfo').click(function(){
//            if (blame.lock) return;
            blame.lock = true;

            blame.popupPosition.x = '20px';
            blame.popupPosition.y = $(this).offset().top + 'px';

            current_commit = $(this).find('a:first').html();
            $('.blame .commitinfo').css({'background-color': 'transparent'});
            $('.blame .commitinfo code a').each(function(index, value){
                if(current_commit == $(value).html()) {
                    $(value).parent().parent().css({'background-color': '#dfa'});
                }
            });

            jsonp("commits/show" + $(this).find('a:first').attr('href').replace(/\/commit\//, '/'), 'blame.loadCommit');
        });

        $('body').append('

');
        $('#blame-popup').css({
            'position': 'absolute',
            'width':    'auto',
            'z-index': '100500',
            'display': 'none',
            'background': '#fff',
            'padding': '6px',
            'padding-top': '10px',
            'color' :  '#444',
			'border-radius': '8px',
			'box-shadow': '0px 0px 10px 0px #888'
        });
		$('#blame-popup .close').live('click', function(){
			$('#blame-popup').fadeOut();
		});
		$('#blame-popup .blame-block h3').live('click', blame.showHide);
		$('#blame-popup .blame-block .s-h').live('click', blame.showHide);
    }

}(window));

$(document).ready(function(){
    blame.register();
});
<commit_msg>[!] Dublicate files in sections Added and Deletted. Fixed [!] Wrong link on file. Fixed<commit_after>/**
 * blame.js is user JavaScript file wich will be include to github page and adds new feachures on blame page.i
 *
 * @author Andrew Kulakov <avk@8xx8.ru>
 * @version 1.0.0
 * @license https://github.com/Andrew8xx8/blame.js/blob/master/MIT-LICENSE.txt
 * @copyright Andrew Kulakov (c) 2011
 */

(function (globals) {

    var apiRoot = "https://github.com/api/v2/json/",

    jsonp = function (url, callback, context) {
        script = document.createElement("script");

        var prefix = "?";
        if (url.indexOf("?") >= 0)
            prefix = "&";

        url += prefix + "callback=" + encodeURIComponent(callback);

        url += "&login=&authToken=";

        script.setAttribute("src", apiRoot + url);

        document.getElementsByTagName('head')[0].appendChild(script);
    },

    blame = globals.blame = {};

    blame.cache = {};

	blame.showTemplate = "[ show \u2193 ]";
	blame.hideTemplate = "[ hide \u2191 ]";
    blame.fileTemplate = '
{name}

';
    blame.popupTemplate =
	'
[ X ]
' +
    '
' +
        '
Commit: {commit_hash}
' +
        '
' +
            '
Committed: {committed_time} ({committed_date})
'+
            'Authored: {authored_time} ({authored_date})
'+
            'by {username}
'+
            '
Message
' +
            '
{message}
' +
       '
' +
    '
' +
    '
' +
        '
Diff
' +
		'' + blame.showTemplate + ''+
        '
' +
            '{diff}' +
       '
' +
    '
' +
    '
' +
        '
Files
' +
		'' + blame.showTemplate + ''+
        '
' +
            '
Added:
' +
            '
{added}
' +
            '
Modified
' +
            '
{modified}
' +
            '
Deleted
' +
            '
{deleted}
' +
       '
' +
    '
';

    blame.popupPosition = {x: '0px', y: '0px'};
    blame.lock = false;

    blame.loadCommit = function (data){

        var popup = ' ', added = 'none', deleted = 'none', modified = 'none';

        if ( data.commit.added != null) {
            added = '';
            for (var i = 0; i < data.commit.added['length']; i++) {
                console.log( data.commit.added['length']);
                added += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.added[i],
                    'href' :  data.commit.added[i],
                    'color': 'green'
                });
            }
        }

        if ( data.commit.modified != null) {
            modified = '';
            for (var i = 0; i < data.commit.modified['length']; i++) {
                modified += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.modified[i].filename,
                    'href' :  data.commit.modified[i].filename,
                    'color' : 'blue'
                });
            }
        }

        if ( data.commit.deleted != null) {
            deleted = '';
            for (var i = 0; i < data.commit.deleted['length']; i++) {
                deleted += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.deleted[i],
                    'href' :  data.commit.deleted[i],
                    'color':'red'
                });
            }
        }

        committed_date = new Date(data.commit.committed_date);
        authored_date = new Date(data.commit.authored_date);

        popup = blame.fetchTemplate(blame.popupTemplate, {
            'modified'  : modified,
            'added'     : added,
            'deleted'   : deleted,
            'username'  : data.commit.author.name,
            'email'     : data.commit.author.email,
            'userlogin' : data.commit.author.login,
            'message'   : data.commit.message,
            'committed_time' : committed_date.toLocaleTimeString(),
            'committed_date' : committed_date.toLocaleDateString(),
            'authored_time'  : authored_date.toLocaleTimeString(),
            'authored_date'  : authored_date.toLocaleDateString(),
        });

        $('#blame-popup').html(popup);

        $('#blame-popup').css({
            'right': blame.popupPosition.x,
            'top':  blame.popupPosition.y,
        });

        $('#blame-popup').fadeIn();
        blame.lock = false;
    };

	blame.showHide = function(){
			var info = $(this).parent().find('.blame-info')
			if(info.is(':visible')){
				info.slideUp(300, function(){
                    $(this).parent().find('.s-h').html(blame.showTemplate);
                });
			} else {
				info.slideDown(300, function(){
                    $(this).parent().find('.s-h').html(blame.hideTemplate);
                });
			}
	}

    blame.fetchTemplate = function(template, data){
        var result = template;

        for(var i in data) {
            name = '{' + i + '}';
            result = result.replace(name, data[i]);
        }
        return result;
    };

    blame.register = function() {
        $('.blame .commitinfo').click(function(){
//            if (blame.lock) return;
            blame.lock = true;

            blame.popupPosition.x = '20px';
            blame.popupPosition.y = $(this).offset().top + 'px';

            current_commit = $(this).find('a:first').html();
            $('.blame .commitinfo').css({'background-color': 'transparent'});
            $('.blame .commitinfo code a').each(function(index, value){
                if(current_commit == $(value).html()) {
                    $(value).parent().parent().css({'background-color': '#dfa'});
                }
            });

            jsonp("commits/show" + $(this).find('a:first').attr('href').replace(/\/commit\//, '/'), 'blame.loadCommit');
        });

        $('body').append('

');
        $('#blame-popup').css({
            'position': 'absolute',
            'width':    'auto',
            'z-index': '100500',
            'display': 'none',
            'background': '#fff',
            'padding': '6px',
            'padding-top': '10px',
            'color' :  '#444',
			'border-radius': '8px',
			'box-shadow': '0px 0px 10px 0px #888'
        });
		$('#blame-popup .close').live('click', function(){
			$('#blame-popup').fadeOut();
		});
		$('#blame-popup .blame-block h3').live('click', blame.showHide);
		$('#blame-popup .blame-block .s-h').live('click', blame.showHide);
    }

}(window));

$(document).ready(function(){
    blame.register();
});
<|endoftext|>


<commit_before>// TODO: google closure?  dojo?
var nx = nx || {};

// DEPENDS: common.js

// TODO: document this

/**
 * Constructor for a reticle.
 * @param element The DOM element of the SVG surface on which to render.
 */
nx.reticle = function(surface) {
  this.surface = surface;

  this.outerCircle = this.surface.circle();
  this.centerDot = this.surface.circle();

  this.crossTop = this.surface.rect();
  this.crossBottom = this.surface.rect();
  this.crossLeft = this.surface.rect();
  this.crossRight = this.surface.rect();

  this.cross = this.surface.g(
      this.crossTop, this.crossBottom, this.crossLeft, this.crossRight);

  this.center = {x: 0, y: 0};

  this.lastSpinSpeed_ = 0;
  // Initialize
  this.updateCenter();
};
/**
 * Updates the stored coordinates for the center of the surface.
 */
nx.reticle.prototype.updateCenter = function() {
  var size = nx.elementSize(this.surface.node);
  this.center = {x: size.width / 2, y: size.height / 2};
};
/**
 * Helper function to convert booleans to visibilty states.
 * @param {boolean} isVisible True if visible, false otherwise.
 */
nx.reticle.prototype.toVisibility = function (isVisible) {
  return isVisible ? 'visible' : 'hidden'
};
/**
 * Stops any current spinning animation applied to the reticle cross.
 */
nx.reticle.prototype.stopSpin = function() {
  this.cross.stop().attr({transform: 'r0,'+this.center.x+','+this.center.y});
};
/**
 * Starts spinning the reticle cross at the speed last used by render()
 */
nx.reticle.prototype.startSpin = function() {
  this.stopSpin();
  this.cross.animate({transform: 'r360,'+this.center.x+','+this.center.y},
      this.lastSpinSpeed_, nx.bind(this,'animationEnded'));
};
/**
 * Callback triggered when the reticle cross animation ends; simply restarts
 * the animation to give it an infinite looping.
 */
nx.reticle.prototype.animationEnded = function() {
  this.stopSpin();
  this.startSpin();
};
/**
 * Renders the crosshair using the provided settings.
 * @param {Object} data An object whose properties define the reticle settings.
 */
nx.reticle.prototype.render = function (data) {
  this.updateCenter();
  this.outerCircle.attr({
      cx: this.center.x,
      cy: this.center.y,
      r: data.circleRadius,
      fill: 'none',
      stroke: data.circleColor,
      visibility: this.toVisibility(data.circleEnabled),
      strokeWidth: data.circleThickness});

  this.centerDot.attr({
      cx: this.center.x,
      cy: this.center.y,
      r: data.dotRadius,
      fill: data.dotColor,
      stroke: data.dotColor,
      visibility: this.toVisibility(data.dotEnabled),
      strokeWidth: 1});

  // Offset for left/top offsets to gap from the center
  var negativeOffset = -data.crossLength - data.crossSpread;
  var halfThickness = -(data.crossThickness/2);
  var cross = {
      x: this.center.x,
      y: this.center.y,
      fill: data.crossColor,
      visibility: this.toVisibility(data.crossEnabled) };

  var topBottom = {width: data.crossThickness, height: data.crossLength};
  var leftRight = {width: data.crossLength, height: data.crossThickness};

  this.crossTop.attr(cross).attr(topBottom).attr({
      width: data.crossThickness,
      height: data.crossLength,
      transform: 't' + [halfThickness, negativeOffset]});

  this.crossBottom.attr(cross).attr(topBottom).attr({
      x: this.center.x,
      y: this.center.y,
      width: data.crossThickness,
      height: data.crossLength,
      transform: 't' + [halfThickness, data.crossSpread]});

  this.crossLeft.attr(cross).attr(leftRight).attr({
      x: this.center.x,
      y: this.center.y,
      transform: 't' + [negativeOffset, halfThickness]});

  this.crossRight.attr(cross).attr(leftRight).attr({
      x: this.center.x,
      y: this.center.y,
      width: data.crossLength,
      height: data.crossThickness,
      transform: 't' + [data.crossSpread, halfThickness]});

  var speed = parseInt(data.crossSpinSpeed);
  if (speed > 0) {
    this.lastSpinSpeed_ = speed;
    this.startSpin();
  } else {
    this.stopSpin();
  }
};
<commit_msg>Removed TODO.<commit_after>// TODO: google closure?  dojo?
var nx = nx || {};

// DEPENDS: common.js

/**
 * Constructor for a reticle.
 * @param element The DOM element of the SVG surface on which to render.
 */
nx.reticle = function(surface) {
  this.surface = surface;

  this.outerCircle = this.surface.circle();
  this.centerDot = this.surface.circle();

  this.crossTop = this.surface.rect();
  this.crossBottom = this.surface.rect();
  this.crossLeft = this.surface.rect();
  this.crossRight = this.surface.rect();

  this.cross = this.surface.g(
      this.crossTop, this.crossBottom, this.crossLeft, this.crossRight);

  this.center = {x: 0, y: 0};

  this.lastSpinSpeed_ = 0;
  // Initialize
  this.updateCenter();
};
/**
 * Updates the stored coordinates for the center of the surface.
 */
nx.reticle.prototype.updateCenter = function() {
  var size = nx.elementSize(this.surface.node);
  this.center = {x: size.width / 2, y: size.height / 2};
};
/**
 * Helper function to convert booleans to visibilty states.
 * @param {boolean} isVisible True if visible, false otherwise.
 */
nx.reticle.prototype.toVisibility = function (isVisible) {
  return isVisible ? 'visible' : 'hidden'
};
/**
 * Stops any current spinning animation applied to the reticle cross.
 */
nx.reticle.prototype.stopSpin = function() {
  this.cross.stop().attr({transform: 'r0,'+this.center.x+','+this.center.y});
};
/**
 * Starts spinning the reticle cross at the speed last used by render()
 */
nx.reticle.prototype.startSpin = function() {
  this.stopSpin();
  this.cross.animate({transform: 'r360,'+this.center.x+','+this.center.y},
      this.lastSpinSpeed_, nx.bind(this,'animationEnded'));
};
/**
 * Callback triggered when the reticle cross animation ends; simply restarts
 * the animation to give it an infinite looping.
 */
nx.reticle.prototype.animationEnded = function() {
  this.stopSpin();
  this.startSpin();
};
/**
 * Renders the crosshair using the provided settings.
 * @param {Object} data An object whose properties define the reticle settings.
 */
nx.reticle.prototype.render = function (data) {
  this.updateCenter();
  this.outerCircle.attr({
      cx: this.center.x,
      cy: this.center.y,
      r: data.circleRadius,
      fill: 'none',
      stroke: data.circleColor,
      visibility: this.toVisibility(data.circleEnabled),
      strokeWidth: data.circleThickness});

  this.centerDot.attr({
      cx: this.center.x,
      cy: this.center.y,
      r: data.dotRadius,
      fill: data.dotColor,
      stroke: data.dotColor,
      visibility: this.toVisibility(data.dotEnabled),
      strokeWidth: 1});

  // Offset for left/top offsets to gap from the center
  var negativeOffset = -data.crossLength - data.crossSpread;
  var halfThickness = -(data.crossThickness/2);
  var cross = {
      x: this.center.x,
      y: this.center.y,
      fill: data.crossColor,
      visibility: this.toVisibility(data.crossEnabled) };

  var topBottom = {width: data.crossThickness, height: data.crossLength};
  var leftRight = {width: data.crossLength, height: data.crossThickness};

  this.crossTop.attr(cross).attr(topBottom).attr({
      width: data.crossThickness,
      height: data.crossLength,
      transform: 't' + [halfThickness, negativeOffset]});

  this.crossBottom.attr(cross).attr(topBottom).attr({
      x: this.center.x,
      y: this.center.y,
      width: data.crossThickness,
      height: data.crossLength,
      transform: 't' + [halfThickness, data.crossSpread]});

  this.crossLeft.attr(cross).attr(leftRight).attr({
      x: this.center.x,
      y: this.center.y,
      transform: 't' + [negativeOffset, halfThickness]});

  this.crossRight.attr(cross).attr(leftRight).attr({
      x: this.center.x,
      y: this.center.y,
      width: data.crossLength,
      height: data.crossThickness,
      transform: 't' + [data.crossSpread, halfThickness]});

  var speed = parseInt(data.crossSpinSpeed);
  if (speed > 0) {
    this.lastSpinSpeed_ = speed;
    this.startSpin();
  } else {
    this.stopSpin();
  }
};
<|endoftext|>


<commit_before>'use strict';

import bower from 'gulp-bower';
import cache from 'gulp-cached';
import debug from 'gulp-debug';
import gulp from 'gulp';
import remember from 'gulp-remember';
// import rsync from 'gulp-rsync';

import {config, browserSync} from './_config.babel.js';
import reportError from './_report-error.babel.js';

let sourceFiles = config.files.source.bowerConfiguration;

gulp.task('bower', () => {

  if (process.env.ENV === 'development') {
    bower({
      cmd: 'install'
    })
    .pipe(debug({
      title: 'bower install:'
    }))
    // .pipe(rsync({
    //   root: config.path.root,
    //   destination: config.path.destination.bowerComponents
    // }))
    .pipe(gulp.dest(config.path.destination.bowerComponents))
    .on('end', browserSync.reload)
    .on('error', reportError);]

    bower({
      cmd: 'update'
    })
    .pipe(debug({
      title: 'bower update:'
    }))
    // .pipe(rsync({
    //   root: config.path.root,
    //   destination: config.path.destination.bowerComponents
    // }))
    .pipe(gulp.dest(config.path.destination.bowerComponents))
    .on('end', browserSync.reload)
    .on('error', reportError);
  }

});

gulp.task('bower:watch', ['browser-sync'], () => {
  let watcher = gulp.watch(sourceFiles, ['bower']);

  watcher.on('change', (event) => {
    browserSync.reload();

    if (event.type === 'deleted') { // if a file is deleted, forget about it
      delete cache.caches.bower[event.path];
      remember.forget('bower', event.path);
    }
  });
});
<commit_msg>Fix typo in bower gulp task<commit_after>'use strict';

import bower from 'gulp-bower';
import cache from 'gulp-cached';
import debug from 'gulp-debug';
import gulp from 'gulp';
import remember from 'gulp-remember';
// import rsync from 'gulp-rsync';

import {config, browserSync} from './_config.babel.js';
import reportError from './_report-error.babel.js';

let sourceFiles = config.files.source.bowerConfiguration;

gulp.task('bower', () => {

  if (process.env.ENV === 'development') {
    bower({
      cmd: 'install'
    })
    .pipe(debug({
      title: 'bower install:'
    }))
    // .pipe(rsync({
    //   root: config.path.root,
    //   destination: config.path.destination.bowerComponents
    // }))
    .pipe(gulp.dest(config.path.destination.bowerComponents))
    .on('end', browserSync.reload)
    .on('error', reportError);

    bower({
      cmd: 'update'
    })
    .pipe(debug({
      title: 'bower update:'
    }))
    // .pipe(rsync({
    //   root: config.path.root,
    //   destination: config.path.destination.bowerComponents
    // }))
    .pipe(gulp.dest(config.path.destination.bowerComponents))
    .on('end', browserSync.reload)
    .on('error', reportError);
  }

});

gulp.task('bower:watch', ['browser-sync'], () => {
  let watcher = gulp.watch(sourceFiles, ['bower']);

  watcher.on('change', (event) => {
    browserSync.reload();

    if (event.type === 'deleted') { // if a file is deleted, forget about it
      delete cache.caches.bower[event.path];
      remember.forget('bower', event.path);
    }
  });
});
<|endoftext|>


<commit_before>test(
  'Atomic Test: parts.PartTypeSchemasTest',

  [
    'ephox.agar.api.RawAssertions',
    'ephox.alloy.parts.PartType',
    'ephox.boulder.api.Objects',
    'ephox.boulder.api.ValueSchema',
    'ephox.peanut.Fun',
    'ephox.wrap.Jsc',
    'global!console'
  ],

  function (RawAssertions, PartType, Objects, ValueSchema, Fun, Jsc, console) {
    // { external: [ 'factory', 'schema', 'name', 'defaults', 'overrides' ] },
    //   { optional: [ 'factory', 'schema', 'name', 'pname', 'defaults', 'overrides' ] },
    //   { group: [ 'factory', 'schema', 'name', 'unit', 'pname', 'defaults', 'overrides' ] }

    var internal = PartType.internal(
      { sketch: function (x) { return 'sketch.' + x; } },
      [ ],
      'internal',
      '<part.internal>',
      function () {
        return {
          value: 10
        };
      },
      function () {
        return {
          otherValue: 15
        };
      }
    );

    var external = PartType.external(
      { sketch: function (x) { return x + '.external'; } },
      [ ],
      'external',
      Fun.constant({ defaultValue: 10 }),
      Fun.constant({ overriddenValue: 15 })
    );

    var optional = PartType.optional(
      { sketch: function (x) { return x + '.optional'; } },
      [ ],
      'optional',
      '<part.optional>',
      Fun.constant({ defaultValue: 10 }),
      Fun.constant({ overriddenValue: 15 })
    );

    // We split up the checking functions like so:
    // checkSuccessWithNone, the non-optional parts are expected, and the optional = None
    // checkSuccessWithSome, the non-optional parts are expected, and the optional is optExpected

    var checkSuccess = function (label, expected, parts, input) {
      var schemas = PartType.schemas(parts);
      var output = ValueSchema.asRawOrDie(
        label,
        ValueSchema.objOf(schemas),
        input
      );

      RawAssertions.assertEq(label, expected, output);
    };

    var checkSuccessWithNone = function (label, expected, parts, input) {
      var schemas = PartType.schemas(parts);
      var output = ValueSchema.asRawOrDie(
        label,
        ValueSchema.objOf(schemas),
        input
      );

      // We can't check Optionals with eq
      var narrowed = Objects.narrow(output, [ 'internal', 'external' ]);
      RawAssertions.assertEq('narrowed.' + label, expected, narrowed);
      RawAssertions.assertEq('checking none.' + label, true, output.optional.isNone());
    };

    var checkSuccessWithSome = function (label, expected, optExpected, parts, input) {
      var schemas = PartType.schemas(parts);
      var output = ValueSchema.asRawOrDie(
        label,
        ValueSchema.objOf(schemas),
        input
      );

      // We can't check Optionals with eq
      var narrowed = Objects.narrow(output, [ 'internal', 'external' ]);
      RawAssertions.assertEq('narrowed.' + label, expected, narrowed);
      RawAssertions.assertEq('checking some' + label, optExpected, output.optional.getOrDie(
        'Optional value was not set. Expecting: ' + optExpected
      ));
    };

    checkSuccess(
      'sanity: just internal',
      {
        internal: { entirety: 'internal.schema' }
      },
      [ internal ],
      { internal: 'internal.schema' }
    );

    checkSuccess(
      'sanity: just external',
      { external: { entirety: 'external.schema' } },
      [ external ],
      { external: 'external.schema' }
    );

    checkSuccessWithNone(
      'sanity: just optional',
      {  },
      [ optional ],
      {  }
    );

    var qcheck = function (arb, checker) {
      Jsc.check(
        Jsc.forall(arb, function (input) {
          checker(input);
          return true;
        })
      );
    };

    // MIGRATION: Use wrap-vsverify when migrating
    qcheck(Jsc.string, function (s) {
      checkSuccess(
        'just internal',
        {
          internal: { entirety: s }
        },
        [ internal ],
        { internal: s }
      );
    });

    qcheck(Jsc.string, function (s) {
      checkSuccess(
        'just external',
        {
          external: { entirety: s }
        },
        [ external ],
        { external: s }
      );
    });

  }
);
<commit_msg>VAN-44: optional and present<commit_after>test(
  'Atomic Test: parts.PartTypeSchemasTest',

  [
    'ephox.agar.api.RawAssertions',
    'ephox.alloy.parts.PartType',
    'ephox.boulder.api.Objects',
    'ephox.boulder.api.ValueSchema',
    'ephox.peanut.Fun',
    'ephox.wrap.Jsc',
    'global!console'
  ],

  function (RawAssertions, PartType, Objects, ValueSchema, Fun, Jsc, console) {
    // { external: [ 'factory', 'schema', 'name', 'defaults', 'overrides' ] },
    //   { optional: [ 'factory', 'schema', 'name', 'pname', 'defaults', 'overrides' ] },
    //   { group: [ 'factory', 'schema', 'name', 'unit', 'pname', 'defaults', 'overrides' ] }

    var internal = PartType.internal(
      { sketch: function (x) { return 'sketch.' + x; } },
      [ ],
      'internal',
      '<part.internal>',
      function () {
        return {
          value: 10
        };
      },
      function () {
        return {
          otherValue: 15
        };
      }
    );

    var external = PartType.external(
      { sketch: function (x) { return x + '.external'; } },
      [ ],
      'external',
      Fun.constant({ defaultValue: 10 }),
      Fun.constant({ overriddenValue: 15 })
    );

    var optional = PartType.optional(
      { sketch: function (x) { return x + '.optional'; } },
      [ ],
      'optional',
      '<part.optional>',
      Fun.constant({ defaultValue: 10 }),
      Fun.constant({ overriddenValue: 15 })
    );

    // We split up the checking functions like so:
    // checkSuccessWithNone, the non-optional parts are expected, and the optional = None
    // checkSuccessWithSome, the non-optional parts are expected, and the optional is optExpected

    var checkSuccess = function (label, expected, parts, input) {
      var schemas = PartType.schemas(parts);
      var output = ValueSchema.asRawOrDie(
        label,
        ValueSchema.objOf(schemas),
        input
      );

      RawAssertions.assertEq(label, expected, output);
    };

    var checkSuccessWithNone = function (label, expected, parts, input) {
      var schemas = PartType.schemas(parts);
      var output = ValueSchema.asRawOrDie(
        label,
        ValueSchema.objOf(schemas),
        input
      );

      // We can't check Optionals with eq
      var narrowed = Objects.narrow(output, [ 'internal', 'external' ]);
      RawAssertions.assertEq('narrowed.' + label, expected, narrowed);
      RawAssertions.assertEq('checking none.' + label, true, output.optional.isNone());
    };

    var checkSuccessWithSome = function (label, expected, optExpected, parts, input) {
      var schemas = PartType.schemas(parts);
      var output = ValueSchema.asRawOrDie(
        label,
        ValueSchema.objOf(schemas),
        input
      );

      // We can't check Optionals with eq
      var narrowed = Objects.narrow(output, [ 'internal', 'external' ]);
      RawAssertions.assertEq('narrowed.' + label, expected, narrowed);
      RawAssertions.assertEq('checking some' + label, optExpected, output.optional.getOrDie(
        'Optional value was not set. Expecting: ' + optExpected
      ));
    };

    checkSuccess(
      'sanity: just internal',
      {
        internal: { entirety: 'internal.schema' }
      },
      [ internal ],
      { internal: 'internal.schema' }
    );

    checkSuccess(
      'sanity: just external',
      { external: { entirety: 'external.schema' } },
      [ external ],
      { external: 'external.schema' }
    );

    checkSuccessWithNone(
      'sanity: just optional and missing',
      { },
      [ optional ],
      { }
    );

    checkSuccessWithSome(
      'sanity: just optional and present',
      { },
      { entirety: 'optional.schema' },
      [ optional ],
      { optional: 'optional.schema' }
    );

    var qcheck = function (arb, checker) {
      Jsc.check(
        Jsc.forall(arb, function (input) {
          checker(input);
          return true;
        })
      );
    };

    // MIGRATION: Use wrap-vsverify when migrating
    qcheck(Jsc.string, function (s) {
      checkSuccess(
        'just internal',
        {
          internal: { entirety: s }
        },
        [ internal ],
        { internal: s }
      );
    });

    qcheck(Jsc.string, function (s) {
      checkSuccess(
        'just external',
        {
          external: { entirety: s }
        },
        [ external ],
        { external: s }
      );
    });

  }
);
<|endoftext|>


<commit_before>/**
 * Copyright 2013 Google, Inc. All Rights Reserved.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/**
 * @fileoverview Event navigator table source.
 *
 * @author chizeng@google.com (Chi Zeng)
 */

goog.provide('wtf.replay.graphics.ui.EventNavigatorTableSource');

goog.require('wtf.db.Filter');
goog.require('wtf.ui.VirtualTableSource');

/**
 * Virtual table data source wrapping events for graphics playback.
 *
 * @param {!wtf.replay.graphics.Playback} playback The relevant playback.
 * @param {!wtf.db.EventList} eventList Event list for an entire animation.
 * @constructor
 * @extends {wtf.ui.VirtualTableSource}
 */
wtf.replay.graphics.ui.EventNavigatorTableSource = function(
    playback, eventList) {
  goog.base(this);

  /**
   * The relevant playback
   * @type {!wtf.replay.graphics.Playback}
   * @private
   */
  this.playback_ = playback;

  /**
   * Event list for an entire animation.
   * @type {!wtf.db.EventList}
   * @private
   */
  this.eventList_ = eventList;

  /**
   * Current search filter, if any.
   * @type {wtf.db.Filter}
   * @private
   */
  this.filter_ = null;

  /**
   * A set of IDs matched event types.
   * @type {!Object.<number, boolean>}
   * @private
   */
  this.matchedEventTypeIds_ = {};

  var currentStep = playback.getCurrentStep();
  var eventIterator = currentStep ? currentStep.getEventIterator(true) : null;
  var numEventsInStep = currentStep ? eventIterator.getCount() : 0;

  // Include an additional dummy row denoting the beginning of the step.
  this.setRowCount(currentStep ? numEventsInStep + 1 : 0);
};
goog.inherits(
    wtf.replay.graphics.ui.EventNavigatorTableSource,
    wtf.ui.VirtualTableSource);

/**
 * @override
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.paintRowRange =
    function(ctx, bounds, scrollBounds, rowOffset, rowHeight, first, last) {
  var currentStep = this.playback_.getCurrentStep();
  var it = currentStep ? currentStep.getEventIterator(true) : null;
  if (!it) {
    return;
  }

  this.setRowCount(currentStep ? it.getCount() + 1 : 0);
  ctx.font = '11px monospace';
  var charWidth = ctx.measureText('0').width;
  var rowCenter = rowHeight / 2 + 10 / 2;

  // Gutter.
  // TODO(benvanik): move into table as an option?
  var gutterWidth = 60;
  ctx.fillStyle = '#eeeeee';
  ctx.fillRect(0, 0, gutterWidth, bounds.height);
  var y = rowOffset;
  for (var n = first; n <= last; n++, y += rowHeight) {
    var line = String(n);
    ctx.fillStyle = 'black';
    ctx.fillText(
        line,
        gutterWidth - ((line.length + 1) * charWidth),
        Math.floor(y + rowCenter));
  }
  ctx.fillStyle = '#dddddd';
  ctx.fillRect(gutterWidth - 1, 0, 1, bounds.height);

  // Draw row contents.
  y = rowOffset;
  var color1 = '#fafafa';
  var color2 = '#ffffff';
  var highlightedColor = '#2eccfa';
  var matchedEventColor = '#ffa500';
  var x = gutterWidth + charWidth;
  var rectWidth = bounds.width - gutterWidth;

  // Iterate ahead to the event represented by the top row displayed.
  var currentRow = this.playback_.getSubStepEventId();
  var currentContextHandle = currentStep.getInitialCurrentContext();
  var contextChangingEvents = currentStep.getContextChangingEvents();
  for (var i = 1; i < first; ++i) {
    it.next();
  }

  // Get the current entry in the list of context-changing events in the step.
  var currentContextEntry = this.getContextChange_(
      currentContextHandle, contextChangingEvents, it.getIndex());

  // Get events that change the current context.
  var createContextTypeId =
      this.eventList_.getEventTypeId('wtf.webgl#createContext');
  var setContextTypeId =
      this.eventList_.getEventTypeId('wtf.webgl#setContext');

  var columnTitle = '';
  var argumentFilter = this.filter_ ? this.filter_.getArgumentFilter() : null;
  for (var n = first; n <= last && !it.done(); n++, y += rowHeight) {
    // TODO(benvanik): icons to differentiate event types?

    // Determine the background color.
    if ((currentRow == -1 && !n) || currentRow == n - 1) {
      ctx.fillStyle = highlightedColor;
    } else {
      if (n && this.filter_ && this.matchedEventTypeIds_[it.getTypeId()] &&
          (!argumentFilter || argumentFilter(it))) {
        ctx.fillStyle = matchedEventColor;
      } else {
        ctx.fillStyle = n % 2 ? color1 : color2;
      }
    }

    // Determine the text content.
    if (n) {
      if (it.isScope() || it.isInstance()) {
        // Change to the next current context if necessary.
        if (currentContextEntry < contextChangingEvents.length &&
            contextChangingEvents[currentContextEntry][0] <= it.getIndex()) {
          currentContextHandle =
              contextChangingEvents[currentContextEntry][1];
          ++currentContextEntry;
        }

        var typeId = it.getTypeId();
        if (typeId == createContextTypeId) {
          columnTitle =
              'Context with handle ' + it.getArgument('handle') + ' created.';
        } else if (typeId == setContextTypeId) {
          columnTitle =
              'Context with handle ' + it.getArgument('handle') +
                  ' set as current.';
        } else {
          var contextHandleText = (currentContextHandle != -1) ?
              currentContextHandle : 'None';
          columnTitle = it.getLongString(true) +
              ' (context handle  ' + contextHandleText + ')';
        }

        it.next();
      }
    } else {
      columnTitle = 'Beginning of step.';
    }

    ctx.fillRect(gutterWidth, y, rectWidth, rowHeight);
    ctx.fillStyle = '#000000';
    ctx.fillText(columnTitle, x, Math.floor(y + rowCenter));
  }
};

/**
 * Gets the current entry within the table of events that change the context
 * within a step based on the index of the current event.
 * @param {number} initialContextHandle The handle of the current context at
 *     the beginning of this step.
 * @param {!Array.<!Array.<number>>} contextChangingEvents A list of 2-tuples.
 *     Each 2-tuple contains the ID of a context-changing event and the new
 *     context handle.
 * @param {number} eventIndex The index of the current event.
 * @return {number} The index within the table of events.
 * @private
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.getContextChange_ =
    function(initialContextHandle, contextChangingEvents, eventIndex) {
  // Find out which context the first displayed event pertains to.
  var lowContextEntry = 0;
  var highContextEntry = contextChangingEvents.length;
  var midContextEntry = 0;
  while (lowContextEntry < highContextEntry) {
    midContextEntry = lowContextEntry +
        Math.floor((highContextEntry - lowContextEntry) / 2);
    if (contextChangingEvents[midContextEntry][0] == eventIndex) {
      break;
    } else if (contextChangingEvents[midContextEntry][0] < eventIndex) {
      lowContextEntry = midContextEntry + 1;
    } else {
      highContextEntry = midContextEntry - 1;
    }
  }

  return midContextEntry;
};

/**
 * @override
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.onClick =
    function(row, x, modifiers, bounds) {
  var playback = this.playback_;
  var currentStep = playback.getCurrentStep();
  if (!currentStep) {
    return;
  }

  // If this row reflects an event, go to it.
  if (row) {
    playback.seekSubStepEvent(row - 1);
  } else {
    // Go to the beginning of the step.
    playback.seekStep(playback.getCurrentStepIndex());
    this.invalidate();
  }

  // Redraw.
  return true;
};

/**
 * @override
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.getInfoString =
    function(row, x, bounds) {
  // TODO(chizeng): Return a useful info string.
  return '';
};

/**
 * Updates the token used to search for events.
 * @param {string} value The new value.
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.setSearchValue =
    function(value) {
  if (!value || !value.length) {
    this.filter_ = null;
    this.matchedEventTypeIds_ = {};
  } else {
    this.filter_ = new wtf.db.Filter(value);
    this.matchedEventTypeIds_ =
        this.filter_.getMatchedEventTypes(this.eventList_.eventTypeTable);
  }

  this.invalidate();
};
<commit_msg>Added a column for contexts. Fixes #401.<commit_after>/**
 * Copyright 2013 Google, Inc. All Rights Reserved.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/**
 * @fileoverview Event navigator table source.
 *
 * @author chizeng@google.com (Chi Zeng)
 */

goog.provide('wtf.replay.graphics.ui.EventNavigatorTableSource');

goog.require('goog.asserts');
goog.require('wtf.db.Filter');
goog.require('wtf.ui.VirtualTableSource');

/**
 * Virtual table data source wrapping events for graphics playback.
 *
 * @param {!wtf.replay.graphics.Playback} playback The relevant playback.
 * @param {!wtf.db.EventList} eventList Event list for an entire animation.
 * @constructor
 * @extends {wtf.ui.VirtualTableSource}
 */
wtf.replay.graphics.ui.EventNavigatorTableSource = function(
    playback, eventList) {
  goog.base(this);

  /**
   * The relevant playback
   * @type {!wtf.replay.graphics.Playback}
   * @private
   */
  this.playback_ = playback;

  /**
   * Event list for an entire animation.
   * @type {!wtf.db.EventList}
   * @private
   */
  this.eventList_ = eventList;

  /**
   * Current search filter, if any.
   * @type {wtf.db.Filter}
   * @private
   */
  this.filter_ = null;

  /**
   * A set of IDs matched event types.
   * @type {!Object.<number, boolean>}
   * @private
   */
  this.matchedEventTypeIds_ = {};

  var currentStep = playback.getCurrentStep();
  var eventIterator = currentStep ? currentStep.getEventIterator(true) : null;
  var numEventsInStep = currentStep ? eventIterator.getCount() : 0;

  // Include an additional dummy row denoting the beginning of the step.
  this.setRowCount(currentStep ? numEventsInStep + 1 : 0);
};
goog.inherits(
    wtf.replay.graphics.ui.EventNavigatorTableSource,
    wtf.ui.VirtualTableSource);

/**
 * @override
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.paintRowRange =
    function(ctx, bounds, scrollBounds, rowOffset, rowHeight, first, last) {
  var currentStep = this.playback_.getCurrentStep();
  var it = currentStep ? currentStep.getEventIterator(true) : null;
  if (!it) {
    return;
  }

  this.setRowCount(currentStep ? it.getCount() + 1 : 0);
  ctx.font = '11px monospace';
  var charWidth = ctx.measureText('0').width;
  var rowCenter = rowHeight / 2 + 10 / 2;

  // Gutter.
  // TODO(benvanik): move into table as an option?
  var gutterWidth = 60;
  ctx.fillStyle = '#eeeeee';
  ctx.fillRect(0, 0, gutterWidth, bounds.height);
  var y = rowOffset;
  for (var n = first; n <= last; n++, y += rowHeight) {
    var line = String(n);
    ctx.fillStyle = 'black';
    ctx.fillText(
        line,
        gutterWidth - ((line.length + 1) * charWidth),
        Math.floor(y + rowCenter));
  }
  ctx.fillStyle = '#dddddd';
  ctx.fillRect(gutterWidth - 1, 0, 1, bounds.height);

  // Draw row contents.
  y = rowOffset;
  var color1 = '#fafafa';
  var color2 = '#ffffff';
  var highlightedColor = '#2eccfa';
  var matchedEventColor = '#ffa500';
  var x = gutterWidth + charWidth;
  var rectWidth = bounds.width - gutterWidth;

  // Iterate ahead to the event represented by the top row displayed.
  var currentRow = this.playback_.getSubStepEventId();
  var currentContextHandle = currentStep.getInitialCurrentContext();
  var contextChangingEvents = currentStep.getContextChangingEvents();
  for (var i = 1; i < first; ++i) {
    it.next();
  }

  // Get the current entry in the list of context-changing events in the step.
  var currentContextEntry = this.getContextChange_(
      currentContextHandle, contextChangingEvents, it.getIndex());

  // Get events that change the current context.
  var createContextTypeId =
      this.eventList_.getEventTypeId('wtf.webgl#createContext');
  var setContextTypeId =
      this.eventList_.getEventTypeId('wtf.webgl#setContext');

  var columnTitle = '';
  var argumentFilter = this.filter_ ? this.filter_.getArgumentFilter() : null;
  for (var n = first; n <= last && !it.done(); n++, y += rowHeight) {
    // TODO(benvanik): icons to differentiate event types?

    // Determine the background color.
    if ((currentRow == -1 && !n) || currentRow == n - 1) {
      ctx.fillStyle = highlightedColor;
    } else {
      if (n && this.filter_ && this.matchedEventTypeIds_[it.getTypeId()] &&
          (!argumentFilter || argumentFilter(it))) {
        ctx.fillStyle = matchedEventColor;
      } else {
        ctx.fillStyle = n % 2 ? color1 : color2;
      }
    }

    // Determine the text content.
    if (n) {
      if (it.isScope() || it.isInstance()) {
        // Change to the next current context if necessary.
        if (currentContextEntry < contextChangingEvents.length &&
            contextChangingEvents[currentContextEntry][0] <= it.getIndex()) {
          currentContextHandle =
              contextChangingEvents[currentContextEntry][1];
          ++currentContextEntry;
        }

        var typeId = it.getTypeId();
        var contextHandleText = currentContextHandle != -1 ?
            currentContextHandle : 'None';
        if (typeId == createContextTypeId) {
          columnTitle =
              'New context created.';
        } else if (typeId == setContextTypeId) {
          columnTitle =
              'Context set as current.';
        } else {
          // Remove the 'WebGLRenderingContext#' prefix.
          columnTitle = it.getLongString(true).substring(22);
        }
        columnTitle = contextHandleText + ' ' + columnTitle;

        it.next();
      }
    } else {
      columnTitle = 'Beginning of step.';
    }

    ctx.fillRect(gutterWidth, y, rectWidth, rowHeight);
    ctx.fillStyle = '#000000';
    ctx.fillText(columnTitle, x, Math.floor(y + rowCenter));
  }
};

/**
 * Gets the current entry within the table of events that change the context
 * within a step based on the index of the current event.
 * @param {number} initialContextHandle The handle of the current context at
 *     the beginning of this step.
 * @param {!Array.<!Array.<number>>} contextChangingEvents A list of 2-tuples.
 *     Each 2-tuple contains the ID of a context-changing event and the new
 *     context handle.
 * @param {number} eventIndex The index of the current event.
 * @return {number} The index within the table of events.
 * @private
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.getContextChange_ =
    function(initialContextHandle, contextChangingEvents, eventIndex) {
  // Find out which context the first displayed event pertains to.
  var lowContextEntry = 0;
  var highContextEntry = contextChangingEvents.length;
  var midContextEntry = 0;
  while (lowContextEntry < highContextEntry) {
    midContextEntry = lowContextEntry +
        Math.floor((highContextEntry - lowContextEntry) / 2);
    if (contextChangingEvents[midContextEntry][0] == eventIndex) {
      break;
    } else if (contextChangingEvents[midContextEntry][0] < eventIndex) {
      lowContextEntry = midContextEntry + 1;
    } else {
      highContextEntry = midContextEntry - 1;
    }
  }

  return midContextEntry;
};

/**
 * @override
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.onClick =
    function(row, x, modifiers, bounds) {
  var playback = this.playback_;
  var currentStep = playback.getCurrentStep();
  if (!currentStep) {
    return;
  }

  // If this row reflects an event, go to it.
  if (row) {
    playback.seekSubStepEvent(row - 1);
  } else {
    // Go to the beginning of the step.
    playback.seekStep(playback.getCurrentStepIndex());
    this.invalidate();
  }

  // Redraw.
  return true;
};

/**
 * @override
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.getInfoString =
    function(row, x, bounds) {
  // The first row is a dummy row that does not represent a call.
  if (!row) {
    return '';
  }

  var currentStep = this.playback_.getCurrentStep();
  goog.asserts.assert(currentStep);
  var it = currentStep.getEventIterator(true);
  it.seek(row - 1);
  return it.getInfoString();
};

/**
 * Updates the token used to search for events.
 * @param {string} value The new value.
 */
wtf.replay.graphics.ui.EventNavigatorTableSource.prototype.setSearchValue =
    function(value) {
  if (!value || !value.length) {
    this.filter_ = null;
    this.matchedEventTypeIds_ = {};
  } else {
    this.filter_ = new wtf.db.Filter(value);
    this.matchedEventTypeIds_ =
        this.filter_.getMatchedEventTypes(this.eventList_.eventTypeTable);
  }

  this.invalidate();
};
<|endoftext|>


<commit_before>/*jshint node: true */
'use strict';

var path = require('path');
var clone = require('clone');
var dot = require('dot');

var templates = {
	evaluate: 'function (node, options) {\n<%=source%>\n}',
	after: 'function (results, options) {\n<%=source%>\n}',
	gather: 'function (context) {\n<%=source%>\n}',
	matches: 'function (node) {\n<%=source%>\n}',
};

var fns = {
	check: ['evaluate', 'after', 'matches'],
	rule: ['matches']
};

module.exports = function (grunt) {

	function parseMetaData(data) {
		var result = clone(data) || {};
		if (result.failureMessage) {
			result.failureMessage = dot.template(result.failureMessage).toString();
		}
		return result;
	}

	function createCheckObject(checks) {
		var result = {};
		checks.forEach(function (check) {
			result[check.id] = check;
		});
		return result;
	}

	function replaceFunctions(string) {
		return string.replace(/"(evaluate|after|gather|matches)":\s*("[^"]+")/g, function (m, p1, p2) {
			return m.replace(p2, getSource(p2.replace(/^"|"$/g, ''), p1));
		}).replace(/"(function anonymous\(it(?:\n?\/\*\*\/)?\) {)(.+?)(})"/g, function (m, p1, p2, p3) {
			return p1 + (p2.replace(/\\(n|r|t)/g, ' ').replace(/\\\\/g, '\\')) + p3;
		});
	}

	function getSource(file, type) {
		return grunt.template.process(templates[type], {
			data: {
				source: grunt.file.read(file)
			}
		});
	}

	function parseObject(src, type) {
		var files = grunt.file.expand(src);
		return files.map(function (file) {
			var json = grunt.file.readJSON(file);
			var dirname = path.dirname(file);
			fns[type].forEach(function (name) {
				if (json[name]) {
					json[name] = path.resolve(dirname, json[name]);
				}
			});
			return json;
		});
	}

	function findCheck(checks, id) {
		return checks.filter(function (check) {
			if (check.id === id) {
				return true;
			}
		})[0];
	}

	grunt.registerMultiTask('rules', function () {

		function blacklist(k, v) {
			if (options.blacklist.indexOf(k) !== -1) {
				return undefined;
			}
			return v;
		}

		var metadata = {
			rules: {},
			checks: {}
		};

		var options = this.options({
			rules: ['lib/rules/**/*.json'],
			checks: ['lib/checks/**/*.json'],
			blacklist: ['metadata', 'tags'],
			standards: ''
		});

		var standards = options.standards ? options.standards.split(/\s*,\s*/) : [];

		var rules = parseObject(options.rules, 'rule');

		if (standards.length) {
			rules = rules.filter(function (r) {
				return r.tags.filter(function (t) {
					return standards.indexOf(t) !== -1;
				}).length;
			});
		}
		var checks = parseObject(options.checks, 'check');

		rules.map(function (rule) {
			rule.checks = rule.checks.map(function (check) {

				var id = typeof check === 'string' ? check : check.id;
				var c = clone(findCheck(checks, id));
				if (!c) throw new Error('check ' + id + ' not found');
				c.options = check.options || c.options;

				if (c.metadata && !metadata.checks[id]) {
					metadata.checks[id] = parseMetaData(c.metadata);
				}

				return c;
			});
			if (rule.metadata && !metadata.rules[rule.id]) {
				metadata.rules[rule.id] = parseMetaData(rule.metadata);
			}
			return rule;
		});
		var r = replaceFunctions(JSON.stringify({ data: metadata, rules: rules }, blacklist));
		var c = replaceFunctions(JSON.stringify(createCheckObject(checks), blacklist));

		grunt.file.write(this.data.dest.rules, 'dqre.configure(' + r + ');');
		grunt.file.write(this.data.dest.checks, 'var checks = ' + c + ';');

	});
};
<commit_msg>Update regex again<commit_after>/*jshint node: true */
'use strict';

var path = require('path');
var clone = require('clone');
var dot = require('dot');

var templates = {
	evaluate: 'function (node, options) {\n<%=source%>\n}',
	after: 'function (results, options) {\n<%=source%>\n}',
	gather: 'function (context) {\n<%=source%>\n}',
	matches: 'function (node) {\n<%=source%>\n}',
};

var fns = {
	check: ['evaluate', 'after', 'matches'],
	rule: ['matches']
};

module.exports = function (grunt) {

	function parseMetaData(data) {
		var result = clone(data) || {};
		if (result.failureMessage) {
			result.failureMessage = dot.template(result.failureMessage).toString();
		}
		return result;
	}

	function createCheckObject(checks) {
		var result = {};
		checks.forEach(function (check) {
			result[check.id] = check;
		});
		return result;
	}

	function replaceFunctions(string) {
		return string.replace(/"(evaluate|after|gather|matches)":\s*("[^"]+")/g, function (m, p1, p2) {
			return m.replace(p2, getSource(p2.replace(/^"|"$/g, ''), p1));
		}).replace(/"(function anonymous\([\s\S]+?\) {)([\s\S]+?)(})"/g, function (m, p1, p2, p3) {
			return p1 + (p2.replace(/\\(n|r|t)/g, ' ').replace(/\\\\/g, '\\')) + p3;
		});
	}

	function getSource(file, type) {
		return grunt.template.process(templates[type], {
			data: {
				source: grunt.file.read(file)
			}
		});
	}

	function parseObject(src, type) {
		var files = grunt.file.expand(src);
		return files.map(function (file) {
			var json = grunt.file.readJSON(file);
			var dirname = path.dirname(file);
			fns[type].forEach(function (name) {
				if (json[name]) {
					json[name] = path.resolve(dirname, json[name]);
				}
			});
			return json;
		});
	}

	function findCheck(checks, id) {
		return checks.filter(function (check) {
			if (check.id === id) {
				return true;
			}
		})[0];
	}

	grunt.registerMultiTask('rules', function () {

		function blacklist(k, v) {
			if (options.blacklist.indexOf(k) !== -1) {
				return undefined;
			}
			return v;
		}

		var metadata = {
			rules: {},
			checks: {}
		};

		var options = this.options({
			rules: ['lib/rules/**/*.json'],
			checks: ['lib/checks/**/*.json'],
			blacklist: ['metadata', 'tags'],
			standards: ''
		});

		var standards = options.standards ? options.standards.split(/\s*,\s*/) : [];

		var rules = parseObject(options.rules, 'rule');

		if (standards.length) {
			rules = rules.filter(function (r) {
				return r.tags.filter(function (t) {
					return standards.indexOf(t) !== -1;
				}).length;
			});
		}
		var checks = parseObject(options.checks, 'check');

		rules.map(function (rule) {
			rule.checks = rule.checks.map(function (check) {

				var id = typeof check === 'string' ? check : check.id;
				var c = clone(findCheck(checks, id));
				if (!c) throw new Error('check ' + id + ' not found');
				c.options = check.options || c.options;

				if (c.metadata && !metadata.checks[id]) {
					metadata.checks[id] = parseMetaData(c.metadata);
				}

				return c;
			});
			if (rule.metadata && !metadata.rules[rule.id]) {
				metadata.rules[rule.id] = parseMetaData(rule.metadata);
			}
			return rule;
		});
		var r = replaceFunctions(JSON.stringify({ data: metadata, rules: rules }, blacklist));
		var c = replaceFunctions(JSON.stringify(createCheckObject(checks), blacklist));

		grunt.file.write(this.data.dest.rules, 'dqre.configure(' + r + ');');
		grunt.file.write(this.data.dest.checks, 'var checks = ' + c + ';');

	});
};
<|endoftext|>