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

/**
 * webida - run configuration manager
 *
 * Src:
 *   plugins/webida.ide.project-management.run/run-configuration-manager.js
 */
define([
    'external/async/dist/async.min',
    'external/lodash/lodash.min',
    'dojo/i18n!./nls/resource',
    'dojo/topic',
    'webida-lib/app',
    'webida-lib/plugins/workspace/plugin',
    'webida-lib/util/logger/logger-client',
    'webida-lib/util/locale',
    'webida-lib/util/notify',
    'webida-lib/util/path'
], function (
    async,
    _,
    i18n,
    topic,
    ide,
    workspace,
    Logger,
    Locale,
    notify,
    pathutil
) {
    'use strict';

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    logger.off();

    var locale = new Locale(i18n);

    var PATH_WORKSPACE = ide.getPath();
    var WORKSPACE_INFO_DIR_NAME = '.workspace';
    var RUN_CONFIG_FILE_NAME = 'workspace.json';
    var PATH_RUN_CONFIG = PATH_WORKSPACE + '/' + WORKSPACE_INFO_DIR_NAME + '/' + RUN_CONFIG_FILE_NAME;

    //var topics = {
    //    RUN_AS_DISABLED: 'toolbar.runas.disable',
    //    RUN_AS_ENABLED: 'toolbar.runas.enable'
    //};

    var MODE = {
        RUN_MODE: 'run',
        DEBUG_MODE: 'debug'
    };

    var fsMount = ide.getFSCache();

    var runConfigurationFileCache;
    var runConfigurations = {};

    var isFlushing = false;

    /**
     * Create sorted object in ascending order by keys
     */
    function sortKeysBy(obj) {
        var keys = _.sortBy(_.keys(obj));
        return _.object(keys, _.map(keys, function (key) {
            return obj[key];
        }));
    }

    /**
     * load run configurations of all project from workspace.json file
     */
    function loadRunConfigurations(callback) {
        if (!isFlushing) {
            async.waterfall([
                function (next) {
                    fsMount.exists(PATH_RUN_CONFIG, function (err, exist) {
                        if (err) {
                            next(err);
                        } else if (!exist) {
                            next(locale.formatMessage('messageNotExist', {target: PATH_RUN_CONFIG}));
                        } else {
                            next();
                        }
                    });
                },
                function (next) {
                    fsMount.readFile(PATH_RUN_CONFIG, function (err, content) {
                        var workspaceObj;
                        if (err) {
                            next(err);
                        } else {
                            runConfigurationFileCache = content || '{}';
                            workspaceObj = JSON.parse(runConfigurationFileCache);
                            if (workspaceObj.run && Object.getOwnPropertyNames(workspaceObj.run).length > 0) {
                                runConfigurations = sortKeysBy(workspaceObj.run);
                                next();
                            } else {
                                next(PATH_RUN_CONFIG + ' hasn\'t run configuration info');
                            }
                        }
                    });
                }
            ], function (err) {
                if (err) {
                    logger.error('loadRunConfigurations', err);
                }
                if (callback) {
                    callback(err);
                }
            });
        }
    }

    /**
     * flush updated run configurations to workspace.json file
     */
    function flushRunConfigurations(callback) {
        var originalRun = JSON.parse(runConfigurationFileCache).run;
        isFlushing = true;

        _.each(runConfigurations, function (runConf) {
            if (runConf._dirty) {
                if (originalRun[runConf.originalName]) {
                    runConfigurations[runConf.originalName] = originalRun[runConf.originalName];
                } else {
                    runConf._deleted = true;
                }
            }
            delete runConf._dirty;
            delete runConf.originalName;
        });

        runConfigurations = _.omit(runConfigurations, function (runConf) {
            return runConf._deleted;
        });

        var unsyncedItems = [];
        _.map(runConfigurations, function (runConf, name) {
            if (runConf.name !== name) {
                unsyncedItems.push({
                    oldName: name,
                    newName: runConf.name
                });
            }
        });

        _.each(unsyncedItems, function (item) {
            runConfigurations[item.newName] = runConfigurations[item.oldName];
            delete runConfigurations[item.oldName];
        });

        runConfigurationFileCache = JSON.stringify({ run: sortKeysBy(runConfigurations) });
        fsMount.writeFile(PATH_RUN_CONFIG, runConfigurationFileCache, function (err) {
            isFlushing = false;
            if (err) {
                notify.error(err);
                logger.error('flushRunConfigurations:writeFile', PATH_RUN_CONFIG);
            }
            if (callback) {
                callback(err);
            }
        });
    }

    function _getPathInfo(path) {
        var result = {};
        if (!path) {
            return result;
        }
        if (path.charAt(0) === '/') {
            path = path.substring(1);
        }
        var workspaceName = PATH_WORKSPACE.substring(1);
        var splitedPath = pathutil.detachSlash(path).split('/');

        if (splitedPath.length > 0) {
            result.name = splitedPath[splitedPath.length - 1];
            var distanceFromWorkspace = splitedPath.length - splitedPath.indexOf(workspaceName);
            if (distanceFromWorkspace <= splitedPath.length) {
                result.isInWorkspace = true;
                if (distanceFromWorkspace === 1) {
                    result.type = 'workspace';
                } else if (distanceFromWorkspace === 2 && result.name !== WORKSPACE_INFO_DIR_NAME) {
                    result.type = 'project';
                } else if (distanceFromWorkspace === 2 && result.name === WORKSPACE_INFO_DIR_NAME) {
                    result.type = 'workspaceInfo';
                } else if (distanceFromWorkspace === 3 && result.name === RUN_CONFIG_FILE_NAME &&
                    splitedPath[splitedPath.indexOf(workspaceName) + 1] === WORKSPACE_INFO_DIR_NAME) {
                    result.type = 'runConfig';
                } else {
                    result.projectName = splitedPath[splitedPath.indexOf(workspaceName) + 1];
                }
            } else {
                result.isInWorkspace = false;
            }
        }
        return result;
    }

    var projectActions = {
        replaceProject: function (oldProjectName, newProjectName) {
            // change runConfigurations object
            _.each(_.where(runConfigurations, {
                project: oldProjectName
            }), function (runConf) {
                runConf.project = newProjectName;
            });
            // change runConfigurationsByProject object

            flushRunConfigurations();
        },
        deleteProject: function (projectName) {
            // change runConfigurations object
            runConfigurations = _.omit(runConfigurations, function (runConf) {
                return runConf.project === projectName;
            });
            flushRunConfigurations();
        }
    };

    function addListeners() {
        topic.subscribe('sys.fs.node.moved', function (event) {
            logger.log('sys.fs.node.moved', arguments);
            var src = event.srcURL;
            var dest = event.dstURL;
            var srcPathInfo = _getPathInfo(src);
            var destPathInfo = _getPathInfo(dest);
            if (srcPathInfo.type === 'project' && destPathInfo.type === 'project') {
                // ignore the case of nested projects
                projectActions.replaceProject(srcPathInfo.name, destPathInfo.name);
            } else if (srcPathInfo.type === 'workspaceInfo' || srcPathInfo.type === 'runConfig') {
                loadRunConfigurations();
            }
        });

        topic.subscribe('fs.cache.file.set', function (fsURL, target /*, type, maybeModified*/ ) {
            logger.log('fs.cache.file.set', arguments);
            var targetPathInfo = _getPathInfo(target);
            if (targetPathInfo.type === 'runConfig') {
                require(['plugins/webida.ide.project-management.run/view-controller'], function (
                    viewController) {
                    if (!viewController.getWindowOpened()) {
                        loadRunConfigurations();
                    }
                });
            }
        });

        topic.subscribe('fs.cache.node.deleted', function (fsURL, targetDir, name, type) {
            logger.log('fs.cache.node.deleted', arguments);
            if (type !== 'dir') {
                return;
            }
            var targetPathInfo = _getPathInfo(targetDir);
            if (targetPathInfo.type === 'workspace') {
                projectActions.deleteProject(name);
            } else if (targetPathInfo.type === 'workspaceInfo' || targetPathInfo.type === 'runConfig') {
                loadRunConfigurations();
            }
        });
    }

    (function initialize() {
        loadRunConfigurations();
        addListeners();
    })();

    function RunConfigurationManager() {
        var self = this;

        this.MODE = MODE;

        this.flushRunConfigurations = flushRunConfigurations;
        this.getByPath = function (path) {
            var pathInfo = _getPathInfo(path);
            if (pathInfo.projectName) {
                return self.getByProjectName(pathInfo.projectName);
            }
            return;
        };
        this.getByProjectName = function (projectName, callback) {
            var confList = _.filter(_.values(runConfigurations), function (runConf) {
                return runConf.project === projectName;
            });

            if (callback) {
                callback(confList);
            }
            return confList;
        };
        this.getByName = function (runConfigurationName, callback) {
            var conf = runConfigurations[runConfigurationName];
            if (callback) {
                callback(conf);
            }
            return conf;
        };
        this.getAll = function () {
            return runConfigurations;
        };
        this.add = function (runConfiguration) {
            runConfigurations[runConfiguration.name] = runConfiguration;
        };
        this.save = function (runConfiguration) {
            delete runConfiguration._dirty;
            runConfigurations[runConfiguration.name] = runConfiguration;

            flushRunConfigurations();
        };
        this.set = function (projectName, runConfigurations, callback) {
            _.each(runConfigurations, function (runConf) {
                runConfigurations[runConf.name] = runConf;
            });

            flushRunConfigurations(function (err) {
                if (!err) {
                    loadRunConfigurations(callback);
                }
            });
        };
        this.delete = function (runConfigurationName) {
            if (runConfigurations[runConfigurationName]) {
                runConfigurations[runConfigurationName]._deleted = true;
            }
            flushRunConfigurations();
        };
        this.setLatestRun = function (runConfigurationName) {
            if (runConfigurations[runConfigurationName]) {
                var project = runConfigurations[runConfigurationName].project;
                _.each(runConfigurations, function (runConf) {
                    if (runConf.project === project) {
                        runConf.latestRun = false;
                    }
                });
                runConfigurations[runConfigurationName].latestRun = true;
                flushRunConfigurations();
            }
        };
        this.getProjectRootHtml = function (filePath, callback) {
            var pathInfo = _getPathInfo(filePath);
            var htmlPaths = [];
            if (pathInfo.projectName) {
                _.each(runConfigurations, function (runConf) {
                    if (runConf.project === pathInfo.projectName &&
                        runConf.type === '' &&
                        pathutil.isHtml(runConf.path)) {
                        htmlPaths.push(pathutil.combine(PATH_WORKSPACE + '/' + pathInfo.projectName, runConf.path));
                    }
                });
            }
            callback(htmlPaths);
        };
    }

    return new RunConfigurationManager();
});
<commit_msg>[BUGFIX] (fix #758) Changed run configuration information is rollbacked when multiple IDE are loaded.<commit_after>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * webida - run configuration manager
 *
 * Src:
 *   plugins/webida.ide.project-management.run/run-configuration-manager.js
 */
define([
    'external/async/dist/async.min',
    'external/lodash/lodash.min',
    'external/URIjs/src/URI',
    'dojo/i18n!./nls/resource',
    'dojo/topic',
    'webida-lib/app',
    'webida-lib/plugins/workspace/plugin',
    'webida-lib/util/logger/logger-client',
    'webida-lib/util/locale',
    'webida-lib/util/notify',
    'webida-lib/util/path'
], function (
    async,
    _,
    URI,
    i18n,
    topic,
    ide,
    workspace,
    Logger,
    Locale,
    notify,
    pathutil
) {
    'use strict';

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    logger.off();

    var locale = new Locale(i18n);

    var PATH_WORKSPACE = ide.getPath();
    var WORKSPACE_INFO_DIR_NAME = '.workspace';
    var RUN_CONFIG_FILE_NAME = 'workspace.json';
    var PATH_RUN_CONFIG = PATH_WORKSPACE + '/' + WORKSPACE_INFO_DIR_NAME + '/' + RUN_CONFIG_FILE_NAME;

    //var topics = {
    //    RUN_AS_DISABLED: 'toolbar.runas.disable',
    //    RUN_AS_ENABLED: 'toolbar.runas.enable'
    //};

    var MODE = {
        RUN_MODE: 'run',
        DEBUG_MODE: 'debug'
    };

    var fsMount = ide.getFSCache();

    var runConfigurationFileCache;
    var runConfigurations = {};

    var isFlushing = false;

    /**
     * Create sorted object in ascending order by keys
     */
    function sortKeysBy(obj) {
        var keys = _.sortBy(_.keys(obj));
        return _.object(keys, _.map(keys, function (key) {
            return obj[key];
        }));
    }

    /**
     * load run configurations of all project from workspace.json file
     */
    function loadRunConfigurations(callback) {
        if (!isFlushing) {
            async.waterfall([
                function (next) {
                    fsMount.exists(PATH_RUN_CONFIG, function (err, exist) {
                        if (err) {
                            next(err);
                        } else if (!exist) {
                            next(locale.formatMessage('messageNotExist', {target: PATH_RUN_CONFIG}));
                        } else {
                            next();
                        }
                    });
                },
                function (next) {
                    fsMount.readFile(PATH_RUN_CONFIG, function (err, content) {
                        var workspaceObj;
                        if (err) {
                            next(err);
                        } else {
                            runConfigurationFileCache = content || '{}';
                            workspaceObj = JSON.parse(runConfigurationFileCache);
                            if (workspaceObj.run && Object.getOwnPropertyNames(workspaceObj.run).length > 0) {
                                runConfigurations = sortKeysBy(workspaceObj.run);
                                next();
                            } else {
                                next(PATH_RUN_CONFIG + ' hasn\'t run configuration info');
                            }
                        }
                    });
                }
            ], function (err) {
                if (err) {
                    logger.error('loadRunConfigurations', err);
                }
                if (callback) {
                    callback(err);
                }
            });
        }
    }

    /**
     * flush updated run configurations to workspace.json file
     */
    function flushRunConfigurations(callback) {
        var originalRun = JSON.parse(runConfigurationFileCache).run;
        isFlushing = true;

        _.each(runConfigurations, function (runConf) {
            if (runConf._dirty) {
                if (originalRun[runConf.originalName]) {
                    runConfigurations[runConf.originalName] = originalRun[runConf.originalName];
                } else {
                    runConf._deleted = true;
                }
            }
            delete runConf._dirty;
            delete runConf.originalName;
        });

        runConfigurations = _.omit(runConfigurations, function (runConf) {
            return runConf._deleted;
        });

        var unsyncedItems = [];
        _.map(runConfigurations, function (runConf, name) {
            if (runConf.name !== name) {
                unsyncedItems.push({
                    oldName: name,
                    newName: runConf.name
                });
            }
        });

        _.each(unsyncedItems, function (item) {
            runConfigurations[item.newName] = runConfigurations[item.oldName];
            delete runConfigurations[item.oldName];
        });

        runConfigurationFileCache = JSON.stringify({ run: sortKeysBy(runConfigurations) });
        fsMount.writeFile(PATH_RUN_CONFIG, runConfigurationFileCache, function (err) {
            isFlushing = false;
            if (err) {
                notify.error(err);
                logger.error('flushRunConfigurations:writeFile', PATH_RUN_CONFIG);
            }
            if (callback) {
                callback(err);
            }
        });
    }

    function _getPathInfo(path) {
        var result = {};
        if (!path) {
            return result;
        }
        if (path.charAt(0) === '/') {
            path = path.substring(1);
        }
        var workspaceName = PATH_WORKSPACE.substring(1);
        var splitedPath = pathutil.detachSlash(path).split('/');

        if (splitedPath.length > 0) {
            result.name = splitedPath[splitedPath.length - 1];
            var distanceFromWorkspace = splitedPath.length - splitedPath.indexOf(workspaceName);
            if (distanceFromWorkspace <= splitedPath.length) {
                result.isInWorkspace = true;
                if (distanceFromWorkspace === 1) {
                    result.type = 'workspace';
                } else if (distanceFromWorkspace === 2 && result.name !== WORKSPACE_INFO_DIR_NAME) {
                    result.type = 'project';
                } else if (distanceFromWorkspace === 2 && result.name === WORKSPACE_INFO_DIR_NAME) {
                    result.type = 'workspaceInfo';
                } else if (distanceFromWorkspace === 3 && result.name === RUN_CONFIG_FILE_NAME &&
                    splitedPath[splitedPath.indexOf(workspaceName) + 1] === WORKSPACE_INFO_DIR_NAME) {
                    result.type = 'runConfig';
                } else {
                    result.projectName = splitedPath[splitedPath.indexOf(workspaceName) + 1];
                }
            } else {
                result.isInWorkspace = false;
            }
        }
        return result;
    }

    var projectActions = {
        replaceProject: function (oldProjectName, newProjectName) {
            // change runConfigurations object
            _.each(_.where(runConfigurations, {
                project: oldProjectName
            }), function (runConf) {
                runConf.project = newProjectName;
            });
            // change runConfigurationsByProject object

            flushRunConfigurations();
        },
        deleteProject: function (projectName) {
            // change runConfigurations object
            runConfigurations = _.omit(runConfigurations, function (runConf) {
                return runConf.project === projectName;
            });
            flushRunConfigurations();
        }
    };

    function addListeners() {
        topic.subscribe('sys.fs.node.moved', function (event) {
            logger.log('sys.fs.node.moved', arguments);
            var src = event.srcURL;
            var dest = event.dstURL;
            var srcPathInfo = _getPathInfo(src);
            var destPathInfo = _getPathInfo(dest);
            if (srcPathInfo.type === 'project' && destPathInfo.type === 'project') {
                // ignore the case of nested projects
                projectActions.replaceProject(srcPathInfo.name, destPathInfo.name);
            } else if (srcPathInfo.type === 'workspaceInfo' || srcPathInfo.type === 'runConfig') {
                loadRunConfigurations();
            }
        });

        function _applyChangesOnFile(filePath) {
            var targetPathInfo = _getPathInfo(filePath);
            if (targetPathInfo.type === 'runConfig') {
                require(['plugins/webida.ide.project-management.run/view-controller'], function (viewController) {
                    if (!viewController.getWindowOpened()) {
                        loadRunConfigurations();
                    }
                });
            }
        }

        // apply changes on run config file at current IDE
        topic.subscribe('fs.cache.file.set', function (fsURL, target) {
            logger.log('fs.cache.file.set', arguments);
            _applyChangesOnFile(target);
        });

        // apply changes on run config file at another IDE
        topic.subscribe('sys.fs.file.written', function (data) {
            logger.log('sys.fs.file.written', data);
            var uri = new URI(data.url);
            uri.segment(0, '');	                    // drop the fsid
            _applyChangesOnFile(uri.path(true));    // get decoded path
        });

        topic.subscribe('fs.cache.node.deleted', function (fsURL, targetDir, name, type) {
            logger.log('fs.cache.node.deleted', arguments);
            if (type !== 'dir') {
                return;
            }
            var targetPathInfo = _getPathInfo(targetDir);
            if (targetPathInfo.type === 'workspace') {
                projectActions.deleteProject(name);
            } else if (targetPathInfo.type === 'workspaceInfo' || targetPathInfo.type === 'runConfig') {
                loadRunConfigurations();
            }
        });
    }

    (function initialize() {
        loadRunConfigurations();
        addListeners();
    })();

    function RunConfigurationManager() {
        var self = this;

        this.MODE = MODE;

        this.flushRunConfigurations = flushRunConfigurations;
        this.getByPath = function (path) {
            var pathInfo = _getPathInfo(path);
            if (pathInfo.projectName) {
                return self.getByProjectName(pathInfo.projectName);
            }
            return;
        };
        this.getByProjectName = function (projectName, callback) {
            var confList = _.filter(_.values(runConfigurations), function (runConf) {
                return runConf.project === projectName;
            });

            if (callback) {
                callback(confList);
            }
            return confList;
        };
        this.getByName = function (runConfigurationName, callback) {
            var conf = runConfigurations[runConfigurationName];
            if (callback) {
                callback(conf);
            }
            return conf;
        };
        this.getAll = function () {
            return runConfigurations;
        };
        this.add = function (runConfiguration) {
            runConfigurations[runConfiguration.name] = runConfiguration;
        };
        this.save = function (runConfiguration) {
            delete runConfiguration._dirty;
            runConfigurations[runConfiguration.name] = runConfiguration;

            flushRunConfigurations();
        };
        this.set = function (projectName, runConfigurations, callback) {
            _.each(runConfigurations, function (runConf) {
                runConfigurations[runConf.name] = runConf;
            });

            flushRunConfigurations(function (err) {
                if (!err) {
                    loadRunConfigurations(callback);
                }
            });
        };
        this.delete = function (runConfigurationName) {
            if (runConfigurations[runConfigurationName]) {
                runConfigurations[runConfigurationName]._deleted = true;
            }
            flushRunConfigurations();
        };
        this.setLatestRun = function (runConfigurationName) {
            if (runConfigurations[runConfigurationName]) {
                var project = runConfigurations[runConfigurationName].project;
                _.each(runConfigurations, function (runConf) {
                    if (runConf.project === project) {
                        runConf.latestRun = false;
                    }
                });
                runConfigurations[runConfigurationName].latestRun = true;
                flushRunConfigurations();
            }
        };
        this.getProjectRootHtml = function (filePath, callback) {
            var pathInfo = _getPathInfo(filePath);
            var htmlPaths = [];
            if (pathInfo.projectName) {
                _.each(runConfigurations, function (runConf) {
                    if (runConf.project === pathInfo.projectName &&
                        runConf.type === '' &&
                        pathutil.isHtml(runConf.path)) {
                        htmlPaths.push(pathutil.combine(PATH_WORKSPACE + '/' + pathInfo.projectName, runConf.path));
                    }
                });
            }
            callback(htmlPaths);
        };
    }

    return new RunConfigurationManager();
});
<|endoftext|>


<commit_before>/**
 * Controller for the assignment overview.
 */
Ext.define('subjectadmin.controller.assignment.Overview', {
    extend: 'Ext.app.Controller',

    //requires: [
    //],
    views: [
        'assignment.Overview',
        'ActionList',
        'assignment.EditPublishingTime'
    ],

    stores: [
        'SingleAssignment'
    ],

    controllers: [
        'assignment.EditPublishingTime'
    ],

    refs: [{
        ref: 'gradeEditorSidebarBox',
        selector: 'editablesidebarbox[itemId=gradeeditor]'
    }, {
        ref: 'publishingTimeSidebarBox',
        selector: 'editablesidebarbox[itemId=publishingtime]'
    }, {
        ref: 'primaryTitle',
        selector: 'centertitle[itemId=primaryTitle]'
    }, {
        ref: 'assignmentView',
        selector: 'assignmentoverview'
    }],

    init: function() {
        this.control({
            'viewport assignmentoverview': {
                render: this._onAssignmentViewRender
            },
            'viewport assignmentoverview editablesidebarbox[itemId=gradeeditor] button': {
                click: this._onEditGradeEditor
            },
            'viewport assignmentoverview editablesidebarbox[itemId=publishingtime] button': {
                click: this._onEditPublishingTime
            },
            'viewport assignmentoverview editablesidebarbox[itemId=publishingtime] button': {
                click: this._onEditPublishingTime
            },
        });
    },

    _onAssignmentViewRender: function() {
        this.subject_shortname = this.getAssignmentView().subject_shortname;
        this.period_shortname = this.getAssignmentView().period_shortname;
        this.assignment_shortname = this.getAssignmentView().assignment_shortname;
        this._loadAssignment();
    },

    _loadAssignment: function() {
        var store = this.getSingleAssignmentStore();
        store.loadAssignment(
            this.subject_shortname, this.period_shortname, this.assignment_shortname,
            this._onLoadAssignment, this
        );
    },

    _onLoadAssignment: function(records, operation) {
        if(operation.success) {
            this._onLoadAssignmentSuccess(records[0]);
        } else {
            this._onLoadAssignmentFailure(operation);
        }
    },

    _onLoadAssignmentFailure: function(operation) {
        var tpl = Ext.create('Ext.XTemplate',
            '
{title}
',
            '
{subject_shortname}.{period_shortname}.{assignment_shortname}
'
        );
        Ext.defer(function() { // NOTE: The delay is required for the mask to draw itself correctly.
            this.getAssignmentView().getEl().mask(tpl.apply({
                title: dtranslate('themebase.doesnotexist'),
                subject_shortname: this.subject_shortname,
                period_shortname: this.period_shortname,
                assignment_shortname: this.assignment_shortname
            }), 'messagemask');
        }, 50, this);
    },

    _onLoadAssignmentSuccess: function(record) {
        this.assignmentRecord = record;
        this.getPrimaryTitle().update(record.get('long_name'));
        this._updatePublishingTimeBox();
    },

    _updatePublishingTimeBox: function() {
        var published = this.assignmentRecord.get('publishing_time') < Ext.Date.now();
        var title, tpl;
        if(published) {
            title = dtranslate('subjectadmin.assignment.published.title');
            tpl = dtranslate('subjectadmin.assignment.published.body');
        } else {
            title = dtranslate('subjectadmin.assignment.notpublished.title');
            tpl = dtranslate('subjectadmin.assignment.notpublished.body');
        }
        var publishing_time = this.assignmentRecord.get('publishing_time');
        this.getPublishingTimeSidebarBox().updateTitle(title);
        this.getPublishingTimeSidebarBox().updateBody([tpl], {
            publishing_time: Ext.Date.format(publishing_time, dtranslate('Y-m-d H:i'))
        });
    },

    _onEditGradeEditor: function() {
        console.log('grade', this.getGradeEditorSidebarBox());
    },

    _onEditPublishingTime: function() {
        //console.log('pub', this.getPublishingTimeSidebarBox());
        Ext.widget('editpublishingtime', {
            assignmentRecord: this.assignmentRecord
        }).show();
    }
});
<commit_msg>apps.subjectadmin...assignment.Overview: assignmentView->assignmentOverview.<commit_after>/**
 * Controller for the assignment overview.
 */
Ext.define('subjectadmin.controller.assignment.Overview', {
    extend: 'Ext.app.Controller',

    //requires: [
    //],
    views: [
        'assignment.Overview',
        'ActionList',
        'assignment.EditPublishingTime'
    ],

    stores: [
        'SingleAssignment'
    ],

    controllers: [
        'assignment.EditPublishingTime'
    ],

    refs: [{
        ref: 'gradeEditorSidebarBox',
        selector: 'editablesidebarbox[itemId=gradeeditor]'
    }, {
        ref: 'publishingTimeSidebarBox',
        selector: 'editablesidebarbox[itemId=publishingtime]'
    }, {
        ref: 'primaryTitle',
        selector: 'centertitle[itemId=primaryTitle]'
    }, {
        ref: 'assignmentOverview',
        selector: 'assignmentoverview'
    }],

    init: function() {
        this.control({
            'viewport assignmentoverview': {
                render: this._onAssignmentViewRender
            },
            'viewport assignmentoverview editablesidebarbox[itemId=gradeeditor] button': {
                click: this._onEditGradeEditor
            },
            'viewport assignmentoverview editablesidebarbox[itemId=publishingtime] button': {
                click: this._onEditPublishingTime
            },
            'viewport assignmentoverview editablesidebarbox[itemId=publishingtime] button': {
                click: this._onEditPublishingTime
            },
        });
    },

    _onAssignmentViewRender: function() {
        this.subject_shortname = this.getAssignmentOverview().subject_shortname;
        this.period_shortname = this.getAssignmentOverview().period_shortname;
        this.assignment_shortname = this.getAssignmentOverview().assignment_shortname;
        this._loadAssignment();
    },

    _loadAssignment: function() {
        var store = this.getSingleAssignmentStore();
        store.loadAssignment(
            this.subject_shortname, this.period_shortname, this.assignment_shortname,
            this._onLoadAssignment, this
        );
    },

    _onLoadAssignment: function(records, operation) {
        if(operation.success) {
            this._onLoadAssignmentSuccess(records[0]);
        } else {
            this._onLoadAssignmentFailure(operation);
        }
    },

    _onLoadAssignmentFailure: function(operation) {
        var tpl = Ext.create('Ext.XTemplate',
            '
{title}
',
            '
{subject_shortname}.{period_shortname}.{assignment_shortname}
'
        );
        Ext.defer(function() { // NOTE: The delay is required for the mask to draw itself correctly.
            this.getAssignmentOverview().getEl().mask(tpl.apply({
                title: dtranslate('themebase.doesnotexist'),
                subject_shortname: this.subject_shortname,
                period_shortname: this.period_shortname,
                assignment_shortname: this.assignment_shortname
            }), 'messagemask');
        }, 50, this);
    },

    _onLoadAssignmentSuccess: function(record) {
        this.assignmentRecord = record;
        this.getPrimaryTitle().update(record.get('long_name'));
        this._updatePublishingTimeBox();
    },

    _updatePublishingTimeBox: function() {
        var published = this.assignmentRecord.get('publishing_time') < Ext.Date.now();
        var title, tpl;
        if(published) {
            title = dtranslate('subjectadmin.assignment.published.title');
            tpl = dtranslate('subjectadmin.assignment.published.body');
        } else {
            title = dtranslate('subjectadmin.assignment.notpublished.title');
            tpl = dtranslate('subjectadmin.assignment.notpublished.body');
        }
        var publishing_time = this.assignmentRecord.get('publishing_time');
        this.getPublishingTimeSidebarBox().updateTitle(title);
        this.getPublishingTimeSidebarBox().updateBody([tpl], {
            publishing_time: Ext.Date.format(publishing_time, dtranslate('Y-m-d H:i'))
        });
    },

    _onEditGradeEditor: function() {
        console.log('grade', this.getGradeEditorSidebarBox());
    },

    _onEditPublishingTime: function() {
        //console.log('pub', this.getPublishingTimeSidebarBox());
        Ext.widget('editpublishingtime', {
            assignmentRecord: this.assignmentRecord
        }).show();
    }
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

YUI.add('RoutingMojit', function(Y, NAME) {
  Y.namespace('mojito.controllers')[NAME] = {
    init: function(config) {
      this.config = config;
    },
    index: function(ac) {
      ac.done(route_info(ac));
    },
    show: function(ac){
      ac.done(route_info(ac));
    }
  };
  // Builds object containing route information
  function route_info(ac){
    var methods = "";
    var name="";
    var action = ac.action;
    var path = ac.http.getRequest().url;
    ac.url.getRouteMaker();
    if(action==="index" && path==="/"){
      name = ac.app.routes.root_route.name;
      Object.keys(ac.app.routes.root_route.verbs).forEach(function(n) {
        methods += n + ", ";
      });
    }else if(action==="index"){
      name = ac.app.routes.index_route.name;
      Object.keys(ac.app.routes.index_route.verbs).forEach(function(n) {
        methods += n + ", ";
      });
    }else {
      name = ac.app.routes.show_route.name;
      Object.keys(ac.app.routes.show_route.verbs).forEach(function(n) {
          methods += n + ", ";
      });
    }
    return {
      "path": path,
      "name": name,
      "methods": methods.replace(/, $/,"")
    };
  }
}, '0.0.1', {requires: ['mojito-url-addon']});
<commit_msg>updated example<commit_after>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

YUI.add('RoutingMojit', function(Y, NAME) {
  Y.namespace('mojito.controllers')[NAME] = {
    init: function(config) {
      this.config = config;
    },
    index: function(ac) {
      ac.done(route_info(ac));
    },
    show: function(ac){
      ac.done(route_info(ac));
    }
  };
  // Builds object containing route information
  function route_info(ac){
    var methods = "";
    var name = "";
    var action = ac.action;
    var path = ac.http.getRequest().url;
    var routes = ac.config.getRoutes();
    if(action==="index" && path==="/"){
      name = routes.root_route.name;
      Object.keys(routes.root_route.verbs).forEach(function(n) {
        methods += n + ", ";
      });
    }else if(action==="index"){
      name = routes.index_route.name;
      Object.keys(routes.index_route.verbs).forEach(function(n) {
        methods += n + ", ";
      });
    }else {
      name = routes.show_route.name;
      Object.keys(routes.show_route.verbs).forEach(function(n) {
          methods += n + ", ";
      });
    }
    return {
      "path": path,
      "name": name,
      "methods": methods.replace(/, $/,"")
    };
  }
}, '0.0.1', {requires: ['mojito-config-addon', 'mojito-http-addon']});
<|endoftext|>


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

/**
 * Style and layout parameters for cytoscape.js
 */
Gemma.CytoscapeSettings = {

   // white, for the display bkg
   backgroundColor : "#FFFFFF",

   // node color stuff
   labelFontName : 'Arial',

   // grey
   labelFontColor : "#4F4F4F",

   // grey; modified by 'overlays' and 'emphasis'
   nodeColor : "#222222",

   nodeColorOverlay : "#66ACDE", // baby blue

   // size stuff (edge size is in the cytoscapeJSCoexGraphInitializer)
   labelFontSize : 12,
   nodeSize : 18,

   nodeQueryColorTrue : "#AB1AE4", // purple

   // edge color stuff
   supportColorBoth : "#CCCCCC", // grey

   supportColorPositive : "#059900", // greenish
   supportColorNegative : "#E81C7B", // reddish

   selectionGlowColor : "#CC9C00", // gold

   /*
    * This is the few values here that is not for style, has nothing to do with visualization per se - consider moving.
    */
   maxGeneIdsPerCoexVisQuery : 200,

   // inoperative in cytoscape.js as of 2.2
   nodeTooltipText : "${id} (${officialName})
Specificity:${nodeDegreeBin}
NCBI Id:${ncbiId}
",

   // inoperative in cytoscape.js as of 2.2
   edgeTooltipText : "Edge Nodes: ${target} to ${source}
Positive Support:${positivesupport}
Negative Support:${negativesupport}",

   // thresholds e.g. dark colour is >dark value and <moderate value
   // high values mean high node degree.
   nodeDegreeValue : {
      highest : 0.9,
      high : 0.8,
      moderate : 0.7,
      low : 0.5,
      lowest : 0.3
   },

   // alpha values. We're blending in white, so low numbers translate to dark
   nodeDegreeColor : {
      lightest : 0.85,
      light : 0.65,
      moderate : 0.5,
      dark : 0.35,
      darkest : 0.0
   },

};

/**
 * Todo: make negative correlations cause repulsion?
 */
Gemma.CytoscapejsSettings = {

   nodeSettings : {},

   coseLayout : {
      name : 'cose',
      refresh : 0,
      fit : true,
   },

   // See also http://arborjs.org/reference
   arborLayout : {
      name : 'arbor',
      // liveUpdate : true,
      // edgeLength:100,
      // nodeMass : 2,
      // maxSimulationTime : 4000,
      repulsion : 100,
      stiffness : 60,
      // edgeLength : function( el ) {
      // return 5.0 / el.support;
      // },
      //
      // nodeMass : function( el ) {
      // return 1.0;
      // },

      // gravity: false,
      friction : 0.1,
      // simulationBounds : [ 0, 0, 7000, 5000 ],
      fit : true
   }

};
<commit_msg>minor.<commit_after>/*
 * The Gemma project
 *
 * Copyright (c) 2008 University of British Columbia
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 */
Ext.namespace( 'Gemma' );

/**
 * Style and layout parameters for cytoscape.js
 */
Gemma.CytoscapeSettings = {

   // white, for the display bkg
   backgroundColor : "#FFFFFF",

   // node color stuff
   labelFontName : 'Arial',

   // grey
   labelFontColor : "#4F4F4F",

   // grey; modified by 'overlays' and 'emphasis'
   nodeColor : "#222222",

   nodeColorOverlay : "#66ACDE", // baby blue

   // size stuff (edge size is in the cytoscapeJSCoexGraphInitializer)
   labelFontSize : 12,

   nodeSize : 18,

   nodeQueryColorTrue : "#AB1AE4", // purple

   // edge color stuff
   supportColorBoth : "#CCCCCC", // grey

   supportColorPositive : "#059900", // greenish
   supportColorNegative : "#E81C7B", // reddish

   selectionGlowColor : "#CC9C00", // gold

   /*
    * This is the few values here that is not for style, has nothing to do with visualization per se - consider moving.
    */
   maxGeneIdsPerCoexVisQuery : 200,

   // inoperative in cytoscape.js as of 2.2
   nodeTooltipText : "${id} (${officialName})
Specificity:${nodeDegreeBin}
NCBI Id:${ncbiId}
",

   // inoperative in cytoscape.js as of 2.2
   edgeTooltipText : "Edge Nodes: ${target} to ${source}
Positive Support:${positivesupport}
Negative Support:${negativesupport}",

   // thresholds e.g. dark colour is >dark value and <moderate value
   // high values mean high node degree.
   nodeDegreeValue : {
      highest : 0.9,
      high : 0.8,
      moderate : 0.7,
      low : 0.5,
      lowest : 0.3
   },

   // Shades. We're blending in white, so low numbers translate to
   // dark. Note: alpha is much slower.
   nodeDegreeColor : {
      lightest : 0.85,
      light : 0.65,
      moderate : 0.5,
      dark : 0.35,
      darkest : 0.0
   },

};

/**
 * Todo: make negative correlations cause repulsion?
 */
Gemma.CytoscapejsSettings = {

   nodeSettings : {},

   coseLayout : {
      name : 'cose',
      refresh : 0,
      fit : true,
   },

   // See also http://arborjs.org/reference
   arborLayout : {
      name : 'arbor',
      // liveUpdate : true,
      // edgeLength:100,
      // nodeMass : 2,
      // maxSimulationTime : 4000,
      repulsion : 100,
      stiffness : 60,
      // edgeLength : function( el ) {
      // return 5.0 / el.support;
      // },
      //
      // nodeMass : function( el ) {
      // return 1.0;
      // },

      // gravity: false,
      friction : 0.1,
      // simulationBounds : [ 0, 0, 7000, 5000 ],
      fit : true
   }

};
<|endoftext|>


<commit_before>var log = console.log;
var balance = web3.eth.getBalance;

contract("AuctionHouse", function(accounts) {
    it("should know if a seller owns an asset on an external contract", function() {
	var sn = SampleName.deployed();
	var owner = accounts[0];
	var recordId = "test.name";

	// Create a samplename record
	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(res) {
	    return AuctionHouse.new().then(function(ah) {
		return ah.partyOwnsAsset.call(owner, sn.address, recordId).then(function(res) {
		    assert.strictEqual(res, true, "the owner doesn't own this asset");
		}).then(function(res) {
		    return ah.partyOwnsAsset.call(accounts[1], sn.address, recordId).then(function(res) {
			assert.strictEqual(res, false, "the owner owns this asset, but shouldn't.");
		    });
		});
	    });
	});
    });

    it("should let us construct a valid auction", function() {
	var sn = SampleName.deployed();
	var owner = accounts[0];
	var recordId = "test2.name";
	var targetAuctionId = 0;
	var startingBid = web3.toWei(0.2, "ether");
	var reservePrice = web3.toWei(0.3, "ether");

	// Start by creating a sample record
	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
	    return AuctionHouse.new().then(function(ah) {
		// Now create an auction
		return ah.createAuction("Title",
					"Description",
					sn.address,
					recordId,
					web3.eth.blockNumber + 100,
					startingBid,
					reservePrice,
					5,
					accounts[2], {from:owner}).then(function(txId) {

					    return ah.getAuction.call(targetAuctionId).then(function(auction) {
						assert.strictEqual(auction[0], owner, "Didn't get the correct seller");
						assert.strictEqual(auction[3], "Title", "Didn't get an updated auction");
						assert.equal(auction[10], startingBid, "Didn't get an updated auction bid price");
						return ah.getAuctionsCountForUser.call(owner);
					    }).then(function(auctionsCount) {
					 	assert.strictEqual(auctionsCount.toNumber(), 1, "Should only have 1 auction");
					 	return ah.getAuctionIdForUserAndIdx.call(owner, auctionsCount.toNumber() - 1);
					    }).then(function(auctionId) {
					 	assert.strictEqual(auctionId.toNumber(), targetAuctionId, "AuctionId should be zero");
					    });

					});
	    });
	});
    });

    it("should activate and cancel an auction", function() {
	var sn = SampleName.deployed();
	var owner = accounts[1];
	var recordId = "test3.name";
	var auctionId;

	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
	    return AuctionHouse.new().then(function(ah) {
		ah.createAuction("Title",
				 "Description",
				 sn.address,
				 recordId,
				 web3.eth.blockNumber + 100,
				 (2 * 10^6),
				 (3 * 10^6),
				 5,
				 accounts[2], {from:owner}).then(function(txId) {
			    	     return ah.getAuctionsCountForUser.call(owner);
				 }).then(function(auctionsCount) {
			    	     return ah.getAuctionIdForUserAndIdx.call(owner, auctionsCount - 1);
				 }).then(function(aucId) {
			    	     auctionId = aucId;
			    	     return ah.getStatus.call(auctionId);
				 }).then(function(auctionStatus) {
			    	     assert.strictEqual(auctionStatus.toNumber(), 0, "Auction status should be pending");
			    	     return sn.setOwner(recordId, ah.address, {from:owner});
				 }).then(function() {
			    	     return ah.activateAuction(auctionId, {from:owner});
				 }).then(function(res) {
			    	     return ah.getStatus.call(auctionId);
				 }).then(function(activeAuctionStatus) {
			    	     assert.strictEqual(activeAuctionStatus.toNumber(), 1, "Auction should be active");
			    	     return ah.cancelAuction(auctionId, {from:owner});
				 }).then(function(res) {
			    	     return ah.getStatus.call(auctionId);
				 }).then(function(cancelledAuctionStatus) {
			    	     assert.strictEqual(cancelledAuctionStatus.toNumber(), 2, "Auction should be inactive");
			    	     return sn.owner.call(recordId);
				 }).then(function(assetOwner) {
			    	     assert.strictEqual(assetOwner, owner, "Should return the asset to the seller");
				 });
	    });
	});
    });

    it("should place a valid bid", function() {
	var sn = SampleName.deployed();
	var owner = accounts[4];
	var recordId = "test4.name";
	var bidder = accounts[5];
	var bidAmount = web3.toWei(0.4, "ether");
	var contractStartBalance;
	var auctionId;

	// Create an asset,
	// create an auction,
	// transfer the asset to the auction
	// activate the auction
	// place a bid
	// check that the bid properties and auction current bid updated

	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
	    return AuctionHouse.new().then(function(ah) {
		contractStartBalance = web3.eth.getBalance(ah.address);
		ah.createAuction("Title",
				 "Description",
				 sn.address,
				 recordId,
				 web3.eth.blockNumber + 100,
				 (2 * 10^6),
				 (3 * 10^6),
				 5,
				 accounts[2], {from:owner}).then(function(txId) {
			    	     return ah.getAuctionsCountForUser.call(owner);
				 }).then(function(auctionsCount) {
			    	     return ah.getAuctionIdForUserAndIdx.call(owner, auctionsCount - 1);
				 }).then(function(aucId) {
			    	     auctionId = aucId;
			    	     return sn.setOwner(recordId, ah.address, {from:owner});
				 }).then(function() {
			    	     return ah.activateAuction(auctionId, {from:owner});
				 }).then(function(res) {
				     return ah.placeBid(auctionId, {from:bidder, value:bidAmount});
				 }).then(function() {
			    	     return ah.getBidCountForAuction.call(auctionId);
				 }).then(function(bidCount){
				     assert.strictEqual(bidCount.toNumber(), 1, "there should be one bid");
				     return ah.getBidForAuctionByIdx.call(auctionId, bidCount - 1);
				 }).then(function(bids) {
				     assert.strictEqual(bids[0], bidder, "bidder was not correct");
				     assert.equal(bids[1].toNumber(), bidAmount, "bid amount was not correct");
				     assert.equal(web3.eth.getBalance(ah.address).toNumber(), contractStartBalance + bidAmount, "Contract balance did not equal the bid amount");
				     return ah.getAuction.call(auctionId);
				 }).then(function(auction) {
				     assert.equal(auction[10].toNumber(), bidAmount, "current bid was not equal to the newly bid amount");
				 });
	    });
	});
    });

    // Here's an example of catching a throw and validating that the throw occurred.
    // It seems to work independently, but screws up the test suite if I'm running the suite
    // and other tests execute after this one?
    // it("should fail if throwtest doesn't throw", function() {
    // 	var ah = AuctionHouse.deployed();
    // 	var reachedStatementDespiteThrow = false;
    // 	return expectedExceptionPromise(function() {
    // 	    return ah.throwTest().then(function() {
    // 		reachedStatementDespiteThrow = true;
    // 	    });
    // 	}, 300000000).then(function() {
    // 	    assert.strictEqual(reachedStatementDespiteThrow, false, "shouldn't be here because the above function should throw");
    // 	});
    // });

    // // This is an attempt at trying to catch a throw on a bad auction creation, but it's not working
    // it("should fail on creation of a bad auction", function() {
    // 	var reachedStatementDespiteThrow = false;
    // 	return expectedExceptionPromise(function() {
    // 	    return createBadAuction().then(function() {
    // 		reachedStatementDespiteThrow = true;
    // 	    });
    // 	}, 300000000).then(function() {
    // 	    assert.strictEqual(reachedStatementDespiteThrow, false, "shouldn't be here because the above function should throw");
    // 	});
    // });

    // function createBadAuction() {
    // 	var sn = SampleName.deployed();
    // 	var ah = AuctionHouse.deployed();
    // 	var owner = accounts[7];
    // 	var recordId = "test7.name";

    // 	// Start by creating a sample record
    // 	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
    // 	    // Now create an auction
    // 	    return ah.createAuction("Title",
    // 				    "Description",
    // 				    sn.address,
    // 				    recordId,
    // 				    web3.eth.blockNumber - 11,
    // 				    (2 * 10^6),
    // 				    (3 * 10^6),
    // 				    5,
    // 				    accounts[2], {from:owner});
    // 	});
    // }

    var expectedExceptionPromise = function (action, gasToUse) {
	return new Promise(function (resolve, reject) {
	    try {
		resolve(action());
	    } catch(e) {
		reject(e);
	    }
	})
	    .then(function (txn) {
		// https://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6
		return web3.eth.getTransactionReceiptMined(txn);
	    })
	    .then(function (receipt) {
		// We are in Geth
		assert.equal(receipt.gasUsed, gasToUse, "should have used all the gas");
	    })
	    .catch(function (e) {
		if ((e + "").indexOf("invalid JUMP") || (e + "").indexOf("out of gas") > -1) {
		    // We are in TestRPC
		} else if ((e + "").indexOf("please check your gas amount") > -1) {
		    // We are in Geth for a deployment
		} else {
		    throw e;
		}
	    });
    };
});
<commit_msg>test case to make sure current bid is set to start price for new auctions<commit_after>var log = console.log;
var balance = web3.eth.getBalance;

contract("AuctionHouse", function(accounts) {
    it("should know if a seller owns an asset on an external contract", function() {
	var sn = SampleName.deployed();
	var owner = accounts[0];
	var recordId = "test.name";

	// Create a samplename record
	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(res) {
	    return AuctionHouse.new().then(function(ah) {
		return ah.partyOwnsAsset.call(owner, sn.address, recordId).then(function(res) {
		    assert.strictEqual(res, true, "the owner doesn't own this asset");
		}).then(function(res) {
		    return ah.partyOwnsAsset.call(accounts[1], sn.address, recordId).then(function(res) {
			assert.strictEqual(res, false, "the owner owns this asset, but shouldn't.");
		    });
		});
	    });
	});
    });

    it("should let us construct a valid auction", function() {
	var sn = SampleName.deployed();
	var owner = accounts[0];
	var recordId = "test2.name";
	var targetAuctionId = 0;
	var startingBid = web3.toWei(0.2, "ether");
	var reservePrice = web3.toWei(0.3, "ether");

	// Start by creating a sample record
	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
	    return AuctionHouse.new().then(function(ah) {
		// Now create an auction
		return ah.createAuction("Title",
					"Description",
					sn.address,
					recordId,
					web3.eth.blockNumber + 100,
					startingBid,
					reservePrice,
					5,
					accounts[2], {from:owner}).then(function(txId) {

					    return ah.getAuction.call(targetAuctionId).then(function(auction) {
						assert.strictEqual(auction[0], owner, "Didn't get the correct seller");
						assert.strictEqual(auction[3], "Title", "Didn't set an auction name");
            assert.equal(auction[8], startingBid, "Didn't set a starting bid price")
						assert.equal(auction[10], startingBid, "Didn't set a current bid price");
						return ah.getAuctionsCountForUser.call(owner);
					    }).then(function(auctionsCount) {
					 	assert.strictEqual(auctionsCount.toNumber(), 1, "Should only have 1 auction");
					 	return ah.getAuctionIdForUserAndIdx.call(owner, auctionsCount.toNumber() - 1);
					    }).then(function(auctionId) {
					 	assert.strictEqual(auctionId.toNumber(), targetAuctionId, "AuctionId should be zero");
					    });

					});
	    });
	});
    });

    it("should activate and cancel an auction", function() {
	var sn = SampleName.deployed();
	var owner = accounts[1];
	var recordId = "test3.name";
	var auctionId;

	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
	    return AuctionHouse.new().then(function(ah) {
		ah.createAuction("Title",
				 "Description",
				 sn.address,
				 recordId,
				 web3.eth.blockNumber + 100,
				 (2 * 10^6),
				 (3 * 10^6),
				 5,
				 accounts[2], {from:owner}).then(function(txId) {
			    	     return ah.getAuctionsCountForUser.call(owner);
				 }).then(function(auctionsCount) {
			    	     return ah.getAuctionIdForUserAndIdx.call(owner, auctionsCount - 1);
				 }).then(function(aucId) {
			    	     auctionId = aucId;
			    	     return ah.getStatus.call(auctionId);
				 }).then(function(auctionStatus) {
			    	     assert.strictEqual(auctionStatus.toNumber(), 0, "Auction status should be pending");
			    	     return sn.setOwner(recordId, ah.address, {from:owner});
				 }).then(function() {
			    	     return ah.activateAuction(auctionId, {from:owner});
				 }).then(function(res) {
			    	     return ah.getStatus.call(auctionId);
				 }).then(function(activeAuctionStatus) {
			    	     assert.strictEqual(activeAuctionStatus.toNumber(), 1, "Auction should be active");
			    	     return ah.cancelAuction(auctionId, {from:owner});
				 }).then(function(res) {
			    	     return ah.getStatus.call(auctionId);
				 }).then(function(cancelledAuctionStatus) {
			    	     assert.strictEqual(cancelledAuctionStatus.toNumber(), 2, "Auction should be inactive");
			    	     return sn.owner.call(recordId);
				 }).then(function(assetOwner) {
			    	     assert.strictEqual(assetOwner, owner, "Should return the asset to the seller");
				 });
	    });
	});
    });

    it("should place a valid bid", function() {
	var sn = SampleName.deployed();
	var owner = accounts[4];
	var recordId = "test4.name";
	var bidder = accounts[5];
	var bidAmount = web3.toWei(0.4, "ether");
	var contractStartBalance;
	var auctionId;

	// Create an asset,
	// create an auction,
	// transfer the asset to the auction
	// activate the auction
	// place a bid
	// check that the bid properties and auction current bid updated

	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
	    return AuctionHouse.new().then(function(ah) {
		contractStartBalance = web3.eth.getBalance(ah.address);
		ah.createAuction("Title",
				 "Description",
				 sn.address,
				 recordId,
				 web3.eth.blockNumber + 100,
				 (2 * 10^6),
				 (3 * 10^6),
				 5,
				 accounts[2], {from:owner}).then(function(txId) {
			    	     return ah.getAuctionsCountForUser.call(owner);
				 }).then(function(auctionsCount) {
			    	     return ah.getAuctionIdForUserAndIdx.call(owner, auctionsCount - 1);
				 }).then(function(aucId) {
			    	     auctionId = aucId;
			    	     return sn.setOwner(recordId, ah.address, {from:owner});
				 }).then(function() {
			    	     return ah.activateAuction(auctionId, {from:owner});
				 }).then(function(res) {
				     return ah.placeBid(auctionId, {from:bidder, value:bidAmount});
				 }).then(function() {
			    	     return ah.getBidCountForAuction.call(auctionId);
				 }).then(function(bidCount){
				     assert.strictEqual(bidCount.toNumber(), 1, "there should be one bid");
				     return ah.getBidForAuctionByIdx.call(auctionId, bidCount - 1);
				 }).then(function(bids) {
				     assert.strictEqual(bids[0], bidder, "bidder was not correct");
				     assert.equal(bids[1].toNumber(), bidAmount, "bid amount was not correct");
				     assert.equal(web3.eth.getBalance(ah.address).toNumber(), contractStartBalance + bidAmount, "Contract balance did not equal the bid amount");
				     return ah.getAuction.call(auctionId);
				 }).then(function(auction) {
				     assert.equal(auction[10].toNumber(), bidAmount, "current bid was not equal to the newly bid amount");
				 });
	    });
	});
    });

    // Here's an example of catching a throw and validating that the throw occurred.
    // It seems to work independently, but screws up the test suite if I'm running the suite
    // and other tests execute after this one?
    // it("should fail if throwtest doesn't throw", function() {
    // 	var ah = AuctionHouse.deployed();
    // 	var reachedStatementDespiteThrow = false;
    // 	return expectedExceptionPromise(function() {
    // 	    return ah.throwTest().then(function() {
    // 		reachedStatementDespiteThrow = true;
    // 	    });
    // 	}, 300000000).then(function() {
    // 	    assert.strictEqual(reachedStatementDespiteThrow, false, "shouldn't be here because the above function should throw");
    // 	});
    // });

    // // This is an attempt at trying to catch a throw on a bad auction creation, but it's not working
    // it("should fail on creation of a bad auction", function() {
    // 	var reachedStatementDespiteThrow = false;
    // 	return expectedExceptionPromise(function() {
    // 	    return createBadAuction().then(function() {
    // 		reachedStatementDespiteThrow = true;
    // 	    });
    // 	}, 300000000).then(function() {
    // 	    assert.strictEqual(reachedStatementDespiteThrow, false, "shouldn't be here because the above function should throw");
    // 	});
    // });

    // function createBadAuction() {
    // 	var sn = SampleName.deployed();
    // 	var ah = AuctionHouse.deployed();
    // 	var owner = accounts[7];
    // 	var recordId = "test7.name";

    // 	// Start by creating a sample record
    // 	sn.addRecord(recordId, owner, recordId, owner, {from:owner}).then(function(txId) {
    // 	    // Now create an auction
    // 	    return ah.createAuction("Title",
    // 				    "Description",
    // 				    sn.address,
    // 				    recordId,
    // 				    web3.eth.blockNumber - 11,
    // 				    (2 * 10^6),
    // 				    (3 * 10^6),
    // 				    5,
    // 				    accounts[2], {from:owner});
    // 	});
    // }

    var expectedExceptionPromise = function (action, gasToUse) {
	return new Promise(function (resolve, reject) {
	    try {
		resolve(action());
	    } catch(e) {
		reject(e);
	    }
	})
	    .then(function (txn) {
		// https://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6
		return web3.eth.getTransactionReceiptMined(txn);
	    })
	    .then(function (receipt) {
		// We are in Geth
		assert.equal(receipt.gasUsed, gasToUse, "should have used all the gas");
	    })
	    .catch(function (e) {
		if ((e + "").indexOf("invalid JUMP") || (e + "").indexOf("out of gas") > -1) {
		    // We are in TestRPC
		} else if ((e + "").indexOf("please check your gas amount") > -1) {
		    // We are in Geth for a deployment
		} else {
		    throw e;
		}
	    });
    };
});
<|endoftext|>


<commit_before>/**
 * Template provides directions an how to bind to a given element.
 * It contains a list of init functions which need to be called to
 * bind to a new instance of elements. It also provides a list
 * of child paths which contain child templates
 */
function Template() {
  this.paths = [];
  this.children = [];
  this.inits = [];
}

Template.prototype = {
  init: function(element, scope) {
    foreach(this.inits, function(fn) {
      scope.apply(fn, element);
    });

    var i,
        childNodes = element.childNodes,
        children = this.children,
        paths = this.paths,
        length = paths.length;
    for (i = 0; i < length; i++) {
      children[i].init(childNodes[paths[i]], scope);
    }
  },

  addInit:function(init) {
    if (init) {
      this.inits.push(init);
    }
  },

  setExclusiveInit: function(init) {
    this.inits = [init];
    this.addInit = noop;
  },

  addChild: function(index, template) {
    this.paths.push(index);
    this.children.push(template);
  }
};

///////////////////////////////////
// Compiler
//////////////////////////////////

function Compiler(directives){
  this.directives = directives;
}

DIRECTIVE = /^ng-(.*)$/;

Compiler.prototype = {
  compile: function(element) {
    var template = this.templetize(element) || new Template();
    return function(element){
      var scope = new Scope();
      scope.element = element;
      return {
        scope: scope,
        element:element,
        init: bind(template, template.init, element, scope)
      };
    };
  },

  templetize: function(element){
    var items, item, length, i, directive, init, template,
        childTemplate, recurse = true;

    // Process attributes/directives
    for (i = 0, items = element.attributes || [], length = items.length;
         i < length; i++) {
      item = items[i];
      var match = item.name.match(DIRECTIVE);
      if (match) {
        directive = this.directives[match[1]];
        if (directive) {
          init = directive.call(this, item.value, element);
          template = template || new Template();
          if (directive.exclusive) {
            template.setExclusiveInit(init);
            i = length; // quit iterations
          } else {
            template.addInit(init);
          }
          recurse = recurse && init;
        } else {
          error("Directive '" + match[0] + "' is not recognized.");
        }
      }
    }

    // Process children
    if (recurse) {
      for (i = 0, items = element.childNodes, length = items.length;
           i < length; i++) {
        if(childTemplate = this.templetize(items[i])) {
          template = template || new Template();
          template.addChild(i, childTemplate);
        }
      }
    }
    return template;
  }
};

describe('compiler', function(){
  function element(html) {
    return jQuery(html)[0];
  }

  var compiler, directives, compile, log;

  beforeEach(function(){
    log = "";
    directives = {
      hello: function(expression, element){
        log += "hello ";
        return function() {
          log += expression;
        };
      },

      watch: function(expression, element){
        return function() {
          this.$watch(expression, function(val){
            log += ":" + val;
          });
        };
      }

    };
    compiler = new Compiler(directives);
    compile = function(html){
      var e = element("
" + html + "
");
      var view = compiler.compile(e)(e);
      view.init();
      return view.scope;
    };
  });

  it('should recognize a directive', function(){
    var e = element('

');
    directives.directive = function(expression, element){
      log += "found";
      expect(expression).toEqual("expr");
      expect(element).toEqual(e);
      return function initFn() {
        log += ":init";
      };
    };
    var template = compiler.compile(e);
    var init = template(e).init;
    expect(log).toEqual("found");
    init();
    expect(log).toEqual("found:init");
  });

  it('should recurse to children', function(){
    var scope = compile('

');
    expect(log).toEqual("hello misko");
  });

  it('should watch scope', function(){
    var scope = compile('');
    expect(log).toEqual("");
    scope.updateView();
    scope.set('name', 'misko');
    scope.updateView();
    scope.updateView();
    scope.set('name', 'adam');
    scope.updateView();
    scope.updateView();
    expect(log).toEqual(":misko:adam");
  });

  it('should prevent recursion', function(){
    directives.stop = function(){ return false; };
    var scope = compile('');
    expect(log).toEqual("hello misko");
  });

  it('should allow creation of templates', function(){
    directives.duplicate = function(expr, element){
      var template,
          marker = document.createComment("marker"),
          parentNode = element.parentNode;
      parentNode.insertBefore(marker, element);
      parentNode.removeChild(element);
      element.removeAttribute("ng-duplicate");
      template = this.compile(element);
      return function(marker) {
        var parentNode = marker.parentNode;
        this.$eval(function() {
          parentNode.insertBefore(
              template(element.cloneNode(true)).element,
              marker.nextSibling);
        });
      };
    };
    var scope = compile('beforexafter');
    expect($(scope.element).html()).toEqual('beforeafter');
    scope.updateView();
    expect($(scope.element).html()).toEqual('beforexafter');
    scope.updateView();
    expect($(scope.element).html()).toEqual('beforexxafter');
  });

  it('should allow for exculsive tags which suppress others', function(){
    directives.exclusive = function(){
      return function() {
        log += ('exclusive');
      };
    };
    directives.exclusive.exclusive = true;

    compile('');
    expect(log).toEqual('exclusive');
  });
});
<commit_msg>markup now works<commit_after>/**
 * Template provides directions an how to bind to a given element.
 * It contains a list of init functions which need to be called to
 * bind to a new instance of elements. It also provides a list
 * of child paths which contain child templates
 */
function Template() {
  this.paths = [];
  this.children = [];
  this.inits = [];
}

Template.prototype = {
  init: function(element, scope) {
    foreach(this.inits, function(fn) {
      scope.apply(fn, element);
    });

    var i,
        childNodes = element.childNodes,
        children = this.children,
        paths = this.paths,
        length = paths.length;
    for (i = 0; i < length; i++) {
      children[i].init(childNodes[paths[i]], scope);
    }
  },

  addInit:function(init) {
    if (init) {
      this.inits.push(init);
    }
  },

  setExclusiveInit: function(init) {
    this.inits = [init];
    this.addInit = noop;
  },

  addChild: function(index, template) {
    this.paths.push(index);
    this.children.push(template);
  }
};

///////////////////////////////////
// Compiler
//////////////////////////////////

function Compiler(markup, directives){
  this.markup = markup;
  this.directives = directives;
}

DIRECTIVE = /^ng-(.*)$/;

Compiler.prototype = {
  compile: function(element) {
    var template = this.templetize(element) || new Template();
    return function(element){
      var scope = new Scope();
      scope.element = element;
      return {
        scope: scope,
        element:element,
        init: bind(template, template.init, element, scope)
      };
    };
  },

  templetize: function(element){
    var chldrn, item, child, length, i, j, directive, init, template,
        childTemplate, recurse = true, directives = this.directives,
        markup = this.markup, markupLength = markup.length;

    for (i = 0, chldrn = element.childNodes, length = chldrn.length;
        i < length; i++) {
      if ((child = chldrn[i]).nodeType == Node.TEXT_NODE) {
        for (j = 0; j < markupLength; j++) {
          markup[j].call(this, child.nodeValue, child, element);
        }
      }
    }

    // Process attributes/directives
    for (i = 0, chldrn = element.attributes || [], length = chldrn.length;
         i < length; i++) {
      item = chldrn[i];
      var match = item.name.match(DIRECTIVE);
      if (match) {
        directive = directives[match[1]];
        if (directive) {
          init = directive.call(this, item.value, element);
          template = template || new Template();
          if (directive.exclusive) {
            template.setExclusiveInit(init);
            i = length; // quit iterations
          } else {
            template.addInit(init);
          }
          recurse = recurse && init;
        } else {
          error("Directive '" + match[0] + "' is not recognized.");
        }
      }
    }

    // Process children
    if (recurse) {
      for (i = 0, chldrn = element.childNodes, length = chldrn.length;
           i < length; i++) {
        if((child = chldrn[i]).nodeType != Node.TEXT_NODE &&
            (childTemplate = this.templetize(child))) {
          template = template || new Template();
          template.addChild(i, childTemplate);
        }
      }
    }
    return template;
  }
};

describe('compiler', function(){
  function element(html) {
    return jQuery(html)[0];
  }

  var compiler, markup, directives, compile, log;

  beforeEach(function(){
    log = "";
    directives = {
      hello: function(expression, element){
        log += "hello ";
        return function() {
          log += expression;
        };
      },

      watch: function(expression, element){
        return function() {
          this.$watch(expression, function(val){
            log += ":" + val;
          });
        };
      }

    };
    markup = [];
    compiler = new Compiler(markup, directives);
    compile = function(html){
      var e = element("
" + html + "
");
      var view = compiler.compile(e)(e);
      view.init();
      return view.scope;
    };
  });

  it('should recognize a directive', function(){
    var e = element('

');
    directives.directive = function(expression, element){
      log += "found";
      expect(expression).toEqual("expr");
      expect(element).toEqual(e);
      return function initFn() {
        log += ":init";
      };
    };
    var template = compiler.compile(e);
    var init = template(e).init;
    expect(log).toEqual("found");
    init();
    expect(log).toEqual("found:init");
  });

  it('should recurse to children', function(){
    var scope = compile('

');
    expect(log).toEqual("hello misko");
  });

  it('should watch scope', function(){
    var scope = compile('');
    expect(log).toEqual("");
    scope.updateView();
    scope.set('name', 'misko');
    scope.updateView();
    scope.updateView();
    scope.set('name', 'adam');
    scope.updateView();
    scope.updateView();
    expect(log).toEqual(":misko:adam");
  });

  it('should prevent recursion', function(){
    directives.stop = function(){ return false; };
    var scope = compile('');
    expect(log).toEqual("hello misko");
  });

  it('should allow creation of templates', function(){
    directives.duplicate = function(expr, element){
      var template,
          marker = document.createComment("marker"),
          parentNode = element.parentNode;
      parentNode.insertBefore(marker, element);
      parentNode.removeChild(element);
      element.removeAttribute("ng-duplicate");
      template = this.compile(element);
      return function(marker) {
        var parentNode = marker.parentNode;
        this.$eval(function() {
          parentNode.insertBefore(
              template(element.cloneNode(true)).element,
              marker.nextSibling);
        });
      };
    };
    var scope = compile('beforexafter');
    expect($(scope.element).html()).toEqual('beforeafter');
    scope.updateView();
    expect($(scope.element).html()).toEqual('beforexafter');
    scope.updateView();
    expect($(scope.element).html()).toEqual('beforexxafter');
  });

  it('should allow for exculsive tags which suppress others', function(){
    directives.exclusive = function(){
      return function() {
        log += ('exclusive');
      };
    };
    directives.exclusive.exclusive = true;

    compile('');
    expect(log).toEqual('exclusive');
  });

  it('should process markup before directives', function(){
    markup.push(function(text, textNode, parentNode) {
      if (text == 'middle') {
        expect(textNode.nodeValue).toEqual(text);
        parentNode.setAttribute('ng-hello', text);
        textNode.nodeValue = 'replaced';
      }
    });
    var scope = compile('beforemiddleafter');
    expect(scope.element.innerHTML).toEqual('beforereplacedafter');
    expect(log).toEqual("hello middle");
  });
});
<|endoftext|>


<commit_before>/*globals describe it beforeEach afterEach */
"use strict";

require("should");
const path = require("path");
const TestHelper = require("./helpers/TestHelper");
const Watchpack = require("../lib/watchpack");
const watchEventSource = require("../lib/watchEventSource");

const fixtures = path.join(__dirname, "fixtures");
const testHelper = new TestHelper(fixtures);

describe("ManyWatchers", function() {
	this.timeout(240000);
	beforeEach(testHelper.before);
	afterEach(testHelper.after);

	it("should watch more than 4096 directories", done => {
		const files = [];
		for (let i = 1; i < 5000; i++) {
			let highBit = 1;
			let j = i;
			while (j > 1) {
				highBit <<= 1;
				j >>= 1;
			}
			const dir = `${i & highBit}/${i & ~highBit}`;
			if (i === highBit) {
				testHelper.dir(`${i}`);
				testHelper.file(`${i}/file`);
				files.push(path.join(fixtures, `${i}`, "file"));
			}
			testHelper.dir(dir);
			testHelper.file(`${dir}/file`);
			files.push(path.join(fixtures, dir, "file"));
			if (i === highBit) {
				testHelper.file(`${dir}/file2`);
				files.push(path.join(fixtures, dir, "file2"));
			}
		}
		testHelper.file("file");
		files.push(path.join(fixtures, "file"));
		testHelper.tick(1000, () => {
			const w = new Watchpack({
				aggregateTimeout: 1000
			});
			w.on("aggregated", function(changes) {
				Array.from(changes).should.be.eql([
					path.join(fixtures, "4096/900/file")
				]);
				w.close();
				done();
			});
			for (let i = 100; i < files.length; i += 987) {
				for (let j = 0; j < files.length - i; j += 987) {
					w.watch({ files: files.slice(j, j + i) });
				}
			}
			w.watch({ files });
			testHelper.tick(10000, () => {
				testHelper.file("4096/900/file");
			});
		});
	});
});
<commit_msg>wait longer before starting testing<commit_after>/*globals describe it beforeEach afterEach */
"use strict";

require("should");
const path = require("path");
const TestHelper = require("./helpers/TestHelper");
const Watchpack = require("../lib/watchpack");
const watchEventSource = require("../lib/watchEventSource");

const fixtures = path.join(__dirname, "fixtures");
const testHelper = new TestHelper(fixtures);

describe("ManyWatchers", function() {
	this.timeout(240000);
	beforeEach(testHelper.before);
	afterEach(testHelper.after);

	it("should watch more than 4096 directories", done => {
		const files = [];
		for (let i = 1; i < 5000; i++) {
			let highBit = 1;
			let j = i;
			while (j > 1) {
				highBit <<= 1;
				j >>= 1;
			}
			const dir = `${i & highBit}/${i & ~highBit}`;
			if (i === highBit) {
				testHelper.dir(`${i}`);
				testHelper.file(`${i}/file`);
				files.push(path.join(fixtures, `${i}`, "file"));
			}
			testHelper.dir(dir);
			testHelper.file(`${dir}/file`);
			files.push(path.join(fixtures, dir, "file"));
			if (i === highBit) {
				testHelper.file(`${dir}/file2`);
				files.push(path.join(fixtures, dir, "file2"));
			}
		}
		testHelper.file("file");
		files.push(path.join(fixtures, "file"));
		testHelper.tick(10000, () => {
			const w = new Watchpack({
				aggregateTimeout: 1000
			});
			w.on("aggregated", function(changes) {
				Array.from(changes).should.be.eql([
					path.join(fixtures, "4096/900/file")
				]);
				w.close();
				done();
			});
			for (let i = 100; i < files.length; i += 987) {
				for (let j = 0; j < files.length - i; j += 987) {
					w.watch({ files: files.slice(j, j + i) });
				}
			}
			w.watch({ files });
			testHelper.tick(10000, () => {
				testHelper.file("4096/900/file");
			});
		});
	});
});
<|endoftext|>


<commit_before>var child = require('child_process');
var http = require('http');
var test = require('tape');
var fs = require('fs');
var path = require('path');
var url = require('url');

var browsers = [
  'chrome',
  'chromium',
];

browsers.forEach(function (browser) {
  test('bin hot patch basic with file url in ' + browser, function (test) {
    test.plan(23);

    var args = [
      'bin/amok.js',
      '--hot',
      '--browser',
      browser,
      url.resolve('file://', path.join('/' + __dirname, '/fixture/hotpatch-basic/index.html'))
    ];

    test.comment(args.join(' '));

    var cli = child.spawn('node', args);
    cli.stderr.pipe(process.stderr);

    cli.on('close', function () {
      test.pass('close');
    });

    var values = [
      'ready',
      'step-0',
      'step-1',
      'step-2',
      'step-3',
      'step-4',
      'step-5',
      'step-6',
      'step-7',
      'step-8',
      'step-9',
      'step-0',
    ];

    var source = fs.readFileSync('test/fixture/hotpatch-basic/index.js', 'utf-8');
    cli.stdout.setEncoding('utf-8');
    cli.stdout.on('data', function (chunk) {
      chunk.split('\n').forEach(function (line) {
        if (line.length === 0) {
          return;
        }

        test.comment(line);
        test.equal(line, values.shift(), line);

        if (values[0] === undefined) {
          cli.kill('SIGTERM')
        } else if (line.match(/^step/)) {
          source = source.replace(line, values[0]);

          fs.writeFile('test/fixture/hotpatch-basic/index.js', source, 'utf-8', function (error) {
            test.error(error);
          });
        }
      });
    });
  });
});

browsers.forEach(function (browser) {
  test('bin hot patch basic with server in ' + browser, function (test) {
    test.plan(13);

    var args = [
      'bin/amok.js',
      '--hot',
      '--browser',
      browser,
      'test/fixture/hotpatch-basic/index.js'
    ];

    test.comment(args.join(' '));

    var cli = child.spawn('node', args);
    cli.stderr.pipe(process.stderr);

    cli.on('close', function () {
      test.pass('close');
    });

    var values = [
      'ready',
      'step-0',
      'step-1',
      'step-2',
      'step-3',
      'step-4',
      'step-5',
      'step-6',
      'step-7',
      'step-8',
      'step-9',
      'step-0',
    ];

    var source = fs.readFileSync('test/fixture/hotpatch-basic/index.js', 'utf-8');
    cli.stdout.setEncoding('utf-8');
    cli.stdout.on('data', function (chunk) {
      chunk.split('\n').forEach(function (line) {
        if (line.length === 0) {
          return;
        }

        test.equal(line, values.shift(), line);

        if (values[0] === undefined) {
          cli.kill('SIGTERM')
        } else if (line.match(/^step/)) {
          source = source.replace(line, values[0]);

          fs.writeFileSync('test/fixture/hotpatch-basic/index.js', source, 'utf-8');
        }
      });
    });
  });
});<commit_msg>Remove duplicate code in test/bin_hotpatch.js<commit_after>var child = require('child_process');
var http = require('http');
var test = require('tape');
var fs = require('fs');
var path = require('path');
var url = require('url');

var browsers = [
  'chrome',
  'chromium',
];

browsers.forEach(function (browser) {
  var entries = [
    'test/fixture/hotpatch-basic/index.js',
    url.resolve('file://', path.join('/' + __dirname, '/fixture/hotpatch-basic/index.html'))
  ];

  entries.forEach(function (entry) {
    var args = [
      'bin/amok.js',
      '--hot',
      '--browser',
      browser,
      entry
    ];

    test(args.join(' '), function (test) {
      test.plan(23);

      var cli = child.spawn('node', args);
      cli.stderr.pipe(process.stderr);

      cli.on('close', function () {
        test.pass('close');
      });

      var values = [
        'ready',
        'step-0',
        'step-1',
        'step-2',
        'step-3',
        'step-4',
        'step-5',
        'step-6',
        'step-7',
        'step-8',
        'step-9',
        'step-0',
      ];

      var source = fs.readFileSync('test/fixture/hotpatch-basic/index.js', 'utf-8');
      cli.stdout.setEncoding('utf-8');
      cli.stdout.on('data', function (chunk) {
        chunk.split('\n').forEach(function (line) {
          if (line.length === 0) {
            return;
          }

          test.comment(line);
          test.equal(line, values.shift(), line);

          if (values[0] === undefined) {
            cli.kill('SIGTERM')
          } else if (line.match(/^step/)) {
            source = source.replace(line, values[0]);

            fs.writeFile('test/fixture/hotpatch-basic/index.js', source, 'utf-8', function (error) {
              test.error(error);
            });
          }
        });
      });
    });
  });
});<|endoftext|>


<commit_before>'use strict';

describe('Restmod builder:', function() {

  beforeEach(module('restmod'));

  var Bike;
  var restmod, $httpBackend;
  beforeEach(inject(function($injector) {
    restmod = $injector.get('restmod');
    $httpBackend = $injector.get('$httpBackend');

    $httpBackend.when('GET', '/api/bikes/1').respond(200, { 'dropper_seat': true });
  }));

  describe('setUrlPrefix', function() {

    beforeEach(function() {
      Bike = restmod.model('/bikes', function() {
        this.setUrlPrefix('/api');
      });
    });

    it('should change the url prefix for model base url', function() {
      expect(Bike.$url()).toEqual('/api/bikes');
    });

    it('should change the url prefix for objects generated using $single', function() {
      var bike = Bike.$single('my-bike');
      expect(bike.$url()).toEqual('/api/my-bike');
    });
  });

  describe('setPrimaryKey', function() {
    beforeEach(function() {
      Bike = restmod.model('/bikes', function() {
        this.setPrimaryKey('my_id');
      });
    });

    it('should change the property used to resolve an objects primary key', function() {
      var bike = Bike.$buildRaw({ my_id: 'key' });
      expect(bike.$pk).toEqual('key');
    });
  });

  describe('disableRenaming', function() {

    beforeEach(function() {
      Bike = restmod.model('/api/bikes', function() {
        this.disableRenaming();
      });
    });

    it('should disable renaming', function() {
      var bike = Bike.$find(1);
      $httpBackend.flush();
      expect(bike.dropperSeat).not.toBeDefined();
      expect(bike.dropper_seat).toBeDefined();
    });
  });

  describe('setNameDecoder', function() {

    beforeEach(function() {
      Bike = restmod.model('/api/bikes', function() {
        this.setNameDecoder(function(_name) { return '_' + _name; });
      });
    });

    it('should change name decoding', function() {
      var bike = Bike.$find(1);
      $httpBackend.flush();
      expect(bike._dropper_seat).toBeDefined();
      expect(bike.dropper_seat).not.toBeDefined();
    });
  });

  describe('setNameEncoder', function() {

    beforeEach(function() {
      Bike = restmod.model('/api/bikes', function() {
        this.setNameDecoder(function(_name) { return _name.substr(1); });
      });
    });

    it('should change name encoding', function() {
      // var bike = Bike.$build(1);
      // $httpBackend.flush();
      // expect(bike._noUndercore).toBeDefined();
    });
  });

  // Object definition spec

  describe('OD prefix: @', function() {
    it('should register a new class ', function() {
      var Bike = restmod.model(null, {
        '@classMethod': function() {
          return 'teapot';
        }
      });

      expect(Bike.classMethod()).toEqual('teapot');
    });
  });

  describe('OD prefix: ~', function() {
    it('should register a new hook callback ', function() {
      var Bike = restmod.model(null, {
        '~afterFeed': function() {
          this.teapot = true;
        }
      });

      var bike = Bike.$build().$decode({});
      expect(bike.teapot).toBeTruthy();
    });
  });

});

<commit_msg>test(builder): adds setProperty test<commit_after>'use strict';

describe('Restmod builder:', function() {

  beforeEach(module('restmod'));

  var Bike;
  var restmod, $httpBackend;
  beforeEach(inject(function($injector) {
    restmod = $injector.get('restmod');
    $httpBackend = $injector.get('$httpBackend');

    $httpBackend.when('GET', '/api/bikes/1').respond(200, { 'dropper_seat': true });
  }));

  describe('setUrlPrefix', function() {

    beforeEach(function() {
      Bike = restmod.model('/bikes', function() {
        this.setUrlPrefix('/api');
      });
    });

    it('should change the url prefix for model base url', function() {
      expect(Bike.$url()).toEqual('/api/bikes');
    });

    it('should change the url prefix for objects generated using $single', function() {
      var bike = Bike.$single('my-bike');
      expect(bike.$url()).toEqual('/api/my-bike');
    });
  });

  describe('setPrimaryKey', function() {
    beforeEach(function() {
      Bike = restmod.model('/bikes', function() {
        this.setPrimaryKey('my_id');
      });
    });

    it('should change the property used to resolve an objects primary key', function() {
      var bike = Bike.$buildRaw({ my_id: 'key' });
      expect(bike.$pk).toEqual('key');
    });
  });

  describe('setProperty', function() {
    beforeEach(function() {
      Bike = restmod.model('/bikes', function() {
        this.setProperty('test', 'test');
      });
    });

    it('should set the internal model property', function() {
      expect(Bike.$getProperty('test')).toEqual('test');
    });
  });

  describe('disableRenaming', function() {

    beforeEach(function() {
      Bike = restmod.model('/api/bikes', function() {
        this.disableRenaming();
      });
    });

    it('should disable renaming', function() {
      var bike = Bike.$find(1);
      $httpBackend.flush();
      expect(bike.dropperSeat).not.toBeDefined();
      expect(bike.dropper_seat).toBeDefined();
    });
  });

  describe('setNameDecoder', function() {

    beforeEach(function() {
      Bike = restmod.model('/api/bikes', function() {
        this.setNameDecoder(function(_name) { return '_' + _name; });
      });
    });

    it('should change name decoding', function() {
      var bike = Bike.$find(1);
      $httpBackend.flush();
      expect(bike._dropper_seat).toBeDefined();
      expect(bike.dropper_seat).not.toBeDefined();
    });
  });

  describe('setNameEncoder', function() {

    beforeEach(function() {
      Bike = restmod.model('/api/bikes', function() {
        this.setNameDecoder(function(_name) { return _name.substr(1); });
      });
    });

    it('should change name encoding', function() {
      // var bike = Bike.$build(1);
      // $httpBackend.flush();
      // expect(bike._noUndercore).toBeDefined();
    });
  });

  // Object definition spec

  describe('OD prefix: @', function() {
    it('should register a new class ', function() {
      var Bike = restmod.model(null, {
        '@classMethod': function() {
          return 'teapot';
        }
      });

      expect(Bike.classMethod()).toEqual('teapot');
    });
  });

  describe('OD prefix: ~', function() {
    it('should register a new hook callback ', function() {
      var Bike = restmod.model(null, {
        '~afterFeed': function() {
          this.teapot = true;
        }
      });

      var bike = Bike.$build().$decode({});
      expect(bike.teapot).toBeTruthy();
    });
  });

});

<|endoftext|>