<commit_before>const electron = require('electron')
const app = electron.app
const globalShortcut = electron.globalShortcut
const ipcMain = electron.ipcMain
const nativeImage = electron.nativeImage
const BrowserWindow = electron.BrowserWindow

app.setName("Requesto");

if (app.dock) {
    app.dock.setIcon(nativeImage.createFromPath("resources/icon.png"));
    // app.dock.setBadge("1");
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
    mainWindow = new BrowserWindow({
        background: "#1d1e26",
        title: "Requesto",
        center: true,
    })
    // mainWindow.webContents.openDevTools()
    mainWindow.maximize()
    mainWindow.loadURL(`file://${__dirname}/dist/index.html`)
    mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null
    })

    //TODO: remove console.log
    globalShortcut.register('Command+W', () => {
        console.log('Command+W is pressed');
    })

    console.log('Command+W : ',globalShortcut.isRegistered('Command+W'));
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function() {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<commit_msg>remove unused code<commit_after>const electron = require('electron')
const app = electron.app
const globalShortcut = electron.globalShortcut
const ipcMain = electron.ipcMain
const nativeImage = electron.nativeImage
const BrowserWindow = electron.BrowserWindow

app.setName("Requesto");

if (app.dock) {
    app.dock.setIcon(nativeImage.createFromPath("resources/icon.png"));
    // app.dock.setBadge("1");
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
    mainWindow = new BrowserWindow({
        background: "#1d1e26",
        title: "Requesto",
        center: true,
    })
    // mainWindow.webContents.openDevTools()
    mainWindow.maximize()
    mainWindow.loadURL(`file://${__dirname}/dist/index.html`)
    mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null
    })

    // Shortcuts
    globalShortcut.register('Command+W', () => {});
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function() {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<|endoftext|>


<commit_before>{
    init: function(elevators, floors) {
        // "Constants" =========================================================
        var settings = {
            FULL: 4
        };

        // Queue Definition ====================================================
        var Queue = function() {
            var FloorQ = function() {
                    _waiting = 0;
                    return {
                        get: function() { return _waiting; },
                        add: function() { _waiting++; },
                        clear: function() { _waiting = 0; }
                    }
                },
                _floor = [];

            floors.forEach(function(floor, idx) {
                _floor[floor.floorNum()] = new FloorQ();
            });

            return {
                get: function(floorNum) { return _floor[floorNum].get(); },
                add: function(floorNum) {
                    _floor[floorNum].add();
                    console.log(floorNum + ' incremented to ' + _floor[floorNum].get());
                },
                clear: function(floorNum) {
                    console.log(floorNum + ' cleared from ' + _floor[floorNum].get());
                    _floor[floorNum].clear();
                },
                highest: function() {
                    for (var i=floors.length-1;i>=0;i--) {
                        if (_floor[floors[i].floorNum()].get() > 0) {
                            return floors[i].floorNum();
                        }
                    }
                },
                lowest: function() {
                    for (var i=0;i<floors.length;i++) {
                        if (_floor[floors[i].floorNum()].get() > 0) {
                            return floors[i].floorNum();
                        }
                    }
                },
                most: function() {
                    var retFloor = -1,
                        retNum = 0;

                    for (var i=0;i<floors.length;i++) {
                        if (_floor[floors[i].floorNum()].get() > retNum) {
                            retFloor = floors[i].floorNum();
                            retNum = _floor[floors[i].floorNum()].get();
                        }
                    }

                    return {
                        floorNum: retFloor,
                        requests: retNum
                    };
                },
                count: function() {
                    var sum = 0;
                    for (var i=0;i<floors.length;i++) {
                        sum += _floor[floors[i].floorNum()].get();
                    }
                    return sum;
                }
            };
        };

        // Queue Variables =====================================================
        var downQueue = new Queue(),
            upQueue = new Queue();

        // Utility Functions ===================================================
        var elevatorOnTheWay = function(floorNum) {
            var queue = [];
            elevators.forEach(function(elevator, i) {
                queue.concat(elevator.destinationQueue);
            });
            return (queue.indexOf(floorNum) > -1);
        };

        var closestRequest = function(floorNum) {
            var next = -1,
                mostUp = upQueue.most(),
                mostDown = downQueue.most();

            if ((mostUp.requests == settings.FULL)&&(mostDown.requests == settings.FULL)) {
                var closerUp = Math.abs(floorNum - mostUp.floorNum),
                    closerDown = Math.abs(floorNum - mostDown.floorNum);

                next = (closerUp < closerDown)
                    ? mostUp.floorNum
                    : mostDown.floorNum;

            } else if (mostUp.requests == settings.FULL) {
                next = mostUp.floorNum;

            } else if (mostDown.requests == settings.FULL) {
                next = mostDown.floorNum;

            } else if ((upQueue.count() > 0)&&(downQueue.count() > 0)) { // If both queues have values, choose whichever is closer
                var closestUp = Math.abs(floorNum - upQueue.lowest()),
                    closestDown = Math.abs(floorNum - downQueue.highest());

                next = (closestUp < closestDown)
                    ? upQueue.lowest()
                    : downQueue.highest();

            } else if (upQueue.length > 0) {
                next = upQueue.lowest();
            } else if (downQueue.length > 0) {
                next = downQueue.highest();
            }

            return next;
        };

        // Elevator Code =======================================================
        elevators.forEach(function(elevator, idx) {
            elevator.on("idle", function() {
                var waitForInstructions = setInterval(function () {
                    var nextBest = closestRequest(elevator.currentFloor());

                    if ((nextBest > -1)&&(!elevatorOnTheWay(nextBest))) {
                        elevator.goToFloor(nextBest);
                        clearInterval(waitForInstructions);
                    } else {
                        //debugger;
                    }
                }, 500);
            });

            elevator.on("floor_button_pressed", function(floorNum) {
                elevator.goToFloor(floorNum);
            });

            elevator.on("passing_floor", function(floorNum, direction) {
                if (elevator.destinationQueue.indexOf(floorNum) > -1) {
                    elevator.goToFloor(floorNum, true);
                }
            });

            elevator.on("stopped_at_floor", function(floorNum) {
                var idx = elevator.destinationQueue.indexOf(floorNum);
                if (idx > -1) {
                    elevator.destinationQueue.slice(idx,1);
                }

                upQueue.clear(floorNum);
                downQueue.clear(floorNum);
            });
        });

        // Floor Code ==========================================================
        floors.forEach(function(floor, idx) {
            floor.on("up_button_pressed", function() {
                upQueue.add(floor.floorNum());
            });

            floor.on("down_button_pressed", function() {
                downQueue.add(floor.floorNum());
            });
        });
    },
    update: function(dt, elevators, floors) {
        // We normally don't need to do anything here
    }
}<commit_msg>Refactor, v0.2<commit_after>{
    init: function(elevators, floors) {
        // "Constants" =========================================================
        var settings = {
            FULL: 4,
            BOTTOM_FLOOR: 0,
            TOP_FLOOR: floors.length - 1,
            NUM_ELEVATORS: elevators.length - 1
        };

        // Floor Code ==========================================================
        floors.forEach(function(floor, floor_index) {
            /** Elevator Properties ********************************************
             *  - floorNum()
             ******************************************************************/
            floor.queueUp = 0;
            floor.queueDown = 0;
            floor.upClaimed = -1;
            floor.downClaimed = -1;

            // Floor Events ----------------------------------------------------
            floor.on("up_button_pressed", function() {
                // Triggered when someone has pressed the up button at a floor.
                // Note that passengers will press the button again if they fail to enter an elevator.
                this.queueUp++;

                var available = masterQueue.availableElevator(floor.floorNum(),"up");
                if (available > -1) {
                    floor.upClaimed = available;
                    elevators[available].goUp(floor.floorNum());
                }
            });
            floor.on("down_button_pressed", function() {
                // Triggered when someone has pressed the down button at a floor.
                // Note that passengers will press the button again if they fail to enter an elevator.
                this.queueDown++;

                var available = masterQueue.availableElevator(floor.floorNum(),"down");
                if (available > -1) {
                    floor.downClaimed = available;
                    elevators[available].goDown(floor.floorNum());
                }
            });
        });

        // Master Queue Code ===================================================
        var masterQueue = (function() {
            var _downQueue = function() {
                var _queue = [],
                    _topDown = -1;

                // Check All Floors
                floors.forEach(function (floor, fidx) {
                    _queue[fidx] = floor.queueDown;
                    _topDown = (floor.queueDown > 0)
                        ? fidx
                        : _topDown;
                });

                return {
                    queue: _queue,
                    topDown: _topDown
                };
            };

            var _upQueue = function() {
                var _queue = [],
                    _bottomUp = -1;

                // Check All Floors
                floors.forEach(function(floor, fidx) {
                    _queue[fidx] = floor.queueUp;
                    _bottomUp = ((floor.queueUp > 0) && (_bottomUp === -1))
                        ? fidx
                        : _bottomUp;
                });

                return {
                    queue: _queue,
                    bottomUp: _bottomUp
                };
            };

            var _refreshAvailableElevator = function(floorNum, direction) {
                // Clear Queue
                var bestElevator = -1,
                    availableElevators = [],
                    availability = -1,
                    bestAvailablility = -1;

                // Check All Elevators
                elevators.forEach(function(elevator, eidx) {
                    availability = elevator.available(floorNum, direction);

                    if (availability > bestAvailablility) {
                        bestElevator = eidx;
                        bestAvailablility = availability;
                    }
                });

                return bestElevator;
            };

            return {
                queue: function() {
                    var up = _upQueue(),
                        down = _downQueue();

                    return {
                        up: up.queue,
                        down: down.queue,
                        topDown: up.topDown,
                        bottomUp: down.bottomUp
                    };
                },
                downQueue: function() {
                    return _downQueue();
                },
                upQueue: function() {
                    return _upQueue();
                },
                availableElevator: function(floorNum, direction) {
                    return _refreshAvailableElevator(floorNum, direction);
                }
            }
        })();

        // Elevator Code =======================================================
        elevators.forEach(function(elevator, elevator_index) {
            /** Elevator Properties ********************************************
             *  - goToFloor(floorNum, [force])
             *  - stop()
             *  - currentFloor()
             *  - goingUpIndicator([set])
             *  - goingDownIndicator([set])
             *  - loadFactor()
             *  - destinationQueue
             *  - checkDestinationQueue()
             ******************************************************************/

            elevator.direction = "";
            elevator.goingTo = -1;

            // Pretend In-car Lights (for floors) pressed
            elevator.buttons = (function() {
                var _lights = [];

                return {
                    press: function(floorNum) {
                        if (!this.isLit) {
                            _lights.push(floorNum);
                            _lights.sort();
                        }
                    },
                    clear: function(floorNum) {
                        var i = _lights.indexOf(floorNum);
                        if (i > -1) {
                            _lights = _lights.splice(i, 1);
                        }

                        do {
                            i = elevator.destinationQueue.indexOf(floorNum);
                            if (i > -1) {
                                elevator.destinationQueue.splice(i, 1);
                            }
                        } while (i > -1);
                        elevator.checkDestinationQueue();
                    },
                    isLit: function(floorNum) {
                        var i = _lights.indexOf(floorNum);
                        return (i > -1);
                    }
                }
            })();

            elevator.queueLength = function() {
                return elevator.destinationQueue.length;
            };

            elevator.newQueue = function() {
                elevator.direction = "";
                elevator.goingTo = -1;
                elevator.goingUpIndicator(false);
                elevator.goingDownIndicator(false);
            };

            elevator.goUp = function(floorNum) {
                elevator.direction = "up";
                elevator.goingUpIndicator(true);
                elevator.goingDownIndicator(false);

                if (floorNum) {
                    elevator.goToFloor(floorNum);

                    elevator.goingTo = (floorNum > elevator.goingTo)
                        ? floorNum
                        : elevator.goingTo;
                }
            };

            elevator.goDown = function(floorNum) {
                elevator.direction = "down";
                elevator.goingDownIndicator(true);
                elevator.goingUpIndicator(false);

                if (floorNum) {
                    elevator.goToFloor(floorNum);

                    elevator.goingTo = (elevator.goingTo === -1 || floorNum < elevator.goingTo)
                        ? floorNum
                        : elevator.goingTo;
                }
            };

            elevator.available = function(floorNum, direction) {
                /* Returns a weighted availability
                 *    2 : elevator already on its way
                 *    1 : idle, feel free
                 *    0 : busy, but might be going past
                 *   -1 : going the other way past this floor, not available
                 */

                // If the elevator is idle, it is available for use
                if (elevator.queueLength() === 0) {
                    return 1;
                }

                // If the elevator is heading to this floor, it's a candidate
                if (elevator.goingTo === floorNum) {
                    return 2;
                }

                // If the elevator is going past in the other direction, it's not available right now
                if ((elevator.direction === "up" && direction === "down" && elevator.goingTo > floorNum) ||
                   (elevator.direction === "down" && direction === "up" && elevator.goingTo < floorNum)) {

                    return -1;
                }

                // TODO: Maybe add some logic about capacity?
                return 0;
            };

            // Elevator Events -------------------------------------------------
            elevator.on("idle", function() {
                // Triggered when the elevator has completed all its tasks and is not doing anything.
                elevator.newQueue();
                debugger;

                var queue = masterQueue.queue(),
                    floorNum = elevator.currentFloor();

                if ((Math.abs(floorNum - queue.topDown)) < (Math.abs(floorNum - queue.bottomUp))) {
                    elevator.goDown(queue.topDown);
                } else {
                    elevator.goUp(queue.bottomUp);
                }
            });

            elevator.on("floor_button_pressed", function(floorNum) {
                // Triggered when a passenger has pressed a button inside the elevator.
                if (elevator.direction === '') {
                    if (elevator.floorNum() < floorNum) {
                        elevator.goUp();
                    } else {
                        elevator.goDown();
                    }
                }

                elevator.buttons.press(floorNum);
                elevator.goToFloor(floorNum);

                // Make sure that the elevator stops at the floors in order (depending on the direction)
                elevator.destinationQueue.sort();
                if (elevator.direction === "down") {
                    elevator.destinationQueue.reverse();
                }
                elevator.checkDestinationQueue();
            });

            elevator.on("passing_floor", function(floorNum, direction) {
                // Triggered slightly before the elevator will pass a floor. A good time to decide
                // whether to stop at that floor. Note that this event is not triggered for the
                // destination floor. Direction is either "up" or "down".
                var floor = floors[floorNum];

                // Don't even think about stopping if you're on the way to a farther floor to go
                // the opposite direction
                if (direction !== elevator.direction) {
                    return false;
                }

                if (direction === "down") {
                    if ((floor.downQueue > 0) &&
                        ((floor.downClaimed === -1) || (floor.downClaimed === elevator.elevator_index))) {

                        elevator.goToFloor(floorNum, true);
                    }
                } else { // direction === "up"
                    if ((floor.upQueue > 0) &&
                        ((floor.upClaimed === -1) || (floor.upClaimed === elevator.elevator_index))) {

                        elevator.goToFloor(floorNum, true);
                    }
                }
            });

            elevator.on("stopped_at_floor", function(floorNum) {
                // Triggered when the elevator has arrived at a floor.
                switch (floorNum) {
                    case settings.BOTTOM_FLOOR:
                        elevator.goUp();
                        break;

                    case settings.TOP_FLOOR:
                        elevator.goDown();
                        break;

                    default:
                        // do nothing special, yet
                        break;
                };

                elevator.buttons.clear(floorNum);
                if (elevator.direction === "up") {
                    floors[floorNum].upQueue = 0;
                } else if (elevator.direction === "down") {
                    floors[floorNum].downQueue = 0;
                }
            });
        });
    },
    update: function(dt, elevators, floors) {
        // We normally don't need to do anything here
    }
}<|endoftext|>


<commit_before>{
    init: function(elevators, floors) {
      _.each(floors, function(f) {
          f.on("down_button_pressed", function(event) {

          });

          f.on("up_button_pressed", function(event) {

          });
      });

      _.each(elevators, function(e) {
        e.on("idle", function() {
            e.goToFloor(0);
        });

        e.on("floor_button_pressed", function(floorNum) {
            e.goToFloor(floorNum);
        });

        e.on("passing_floor", function(floorNum, direction) {

        });

        e.on("stopped_at_floor", function(floorNum) {

        });
      });
    },

    update: function(dt, elevators, floors) {
    }
}
<commit_msg>Very basic logic<commit_after>{
    init: function(elevators, floors) {
        var requests = new Array();

        _.each(floors, function(f) {
            f.on("down_button_pressed", function(event) {
                requests.push(f.floorNum());
            });

            f.on("up_button_pressed", function(event) {
                requests.push(f.floorNum());
            });
        });

        _.each(elevators, function(e) {
            e.on("idle", function() {
                if (_.isEmpty(requests)) {
                    e.goToFloor(0);
                } else {
                    e.goToFloor(requests.pop());
                }
            });

            e.on("floor_button_pressed", function(floorNum) {
                e.goToFloor(floorNum);
            });

            e.on("passing_floor", function(floorNum, direction) {
                if (_.contains(requests, floorNum)) {
                    e.stop();
                }
            });

            e.on("stopped_at_floor", function(floorNum) {
                _.without(requests, _.findWhere(requests, floorNum));
            });
        });
    },

    update: function(dt, elevators, floors) {
    }
}
<|endoftext|>


<commit_before>exports.node = {
  encode: function(val) {
    return new Buffer(JSON.stringify(val))
  },
  decode: function(buf) {
    return JSON.parse(buf.toString())
  }
}

exports.replicate = {
  encode: function(val) {
    return new Buffer(JSON.stringify(val))
  },
  decode: function(buf) {
    return new Buffer(JSON.parse(val))
  }
}<commit_msg>remove unused json encoder<commit_after><|endoftext|>


<commit_before>module.exports = function (bot) {

    bot.on(PlugAPI.events.MODERATE_WLBAN, function (data) {

        if (config.verboseLogging) {
            console.log('[EVENT] modWaitlistBan ', JSON.stringify(data, null, 2));
        }

        if (data.user == undefined) {
            console.log('[WARNING] data.user was undefined in modWaitlistBan event');
        }

        var duration = 'unknown';
        switch (data.duration) {
            case 'Short':
                duration = '15 min';
                break;
            case 'Medium':
                duration = '30 min';
                break;
            case 'Long':
                duration = '45 min';
                break;
            case 'Forever':
                duration = 'forever';
                break;
            default:
                // maybe this is an unmute?
                break;
        }

        getDbUserFromUsername(data.user.username, function (dbUser) {
            var message;
            if (duration == 'unknown') {
                message = '[WLUNBAN] ' + data.user.username + ' (ID: ' + data.user.id + ') was unbanned from the waitlist by ' + data.moderator.username;
            } else if (dbUser == null) {
                message = '[WLBAN] ' + data.user.username + ' (ID: ' + data.user.id + ') was banned from the waitlist for ' + duration + ' by ' + data.moderator.username;
            } else {
                message = '[WLBAN] ' + data.user.username + ' (ID: ' + data.user.id + ', LVL: ' + dbUser.site_points + ') was banned from the waitlist for ' + duration + ' by ' + data.moderator.username;
            }
            console.log(message);
            sendToWebhooks(message);
        });
    });

};
<commit_msg>Punt out of modWaitListBan if data.user is undefined<commit_after>module.exports = function (bot) {

    bot.on(PlugAPI.events.MODERATE_WLBAN, function (data) {

        if (config.verboseLogging) {
            console.log('[EVENT] modWaitlistBan ', JSON.stringify(data, null, 2));
        }

        if (data.user == undefined) {
            console.log('[WARNING] data.user was undefined in modWaitlistBan event');
            return;
        }

        var duration = 'unknown';
        switch (data.duration) {
            case 'Short':
                duration = '15 min';
                break;
            case 'Medium':
                duration = '30 min';
                break;
            case 'Long':
                duration = '45 min';
                break;
            case 'Forever':
                duration = 'forever';
                break;
            default:
                // maybe this is an unmute?
                break;
        }

        getDbUserFromUsername(data.user.username, function (dbUser) {
            var message;
            if (duration == 'unknown') {
                message = '[WLUNBAN] ' + data.user.username + ' (ID: ' + data.user.id + ') was unbanned from the waitlist by ' + data.moderator.username;
            } else if (dbUser == null) {
                message = '[WLBAN] ' + data.user.username + ' (ID: ' + data.user.id + ') was banned from the waitlist for ' + duration + ' by ' + data.moderator.username;
            } else {
                message = '[WLBAN] ' + data.user.username + ' (ID: ' + data.user.id + ', LVL: ' + dbUser.site_points + ') was banned from the waitlist for ' + duration + ' by ' + data.moderator.username;
            }
            console.log(message);
            sendToWebhooks(message);
        });
    });

};
<|endoftext|>


<commit_before>require('jquery');
require('jquery-mobile');
require('jquery.cookie');

// for flat-ui
require('jquery-ui');
require('jquery-ui-touch-punch');
require('../bower_components/bootstrap/dist/js/bootstrap.js');
require('bootstrap-switch');
require('bootstrap-tagsinput');
// require('holderjs');
// require('typeahead.js');
require('select2');
require('../bower_components/flat-ui/js/radiocheck.js');

import * as shiren4 from '../es6/model/shiren4.js';

$(() => {
  if (location.pathname == '/shiren4/') {
    $(':checkbox').checkboxradio();

    $('a.reset-checkboxes').click(() => {
      if(window.confirm('リセットしますか？'))
        clearCheckboxes();
    });

    loadFromCookie();
    $(':checkbox').change(() => saveToCookie());
  }
});

// Clear CheckBoxes "{{{1

var clearCheckboxes = () => {
  $(':checkbox')
  .prop('checked', false)
  .checkboxradio('refresh');

  saveToCookie();
};

// Save/Load Cookie Data "{{{1

var loadFromCookie = () => {
  if (typeof getCookie() === "undefined") return;

  var cookieData = JSON.parse(getCookie());
  Object.keys(cookieData)
  .forEach((key) => {
    $(`#${key} :checkbox`)
    .each((index, elem) =>
      $(elem)
      .prop('checked', cookieData[key][$(elem).data('id')])
      .checkboxradio('refresh')
    );
  });
};

var saveToCookie = () => {
  var ary = {};
    $(':checkbox')
    .each((index, val) => {
      var t = $(val).data('type');
      if (!(t in ary))
        ary[t] = {};
      ary[t][$(val).data('id')] = $(val).prop('checked');
    });
  var json = JSON.stringify(ary);
  setCookie(json);
};

var setCookie = (data) => {
  var thirtyDaysLater = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
  document.cookie = `data=${encodeURIComponent(data)};path=${location.pathname};expires=${thirtyDaysLater.toGMTString()}`;
}

var getCookie = () => {
	if (!document.cookie) return;

  var targetCookie =
    document.cookie
    .split("; ")
    .map((elem) => {
      var str = elem.split('=');
      return {key: str[0], value: str[1]};
    })
    .filter((cookie) => cookie.key == 'data');

  if (!targetCookie.some((cookie) => cookie.key == 'data')) return;

  return decodeURIComponent(targetCookie[0].value);
}

// __END__  "{{{1
// vim: expandtab softtabstop=2 shiftwidth=2
// vim: foldmethod=marker
<commit_msg>main.js: Add CookieManager<commit_after>require('jquery');
require('jquery-mobile');
require('jquery.cookie');

// for flat-ui
require('jquery-ui');
require('jquery-ui-touch-punch');
require('../bower_components/bootstrap/dist/js/bootstrap.js');
require('bootstrap-switch');
require('bootstrap-tagsinput');
// require('holderjs');
// require('typeahead.js');
require('select2');
require('../bower_components/flat-ui/js/radiocheck.js');

import * as shiren4 from '../es6/model/shiren4.js';

$(() => {
  if (location.pathname == '/shiren4/') {
    $(':checkbox').checkboxradio();

    $('a.reset-checkboxes').click(() => {
      if(window.confirm('リセットしますか？'))
        clearCheckboxes();
    });

    loadFromCookie();
    $(':checkbox').change(() => saveToCookie());
  }
});

// Clear CheckBoxes "{{{1

var clearCheckboxes = () => {
  $(':checkbox')
  .prop('checked', false)
  .checkboxradio('refresh');

  saveToCookie();
};

// Save/Load Cookie Data "{{{1

class CookieManager {
  constructor(doc) {
    this.doc = doc;
  }
}

var loadFromCookie = () => {
  if (typeof getCookie() === "undefined") return;

  var cookieData = JSON.parse(getCookie());
  Object.keys(cookieData)
  .forEach((key) => {
    $(`#${key} :checkbox`)
    .each((index, elem) =>
      $(elem)
      .prop('checked', cookieData[key][$(elem).data('id')])
      .checkboxradio('refresh')
    );
  });
};

var saveToCookie = () => {
  var ary = {};
    $(':checkbox')
    .each((index, val) => {
      var t = $(val).data('type');
      if (!(t in ary))
        ary[t] = {};
      ary[t][$(val).data('id')] = $(val).prop('checked');
    });
  var json = JSON.stringify(ary);
  setCookie(json);
};

var setCookie = (data) => {
  var thirtyDaysLater = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
  document.cookie = `data=${encodeURIComponent(data)};path=${location.pathname};expires=${thirtyDaysLater.toGMTString()}`;
}

var getCookie = () => {
	if (!document.cookie) return;

  var targetCookie =
    document.cookie
    .split("; ")
    .map((elem) => {
      var str = elem.split('=');
      return {key: str[0], value: str[1]};
    })
    .filter((cookie) => cookie.key == 'data');

  if (!targetCookie.some((cookie) => cookie.key == 'data')) return;

  return decodeURIComponent(targetCookie[0].value);
}

// __END__  "{{{1
// vim: expandtab softtabstop=2 shiftwidth=2
// vim: foldmethod=marker
<|endoftext|>


<commit_before>(function(define) {
'use strict';
define(function(require) {

   var Frame, Value;

   Frame = require('./frame');
   Value = require('./value');

   function Evaluate() {
      this.global = Frame.newGlobal();
   }

   Evaluate.prototype = {
      eval: function(node) {
         return evalInFrame(node, this.global);
      }
   };

   // "runs" a certain node to completion.
   // Emits the resulting value
   function evalInFrame(node, frame) {
      switch (node.name) {
      case 'number': return Value.make_numeric(node.args[0]);
      case 'range': return evalInFrame(node.args[0], frames); // FIXME
      case 'arithop':
         return do_arith(node.args[0],
                         evalInFrame(node.args[1], frame),
                         evalInFrame(node.args[2], frame));
      case 'var':
         return lookup(node.args[0], frame);
      case 'assign':
         return assign(node.args[0].args[0],
                       evalInFrame(node.args[1], frame),
                       frame);
      case 'assign_inherit':
         return assignInherit(node.args[0].args[0],
                              evalInFrame(node.args[1], frame),
                              frame);
      case 'fun_def':
         // TODO: Need to do some checking to ensure argument list
         // is valid
         return Value.make_closure(node, frame);
      case 'expr_seq':
         return eval_seq(node.args[0], frame);
      case 'fun_call':
         return eval_call(evalInFrame(node.args[0], frame),
                          eval_actuals(node.args[1], frame));
      default:
         throw new Error('Unknown node: ' + node.name);
      }
   }

   function lookup(symbol, frame) {
      var val;

      val = frame.lookup(symbol);
      if (val === null) {
         throw new Error("Unknown property: ", symbol);
      }
      if (Array.isArray(val)) { return val; } // Case of "..."
      return val.resolve();
   }
   // Assigns value in the current frame (possibly shadowing existing value)
   function assign(symbol, value, frame) {
      frame.store(symbol, value);

      return value;
   }
   // Assigns value to whichever frame in the inheritance chain the
   // value is defined. If the value is not defined in a previous
   // frame, it will be created as a global value.
   // TODO: What about protecting functions like "c"?
   function assignInherit(symbol, value, frame) {
      while (!frame.hasOwnProperty(symbol) &&
             frame.getParent() !== null) {
         frame = frame.getParent();
      }
      frame.store(symbol, value);

      return value;
   }

   function eval_seq(exprs, frame) {
      var i, val;

      for (i = 0; i < exprs.length; i += 1) {
         val = evalInFrame(exprs[i], frame);
      }
      return val;
   }

   // Evaluates the actuals represented by the array of exprs
   // in the current frame. It also takes care to properly transform "..."
   // If it is present (it would have a value from the current function call).
   function eval_actuals(exprs, frame) {
      var actuals, symbols;

      symbols = {}; // Used to make sure the same symbol is not provided twice.
      actuals = [];

      exprs.forEach(function(expr) {
         switch (expr.name) {
         case 'actual':
            actuals.push({ value: evalInFrame(expr.args[0], frame) });
            break;
         case 'actual_named':
            if (symbols.hasOwnProperty(expr.args[0])) {
               throw new Error('symbol occurred twice');
            }
            symbols[expr.args[0]] = evalInFrame(expr.args[1], frame);
            actuals.push({ name: expr.args[0],
                           value: symbols[expr.args[0]] });
            break;
         case 'actual_dots':
            // Need to look for a defined dots in the immediate environment
            actuals = actuals.concat(lookup('...', frame));
            break; // TODO
         default:
            throw new Error('actual expected, but got' + expr.type);
         }
      });

      return actuals;
   }

   // "actuals" will be an array of objects.
   // Each object has a property "value" corresponding to the value of that
   // actual, and also possibly a property "name" if it was a named parameter.
   function eval_call(clos, actuals) {
      var formals, body, closExtFrame, i, result, actualPos;
      if (clos.type !== 'closure') {
         throw new Error('trying to call non-closure');
      }
      // Will be messing with the array of formals, so need to copy it
      formals = clos.value.func.args[0].slice();
      body = clos.value.func.args[1];
      closExtFrame = clos.value.env.extend();

      // Go through actuals, see if they are named and match a formal
      // Compares the i-th element in the actuals list to the j-th element
      // in the formals list. It adjusts the arrays if necessary.
      function matchNamed(i, j) {
         if (i >= actuals.length) { return; }
         if (!actuals[i].hasOwnProperty('name')) { return matchNamed(i + 1, 0); }
         if (j >= formals.length) { return matchNamed(i + 1, 0); }
         if ((formals[j].name === 'arg' ||
              formals[j].name === 'arg_default') &&
             formals[j].args[0] === actuals[i].name) {
            // found match
            closExtFrame.store(formals[j].args[0], actuals[i].value);
            formals.splice(j, 1);
            actuals.splice(i, 1);
            // i-th spot now contains the next entry
            return matchNamed(i, 0);
         }
         return matchNamed(i, j + 1);
      }
      matchNamed(0, 0);

      // At this point named arguments have been matched and removed from
      // both lists.
      // Any remaining named actuals may still be absorbed by "...""
      // We match remaining arguments by position skipping named
      // actuals, until we encounter "..."
      // If there is a remaining dots argument, we need to bind it to "..."
      // If there are other remaining arguments they need to be bound to a
      // "missing" value, which if accessed should raise error.
      actualPos = 0; // Holds the place in the actuals that contains the
                     // first nonnamed actual.
      while (formals.length !== 0) {
         while (actualPos < actuals.length &&
                actuals[actualPos].hasOwnProperty('name')) {
            actualPos += 1; // Find first unnamed argument
         }
         if (formals[0].name === 'arg_dots') {
            // Need to eat up all remaining actuals.
            closExtFrame.store('...', actuals);
            actuals = [];
         } else if (actualPos < actuals.length) {
            // There is a value to read
            closExtFrame.store(formals[0].args[0], actuals[actualPos].value);
            actuals.splice(actualPos, 1);
         } else if (formals[0].name === 'arg_default') {
            // Need to evaluate the default value
            // Cannot evaluate right away because it might depend on
            // later defaults. Must create a promise. It will not be
            // executed unless needed.
            closExtFrame.store(
               formals[0].args[0],
               Value.make_promise(
                  evalInFrame.bind(null, formals[0].args[1], closExtFrame)
               )
            );
         } else {
            // Need to set to missing value
            closExtFrame.store(formals[0].args[0], Value.make_missing());
         }
         formals.splice(0, 1);
      }

      return evalInFrame(body, closExtFrame);
   }

   function do_arith(op, v1, v2) {
      if (v1.type !== 'numeric' || v2.type !== 'numeric') {
         throw new Error('operating on non-numeric values');
      }
      switch (op) {
         case '+': return Value.make_numeric(v1.value + v2.value);
         case '-': return Value.make_numeric(v1.value - v2.value);
         case '*': return Value.make_numeric(v1.value * v2.value);
         case '/': return Value.make_numeric(v1.value / v2.value);
      }
   }

   return Evaluate;

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<commit_msg>Prepare for adding builtins<commit_after>(function(define) {
'use strict';
define(function(require) {

   var Frame, Value;

   Frame = require('./frame');
   Value = require('./value');

   function Evaluate() {
      this.global = Frame.newGlobal();
   }

   Evaluate.prototype = {
      eval: function(node) {
         return evalInFrame(node, this.global);
      }
   };

   // "runs" a certain node to completion.
   // Emits the resulting value
   function evalInFrame(node, frame) {
      switch (node.name) {
      case 'number': return Value.make_numeric(node.args[0]);
      case 'range': return evalInFrame(node.args[0], frames); // FIXME
      case 'arithop':
         return do_arith(node.args[0],
                         evalInFrame(node.args[1], frame),
                         evalInFrame(node.args[2], frame));
      case 'var':
         return lookup(node.args[0], frame);
      case 'assign':
         return assign(node.args[0].args[0],
                       evalInFrame(node.args[1], frame),
                       frame);
      case 'assign_inherit':
         return assignInherit(node.args[0].args[0],
                              evalInFrame(node.args[1], frame),
                              frame);
      case 'fun_def':
         // TODO: Need to do some checking to ensure argument list
         // is valid
         return Value.make_closure(node, frame);
      case 'expr_seq':
         return eval_seq(node.args[0], frame);
      case 'fun_call':
         return eval_call(evalInFrame(node.args[0], frame),
                          eval_actuals(node.args[1], frame));
      default:
         throw new Error('Unknown node: ' + node.name);
      }
   }

   function lookup(symbol, frame) {
      var val;

      val = frame.lookup(symbol);
      if (val === null) {
         throw new Error("Unknown property: ", symbol);
      }
      if (Array.isArray(val)) { return val; } // Case of "..."
      return val.resolve();
   }
   // Assigns value in the current frame (possibly shadowing existing value)
   function assign(symbol, value, frame) {
      frame.store(symbol, value);

      return value;
   }
   // Assigns value to whichever frame in the inheritance chain the
   // value is defined. If the value is not defined in a previous
   // frame, it will be created as a global value.
   // TODO: What about protecting functions like "c"?
   function assignInherit(symbol, value, frame) {
      while (!frame.hasOwnProperty(symbol) &&
             frame.getParent() !== null) {
         frame = frame.getParent();
      }
      frame.store(symbol, value);

      return value;
   }

   function eval_seq(exprs, frame) {
      var i, val;

      for (i = 0; i < exprs.length; i += 1) {
         val = evalInFrame(exprs[i], frame);
      }
      return val;
   }

   // Evaluates the actuals represented by the array of exprs
   // in the current frame. It also takes care to properly transform "..."
   // If it is present (it would have a value from the current function call).
   function eval_actuals(exprs, frame) {
      var actuals, symbols;

      symbols = {}; // Used to make sure the same symbol is not provided twice.
      actuals = [];

      exprs.forEach(function(expr) {
         switch (expr.name) {
         case 'actual':
            actuals.push({ value: evalInFrame(expr.args[0], frame) });
            break;
         case 'actual_named':
            if (symbols.hasOwnProperty(expr.args[0])) {
               throw new Error('symbol occurred twice');
            }
            symbols[expr.args[0]] = evalInFrame(expr.args[1], frame);
            actuals.push({ name: expr.args[0],
                           value: symbols[expr.args[0]] });
            break;
         case 'actual_dots':
            // Need to look for a defined dots in the immediate environment
            actuals = actuals.concat(lookup('...', frame));
            break; // TODO
         default:
            throw new Error('actual expected, but got' + expr.type);
         }
      });

      return actuals;
   }

   // "actuals" will be an array of objects.
   // Each object has a property "value" corresponding to the value of that
   // actual, and also possibly a property "name" if it was a named parameter.
   function eval_call(clos, actuals) {
      if (clos.type === 'closure') {
         return eval_closure(clos, actuals);
      } else if (close.type === 'builtin') {
         return eval_builtin(clos, actuals);
      }
      throw new Error('trying to call non-function');
   }

   // "Builtin" functions are Javascript functions. They expect one argument
   // that is a "list" in the panthrBase sense.
   // We need here to turn "actuals" into that list.
   function eval_builtin(f, actuals) {
      // TODO
   }

   function eval_closure(clos, actuals) {
      var formals, body, closExtFrame, i, result, actualPos;
      // Will be messing with the array of formals, so need to copy it
      formals = clos.value.func.args[0].slice();
      body = clos.value.func.args[1];
      closExtFrame = clos.value.env.extend();

      // Go through actuals, see if they are named and match a formal
      // Compares the i-th element in the actuals list to the j-th element
      // in the formals list. It adjusts the arrays if necessary.
      function matchNamed(i, j) {
         if (i >= actuals.length) { return; }
         if (!actuals[i].hasOwnProperty('name')) { return matchNamed(i + 1, 0); }
         if (j >= formals.length) { return matchNamed(i + 1, 0); }
         if ((formals[j].name === 'arg' ||
              formals[j].name === 'arg_default') &&
             formals[j].args[0] === actuals[i].name) {
            // found match
            closExtFrame.store(formals[j].args[0], actuals[i].value);
            formals.splice(j, 1);
            actuals.splice(i, 1);
            // i-th spot now contains the next entry
            return matchNamed(i, 0);
         }
         return matchNamed(i, j + 1);
      }
      matchNamed(0, 0);

      // At this point named arguments have been matched and removed from
      // both lists.
      // Any remaining named actuals may still be absorbed by "...""
      // We match remaining arguments by position skipping named
      // actuals, until we encounter "..."
      // If there is a remaining dots argument, we need to bind it to "..."
      // If there are other remaining arguments they need to be bound to a
      // "missing" value, which if accessed should raise error.
      actualPos = 0; // Holds the place in the actuals that contains the
                     // first nonnamed actual.
      while (formals.length !== 0) {
         while (actualPos < actuals.length &&
                actuals[actualPos].hasOwnProperty('name')) {
            actualPos += 1; // Find first unnamed argument
         }
         if (formals[0].name === 'arg_dots') {
            // Need to eat up all remaining actuals.
            closExtFrame.store('...', actuals);
            actuals = [];
         } else if (actualPos < actuals.length) {
            // There is a value to read
            closExtFrame.store(formals[0].args[0], actuals[actualPos].value);
            actuals.splice(actualPos, 1);
         } else if (formals[0].name === 'arg_default') {
            // Need to evaluate the default value
            // Cannot evaluate right away because it might depend on
            // later defaults. Must create a promise. It will not be
            // executed unless needed.
            closExtFrame.store(
               formals[0].args[0],
               Value.make_promise(
                  evalInFrame.bind(null, formals[0].args[1], closExtFrame)
               )
            );
         } else {
            // Need to set to missing value
            closExtFrame.store(formals[0].args[0], Value.make_missing());
         }
         formals.splice(0, 1);
      }

      return evalInFrame(body, closExtFrame);
   }

   function do_arith(op, v1, v2) {
      if (v1.type !== 'numeric' || v2.type !== 'numeric') {
         throw new Error('operating on non-numeric values');
      }
      switch (op) {
         case '+': return Value.make_numeric(v1.value + v2.value);
         case '-': return Value.make_numeric(v1.value - v2.value);
         case '*': return Value.make_numeric(v1.value * v2.value);
         case '/': return Value.make_numeric(v1.value / v2.value);
      }
   }

   return Evaluate;

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<|endoftext|>


<commit_before>function EvDa(a){function G(a){return a.match(/[?*]/)}function H(a,b){return G(a)?p(m(b?b:B),function(b){return b.match(a)}):a}function I(a,b){var c={};return d(a)?(j(a,function(a){c[a]=b(a)}),c):b(a)}function J(a){if(a in B)return B[a];var b=a.split("."),c=b.pop(),d=b.join(".");if(d){var e=J(d);if(h(e)&&c in e)return e[c]}}function K(a,c,f,g){if(g=g||{},0===arguments.length)return{data:B,events:F,globs:E};if(d(a)){var i=b.call(arguments,1);return r(a,function(a){return K.apply(K.context,[a].concat(i))})}if(h(a)){var k={};return g.noexec=1,j(a,function(a,b){k[a]=K(a,b,f,g)}),g.bypass||j(k,function(b){e(k[b])&&!e(a[b])&&(a[b]=k[b]())}),O(m(k)[0]),a}return 1==arguments.length?I(a,J):K[e(c)||d(c)&&e(c[0])?v:"set"].apply(this,arguments)}function L(a){j(a.$,function(b){var c=G(b)?E:F;c[b]=n(c[b],a)})}function M(a,b,c){if(d(a)){var e=a.pop();return M(H(e),function(c,d){var e=1==a.length?a[0]:a;return M(e,b,d)},c)}if(h(a))return j(a,function(b,d){G(b)?t(b,I(b,function(){return M(b,d,c)})):a[b]=M(b,d,c)}),a;var f="set"+a;return F[f]&&(F[f](function(b){K.set.call(K.context,a,b,c)}),delete F[f]),b?a in B?b.call(K.context,B[a],c):K(a,b,t(c||{},y)):a in B}function N(a,b,c,d){a.S||(a.call(b,c,d),a.once&&L(a))}function O(a){var c=a.split("."),d=c.pop();parts_obj=[],parts_obj[d]=B[a],K.extend.apply(K.context,[c.join("."),parts_obj].concat(b.call(arguments,1)))}var b=Array.prototype.slice,c=Object.prototype.toString,d=[].isArray||function(a){return"[object Array]"===c.call(a)},e=function(a){return!!(a&&a.constructor&&a.call&&a.apply)},f=function(a){return!!(""===a||a&&a.charCodeAt&&a.substr)},g=function(a){return"[object Number]"===c.call(a)},h=function(a){return e(a)||f(a)||g(a)||d(a)?!1:null==a?"object"==String(a):"[object Object]"===c.call(a)||!0},i=function(a){return b.call(a)},j=[].forEach?function(a,b){if(d(a)||a.length)i(a).forEach(b);else for(var c in a)b(c,a[c])}:function(a,b){if(d(a))for(var c=0,e=a.length;e>c;c++)b(a[c],c);else for(var f in a)b(f,a[f])},k=function(a){return a.length?a[a.length-1]:void 0},l=function(a){var b=[];for(var c in a)b.push(a[c]);return b},m={}.keys||function(a){if(d(a))return a;var b=[];for(var c in a)b.push(c);return b},n=function(a,b){var c=[];return j(a,function(a){a!==b&&c.push(a)}),c},o=function(a){var b,c=[];return j(m(a).sort(),function(a){a!=b&&(b=a,c.push(a))}),c},p=function(a,b){var c=[];return j(a,function(a){b(a)&&c.push(a)}),c},q=function(a){return a&&"length"in a?a.length:0},r=[].map?function(a,b){return a.map(b)}:function(a,b){for(var c=[],d=0,e=a.length;e>d;d++)c.push(b(a[d],d));return c},s=function(a){return d(a)?b.call(a):h(a)?t(a,{}):a},t=function(a){return j(b.call(arguments,1),function(b){for(var c in b)void 0!==b[c]&&(a[c]=b[c])}),a},u="first",v="on",w="after",x=[u,v,w,"test","or"],y={once:1},z={},A={},B=a||{},D=[],E={},F={};return j(x,function(a){K[a]=function(c,d,e){if(_.isArray(d)){var f=b.call(arguments,2);return r(d,function(b){return K[a].apply(K.context,[c,b].concat(f))})}var g=F;return d?((d.$||(d.$=[])).push(a+c),G(c)&&(g=E),(g[a+c]||(g[a+c]=[])).push(d),t(d,e)):g[a+c]}}),t(K,{_:{},context:this,list:{},isPaused:!1,db:B,events:function(a,b){return b?F[b+a]:a?I(x.concat(["set"]),function(b){return F[b+a]}):F},del:L,whenSet:M,isset:M,pause:function(){return K.isPaused?!1:(K.isPaused=!0,K._.set=K.set,K.set=function(){D.push(["set",arguments])},!0)},play:function(){if(K.isPaused){K.isPaused=!1;var a=EvDa();return K.set=K._.set,j(D,function(b){a[b[0]].apply(a,b[1])}),D=[],K(a.db),!0}return!1},setter:function(a,b){return F["set"+a]=b,F[v+a]?M(a):void 0},when:function(a,c,g){if(h(a)){var i={},k={},m=function(a,b){k[b.key]=!1,b()},n=function(a,d){k[d.key]=!0,-1==l(k).indexOf(!1)&&c.apply(K.context,b.call(arguments))};return j(a,function(a,b){i[a+"-test"]=K.test(a,m),i[a]=K.when(a,b,n),k[a]=!1}),i}if(f(c))try{var o=new Function("x","return x"+c);o(),c=o}catch(p){}return K(a,function(a){(d(c)&&c.sort().join("")===a.sort().join("")||e(c)&&c(a)||a===c)&&g.apply(K.context,b.call(arguments))})},empty:function(){for(var a in B)delete B[a]},incr:function(a,b,c){return b=b||1,K.set(a,g(B[a])?B[a]+b:b,c)},decr:function(a,b,c){return b=b||1,K.set(a,B[a]-b||0,c)},push:function(a,b,c){return K.set(a,[].concat(B[a]||[],[b]),c)},pop:function(a,b){return K.set(a,B[a].slice(0,-1),b)},traceList:[],group:function(a){var b=i(arguments),a=b.shift(),c=K.apply(0,b);return K.list[a]||(K.list[a]=[]),e(c)?K.list[a].push(c):j(c,function(b){K.list[a].push(b)}),function(){return K.group.apply(0,[a].concat(i(arguments)))}},extend:function(a,c){return K.set.apply(K.context,[a,t({},B[a]||{},c)].concat(b.call(arguments,2)))},set:function(a,c,d,e){e=e||{};var f,g=e.bypass,h=e.coroutine||function(){return!0},i="value"in e,k=e.noexec;if(1==arguments.length){var l=function(){K.set.apply(K.context,[a].concat(b.call(arguments)))};return K.set.call(K.context,a,void 0),l}if(z[a]>0)return B[a];z[a]=(z[a]||0)+1;var n,y,m="test"+a,o=b.call(arguments),p=q(F[m]),r=0,x=p&&!g,C=function(){j(F["or"+a]||[],function(a){N(a,K.context,i?e.value:D.value,D)})},D=x?function(b){return y|=b===!1,--p?(r++,h(D,!1)?(f=F[m][r].call(K.context,i?e.value:D.value,D),(f===!0||f===!1)&&D(f)):C()):y?C():h(D,!0)?K.set(a,D.value,D.meta,{bypass:1}):C(),b}:{};if(D.old=s(B[a]),t(D,{meta:d||{},done:D,result:D,key:a,value:c}),x)z[a]--,A[a]!==!0&&(A[a]=!0,h(D,!1)?(f=F[m][r].call(K.context,i?e.value:D.value,D),(f===!0||f===!1)&&D(f)):C(),A[a]=!1),n=B[a];else{if(j(K.traceList,function(a){a.call(K.context,o)}),!h(D,!0))return n;c=D.value,B[a]=c;var E=arguments,G=function(){return j((F[u+a]||[]).concat(F[v+a]||[]),function(a){D.last=N(a,K.context,c,D)}),a.length>0&&O.apply(K.context,[a].concat(b.call(E,2))),j(F[w+a]||[],function(a){D.last=N(a,K.context,c,D)}),c};n=k?G:G.call(K.context)}return z[a]=0,n},fire:function(a){K.set(a,B[a])},once:function(a,b,c){return h(a)&&(a=l(a)),d(a)?r(a,function(a){K.once.call(K.context,a,b,c)}):b?K.once(K(a,b,c)):t(a,y)},enable:function(a){return j(K.list[a],function(b){b.S&&b.S[a]&&delete b.S[a],0==q(b.S)&&delete b.S}),K.list[a]},osetadd:function(a,b,c){var e=B[a]||[];return K(a,b,c,{coroutine:function(a,b){var c=d(a.value)?a.value:[a.value];return a.set=s(e),j(c,function(b){-1==a.set.indexOf(b)&&a.set.push(b)}),b&&(a.value=a.set),e.length!=a.set.length}})},setadd:function(a,b,c){var e=B[a]||[];return K(a,b,c,{coroutine:function(a,b){var c=d(a.value)?a.value:[a.value];return a.set=o(e.concat(c)),b&&(a.value=a.set),e.length!=a.set.length}})},setdel:function(a,b,c){var d=B[a]||[],e=n(d,b);return d.length!=e.length?K(a,e,c,{value:b}):e},disable:function(a){return j(K.list[a],function(b){(b.S||(b.S={}))[a]=!0}),K.list[a]},unset:function(){var a=!0;return j(arguments,function(b){a&=b in B;var g,h,i,c=b.split("."),d="",e=c.length,f=c[e-1];for(g=0;e>g;g++)if(d=c.slice(0,g).join("."),i=B[d]){for(h=g;e-1>h;h++)i=i[c[h]];delete i[f]}delete B[b]}),a},find:function(a){return p(m(B),function(b){return b.match(a)})},changed:function(a,b){return K.on(a,function(a,c){var d=q(a),e=q(c.old);1==d-e?b.call(K.context,k(a)):d>e&&b.call(K.context,i(a).slice(e))})},sniff:function(){var a={},b=+new Date,c=function(c){a[c[0]]||console.log(+new Date-b,c)},d=function(){},e=c;K.traceList.unshift(function(a){e(a)}),K.sniff=function(b){return arguments.length>0?f(b)?(a[b]=!a[b],"[Un]ignoring "+b):(e=b?c:d,b):m(a)}}}),K.setAdd=K.setadd,K.osetAdd=K.osetadd,K.setDel=K.setdel,K.isSet=K.isset,K.get=K,K.change=K.on,K.add=K.push,K.isArray=d,K}<commit_msg>minified version<commit_after>function EvDa(a){function G(a){return a.match(/[?*]/)}function H(a,b){return G(a)?p(m(b?b:B),function(b){return b.match(a)}):a}function I(a,b){var c={};return d(a)?(j(a,function(a){c[a]=b(a)}),c):b(a)}function J(a){if(a in B)return B[a];var b=a.split("."),c=b.pop(),d=b.join(".");if(d){var e=J(d);if(h(e)&&c in e)return e[c]}}function K(a,c,f,g){if(0===arguments.length)return{data:B,events:F,globs:E};if(d(a)){var i=b.call(arguments,1);return r(a,function(a){return K.apply(K.context,[a].concat(i))})}if(h(a)){var k={};return g=f||{},f=c,g.noexec=1,j(a,function(a,b){k[a]=K(a,b,f,g)}),g.bypass||j(k,function(b){e(k[b])&&!e(a[b])&&(a[b]=k[b]())}),O(m(k)[0]),a}return 1==arguments.length?I(a,J):K[e(c)||d(c)&&e(c[0])?v:"set"].apply(this,arguments)}function L(a){j(a.$,function(b){var c=G(b)?E:F;c[b]=n(c[b],a)})}function M(a,b,c){if(d(a)){var e=a.pop();return M(H(e),function(c,d){var e=1==a.length?a[0]:a;return M(e,b,d)},c)}if(h(a))return j(a,function(b,d){G(b)?t(b,I(b,function(){return M(b,d,c)})):a[b]=M(b,d,c)}),a;var f="set"+a;return F[f]&&(F[f](function(b){K.set.call(K.context,a,b,c)}),delete F[f]),b?a in B?b.call(K.context,B[a],c):K(a,b,t(c||{},y)):a in B}function N(a,b,c,d){a.S||(a.call(b,c,d),a.once&&L(a))}function O(a){var c=a.split("."),d=c.pop();parts_obj=[],parts_obj[d]=B[a],K.extend.apply(K.context,[c.join("."),parts_obj].concat(b.call(arguments,1)))}var b=Array.prototype.slice,c=Object.prototype.toString,d=[].isArray||function(a){return"[object Array]"===c.call(a)},e=function(a){return!!(a&&a.constructor&&a.call&&a.apply)},f=function(a){return!!(""===a||a&&a.charCodeAt&&a.substr)},g=function(a){return"[object Number]"===c.call(a)},h=function(a){return e(a)||f(a)||g(a)||d(a)?!1:null==a?"object"==String(a):"[object Object]"===c.call(a)||!0},i=function(a){return b.call(a)},j=[].forEach?function(a,b){if(d(a)||a.length)i(a).forEach(b);else for(var c in a)b(c,a[c])}:function(a,b){if(d(a))for(var c=0,e=a.length;e>c;c++)b(a[c],c);else for(var f in a)b(f,a[f])},k=function(a){return a.length?a[a.length-1]:void 0},l=function(a){var b=[];for(var c in a)b.push(a[c]);return b},m={}.keys||function(a){if(d(a))return a;var b=[];for(var c in a)b.push(c);return b},n=function(a,b){var c=[];return j(a,function(a){a!==b&&c.push(a)}),c},o=function(a){var b,c=[];return j(m(a).sort(),function(a){a!=b&&(b=a,c.push(a))}),c},p=function(a,b){var c=[];return j(a,function(a){b(a)&&c.push(a)}),c},q=function(a){return a&&"length"in a?a.length:0},r=[].map?function(a,b){return a.map(b)}:function(a,b){for(var c=[],d=0,e=a.length;e>d;d++)c.push(b(a[d],d));return c},s=function(a){return d(a)?b.call(a):h(a)?t(a,{}):a},t=function(a){return j(b.call(arguments,1),function(b){for(var c in b)void 0!==b[c]&&(a[c]=b[c])}),a},u="first",v="on",w="after",x=[u,v,w,"test","or"],y={once:1},z={},A={},B=a||{},D=[],E={},F={};return j(x,function(a){K[a]=function(c,d,e){if(_.isArray(d)){var f=b.call(arguments,2);return r(d,function(b){return K[a].apply(K.context,[c,b].concat(f))})}var g=F;return d?((d.$||(d.$=[])).push(a+c),G(c)&&(g=E),(g[a+c]||(g[a+c]=[])).push(d),t(d,e)):g[a+c]}}),t(K,{_:{},context:this,list:{},isPaused:!1,db:B,events:function(a,b){return b?F[b+a]:a?I(x.concat(["set"]),function(b){return F[b+a]}):F},del:L,whenSet:M,isset:M,pause:function(){return K.isPaused?!1:(K.isPaused=!0,K._.set=K.set,K.set=function(){D.push(["set",arguments])},!0)},play:function(){if(K.isPaused){K.isPaused=!1;var a=EvDa();return K.set=K._.set,j(D,function(b){a[b[0]].apply(a,b[1])}),D=[],K(a.db),!0}return!1},setter:function(a,b){return F["set"+a]=b,F[v+a]?M(a):void 0},when:function(a,c,g){if(h(a)){var i={},k={},m=function(a,b){k[b.key]=!1,b()},n=function(a,d){k[d.key]=!0,-1==l(k).indexOf(!1)&&c.apply(K.context,b.call(arguments))};return j(a,function(a,b){i[a+"-test"]=K.test(a,m),i[a]=K.when(a,b,n),k[a]=!1}),i}if(f(c))try{var o=new Function("x","return x"+c);o(),c=o}catch(p){}return K(a,function(a){(d(c)&&c.sort().join("")===a.sort().join("")||e(c)&&c(a)||a===c)&&g.apply(K.context,b.call(arguments))})},empty:function(){for(var a in B)delete B[a]},incr:function(a,b,c){return b=b||1,K.set(a,g(B[a])?B[a]+b:b,c)},decr:function(a,b,c){return b=b||1,K.set(a,B[a]-b||0,c)},push:function(a,b,c){return K.set(a,[].concat(B[a]||[],[b]),c)},pop:function(a,b){return K.set(a,B[a].slice(0,-1),b)},traceList:[],group:function(a){var b=i(arguments),a=b.shift(),c=K.apply(0,b);return K.list[a]||(K.list[a]=[]),e(c)?K.list[a].push(c):j(c,function(b){K.list[a].push(b)}),function(){return K.group.apply(0,[a].concat(i(arguments)))}},extend:function(a,c){return K.set.apply(K.context,[a,t({},B[a]||{},c)].concat(b.call(arguments,2)))},set:function(a,c,d,e){e=e||{};var f,g=e.bypass,h=e.coroutine||function(){return!0},i="value"in e,k=e.noexec;if(1==arguments.length){var l=function(){K.set.apply(K.context,[a].concat(b.call(arguments)))};return K.set.call(K.context,a,void 0),l}if(z[a]>0)return B[a];z[a]=(z[a]||0)+1;var n,y,m="test"+a,o=b.call(arguments),p=q(F[m]),r=0,x=p&&!g,C=function(){j(F["or"+a]||[],function(a){N(a,K.context,i?e.value:D.value,D)})},D=x?function(b){return y|=b===!1,--p?(r++,h(D,!1)?(f=F[m][r].call(K.context,i?e.value:D.value,D),(f===!0||f===!1)&&D(f)):C()):y?C():h(D,!0)?K.set(a,D.value,D.meta,{bypass:1}):C(),b}:{};if(D.old=s(B[a]),t(D,{meta:d||{},done:D,result:D,key:a,value:c}),x)z[a]--,A[a]!==!0&&(A[a]=!0,h(D,!1)?(f=F[m][r].call(K.context,i?e.value:D.value,D),(f===!0||f===!1)&&D(f)):C(),A[a]=!1),n=B[a];else{if(j(K.traceList,function(a){a.call(K.context,o)}),!h(D,!0))return n;c=D.value,B[a]=c;var E=arguments,G=function(){return j((F[u+a]||[]).concat(F[v+a]||[]),function(a){D.last=N(a,K.context,c,D)}),a.length>0&&O.apply(K.context,[a].concat(b.call(E,2))),j(F[w+a]||[],function(a){D.last=N(a,K.context,c,D)}),c};n=k?G:G.call(K.context)}return z[a]=0,n},fire:function(a){K.set(a,B[a])},once:function(a,b,c){return h(a)&&(a=l(a)),d(a)?r(a,function(a){K.once.call(K.context,a,b,c)}):b?K.once(K(a,b,c)):t(a,y)},enable:function(a){return j(K.list[a],function(b){b.S&&b.S[a]&&delete b.S[a],0==q(b.S)&&delete b.S}),K.list[a]},osetadd:function(a,b,c){var e=B[a]||[];return K(a,b,c,{coroutine:function(a,b){var c=d(a.value)?a.value:[a.value];return a.set=s(e),j(c,function(b){-1==a.set.indexOf(b)&&a.set.push(b)}),b&&(a.value=a.set),e.length!=a.set.length}})},setadd:function(a,b,c){var e=B[a]||[];return K(a,b,c,{coroutine:function(a,b){var c=d(a.value)?a.value:[a.value];return a.set=o(e.concat(c)),b&&(a.value=a.set),e.length!=a.set.length}})},setdel:function(a,b,c){var d=B[a]||[],e=n(d,b);return d.length!=e.length?K(a,e,c,{value:b}):e},disable:function(a){return j(K.list[a],function(b){(b.S||(b.S={}))[a]=!0}),K.list[a]},unset:function(){var a=!0;return j(arguments,function(b){a&=b in B;var g,h,i,c=b.split("."),d="",e=c.length,f=c[e-1];for(g=0;e>g;g++)if(d=c.slice(0,g).join("."),i=B[d]){for(h=g;e-1>h;h++)i=i[c[h]];delete i[f]}delete B[b]}),a},find:function(a){return p(m(B),function(b){return b.match(a)})},changed:function(a,b){return K.on(a,function(a,c){var d=q(a),e=q(c.old);1==d-e?b.call(K.context,k(a)):d>e&&b.call(K.context,i(a).slice(e))})},sniff:function(){var a={},b=+new Date,c=function(c){a[c[0]]||console.log(+new Date-b,c)},d=function(){},e=c;K.traceList.unshift(function(a){e(a)}),K.sniff=function(b){return arguments.length>0?f(b)?(a[b]=!a[b],"[Un]ignoring "+b):(e=b?c:d,b):m(a)}}}),K.setAdd=K.setadd,K.osetAdd=K.osetadd,K.setDel=K.setdel,K.isSet=K.isset,K.get=K,K.change=K.on,K.add=K.push,K.isArray=d,K}<|endoftext|>


<commit_before>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.EventKit = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});
class CompositeDisposable {
  constructor() {
    this.disposed = false;
    this.disposables = new Set(arguments);
  }
  dispose() {
    if (!this.disposed) {
      this.disposed = true;
      this.disposables.forEach(function (item) {
        item.dispose();
      });
      this.disposables = null;
    }
  }
  add() {
    var _this = this;

    if (!this.disposed) {
      Array.prototype.forEach.call(arguments, function (item) {
        return _this.disposables.add(item);
      });
    }
  }
  remove() {
    var _this2 = this;

    if (!this.disposed) {
      Array.prototype.forEach.call(arguments, function (item) {
        return _this2.disposables.delete(item);
      });
    }
  }
  clear() {
    if (!this.disposed) {
      this.disposables.clear();
    }
  }
}
exports.CompositeDisposable = CompositeDisposable;
},{}],2:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});
class Disposable {
  constructor(callback) {
    this.disposed = false;
    this.callback = callback;
  }
  dispose() {
    if (!this.disposed) {
      this.disposed = true;
      if (typeof this.callback === 'function') {
        this.callback();
      }
      this.callback = null;
    }
  }
}
exports.Disposable = Disposable;
},{}],3:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Emitter = undefined;

var _disposable = require('./disposable');

class Emitter {
  constructor() {
    this.disposed = false;
    this.handlers = {};
  }
  dispose() {
    this.disposed = true;
    this.handlers = null;
  }
  on(eventName, handler) {
    var _this = this;

    if (this.disposed) {
      throw new Error('Emitter has been disposed');
    }
    if (typeof handler !== 'function') {
      throw new Error('Event handler must be a function');
    }
    if (typeof this.handlers[eventName] === 'undefined') {
      this.handlers[eventName] = [handler];
    } else {
      this.handlers[eventName].push(handler);
    }
    return new _disposable.Disposable(function () {
      _this.off(eventName, handler);
    });
  }
  off(eventName, handler) {
    if (this.disposed || typeof this.handlers[eventName] === 'undefined') {
      return;
    }
    const index = this.handlers[eventName].indexOf(handler);
    if (index !== -1) {
      this.handlers[eventName].splice(index, 1);
    }
  }
  clear() {
    this.handlers = [];
  }
  emit(eventName) {
    for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      params[_key - 1] = arguments[_key];
    }

    if (this.disposed || typeof this.handlers[eventName] === 'undefined') {
      return;
    }
    const paramsLength = params.length;
    this.handlers[eventName].forEach(function (callback) {
      if (paramsLength === 1) {
        callback(params[0]);
      } else if (paramsLength === 2) {
        callback(params[0], params[1]);
      } else {
        callback.apply(undefined, params);
      }
    });
  }
}
exports.Emitter = Emitter;
},{"./disposable":2}],4:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _disposable = require('./disposable');

Object.defineProperty(exports, 'Disposable', {
  enumerable: true,
  get: function () {
    return _disposable.Disposable;
  }
});

var _compositeDisposable = require('./composite-disposable');

Object.defineProperty(exports, 'CompositeDisposable', {
  enumerable: true,
  get: function () {
    return _compositeDisposable.CompositeDisposable;
  }
});

var _emitter = require('./emitter');

Object.defineProperty(exports, 'Emitter', {
  enumerable: true,
  get: function () {
    return _emitter.Emitter;
  }
});
},{"./composite-disposable":1,"./disposable":2,"./emitter":3}]},{},[4])(4)
});<commit_msg>:arrow_up: Upgrade dist file<commit_after>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.EventKit = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});
class CompositeDisposable {
  constructor() {
    this.disposed = false;
    this.disposables = new Set(arguments);
  }
  dispose() {
    if (!this.disposed) {
      this.disposed = true;
      this.disposables.forEach(function (item) {
        item.dispose();
      });
      this.disposables = null;
    }
  }
  add() {
    var _this = this;

    if (!this.disposed) {
      Array.prototype.forEach.call(arguments, function (item) {
        return _this.disposables.add(item);
      });
    }
  }
  remove() {
    var _this2 = this;

    if (!this.disposed) {
      Array.prototype.forEach.call(arguments, function (item) {
        return _this2.disposables.delete(item);
      });
    }
  }
  clear() {
    if (!this.disposed) {
      this.disposables.clear();
    }
  }
}
exports.CompositeDisposable = CompositeDisposable;
},{}],2:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});
class Disposable {
  constructor(callback) {
    this.disposed = false;
    this.callback = callback;
  }
  dispose() {
    if (!this.disposed) {
      this.disposed = true;
      if (typeof this.callback === 'function') {
        this.callback();
      }
      this.callback = null;
    }
  }
}
exports.Disposable = Disposable;
},{}],3:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Emitter = undefined;

var _disposable = require('./disposable');

class Emitter {
  constructor() {
    this.disposed = false;
    this.handlers = {};
  }
  dispose() {
    this.disposed = true;
    this.handlers = null;
  }
  on(eventName, handler) {
    var _this = this;

    if (this.disposed) {
      throw new Error('Emitter has been disposed');
    }
    if (typeof handler !== 'function') {
      throw new Error('Event handler must be a function');
    }
    if (typeof this.handlers[eventName] === 'undefined') {
      this.handlers[eventName] = [handler];
    } else {
      this.handlers[eventName].push(handler);
    }
    return new _disposable.Disposable(function () {
      _this.off(eventName, handler);
    });
  }
  off(eventName, handler) {
    if (this.disposed || typeof this.handlers[eventName] === 'undefined') {
      return;
    }
    const index = this.handlers[eventName].indexOf(handler);
    if (index !== -1) {
      this.handlers[eventName].splice(index, 1);
    }
  }
  clear() {
    this.handlers = [];
  }
  emit(eventName) {
    for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      params[_key - 1] = arguments[_key];
    }

    if (this.disposed || typeof this.handlers[eventName] === 'undefined') {
      return;
    }
    const paramsLength = params.length;
    this.handlers[eventName].forEach(function (callback) {
      if (paramsLength === 1) {
        callback(params[0]);
      } else if (paramsLength === 2) {
        callback(params[0], params[1]);
      } else if (paramsLength === 3) {
        callback(params[0], params[1], params[2]);
      } else if (paramsLength === 4) {
        callback(params[0], params[1], params[2], params[3]);
      } else if (paramsLength === 5) {
        callback(params[0], params[1], params[2], params[3], params[4]);
      } else {
        callback.apply(undefined, params);
      }
    });
  }
}
exports.Emitter = Emitter;
},{"./disposable":2}],4:[function(require,module,exports){
'use strict';
'use babel';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _disposable = require('./disposable');

Object.defineProperty(exports, 'Disposable', {
  enumerable: true,
  get: function () {
    return _disposable.Disposable;
  }
});

var _compositeDisposable = require('./composite-disposable');

Object.defineProperty(exports, 'CompositeDisposable', {
  enumerable: true,
  get: function () {
    return _compositeDisposable.CompositeDisposable;
  }
});

var _emitter = require('./emitter');

Object.defineProperty(exports, 'Emitter', {
  enumerable: true,
  get: function () {
    return _emitter.Emitter;
  }
});
},{"./composite-disposable":1,"./disposable":2,"./emitter":3}]},{},[4])(4)
});<|endoftext|>


<commit_before>/*
 * grunt-bower-linker
 * https://github.com/mark/grunt-bower-linker
 *
 * Copyright (c) 2013 Mark Schad
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('bower-linker', 'Link bower components to specified directory.', function() {

    var
      bower = require('bower'),
      path = require('path'),
      async = require('async'),
      minimatch = require('minimatch'),
      glob = require('glob'),

      done = this.async(),

      options = this.options({
        cwd: '.',
        offline: true,
        root: 'linker',
        map: {
          '*.js': '/js',
          '*.css': '/css',
          '*': '/',
        }
      }),

      // Link a main file.
      link = function(source) {

        var filename = path.basename(source);
        grunt.log.writeln('Linking [%s]...', filename);
        for (var key in options.map) {

          // If this is a matching mapping then link the source to the
          // mapped directory.
          if (minimatch(filename, key))
            return grunt.file.copy(source,
              path.join(options.root, options.map[key], filename)
            );

        }

        // Link the source to the root linker directory if no specific
        // mapping was found.
        return grunt.file.copy(source,
          path.join(options.root, filename)
        );

      },

      // Parse a bower package and link its main files.
      parse = function(pkg) {

        async.each(Object.keys(pkg[dependencies]), function(key, next) {

          parse(pkg.dependencies[key]);
          next(null);

        }, function() {

          // Ensure this package has defined meta data, a list main packages and
          // a reference to the absolute location of these files.
          if (pkg.pkgMeta && pkg.pkgMeta.main && pkg.canonicalDir) {

            // Process each main file.
            async.each([].concat(pkg.pkgMeta.main), function(file, next) {

              // Glob the main file reference.
              var sources = [].concat(glob.sync(path.join(pkg.canonicalDir, file)));
              async.each(sources, function(source, next) {

                // Link the sources.
                link(source);
                next(null);

              }, function() { next(null) });

            });

          }

        });

      };

    // Get the list of bower packages and link them.
    bower.commands.list({ map: false, offline: options.offline }, { cwd: options.cwd })
      .on('end', function(data) {

        parse(data);  // Parse the base package.
        done();

      });

  });

};
<commit_msg>fixes<commit_after>/*
 * grunt-bower-linker
 * https://github.com/mark/grunt-bower-linker
 *
 * Copyright (c) 2013 Mark Schad
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('bower-linker', 'Link bower components to specified directory.', function() {

    var
      bower = require('bower'),
      path = require('path'),
      async = require('async'),
      minimatch = require('minimatch'),
      glob = require('glob'),

      done = this.async(),

      options = this.options({
        cwd: '.',
        offline: true,
        root: 'linker',
        map: {
          '*.js': '/js',
          '*.css': '/css',
          '*': '/',
        }
      }),

      // Link a main file.
      link = function(source) {

        var filename = path.basename(source);
        grunt.log.writeln('Linking [%s]...', filename);
        for (var key in options.map) {

          // If this is a matching mapping then link the source to the
          // mapped directory.
          if (minimatch(filename, key))
            return grunt.file.copy(source,
              path.join(options.root, options.map[key], filename)
            );

        }

        // Link the source to the root linker directory if no specific
        // mapping was found.
        return grunt.file.copy(source,
          path.join(options.root, filename)
        );

      },

      // Parse a bower package and link its main files.
      parse = function(pkg) {

        async.each(Object.keys(pkg['dependencies']), function(key, next) {

          parse(pkg.dependencies[key]);
          next(null);

        }, function() {

          // Ensure this package has defined meta data, a list main packages and
          // a reference to the absolute location of these files.
          if (pkg.pkgMeta && pkg.pkgMeta.main && pkg.canonicalDir) {

            // Process each main file.
            async.each([].concat(pkg.pkgMeta.main), function(file, next) {

              // Glob the main file reference.
              var sources = [].concat(glob.sync(path.join(pkg.canonicalDir, file)));
              async.each(sources, function(source, next) {

                // Link the sources.
                link(source);
                next(null);

              }, function() { next(null) });

            });

          }

        });

      };

    // Get the list of bower packages and link them.
    bower.commands.list({ map: false, offline: options.offline }, { cwd: options.cwd })
      .on('end', function(data) {

        parse(data);  // Parse the base package.
        done();

      });

  });

};
<|endoftext|>


<commit_before>var Promise      = require('bluebird');
var EventEmitter = require('events').EventEmitter;
var _            = require('underscore');
var fs           = Promise.promisifyAll(require('fs'));
var path         = require('path');
var gitty        = require('gitty');
var mkdirp       = Promise.promisify(require('mkdirp'));
var rimraf       = Promise.promisify(require('rimraf'));
var marked       = require('marked');
var highlight    = require('highlight.js');
var mv           = Promise.promisify(require('mv'));
var semver       = require('semver');

var renderer = new marked.Renderer();
var BLACKLIST_FILES = ['readme.md']

renderer.heading = function(text, level, raw) {
  var escapedText = raw
    .toLowerCase()
    .replace(/[']/g, '') // Add edge cases: /[1|2|3]/g
    .replace(/[^\w]+/g, '-')
    .replace(/-$/, '');;

  return (
    '<h'+level+'>'+
      ''+
        ''+
      ''+
      text+
    '</h'+level+'>'
  );
};

marked.setOptions({
  renderer: renderer,
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false,
  highlight: function (code, lang) {
    return highlight.highlightAuto(code, [lang]).value;
  }
});

var Compiler = function(paths) {
  this.paths = paths;
  this.repo = Promise.promisifyAll(gitty(this.paths.repo));
};

Compiler.prototype = new EventEmitter();

_.extend(Compiler.prototype, {
  compile: function() {
    return Promise.bind(this)
      .then(this.setup)
      .then(this.readFiles)
      .then(this.writeFiles)
      .then(this.writeTagIndexes)
      .then(this.cleanup);
  },

  remapInvalidTag: function(tag) {
    if (tag == 'v0.4.1a') {
      tag = 'v0.4.1-a';
    } else if (tag == 'v1.7') {
      tag = 'v1.7.0';
    } else if (tag == 'v1.4.0beta') {
      tag = 'v1.4.0-beta';
    }

    return tag;
  },

  sortTags: function(tags) {
    return tags.sort(function(v1, v2) {
      return semver.rcompare(this.remapInvalidTag(v1), this.remapInvalidTag(v2));
    }.bind(this));
  },

  setup: function() {
    return Promise.all([
      fs.readFileAsync(this.paths.template).call('toString'),
      fs.readFileAsync(this.paths.indexTemplate).call('toString'),
      mkdirp(this.paths.tmp),
      this.repo.tagsAsync()
    ]).bind(this).spread(function(template, indexTemplate, dir, tags) {
      this.template = _.template(template);
      this.indexTemplate = _.template(indexTemplate);
      this.tmpDir   = dir;
      this.tags     = this.sortTags(tags)
    });
  },

  compileContents: function(contents) {
    var compiledContents = marked(contents);

    // Strip out view the docs headline from each doc
    compiledContents = compiledContents.replace(/
.*View the new docs.*<\/h2>/, '');

    return compiledContents;
  },

  readFiles: function() {
    return Promise.bind(this).return(this.tags).map(function(tag) {
      return this.repo.checkoutAsync(tag).bind(this).then(function() {
        return fs.readdirAsync(this.paths.src);
      }).filter(function(filename) {
        // first we want to extract only markdown files
        return path.extname(filename) === '.md';
      }).filter(function(filename) {
        // Omit files that are blacklisted
        return BLACKLIST_FILES.indexOf(path.basename(filename)) == -1;
      })
      .map(function(filename) {
        var src = path.resolve(this.paths.src, filename);
        return fs.readFileAsync(src).bind(this).then(function(contents) {
          this.emit('readFile', { file: src });
          return {
            tag      : tag,
            basename : path.basename(filename, '.md'),
            filenane : filename,
            pathname : path.resolve(this.paths.tmp, tag),
            contents : this.compileContents(contents.toString())
          };
        });
      })
      .catch(function(err) {
        return false;
      });
    }, { concurrency: 1 })
    .then(function(files) {
      // If we failed to readthe md files for a version omit that version
      return _.filter(files, function(f){return f});
    })
    .then(function(files) {
      this.files = files;
    });
  },

  validTags: function() {
    return _.chain(this.tags)
    .map(this.remapInvalidTag)
    .filter(_.partial(semver.lte, "v0.9.0"))
    .value();
  },

  // Write out markup for each tag index page
  writeTagIndexes: function() {
    return Promise.bind(this).return(this.files).map(function(files) {
      var indexPath = path.resolve(files[0].pathname, "index.html")
      var indexMarkup = this.indexTemplate({
        tags    : this.validTags(),
        tag     : files[0].tag,
        file    : files[0],
        files   : files
      });

      // If this is the latest release ensure to write the /docs/current file
      if (files[0].tag == this.tags[0]) {
        return fs.writeFileAsync(indexPath, indexMarkup)
        .then(function() {
          var currentPath = path.resolve(files[0].pathname, "../", "current.html");
          return fs.writeFileAsync(currentPath, indexMarkup);
        });
      }

      return fs.writeFileAsync(indexPath, indexMarkup);
    });
  },

  writeFiles: function() {
    return Promise.bind(this).return(this.files).map(function(files) {
      return Promise.bind(this).return(files).map(function(file) {
        file.contents = this.template({
          content : file.contents,
          tags    : this.validTags(),
          tag     : files[0].tag,
          file    : file,
          files   : files
        });

        return mkdirp(file.pathname).bind(this).then(function() {
          this.emit('mkdirp', { dir: file.pathname });
        }).return(file);
      }).map(function(file) {
        var dest = path.resolve(file.pathname, file.basename + '.html');
        return fs.writeFileAsync(dest, file.contents).bind(this).then(function() {
          this.emit('writeFile', { file: dest });
        });
      });
    });
  },

  cleanup: function() {
    var tmpDir = path.resolve(this.paths.tmp, '..');
    return Promise.bind(this).then(function() {
      return rimraf(this.paths.dest);
    }).then(function() {
      this.emit('rimraf', { dir: this.paths.dest });
      return mkdirp(path.resolve(this.paths.dest, '..'));
    }).then(function() {
      this.emit('mkdirp', { dir: this.paths.dest });
      return fs.symlinkAsync(this.paths.tmp, this.paths.dest);
    }).then(function() {
      this.emit('symlink', { from: this.paths.tmp, to: this.paths.dest });
      return fs.readdirAsync(tmpDir);
    }).filter(function(dir) {
      dir = path.resolve(tmpDir, dir);
      return fs.statAsync(dir).bind(this).then(function(stats) {
        return stats.isDirectory() && dir !== this.paths.tmp;
      });
    }).map(function(dir) {
      dir = path.resolve(tmpDir, dir);
      return rimraf(dir).bind(this).then(function() {
        this.emit('rimraf', { dir: dir });
      });
    });
  },

  _readFile: function(file) {
    return fs.readFileAsync(path.resolve(file)).call('toString');
  },

  _readDir: function(dir) {
    return fs.readdirAsync(path.resolve(dir));
  },

  _writeFile: function(file, contents) {
    return fs.writeFileAsync(path.resolve(file), contents);
  },

  finializeBuild: function() {
    return rimraf(this.paths.dest)
    .then(function() {
      this.emit('mv', { from: this.tmpDir, to: this.paths.dest });
      return mv(this.tmpDir, this.paths.dest, {mkdirp: true})
    }.bind(this))
  }
});

module.exports = function(grunt) {
  grunt.registerMultiTask('compileDocs', function() {
    var options   = this.options();
    var files     = this.files[0];

    var compiler  = new Compiler({
      repo     : path.resolve(options.repo),
      template : path.resolve(options.template),
      indexTemplate : path.resolve(options.indexTemplate),
      tmp      : path.resolve('./.grunt/compileDocs/' + Date.now()),
      src      : path.resolve(files.orig.src[0]),
      dest     : path.resolve(files.dest)
    });

    compiler.on('readFile', function(data) {
      grunt.verbose.writeln('readFile: ' + data.file);
    });

    compiler.on('mkdirp', function(data) {
      grunt.verbose.writeln('mkdirp: ' + data.dir);
    });

    compiler.on('writeFile', function(data) {
      grunt.verbose.writeln('writeFile: ' + data.file);
    });

    compiler.on('symlink', function(data) {
      grunt.verbose.writeln('symlink: from ' + data.from + ' to ' + data.to);
    });

    compiler.on('rimraf', function(data) {
      grunt.verbose.writeln('writeFile: ' + data.file);
    });

    compiler.on('mv', function(data) {
      grunt.verbose.writeln('moving: ' + JSON.stringify(data));
    });

    compiler.compile()
    .then(function() {
      return compiler.finializeBuild();
    })
    .then(function() {
      compiler.removeAllListeners();
      grunt.log.ok('Success!');
    })
    .then(this.async());
  });
};
<commit_msg>/docs/current.html -> /docs/current/index.html<commit_after>var Promise      = require('bluebird');
var EventEmitter = require('events').EventEmitter;
var _            = require('underscore');
var fs           = Promise.promisifyAll(require('fs'));
var path         = require('path');
var gitty        = require('gitty');
var mkdirp       = Promise.promisify(require('mkdirp'));
var rimraf       = Promise.promisify(require('rimraf'));
var marked       = require('marked');
var highlight    = require('highlight.js');
var mv           = Promise.promisify(require('mv'));
var semver       = require('semver');

var renderer = new marked.Renderer();
var BLACKLIST_FILES = ['readme.md']

renderer.heading = function(text, level, raw) {
  var escapedText = raw
    .toLowerCase()
    .replace(/[']/g, '') // Add edge cases: /[1|2|3]/g
    .replace(/[^\w]+/g, '-')
    .replace(/-$/, '');;

  return (
    '<h'+level+'>'+
      ''+
        ''+
      ''+
      text+
    '</h'+level+'>'
  );
};

marked.setOptions({
  renderer: renderer,
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false,
  highlight: function (code, lang) {
    return highlight.highlightAuto(code, [lang]).value;
  }
});

var Compiler = function(paths) {
  this.paths = paths;
  this.repo = Promise.promisifyAll(gitty(this.paths.repo));
};

Compiler.prototype = new EventEmitter();

_.extend(Compiler.prototype, {
  compile: function() {
    return Promise.bind(this)
      .then(this.setup)
      .then(this.readFiles)
      .then(this.writeFiles)
      .then(this.writeTagIndexes)
      .then(this.cleanup);
  },

  remapInvalidTag: function(tag) {
    if (tag == 'v0.4.1a') {
      tag = 'v0.4.1-a';
    } else if (tag == 'v1.7') {
      tag = 'v1.7.0';
    } else if (tag == 'v1.4.0beta') {
      tag = 'v1.4.0-beta';
    }

    return tag;
  },

  sortTags: function(tags) {
    return tags.sort(function(v1, v2) {
      return semver.rcompare(this.remapInvalidTag(v1), this.remapInvalidTag(v2));
    }.bind(this));
  },

  setup: function() {
    return Promise.all([
      fs.readFileAsync(this.paths.template).call('toString'),
      fs.readFileAsync(this.paths.indexTemplate).call('toString'),
      mkdirp(this.paths.tmp),
      this.repo.tagsAsync()
    ]).bind(this).spread(function(template, indexTemplate, dir, tags) {
      this.template = _.template(template);
      this.indexTemplate = _.template(indexTemplate);
      this.tmpDir   = dir;
      this.tags     = this.sortTags(tags)
    });
  },

  compileContents: function(contents) {
    var compiledContents = marked(contents);

    // Strip out view the docs headline from each doc
    compiledContents = compiledContents.replace(/
.*View the new docs.*<\/h2>/, '');

    return compiledContents;
  },

  readFiles: function() {
    return Promise.bind(this).return(this.tags).map(function(tag) {
      return this.repo.checkoutAsync(tag).bind(this).then(function() {
        return fs.readdirAsync(this.paths.src);
      }).filter(function(filename) {
        // first we want to extract only markdown files
        return path.extname(filename) === '.md';
      }).filter(function(filename) {
        // Omit files that are blacklisted
        return BLACKLIST_FILES.indexOf(path.basename(filename)) == -1;
      })
      .map(function(filename) {
        var src = path.resolve(this.paths.src, filename);
        return fs.readFileAsync(src).bind(this).then(function(contents) {
          this.emit('readFile', { file: src });
          return {
            tag      : tag,
            basename : path.basename(filename, '.md'),
            filenane : filename,
            pathname : path.resolve(this.paths.tmp, tag),
            contents : this.compileContents(contents.toString())
          };
        });
      })
      .catch(function(err) {
        return false;
      });
    }, { concurrency: 1 })
    .then(function(files) {
      // If we failed to readthe md files for a version omit that version
      return _.filter(files, function(f){return f});
    })
    .then(function(files) {
      this.files = files;
    });
  },

  validTags: function() {
    return _.chain(this.tags)
    .map(this.remapInvalidTag)
    .filter(_.partial(semver.lte, "v0.9.0"))
    .value();
  },

  // Write out markup for each tag index page
  writeTagIndexes: function() {
    return Promise.bind(this).return(this.files).map(function(files) {
      var indexPath = path.resolve(files[0].pathname, "index.html")
      var indexMarkup = this.indexTemplate({
        tags    : this.validTags(),
        tag     : files[0].tag,
        file    : files[0],
        files   : files
      });

      // If this is the latest release ensure to write the /docs/current file
      if (files[0].tag == this.tags[0]) {
        return fs.writeFileAsync(indexPath, indexMarkup)
          .then(function() {
            var currentPath = path.resolve(files[0].pathname, '../current/');
            var currentIndex = path.resolve(currentPath, 'index.html');
            return mkdirp(currentPath).bind(this).then(function() {
                return fs.writeFileAsync(currentIndex, indexMarkup);
              });
          });
      }

      return fs.writeFileAsync(indexPath, indexMarkup);
    });
  },

  writeFiles: function() {
    return Promise.bind(this).return(this.files).map(function(files) {
      return Promise.bind(this).return(files).map(function(file) {
        file.contents = this.template({
          content : file.contents,
          tags    : this.validTags(),
          tag     : files[0].tag,
          file    : file,
          files   : files
        });

        return mkdirp(file.pathname).bind(this).then(function() {
          this.emit('mkdirp', { dir: file.pathname });
        }).return(file);
      }).map(function(file) {
        var dest = path.resolve(file.pathname, file.basename + '.html');
        return fs.writeFileAsync(dest, file.contents).bind(this).then(function() {
          this.emit('writeFile', { file: dest });
        });
      });
    });
  },

  cleanup: function() {
    var tmpDir = path.resolve(this.paths.tmp, '..');
    return Promise.bind(this).then(function() {
      return rimraf(this.paths.dest);
    }).then(function() {
      this.emit('rimraf', { dir: this.paths.dest });
      return mkdirp(path.resolve(this.paths.dest, '..'));
    }).then(function() {
      this.emit('mkdirp', { dir: this.paths.dest });
      return fs.symlinkAsync(this.paths.tmp, this.paths.dest);
    }).then(function() {
      this.emit('symlink', { from: this.paths.tmp, to: this.paths.dest });
      return fs.readdirAsync(tmpDir);
    }).filter(function(dir) {
      dir = path.resolve(tmpDir, dir);
      return fs.statAsync(dir).bind(this).then(function(stats) {
        return stats.isDirectory() && dir !== this.paths.tmp;
      });
    }).map(function(dir) {
      dir = path.resolve(tmpDir, dir);
      return rimraf(dir).bind(this).then(function() {
        this.emit('rimraf', { dir: dir });
      });
    });
  },

  _readFile: function(file) {
    return fs.readFileAsync(path.resolve(file)).call('toString');
  },

  _readDir: function(dir) {
    return fs.readdirAsync(path.resolve(dir));
  },

  _writeFile: function(file, contents) {
    return fs.writeFileAsync(path.resolve(file), contents);
  },

  finializeBuild: function() {
    return rimraf(this.paths.dest)
    .then(function() {
      this.emit('mv', { from: this.tmpDir, to: this.paths.dest });
      return mv(this.tmpDir, this.paths.dest, {mkdirp: true})
    }.bind(this))
  }
});

module.exports = function(grunt) {
  grunt.registerMultiTask('compileDocs', function() {
    var options   = this.options();
    var files     = this.files[0];

    var compiler  = new Compiler({
      repo     : path.resolve(options.repo),
      template : path.resolve(options.template),
      indexTemplate : path.resolve(options.indexTemplate),
      tmp      : path.resolve('./.grunt/compileDocs/' + Date.now()),
      src      : path.resolve(files.orig.src[0]),
      dest     : path.resolve(files.dest)
    });

    compiler.on('readFile', function(data) {
      grunt.verbose.writeln('readFile: ' + data.file);
    });

    compiler.on('mkdirp', function(data) {
      grunt.verbose.writeln('mkdirp: ' + data.dir);
    });

    compiler.on('writeFile', function(data) {
      grunt.verbose.writeln('writeFile: ' + data.file);
    });

    compiler.on('symlink', function(data) {
      grunt.verbose.writeln('symlink: from ' + data.from + ' to ' + data.to);
    });

    compiler.on('rimraf', function(data) {
      grunt.verbose.writeln('writeFile: ' + data.file);
    });

    compiler.on('mv', function(data) {
      grunt.verbose.writeln('moving: ' + JSON.stringify(data));
    });

    compiler.compile()
    .then(function() {
      return compiler.finializeBuild();
    })
    .then(function() {
      compiler.removeAllListeners();
      grunt.log.ok('Success!');
    })
    .then(this.async());
  });
};
<|endoftext|>